text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
select values missing from one table based upon values in another table
I am using mysql and have 2 tables
table1
id
324
325
328
350
420
650
850
950
table2
id mapping_id
324 1
325 2
328 3
350 4
420 5
650 1
850 2
I want to produce a list of all the DISTINCT field mapping_ids that are missing for the ids in table one. For example id 850 has a mapping_id of 2 so is missing 1,3,4,5 and id 950 is not even in table 2 and so is missing 1,2,3,4,5. This should give me a distinct list of 1,2,3,4,5.
I have tried various LEFT JOIN queries but cannot get the results I need. Thanks in advance.
A:
You could build a matrix of id - mapping combinations using a cross join. A not in subquery can determine which parts of the matrix are empty:
select *
from table1 t1
cross join
(
select distinct mapping_id
from table2
) mappings
where not exists
(
select *
from table2 t2
where t2.id = t1.id
and t2.mapping_id = mappings.mapping_id
)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jQuery scope with multiple functions
I have a tool that allows a user to create a dashboard and add widgets to it. Each widget is its own JS file that is loaded into the page.
To keep things the same across the board, I create a function called load which is triggered when the document is ready.
The problem is, each of the other modules that are included all have the same function called load which is causing problems.
While I can change the function name to something unique, I would like to see if its possible to keep them all the same where they are locked down to the scope of the file they are in?
/*
Module Details: Department Links - A collection of links specific to the users department or selected department
*/
$(function() {
// Define our moduleID
var moduleID = 1;
// Load our module
load(moduleID, '', false);
// Create a event for dropdown change
$('body').on('select2-selecting', '#Department_' + moduleID, function (e) {
// When the user picks a department, reload this module and fetch those department links.
load(moduleID, e.val, true);
});
});
/*
Load the module
@moduleID: required.
@departmentID: if not passed, the SP will use the viewers departmentID.
@reload: passed when changing the dropdown so we only render the new data and not the whole module
*/
function load(moduleID, departmentID, reload){
... Do other stuff here
}
I guess my question is.. With multiple functions called load in the various js files included, how can I trigger the one specific to its own file?
A:
@binariedMe is correct.. There is nothing like file scope in JavaScript.. You can do like if you have any object which is separate in every file so you can write as follows...
`Object.load = function (){
// do stuff
}`
And you can call object.load for every module you are loading...!!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
javascript: add script that will be evaluated before body scripts?
I have a script foo.js that is included in <head>. Inside body I have an inline script. Inside it, I want to add to the document another script for bar.js that will be loaded and evaluated before the inline script.
<html>
<head>
<script src="foo.js" type="text/javascript"/>
</head>
<body>
<script type="text/javascript">
bar()
</script>
</body>
</html>
In foo.js I want to add a script pointing to bar.js
bar.js:
function bar() {
alert('hi');
}
What should be the code of foo.js?
NOTE: I know I can use onload in this trivial example. But in my real case, bar.js contains a function that is called several times and I want to be able to inline these calls in the right sections of the page (for code locality)
A:
You have got two options:
Use document.write('<script src="bar.js"></script>') in foo.js.
Dynamically create and insert a <script> element within the head (since scripts in the head have to be loaded before the rest is parsed, this works):
!function(){
var s = document.createElement('script'),
currentScript = document.getElementsByTagName('script')[0];
s.src = "bar.js";
currentScript.parentNode.insertBefore(s, currentScript);
}()
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cambio de alert por sweet alert
if($resultado_pendientes>=1){
echo "alert(\"Usted posee 1 solicitud cerrada parcialmente por el departamento de sistemas, valide y cierrela antes de crear otra nueva.\");
document.location=(\"./listTicketUnrevised.php?active=0\");";
}
?>
buenas, necesito ayuda con este codigo que tengo , el cual me genera una alerta corriente y quiero cambiarla por el sweet alert.
el problema es que siempre me da errores .
quiero usar el warning de esa libreria mas no se como implementarlo...
duda 1
no entiendo por que se usan los \dentro del alert pero estoy viendo que sin eso no se imprime el mensaje de alerta.
duda 2
al cambiar lo que esta dentro de las comillas del echo me sale un error Parse error: syntax error, unexpected '='
intente meter el document location en el eco pero aun así no funciona.
A:
eso si lo habia hecho, lo que no habia hecho era separar el php del javascript
<script>
<?php
if($resultado_pendientes>=1){
//aqui ira el sweet alert y aqui cerre el php , cosa habia hecho despues del sweet alert
?>
swal({
title: 'Tiene 1 ticket pendiente por cerrar',
html: 'Cierrelos para poder crear uno nuevo ',
type: 'warning',
confirmButtonText: 'Got it!'
}).then(function () {
window.location.href = "tickets-sin-revisar-1";
}, function (dismiss) {
// dismiss can be 'cancel', 'overlay',
// 'close', and 'timer'
if (dismiss === 'cancel') {
window.location.href = "tickets-sin-revisar-1";
}
});
<?php
//aqui lo vuelvo a abrir para cerrar el if continuando con mi js
//este codigo lo copie de la web de aca , yo le hice la modificacion al darme //cuenta y funciono , me redirije a la pagina que quiero , ya le agrego el //tiempo de redireccionamiento usando la version 2del sweet alert.
//posteo el codigo para que la gente se ayude si tiene este problema
// saludos
}
?>
});
</script>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
To translate truth table into English and decipher logical argument it makes
This is from How to prove it by Velleman.
It will either rain or snow tomorrow.
It is too warm to snow.
Therefore, it will rain.
Let P - It will rain tomorrow, Q - It will snow tomorrow; representing the argument symbolically,
$P \vee Q$
$\neg Q$
$\therefore P$
The last line reads as "It will rain tomorrow OR it will snow tomorrow. It will snow tomorrow. Therefore, it will rain." I did not understand it.
A:
I am reading here
$$(P \vee Q) \wedge \neg Q \Rightarrow P.$$
In English, "Either $P$ is true or $Q$ is true, and $Q$ is false, therefore $P$ is true." This corresponds with line 3 of your truth table. I hope that was useful in some way. Do tell if further clarification is desired.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is the current control knob in DC voltage source kept at maximum initially?
In a DC Voltage Source(0-15-30V), why do we need to keep the current control knob at maximum at the beginning?
Note : I am using this DC Voltage Source for basic experiments of electronics like getting characteristics of P-N junction diode, zener diode, etc. This advice came from my instructor in the course 'Electronic Devices and Circuits Laboratory' and is also mentioned in the laboratory manual.
A:
Best practice when initially setting up a bench supplies is to set the voltage first with no load.
Since the current limiter will hold the voltage at a lower level if set too low, it is prudent to turn it all the way up initially to make sure that the voltage indicated is indeed the regulated voltage not the limited voltage. Once the voltage is set it is then prudent to wind back the current limit to a level you expect not to exceed with the load you are about to attach.
If you do it the other way around with a load attached the voltage you see may in fact be the limited voltage. If the load current drops it can cause the output voltage to suddenly rise to the higher set-voltage level and may damage your load.
Generally when powering an unknown load or circuit of unknown quality, it is prudent to start at zero volts, wind the current limit to max, then slowly increase the voltage while monitoring the current meter manually. If you see the current increase too rapidly, back off the voltage and try and figure out the cause.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Prototype Framework Breaking Other Scripts
I have a simple page that has a (non-Prototype) JavaScript pop-up for login. It has been working fine. But when I add the Prototype framework to the page the pop-up quits working.
<script type="text/javascript" src="recipes/js/prototype.js"></script>
<script type="text/javascript">
var imgnum = 1;
function nextimg() {
/* <![CDATA[ */
imgnum++;
if (imgnum > 5) imgnum = 1;
var nextimg = 'recipes/img/iphone_' + imgnum + '.png';
var nextimg2 = 'recipes/img/iphone_' + (imgnum + 1) + '.png';
imagepreload = new Image();
imagepreload.src = nextimg2;
$('iphoneimg').src=nextimg;
/* ]]> */
}
</script>
I have tried to move the JS include to the bottom, with no luck. Any ideas?
Also, it works fine in IE but not Firefox or Safari.
A:
Prototype takes the $ function that JQuery also uses (are you using JQuery?).
See here
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to modify partial, depending on controller it's viewed from?
I'm using a partial from my "messages" controller in my "tags" controller. The portion in question looks like this:
<% unless message.tag_list.nil? || message.tag_list.empty? %>
<% message.tags.each do |t| %>
<div class="tag"><%= link_to t.name.titleize, tag_path(t) %></div>
<% end %>
<% end %>
Is there a way to hide this portion of the partial only when it is viewed from the "tags" controller?
A:
<% unless controller.controller_name.eql?("tags") %>
will only show if controller is NOT tags
<% end %>
:) hope that helps!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Media Folder with insert option of MP3 files and Media Folders that can only contain Media Folders and MP3 files
I would like to have a folder in my media library that can only contain MP3s, or Folders of MP3s. The only way I can think of doing this is by creating a new "MP3 folder" type that includes itself and MP3 files in its insert options. Is there another way that's more elegant? Will what I describe even work?
A:
You can create a new template of MP3 Folder type and set the insert options on that template's standard values. If you don't want to create another template, you can use the rules engine and create an insert rule where that specific folder or folders are assigned specific insert options.
That being said, insert options do not provide hard enforcement for only those types, that is, a content author can still add other types by using the Insert from template option. If you want more strict enforcement, you'll need to patch a number of pipelines to ensure that users can't upload non-MP3 files to that item tree or move non-MP3 files into that item tree.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SharePoint Feature Activation - Value does not fall within the expected range
I have started writing a simple feature to create a site column, and a content type. If I try to activate the feature as such, it gives me the error Value does not fall within the expected range and nothing much more helpful. If I remove the ContentType tag, the feature activates just fine and I can see the newly created Account site column. Any idea what the error is with the ContentType?
<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Field
ID="{345C9562-F0D9-4327-853B-5072E296823A}"
Name="Account"
DisplayName="Account"
Type="Text"
Group="Accounts">
</Field>
<ContentType
ID="0X010100"
Name="Account Doc"
Description="Account Doc"
Version="0"
Group="Account Types">
<FieldRefs>
<FieldRef
ID="{345C9562-F0D9-4327-853B-5072E296823A}"
Name="Account"
DisplayName="Account" />
</FieldRefs>
</ContentType>
</Elements>
A:
It turns out SharePoint was unhappy about the trailing 00 in the ID attribute of the ContentType tag. Changing to 01 fixed the problem, or just adding a GUID on the end after the 00 worked as well:
<ContentType
ID="0x010100C8813FB7C4814B44BA7FD679120EF6F5"
Name="Account Doc"
Description="Account Doc"
Version="0"
Group="Account Types">
<FieldRefs>
<FieldRef
ID="{345C9562-F0D9-4327-853B-5072E296823A}"
Name="Account"
DisplayName="Account" />
</FieldRefs>
</ContentType>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Converting docx/odt to PDF using JavaScript
I have a node web app that needs to convert a docx file into pdf (using client side resources only and no plugins). I've found a possible solution by converting my docx into HTML using docxjs and then HTML to PDF using jspdf (docx->HTML->PDF).
This solution could make it but I encountered several issues especially with rendering. I know that docxjs doesn't keep the same rendering in HTML as the docx file so it is a problem...
So my question is do you know any free module/solution that could directly do the job without going through HTML (I'm open to odt as a source as well)? If not, what would you advise me to do?
Thanks
A:
As you already know there is no ready-to-use and open libs for this.. You just can't get good results with available variants. My suggesition is:
Use third party API. Like https://market.mashape.com/convertapi/word2pdf-1#!documentation
Create your own service for this purpose. If you have such ability, I suggest to create a small server on node.js (I bet you know how to do this). You can use Libreoffice as a good converter with good render quality like this:
libreoffice -headless -invisible -convert-to pdf {$file_name} -outdir /www-disk/
Don't forget that this is usually takes a lot of time, do not block the request-answer flow: use separate process for each convert operation.
And the last thing. Libreoffice is not very lightweight but it has good quality. You can also find notable unoconv tool.
As of January 2019, there is docx-wasm, which works in node and performs the conversion locally where node is installed. Proprietary but freemium.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to give custom error message in api response
I want to give a proper error handling, in my endpoint, in this case i try to do some syntax error in raw json body request in postman.
i dont want the response like this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>SyntaxError: Unexpected token a in JSON at position 125<br> at JSON.parse (<anonymous>)<br> at parse (/Users/admin/Documents/NEW-SOURCE/security/boost-svc-consumer/node_modules/body-parser/lib/types/json.js:89:19)<br> at /Users/admin/Documents/NEW-SOURCE/security/boost-svc-consumer/node_modules/body-parser/lib/read.js:121:18<br> at invokeCallback (/Users/admin/Documents/NEW-SOURCE/security/boost-svc-consumer/node_modules/raw-body/index.js:224:16)<br> at done (/Users/admin/Documents/NEW-SOURCE/security/boost-svc-consumer/node_modules/raw-body/index.js:213:7)<br> at IncomingMessage.onEnd (/Users/admin/Documents/NEW-SOURCE/security/boost-svc-consumer/node_modules/raw-body/index.js:273:7)<br> at emitNone (events.js:106:13)<br> at IncomingMessage.emit (events.js:208:7)<br> at IncomingMessage.wrapped [as emit] (/Users/admin/Documents/NEW-SOURCE/security/boost-svc-consumer/node_modules/newrelic/lib/transaction/tracer/index.js:193:22)<br> at endReadableNT (_stream_readable.js:1064:12)<br> at _combinedTickCallback (internal/process/next_tick.js:138:11)<br> at process._tickCallback (internal/process/next_tick.js:180:9)</pre>
</body>
</html>
I want give some custom message. Like "Unknown error or syntax error in json request", I gave try catch in my controller fucntion but looks like try catch doesnt catch it" it throw error befor it come in to the try catch block.
do you know hot to do it ?
Thanks in advance
A:
Yes, you can do it easily if you are working with express.
Below is the code of my api server that you can find the sources HERE.
I'm using typescript but the same can be achieved with javascript at 0 cost.
ErrorMiddleware
This middleware can catch any error thrown. As you can see there is a specific SyntaxError that can catch malformed JSON and reply to the client.
import { Response, Request, NextFunction } from 'express';
import { UnauthorizedError } from 'express-jwt';
import logger from '@app/logger';
import { EnvUtil } from '@app/util';
import { ResponseHelper, HttpStatusCode } from '@app/helper';
import { EmptyFileError } from '@app/common/error';
export default class ErrorMiddleware {
public static handle(err: Error, _req: Request, res: Response, _next: NextFunction): void {
if (err instanceof UnauthorizedError) {
logger.warn(`Authentication with JWT failed due to ${err.message}`);
ResponseHelper.send(res, HttpStatusCode.UNAUTHORIZED);
} else if (err instanceof SyntaxError) {
logger.warn(`Malformed JSON due to ${err.message}`);
ResponseHelper.send(res, HttpStatusCode.BAD_REQUEST, [err.message]);
} else {
logger.error(`Internal Server error due to ${err.message}`);
ResponseHelper.send(
res,
HttpStatusCode.INTERNAL_SERVER_ERROR,
EnvUtil.isDevelopment() ? err.stack : undefined
);
}
}
}
Express app
When you create the Express app remember to register (with use) the ErrorMiddleware. I register the error middleware Here.
import express from 'express';
import bodyParser from 'body-parser';
import { ErrorMiddleware } from '@app/middleware';
const app = express();
// JSON body parser
app.use(bodyParser.json())
// Before error middleware configure all your express app
app.use(ErrorMiddleware.handle);
ResponseHelper
This class handle the response given the res express parameter, http status code you want to return and some data (optional). You can find the implementation Here.
You can find the implementation of httpStatusCode Here
As you can see the interface Response is the mapping for all API responses with:
status: string success or fail
is_success: boolean true if is success, false otherwise
status_code: http status code
status_code_name: http status code description
data: the data (any type)
import { Response as ExpressResponse } from 'express';
import HttpStatusCode, { Status } from './httpStatusCode';
export interface Response {
status: Status;
is_success: boolean;
status_code: number;
status_code_name: string;
data: object;
}
export default class ResponseHelper {
public static send(
res: ExpressResponse,
httpStatusCode: HttpStatusCode,
data: any = undefined
): void {
res
.status(httpStatusCode.code)
.json(<Response>{
status: httpStatusCode.status(),
is_success: httpStatusCode.isSuccess(),
status_code: httpStatusCode.code,
status_code_name: httpStatusCode.name,
data,
})
.end();
}
}
You can test the application sending malformed JSON at the following URL: https://racer-2020.herokuapp.com/api/v1/car
The error response will be the following:
{
"status": "fail",
"is_success": false,
"status_code": 400,
"status_code_name": "Bad Request",
"data": [
"Unexpected end of JSON input"
]
}
In the source code you can find other middleware that handle for example a not found route path.
Hope it helps :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP PDO prepare throwing exception when using "%"
The following line throws an exception -
$sth = $db->prepare("SELECT * FROM providers WHERE name LIKE %:name%");
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 1 near "%": syntax error'
Taking the % signs out gets rid of the error, but obviously the search doesn't work as I want it. I've tried toying with quotes, putting in an actual value instead of the :-prefixed PDO variable, the only thing that gets rid of the error is removing the % signs. I'm at a loss.
A:
The LIKE operator takes a string:
$db->prepare("SELECT * FROM providers WHERE name LIKE '%' + :name + '%'");
Note that an empty :name will match everything ('%%')
Sqlite uses || to concatenate strings, so '%' || :name || '%' should do.
Another way (taken from this question) is to add the percent signs to the value of your param. So you'd have a query LIKE :name and then before binding the parameter, add the percent signs: $name = '%'.$name.'%'; $sth->execute(array('name' => $name));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
DHCP server access problem
What will stop a PC from receiving an IP address from a DHCP server? Is it STP, VTP, 802.1Q or DTP? What is the most preferable of these?
A:
Neither.
DHCP works by the server receiving the client's broadcast - so you need a working broadcast domain (aka L2 segment aka VLAN) in between, unless you're using a DHCP relay. As long as the network is functioning, DHCP will work.
xSTP, VTP, or DTP all help establishing and maintaining a working network. There are no 'most preferable' protocols in these - you use whatever is best in your situation which you haven't detailed. (Except that MSTP is preferable over RSTP which is generally preferable over obsolete classic STP.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the default icon set in Ubuntu 16.04?
I would like my Qt configuration to match the default Ubuntu 16.04 style.
What is the default icon set from the below list of icon sets?
A:
Ambiance GTK is the default theme and Ubuntu Mono (dark) is the default iconset
(Ubuntu tweak tool can be used to change it if you want to match Ubuntu with your QT)
A:
Using the Unity Tweak Tool, I have found out that the default icon theme for Ubuntu 16.04 is Ubuntu-mono-dark.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Name of the point whose coordinates are the mean of the coordinates of a list of points.
Let $ X = \{ (x_i,y_i) \, | \, i \in I\}$
be a set of points (where $I$ is a finite index set).
Does the point $x_0 = \frac{1}{|I|} \sum_{i \in I} (x_i,y_i) $ have any name?
A:
In geometry it's called centroid, geometric center or barycenter.
Please note that depending on context, the latter term may be ambiguous because in physics barycenter has a slightly different meaning: the center of mass (which may or may not be the same as the centroid, depending on the distribution of mass).
A:
It is the barycenter of the sets of points.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I make the most effective use of limited static IP addresses for a mail server?
I am running a Zimbra ZCS 7.1.2 server. The server is setup to host multiple domains, 3 at the moment. But I have a problem and I think I am over thinking the solution.
The problem is I want every domain to have its own SSL cert. As per Zimbra documentation I have to configure the Zimbra proxy to handle connections to each of the domains. Each domain has a virtual domain name and a virtual IP address.
The command mentioned is zmprov md [domain name] +ZimbraVirtualHostName {hostname} +ZimbraVirtualIPAddress {1.2.3.4}
As far as I am aware I need a sperate IP address for each domain. So I have 10.0.0.17 thru 10.0.0.20. assingned to virtual interfaces on my Zimbra server.
SMTP\S is handled by 10.0.0.17 and is NAT'd to public IP. But for the items that are proxied like webmail, IMAP and POP3 do I need seperate public IPs for each internal IP or is there a way consolidate things to one public IP, I only have 3 available out of a pool of 5.
I can elaborate more if needed.
A:
Each service uses a separate port, SMTP typically is on port 25, webmail (HTTP) is 80 or 443 for SSL, IMAP 443, etc.
So it's prefectly acceptable to use just the 3 ip addresses, essentially assigning 1 ip address per domain. Domain A (all services) on 10.0.0.17, Domain B (all services) on 10.0.0.18, etc.
The only time you would need to worry is if you need to have the same service, with different parameters (be-it ssl cert, or some other configuration) on the same IP. You cannot have two SMTP servers listening to the same port/ip combination.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
switching between pictures randomally
i need to make a set of pictures that every 10 seconds a different picture will appear in the same position as the other one before it. i dont really know how to even begin. i need it to be with HTML and javascript only. thank you.
A:
I made you a page that switches between two images in a random manner. You can easily expand this, by adding image urls to the images array
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var p = {
onload: function() {
setInterval(p.switchImage, 10000);
},
switchImage: function() {
document.getElementById("image").src = p.images[Math.floor(Math.random() * p.images.length)];
},
images: ["http://www.schoolplaten.com/afbeelding-hond-tt20990.jpg", "http://www.schoolplaten.com/afbeelding-hond-tt19753.jpg"]
};
</script>
</head>
<body onload="p.onload()">
<img src="http://www.schoolplaten.com/afbeelding-hond-tt20990.jpg" id="image"/>
</body>
</html>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Movies & TV hot network question ads have poor colouring. Please improve it?
A hot network question just showed up on RPG.SE for Movies & TV, which is fine, but its colouring is nuts:
Could M&TV have their ad adjusted slightly so that it doesn't do uncomfortable things to my eyes?
A:
UDPATE 2015-09-15: The font color seems to have been fixed to some degree into plain white, which makes it less agressively fighting with the background (that has been fixed, too) and improves readability.
However, I'd still not consider this solved yet, since the current plain white text and the very bold and blurry font is still quite hard on the eyes.
UDPATE 2015-09-22: So, the problems with the thick font/white drop shadow seem to have been solved now, too. With those changes I'd consider all the problems with our HNQ ad solved now:
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Golang import based on config variable
I'm currently in the process of still learning go but I recently got to a point where in one of my tests I wanted to create a quick backup application that will reference a config file and switch what "plugin" to use for the backup. So what I got to at this point is to create (as example, written from my head and syntax may be incorrect):
type BackupStorage interface{
Put (d []byte) (n int, err Error)
Get (l []byte) (d []byte, err Error)
}
At this point I would assume I should use reflection to switch on the type and return the specific backup function, although that does not seem right.
The second alternative I came to was to still use my BackupStorage interface and create "plugin" packages to dictate which import will be used, but how do I switch that then based on a config file variable. And I'd like to do this because some stuff on one machine may backup only to s3 where as others may backup to both s3 and google drive etc.
With the basic example above what I have in mind is this:
Implement 2 BackupStorage "plugins" (Google Drive / S3) with the flexibility to add more at any time, but have my code be generic enough to execute on whatever storage backend is selected in config files.
As I mentioned above I'm still learning and any explanations would be appreciated or examples on how to accomplish this. I don't mind the "your doing it wrong" as long as there is a proper explanation on why it's wrong and how to do it right.
A:
You have the right idea to start, implement everything you need via an interface, and then you can plug in any concrete backup "plugin" that implements that interface.
Once you can run your backup via an interface, you can simply assign an instance of the backend you want based on whatever conditions you set.
var storage Backupper
type Backupper interface {
Backup()
}
type GDrive struct {
config string
}
func (g *GDrive) Backup() {
fmt.Println("Doing backup to Google Drive")
}
func main() {
storage = &GDrive{}
storage.Backup()
}
Or with multiple options: http://play.golang.org/p/RlmXjf55Yh
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Automatically update $_SESSION variables without refreshing
I am using a $_SESSION variable to send emails via AJAX (they need to be sent without refreshing the page), but the $_SESSION variable doesn't automatically update, so when it changes I need to refresh the page to update the variable.
Is it possible to update the $_SESSION variable without refreshing?
This is the code I'm using to send the email:
$(document).ready(function(){
$("#medicalembassy").validate({
debug: false,
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please let us know who you are.",
email: "",
},
submitHandler: function(form) {
// do other stuff for a valid form
$.post('http://www.example.co.uk/erc/process.php?imei=<?php echo $_SESSION['imei2']; ?>&send_type=2', $("#medicalembassy").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
So basically, if the $_SESSION variable changes, I need this AJAX email to recognise that without having to refresh.
Thanks for any help
A:
A $_SESSION variable is obtained when you run "session_start();" and cleared if you use "session_destroy();". You cannot get the change in the session variables multiple times in the same document, however: the document your AJAX is requesting would see the changes in $_SESSION each time that page was requested (the page inside the AJAX).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is Ironpython suitable for value calculation?
I want to allow the users to define a formula based on two variables. Say I have a Quantity and Value and I want to allow the users of my app to write something like
Quantity*20+Value*0,005
in a textbox and pass the result back to the C# app. I thought of embedding the IronPython interpreter in my app, but I'm not sure it's worth the effort. Is this the way to go or should I consider another option?
Update
To clarify, users may also write more complex formulae like:
if Value > 10000:
return Value*0,05
elif Value > 1000:
return Value*0,02
else
return 0
A:
I think I'll go this way. Embedding the Python runtime is easy enough and the syntax is really simple for users to write simple scripts.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to bind graphicsmetrics jquery plugin in Angular app
I'm doing an Angular app and I recently found Metrics Graphics. The problem is that I'm having a hard time trying to integrate it to my angular app, given that is build for Jquery.
The another tricky problem is that my Angular app is consuming a restful API, and for the graphics that I want to integrate, the data is in the API.
The code to generate the graphics:
$(function () {
d3.json('file/json.json', function(data) {
data_graphic({
data: data,
width: 650,
height: 150,
target: '#element',
x_accessor: 'Month',
y_accessor: 'Value'
})
});
});
As you see, this code extracts data from a json file. Gratefully, my API is also returning json format in, i.e., http://api.example.com/api/data.
So what I want to do is bind this jquery script inside an angular directive (or controller) and make the data comes from the API and not a file.
Thank you
A:
Here is a simple example where everything is handled by a directive:
app.directive('metrics', function($http) {
return {
restrict: 'E',
link: function(scope, element) {
var success = function(result) {
data_graphic({
title: "UFO Sightings",
description: "Yearly UFO sightings from 1945 to 2010.",
data: result,
markers: [{
'year': 1964,
'label': '"The Creeping Terror" released'
}],
width: 400,
height: 250,
target: element[0],
x_accessor: "year",
y_accessor: "sightings",
interpolate: "monotone"
});
};
var error = function() {
console.log('Error.');
};
$http.get('data.json').success(success).error(error);
}
};
});
Usage:
<metrics></metrics>
You can replace data.json with the URL you need as long as it returns the correct format. The success function will initiate data_graphic and set data to the result from the $http.get and target to the directive DOM element.
Demo: http://plnkr.co/edit/SOfTS6KL0GJ7ynvyrBfn?p=preview
If you want a controller to handle the retrieving of the data:
app.controller('MyController', function($scope, $http) {
var success = function(result) {
$scope.data = result;
};
var error = function() {
console.log('Error.');
};
$http.get('data.json').success(success).error(error);
});
Directive:
app.directive('metrics', function($http) {
return {
restrict: 'E',
scope: {
data: '='
},
link: function(scope, element) {
data_graphic({
title: "UFO Sightings",
description: "Yearly UFO sightings from 1945 to 2010.",
data: scope.data,
markers: [{
'year': 1964,
'label': '"The Creeping Terror" released'
}],
width: 400,
height: 250,
target: element[0],
x_accessor: "year",
y_accessor: "sightings",
interpolate: "monotone"
});
}
};
});
Usage:
<body ng-controller="MyController">
<metrics ng-if="data" data="data"></metrics>
</body>
Note that ng-if is used to prevent the directive from executing before the data is available.
Demo: http://plnkr.co/edit/96IVbjlZk8nriiREHdl4?p=preview
The next step would be to pass the entire object that is used in data_graphic to the directive as well, making it even more general and reusable.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Convert node data to pdf via Rules
I have a project plan content type. I would like to be able to change the "start date" field value to the current date, and set the "deadline date" field value to 2 weeks after. Then I would like to convert this data into a file (eg. pdf) which I can then attach to another entity.
The majority of this can be achieved using the Set Data Value action in Rules module; except of course for converting the data into a file. The module FillPDF comes quite close although it only allows for converting Webform data to pdf and not node data.
The following modules are able to convert nodes to pdf, however they do not have Rules integration: PDF using mPDF, Printer, email, PDF versions
What is the best way to achieve this?
A:
It appears that this module is the answer: PDF Archive
The only issue with this module is that it only converts the text of the node. Any images are not outputted to the pdf.
PDF Archive:
The PDF Archive module provides the ability to generate PDF archives of any entity triggered by Rules actions. Both the entity view mode and role of the simulated user used for rendering the entity can be set per rule.
An example feature is included to demonstrate the configuration of this module.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Vectorized column selection
How can I use one column's value (eg, x below) to select among values among possible columns, when the selection is specific to each row?
The x variable determines whether variable a, b, or c should be selected for a given row. Here's a simplified example; the real cells aren't a concatenation of the column name and row number.
library(magrittr); requireNamespace("tibble"); requireNamespace("dplyr")
ds <- tibble::tibble(
x = c( 1 , 1 , 2 , 3 , 1 ),
a = c("a1", "a2", "a3", "a4", "a5"),
b = c("b1", "b2", "b3", "b4", "b5"),
c = c("c1", "c2", "c3", "c4", "c5")
)
The desired columns are values are:
# ds$y_desired <- c("a1", "a2", "b3", "c4", "a5")
# ds$column_desired <- c("a" , "a" , "b" , "c" , "a" )
Of course the following doesn't produce a single column, but fives columns.
ds[, ds$column_desired]
And the following produces the error:
Error in mutate_impl(.data, dots) : basic_string::_M_replace_aux.
ds %>%
dplyr::rowwise() %>%
dplyr::mutate(
y = .[[column_desired]]
) %>%
dplyr::ungroup()
If my real scenario had only two or three choices, I'd probably use nested-ifs, but I'd like a generalized mapping approach to accommodate a larger number of conditions.
ds %>%
dplyr::mutate(
y_if_chain = ifelse(x==1, a, ifelse(x==2, b, c))
)
Ideally the approach could be directed by a lookup table, or some other metadata object like:
ds_lookup <- tibble::tribble(
~x, ~desired_column,
1L, "a",
2L, "b",
3L, "c"
)
I'm sure this column switching question has been asked before, but I didn't find one that applied.
I'd prefer a tidyverse solution (b/c that's what my team is most comfortable with), but I'm open to any tool. I couldn't figure out how to use a combination of apply and kimisc::vswitch.
A:
Try this:
ds$y_desired = apply(ds, 1, function(r) r[as.integer(r[1])+1])
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a way in C++ of saving an object and then reload it although it has a pointer as attribute?
I have an object that has this pointer 'SDL_Texture *texture' and of course some other irrelevant attributes and methods. I wanted to save the whole object to a file and then reload it in the next session.
I tried to load it and reassign the texture (that would point to a wrong memory address) before using it, but of course I get completely wrong values.
Here is the code:
class Entity
{
private:
SDL_Texture *texture = NULL;
// ...
public:
Entity::Entity(){}
void Entity::loadSprites()
{
this->texture = IMG_Load("./sprites/puppet/idle.png");
// ...
}
}
Entity load(const char filepath[])
{
Entity ent;
ifstream file(filepath);
file.read(reinterpret_cast<char*>(&ent), sizeof(Entity));
file.close();
ent.loadTexture();
return ent;
}
I know the idea of loading a wrong pointer is probably one of the worst things I can do but I was wondering how this can change the values of every attribute of my object, and how I can avoid this.
I also have to admit that I don't really understand how 'reinterpret_cast(&ent)' works.
A:
The problem you are describling is about a data serialization. In such process you write all data you need into a data stream so that you can reconstruct the object internal state from that data later. You usually want to write the bare minimum of data required.
There are many ways to go how to implement it:
Make save(std::ostream & data) member function and define constructor:
Entity(std::istream & data) which constructs the object from data read from the stream.
Use serialization library like boost::serialization (very generic, can (de)serialize anything)
Any case, you need to decide the data format of an object so that you can reliably read it. Just dumping the entire object to disk via fstream::write()/read() is a bad idea for many reasons:
Objects may contain some pointers like vtable that cannot be saved. They are fixed inplace at constructor.
If the class changes in any way after the data was dumped it would render any already saved data useless.
Writing any data address values to file is an error: next time the program is run they are invalid. Any pointers to data need to be serialized (the data itself, not the pointer!)
Serialization is usually a recursive process. E.g boost::serialization handles this so that you can serialize things like containers of objects. (like std::list)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Show that his cover does not have any finite sub covers
My question is how to prove that the following cover does not have a finite sub cover :
$$A_{n}=\{x \in \mathbb{R}^{n}: \frac{1}{2n}<|x|<\frac{3}{2n} \}$$
for the pointed ball $B_1^*(x) = \{ x: 0 < |x| \le 1 \}$
But the thing is how can I prove it because I don't know is there is a standard method to do it or how do I have to proceed, I think that this has to be easy, but I need your help :) thanks in advance
A:
Suppose that $U = \{ A_i \mid i \ J \}$ is a subcover, where $J$ is a set of integers. Every subcover can be written this way: you just include in $J$ the indices of all the "A"-sets that are included.
If $J$ were finite, then it has a maximum (every finite set of integers has a maximum element); class this maximum $N$. Then the point $(\frac{1}{4N}, 0, \ldots, 0)$, is not covered by $U$. Why not? Suppose that it were. Then for some $i \in J$, we'd have
$$
\frac{1}{2i} < \frac{1}{4N} < \frac{3}{2i}
$$
Ignoring the second inequality, this says that
$$
\frac{1}{2i} < \frac{1}{4N} \\
2i > 4N \\
i > 2N
$$
But since $N$ is the maximum of a set of positive integers, it's positive. Hence $2N > N$, so we conclude $i > N$, which is a contradiction, since $N$ was defined to be the largest element of $J$.
(By the way, the letter $n$ is used for two different things in this problem. (1) the dimension of the space $\mathbb R^n$, and (2) an index for elements of an open cover. I suggest replacing the first use by $k$.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to solve java.security.AccessControlException
I need suggestions concerning the java.security.AccessControlException, I get when executing the following code. (I have consulted similar questions here but didn't success to make it work)
Here is my server code:
public class GetPageInfos extends UnicastRemoteObject implements RemoteGetInfo{
private static final String url="http://www.lemonde.fr/";
public class GetPageInfos extends UnicastRemoteObject implements RemoteGetInfo{
private static final String url="http://www.lemonde.fr/";
public GetPageInfos() throws RemoteException{
}
public String getSiteInfos() throws RemoteException {
Document doc;
try {
doc = Jsoup.connect(url).get();
String title = doc.title();
return "title is "+title;
} catch (IOException e) {
System.out.println("Faild! "+e.getMessage());
return "not found";
}
}
public static void main(String[] args){
try {
GetPageInfos infos= new GetPageInfos();
//System.setProperty("java.rmi.server.hostname","5lq04x1.gemalto.com");
Naming.rebind("RemoteGetInfo", infos);
/*GetPageInfos obj=new GetPageInfos();
RemoteGetInfo stub = (RemoteGetInfo) UnicastRemoteObject.exportObject(obj, 0);
Registry registry = LocateRegistry.getRegistry();
registry.bind("RemoteGetInfo", stub);
*/
System.out.println("server ready");
} catch (RemoteException e) {
System.out.println("GetPageInfos "+e.getMessage());
}
catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And here is my client code:
//RMI Client
public class PrintSiteInfos {
public static void main(String arg[])
{
System.setSecurityManager(new RMISecurityManager());
try
{
/*String host=null;
Registry registry = LocateRegistry.getRegistry(host);
RemoteGetInfo stub = (RemoteGetInfo) registry.lookup("RemoteGetInfo");
String response = stub.getSiteInfos();
System.out.println(response); */
RemoteGetInfo obj = (RemoteGetInfo) Naming.lookup( "RemoteGetInfo");
System.out.println(obj.getSiteInfos());
}
catch (Exception e)
{
System.out.println("PrintSiteInfos exception: " + e.getMessage());
e.printStackTrace();
}
}
}
So I got
exception: access denied ("java.net.SocketPermission" "127.0.0.1:1099" "connect,resolve")
I found that I have to pass a policy file which I have like:
grant {
permission java.security.AllPermission;};
But how? Anyother suggestions?
A:
You may grant only the socket permission not all permissions (which might be a security risk). Thus something like:
grant {
permission java.net.SocketPermission "127.0.0.1:1099", "connect, resolve";
};
Two ways to do it:
1) As an argument at the command line
java -Djava.security.policy=mypolicyfile PrintSiteInfo
2) within the JRE environment:
Add the permission in the JRE_HOME/lib/security/java.policy file
|
{
"pile_set_name": "StackExchange"
}
|
Q:
svn branch creation from specific revisions
Is there any way to make a (svn) branch from specific revisions,
as i want to skip some revisions (in new branch) in my commit history.
For example i have revisions from 1 to 1590 and i want to create a new branch and skip the commits (from revision 1504 to 1574 ) and
revision#1584, revision#1586, and revision#1587.
Kindly help me i will be thankful.
A:
There are two ways to make a new branch from old revision. One is to set your working copy to old revision (right click > TortoiseSVN > Update to revision), and then make a branch (right click > TortoiseSVN > Branch/tag). After that update to head revision with usual Update command.
Another way is to use repository browser (right click > TortoiseSVN > Repo-browser), choose a revision (click on a button in top-right corner with text HEAD), and then use Ctrl+mouse drag-drop to copy folder (or, as alternative, right click on folder > Copy to).
EDIT: Because you want some later revisions in new branch, after you make a branch do a merge. Merge into new branch all the revisions from main line that you want there.
I see now that there is a third way. You can make a branch from HEAD revision, but then do a "reverse merge", to remove unwanted revisions. Just select that option when merging.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
not able to insert record in firebase table using Angular 6
not able to insert record in firebase table using Angular 6, I am using real-time database
Component code below:-
*CreateRecord() {
let jsonob: jsonob = {
'MSG-21A7605D-A48E-4291-ABDA-4DFE046FE597': {
msg_text: 'Test Person1'
}
};
this.crudService.create_NewStudent(jsonob).then(resp => {
this.msg_text = "";
console.log(resp);
}).catch(error => {
console.log(error);
});
}
create_NewStudent(record) {
return this.firestore.collection('messages').add(record);
}
Firebase Rules is below:-
{
"rules": {
".read": true,
".write": true
}
}
messages table is below:-
https://i.stack.imgur.com/InWGE.png
Error Message:
FirebaseError: Missing or insufficient permissions.
at new FirestoreError (http://localhost:4200/vendor.js:93048:28)
A:
Your question says "I am using real-time database", but the code is using Firestore. On top of that, you're showing rules for Realtime Database, which in no way affect access to Firestore. The error message "Missing or insufficient permissions" is suggesting that your Firestore security rules (not your Realtime Database rules) are disallowing access.
Basically, you're going to have to go back and make sure you're using the correct database system across the board.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to remove white space from HTML text
How do I remove spaces in my code? If I parse this HTML with Nokogiri:
<div class="address-thoroughfare mobile-inline-comma ng-binding">Kühlungsborner Straße
10
</div>
I get the following output:
Kühlungsborner Straße
10
which is not left-justified.
My code is:
address_street = page_detail.xpath('//div[@class="address-thoroughfare mobile-inline-comma ng-binding"]').text
A:
Consider this:
require 'nokogiri'
doc = Nokogiri::HTML('<div class="address-thoroughfare mobile-inline-comma ng-binding">Kühlungsborner Straße
10
</div>')
doc.search('div').text
# => "Kühlungsborner Straße\n 10\n "
puts doc.search('div').text
# >> Kühlungsborner Straße
# >> 10
# >>
The given HTML doesn't replicate the problem you're having. It's really important to present valid input that duplicates the problem. Moving on....
Don't use xpath, css or search with text. You usually won't get what you expect:
require 'nokogiri'
doc = Nokogiri::HTML(<<EOT)
<html>
<body>
<div>
<span>foo</span>
<span>bar</span>
</div>
</body>
</html>
EOT
doc.search('span').class # => Nokogiri::XML::NodeSet
doc.search('span') # => [#<Nokogiri::XML::Element:0x3fdb6981bcd8 name="span" children=[#<Nokogiri::XML::Text:0x3fdb6981b5d0 "foo">]>, #<Nokogiri::XML::Element:0x3fdb6981aab8 name="span" children=[#<Nokogiri::XML::Text:0x3fdb6981a054 "bar">]>]
doc.search('span').text
# => "foobar"
Note that text returned the concatenated text of all nodes found.
Instead, walk the NodeSet and grab the individual node's text:
doc.search('span').map(&:text)
# => ["foo", "bar"]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
multiple nested if statements not calculating
I'm trying to get this payslip calculator to run multiple if statements nested in eachother.
The conditions it requires to meet are as follows:
If the monthly gross pay is 2000 for example
and the last letter of the NI code is A
to work out a national insurance allowance you do the gross pay divided by 4.
2000 / by 4 = 500. Meaning that the NI band is a2.
The sum then is "gross * a2" (as seen on the variables listed at the top of the code)
This then displays the result as "Your NI deduction:??"
I'm struggling to get the if statements to run if a different letter is inputted.. For example "B"
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script>
function computeNet() {
<!--NI Codes - use https://www.gov.uk/national-insurance-rates-letters/contribution-rates for updates on NI rates--!>
//NI Code A//
var a1 = 0;
var a2 = 0.12;
var a3 = 0.12;
var a4 = 0.02;
//NI Code B//
var b1 = 0;
var b2 = 0.0585;
var b3 = 0.0585;
var b4 = 0.02;
//NI Code C//
var c = 0;
var d1 = 1.4;
var d2 = 0.106;
var d3 = 0.12;
var d4 = 0.02;
//NI Code E//
var e1 = 0;
var e2 = 0.0585;
var e3 = 0.0585;
var e4 = 0.02;
//NI Code J//
var j1 = 0;
var j2 = 0.02;
var j3 = 0.02;
var j4 = 0.02;
//NI Code L//
var l1 = 1.4;
var l2 = 0.02;
var l3 = 0.02;
var l4 = 0.02;
var gross = document.getElementById('gross').value;
var tax_code = document.getElementById('tcode').value;
var ni_code = document.getElementById('ni').value;
var allowance = ((gross - ((tax_code * 10)/12)));
var ni_allowance = (gross / 4);
if (ni_code = "A") {
if (ni_allowance > 111 && ni_allowance < 153) {
ni_minus = (gross * a1);
}
else if (ni_allowance > 153.01 && ni_allowance < 770) {
ni_minus = (gross * a2);
}
else if (ni_allowance > 770.01 && ni_allowance < 805) {
ni_minus = (gross * a3);
}
else {
ni_minus = (gross * a4);
}
if (ni_code = "B") {
if (ni_allowance > 111 && ni_allowance < 153) {
ni_minus = (gross * b1);
}
else if (ni_allowance > 153.01 && ni_allowance < 770) {
ni_minus = (gross * b2);
}
else if (ni_allowance > 770.01 && ni_allowance < 805) {
ni_minus = (gross * b3);
}
else {
ni_minus = (gross * b4);
}
}
document.getElementById('ni_deduction').innerHTML = "Your NI deduction:"+ni_minus;
}
}
</script>
</head>
<body>
<p>Your Monthly Gross Pay: £<input id="gross" type="number" onChange="computeNet()"></p>
<p>The numerical part of your tax code: <input id="tcode" type="number" onChange="computeNet()"></p>
<p>last letter of your NI code: <input id="ni" type="text" onChange="computeNet()"></p>
<h2 id="gross_pay"></h2>
<h2 id="paye-deduction"></h2>
<h2 id="ni_deduction"></h2>
<h2 id="net_pay"></h2>
</body>
</html>
Code here: http://jsfiddle.net/n384noLk/
I look forward to your help
A:
If "B" needs to be moved out of If "A".
Because it is nested, you skip the If "B" statement completely if ni_code doesn't equal "A".
if (ni_code == "A") {
if (ni_allowance > 111 && ni_allowance < 153) {
ni_minus = (gross * a1);
} else if (ni_allowance > 153.01 && ni_allowance < 770) {
ni_minus = (gross * a2);
} else if (ni_allowance > 770.01 && ni_allowance < 805) {
ni_minus = (gross * a3);
} else {
ni_minus = (gross * a4);
}
} elseif (ni_code == "B") {
if (ni_allowance > 111 && ni_allowance < 153) {
ni_minus = (gross * b1);
} else if (ni_allowance > 153.01 && ni_allowance < 770) {
ni_minus = (gross * b2);
} else if (ni_allowance > 770.01 && ni_allowance < 805) {
ni_minus = (gross * b3);
} else {
ni_minus = (gross * b4);
}
}
http://jsfiddle.net/n384noLk/2/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What proportion are above x of sample size n where X ~ N(0,1) Homework
I have a homework question that I'm not quiet sure of. It follows as so:
Consider a random variable $X$ that has a standard normal distribution with mean $\mu=0$ and standard deviation $\sigma=1$. What proportion of the means of samples of size 10 are greater than 0.60?
This is what I did:
$$X \sim N(\mu=0, \sigma=1)$$
$$Z = \frac{X - \mu}{\sigma/\sqrt(n)}$$
$$Z = \frac{X - 0}{1/\sqrt(10)}$$
$$= 0.189$$
Thank you,
A:
Let $\bar{X}$ be the sample mean. Then $\bar{X}$ has normal distribution, mean $0$, standard deviation $\frac{1}{\sqrt{10}}$.
We want to find $\Pr(\bar{X}\gt 0.6)$. This is equal to
$$\Pr\left(Z\gt \frac{0.6-0}{1/\sqrt{10}}\right),$$
where $Z$ is standard normal.
Note that $\dfrac{0.6}{1/\sqrt{10}}\approx 1.897$. Now you can find the required information from tables of the standard normal, or from appropriate software.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What does it mean for an application to be FIPS 140 compliant?
Is it as simple as using FIPS 140 compliant crypto providers or is there more to it? Are there differences if it is a web app vs a windows app? What if it is a distributed app? Are there any special considerations for IIS, WCF, ASP.Net, Silverlight, AJAX, etc?
Thanks
A:
FIPS is a series of standards followed by the U.S. government regarding information security. There are policies, practices etc. In order to qualify to be compliant you have to make sure that you only use certain algorithms, the hardware and software you use must be deemed compliant etc.
Is it as simple as using FIPS 140
compliant crypto providers or is there
more to it?
It depends on each specific scenario, but yes it can be. For example, if certain routers you use are 140-2 compliant then your application behind them can get exemption of going through parts of the process, because the hardware you use accomplishes the same task the certification requires. For example, we use the F5 Big IP to handle a lot of our SSL etc., because they have gone through the certification process. Our other systems may be able to do the same thing, but it means we don't have to go through the approval process, which is long and painful.
http://en.wikipedia.org/wiki/FIPS_140
I think these are the links which talk about accreditation:
http://csrc.nist.gov/groups/STM/index.html
http://csrc.nist.gov/groups/STM/cmvp/index.html
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I insert content between the 2nd and 3rd paragraphs in HTML, using Perl?
I'm trying to match the point between 2nd and 3rd paragraphs to insert some content. Paragraphs are delimited either by <p> or 2 newlines, mixed. Here's an example:
text text text text
text text text text
<p>
text text text text
text text text text
</p>
<--------------------------- want to insert text here
<p>
text text text text
text text text text
</p>
A:
Assuming there are no nested paragraphs...
my $to_insert = get_thing_to_insert();
$text =~ s/((?:<p>.*?</p>|\n\n){2})/$1$to_insert/s;
should just about do it.
With extended formatting:
$text =~ s{
( # a group
(?: # containing ...
<p> # the start of a paragraph
.*? # to...
</p> # its closing tag
| # OR...
\n\n # two newlines alone.
){2} # twice
) # and take all of that...
}
{$1$to_insert}xms # and append $val to it
Note, I used \n\n as the delimiter; if you're using a windows style text file, this needs to be \r\n\r\n, or if it might be mixed, something like \r?\n\r?\n to make the \r optional.
Also note that because the '\n\n' is after the |, the <p> blocks can have double newlines in them - <p> to </p> takes priority. If you want newlines inside the <p>'s to take priority, swap those around.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MariaDB Slave cause "Copying to tmp table"
DB: MariaDB 10.0.23
STOP SLAVE;
run query
SHOW PROFILE;
Status Duration
starting 0.000028
Waiting for query cache lock 0.000006
init 0.000004
checking query cache for query 0.000011
checking privileges on cached 0.000005
checking permissions 0.000007
checking permissions 0.000005
checking permissions 0.000005
sending cached result to clien 0.000154
updating status 0.000005
cleaning up 0.000003
After starting slave, long "Copying to tmp table" shows up:
START SLAVE;
run query EXPLAIN outputs same query plan like before starting the slave.
SHOW PROFILE;
Status Duration
starting 0.000046
Waiting for query cache lock 0.000007
init 0.000006
checking query cache for query 0.000109
checking permissions 0.000007
checking permissions 0.000005
checking permissions 0.000006
Opening tables 0.000020
After opening tables 0.000009
System lock 0.000007
Table lock 0.000005
After opening tables 0.000007
Waiting for query cache lock 0.000005
After opening tables 0.000031
init 0.000050
optimizing 0.000032
statistics 0.000139
preparing 0.000050
executing 0.000007
Copying to tmp table 0.000025
Copying to tmp table 1.760070 <<<<<<<<<<<<<<<<<<<<
Sorting result 0.003707
Sending data 0.000013
end 0.000005
removing tmp table 0.000261
end 0.000006
query end 0.000006
closing tables 0.000010
freeing items 0.000013
updating status 0.000068
logging slow query 0.000008
cleaning up 0.000005
A:
Not MariaDB Slave, the Query Cache.
It appears that the first Profile came from a machine where the identical query had already been stored in the Query Cache. Hence, the query took only a fraction of a millisecond to simply deliver the old resultset to the client.
The second server apparently has not seen the identical query recently, so it had to work on the query (open tables, optimize, use a tmp table, etc). This took a lot longer.
Addenda
The Query Cache works this way:
If a query is in the QC, and exactly the same query shows up to be run, the resultset is delivered very rapidly from the QC. However,
When any modification to the tables(s) involved occurs, the all entries in the QC for that table(s) are purged.
Replication is a stream of modifications.
For this reason, then QC is rarely worth turning on for Production servers with a lot of write traffic.
So, I deduce that the some modification (INSERT, UPDATE, etc) occurred to that table, thereby invalidating the entry in the QC before that second copy of the SELECT was presented.
If the stream of changes from Replication had only touched other tables, then the second query would have been just as fast as the first.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
self.tabBarController.selectedIndex not calling viewDidAppear
I've been looking at and trying all the solutions others have posted to this problem, but I'm still not getting it.
My use case is very simple. I have a viewController with a button, when that button is pressed I want to navigate to another tab and reload the data including an api call.
When using the button, I navigate to the tab fine, but viewDidAppear is not being called.
If on another tab, and navigate using the tab bar, viewDidAppear works fine. Also viewWillAppear is working, but I have to add a manual delay to the functions I want to call so it's not ideal.
So what do I need to do to navigate using self.tabBarController.selectedIndex = 0 and get the functionality of viewDidAppear?
Update: The viewWillAppear method I added gets called but I have to add a delay to my functions in order for them to work, and it's a bit clunky, not ideal. Not sure why viewDidAppear will not work :(
Here is a screenshot of the structure:
I appreciate any help on this one!
The "current" ViewController is my tab index 2:
import UIKit
class PostPreviewVC: UIViewController {
//Here I create a post object and post it to the timeline with the below button
@IBAction func postButtonPressed(_ sender: Any) {
//create the post via Firebase api
self.tabBarController?.selectedIndex = 0
}
}
In my destination viewController:
import UIKit
import Firebase
import SDWebImage
import AVFoundation
class HomeVC: UIViewController {
// MARK: - PROPERTIES
var posts = [Post]()
let refreshControl = UIRefreshControl()
//more properties...
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
configureTableView()
reloadTimeline()
UserFirebase.timeline { (posts) in
self.posts = posts
self.tableView.reloadData()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("viewDidAppear")
_ = self.view
setupUI()
configureTableView()
reloadTimeline()
UserFirebase.timeline { (posts) in
self.posts = posts
self.tableView.reloadData()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("viewWillAppear")
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.reloadTimeline()
self.configureTableView()
}
}
//All the tableview code below here...
}
Added a custom class for my tab bar controller:
import UIKit
class TabBarController: UITabBarController, UITabBarControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("viewDidAppear in tabBar custom Class called")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("viewWillAppear in tabBar custom Class called")
}
}
A:
When you are using UITabBarController, the method viewDidLoad will called only once when any UIViewController is loaded in memory. After that, when you are navigating the same UIViewController, then it will load from memory.
In order to overcome this problem, you must divide your code in viewDidLoad & viewDidAppear. So, in viewDidLoad, you only put that code which you want to intialize once throughout the app such as adding UIView's or other things, while in viewDidAppear / viewWillAppear, you can make API calls or some functions which fetches dynamic data.
Finally, when you are calling self.tabBarController.selectedIndex = 0, it will call viewDidLoad only once and viewDidAppear / viewWillAppear every time when you are navigating that UIViewController.
Hope this helps to understand like how UITabBarController works.
A:
For UITabBarController viewDidLoad only gets called once. and your viewWillAppear and viewDidAppear get called multiple times. you can either check if your viewWillAppear gets called or not. because your view will appear gets called before your viewDidAppear it's just like going through the reverse engineering process.
You can also add viewDidAppear method into your UITabBarController custom class. and call its superclass method into it in that way I think it will solve your problem.
Note: In the case of UITabbarController, Always do your UI update task and API calling a task in either
viewWillAppear or viewDidAppear
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Close android activity (completely, not even in background) using finish on a button click
I need to close an activity when a button is clicked. Unfortunately, when button is clicked, the activity does disappear but is still in the background. User can still select it and it comes back to front. What I need is the activity completely gone/destroyed.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
I searched on SO on related questions, however, none of them help with closing the activity completely. I already tried adding return, adding another broadcast listener and passing command to call finish outside onCreate. So at this point, the question is - is this really possible or is this how Android works, you can call finish() but it is still in the background and user can re-launch it.
Here is xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app1.test.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
EDIT: Adding android:excludeFromRecents="true" does not solve the issue. Here are steps to recreate this, if anyone thinks it is a duplicate or already solved, please try and post comment/answer, I will accept it.
Open Android Studio
Create empty activity project.
Add a button.
Add code in MainActivity's onCreate for button click listener.
Inside click listener, call finish.
Run the app and click button and see if the activity is still in background or not.
A:
Just give it a try.
In you manifest.
<activity
android:excludeFromRecents="true"
android:name=".Activities.SplashActivity"
android:theme="@style/AppThemeSubActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Now in your java code.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item_search:
// Intent intent = new Intent(MainActivity.this, SearchActivity.class);
// startActivity(intent);
finish();
System.exit(0);}
}
put the extra line System.exit(0); after calling finish it works for me.
A:
You need to put this in your XML manifest:android:excludeFromRecents="true"
in your Activity TAG.
<activity
...
android:excludeFromRecents="true">
</activity>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why my regex does not match the 'username' constraints
I am struggling to write a regex on code camp which must fit the following 4 constraints defined for a correct 'username'
1) Usernames can only use alpha-numeric characters.
2) The only numbers in the username have to be at the end. There can be zero or more of them at the end. Username cannot start with the number.
3) Username letters can be lowercase and uppercase.
4) Usernames have to be at least two characters long. A two-character username can only use alphabet letters as characters.
Here is the Regex I came up with, in the following code (first line)
let userCheck = /[a-zA-Z]([a-zA-Z]+\d*|\d\d+)/; // the regex I wrote
let result = userCheck.test(username);
However, it displays the following fault
Your regex should not match BadUs3rnam3
Your regex should not match c57bT3
I am absolutely confused. I actually know what the correct regex to this problem is, however, I need to know where my own regex is going wrong which is producing the above error. Please help
A:
Your code passes because you are not using anchors so you get a partial match.
You could update the pattern to ^[a-zA-Z](?:[a-zA-Z]+\d*|\d{2,})$
Another way to write it could be matching either 2 chars a-zA-Z and 0+ digits, or in case there is a single char a-zA-Z, match 2 or more digits to pass the rule
A two-character username can only use alphabet letters as characters.
^(?:[a-zA-Z]{2,}\d*|[a-zA-Z]\d{2,})$
Regex demo
let userCheck = /^[a-zA-Z](?:[a-zA-Z]+\d*|\d{2,})$/;
[
"BadUs3rnam3",
"c57bT3",
"aa",
"a111111",
"a1",
"11"
].forEach(username => console.log(username + ": " + userCheck.test(username)));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Thymeleaf, fragments and default parameters
I have created fragments.html file. It contains the following fragment:
<div th:fragment="my_fragment(content)">
<p th:text="${content}"></p>
</div>
I put the above fragment into my view file:
<div th:replace="fragments :: my_fragment('test')"></div>
Now, I want to pass two parameters to my_fragment, but I must ensure backward compatibility.
I tried to solve the problem as follows:
<div th:fragment="my_fragment(content, defaultParameter='default value')">
<p th:text="${content}"></p>
</div>
Unfortunelly, the above solution generated error:
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is
org.thymeleaf.exceptions.TemplateProcessingException: Cannot resolve
fragment. Signature "my_fragment (content,defaultParameter='default value')"
declares 2 parameters, but fragment selection specifies 1 parameters.
Fragment selection does not correctly match.
Any idea?
A:
Thymeleaf allows a signature of a fragment without explicit parameters like this:
<div th:fragment="my_fragment">
<p th:text="${content}"></p>
<p th:text="${defaultParameter}"></p>
</div>
To call this fragment and pass content and defaultParameter you may call the fragment as follows:
<!-- both parameters not specified -->
<div th:replace="fragments :: my_fragment"></div>
<!-- only content parameter specified -->
<div th:replace="fragments :: my_fragment(content='a')"></div>
<!-- both parameters specified -->
<div th:replace="fragments :: my_fragment(content='a', defaultParameter='b')"></div>
But the below will not work:
<div th:replace="fragments :: my_fragment('a', 'b')"></div>
And the message is self-explonatory:
Signature "my_fragment" declares no parameters, but fragment selection did specify parameters in a synthetic manner (without names), which is not correct due to the fact parameters cannot be assigned names unless signature specifies these names.
So in case you want to maintain backward compatibility, you should use named parameters while calling a fragment and do not specify parameters in a signature of a fragment.
A:
The best way to allow optional parameter for a fragment is to declare them with "th:with" and describe them with meaningful default values.
So, you define explicit your mandatory and your optional values in the declaration tag of your fragment.
Here is simple example, with 1 mandatory and 2 optional parameters:
<div th:fragment="printGreetings (name)" th:with="title=${title} ?: 'Mr.', greeting=${greeting} ?: 'Hello'">
<span th:text="${greeting}">Hello</span>
<span th:text="${title}">Mr.</span>
<span th:text="${name}">John Doe</span>
</div>
You can then call it like the following:
<div th:replace="fragments :: printGreetings (name='daniel')">
Hello Mr. Daniel
</div>
<div th:replace="fragments :: printGreetings (name='Lea', title='Ms.')>
Hello Ms. Lea
</div>
<div th:replace="fragments :: printGreetings (name='Lea', title='Ms.', greeting='Hi')>
Hi Ms. Lea
</div>
(Please note that all values inside the tags are replaced by the dynamic ones. It's just for better reading.)
A:
If you want to provide a default value (as in your case) you can use the elvis operator to specify a default value, for example:
<div th:fragment="my_fragment">
<p th:text="${content}"></p>
<p th:text="${defaultParameter ?: 'the backwards compat value'}"></p>
</div>
see: elvis-operator
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What should I do when Fargate runs out of capacity?
I'm kicking off a single ECS Fargate task with a command such as:
aws ecs run-task --cluster Fargate \
--task-definition $ECR_REPO-run-setup
--overrides file:///tmp/ecs-overrides-db-migrate.txt \
--count 1 --launch-type FARGATE \
--network-configuration "awsvpcConfiguration={subnets=[$PUBLIC_SUBNET_1, $PUBLIC_SUBNET_2],securityGroups=[$FARGATE_SG],assignPubli cIp=ENABLED}"
There are no ECS services, tasks or instances at all running in my account at the moment. This is the response I get back:
{
"failures": [
{
"reason": "Capacity is unavailable at this time. Please try again later or in a different availability zone"
}
],
"tasks": []
}
I don't even see a way to specify a different availability zone for a Fargate Task?
If I should just retry, how long should I wait before retries?
A:
Withing a VPC you can create one or more subnets that correspond to an availability zone.
When launching your Fargate task you will notice the network-configuration parameter and associated awsvpcConfiguration. To specify multiple zones you can pass in multiple subnets. For example:
aws ecs run-task --cluster Fargate \
--task-definition $ECR_REPO-run-setup
--overrides file:///tmp/ecs-overrides-db-migrate.txt \
--count 1 --launch-type FARGATE \
--network-configuration "awsvpcConfiguration={subnets=[$MY_SUBNET_IN_AZ1,
$MY_SUBNET_IN_AZ2]
The VPC documentation in aws contains more helpful information:
https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Subnets.html#vpc-subnet-basics
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Returning exit code from a batch file in a PowerShell script block
I am trying to call a batch file remotely in a one liner PowerShell command as such:
PowerShell -ExecutionPolicy UnRestricted invoke-command -ComputerName Server1 -ScriptBlock {cmd.exe /c "\\server1\d$\testPath\test.bat"}
What I want to do is return any exit codes from the test.bat file back to my command. Can anyone give me an idea on how to do this?
(PS, for multiple reasons, I am not able to use PSExec).
Cheers
A:
You should be able to get the exit code from cmd.exe with the automatic variable $LASTEXITCODE.
If you're interested in only that, and not any output from the batch file, you could change the scriptblock to:
{cmd.exe /c "\\server1\d$\testPath\test.bat" *> $null; return $LASTEXITCODE}
If you're already running powershell, there's no need to invoke powershell again, just establish a session on the remote computer and attach Invoke-Command to it:
$session = New-PSSession remoteComputer.domain.tld
$ExitCode = Invoke-Command -Session $session -ScriptBlock { cmd /c "\\server1\d$\testPath\test.bat" *> $null; return $LASTEXITCODE }
$ExitCode # this variable now holds the exit code from test.bat
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Map a method to a field with Automapper
I want to use Automapper and need to map a method to the field(such as command part).
How can I do it?
This my first Code
foreach(source item in sources)
{
ss.ServerStatusType = ServerStatusTypeName(item);
ss.A = item.A ;
ss.B =item.B;
destinations.Add(dto);
}
I want Use Automapper and I just have problem with ServerStatusTypeName method
var config = new MapperConfiguration(cfg =>
cfg.CreateMap<IList<source >, IList<Destination>>());
IList<Source> statuses = context.Sp_ServerUpdateStatus(userName).ToList();
var mapper = new Mapper(config);
IList<Source> dto = mapper.Map<IList<Destination>>(statuses);
Everything is ok just ss.ServerStatusType is null because I use a method to fill this item
A:
You could try
class YourObjectProfile : Profile
{
public YourObjectProfile()
{
CreateMap<UI_Object, Domain_Object>()
.ForMember(c => c.name, p => p.MapFrom(dbc => dbc.name));
CreateMap<Domain_Object, UI_Object>()
.ForMember(dbc => dbc.name, dbp => dbp.MapFrom(c => c.name));
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Integrals of the form $\int^1_{0} x^\alpha(1-x)^\beta dx$ where $\alpha,\beta \in \mathbb{R}$.
Let $\alpha,\beta \in \mathbb{R}$. I was wondering if there is a systematic way to solve integrals of the following form:
\begin{equation}
\int^1_{0} x^\alpha(1-x)^\beta dx
\end{equation}
I have seen similar kind of integrals many times. Any help/hints would be really appreciated. Thanks!
A:
Begin with the definition of the Gamma function:
$$\Gamma(\alpha+1) = \int_0^{\infty} du\; u^{\alpha} e^{-u} $$
Similarly,
$$\Gamma(\beta+1) = \int_0^{\infty} dv\; v^{\beta} e^{-v} $$
Multiply these together...
$$\begin{align}\Gamma(\alpha+1) \Gamma(\beta+1) &= \int_0^{\infty} du\; \int_0^{\infty} dv\; u^{\alpha} v^{\beta} e^{-u-v}\\ &= \frac1{2^{\alpha+\beta+1}} \int_0^{\infty} dp \; \int_{-p}^p dq \, (p+q)^{\alpha} (p-q)^{\beta} e^{-p} \\ &= \frac1{2^{\alpha+\beta+1}} \int_0^{\infty} dp \; p^{\alpha+\beta+1} e^{-p} \, \int_{-1}^1 dr \, (1+r)^{\alpha} (1-r)^{\beta}\\ &= \Gamma(\alpha+\beta+2) \frac1{2^{\alpha+\beta+1}} \int_0^2 dr \, r^{\alpha} (2-r)^{\beta} \\ &= \Gamma(\alpha+\beta+2) \int_0^1 dx \, x^{\alpha} (1-x)^{\beta}\end{align}$$
In the second line, I used the transformation $p=u+v$, $q=u-v$, which has Jacobian $1/2$. Thus,
$$\int_0^1 dx \, x^{\alpha} (1-x)^{\beta} = \frac{\Gamma(\alpha+1) \Gamma(\beta+1)}{\Gamma(\alpha+\beta+2)} $$
A:
Using the definition of the Beta Function:
$$B(x,y)=\int_0^1t^{x-1}(1-t)^{1-y}dt$$
By matching coefficients,we would conclude that:
$$\int_0^1x^\alpha(1-x)^\beta dx=B(\alpha+1,1-\beta)$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Javascript get request from https server to localhost:port with self signed SSL
I have two servers configured and running om my Debian server. One main server and one Elasticsearch (search engine) server.
The main server is running on a https node server with a NGINX proxy and a purchased SSL certificate. The Elasticsearch server is running on a http server. I've added a new NGINX proxy server to redirect https://localhost:9999 to http://localhost:9200 with a self-signed SSL certificate. There's also a configured authentication on the Elasticsearch server with a username and a password.
Everything seem to be properly configured since I can get a successful response from the server when I'm doing a curl from the servers terminal towards https://localhost:9999 with the -k option to bypass the verication of the self-signed certificate, without it, it does not work.
I cannot do a cross-domain request from my https main server to my http localhost server. Therefore I need to configure https on my localhost server.
Without the -k option:
curl: (60) SSL certificate problem: self signed certificate
More details here: http://curl.haxx.se/docs/sslcerts.html
curl performs SSL certificate verification by default, using a "bundle"
of Certificate Authority (CA) public keys (CA certs). If the default
bundle file isn't adequate, you can specify an alternate file
using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
the bundle, the certificate verification probably failed due to a
problem with the certificate (it might be expired, or the name might
not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
the -k (or --insecure) option.
With the -k option:
{
"name" : "server-name",
"cluster_name" : "name",
"cluster_uuid" : "uuid",
"version" : {
"number" : "x.x.x",
"build_hash" : "abc123",
"build_date" : "Timestamp",
"build_snapshot" : false,
"lucene_version" : "x.x.x"
},
"tagline" : "You Know, for Search"
}
Which is a successful Elasticsearch server response.
So the full curl request looks something like curl -k https://localhost:9999/ --user username:password.
So, the actual question:
I would like to be able to do a simple jQuery AJAX request towards this server. I'm trying with the following request $.get('https://username:password@localhost:9999/') but I'm getting ERR_CONNECTION_REFUSED.
My guess is that that the AJAX request does not bypass the self-signed certificate verification and therefore it refuses to connect.
Is there any simple way to solve this with request headers or something like that? Or do i need to purchase a CA-certificate to make this work with AJAX?
A:
You are right the problem is the self signed certificate.If you try the same request but as http it will work.
Here is a workaround to make ElasticSearch work with https:
You need to implement your own Http Connector:
var HttpConnector = require('elasticsearch/src/lib/connectors/http');
var inherits = require('util').inherits;
var qs = require('querystring');
var fs = require('fs');
function CustomHttpConnector(host, config) {
HttpConnector.call(this, host, config);
}
inherits(CustomHttpConnector, HttpConnector);
// This function is copied and modified from elasticsearch-js/src/lib/connectors/http.js
CustomHttpConnector.prototype.makeReqParams = function (params) {
params = params || {};
var host = this.host;
var reqParams = {
method: params.method || 'GET',
protocol: host.protocol + ':',
auth: host.auth,
hostname: host.host,
port: host.port,
path: (host.path || '') + (params.path || ''),
headers: host.getHeaders(params.headers),
agent: this.agent,
rejectUnauthorized: true,
ca: fs.readFileSync('publicCertificate.crt', 'utf8')
};
if (!reqParams.path) {
reqParams.path = '/';
}
var query = host.getQuery(params.query);
if (query) {
reqParams.path = reqParams.path + '?' + qs.stringify(query);
}
return reqParams;
};
module.exports = CustomHttpConnector;
Then register it like so:
var elasticsearch = require('elasticsearch');
var CustomHttpConnector = require('./customHttpConnector');
var Elasticsearch = function() {
this.client = new elasticsearch.Client({
host: {
host: 'my.server.com',
port: '443',
protocol: 'https',
auth: 'user:passwd'
},
keepAlive: true,
apiVerison: "1.3",
connectionClass: CustomHttpConnector
});
}
https://gist.github.com/fractalf/d08de3b59c32197ccd65
If you want to make simple ajax calls not using ES the only thing you can do is prompt the user to visit the page and accept the certificate themselves when the request is denied.
Also see: https://stackoverflow.com/a/4566055/5758328
|
{
"pile_set_name": "StackExchange"
}
|
Q:
encryption from char to int
i'am writing some encryption program in c++, and when i start it then console print only one char, and decryption don't work, when i do encryption / decryption then program not doing that with numeric numbers of nn, he do that with hes adress. sorry for my english.
// Var
std::string text = "string";
const char *nn = text.c_str();
// Encryption
int x = (int(nn));
x = x * 3 - 100 * 2;
cout << "Numerical numbers: " << x << endl;
cout << "String: " << (char(x)) << endl;
// Decryption
x = (x - 100 * 2) / 3;
cout << "Numerical numbers: " << x << endl;
cout << "String: " << (char(x));
A:
Unless you have restrictions that you have to use the formula x * 3 - 100 * 2 for encryption/decryption, I suggest you to use XOR.
#include <iostream>
#include <string>
int main()
{
// Var
std::string text = "string", encrypt, decrypt;
// Encryption
for (int i = 0; i < text.length(); i++)
{
encrypt += text[i] ^ '1';
}
// Decryption
for (int i = 0; i < encrypt.length(); i++)
{
decrypt += encrypt[i] ^ '1';
}
std::cout << "original text: " << text << std::endl << "encrypted text: " << encrypt << std::endl << "decrypted text: " << decrypt;
}
The output of the above code would be:
original text: string
encrypted text: BECX_V
decrypted text: string
Here is an working example of the above code.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Polymer back button doesn't work with hash routing
Sup! Back button sometimes doesn't work with my polymer project. When i hit back button the page variable is steel the current page and i need to hit the button twice or three times to get it working for example i go to the /#/rules page from /#/home but it doesn't go back to /#/home once i press the back button the second or third time by the way it does go back to the main page. Here is my observer and router:
properties: {
page: {
type: String,
reflectToAttribute: true,
observer: '_pageChanged',
},
},
observers: [
'_routePageChanged(routeData.page)',
],
_routePageChanged: function (page) {
this.page = page || 'home';
this.set('route.path', `/${this.page}`);
},
_pageChanged: function (page) {
// Load page import on demand. Show 404 page if fails
var resolvedPageUrl = this.resolveUrl(page + '.html');
this.importHref(resolvedPageUrl, null, this._showPage404, true);
window.history.pushState({}, null, `#/${this.page}`);
},
And this is my app-route element:
<app-route route="{{route}}" pattern="/:page" data="{{routeData}}" tail="{{subroute}}"></app-route>
Just can't figure out why it does not work the first time. Any help is appreciated and i have already searched a lot with no results.
A:
Can you try this, assuming you have <app-route route="{{route}}"></app-route>?
observers: [
'_routePageChanged(route.path)',
],
_routePageChanged: function(path) {
if (path) {
this.page = this.routeData.page;
} else {
/*
* It's unnecessary to have the following line.
*/
// this.page = 'home';
this.set('route.path', '/home');
}
},
Why it works after all?
I learned my lesson by debugging the source code of <app-route>. If the path is empty, the code for updating data will be skipped - and your observer, _routePageChanged(routeData.page), won't be triggered. See
https://github.com/PolymerElements/app-route/blob/master/app-route.html#L254-L257
https://github.com/PolymerElements/app-route/blob/master/app-route.html#L320-L328
You may consider it to be a flaw in <app-route>. Whatsoever, it's open source, and you can always find your way.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Converting .Net API to PHP
I have this .Net REST API function modified from the demo for a grid control here: http://gijgo.com/grid/demos/ajax-sourced-data.
However, I am using PHP on the backend.
public JsonResult Get(int? page, int? limit)
{
List<Models.inventory> records;
int total;
using (ApplicationDbContext context = new ApplicationDbContext())
{
var query = context.inventory.Select(p => new Models.inventory
{
id = p.id,
company = p.company,
part = p.part,
year = p.year,
model = p.model,
stock = p.stock,
ic = p.ic,
vin = p.vin,
status = p.status,
bodycolor = p.bodycolor,
condition = p.condition,
comments = p.comments,
miles = p.miles,
price = p.price,
qty = p.qty
});
query = query.OrderBy(q => q.id);
total = query.Count();
if (page.HasValue && limit.HasValue)
{
int start = (page.Value - 1) * limit.Value;
records = query.Skip(start).Take(limit.Value).ToList();
}
else
{
records = query.ToList();
}
}
return this.Json(new { records, total }, JsonRequestBehavior.AllowGet);
}
I have converted the function to PHP but am having difficulty with the pagination because the total records isn't really being sent.
The C# code, filters the data after the query and i'm not sure how to do that with PHP and PostgreSQL.
I also want to return the total number of rows without the limit and offset in the result I suppose I'm going to have to run a 2nd query to return that data,
is that correct or can I do it in another way?
private function GetInventory()
{
$ic=$_request['ic'];
$limit=$_request['limit'];
$offset=$_request['page']-1;
$sql = "SELECT u.id, "
. " (SELECT company FROM urgss.users WHERE id = u.id) AS company, "
. " u.itemname || ' (' || u.part || ')' as part, "
. " u.year, "
. " u.model, "
. " u.stockno AS stock, "
. " u.ic AS ic, "
. " u.vin, "
. " u.status || ' / ' || u.currentstatus AS status, "
. " REGEXP_REPLACE(u.bod_col, '[\[\]]', '', 'g') AS bodycolor, "
. " u.condition, "
. " u.comments, "
. " CASE "
. " WHEN u.miles::integer < 1000 THEN "
. " u.miles::INTEGER * 1000 "
. " ELSE "
. " u.miles::INTEGER "
. " END AS miles, "
. " CASE "
. " WHEN u.rprice > 0 THEN "
. " u.rprice "
. " ELSE "
. " NULL "
. " END AS price, "
. " u.qty "
. "FROM unet u "
. "WHERE ic = '" . $ic. "' "
. "AND year::integer > 0"
. " LIMIT " . $limit . " OFFSET ". ($offset * $limit);
$result = pg_exec($db, $sql);
$rows = pg_fetch_all($result);
echo json_encode($rows);
}
A:
If you remove LIMIT from the query (REMOVE THIS . " LIMIT " . $limit . " OFFSET ". ($offset * $limit);), then there are two options:
Instead of pg_fetch_all you could fetch in a loop and specify the $row_num based on offset and limit:
//get total number of rows
$total = pg_num_rows($result);
//get rows from offset up to limit
$row_num = $offset;
while($row_num < ($offset + $limit) && $rows[] = pg_fetch_assoc($result, $row_num)) {
$row_num++;
}
echo json_encode($rows);
Or pg_fetch_all and slice what you want:
//get total number of rows
$total = pg_num_rows($result);
//get ALL rows
$rows = pg_fetch_all($result);
//get rows from offset up to limit
$rows = array_slice($rows, $offset, $limit);
echo json_encode($rows);
Not sure what new { records, total } does in .NET, but you could return one of these:
return json_encode([$rows, $total]);
//or
return json_encode(['rows' => $rows, 'total' => $total]);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Changing TextView LayoutParameters on Button Click
I am willing to create a Button named READ MORE on click the Layout of TextView should turn to WRAP CONTENT and READ MORE button text should be changed to SHOW LESS (this is new button which I created but set visibility GONE in xml while READ MORE has visibility VISIBLE)
So here is the code of mine which work awesome.. on very first click of READ MORE and also very first click of SHOW LESS but after then if again I click READ MORE just only the button gets replaced with SHOW LESS and the layout remains same.
NOTE: I am placing TextView which is inside LinearLayout which is inside CardView and its a fragment
XML CODE
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/view_project_description"
android:layout_width="match_parent"
android:layout_height="80dp"
android:padding="15dp"
android:text="No Description"
android:textColor="@color/black_overlay"
android:textSize="18dp" />
<View
android:layout_width="match_parent"
android:layout_height="12dp"
android:background="#44eaeaea" />
<Button
android:id="@+id/view_project_readmore_button"
android:layout_width="match_parent"
android:layout_height="27dp"
android:background="#55f4f4f4"
android:layout_marginLeft="75dp"
android:layout_marginRight="75dp"
android:text="Read More >>>"
android:textColor="#3143b3"
android:textSize="13sp" />
<Button
android:id="@+id/view_project_showless_button"
android:layout_width="match_parent"
android:layout_height="27dp"
android:background="#55f4f4f4"
android:layout_marginLeft="75dp"
android:layout_marginRight="75dp"
android:text="Show Less >>>"
android:textColor="#3143b3"
android:textSize="13sp"
android:visibility="gone"/>
</LinearLayout>
JAVA BUTTON CODE
final Button view_project_readmore =(Button)getView().findViewById(R.id.view_project_readmore_button);
final Button view_project_showless = (Button)getView().findViewById(R.id.view_project_showless_button);
view_project_showless.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
project_desc.setEnabled(false);
project_desc.setVisibility(View.GONE);
final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (80 * scale + 0.5f);
project_desc.setHeight(500);
project_desc.setText("This is less Description Now");
project_desc.setEnabled(true);
project_desc.setVisibility(View.VISIBLE);
view_project_readmore.setVisibility(View.VISIBLE);
view_project_showless.setVisibility(View.GONE);
}
});
view_project_readmore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
project_desc.setEnabled(false);
//project_desc.setVisibility(View.GONE);
Typeface typeface=Typeface.createFromAsset(getActivity().getAssets(), "fonts/Raleway-Medium.ttf");
project_desc.setTypeface(typeface);
project_desc.setText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec non sapien tellus. Suspendisse non sapien nulla. Maecenas ornare velit sit amet consequat hendrerit. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec egestas dignissim enim. Nunc non egestas lacus. Aliquam rhoncus nec urna eu semper. In varius justo augue, eu tincidunt tellus ultricies nec. Pellentesque vel metus sapien.\n" +
"\n" +
"Morbi venenatis ultrices felis et sodales. Suspendisse aliquet justo nec gravida viverra. Nulla condimentum mi ac purus feugiat semper. Ut libero nunc, molestie ac dignissim quis, laoreet vel sapien. Morbi porttitor pulvinar mi, non consectetur lectus posuere ac. Morbi blandit nisl eu diam pretium, maximus mattis orci lobortis. Donec ut tincidunt erat. Donec pharetra, sapien eget mollis vestibulum, felis nisl finibus sapien, tempus laoreet turpis ipsum fermentum eros. Praesent eu nulla facilisis, aliquam massa a, hendrerit risus. Proin at mi odio. Quisque semper, nunc sit amet molestie mattis, quam orci commodo ipsum, ut congue risus dolor eget tellus. Nullam ac mauris in eros condimentum lobortis eget eget ipsum. Lorem ipsum dolor sit amet, consectetur adipiscing elit.");
ViewGroup.LayoutParams params = project_desc.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
project_desc.setLayoutParams(params);
project_desc.setEnabled(true);
//project_desc.setVisibility(View.VISIBLE);
view_project_readmore.setVisibility(View.GONE);
view_project_showless.setVisibility(View.VISIBLE);
}
});
A:
Setting the height through the layout params in the click listener of the show less button does the trick.
So replace this:
project_desc.setHeight(500);
With this:
ViewGroup.LayoutParams params = project_desc.getLayoutParams();
params.height = 500;
project_desc.setLayoutParams(params);
Or if you want it to be shorter, this works as well:
project_desc.getLayoutParams().height = 500;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Maven clean install Failed [ Illegal character in path at index ]
I am using Jfrog Artifactory in windows 8.1. I deployed the hibernate jars through Artifactory deploy option. But when I tried to use maven clean install option I ended up in the following error.
[ERROR] Failed to execute goal on project hibernate: Could not resolve dependencies for project com.bala.exercises.hibernate:hibernate:jar:0.0.1-SNAPSHOT: Failed to collect dependencies for [junit:junit:jar:3.8.1 (test), com.fasterxml:classmate:jar:1.0.0 (compile), dom4j:dom4j:jar:1.6.1 (compile), hibernate-core:hibernate-core:jar:4.3.5.Final (compile), hibernate-commons-annotations:hibernate-commons-annotations:jar:4.0.4.Final (compile), hibernate-jpa:hibernate-jpa:jar:1.0.0.Final:2.1-api (compile), org.jboss:jandex:jar:1.1.0.Final (compile), org.javassist:javassist:jar:3.18.1-GA (compile), org.jboss.logging:jboss-logging:jar:3.1.3.GA (compile), mysql-connector-java:mysql-connector-java:jar:bin:5.1.31 (compile)]: Failed to read artifact descriptor for hibernate-core:hibernate-core:jar:4.3.5.Final: Could not transfer artifact hibernate-core:hibernate-core:pom:4.3.5.Final from/to balahome server (http://localhost:8080/artifactory/ bala-libs-mandatories): Illegal character in path at index 34: http://localhost:8080/artifactory/ bala-libs-mandatories/hibernate-core/hibernate-core/4.3.5.Final/hibernate-core-4.3.5.Final.pom -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal on project hibernate: Could not resolve dependencies for project com.bala.exercises.hibernate:hibernate:jar:0.0.1-SNAPSHOT: Failed to collect dependencies for [junit:junit:jar:3.8.1 (test), com.fasterxml:classmate:jar:1.0.0 (compile), dom4j:dom4j:jar:1.6.1 (compile), hibernate-core:hibernate-core:jar:4.3.5.Final (compile), hibernate-commons-annotations:hibernate-commons-annotations:jar:4.0.4.Final (compile), hibernate-jpa:hibernate-jpa:jar:1.0.0.Final:2.1-api (compile), org.jboss:jandex:jar:1.1.0.Final (compile), org.javassist:javassist:jar:3.18.1-GA (compile), org.jboss.logging:jboss-logging:jar:3.1.3.GA (compile), mysql-connector-java:mysql-connector-java:jar:bin:5.1.31 (compile)]
at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies(LifecycleDependencyResolver.java:210)
at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies(LifecycleDependencyResolver.java:117)
at org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved(MojoExecutor.java:258)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:201)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.apache.maven.project.DependencyResolutionException: Could not resolve dependencies for project com.bala.exercises.hibernate:hibernate:jar:0.0.1-SNAPSHOT: Failed to collect dependencies for [junit:junit:jar:3.8.1 (test), com.fasterxml:classmate:jar:1.0.0 (compile), dom4j:dom4j:jar:1.6.1 (compile), hibernate-core:hibernate-core:jar:4.3.5.Final (compile), hibernate-commons-annotations:hibernate-commons-annotations:jar:4.0.4.Final (compile), hibernate-jpa:hibernate-jpa:jar:1.0.0.Final:2.1-api (compile), org.jboss:jandex:jar:1.1.0.Final (compile), org.javassist:javassist:jar:3.18.1-GA (compile), org.jboss.logging:jboss-logging:jar:3.1.3.GA (compile), mysql-connector-java:mysql-connector-java:jar:bin:5.1.31 (compile)]
at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve(DefaultProjectDependenciesResolver.java:158)
at org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies(LifecycleDependencyResolver.java:185)
... 22 more
Caused by: org.sonatype.aether.collection.DependencyCollectionException: Failed to collect dependencies for [junit:junit:jar:3.8.1 (test), com.fasterxml:classmate:jar:1.0.0 (compile), dom4j:dom4j:jar:1.6.1 (compile), hibernate-core:hibernate-core:jar:4.3.5.Final (compile), hibernate-commons-annotations:hibernate-commons-annotations:jar:4.0.4.Final (compile), hibernate-jpa:hibernate-jpa:jar:1.0.0.Final:2.1-api (compile), org.jboss:jandex:jar:1.1.0.Final (compile), org.javassist:javassist:jar:3.18.1-GA (compile), org.jboss.logging:jboss-logging:jar:3.1.3.GA (compile), mysql-connector-java:mysql-connector-java:jar:bin:5.1.31 (compile)]
at org.sonatype.aether.impl.internal.DefaultDependencyCollector.collectDependencies(DefaultDependencyCollector.java:258)
at org.sonatype.aether.impl.internal.DefaultRepositorySystem.collectDependencies(DefaultRepositorySystem.java:308)
at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve(DefaultProjectDependenciesResolver.java:150)
... 23 more
Caused by: org.sonatype.aether.resolution.ArtifactDescriptorException: Failed to read artifact descriptor for hibernate-core:hibernate-core:jar:4.3.5.Final
at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom(DefaultArtifactDescriptorReader.java:296)
at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.readArtifactDescriptor(DefaultArtifactDescriptorReader.java:186)
at org.sonatype.aether.impl.internal.DefaultDependencyCollector.process(DefaultDependencyCollector.java:412)
at org.sonatype.aether.impl.internal.DefaultDependencyCollector.collectDependencies(DefaultDependencyCollector.java:240)
... 25 more
Caused by: org.sonatype.aether.resolution.ArtifactResolutionException: Could not transfer artifact hibernate-core:hibernate-core:pom:4.3.5.Final from/to balahome server (http://localhost:8080/artifactory/ bala-libs-mandatories): Illegal character in path at index 34: http://localhost:8080/artifactory/ bachan-libs-mandatories/hibernate-core/hibernate-core/4.3.5.Final/hibernate-core-4.3.5.Final.pom
at org.sonatype.aether.impl.internal.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:538)
at org.sonatype.aether.impl.internal.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:216)
at org.sonatype.aether.impl.internal.DefaultArtifactResolver.resolveArtifact(DefaultArtifactResolver.java:193)
at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom(DefaultArtifactDescriptorReader.java:281)
... 28 more
Caused by: org.sonatype.aether.transfer.ArtifactTransferException: Could not transfer artifact hibernate-core:hibernate-core:pom:4.3.5.Final from/to balahome server (http://localhost:8080/artifactory/ bala-libs-mandatories): Illegal character in path at index 34: http://localhost:8080/artifactory/ bachan-libs-mandatories/hibernate-core/hibernate-core/4.3.5.Final/hibernate-core-4.3.5.Final.pom
at org.sonatype.aether.connector.async.AsyncRepositoryConnector$3.wrap(AsyncRepositoryConnector.java:1546)
at org.sonatype.aether.connector.async.AsyncRepositoryConnector$3.wrap(AsyncRepositoryConnector.java:1537)
at org.sonatype.aether.connector.async.AsyncRepositoryConnector$GetTask.flush(AsyncRepositoryConnector.java:1035)
at org.sonatype.aether.connector.async.AsyncRepositoryConnector.get(AsyncRepositoryConnector.java:409)
at org.sonatype.aether.impl.internal.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:457)
... 31 more
Caused by: java.lang.IllegalArgumentException: Illegal character in path at index 34: http://localhost:8080/artifactory/ bachan-libs-mandatories/hibernate-core/hibernate-core/4.3.5.Final/hibernate-core-4.3.5.Final.pom
at java.net.URI.create(Unknown Source)
at com.ning.http.client.RequestBuilderBase.buildUrl(RequestBuilderBase.java:299)
at com.ning.http.client.RequestBuilderBase.setUrl(RequestBuilderBase.java:294)
at com.ning.http.client.AsyncHttpClient$BoundRequestBuilder.setUrl(AsyncHttpClient.java:333)
at com.ning.http.client.AsyncHttpClient.requestBuilder(AsyncHttpClient.java:560)
at com.ning.http.client.AsyncHttpClient.prepareGet(AsyncHttpClient.java:405)
at org.sonatype.aether.connector.async.AsyncRepositoryConnector$GetTask.run(AsyncRepositoryConnector.java:596)
at org.sonatype.aether.connector.async.AsyncRepositoryConnector.get(AsyncRepositoryConnector.java:402)
... 32 more
Caused by: java.net.URISyntaxException: Illegal character in path at index 34: http://localhost:8080/artifactory/ bachan-libs-mandatories/hibernate-core/hibernate-core/4.3.5.Final/hibernate-core-4.3.5.Final.pom
at java.net.URI$Parser.fail(Unknown Source)
at java.net.URI$Parser.checkChars(Unknown Source)
at java.net.URI$Parser.parseHierarchical(Unknown Source)
at java.net.URI$Parser.parse(Unknown Source)
at java.net.URI.<init>(Unknown Source)
... 40 more
I downloaded and deployed the respective pom files yet no luck. More over unless I exit eclipse I cannot clean the .m2 repository in windows 8.1.
Thanks.
A:
When you have a heavily nested stack trace like this, it is helpful to remember that the original cause is at the bottom (The rest is context which may in some cases be useful). In this case it is
java.net.URISyntaxException: Illegal character in path at index 34: http://localhost:8080/artifactory/ bachan-libs-mandatories/hibernate-core/hibernate-core/4.3.5.Final/hibernate-core-4.3.5.Final.pom
Then it is easy to see that you have a space in the path http://localhost:8080/artifactory/ bala-libs-mandatories. If it is a typo delete it, otherwise encode it as %20.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should non-numerical MPI questions go here or Stack Overflow?
Should general questions on MPI go here or Stack Overflow? An example of such a question is
http://scicomp.stackexchange.com/questions/2876/nonblocking-version-of-mpi-barrier-in-mpi-2
A:
Noting my obvious bias as a SciComp mod, I'd prefer that the MPI questions go here. I believe that questions on MPI would be on-topic in both places. Due to the widespread usage of MPI in computational science, I think most MPI questions would be on-topic here. (I hesitate to say "all," because you never know...)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to remove touchevent in js?
I'm trying to remove touchevent after the first touch.
I've tried the next code, but it did not work:
ourCanvas.addEventListener("touchstart", function(){
evt.preventDefault();
startGame();
ourGameCanvas.removeEventListener("touchstart");
}, false);`
A:
You need to pass a reference to the original function to removeEventListener:
ourCanvas.addEventListener("touchstart", function funcref(evt) {
evt.preventDefault();
startGame();
ourCanvas.removeEventListener("touchstart", funcref, false);
}, false);
In the previous code, I turned the anonymous function expression in a named function expression (funcref) so that it can be used later within the function.
And I renamed ourGameCanvas to ourCanvas. An event listener can only be removed if the element, event name, function reference and useCapture flag are identical to the ones used by addEventListener.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to remove dynamically assigned major number from /proc/devices?
In my kernel driver project I register with a dynamic major number by calling
register_chrdev(0, "xxxxx", &xxxxx);
and unregistered my module with
unregister_chrdev(0. "xxxxx");
When I load my driver with insmod, I received dynamic major number, for example 243, and, after rmmod, success removing module.
But, after removing the module /proc/devices still shows the major number (243).
How do I get removing my driver to also remove its major number from the list in /proc/devices?
A:
When you call register_chrdev() with 0 as the first argument to request the assignment of a dynamic major number, the return value will be the assigned major number, which you should save.
Then when you call unregister_chrdev() you should pass the saved major number as an argument, rather than the 0 you were. Also make sure that the device name argument matches. And be aware that this function returns a result, which you can check for status/failure - in the latter case you definitely want to printk() a message so that you know that your code has not accomplished its goal.
You can see a complete example at http://www.tldp.org/LDP/lkmpg/2.6/html/x569.html with the key parts being:
static int Major; /* Major number assigned to our device driver */
int init_module(void)
{
Major = register_chrdev(0, DEVICE_NAME, &fops);
if (Major < 0) {
printk(KERN_ALERT "Registering char device failed with %d\n", Major);
return Major;
}
return SUCCESS;
}
void cleanup_module(void)
{
int ret = unregister_chrdev(Major, DEVICE_NAME);
if (ret < 0)
printk(KERN_ALERT "Error in unregister_chrdev: %d\n", ret);
}
Also be aware that this method of registering a device is considered outdated - you might want to research the newer method.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Replacing elements in a list of lists
The apply functions in R are a nice way to simplify for loops to get to an output. Is there an equivalent function that helps one avoid for loops when replacing the values of a vector? This is better understood by example...
# Take this list for example
x = list( list(a=1,b=2), list(a=3,b=4), list(a=5,b=6) )
# To get all of the "a" elements from each list, I can do
vapply(x,"[[",1,"a")
[1] 1 3 5
# If I want to change all of the "a" elements, I cannot do
vapply(x,"[[",1,"a") = 10:12
Error in vapply(x, "[[", 1, "a") = 10:12 :
could not find function "vapply<-"
# (this error was expected)
# Instead I must do something like this...
new.a = 10:12
for(i in seq_along(x)) x[[i]]$a = new.a[i]
Is there a simpler or faster alternative to using a loop?
A:
One option would be to first unlist the list x, then replace the values named "a", and then relist the new list u based on the list structure of x.
u <- unlist(x)
u[names(u) == "a"] <- 10:12
relist(u, x)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Concatenating two numpy array issues
I have two numpy arrays of shape
(129873, 12)
(129873,)
I would like to concatenate these so they are in the shape of:
(129873, 13)
I have tried numpy.concatenate and numpy.vstack but seem to be getting errors:
ValueError: all the input arrays must have same number of dimensions
Any suggestions on how to do this?
A:
So one array has 2 dimensions, the other 1:
(129873, 12)
(129873,)
You need to change the 2nd to have shape (129873,1). Then you can concatenate on axis 1.
There are a number of way of do this. The [:,None] or np.newaxis indexing is my favorite:
In [648]: A=np.ones((3,4),int)
In [649]: B=np.ones((3,),int)
In [650]: B[:,None].shape
Out[650]: (3, 1)
In [651]: np.concatenate((A,B[:,None]),axis=1).shape
Out[651]: (3, 5)
B.reshape(-1,1) also works. Also np.atleast_2d(B).T and np.expand_dims(B,1).
np.column_stack((A,B)) uses np.array(arr, copy=False, subok=True, ndmin=2).T to ensure each array has the right number of dimensions.
While there are friendly covers to concatenate like column_stack, it's important to know how to change dimensions directly.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL Syntax wrong Select Where Like
My phpmyadmin gives me the following error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '17, COL 19, COL 21, COL 23
FROM `table 1`
WHERE (COL 7
LIKE '%13%' OR COL ' at line 1
When I try to call like this:
SELECT COL 17, COL 19, COL 21, COL 23
FROM `table 1`
WHERE (COL 7
LIKE '%13%' OR COL 1
LIKE '%13%' OR COL 2
LIKE '%13%' OR COLE 3
LIKE '%13%')
I tried several options but did not work I probably oversee something but cannot find it.
A:
Try putting the column names, which appear to have spaces in them, in single backticks:
SELECT `COL 17`, `COL 19`, `COL 21`, `COL 23`
FROM `table 1`
WHERE (`COL 7` LIKE '%13%' OR `COL 1` LIKE '%13%' OR `COL 2` LIKE '%13%'
OR `COL 3` LIKE '%13%')
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Created RuntimeTypeModel fails during deserialization complex object
I wanted to use protocolbuf .net version without attributes, with RuntimeTypeModel created via specific code. It worked pretty good till I hit the case, which was extracted in the case below. The referenced protobuf-net library's version is 2.0.0.447. What's wrong with this model's creation? Any clues?
public class ProtoBufFailingTest
{
public abstract class Message
{
}
public class SomeMessage : Message
{
public readonly Descriptor Desc;
public SomeMessage(Descriptor desc)
{
Desc = desc;
}
}
public struct Descriptor
{
public readonly Event EventData;
public Descriptor(Event eventData)
{
EventData = eventData;
}
}
public abstract class Event
{
}
public class SomeEvent : Event
{
public int SomeField;
}
[Test]
public void FailingTest( )
{
var model = TypeModel.Create();
// message hierarchy
{
var messages = model.Add(typeof(Message), true);
messages.AddSubType(1, typeof(SomeMessage));
model[typeof(SomeMessage)].UseConstructor = false;
}
// events hierarchy
{
var events = model.Add(typeof (Event), true);
events.AddSubType(1, typeof (SomeEvent));
model[typeof (SomeEvent)].UseConstructor = false;
}
// descriptor
var eventDescriptorModel = model.Add(typeof(Descriptor), true);
eventDescriptorModel.UseConstructor = false;
var typeModel = model.Compile();
const PrefixStyle prefixStyle = PrefixStyle.Base128;
const int testValue = 5;
using (var ms = new MemoryStream())
{
typeModel.SerializeWithLengthPrefix(ms, new SomeMessage(new Descriptor(new SomeEvent { SomeField = testValue })), null, prefixStyle, 0);
ms.Seek(0, SeekOrigin.Begin);
// fails here
var message = (SomeMessage)typeModel.DeserializeWithLengthPrefix(ms, null, typeof(Message), prefixStyle, 0);
Assert.AreEqual(testValue, ((SomeEvent)message.Desc.EventData).SomeField);
}
}
}
A:
Very simply; the library has (had) a bug, emitting
initobj {type}
stloc.0
when obviously (cough) for a value-type Descriptor it should have been emitting
ldloca.s 0
initobj {type}
I'll get this deployed as soon as I've checked I haven't destabilised anything.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to select these IP addresses in notepad ++
I have these IP addresses in a text file:
123.456.789.987 | 0x (8B -> 0B) |N/A
756.789.412.478 | 0x (8B -> 0B) |N/A
321.745.748.415 | 0x (8B -> 0B) |N/A
14.48.210.33 | 6x (8B -> 48B) |N/A
42.117.63.132 | 6x (8B -> 48B) |N/A
2.6.133.228 | 6x (8B -> 48B) |N/A
I only need to select all IP addresses with 123.456.789.987 | 0x (8B -> 0B) |N/A
I need the complete line, to remplace with a blank line, leaving the IPaddresses in this way:
14.48.210.33 | 6x (8B -> 48B) |N/A
42.117.63.132 | 6x (8B -> 48B) |N/A
2.6.133.228 | 6x (8B -> 48B) |N/A
A:
Not sure about IP to be kept, but this produces your expected result:
Ctrl+H
Find what: ^.+0x\h+\(8B\h+->\h+0B\).+\R
Replace with: LEAVE EMPTY
UNcheck Match case
check Wrap around
check Regular expression
DO NOT CHECK . matches newline
Replace all
Explanation:
^ # beginning of line
.+ # 1 or more any character
0x # literally 0x
\h+ # 1 or more horizontal spaces
\( # opening parenthese
8B # literally 8B
\h+ # 1 or more horizontal spaces
-> # literally ->
\h+ # 1 or more horizontal spaces
0B # literally 0B
\) # closing parenthese
.+ # 1 or more any character
\R # any kind of linebreak (ie. \r, \n, \r\n)
Result for given example:
14.48.210.33 | 6x (8B -> 48B) |N/A
42.117.63.132 | 6x (8B -> 48B) |N/A
2.6.133.228 | 6x (8B -> 48B) |N/A
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Retrieving dll version info via Win32 - VerQueryValue(...) crashes under Win7 x64
The respected open source .NET wrapper implementation (SharpBITS) of Windows BITS services fails identifying the underlying BITS version under Win7 x64.
Here is the source code that fails. NativeMethods are native Win32 calls wrapped by .NET methods and decorated via DllImport attribute.
private static BitsVersion GetBitsVersion()
{
try
{
string fileName = Path.Combine(
System.Environment.SystemDirectory, "qmgr.dll");
int handle = 0;
int size = NativeMethods.GetFileVersionInfoSize(fileName,
out handle);
if (size == 0) return BitsVersion.Bits0_0;
byte[] buffer = new byte[size];
if (!NativeMethods.GetFileVersionInfo(fileName,
handle,
size,
buffer))
{
return BitsVersion.Bits0_0;
}
IntPtr subBlock = IntPtr.Zero;
uint len = 0;
if (!NativeMethods.VerQueryValue(buffer,
@"\VarFileInfo\Translation",
out subBlock,
out len))
{
return BitsVersion.Bits0_0;
}
int block1 = Marshal.ReadInt16(subBlock);
int block2 = Marshal.ReadInt16((IntPtr)((int)subBlock + 2 ));
string spv = string.Format(
@"\StringFileInfo\{0:X4}{1:X4}\ProductVersion",
block1,
block2);
string versionInfo;
if (!NativeMethods.VerQueryValue(buffer,
spv,
out versionInfo,
out len))
{
return BitsVersion.Bits0_0;
}
...
The implementation follows the MSDN instructions by the letter. Still during the second VerQueryValue(...) call, the application crashes and kills the debug session without hesitation.
Just a little more debug info right before the crash:
spv =>
"\StringFileInfo\040904B0\ProductVersion"
buffer => byte[1900] - full with binary data
block1 => 1033
block2 => 1200
I looked at the targeted "C:\Windows\System32\qmgr.dll" file (The implementation of BITS) via Windows. It says that the Product Version is 7.5.7600.16385. Instead of crashing, this value should return in the verionInfo string. Any advice?
A:
The answer of Nobugz does point out a very valid issue (big thanx for that!), but the final killer was a .NET bug: marshaling strings in this scenario fails under the x64 .NET implementation. The bug is fixed in .NET4.0. Here is the issue reported, as well as Microsoft's answer.
The recommended workaround is retrieve an IntPtr instead of the string as output and marshaling the string manually. So the final code (including the fix of Nobugz):
int block1 = Marshal.ReadInt16(subBlock);
int block2 = Marshal.ReadInt16(subBlock, 2);
string spv = string.Format(@"\StringFileInfo\{0:X4}{1:X4}\ProductVersion",
block1, block2);
IntPtr versionInfoPtr;
if (!NativeMethods.VerQueryValue(buffer, spv, out versionInfoPtr, out len))
{
return BitsVersion.Bits0_0;
}
string versionInfo = Marshal.PtrToStringAuto(versionInfoPtr);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Storing permanent value in Form while in validation handler
We can store a permanent value in $form_state in the submission handler, which will be retained against form errors, but I want to know how we can do it while in the validation handler, where I show an error using form_set_error().
In short, I want to show an error in validation with the message "Press submit again to confirm". In this way, if the same form is submitted again it would skip the validation handler.
I can't do it in the submission handler, since it clears the values in the form.
form_set_value() is not able to retain a value.
EDIT (on 28th Dec)
I've found that $form_state['storage'] is works in validator also only if form_state['rebuild] is set to true. Infact this is how we use in submit handler. And if I call form_set_error in the validator form_state['rebuild] is simply ignored even if it is set and the storage value is not retained.
A:
$form_state['storage'] is probably what you're looking for. I've used it on multi-step forms myself to preserve necessary data that I need during various stages of the form processing. As an example you can define a storage variable like this:
$form_state['storage']['mykey'] = 'myval';
Edit:
Considering the additional information you provided it is indeed not quite as simple in your specific case. Setting $form_state['rebuild'] = TRUE; in the form validation handler also means that the user set form values will be lost. So what I think you could do is the following:
In the form validation handler function:
if (!isset($form_state['storage']['mykey'])) {
$form_state['storage']['mykey'] = 'myval';
// Save all the user set form values.
foreach ($form_state['values'] as $key => $val) {
// If you want to skip some values do it here.
$form_state['storage']['values'][$key] = $val;
}
$form_state['rebuild'] = TRUE;
drupal_set_message('Press submit again to confirm');
}
In your form builder function use the stored values as defaults. Example:
$form['key_1'] = array(
'#type' => 'radios',
'#title' => t('Title'),
'#options' => array(0,1,2),
'#default_value' => $form_state['storage']['values']['key_1'],
);
Not sure how well the example code fits your needs, but it should get you started or at least give further ideas/options to try out.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
FirebaseAnalytics is missing several parameter constants
I would like to pass along an array of bundles to FirebaseAnalytics as described here but FirebaseAnalytics.Param does not contain an ITEMS value. In fact, it only seems to contain a subset of the values it should contain as shown here:
I have firebaseanalytics version 17.4.4 and I tried to fill in the Param.ITEMS constant value myself ("items" according to the docs) but DebugView shows a firebase error (20 - Event array parameter name is invalid). All other events and parameters seem to work just fine according to DebugView and I found nobody with similar problems. Does anyone have any ideas as to why I only see a subset of the parameters?
A:
Make sure you perform a Gradle sync, as FirebaseAnalytics.Param.ITEMS is definitely available in v17.4.4.
Here it is in my project, note the version number in the bottom right:
If you're still having trouble, mouseover one of the options in your dropdown and it should show you the version being used.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Download multiple FTP files like d*.txt in ruby
I need to connect to a ftp site and download a bunch of files( max 6) named as D*.txt.
could you please help me code this in Ruby ?
The following code just
ftp = Net::FTP::new("ftp_server_site")
ftp.login("user", "pwd")
ftp.chdir("/RemoteDir")
fileList= ftp.nlst
ftp.getbinaryfile(edi, edi)
ftp.close
Thanks
A:
The simplest way would be to loop through the list of files in fileList.
Here is an example (untested):
ftp = Net::FTP::new("ftp_server_site")
ftp.login("user", "pwd")
ftp.chdir("/RemoteDir")
fileList = ftp.list('D*.txt')
fileList.each do |file|
ftp.gettextfile(file)
end
ftp.close
Hope this helps.
A:
Array of filenames in dir you can get by "nlst" method:
files = ftp.nlst('*.zip')
files.each do |file|
puts file
end
#=> first.zip, second.zip, third.zip, ...
A:
That solution did not work for me, although it may depend on the FTP server. For me, ftp.list returns results similar to ls -l on Linux. I used the following regex to get just the filename of the first file returned by list:
ftp.list('D*.txt')[0][/.*(\d{2}):(\d{2})\s{1}(?<file>.+)$/,1]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
IPA vs just LDAP for Linux boxes - looking for a comparison
There are few (~30) Linux (RHEL) boxes and I'm looking for centralized and easy managed solution, mostly for control user accounts. I'm familiar with LDAP, and I deployed a pilot of IPA ver2 from Red Hat (==FreeIPA).
I understand that in theory IPA provides "MS Windows domain"-like solution, but at a glance it's not so easy and mature product [yet]. Aside with SSO, is there any security features which are available only in IPA domain and not available when I'm using LDAP?
I'm not interesting in DNS and NTP parts of IPA domain.
A:
First of all, I would say IPA is perfectly suited for a production environment as of now (and has been for quite a time), although you should be using the 3.x series by now.
IPA does not provide a "MS Windows AD-like" solution, rather it provides the capability to setup a trust relationship between an Active Directory and a IPA domain, which is a Kerberos REALM, actually.
With regards to some of the security features that you can use out of the box with IPA not present in a standard LDAP installation, or a LDAP-based Kerberos REALM, let's name a few:
storing SSH keys for users
SELinux mappings
HBAC rules
sudo rules
setting password policies
certificate (X509) handling
Related to SSO, keep in mind that the target application must support Kerberos authentication and LDAP authorization. Or be able to talk to SSSD.
Lastly, you don't need to configure NTP nor DNS if you don't want to, both are optional. However, I'd very much recommend using both, as you can always delegate NTP on a higher stratum, and setup forwarders for anything outside your realm easily.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to list audio card IDs from terminal
I am developing a script which deals with sound recording.
As user potentially can have multiple sound cards attached, I would like to give him/her a chance to select desired one. The software I use for actual recording asks for numeric "Device ID".
Is there any way to retreive list of Device IDs along with soundcards' names from command line (terminal)?
A:
system_profiler is the tool in mac OS to show hw or sw configuraion.
Get the datatye you want to look for using --listDataTypes.
$ system_profiler -listDataTypes | grep Audio
SPAudioDataType
Then fire the command,
$ system_profiler SPAudioDataType
Audio:
Intel High Definition Audio:
Audio ID: 128
Headphone:
Connection: Combination Output
Speaker:
Connection: Internal
External Microphone / iPhone Headset:
Connection: Combination Output
Internal Microphone:
Connection: Internal
S/PDIF Optical Digital Audio Output:
Connection: Combination Output
HDMI / DisplayPort Output:
Connection: Display
Devices:
Built-in Microphone:
Default Input Device: Yes
Input Channels: 2
Manufacturer: Apple Inc.
Current SampleRate: 44100
Transport: Built-in
Built-in Output:
Default Output Device: Yes
Default System Output Device: Yes
Manufacturer: Apple Inc.
Output Channels: 2
Current SampleRate: 44100
Transport: Built-in
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Set select list to current date and next day with leading zeros
I've got a problem passing off date information to another site because they still require two digit dates even for the first nine days of the month. I've gotten 90% of the way using the code from the SO page for set select list to current date using Jquery. That moves the months and days from 1-31 and 1-12. I need the output to be from 01-31 and 01-12.
The current situation:
function ragequit() {
var today = new Date();
var daym = today.getDate();
var monthm = today.getMonth();
$('#StartMonth option[value=' + (monthm) + ']').prop('selected',true);
$('#StartDay option[value=' + (daym) + ']').prop('selected',true);
$('#EndMonth option[value=' + (monthm+1) + ']').prop('selected',true);
$('#EndDay option[value=' + (daym+1) + ']').prop('selected',true);
}
It is calling the month perfectly because this is December. Also had to add m to each of the values so that it doesn't compete with another tool that increments the date when the start date is changed.
Simply put, I have 12 7 2011 - I need 12 07 2011.
A:
What you need is a function to pad a string with leading zeros, like this:
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
Then you can use this to add leading zeros to your dates:
function ragequit() {
var today = new Date();
var daym = today.getDate();
var monthm = today.getMonth();
$('#StartMonth option[value=' + pad(monthm,2) + ']').prop('selected',true);
$('#StartDay option[value=' + pad(daym,2) + ']').prop('selected',true);
$('#EndMonth option[value=' + pad(monthm+1,2) + ']').prop('selected',true);
$('#EndDay option[value=' + pad(daym+1,2) + ']').prop('selected',true);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unable to get provider com.crashlytics.android.CrashlyticsInitProvider
After implementation 'com.google.firebase:firebase-core:16.0.1' and classpath 'com.google.gms:google-services:4.0.1'
I started getting the following error when starting the application:
FATAL EXCEPTION: main
Process: com.fentury.android, PID: 10771
java.lang.RuntimeException: Unable to get provider com.crashlytics.android.CrashlyticsInitProvider: io.fabric.sdk.android.services.concurrency.UnmetDependencyException: This app relies on Crashlytics. Please sign up for access at https://fabric.io/sign_up,
install an Android build tool and ask a team member to invite you to this app's organization.
at android.app.ActivityThread.installProvider(ActivityThread.java:5856)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:5445)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5384)
at android.app.ActivityThread.-wrap2(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: io.fabric.sdk.android.services.concurrency.UnmetDependencyException: This app relies on Crashlytics. Please sign up for access at https://fabric.io/sign_up,
install an Android build tool and ask a team member to invite you to this app's organization.
at com.crashlytics.android.core.CrashlyticsCore.onPreExecute(CrashlyticsCore.java:235)
at com.crashlytics.android.core.CrashlyticsCore.onPreExecute(CrashlyticsCore.java:209)
at io.fabric.sdk.android.InitializationTask.onPreExecute(InitializationTask.java:44)
at io.fabric.sdk.android.services.concurrency.AsyncTask.executeOnExecutor(AsyncTask.java:611)
at io.fabric.sdk.android.services.concurrency.PriorityAsyncTask.executeOnExecutor(PriorityAsyncTask.java:43)
at io.fabric.sdk.android.Kit.initialize(Kit.java:69)
at io.fabric.sdk.android.Fabric.initializeKits(Fabric.java:440)
at io.fabric.sdk.android.Fabric.init(Fabric.java:384)
at io.fabric.sdk.android.Fabric.setFabric(Fabric.java:342)
at io.fabric.sdk.android.Fabric.with(Fabric.java:313)
at com.crashlytics.android.CrashlyticsInitProvider.onCreate(CrashlyticsInitProvider.java:27)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
at android.app.ActivityThread.installProvider(ActivityThread.java:5853)
... 10 more
Also added in AndroidManifest.xml next line:
<meta-data android:name="firebase_crash_collection_enabled" android:value="false" />
A:
This helped to solve my problem
<meta-data
android:name="firebase_crashlytics_collection_enabled"
android:value="false" />
And remove this:
<meta-data android:name="firebase_crash_collection_enabled" android:value="false" />
A:
I found that the only thing you need to do after following the instruction on the Firebase Crashlytics docs is to apply the fabric plugin in your app build file (This step is actually missing from the docs!).
In your app-level build.gradle add the following
// Apply the Fabric plugin
apply plugin: 'io.fabric'
Edit: It appears that this step has been recently added to the docs (See Step 2 / part 2).
A:
If you are going to use other Firebase's API's, I'd suggest to setup crashlytics
As mentioned on Firebase's crashlytics page, here.
And obviously before that you'd need to setup firebase for your app
and create project through firebase console.
I believe you had already done that.
It's because I see small difference in crashlytics setup on these two pages(fabric and firebase).
like on firebase's crashlytics:
in app level gradle
dependencies {
// ...
implementation 'com.crashlytics.sdk.android:crashlytics:2.9.3'
}
on fabric:
dependencies {
// ...
implementation('com.crashlytics.sdk.android:crashlytics:2.9.4@aar') {
transitive = true;
}
}
You won't need to add fabric api key through manifest if you are using with firebase, I think it somehow get connected with firebase key(just guessing).
I'm saying this from my experience, anyone correct me if I'm somewhere wrong.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cezve doesn't leak with cold water in it, leaks after heating
I have a cezve I bought some time ago. I've tried making some coffee with it, and after about 30 seconds of heating on the stove, it starts to leak (dripping one by one). Is there any way to fix this, or does it have to be thrown away ?
A:
You would have to find the crack (presumably there is a crack which is tight when cold, but opens with heating due to thermal expansion) and then you would need to fix it, or have someone else fix it, with a food safe (lead and cadmium free) solder or brazing material. Whether this is economical or not depends on many factors:
Can you do it yourself, do you know somone who can, or will you need to hire a professional
Are professionals who do "pot and pan repair" easily found in your area or not?
How much does a new coffeepot (cezve) cost relative to the cost of getting it fixed?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why bind function stop working in this case for NodeJS
Why bind function stops working for the following code?
function exitHandler(options, err) {
console.log('exit');
if (options.cleanup) console.log('clean');
if (err) console.log(err.stack);
if (options.exit) process.exit();
}
//do something when app is closing
//process.on('exit', exitHandler.bind(null,{cleanup:true})); process.exit()
// or
process.on('exit', function() {
exitHandler.bind(null,{cleanup:true})
});
If I un-comment the process.on('exit', exitHandler.bind... line, it'd work fine.
A:
I think it's because the bind creates a new function so in your second example it does not actually fire the function. In the first case it does get fired.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to send ATR to card
I have some card, wanted to get ATR from it (using method from some SDK).
Implementation looks like this:
unsigned char ATR[128]={0};
int len=33;
int maxlen=33;
ret = sd7816_ATR(0,1,ATR,len,maxlen,1);
first, second and last parameters to sd7816_ATR function should be like that.
The length fields I tried changing to different values, including 0 but no help.
My concern is the ATR string I am sending is empty in the beginning, and I am expecting
something to get written in it after the call finishes (which actually returns success).
But after call ATR is still empty .. What can be going wrong here?
(I want to find out if card is of ISO/IEC 14443 or ISO/IEC 7816 type).
A:
You are trying to receive an ATR for a command specific for a ISO/IEC 7816-3 contact card. In this particular case, that's requested from a (SIM form) SAM card reader. However, you are trying to read out the contactless based reader.
Now contactless cards do not have an ATR. Some cards do have an ATS (i.e. ISO/IEC 14443 Type A cards), but that should be requested by a similar 14443 SELECT command. Some cards, particularly Type B cards, contain an EF.ATR to make up for the lack of (space within the) ATR. Still, an ATR/ATS has only limited functionality for identifying cards.
ISO/IEC 7816 is comprised of several parts: parts 1 to 3 describe contact cards and 4 and higher describe the Application level APDU commands and file structure of processor cards. If your contactless card implements ISO/IEC 7816-4 then you can - in general - also directly use the PCSC interface to send and receive APDU's to/from the card.
In general readers are for contact or contactless only. If you have a reader which contains both contact and contactless operation then in general they will show up as two different readers in the operating system. So in general, if you know the reader, you know if the card is a contact card or contactless card.
SAM slots may not be identified as readers by the operating system - you may only be able to access them using a low level interface. They are mainly used as a secure storage of keys from the terminal/inspection system/interface device or whatever the name is of the system that reads out the card.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CodeIgniter and utf8 functions
My site needs to support multiple languages so it needs to handle utf8 data throughout the site. I understand how to configure codeigniter for utf8 data with regards to interacting with the database. My question is how does codeigniter handle things like rules for form fields when using utf8 encoding? For instance using strlen, for utf8 the strlen would be different and so you would need to use the mbstring function for that instead, mb_strlen. Does codeigniter have a setup that automatically handles that or is there something I need to configure inside codeigniter to do that?
A:
It does use mb_strlen by default if it is accessible:
//below default min_length function of CI_Form_Validation lib as an example
/**
* Minimum Length
*
* @access public
* @param string
* @param value
* @return bool
*/
function min_length($str, $val)
{
if (preg_match("/[^0-9]/", $val))
{
return FALSE;
}
if (function_exists('mb_strlen'))
{
return (mb_strlen($str) < $val) ? FALSE : TRUE;
}
return (strlen($str) < $val) ? FALSE : TRUE;
}
For preg_match functions use unicode modifier:
// native CI alpha function:
function alpha($str)
{
return ( ! preg_match("/^([a-z])+$/i", $str)) ? FALSE : TRUE;
}
// ready for unicode using u modifier in regex pattern
function alpha($str)
{
return ( ! preg_match("/^([a-z])+$/iu", $str)) ? FALSE : TRUE;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to format app properly on an ipad from an iphone app in xcode?
I've written an app in Xcode and I set it for iPhone, but now I want to make the app available for iPad. I don't want to go through the trouble of making it universal, is there a way I can run this iPhone app on my iPad correctly formatted?
A:
You can just set the target Device to iPad and run it. See below. Your UI may or may not look good depending on if you properly used either AutoLayout or Springs and Struts.
The iPad is a very different canvas for a UI than the iPhone and there is no definition of what "correctly formatted" really means when going from one to the other. It's a subjective matter and a computer is not going to decide if it looks good for you. As such, you may not get what you are looking for.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Programmatically Blurring combobox control in EXTJS 3.2.1 does not fire 'blur' event
I am trying to implement a Confirmation Dialog box when the user closes a tab w/o saving.
To do this, I am using the component's (textfield, checkbox, combobox, etc.) 'change' event. However, since the 'change' event requires the field to blur, there is an issue if they the user changes a field but does not lose focus of the field BEFORE closing the tab.
To remedy this, I use the tab's 'beforeclose' event to programmatically blur() the active element, and hence fire the 'change' event if the field has changed:
listeners: {
beforeclose: function(form) {
var focusedEl = Ext.getCmp(document.activeElement.id);
focusedEl.blur();
if(tabRC.F('AgentCaseForm').dirty.items.length > 0) {
return(confirm('There are unsaved changes on this tab. Are you sure you want to close?'));
}
}
}
This approach works for all controls (textfield, textarea, checkbox, datefield) EXCEPT for the combobox. The field blurs, but the 'blur' event does not fire and therefore the 'change' event does not fire. Is there a reason for this that I am missing? Thank you very much!
EDIT: I have tried programmatically firing the 'blur' event, but the 'change' event still does not fire.
focusedEl.fireEvent('blur');
EDIT 2: The solution was to do this:
var focusedEl = Ext.getCmp(document.activeElement.id);
if (focusedEl && focusedEl.isDirty()) {
focusedEl.fireEvent('change');
}
A:
Since Ext.form.ComboBox is extending Ext.form.TriggerField, you can trigger blur programatically by
focusedEl.triggerBlur();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
If a polynomial ring is a free module over some subring, is that subring itself a polynomial ring?
Suppose I have a graded polynomial ring $k[x_1,\ldots,x_n]$ on homogeneous generators, where $k$ is a field and the $x_i$ indeterminates, and further that I have a homogeneous graded subring $A$ such that
$k[x_1,\ldots,x_n]$ is made a free $A$-module by the inclusion,
$k[x_1,\ldots,x_n]$ is finite over $A$.
It follows, as pointed out in comments, that then $A$ contains another polynomial ring on $n$ variables.
I'd like this to imply $A$ is a polynomial ring too, but is it?
A:
The third bullet point is automatic by Noether Normalization. What you ask is certainly true if you assume that $A=A_0\oplus A_1\oplus A_2\oplus\cdots$ as a graded ring with $A_0=k$ and $A_1$ generates it. This follows from the fact that your assumptions imply $A$ is a regular ring and then if $A$ is of the form I wrote, $\dim_k A_1=n$ and the rest will follow.
The regularity of $A$ follows from your hypothesis even without gradedness assumption. I do not offhand know an example where $A$ is not a polynomial ring.
A:
The answer to my question is in the affirmative. I've now found two proofs. The result is apparently old and originally due to Macaulay.
One is on pp. 155 and 171 of Larry Smith's book Polynomial Invariants of Finite Groups. It uses some homological algebra to prove first that without the finiteness assumption, the polynomial ring is free over $A$ if and only if $A$ is a polynomial ring on a regular sequence of generators. More than this, finiteness of the polynomial ring over $A$ shows this sequence can have length no less than $n$, and regularity that it can have length no more than $n$. It is also shown that given a sequence $f_1,\ldots,f_n \in k[x_1,\ldots,x_n]$, it is regular if and only if the $f_i$ are algebraically independent and $k[x_1,\ldots,x_n]$ is a finite $k[f_1,\ldots,f_n]$-module.
The second is in Richard Kane's Reflection Groups and Invariant Theory. Starting on p. 195, he wants to show that if a polynomial ring $S(V)$ (symmetric algebra on a vector space $V$) is finite over $R = S(V)^G$ the invariants of some $G$-action by pseudo-reflections on $V$ and $S$ is a finite, free $R$-module, then $R$ is a polynomial algebra. He carries this through with a generators-and-relations level approach involving formal partial derivatives and Euler's theorem on homogeneous functions to leverage a hypothetical algebraic relation on the generators of $R$ into an $S$-linear and then an $R$-linear relation among these same generators and contradict minimality. But nothing in his approach uses anything other than that $S$ is a polynomial ring and there is some generator of $R$ of order relatively prime to the characteristic of $k$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to replace Swift substring with an Un-Equal substring by using location?
Can’t use occurrence of pattern as text can change at any instance.
var originalString = "Hi there <un>"
var stringToPut = "Some Amazing Name"
// Change string between 10th index and 13th to the following.
var requiredString = "Hi there <Some Amazing Name>"
This is very easy for just 1 character or when the length of the replacing string is same. But breaks when the substrings are unequal in length as the length of parent string changes and exact location references cannot be made.
A:
Hopefully this works.
let originalString = "Hi there <un>"
let subString = "Some Amazing Name"
let characters = Array(originalString)
let firstPart = characters[0..<9]
let lastPart = characters[13..<characters.count]
let finaString = ("\(String(firstPart))\(subString)\(String(lastPart))")
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Spring OAuth2 - CustomAuthenticationProvider login issue
I have setup an Authorization and Resource Server to be consumed by a web application (all done in Spring MVC 4.3.9), but have a problem with the requests done with OAuth2RestTemplate and a custom AuthenticationProvider set on the Authorization Server.
At first request (when the user logins), I set the username and password of the autowired OAuth2RestTemplate (I'm using password grant), and send the request to an URL of the API, like:
@Autowired
OAuth2RestOperations restTemplate;
..
public <T> T postEntityNoAuth(String restMethod, Credentials credentials, ParameterizedTypeReference<T> resultType) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// set your entity to send
HttpEntity entity = new HttpEntity(credentials, headers);
restTemplate.getOAuth2ClientContext().getAccessTokenRequest().set("username", credentials.getUsername());
restTemplate.getOAuth2ClientContext().getAccessTokenRequest().set("password", credentials.getPassword());
ResponseEntity<T> restResult = restTemplate.exchange(authServerURL + restMethod, HttpMethod.POST, entity,
resultType);
OAuth2AccessToken token = restTemplate.getAccessToken();
return restResult.getBody();
}
Everything is fine, I get an access token, because the authentication was successful, which was done in the auth server:
@Configuration
@EnableWebSecurity(debug = false)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
CustomAuthenticationProvider customAuthProvider;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthProvider);
}
//more code
The custom authentication provider validates against a LDAP search, as I don't have an UserDetailsService (I don't have permission to read user details from the LDAP server, only authenticate with user and pwd).
The thing is that after login, when I do other requests with the autowired OAuth2RestTemplate, the provider authenticate method is called again , and given that I don't have the credentials anymore (which in this case shouldn't be needed as I have an access token, and I checked that is the one assigned at login), it returns 401 Unauthorized.
The question is, how can I validate against the access token and user id, or how to skip the validation in the custom provider, given that I don't need to authenticate anymore? For the following requests, only the access token should be used, or am I missing something?
A:
So, I ended getting the access token from the OAuth2RestTemplate at first login, and then get the access token so I pass it as a parameter for a normal RestTemplate (as ?access_token=...). When the access token expires, the OAuth2RestTemplate gets another one automatically via the refresh token (for this, you have to set the grant "refresh_token" for the same client). If the refresh token expires, then is time to login again and the cycle repeats.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does PROC FCMP function always return 33 bytes and no more?
I have the following function defined via PROC FCMP. The point of the code should be pretty obvious and relatively straightforward. I'm returning the value of an attribute from a line of XHTML. Here's the code:
proc fcmp outlib=library.funcs.crawl;
function getAttr(htmline $, Attribute $) $;
/*-- Find the position of the match --*/
Pos = index( htmline , strip( Attribute )||"=" );
/*-- Now do something about it --*/
if pos > 0 then do;
Value = scan( substr( htmline, Pos + length( Attribute ) + 2), 1, '"');
end;
else Value = "";
return( Value);
endsub;
run;
No matter what I do with length or attrib statement to try to explicitly declare the data type returned, it ALWAYS returns only a max of 33 bytes of the requested string, regardless of how long the actual return value is. This happens no matter which attribute I am searching for. The same code (hard-coded) into a data step returns the correct results so this is related to PROC FCMP.
Here is the datastep I'm using to test it (where PageSource.html is any html file that has xhtml compliant attributes -- fully quoted):
data TEST;
length href $200;
infile "F:\PageSource.html";
input;
htmline = _INFILE_;
href = getAttr( htmline, "href");
x = length(href);
run;
UPDATE: This seems to work properly after upgrading to SAS9.2 - Release 2
A:
I think the problem (though I don't know why) is in the scan function - it seems to be truncating input from substr(). If you pull the substr function out of scan(), assign the result of the substr function to a new variable that you then pass to scan, it seems to work.
Here is what I ran:
proc fcmp outlib=work.funcs.crawl;
function getAttr(htmline $, Attribute $) $;
length y $200;
/*-- Find the position of the match --*/
Pos = index( htmline , strip( Attribute )||"=" );
/*-- Now do something about it --*/
if pos > 0 then do;
y=substr( htmline, Pos + length( Attribute ) + 2);
Value = scan( y, 1, '"');
end;
else Value = "";
return( Value);
endsub;
run;
options cmplib=work.funcs;
data TEST;
length href $200;
infile "PageSource.html";
input;
htmline = _INFILE_;
href = getAttr( htmline, "href");
x = length(href);
run;
A:
I ended up backing out of using FCMP defined data step functions. I don't think they're ready for primetime. Not only could I not solve the 33 byte return issue, but it started regularly crashing SAS.
So back to the good old (decades old) technology of macros. This works:
/*********************************/
/*= Macro to extract Attribute =*/
/*= from XHTML string =*/
/*********************************/
%macro getAttr( htmline, Attribute, NewVar );
if index( &htmline , strip( &Attribute )||"=" ) > 0 then do;
&NewVar = scan( substr( &htmline, index( &htmline , strip( &Attribute )||"=" ) + length( &Attribute ) + 2), 1, '"' );
end;
%mend;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Add link to Abort page
As a follow-up to this answer, I'm trying to add the link after issuing Abort command, but for some reason it does not appear, no trace of it when viewed in Spy++.
The idea is to add the link above the progress bar, but somehow the macro does not work. Is there a reason for this that I'm missing and is it possible to add that link after calling Abort? I've read somewhere that Abort command can have different effect so I'm guessing this is one of it.
I've tried to make this sample script as concise as best I can and would greatly appreciate any help as I'm still learning NSIS.
!include "MUI2.nsh"
;--------------------------------
;General
ShowInstDetails hide
SetCompressor /SOLID lzma
;Request application privileges for Windows Vista
RequestExecutionLevel user
;--------------------------------
;Interface Configuration
!define MUI_ABORTWARNING
!define MANUAL_DOWNLOAD_TEXT "Automatic download not working? Click here to download manually."
;--------------------------------
;Macros
!macro AddDownloadLink yCoord
FindWindow $0 "#32770" "" $HWNDPARENT ; Find the inner dialog
System::Call 'USER32::CreateWindowEx(i0, t "STATIC", t "${MANUAL_DOWNLOAD_TEXT}", i${WS_CHILD}|${WS_VISIBLE}|${SS_NOTIFY}, i 1, i ${yCoord}, i 500, i 50, p $0, i 0x666, p 0, p 0)p.s'
Pop $0
SetCtlColors $0 0000ff transparent
CreateFont $1 "$(^Font)" "$(^FontSize)" "400" /UNDERLINE
SendMessage $0 ${WM_SETFONT} $1 1
GetFunctionAddress $1 fnLinkClicked
ButtonEvent::AddEventHandler 0x666 $1
!macroend
;--------------------------------
;Pages
!insertmacro MUI_PAGE_INSTFILES
;--------------------------------
;Languages
!insertmacro MUI_LANGUAGE "English"
;--------------------------------
;Installer Sections
Section
Var /global Filename
StrCpy $Filename "test100Mb.db"
Var /global DownloadUrl
StrCpy $DownloadUrl "http://speedtest.ftp.otenet.gr/files/$Filename"
!insertmacro AddDownloadLink 70
inetc::get /caption "Downloading package" $DownloadUrl "$Filename" /end
Pop $R0 ;Get the return value
StrCmp $R0 "OK" 0 dlfailed
Goto quit
dlfailed:
DetailPrint "Download failed: $R0 $DownloadUrl"
SetDetailsView show
Abort
!insertmacro AddDownloadLink 1
quit:
Quit
SectionEnd
Function fnLinkClicked
ExecShell "open" "$DownloadUrl"
FunctionEnd
A:
Abort stops executing the section(s) code, you must do whatever you need to do before calling Abort.
Adding controls in a section can be problematic because it executes on a different thread and windows are tied to the thread that created them. If you need the window to stick around longer than the install thread you can create it as a hidden window in the instfiles page show callback and simply call ShowWindow in the section when you need to display it...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
getting method parameters from SOAPMessageContext
Is it possible to get the parameters passed through a web-service call by using a handler on the client side? I'm trying to log the parameters i've sent to the web-service, everytime i do so.
In this chase, using a jax-ws handler that i've assigned to the web-service. This is a simple and common example of the handler look and methods.
public class RafaSOAPHandler implements SOAPHandler<SOAPMessageContext> {
@Override
public boolean handleMessage(SOAPMessageContext context) {
System.out.println("Client : handleMessage()......");
// TODO: GET METHOD PARAMETERS HERE.
return true;
}
@Override
public boolean handleFault(SOAPMessageContext context) {
System.out.println("Client : handleFault()......");
return true;
}
@Override
public void close(MessageContext context) {
System.out.println("Client : close()......");
}
@Override
public Set<QName> getHeaders() {
System.out.println("Client : getHeaders()......");
return null;
}
}
A:
Is it possible to get the parameters passed through a web-service call
by using a handler on the client side?
The answer is simple: Yes it is possible. You can extract the soap message from SOAPMessageContext like this:
public boolean handleMessage(SOAPMessageContext context) {
SOAPMessage message = context.getMessage();
SOAPHeader header = message.getSOAPHeader();
SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
}
And as long as you have soap envelope you get any parameter from your SOAP message.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Are there public records of results with laetrile treatment against cancer?
I'm looking for what the title says. This is based on the book by Edward Griffins. Is laetrile actually fatal because of its cyanide content? Or can it really help in this fight?
A:
Yes, there are several articles describing experimental data from animals and clinical trials in humans. The results clearly show that laetrile is not effective for cancer treatment, and the drive for laetrile as a cancer drug is widely considered to be a quack. See for example this NCI summary or this article.
Laetrile is a modified form of Amygdalin, a toxic plant product found in some seeds and nuts, for example bitter almonds. The compound contains a cyanide moiety and can cause cyanide poisoning. It was labeled "Vitamin B17" by Ernst Krebs in an attempt to get the compound classified as a nutritional supplement rather than a pharmaceutial (to escape FDA regulations), but this is misleading; it is not a vitamin.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
The flow of Harmonic vector fields
A map or a vector field $g: \mathbb{R}^n \to \mathbb{R}^n $ is called a harmonic map if all its components are harmonic functions.
Motivated by conversations on this questions we ask:
Is the flow of a Harmonic vector field on $\mathbb{R}^n$, a harmonic function?
More precisely, assume that every component of the vector field $x'=f(x)$ is a harmonic map. Is it true to say that for every $t$, $\phi_t$ is a Harmonic map?
Note that the converse is true. Namely, a vector field is Harmonic if its flow is harmonic.
A:
There is a "known true version", but it is basically what you have already as the converse.
Defn Let $(M,g)$ and $(N,h)$ be Riemannian manifolds, and let $\phi: M\to N$ be a smooth mapping. The tension field of $\phi$ is defined to be
$$ \tau(\phi) = \mathrm{trace}_g D \mathrm{d}\phi $$
where $D$ is the pull-back of the Levi-Civita connection on $N$ to $M$ via $\phi$.
Defn A mapping $\phi:M\to N$ is said to be "harmonic" if $\tau(\phi) \equiv 0$.
Rmk In the case $M$ and $N$ are Euclidean spaces, this reduces to the components of mapping being harmonic functions.
Defn Given a Riemannian manifold $(M,g)$, a vector field is said to be 1-harmonic-Killing if, denoting by $\varphi_t$ its corresponding one parameter family of diffeomorphisms, that
$$ \frac{\mathrm{d}}{\mathrm{d}t} \tau(\varphi_t) \Big|_{t = 0} = 0 $$
Rmk $\tau(\varphi_0) = \tau(\mathrm{id}) = 0$. So the definition of 1-harmonic-Killing asks that the flow to be linearly harmonic.
Thm A vector field $V$ is 1-harmonic-Killing if and only if
$$ \triangle X^\flat = \mathrm{Ric}(X,\cdot) \tag{1}$$
where $\triangle$ is the Hodge-Laplacian and $\mathrm{Ric}$ is the Ricci tensor.
Rmk In the Euclidean case, Ricci curvature vanishes, and (1) reduces to what you state as "harmonic vector field".
This result can be found in: Dodson, Trinidad Pérez, and Vázquez-Abal; Stepanov and Shandra; and Nouhaud. The first reference also contains examples showing that there exists 1-harmonic-Killing vector fields whose flow is not always harmonic.
Notice however, Remark 3.1 and Proposition 3.1 in the first-cited paper above, which combine to say that on a compact Riemannian manifold with non-positive Ricci curvature, a vector field $V$ is 1-harmonic-Killing if and only if $V$ is a parallel vector field. In particular, this implies that on such manifolds any 1-harmonic-Killing vector field will give rise to a harmonic flow. While this statement gives a positive answer to your question, we should note that in this setting $V$ is also necessarily Killing and hence the flow generated is a one parameter family of isometries, and hence the result can also be viewed as a rigidity statement.
A geometrically interesting fact is this:
Let $V$ be a vector field and $\varphi_t$ its local one parameter family of isometries. In the above we asked about the property of $\varphi_t$ being harmonic. If we replace the word harmonic by
isometric; we get Killing vector fields;
conformal isometric: we get conformal Killing vector fields;
totally geodesic: we get affine Killing vector fields.
In all three of the above situations, having the "1-" version hold (meaning that the condition holds for $\varphi_t$ to first order as $t \to 0$) implies that the condition in fact holds (to infinite order). So in the literature we do not distinguish between 1-Killing vector fields and Killing vector fields.
One reason behind this distinction is the fact that compositions of harmonic maps need not be harmonic, in contrast to the other three cases mentioned above.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ActionBar buttons maintaining 'pressed' state, possible?
I have an app that in a certain Activity (drawing) can be in any one of a number of states, such as draw, erase, select, etc.
To enable these states, I've got a button for each in the ActionBar, but one thing I'd like to do is to 'show' the user which state is enabled by keeping the button pressed active or pressed until I turn it off (when they have switched state by pressing one of the other buttons).
Searches here and other places have me coming up blank... can anyone recommend a possible solution? I've though about rolling my own toolbar, and while this might be my final solution, using the ActionBar would speed things up greatly at this point.
Thanks.
A:
There is no direct way to do that, as far as I know, but you could implement your custom component to do that. However, my advice to you is having a separate toolbar that's not on the action bar, since the users expect all buttons on the Action Bar to be "Action Items" which perform something immediate, so having toggle items on the Action Bar might break this expectation. This allows you to save space on the action bar for things that the user expects to see there like: navigation, "Undo", "Save", "Delete"...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how I can access to my child routes via localhost?
Hi I can't access the child routes I mean when I type
localhost:4200/general-managment/list-site
this doesn't go to list-site HTML.
this is my list.component.ts:
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.scss']
})
export class ListComponent implements OnInit {
showlist = true;
constructor(private router: Router,
private route: ActivatedRoute) { }
ngOnInit() {
}
siteList() {
this.router.navigate(['list-site'] , {relativeTo: this.route});
this.showlist = false;
}
}
in this.router.navigate(['list-site'] , {relativeTo: this.route}); i try /list-site and ./list-site and ../list-site but it doesn't work
this is my app-routing.service.ts:
import {Routes, RouterModule} from '@angular/router';
import {HomeComponent} from './home/home.component';
import {NgModule} from '@angular/core';
import { LogoutComponent } from './header/logout/logout.component';
import {GeneralManagementComponent} from
'./home/generalmanagement/generalmanagement.component';
import {SiteComponent} from './home/general-
management/list/site/site.component';
const appRoutes: Routes = [
{path: '', component: HomeComponent},
{path: 'log-out', component: LogoutComponent},
{path: 'general-management' , component: GeneralManagementComponent ,
children : [
{path: 'list-site' , component: SiteComponent}
]}
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
],
})
export class AppRoutingService {
}
and this is my HTML file :
<button> id="close-image" type="button" class="box" (click)="siteList()">
<img class="list-content" src="assets/imgs/download.jpg">Site
</button>
I using angular 6.
how I can fix it
I use console here:
siteList() {
console.log(this.router.navigate(['list-site']));
this.router.navigate(['list-site'] , {relativeTo: this.route});
this.showlist = false;
}
and this is what i see :
__proto__:
catch: ƒ (onRejected)
arguments: (...)
caller: (...)
length: 1
name: ""
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: zone.js:966
[[Scopes]]: Scopes[4]
finally: ƒ (onFinally)
arguments: (...)
caller: (...)
length: 1
name: ""
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: zone.js:969
[[Scopes]]: Scopes[4]
then: ƒ (onFulfilled, onRejected)
arguments: (...)
caller: (...)
length: 2
name: ""
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: zone.js:955
[[Scopes]]: Scopes[4]
constructor: ƒ ZoneAwarePromise()
all: ƒ (values)
race: ƒ (values)
reject: ƒ (error)
resolve: ƒ (value)
toString: ƒ ()
__zone_symbol__uncaughtPromiseErrors: []
arguments: (...)
caller: (...)
length: 1
name: "ZoneAwarePromise"
prototype: {then: ƒ, catch: ƒ, finally: ƒ, constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: zone.js:883
[[Scopes]]: Scopes[4]
__proto__:
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ ()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()
A:
i just need create new div and in the new div i call router-outlet and its work well :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Exchange Web Services - cannot get additional properties when calling "FindPeople" method
I'm making raw SOAP requests to Office365 and trying to get a list of contacts for specified AddressListId I successfully get a list of contacts, but it does not include all additional information I need. Once I add some additional properties (e.g. PhoneNumber) to my request, the server returns Invalid shape error.
Here is my request:
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages">
<soap:Header>
<t:RequestServerVersion Version="Exchange2013" />
</soap:Header>
<soap:Body >
<m:FindPeople>
<m:PersonaShape>
<t:BaseShape>IdOnly</t:BaseShape>
<t:AdditionalProperties>
<t:FieldURI FieldURI="persona:DisplayName"/>
<t:FieldURI FieldURI="persona:PhoneNumber"/>
</t:AdditionalProperties>
</m:PersonaShape>
<m:IndexedPageItemView BasePoint="Beginning" MaxEntriesReturned="100" Offset="0"/>
<m:ParentFolderId>
<t:AddressListId Id="###-####-####-####"/>
</m:ParentFolderId>
</m:FindPeople>
</soap:Body>
</soap:Envelope>
How can I get all additional information for each persona?
A:
I am using EWS Managed API, so you will have to search for the raw SOAP calls on MSDN, I can only direct your search a bit:
I had a similar problem, because the very same is applicable for FindAppointments(). Asking for AppointmentSchema.RequiredAttendees will raise the Invalid Shape error, and AppointmentSchema.Organizer won't contain the email address, only the name of the organizer, after using FindAppointments().
The solution was to do TWO requests to Exchange Server.
var appointments = calendarFolder.FindAppointments(BasePropertySet.FirstClassProperties);
exchangeService.LoadPropertiesForItems(appointments, MyAdvancedProperties);
I think that the same "workaround" is possible with FindPeople(), as well as every other Find%Itemtype%() EWS may support, I am not sure, though.
EDIT: I just found http://social.technet.microsoft.com/Forums/exchange/en-US/e83abfb1-37a8-48fe-9579-4e120fb77746/ews-managed-api-loadpropertiesforitems-returns-unexpected-end-of-xml-document?forum=exchangesvrdevelopment where it is stated that LoadPropertiesForItems does a call to raw soap GetItem with multiple ItemIDs.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Override CSS box-shadow with standard border property for IE
css for all browsers:
.bordering {
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: #A3815B 0px 1px 3px;
-moz-box-shadow: #A3815B 0px 1px 3px;
box-shadow: #A3815B 0px 1px 3px;
}
css for IE:
.bordering {
border: 1px solid #A3815B;
}
when remove .bordering class from all-browsers css,that border in IE works OK.
How to do,that box-shadow works in FF,Opera and others and generic border works in IE at one time.
tried:
.bordering {
-webkit-border-radius: none;
-moz-border-radius: none;
border-radius: none;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
}
didn't help.
A:
Make a separate CSS for IE like ie.css and link it to your HTML page with this:
<![if IE]>
<link rel="stylesheet" href="css/ie.css" type="text/css" media="screen" />
<![endif]>
Your CSS will be only included if IE is detected.
After that, put your .bordering CSS in your style.css (for all browser) and put border: xxx only in ie.css.
It should work. I made it a lot of times.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MongoDB, sort() and pagination
I known there is already some patterns on pagination with mongo (skip() on few documents, ranged queries on many), but in my situation i need live sorting.
update:
For clarity i'll change point of question. Can i make query like this:
db.collection.find().sort({key: 1}).limit(n).sort({key: -1}).limit(1)
The main point, is to sort query in "usual" order, limit the returned set of data and then reverse this with sorting to get the last index of paginated data. I tried this approach, but it seems that mongo somehow optimise query and ignores first sort() operator.
A:
I am having a huge problem attempting to grasp your question.
From what I can tell when a user refreshes the page, say 6 hours later, it should show not only the results that were there but also the results that are there now.
As @JohnnyHK says MongoDB does "live" sorting naturally whereby this would be the case and MongoDB, for your queries would give you back the right results.
Now I think one problem you might trying to get at here (the question needs clarification, massively) is that due to the data change the last _id you saw might no longer truely represent the page numbers etc or even the diversity of the information, i.e. the last _id you saw is now in fact half way through page 13.
These sorts of things you would probably spend more time and performance trying to solve than just letting the user understand that they have been AFAK for a long time.
Edit
Aha, I think I see what your trying to do now, your trying to be sneaky by getting both the page and the last item in the list at the same time. Unfortunately just like SQL this is not possible. Even if sort worked like that the sort would not function like it should since you can only sort one way on a single field.
However for future reference the sort() function is exactly that on a cursor and until you actually open the cursor by starting to iterate it calling sort() multiple times will just overwrite the cursor property.
I am afraid that this has to be done with two queries, so you get your page first and then client side (I think your looking for the max of that page) scroll through the records to find the last _id or just do a second query to get the last _id. It should be super dupa fast.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
get an element from a subset of a matrix in Rarmadillo
I have a large-ish matrix. I'm trying to sample from it with dynamically changing weights. As it's forced to use loops in R, I'm trying to implement it in Rcpp so it has the chance of running a bit faster. After a bit of experimenting, I think I've figured out how to grab an index at random with the correct weights.
The trick is that I'm only sampling from a subset of columns at any given time (this can change to rows if it's more efficient in C - the matrix is actually symmetric). My indices are only defined for this subset of columns. In R, I'd do something along the lines of
large_matrix[, columns_of_interest][index]
and this works fine. How would I do the equivalent using Rcpp/Armadillo? My guess of
cppFunction("arma::vec element_from_subset(arma::mat D, arma::uvec i, arma::uvec columns) {
# arma::mat D_subset = D.cols(columns);
return D.cols(columns).elem(i);
}", depends = "RcppArmadillo")
fails to compile (and .at instead of .elem doesn't work either, nor does the standard R trick of surrounding things in paranthesis.
This does work, but is what I'm trying to avoid:
cppFunction("arma::vec element_from_subset(arma::mat D, arma::uvec i, arma::uvec columns) {
arma::mat D_subset = D.cols(columns);
return D_subset.elem(i);
}", depends = "RcppArmadillo")
Is there any way to accommplish this without needing to save D.cols(columns)?
A:
Short answer: No.
But, the problem is phrased incorrectly. Think about what is happening here:
(M <- matrix(1:9, 3, 3))
#> [,1] [,2] [,3]
#> [1,] 1 4 7
#> [2,] 2 5 8
#> [3,] 3 6 9
columns_of_interest = 1:2
M[, columns_of_interest]
#> [,1] [,2]
#> [1,] 1 4
#> [2,] 2 5
#> [3,] 3 6
From here, if we have the index being 1, then we get:
index = 1
M[, columns_of_interest][index]
#> 1
So, in essence, what's really happening is an entry-wise subset of (i,j). Thus, you should just use:
Rcpp::cppFunction("double element_from_subset(arma::mat D, int i, int j) {
return D(i, j);
}", depends = "RcppArmadillo")
element_from_subset(M, 0, 0)
#> [1] 1
I say this based on the R and C++ code posted, e.g. R gives 1 value and C++ has a return type permitting only one value.
The code posted by OP is shown without the error. The initial error as compiled will indicate there is an issue using an Rcpp object inside of an arma class. If we correct the types, e.g. replacing Rcpp::IntegerVector with an arma appropriate type of either arma::ivec or arma::uvec, then compiling yields a more informative error message.
Corrected Code:
Rcpp::cppFunction("double element_from_subset(arma::mat D, int i, arma::uvec columns) {
return D.cols(columns).elem(i);
}", depends = "RcppArmadillo")
Error Message:
file6cf4cef8267.cpp:10:26: error: no member named 'elem' in 'arma::subview_elem2<double, arma::Mat<unsigned int>, arma::Mat<unsigned int> >'
return D.cols(columns).elem(i);
~~~~~~~~~~~~~~~ ^
1 error generated.
make: *** [file6cf4cef8267.o] Error 1
So, there is no way to subset a subview that was created by taking the a subset from an armadillo object.
You may want to read up on a few of the subsetting features of Armadillo. They are immensely helpful.
Rcpp Gallery: http://gallery.rcpp.org/articles/armadillo-subsetting
Guide to Converting R Code to Armadillo: http://thecoatlessprofessor.com/programming/common-operations-with-rcpparmadillo/
Armadillo specific documentation
Matrix subsets: http://arma.sourceforge.net/docs.html#submat
Individual entries: http://arma.sourceforge.net/docs.html#element_access
sub2ind(): http://arma.sourceforge.net/docs.html#sub2ind
ind2sub(): http://arma.sourceforge.net/docs.html#ind2sub
Disclaimer: Both the first and second links I've contributed to or written.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Word that means "periodically purged" or "cleansed by fire"
What is a word that means "periodically purged" or "cleansed by fire"?
A:
Swailing is the term used by the forestry community to describe the process of using intentional controlled burns to reduce the hazards of forest fires and to encourage new tree growth.
Usage of swailing appears particular to wooded parts of the UK (except, naturally, Scotland, where it is called muirburn or moorburn). Controlled burn is more common in the US. Prescribed burn is also common in Australia.
An elegant pen could make fine use of swailing in a literary context, but it may send readers running for a dictionary -- and, unfortunately, the reputable entries for swailing seem to be few.
A:
The word salamanderize has been used with that sort of meaning (regenerate, rejuvenate), but I think in more recent usage just means to burn up without regeneration.
There are several mystical terms that reflect the concept, named with catch-phrases like fiery rebirth, Phoenix rising and star fire cycle. Less-mystical phrases include fire cycle (meaning the actual cycle of fire and regrowth in forests), rising from the ashes, tried in the crucible, and purified by fire. The latter two phrases appear in or stem from Proverbs 27:21 and Zechariah 13:8-9 respectively.
Serotiny is a related but plant-specific term: "an ecological adaptation exhibited by some seed plants, in which seed release occurs in response to an environmental trigger, [...] The most common and best studied trigger is fire". Etymology from wordnik: "Latin sērōtinus, coming late, from sērō, at a late hour, from sērus, late."
The term pyriscence refers in the main to seed release triggered by fire. Also (mis)used in reference to release due to dry conditions, which more properly is xeriscence.
Pyriscence looks like a word that ought to mean what you want, except it doesn't.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to create thumbnail image by using video url for jquery jplayer
i need create to show thumbnail image in poster by using video url for jquery j-player.i have seek in forum.but i didn't got any useful information related to thumbnail.anyone can give me some ideas to do it..
Thanks Advance..
$("#jquery_jplayer_2"+playid).jPlayer({
ready: function () {
$(this).jPlayer("setMedia", {
/*m4v: "media/tokyo.m4v",
ogv: "media/tokyo.ogv",
poster: "media/poster.jpg"*/
m4v: playpath,
ogv: playpath,
poster: playpath
});
},
ended: function (event) {
$("#jquery_jplayer_2"+playid).jPlayer("play", 0);
},
swfPath: "swf",
supplied: "m4v, ogv",
cssSelectorAncestor: "#jp_interface_2"
})
.bind($.jPlayer.event.play, function() { // pause other instances of player when current one play
$(this).jPlayer("pauseOthers");
});
A:
You can create a new canvas to capture the image:
var canvas = document.createElement('canvas');
canvas.width = 640;
canvas.height = 480;
var context = canvas.getContext('2d');
context.drawImage(video, 0, 0, canvas.width, canvas.height);
and then save it to dataURI:
var dataURI = canvas.toDataURL('image/jpeg');
From here you can use it in an image element, save it as a file or upload it to your server:
$('img1').attr("src", dataURI);
Take a look at this plunker. Start the video and press the GET button. Notice that since the video is coming from another domain I had to set the crossOrigin attribute on the video element in the jplayer ready event:
$(this).find("video")[0].setAttribute("crossOrigin", "anonymous");
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Change Fragment by clicking OptionsMenu Item
i try to change the view of my App using a Fragment.
I tried on this several days, so i made a clean code to present my problem.
I have an MainActivity with a OptionsMenu, in this OptionsMenu i have an item called "action_connect".
The first view of my App should be a clean Page(nothing on it).
When someone clicks the "action_connect" item, I want the View to change to my Fragment in which I have an TextView.
Problem with current code: Application will crash on click of the item.
I hope you can help me to solve this. Thanks in advance.
Heres my code:
MainActivity:
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
MainActivityFragment mMainActivityFragment = new MainActivityFragment();
int id = item.getItemId();
if (id == R.id.action_connect) {
ft.replace(R.id.default_container, mMainActivityFragment);
}
ft.commit();
return super.onOptionsItemSelected(item);
}
Fragment:
public class MainActivityFragment extends Fragment{
@Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
//get command buttons
View rootView = inflater.inflate(R.layout.fragment_connect, parent, false);
return rootView;
}
}
Fragment-XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Welcome!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp" />
Activity-XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<FrameLayout
android:id="@+id/default_container"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
Here are the Logs, hope its the right one:
02-27 12:44:44.473 5513-5513/? I/art: Not late-enabling -Xcheck:jni (already on)
02-27 12:44:44.475 5513-5513/? W/art: Unexpected CPU variant for X86 using defaults: x86
02-27 12:44:44.530 5513-5513/hsulm.cermitbasmati_2.app W/System: ClassLoader referenced unknown path: /data/app/hsulm.cermitbasmati_2.app-1/lib/x86
02-27 12:44:44.544 5513-5513/hsulm.cermitbasmati_2.app I/InstantRun: Instant Run Runtime started. Android package is hsulm.cermitbasmati_2.app, real application class is null. [ 02-27 12:44:44.544 1560: 1587 D/ ]HostConnection::get() New Host Connection established 0x98e23700, tid 1587
02-27 12:44:45.850 5513-5513/hsulm.cermitbasmati_2.app W/System: ClassLoader referenced unknown path: /data/app/hsulm.cermitbasmati_2.app-1/lib/x86
02-27 12:44:45.938 5513-5513/hsulm.cermitbasmati_2.app W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
02-27 12:44:46.028 5513-5557/hsulm.cermitbasmati_2.app I/OpenGLRenderer: Initialized EGL, version 1.4
02-27 12:44:46.028 5513-5557/hsulm.cermitbasmati_2.app D/OpenGLRenderer: Swap behavior 1
02-27 12:44:46.159 5513-5557/hsulm.cermitbasmati_2.app E/EGL_emulation: tid 5557: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)
02-27 12:44:46.159 5513-5557/hsulm.cermitbasmati_2.app W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x99e9ce20, error=EGL_BAD_MATCH
02-27 12:44:48.028 5513-5513/hsulm.cermitbasmati_2.app W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
02-27 12:44:48.105 5513-5557/hsulm.cermitbasmati_2.app E/EGL_emulation: tid 5557: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)
02-27 12:44:48.105 5513-5557/hsulm.cermitbasmati_2.app W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x99287620, error=EGL_BAD_MATCH
02-27 12:44:49.497 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: No view found for id 0x7f0b0057 (hsulm.cermitbasmati_2.app:id/default_container) for fragment MainActivityFragment{1d6183d #0 id=0x7f0b0057}
02-27 12:44:49.498 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: Activity state:
02-27 12:44:49.498 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: Local FragmentActivity 5db9396 State:
02-27 12:44:49.498 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: mCreated=truemResumed=true mStopped=false mReallyStopped=false
02-27 12:44:49.498 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: mLoadersStarted=true
02-27 12:44:49.498 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: FragmentManager misc state:
02-27 12:44:49.498 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: mHost=android.support.v4.app.FragmentActivity$HostCallbacks@fb91832
02-27 12:44:49.498 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: mContainer=android.support.v4.app.FragmentActivity$HostCallbacks@fb91832
02-27 12:44:49.499 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: mCurState=5 mStateSaved=false mDestroyed=false
02-27 12:44:49.499 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: View Hierarchy:
02-27 12:44:49.499 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: com.android.internal.policy.DecorView{fdab983 V.E..... ... 0,0-1080,1920}
02-27 12:44:49.499 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: android.widget.LinearLayout{2f91700 V.E..... ... 0,0-1080,1776}
02-27 12:44:49.499 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: android.view.ViewStub{310fb39 G.E..... ... 0,0-0,0 #10203ef android:id/action_mode_bar_stub}
02-27 12:44:49.499 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: android.widget.FrameLayout{1dc857e V.E..... ... 0,72-1080,1776}
02-27 12:44:49.499 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: android.support.v7.widget.ActionBarOverlayLayout{9056adf V.E..... ... 0,0-1080,1704 #7f0b0045 app:id/decor_content_parent}
02-27 12:44:49.499 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: android.support.v7.widget.ContentFrameLayout{558a32c V.E..... ... 0,168-1080,1704 #1020002 android:id/content}
02-27 12:44:49.499 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager:
02-27 12:44:49.499 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: android.support.v7.widget.ActionBarContainer{87d11f5 V.ED.... ... 0,0-1080,168 #7f0b0046 app:id/action_bar_container}
02-27 12:44:49.500 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: android.support.v7.widget.Toolbar{1377b8a V.E..... ... 0,0-1080,168 #7f0b0047 app:id/action_bar}
02-27 12:44:49.500 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: android.support.v7.widget.AppCompatTextView{2ffd5fb V.ED.... ... 48,43-544,124}
02-27 12:44:49.500 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: android.support.v7.widget.ActionMenuView{542c618 V.E..... ... 960,0-1080,168}
02-27 12:44:49.500 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: android.support.v7.widget.ActionMenuPresenter$OverflowMenuButton{459d871 VFED..CL ... 0,12-120,156}
02-27 12:44:49.500 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: android.support.v7.widget.ActionBarContextView{299c656 G.E..... ... 0,0-0,0 #7f0b0048 app:id/action_context_bar}
02-27 12:44:49.500 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: android.view.View{26bd6d7 V.ED.... ... 0,1776-1080,1920 #1020030 android:id/navigationBarBackground}
02-27 12:44:49.500 5513-5513/hsulm.cermitbasmati_2.app E/FragmentManager: android.view.View{4aa2bc4 V.ED.... ... 0,0-1080,72 #102002f android:id/statusBarBackground}
02-27 12:44:49.501 5513-5513/hsulm.cermitbasmati_2.app D/AndroidRuntime: Shutting down VM
02-27 12:44:49.501 5513-5513/hsulm.cermitbasmati_2.app E/AndroidRuntime: FATAL EXCEPTION: main
Process: hsulm.cermitbasmati_2.app, PID: 5513
java.lang.IllegalArgumentException: No view found for id 0x7f0b0057 (hsulm.cermitbasmati_2.app:id/default_container) for fragment MainActivityFragment{1d6183d #0 id=0x7f0b0057}
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:987)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1171)
at android.app.BackStackRecord.run(BackStackRecord.java:816)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1578)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:483)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
A:
I can see your problem now, I think you missed putting this line inside your MainActivity class:
@Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.your_activity_layout);
}
When replacing a Fragment with an id using the replace method, you should use the setContentView() method so that you can access the id of the FrameLayout you are replacing by which is in your case: default_container.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Получить локальную дату пользователя из браузера в Django
Как получить локальную дату пользователя из браузера в Django, чтобы каждому пользователю отдавать контент с его тайм зоной?
A:
https://docs.djangoproject.com/en/dev/topics/i18n/timezones/ - eng
http://djbook.ru/rel1.4/topics/i18n/timezones.html - ru
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jquery dialog - replacing dialog element
I have a document with a #page div, which contains a jQuery dialog div #dia and the JS to create it. Something like this:
<script>
var x;
</script>
<div id="page">
<div id="dia">bla</div>
<script>
$(function () { x = $('#dia').dialog(); });
</script>
</div>
This works fine so far. However, now I need to remove the contents of #page and replace them with new content. This new content will contain another div with id #dia and the same JS code to make that one into a dialog as well.
This does not seem to work. Instead, it seems like x is still the old dialog from before the replacement.
What I think happens is that jQuery moves the #dia div somewhere else when I create the dialog and thus when I replace the contents of #page the old dialog is still there. Then, when my $('#dia').dialog() code runs it is just applied to the old div, which is already a dialog.
I have tried running $('#page').empty(), x.dialog('destroy') and x.remove() before replacing the elements but none of this seems to help.
How do I do this properly?
A:
Your script is set to only run on document ready.
$(function() { ... });
is a short hand for
$(document).ready(function () { ... });
Because you are dynamically loading the content into the page, but not actually changing the page, it will not fire a new document ready event. Subsequently, the value of x will not get changed, and the new content will not get converted to a dialog.
If you are going to dynamically load in the content, without reloading the page, you need to use a callback function to re-trigger the dialog initialize.
<script>
var x;
function reloadContent(url) {
$("#page").load(url, function () {
x = $("#dia").dialog();
}
}
</script>
<div id="page">
<div id="dia">bla</div>
<script>
$(function () { x = $('#dia').dialog(); });
</script>
</div>
<button type="button" onclick="reloadContent('new/url/for/content');>Change Content</button>
If you are going to manually swap out the content by using $.html(), then you will also have to manually reinitialize the dialog box as well.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
fresh CentOS image in AWS
There are a lot of CentOS images in AWS for creating EC2 instance.
In most of them various application and services are pre-installed,for example:
I found most of them having apache, bind, postfix & even mysql is installed,
but, I want a fresh image, where I'll install the services whatever I need,
so which CentOS image is a fresh image, could anybody tell me?
Thanks.
A:
You should use this Official Centos Image from AWS Market Place.
Thanks
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What are the options when looking for gluten free chapati?
Hi does anyone know where I can buy gluten free chapatis or what is the best method of making them and storing them without any preservatives?
A:
I use ivory teff tortillas from La Tortilla Factory as a gluten-free substitute for chapati. They are sometimes available at my local grocery store, but I've also bought them online. They are similar in texture and mouthfeel to wheat chapatis. When heated on a griddle, they brown and puff up just like the real stuff, and they then taste delicious with a little ghee. I don't miss wheat chapatis at all since I discovered these. They are much closer to wheat chapatis than gluten-free sandwich bread is to the genuine article. They freeze well and also keep in the refrigerator for several weeks.
If you're interested in making a gluten free Indian roti, I would suggest not trying to make something that approximates chapati. Instead, make some traditional preparation that uses other flours. For example, there's bhakri, which can be made with any of various flours like jowar (sorghum), bajri (finger millet), or even rice flour.
Or there's one of my all time personal favorite foods, a multigrain flatbread called thalipeeth. Most recipes online include wheat as one of the ingredients, but you can just leave it out and increase the amount of the other flours proportionately. There's also a sabudana (sago) version which is a lot simpler as it just uses whatever flour you have lying around in addition to sago.
Finally, the site Spice Up The Curry has a section on Indian Breads that includes recipes for rotis made with exotic flours such as rajgira (amaranth), singhara (water chestnut), and kuttu (buckwheat). I've never made any of those, so YMMV. In general I've had good success with recipes from that site, though.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
NetBeans sending build to multiple locations
I was wondering if someone knew how to configure NetBeans to send builds to multiple locations? I am writing some server code. Every time I build the code, it gets sent to someplace like this:
C:\Users\MyName\Documents\Net Beans Projects\MyProject\dist
I then need to move that build Jar file to a new location (where my other project will use it). Someplace like:
C:\SmartFoxServer_2X\SFS2X\extensions\MyOtherProject
Is there a way to configure NetBeans to send the build jar file to both locations? FYI, I am using NetBeans IDE 8.2
A:
If you are using NetBeans' "native" project system which is based on Ant, you can customize the build.xml used for your project.
In your case you need to add the "hook" -post-jar to your project's build.xml
<target name="-post-jar">
<copy overwrite="true" file="${dist.jar}" todir="C:/SmartFoxServer_2X/SFS2X/extensions/MyOtherProject"/>
</target>
The build.xml can be opened from the "Files" Window (expand the node for your project):
The build.xml also contains a lot of examples and explanations on which hooks are available for you to use.
But in general this should not be necessary if the other project is also a NetBeans project. Just add MyProject to the other's project classpath.
In the project properties select the Libraries node, then click on the "Add Project" button. The referencing project will then automatically know which jar file to use. You can also tell NetBeans to build MyProject when you build OtherProject:
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Spark groupByKey alternative
According to Databricks best practices, Spark groupByKey should be avoided as Spark groupByKey processing works in a way that the information will be first shuffled across workers and then the processing will occur. Explanation
So, my question is, what are the alternatives for groupByKey in a way that it will return the following in a distributed and fast way?
// want this
{"key1": "1", "key1": "2", "key1": "3", "key2": "55", "key2": "66"}
// to become this
{"key1": ["1","2","3"], "key2": ["55","66"]}
Seems to me that maybe aggregateByKey or glom could do it first in the partition (map) and then join all the lists together (reduce).
A:
groupByKey is fine for the case when we want a "smallish" collection of values per key, as in the question.
TL;DR
The "do not use" warning on groupByKey applies for two general cases:
1) You want to aggregate over the values:
DON'T: rdd.groupByKey().mapValues(_.sum)
DO: rdd.reduceByKey(_ + _)
In this case, groupByKey will waste resouces materializing a collection while what we want is a single element as answer.
2) You want to group very large collections over low cardinality keys:
DON'T: allFacebookUsersRDD.map(user => (user.likesCats, user)).groupByKey()
JUST DON'T
In this case, groupByKey will potentially result in an OOM error.
groupByKey materializes a collection with all values for the same key in one executor. As mentioned, it has memory limitations and therefore, other options are better depending on the case.
All the grouping functions, like groupByKey, aggregateByKey and reduceByKey rely on the base: combineByKey and therefore no other alternative will be better for the usecase in the question, they all rely on the same common process.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Gem::InstallError: The 'json' native gem requires installed build tools. Please update your PATH to include build tools or download the DevKit
I'm having trouble building a Ruby project on Windows 7 Enterprise SP1.
Fetching gem metadata from https://rubygems.org/............
Fetching version metadata from https://rubygems.org/..
Resolving dependencies...
Using awesome_print 1.7.0
Installing json 2.1.0 with native extensions
Using mini_portile2 2.1.0
Using ffi 1.9.18 (x64-mingw32)
Using rubyzip 1.2.1
Using websocket 1.2.4
Using tomlrb 1.2.4
Using bundler 1.14.6
Gem::InstallError: The 'json' native gem requires installed build tools.
Please update your PATH to include build tools or download the DevKit
from 'http://rubyinstaller.org/downloads' and follow the instructions
at 'http://github.com/oneclick/rubyinstaller/wiki/Development-Kit'
An error occurred while installing json (2.1.0), and Bundler cannot continue.
Make sure that `gem install json -v '2.1.0'` succeeds before bundling.
I've included both Ruby and the DevKit in my PATH environment variable, i.e. C:\Ruby22-x64\bin;C:\Ruby-DevKit\bin. What could be going wrong?
The command I'm running is bundle install in the ..\tindermation\node_modules\.bin directory of this project: https://github.com/feelobot/tindermation
A:
I didn't initialize and bind the ruby installations in my DevKit to my PATH:
Downloaded it, ran it to extract it somewhere (permanent). Then cd to it, run ruby dk.rb init and ruby dk.rb install. The bundle install command worked after following these steps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using QPainter and paintEvent to draw circles on a Pixmap that is contained in a QLabel in PYQT5
I'm pretty new to PYQT5 and I wanted to draw a circle on a Pixmap that is contained in a QLabel in the MainWindow UI on PYQT5 with this code:
from PyQt5 import QtCore, QtGui, QtWidgets
background_image_path = '001_01_01_041_05.png'
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(60, 60, 331, 401))
self.label.setObjectName("label")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 28))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self._image = QtGui.QPixmap(background_image_path)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setPixmap(self._image)
def paintEvent(self, event):
painter = QtGui.QPainter(self._image)
painter.drawPixmap(self.rect(), self._image)
pen = QtGui.QPen()
pen.setWidth(5)
painter.setPen(pen)
painter.drawEllipse(300, 300, 70, 70)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
However, I cannot get the paintEvent(self, event) function to get called. When I did get to call paintEvent(self, event), I could not see the circle being drawn onto the pixmap. I tried setting the QPainter to the Pixmap itself (in painter = QtGui.QPainter(self._image)), but that did not work either.
What did I do incorrectly?
The code below works, which is what my code is based on:
from PyQt5 import QtWidgets, QtGui, QtCore
background_image_path = '001_01_01_041_05.png'
class ImageScroller(QtWidgets.QWidget):
def __init__(self):
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.drawPixmap(self.rect(), self._image)
pen = QtGui.QPen()
pen.setWidth(5)
painter.setPen(pen)
painter.drawEllipse(300, 300, 70, 70)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = ImageScroller()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
Any thoughts or advice would be greatly appreciated!
A:
You missed a couple of lines.
Try it:
from PyQt5 import QtWidgets, QtGui, QtCore
background_image_path = 'E:/_Qt/img/heart.png' # '001_01_01_041_05.png'
class ImageScroller(QtWidgets.QWidget):
def __init__(self):
super().__init__() # <-------
self._image = QtGui.QPixmap(background_image_path) # <-------
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.drawPixmap(self.rect(), self._image)
pen = QtGui.QPen()
pen.setWidth(5)
painter.setPen(pen)
painter.drawEllipse(300, 300, 70, 70)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = ImageScroller()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
The real problem here is that you are editing the module generated by pyuic,
which is always a very bad idea. Try it:
from PyQt5 import QtCore, QtGui, QtWidgets
background_image_path = 'E:/_Qt/img/heart.png'
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(200, 0, 760, 560))
self.label.setObjectName("label")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 28))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
# self._image = QtGui.QPixmap(background_image_path)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
# self.label.setPixmap(self._image)
self.label.setText(_translate("MainWindow",
"""
It is not recommended to modify the design file,
it is appropriate to create another file
to join the logic with the design.
"""))
# def paintEvent(self, event):
# painter = QtGui.QPainter(self._image)
# painter.drawPixmap(self.rect(), self._image)
# pen = QtGui.QPen()
# pen.setWidth(5)
# painter.setPen(pen)
# painter.drawEllipse(300, 300, 70, 70)
class MyApp(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super(MyApp, self).__init__()
self.setupUi(self)
self._image = QtGui.QPixmap(background_image_path)
def paintEvent(self, event):
painter = QtGui.QPainter(self)
painter.drawPixmap(self.rect(), self._image)
#pen = QtGui.QPen()
#pen.setWidth(5)
#painter.setPen(pen)
painter.setPen(QtGui.QPen(QtCore.Qt.blue, 5))
painter.drawEllipse(350, 350, 70, 70)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
# MainWindow = QtWidgets.QMainWindow()
# ui = Ui_MainWindow()
# ui.setupUi(MainWindow)
# MainWindow.show()
window = MyApp()
window.show()
sys.exit(app.exec_())
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Typescript: How type a function using generic type in this case?
I have this type definition
type FuncType<T> = (value: T) => T
I want to implement a function using this type that would look like:
const myFunc: FuncType<T> = (value) => value;
and use it as follows:
const a: string = myFunc<string>('a');
const b: number = myFunc<number>(2);
But, of course, the previous line const myFunc: FuncType<T> = (value) => value; doesn't have a valid syntax.
How should it be written ?
Note:
I found a workaround using an intermediate function but it would be nice to avoid this useless currying (that I cannot use anyway in my real use case because it's related to react hook and react hooks doesn't tolerate currying):
const myFunc = <T>(): FuncType<T> => (value) => value;
const a: string = myFunc<string>()('a');
const b: number = myFunc<number>()(2);
Why do I need to use this type alias and cannot directly write ?
const myFunc = <T>(value: T): T => value;
Because in my real use case, the type definition of my function is not that simple.
It looks like something like that:
interface FuncType<T> {
(args: {arg1: T}): {res1: T}
(args: {arg1: T, arg2: T}): {res1: T, res2: T}
}
A:
So far I don't see a use case for FuncType being a generic type alias to a concrete overloaded function. Could you instead make it a concrete type alias to a generic overloaded function? Like this:
interface FuncType {
<T>(args: { arg1: T }): { res1: T }
<T>(args: { arg1: T, arg2: T }): { res1: T, res2: T }
}
Then FuncType will always refer to something that accepts any T, and you can use it the way you wanted:
const myFunc: FuncType =
(value: { arg1: any, arg2?: any }) => ({ res1: value.arg1, res2: value.arg2 });
const a = myFunc<string>({ arg1: "" }); // { res1: string; }
const b = myFunc<number>({ arg1: 1, arg2: 2 }); // { res1: number; res2: number; }
Hopefully that meets your needs. Good luck!
Link to code
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Oracle ADF Comparison 11g vs 12c and integrating with modern coding techniques
My company is currently undergoing a transition to Oracle to replace our legacy supply chain management system.
Part of the transition will involve evaluating whether to use Oracle ADF or not. The main business drive for this is that it is under the Oracle banner. We have traditionally written all our web applications using Spring MVC, but want to evaluate (after an initial learning curve) whether it may be quicker to deliver apps that sit over the Oracle stack using ADF.
We are running Oracle 11g so think we will be restricted to ADF 11g. I've seen online demos for ADF 12c, but not so much on 11g.
Questions:
Is there a matrix to compare ADF over 11g and ADF over 12c?
What extras do you get with 12c and what may I be missing out if we are stuck with 11g?
How does ADF integrate with modern coding techniques like TDD / Continuous Integration / Maven Repositories? All projects in demos I've seen look like they have a flat structure and testing seems secondary.
I have searched the internet for advice and comparisons but to no avail. The lack of decent resources and forum activity on ADF as a whole is a bit of a concern too!
EDIT 28/11/15:
Thanks for all the replies so far...much appreciated.
With regards to the 11g and 12c debate. We are using Oracle Retail 14.1.1 and have possibly been advised that we must use ADF 11g as a lot of the software that belongs to Oracle Retail is at 11g (see table below). I appreciate that ADF 12c should work over the 11g database, so then is it a problem with just integrating with the other parts of Oracle retail? I am far from an expert when it comes to the rest of Oracle Retail.
Oracle Retail Release Version 14.1.1
Database 12.1
Fusion Middleware:
ADF 11.1.1.7
OAM 11.1.2.2
OID 11.1.1.7
WebLogic Server 10.3.6
OBIEE, ODI 11.1.1.7
Forms Server 11.1.2.2
SOA Suite 11.1.1.7
WebCenter Suite 11.1.1.9.0
A:
I have been working with both 11g and 12c and I have to say that 12c (12.2.1.0.0) brings a productivity boost, from development perspective.
I won't see why anyone would start with 11g right now.
The biggest weakness of ADF comes from the fact that is a strange framework. I was used to jumping from one java web framework to another with relative ease. It wasn't the case with ADF. Though you may look you are having a fairly easy start, things will may get tricky after a while.
The key element is to understand the power behind Business Components and unfortunately this is the least understood element in ADF. I have never seen more bad code in my whole life, compared with other frameworks. But once correctly understood, ADF is head and shoulders above any framework in Java I know, when it comes to complex UI, data input screens, complex querying.
An advice: do not start your project without developers with proven ADF production experience. There quite a few ADF consultants around with lot of experience, they might be a bit expensive, but one of these guys can save you 50% of your development budget.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get JSON data parse from Arrays of dictionary iOS
list = ({
clouds = 24;
speed = "4.31";
temp = {
day = "283.84";
eve = "283.84";
night = "283.84";
};
}),
Please can anyone tell me what am I doing wrong - I want to display list-->temp-->day value in table first I am trying to get data in an array which is terminating.
Here is my code am I doing any wrong
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:dataBuffer options:-1 error:nil];
NSLog(@"%@",json);
NSMutableDictionary * list = [json objectForKey:@"list"];
NSMutableArray *arrays = [[NSMutableArray alloc]initWithCapacity:0];
for (NSDictionary *lists in [list allValues]) {
[arrays addObject:[list valueForKey:@"temp"]];
}
A:
If you want to access day then use below line,
NSString *day = [json valueForKeyPath:@"list.temp.day"];
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.