id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23533900
|
For example I have the following action method that deelte a collection and then loop through a collection and delete the records:-
[HttpPost]
public ActionResult AssignPermisionLevel2(ICollection<SecurityroleTypePermision> list, int id)
{
repository.DeleteSecurityroleTypePermisions(id);
foreach (var c in list)
{
repository.InsertOrUpdateSecurityroleTypePermisions(c,User.Identity.Name);
}
repository.Save();
return RedirectToAction("AssignPermisionLevel", new { id = id });
}
Which will call the following repository method:-
public void DeleteSecurityroleTypePermisions(int securityroleID)
{
var r = tms.SecurityroleTypePermisions.Where(a => a.SecurityRoleID == securityroleID);
foreach (var c in r) {
tms.SecurityroleTypePermisions.Remove(c);
}
}
&
public void InsertOrUpdateSecurityroleTypePermisions(SecurityroleTypePermision role, string username)
{
var auditinfo = IntiateAdminAudit(tms.AuditActions.SingleOrDefault(a => a.Name.ToUpper() == "ASSIGN PERMISION").ID, tms.SecurityTaskTypes.SingleOrDefault(a => a.Name.ToUpper() == "SECURITY ROLE").ID, username, tms.SecurityRoles.SingleOrDefault(a=>a.SecurityRoleID == role.SecurityRoleID).Name, tms.PermisionLevels.SingleOrDefault(a=>a.ID== role.PermisionLevelID).Name + " --> " + tms.TechnologyTypes.SingleOrDefault(a=>a.AssetTypeID == role.AssetTypeID).Name);
tms.SecurityroleTypePermisions.Add(role);
InsertOrUpdateAdminAudit(auditinfo);
}
So let say two users access the same action method at the same time, so will their transactions conflict with each other? , or all the transaction actions (Deletion & Addition) will execute and then the other transaction will start?
UPDATE
Inside my Controller class i will initiate the repository as follow :-
[Authorize]
public class SecurityRoleController : Controller
{
Repository repository = new Repository();
my second question is . You mentioned that EF will mark the entities for deletion or for insetion, then the sql will execute indie the database. but what if one sql statement delete some entities and the other sql statement from the second transaction delete the other entities , could this conflict happen at the database level ? or once the first sql statement from the first transaction start execution, it will prevent other transactions from being executed ? can you advice ?
A: This entirely depends on how you implement your DbContext. If your context is instantiated within a controller then each transaction will be contained within that context, i.e.
public class SomeController : Controller
{
var repository = new DbContext();
[HttpPost]
public ActionResult AssignPermisionLevel2(ICollection<SecurityroleTypePermision> list, int id)
{
repository.DeleteSecurityroleTypePermisions(id);
foreach (var c in list)
{
repository.InsertOrUpdateSecurityroleTypePermisions(c,User.Identity.Name);
}
repository.Save();
return RedirectToAction("AssignPermisionLevel", new { id = id });
}
}
Each request will create its own instance of the repository and the two will not conflict on an application level. When SaveChanges is called on a DbContext it is done in a single transaction, and as the repository object is created for each request.
Unfortunately Entity Framework does not delete as you expect, and will delete individual elements rather than the entire table. What is actually happening when you are removing the entities in the first step and adding them in the second is as follows:
*
*Load Entities X,Y, and Z
*Mark X,Y, and Z for deletion
*Insert new rows A, B and C
*Run SQL which deletes X, Y and Z, and inserts A, B and C
Now if two requests come in at the same time what could possibly happen is objects X,Y and Z are both loaded in step 1 by both request contexts. They are both marked for deletion and two sets of A, B and C are set to insert. When the first transaction executes it will be fine, however when the second transaction commits it will not be able to find X, Y and Z as they no longer exist.
You may be able to use a lock over the critical section so that the entities are not loaded before they are deleted by another request. The lock would have to be static so something such as:
public class SecurityRoleController : Controller
{
Repository repository = new Repository();
public static object REQUEST_LOCK = new object();
[HttpPost]
public ActionResult AssignPermisionLevel2(ICollection<SecurityroleTypePermision> list, int id)
{
lock(REQUEST_LOCK)
{
repository.DeleteSecurityroleTypePermisions(id);
foreach (var c in list)
{
repository.InsertOrUpdateSecurityroleTypePermisions(c,User.Identity.Name);
}
repository.Save();
}
return RedirectToAction("AssignPermisionLevel", new { id = id });
}
}
Update 2
There are two sides to your problem, the way SQL handles transactions and the way Entity Framework performs deletes. Without going into massive detail on threading you basically have to lock the action so that the same method cannot execute twice at exactly the same time. This will prevent the context from reading potentially stale/already deleted data.
You can read more on SQL/EF race conditions with this question: Preventing race condition of if-exists-update-else-insert in Entity Framework
| |
doc_23533901
|
I inherited a sloppy database with a table that has duplicate rows. However, they are not exact duplicates due to one column(a text column).
Here is an example:
TestID TestDescription Cost
115893hc127aaq Etiology • Understand the causes of acute pancreatitis $10
115893hc127aaq Etiology • Understand the causes of acute pancreatitis $10
115893hc127aaq Etiology • Understand the causes of acute pancreatitis $10
You can see that all the data except the 'TestDescription' is identical.
There are 1000's of rows like this where there might be 2 or 3 duplicate rows with minor spacing or spelling issues in 'TestDescription'
Because of this, using DISTINCT won't work.
I want to SELECT all rows but only get one row for each TestID...lets say the first one, then ignore the rest.
I tried SELECT DISTINCT *
But I can't do this using DISTINCT because TestDescription contains minor differences between rows.
SELECT DISTINCT TestID works, but that only returns TestID and I need to see all columns.
Is there a way of doing this in Sql Server 2012?
Thanks!
A: One approach uses row_number():
select *
from (
select t.*, row_number() over(partition by testid order by (select null)) rn
from mytable t
) t
where rn = 1
This assumes that you want one row per testid, as your question suggests.
You did not tell which column you want to use to break the ties, and I am unsure there is actually one, so I odered by (select null). This is not a deterministic order by clause, so consequent executions of the query might not always select the same row from a given duplicate group.
| |
doc_23533902
|
The code as is works, but not as it should as App.updatePerfectScrollbar(psSidebar); is executing before the animations happening before it have completed.
I do know how long each animation is and nothing is more than 200ms, but I know timeout is not the answer as you cannot be sure it finished. Is there a way to do a .done() or .promise() type method in this case?
$('#rlogo').on('click', '.rsideleft-toggler', function(e) {
//if large screen view
if( $('#sidebar-check').is(':visible') ){
//toggle minimized sidebar
if( $('body').hasClass('minimized') ) {
$('body').removeClass('minimized');
//show open submenus
App.sidebarHideSubs(false, 200, 0);
App.updatePerfectScrollbar(psSidebar); //**** only when above it is finished
} else {
$('body').addClass('minimized');
//show open submenus
App.sidebarHideSubs(true, 200, 0);
App.updatePerfectScrollbar(psSidebar); //**** only when above it is finished
}
}
//mobile view so the button needs to show sidebar and wait for click to go to page or close it
else {
//toggle mobileshow sidebar
if( $('body').hasClass('mobileshow') ) {
//close it
$('body').removeClass('mobileshow');
//close open submenus
if( $('body').hasClass('minimized') ) {
App.sidebarHideSubs(true, 0, 200);
}
App.updatePerfectScrollbar(psSidebar); //**** only when above it is finished
} else {
//show it
$('body').addClass('mobileshow');
//show open submenus
App.sidebarHideSubs(false, 0, 0);
App.updatePerfectScrollbar(psSidebar); //**** only when above it is finished
}
}
});
A: To detect if css animation is finished, animationend event can be used
var x = document.getElementById("myAnimatedElement");
// For Chrome, Safari and Opera
x.addEventListener("webkitAnimationEnd", cssAnimationEnd);
// Standard syntax
x.addEventListener("animationend", cssAnimationEnd);
// In Jquery
$("#myAnimatedElement").on('animationend webkitAnimationEnd',cssAnimationEnd)
Jquery animations accept a callback function for the same purpose
$('#myAnimatedElement').animate(
{ opacity: .5,
height: "50%"
},
400, function() {
// Animation complete.
});
You can use these techniques simultaneously to detect if both CSS and Jquery animations are finished.
$("#myAnimatedElement").on('animationend webkitAnimationEnd',cssAnimationEnd)
$('#myAnimatedElement').animate(
{ opacity: .5,
height: "50%"
},
400, jQueryAnimationEnd);
let cssAnimationFinished = false, jQueryAnimationFinished = false;
function cssAnimationEnd(){
cssAnimationFinished = true;
if( jQueryAnimationFinished ){
// Do work work here ( Call any callback function )
}
}
function jQueryAnimationEnd(){
jQueryAnimationFinished = true;
if( cssAnimationFinished ){
// Do work work here ( Call any callback function )
}
}
You can include the logic in App.sidebarHideSubs function, and pass App.updatePerfectScrollbar(psSidebar) as a callback
App.sidebarHideSubs(true, 0, 200, App.updatePerfectScrollbar(psSidebar));
A: You can use jQuery promise() to do a task after animation.
| |
doc_23533903
|
Now, I'd like to attach this document as a PDF in an email (nodemailer). I don't want to send an email with a download link to the PDF.
Can someone tell me what's the process to do so (download PDF automatically, save it somewhere)? Is it possible?
| |
doc_23533904
|
I want to fill gradient color in the area under line chart. Although I have tried available color functions in Protovis but they did not work.
Is there any simple solution for this problem?
Below is my code to add area into line chart
addArea: ->
self = this
@vis.add(pv.Area)
.data(self.data[0].values)
.bottom(1)
.left((d) -> self.xAxisUnits(d.index))
.height((d) -> self.yAxisUnits(d.value))
.fillStyle(pv.ramp('black', 'red'))
.anchor("top")
.add(pv.Line)
.lineWidth(2)
.strokeStyle("#78B9E2")
this
A: Sorry, but I'm pretty sure Protovis has no support for gradient fills. You might try D3.js, which doesn't support gradients out of the box but offers lower-level access to the SVG element, which you can use to define an svg:linearGradient fill.
| |
doc_23533905
|
Java 8 will still be supported for the first number of 3.x releases but is expected to be dropped later in 2020
How can I know precisely from with version the Java 8 support has been dropped? If I'm using Java 8, shall I work with 2.x Apache Camel versions or shall I work with 3.0 for example?
A: According to the FAQ (official) Java 8 is still supported with 3.x. If that changes they are bound to write it in the release notes. Furthermore you can always check the source. It is of course your choice, but I would go with 3.x.
| |
doc_23533906
|
You get this functionality for free when you use web services because of the stateless model, but I am building a client/server architecture where the clients are connected for the lifetime of their sessions over TCP.
How can I implement changes without disconnecting users and restarting my server? Obviously the connection management code and the API will not change otherwise that would break things very quickly.
Is it using MEF? Some kind of shadow-copy? I would prefer to NOT use message queuing and multiple processes.
A: *
*You can use MEF's Recomposition
*Abstract your server's way of getting the data to another object
*Inside this object, spin off a background thread to check for updates
*When an update becomes available, lock an object, so the client cannot get data while you're updating
Server-side public API
public SomeDataModel SomeGetDataMethod(...)
{
// auth
return someObject.GetData(); // GetData() methods abstracted
}
Server-side internal
public SomeObject
{
public SomeObject()
{
// spin off a background thread to check for updates
}
private void OnUpdateAvail()
{
lock(recomposeLock)
{
// recompose
}
}
public SomeDataModel GetData()
{
lock(recomposeLock)
{
// get your data
return someDataModel;
}
}
}
| |
doc_23533907
|
interface IGetFullnameRequest extends IAuthenticatedRequest {
readonly body: Readonly<{
fullname: string;
}>;
}
this is my controller -
const getFullname = async (req: IGetFullnameRequest, res: IGetFullnameResponse) => {
const userByFullname: Omit<IUserDocument, 'fullname'
> | null = await UserDB.findOne({ fullname: req.body.fullname });
console.log(userByFullname);
}
i am getting null - anyone know why?
A: You have to specify a function inside of the findOne method to get results,
await UserDB.findOne({ fullname: req.body.fullname }, function(err, result) { ... });
Simply, replace your code with the above one.
| |
doc_23533908
|
missingStuff <- function (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o , p,
q, r, s, t, u, v, w, x, y, z) {
...
}
I could test each like so for instance
missingStuff <- function (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o , p,
q, r, s, t, u, v, w, x, y, z) {
if(missing(a)) a <- NULL
if(missing(b)) b <- NULL
...
}
or I could have them default to NULL
missingStuff <- function (a = NULL, b = NULL, c = NULL, d = NULL, e = NULL,
f = NULL, g = NULL, h = NULL, i = NULL, j = NULL,
k = NULL, l = NULL, m = NULL, n = NULL, o = NULL,
p = NULL, q = NULL, r = NULL, s = NULL, t = NULL,
u = NULL, v = NULL, w = NULL, x = NULL, y = NULL,
z = NULL) {
...
}
But these two options are tedious and rather messy. For the life of me I cannot find a way to do this properly. Surely this could be done in a more practical manner using formals() perhaps
This does not work, it assigns everything to NULL regardless of the if statement
missingStuff <- function (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o , p,
q, r, s, t, u, v, w, x, y, z) {
lapply(formals(), function(x) {
if(missing(x)) x <- NULL
})
}
Neither does
missingStuff <- function (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o , p,
q, r, s, t, u, v, w, x, y, z) {
lapply(formals(), function(x) {
if(x == "") x <- NULL
})
}
Despite
formals(missingStuff)[1] == ""
a
TRUE
What am I missing?
A: Well you could try eval:
missingStuff <- function (a, b, c, d, e, f)
{
lapply(names(formals()), function(x)
{ eval(parse(text = paste0("if (missing(",x,")) {assign(\"",x,"\",NULL)}")), envir = parent.env(environment())) } )
# print them
for(name in names(formals())) { print(get(name)) }
}
missingStuff(a=1,f=4)
When executed, gives:
> missingStuff(a=1,f=4)
[1] 1
NULL
NULL
NULL
NULL
[1] 4
A: you should use sys.call ar match.call to extract the passed arguments.
Then you can set different conditions and update the values you'd like.
missingStuff <- function (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o , p,
q, r, s, t, u, v, w, x, y, z) {
# get the names of the passed variables
var <- names(as.list( sys.call() ))[-1]
# set all the variables that arent passed to NULL
for(i in 1:length(setdiff(names(formals(missingStuff)),var))){
assign(setdiff(names(formals(missingStuff)),var)[i],NULL)
}
# set all the arguments that are passed as "" or NULL as NULL
for(i in 1:length(var[mget(var)=="" | is.null(mget(var))])){
assign(var[mget(var)==""][i],NULL)
}
# print all the values of the arguments
mget(names(formals(missingStuff)))
}
When run for example:
missingStuff(a=,b=5,c=NULL)
You'll get a print of the arguments:
> missingStuff(a=,b=5,c=NULL)
$a
NULL
$b
[1] 5
$c
NULL
$d
NULL
...
A: Here's another way. We filter the formals to keep arguments not found in the call, thus we get a list of missing arguments, then assign NULL to all of them, and we assign the list elements to the local environment.
missingStuff <- function (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o , p,
q, r, s, t, u, v, w, x, y, z) {
fmls <- formals()
missing_fmls <- fmls[!names(fmls) %in% names(match.call()[-1])]
missing_fmls[] <- list(NULL)
list2env(missing_fmls, environment())
print(b)
print(r)
}
missingStuff()
#> NULL
#> NULL
Created on 2019-10-24 by the reprex package (v0.3.0)
| |
doc_23533909
|
And I need to keep track of all changes in the current RDS even after migrating. That's why we have chosen the MDS service.
Ex: I have an existing database in account A and a new database in account B. I need continuous migration of data from account A to account B.
Right now I am trying to achieve it was with the AWS database migration service. I couldn't find the way to select the database from another account. Please suggest if there is any better solution.
A: You can establish network between these 2 accounts(e.g vpc peering) and then use the database endpoint in the target of DMS.
A: I just made these DMS cross-account works.
First, you should create the source and target endpoint both on your Target account.
For your question, you said you couldn't select the source database (which stays on your source account) on your Target account, because you shouldn't choose Select RDS DB instance, instead, you should give the information at Endpoint configuration.
At Endpoint configuration, provide the endpoint identifier, and choose Provide access information manually, on the Server name section, give the source database hostname, which you can find at your source database stay in your source account in the connectivity & security Section.
For the target endpoint, you can simply select the database from your target account.
Make sure you can test both the source and target endpoint connection successfully at the console.
Also, create Replication instances and Database migration tasks all at the Target account.
I hope it helpful for you
| |
doc_23533910
|
I have used {%- for post in collections.featured -%} {% include 'postslist.njk' %} {%- endfor -%} but its not working.
I have added featured tag in posts
Postslist.njk - https://sourceb.in/CbfSslVH7O
A: So first off, can you confirm that featured isn't empty? If you replace the include with just:
a post<br/>
does it iterate over a few items at least? Secondly, the include you tried iterates over a variable called posts:
{% for post in postslist | reverse %}
It doesn't look like it was meant to be used as you are using it. In other words, it's meant to be included one time, not multiple times inside a loop.
| |
doc_23533911
|
Here is my code:
$result_while = mysql_query("SELECT id`
FROM afunda_eleva");
$array = array();
while ($row = mysql_fetch_array($result_while)) {
$array[] = $result_while['id'];
}
for($i=0; $i < 4; $i++)
{
echo "$array[$i]"; //Possibly error happening here!!
}
A: Gustavo mysql_query is deprecated in the newer PHP version, it is unsafe but does the job.
Instead I rather give you an answer with my favorite way of query databases
PDO it is secure and it is object-oriented.
first we need to set it up
// instance of pdo
$config['db'] = array
(
'host' => '',
'username' => '',
'password' => '',
'dbname' => ''
);
$database = new PDO('mysql:host=' . $config['db']['host'] .
';dbname=' . $config['db']['dbname'],
$config['db']['username'],
$config['db']['password']);
$database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//query with a new database object
$queryObject = $database->prepare("SELECT id
FROM afunda_eleva");
//execute sql
$queryObject ->execute();
// store the results in array
$results = $queryObject->fetchAll();
//print_r results to test
print_r($results);
//after analysing the array and how its structured define
for($i=0; $i < 4; $i++)
{
echo $results[$i]
}
try that code with your database credentials on the instance, if you want to include this in a seperate db file that gets included before calling pdo make sure you call global $database; to call upon its instance
here is a good pdo tutorials playlist, good luck
https://www.youtube.com/watch?v=XQjKkNiByCk
A: First if you wish to work with column names in your array you need to replace mysql_fetch_array with mysql_fetch_assoc.
Then you need to access the row, not the result, inside your while loop:
$array[] = $row['id'];
A: 1- To get the result you have to put $row instead $result_while['id]
2-In order to print an array you have to use print_r() or var_dump()
$result_while = mysql_query("SELECT id`
FROM afunda_eleva");
$array = array();
while ($row = mysql_fetch_array($result_while)) {
$array[] = $row;
}
echo '<pre>';
print_r($array);
echo '<pre>';
Text in a <pre> element is displayed in a fixed-width font (usually Courier), and it preserves both spaces and line breaks.
Side Note: Why shouldn't I use mysql_* functions in PHP a useful link
| |
doc_23533912
|
Here's my code:
class Person:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return "[Person = {} {} {}]".format(self.x, self.y, self.z)
def main():
n = int(input())
li = [[Person(int(x), int(y), int(z)) for x, y, z in input().split()][0] for i in range(n)]
for p in li:
print(str(p))
if __name__ == "__main__":
main()
Here's my input:
4
34 45 56
12 23 34
23 355 66666
87 67 45
But the code is not successful. The error depends on the editor, but my most recent error is:
li = [[Person(int(x), int(y), int(z)) for x, y, z in input().split()][0] for i in range(n)] ValueError: need more than 2 values to unpack
I believe it's the pesky input().split() that's causing issues.
A: Try to keep your input handling separate from your business logic.
def main():
# Phase 1: input and validation
try:
line = input()
except Exception:
sys.exit("Problem reading record count from input")
try:
n = int(line)
except ValueError:
sys.exit(f"Problem parsing record count {line}")
parameters = []
for i in range(1, n+1):
try:
line = input()
except Exception:
sys.exit(f"Problem reading record {i} from input")
try:
x, y, z = map(int, line.strip().split())
except Exception:
sys.exit(f"Problem parsing record {i}: {line}")
parameters.append((x, y, z))
# Phase 2: Business logic
li = [Person(*t) for t in parameters] # or Person(x, y, z) for x, y, z in parameters]
for p in li:
print(str(p))
You can do as little or as much input validation as you like during the first phase. Assuming you haven't encountered any errors leading to program exit, you can safely create your list of Person objects.
A: By using input().split() you're creating a list with 3 elements, one for each word in the string. If you want to achieve the wanted unpacking you need to separate the loop from the unpacking with another function for your external loop, like this one:
class Person:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __str__(self):
return "[Person = {} {} {}]".format(self.x, self.y, self.z)
def unpackSplit():
x,y,z = input().split()
return Person(int(x), int(y), int(z))
def main():
n = int(input())
li = [unpackSplit() for i in range(n)]
for p in li:
print(str(p))
if __name__ == "__main__":
main()
| |
doc_23533913
|
Whether I use the .not() filter or the :not() selector, the element I'm trying to filter out is STILL part of the selection when I filter by class name. However, if I try to filter it out based on its id, it works fine.
Here are the selectors:
console.log( $( 'body > *' ).not( '.fullscreen, script' ) ); // div.fullscreen is STILL part of the selection
console.log( $( 'body > *' ).not( '#searchWindow, script' ) ); // div.fullscreen is gone, like I wanted
console.log( $( 'body > *:not(.fullscreen, script)' ) ); // div.fullscreen is STILL part of the selection
console.log( $( 'body > *:not(#searchWindow, script)' ) ); // div.fullscreen is gone, like I wanted
How come the class selector is without effect in this situation?
Here is a jsfiddle of it.
A: You've spelt fullscreen wrong in your HTML. It has three l's in it.
See here:
<div id="searchWindow" class="fulllscreen">
Fixed Demo
| |
doc_23533914
|
The box shadow for each button is simply:
box-shadow: 0 0 0 0.2rem rgba(134,142,150,.5)
Is there a way that we could prevent this? It looks broken, specially when more than two buttons are adjacent.
A: If you want the box shadows to overlap into one consistent color, you can do the following:
box-shadow: 0 0 0 0.2rem rgb(194,198,202)
If you do not want the box shadows to overlap, you can the the following:
.btn-secondary:not([disabled]):not(.disabled).active {
box-shadow:
0 -0.2rem rgba(134,142,150,.5),
0 0.2rem rgba(134,142,150,.5);
}
label.btn-secondary:not([disabled]):not(.disabled).active:first-child {
box-shadow:
-0.2rem 0 0 0.2rem rgba(134,142,150,.5);
}
label.btn-secondary:not([disabled]):not(.disabled).active:last-child {
box-shadow:
0.2rem 0 0 0.2rem rgba(134,142,150,.5);
}
| |
doc_23533915
|
I have a chart, and my goal is to place the carousel left, right always verical aline center (50% from the top), and position both arrows about 5% away, but close enough to the graph.
I have a hard time getting this to work.
I've tried
HTML
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-6">
<div class="panel panel-filled">
<div class="panel-body carousel">
<h1>Network Bandwidth</h1>
<div id="chart1Carousel" class="carousel slide" data-ride="carousel">
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active"><div class="chartjs-size-monitor"><div class="chartjs-size-monitor-expand"><div class=""></div></div><div class="chartjs-size-monitor-shrink"><div class=""></div></div></div>
<small class="lastSelectedMenu">
<span> Current Interval:
<span class="lastSelected" style="color: rgb(255, 235, 59);">day (3/25/2020)</span>
</span>
<select name="last" class="float-right">
<option id="default" value="default">Select Interval</option>
<option value="day">Day</option>
<option value="week">Week</option>
<option value="month">Month</option>
<option value="year">Year</option>
</select>
</small>
<canvas width="558" height="279" id="chart1" style="display: block; width: 558px; height: 279px;" class="chartjs-render-monitor"></canvas>
</div>
</div>
<!-- Left and right controls -->
<a class="left carousel-control" href="#chart1Carousel" data-slide="prev">
<span class="fa fa-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#chart1Carousel" data-slide="next" style="display: block;">
<span class="fa fa-chevron-right"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
</div>
</div>
CSS
@media screen and (min-width: 768px)
/* .carousel-control .fa-chevron-left {
margin-left: -10px;
}*/
@media screen and (min-width: 768px)
.carousel-control .fa-chevron-left, .carousel-control .fa-chevron-right {
position: absolute;
width: 30px;
height: 30px;
font-size: 30px;
top: 50%;
}
.carousel-control .fa-chevron-left {
margin-left: -70px;
margin-top: 120px;
}
.carousel-control .fa-chevron-right{
margin-right: -1200px;
margin-top: 120px;
}
.carousel {
position: relative;
}
.carousel-inner {
position: relative;
width: 100%;
overflow: hidden;
}
.carousel-control.left, .carousel-control.right {
background: none;
}
.carousel-control {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 30px;
font-size: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0,0,0,.6);
background-color: rgba(0,0,0,0);
filter: alpha(opacity=50);
opacity: .5;
}
https://codepen.io/sn4k3eye/project/editor/Akyrky
If you can spot my issue base on looking at my HTML & CSS, please say something.
A: I noticed a couple things and your codepen was read-only so I moved it to a new pen:
*
*Your @media styles aren't wrapped in {} so those weren't getting applied.
*You were trying to move the .fa-chevrons, but they are span elements and margin wasn't going to work.
Here's the complete code you had - without the base CSS, as the stack snippet has a character limit. My codepen link has all of it.
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.4.1/cerulean/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
.item img {
width: 100%;
height: auto;
}
.carousel {
padding-left: 45px;
padding-right: 45px;
}
.carousel-control .fa-chevron-left,
.carousel-control .fa-chevron-right {
position: absolute;
width: 30px;
height: 30px;
font-size: 30px;
top: 50%;
display: block;
transform: translate(0, -50%;
)
}
.carousel-control.right {
right: 0;
left: auto;
}
.carousel-control .fa-chevron-left {}
.carousel-control .fa-chevron-right {}
.carousel {
position: relative;
}
.carousel-inner {
position: relative;
width: 100%;
overflow: hidden;
}
.carousel-control.left,
.carousel-control.right {
background: none;
}
.carousel-control {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 30px;
font-size: 20px;
color: #fff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
background-color: rgba(0, 0, 0, 0);
filter: alpha(opacity=50);
opacity: .5;
}
</style>
<div class="col-xs-4">
<div class="panel panel-filled">
<div class="panel-body carousel">
<h1>Carousel Issue</h1>
<div id="chart1Carousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="item active">
<div class="chartjs-size-monitor">
<div class="chartjs-size-monitor-expand">
<div class=""></div>
</div>
<div class="chartjs-size-monitor-shrink">
<div class=""></div>
</div>
</div>
<img src="https://i.imgur.com/ltw5Pac.png" width="558" height="279">
</div>
</div>
</div>
<!-- Left and right controls -->
<a class="left carousel-control" href="#chart1Carousel" data-slide="prev">
<span class="fa fa-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#chart1Carousel" data-slide="next" style="display: block;">
<span class="fa fa-chevron-right"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
</div>
You'll see I added a little padding around the chart to show how the arrows will set next to the chart.
The biggest thing is changing the chevrons to block elements and moving them up 50% of their height (15px up).
https://codepen.io/chrislafrombois/pen/RwPqdxj
Hopefully this helps you in the right direction. Let me know if missed what you are trying to do.
| |
doc_23533916
|
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.GetCurrent(this).RegisterPostBackControl(ChangeBannerButton);
}
Everything works fine (the banner is being uploaded properly) when FileUpload is on the first page (no postback, just enter the URL). When it's on the second page (I access it by clicking menu button - AJAX postback), it doesn't work.
I know why it doesn't work (binding is lost), however I have no idea how to fix it. Thanks in advance for help.
A: Surprisingly fixed it by adding to Page_Load:
Page.Form.Attributes.Add("enctype", "multipart/form-data");
| |
doc_23533917
|
However, as there are numerous subpages, I would like to rearrange them in subfolders. However, when loading a subpage, my header.html will not load the image unless i change the path to '../images/image.png'. Doing so will cause the same problem when loading the index.html after this path change.
A simplified site structure and codes for each file is shown below. can anyone give me some advice on how to overcome this problem?
Thanks alot in advance!
My site structure:
common/
header.html
images/
image.png
js/
jquery-1.11.1.min.js
subpages/
page1.html
index.html
my codes for the pages:
index.html
<!DOCTYPE html>
<html>
<head>
<title>A site</title>
<script src="js/jquery-1.11.1.min.js" type="text/javascript"></script>
</head>
<body>
<div id="header"></div>
</body>
<script type="text/javascript">
$('#header').load('common/header.html')
</script>
</html>
header.html
<div id='logo'><img src='images/image.png' alt="image"></img></div>
<h1> This is header </h1>
<div id='subpage'><a href='subpages/page1.html'>Page 1</a></div>
page1.html
<!DOCTYPE html>
<html>
<head>
<title>This is a subpage</title>
<script src="../js/jquery-1.11.1.min.js" type="text/javascript"</script>
</head>
<body>
<div id="header"></div>
<h1> This is a subpage </h1>
</body>
<script type="text/javascript">
$('#header').load('../common/header.html')
</script>
</html>
A: By using a script, try this one :
<script type="text/javascript">
var nom = window.location.pathname;
nom = nom.split("/");
nom = nom[nom.length - 1];
nom = nom.substr(0, nom.lastIndexOf("."));
nom = nom.replace(new RegExp("(%20|_|-)", "g"), " ");
if (nom == "index") {
document.write("<div id='logo'><img src='images/image.png' alt=\"image\"></img></div><h1> This is header </h1><div id='subpage'><a href='subpages/page1.html'>Page 1</a></div>");
} else {
document.write("<div id='logo'><img src='../images/image.png' alt=\"image\"></img></div><h1> This is header </h1><div id='subpage'><a href='subpages/page1.html'>Page 1</a></div>");
}
</script>
Tell me if it's working, and you can create a js file for your code to be cleaner
to understand,
var nom = window.location.pathname;
nom = nom.split("/");
nom = nom[nom.length - 1];
nom = nom.substr(0, nom.lastIndexOf("."));
nom = nom.replace(new RegExp("(%20|_|-)", "g"), " ");
this permit to the server to know which page is loaded, and the rest is for using the best url to have your image. if it's not "index", it will use the path "../images/image.png"
| |
doc_23533918
|
import pymysql as db
ModuleNotFoundError: No module named pymysql
Within Terminal...
python --version
Python 3.8.5
sudo apt-get install python3-pymysql
python3-pymysql is already the newest version (0.9.3-2ubuntu3).
pip3 install PyMySQL
Requirement already satisfied: PyMySQL in /usr/lib/python3/dist-packages (0.9.3)
Within Python...
import pymysql as db
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
Any help would be appreciated.
A: use python -m pip install pymysql
that used the pip for the Python interpreter you specified as python
A: sudo systemctl stop gunicorn
source env/bin/activate
python -m pip install pymysql
deactivate
sudo systemctl start gunicorn
works for me.
| |
doc_23533919
|
{
"_embedded": {
"analytics": {
"originCode": "PRD"
},
"product": {
"id": "wi412784",
"description": "AH Waterfles met infuser blauw (500 ml)",
"unitSize": "per stuk",
"brandName": "AH",
"categoryName": "Koken, tafelen, non-food/Bidon",
"availability": {
"orderable": true,
"label": "Leverbaar"
},
"priceLabel": {
"now": 3.49,
"was": 4.99
},
"discount": {
"type": {
"name": "BONUS"
},
"label": "30% korting"
},
"images": [{
"title": "Waterfles met infuser blauw (500 ml)",
"width": 80,
"height": 80,
"link": {
"href": "https://www.ah.nl.kpnis.nl/static/product/AHI_434d50323838313031_1_80x80_JPG.JPG"
}
}, {
"title": "Waterfles met infuser blauw (500 ml)",
"width": 200,
"height": 200,
"link": {
"href": "https://www.ah.nl.kpnis.nl/static/product/AHI_434d50323838313031_1_200x200_JPG.JPG"
}
}, {
"title": "Waterfles met infuser blauw (500 ml)",
"width": 708,
"height": 708,
"link": {
"href": "https://www.ah.nl.kpnis.nl/static/product/AHI_434d50323838313031_1_LowRes_JPG.JPG"
}
}, {
"title": "Waterfles met infuser blauw (500 ml)",
"width": 48,
"height": 48,
"link": {
"href": "https://www.ah.nl.kpnis.nl/static/product/AHI_434d50323838313031_1_48x48_GIF.GIF"
}
}]
}
}
}
Inside product I want to get the href String of the last image.
On the Jsonpath evaluator websites that I know:
http://jsonpath.com/ and http://jsonpath.herokuapp.com/ this
$._embedded.[?(@.id)].images[2].link.href is valid JSON and returns the href.
Trying this inside Jayway JsonPath won't work and returns an emtpy List. To get it working I need to do have this query $..[?(@.id)].images[2].link.href
Why isn't the first query valid inside Jayway JsonPath?
Edit:
This is my test method
@Test
public void getImgSrc() {
String jsonData = "{\"_embedded\": {\"analytics\": {\"originCode\": \"PRD\"},\"product\": {\"id\": \"wi412784\",\"description\": \"AH Wa\u00ADter\u00ADfles met in\u00ADfu\u00ADser blauw (500 ml)\",\"unitSize\": \"per stuk\",\"brandName\": \"AH\",\"categoryName\": \"Koken, tafelen, non-food/Bidon\",\"availability\": {\"orderable\": true,\"label\": \"Leverbaar\"},\"priceLabel\": {\"now\": 3.49,\"was\": 4.99},\"discount\": {\"type\": {\"name\": \"BONUS\"},\"label\": \"30% korting\"},\"images\": [ {\"title\": \"Waterfles met infuser blauw (500 ml)\",\"width\": 80,\"height\": 80,\"link\": {\"href\": \"https://www.ah.nl.kpnis.nl/static/product/AHI_434d50323838313031_1_80x80_JPG.JPG\"}},{\"title\": \"Waterfles met infuser blauw (500 ml)\",\"width\": 200,\"height\": 200,\"link\": {\"href\": \"https://www.ah.nl.kpnis.nl/static/product/AHI_434d50323838313031_1_200x200_JPG.JPG\"}},{\"title\": \"Waterfles met infuser blauw (500 ml)\",\"width\": 708,\"height\": 708,\"link\": {\"href\": \"https://www.ah.nl.kpnis.nl/static/product/AHI_434d50323838313031_1_LowRes_JPG.JPG\"}},{\"title\": \"Waterfles met infuser blauw (500 ml)\",\"width\": 48,\"height\": 48,\"link\": {\"href\": \"https://www.ah.nl.kpnis.nl/static/product/AHI_434d50323838313031_1_48x48_GIF.GIF\"}}]}}}";
DocumentContext cxt = JsonPath.parse(jsonData);
List<String> href = cxt.read("$._embedded.[?(@.id)].images[2].link.href");
Assert.assertEquals("https://www.ah.nl.kpnis.nl/static/product/AHI_434d50323838313031_1_LowRes_JPG.JPG", href.get(0));
}
A: You are missing product in your path.
This will work -
List<String> href = cxt.read("$._embedded.product[?(@.id)].images[2].link.href");
| |
doc_23533920
|
Error I got in IIS
The folder I'm talking about is here:
This is where I have the static files folder
And this is how I'm telling the application that I have a static files folder in the server-side:
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "upload")),
RequestPath = "/upload"
});
I hope some of you guys can help me.
A: You just have to create the upload folder by your own in your application folder.
| |
doc_23533921
|
In which case, when would I absolutely need to use a queue over a topic?
For consistency, could I use a topics everywhere including as a replacement for queues?
A: A topic is not a replacement for a queue. The combination of a topic and a subscription is. A topic is allowing to “replicate” the same message to multiple subscriptions. A subscription what actually holds messages. A subscription is identical to a queue in its attributes and behaviour. You could replace a queue with a topic+subscription combo if you’d like, generating 2 entities per use case instead of a single queue. Just keep in mind there’s a finite number of entities per namespace.
| |
doc_23533922
|
Do you know a simple way (as SQL request) to check if a request send to Postgres is in SSL Tunnel? I use JDBC.
My application support SSL. I need it in order to realise a test. I didn't find something interesting but I could miss some information!
Thank you very much!
| |
doc_23533923
|
I tried:
for idx in itertools.product(range(1,m-1+1),repeat=p)
It already takes some time for m=10 and p=m-1=9. Must be possible to do much better.
A: You should look at the itertools.product function and adapt it to your needs.
Because of the condition k_1+k_2+...+k_{p-1}+k_p <= m, instead of calculating all possible combinations in the cartesian product and filter afterwards, break the loop each time the sum already goes beyond your limit m, since adding a bigger integer instead in the next iteration will also pass over the limit. Depending on your input numbers it will be much faster.
The original source:
https://docs.python.org/2/library/itertools.html#itertools.product
def product(*args, **kwds):
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
I would try something along these lines:
def product2(*args, **kwds):
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
temp = [[]]
for x in result:
for y in pool:
z = x+[y]
if sum(z) > m:
break
else:
temp.append(z)
result = temp
for prod in result:
yield tuple(prod)
Test (runs fast):
m = 10
p = 9
k = range(1,m-1+1)
for x in product2(k,repeat=p):
print x
Not sure if you want only tuples of exactly p values, though, but you seem to expect the same behavior as with product, so here it is.
| |
doc_23533924
|
const { shortId, p_shortId } = req.params;
const { comment } = req.body;
const email = req.tokenInfo.email;
try {
const authData = await User.findOne({email});
const postData = await Post.findOne({shortId});
const parentData = await Upment.findOne({p_shortId});
const newcomment = await Downment.create({
postType: 3,
author: authData,
post_id: postData,
parentment_id: parentData,
comment: comment
});
await Upment.updateOne({p_shortId}, {"$push": {"comments": newcomment._id}});
res.status(200).json({
result: 'recomment success'
})
} catch (err) {
err.message = `${err.message}, market post recomment error.`;
next(err);
}
});
updateOne doesn't work so I changed it to update
router.post("/list/:shortId/comment", async (req, res, next) => {
const { shortId } = req.params;
const { comment } = req.body;
const email = req.tokenInfo.email;
try {
const authData = await User.findOne({email});
const postData = await Post.findOne({shortId});
const newcomment = await Upment.create({
postType: 3,
author: authData,
post_id: postData,
comment: comment
});
// console.log(commentData);
await Post.updateOne({shortId}, {"$push": {"comments": newcomment._id}});
res.status(200).json({
result: 'comment success'
})
} catch (err) {
err.message = `${err.message}, market post comment error.`;
next(err);
}
});
then it worked. So I tried it in mongoDB Compass. like below
db.upments.updateOne({shortId: "wEhPg-wFqS0_2935vuZEQ"}, {"$push": {"comments": new ObjectId("62f38170e3dccbfe7a9842b2")}})
And this worked...
Only in the code, updateOne worked properly why this thing happens? how should I fix it?
thank you for listening question!!
here are schemas ^^ if you need anything more, let me know~
import mongoose from "mongoose"
import shortId from "./type/shortId.js"
const UpmentSchema = new mongoose.Schema({
shortId,
comment: String,
// closet:1, OOTD:2, board:3
postType: {
type: Number,
required: true
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true
},
post_id: {
type : mongoose.Schema.Types.ObjectId,
ref: "Post",
required: true
},
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Downment",
}]
}, {
timestamps: true
}
);
const DownmentSchema = new mongoose.Schema({
shortId,
comment: String,
// closet:1, OOTD:2, board:3
postType: {
type: Number,
required: true
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true
},
post_id: {
type : mongoose.Schema.Types.ObjectId,
ref: "Post",
required: true
},
parentment_id: {
type : mongoose.Schema.Types.ObjectId,
ref: "Upment",
required: true
},
}, {
timestamps: true
}
);
export const Upment = mongoose.model("Upment", UpmentSchema);
export const Downment = mongoose.model("Downment", DownmentSchema);
A: It was an error in update({p_shortId})
p_shortId is not in the upment model
await Post.updateOne({shortId}, {"$push": {"comments": newcomment._id}});
my mistake ^^...
| |
doc_23533925
|
The goal of the AlarmManager/BroadcastReceiver combination is to perform a periodic call to a REST API which is determined by the user location.
Service code
The onHandleIntent method of the service is called by a WakefulBroadcastReceiver with startWakefulService
@Override
protected void onHandleIntent(Intent intent) {
if (BuildConfig.DEBUG) Log.d(TAG, "Handling intent");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setSpeedRequired(false);
criteria.setCostAllowed(true);
String provider = locationManager.getBestProvider(criteria, true);
boolean localizationPermitted = ContextCompact.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED;
if (localizationPermitted) {
Location lastLocation = locationManager.getLastKnownLocation(provider);
if (BuildConfig.DEBUG) Log.d(TAG, "Location: " +lastLocation.toString() );
// stuff that needs the location
} else {
if (BuildConfig.DEBUG) Log.e(TAG, "Localization not allowed");
}
}
Manifest Permissions
I've declared the permissions in the AndroidMainfest.xml file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" ...">
...
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
...
</manifest>
Dynamic permission
I ask for the permission inside a Fragment of the application, before starting the alarm which triggers the service:
boolean gotPermission = ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED;
if (gotPermission){
if (BuildConfig.DEBUG) Log.v(TAG, "Got the permission");
// Schedule the alarm
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
and in the dialog's callback i got the "Permission granted":
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (permissions.length == 1 &&
permissions[0].equals(android.Manifest.permission.ACCESS_COARSE_LOCATION) &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (BuildConfig.DEBUG) Log.d(TAG, "Permission granted");
}
} else {
if (BuildConfig.DEBUG) Log.e(TAG, "Permission not granted");
}
}
A: boolean localizationPermitted = ContextCompact.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED;
This will be true if the permission is not granted (!=). Change this to:
boolean localizationPermitted = ContextCompact.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
(and I really wish they had just used a boolean return value from checkSelfPermission()...)
| |
doc_23533926
|
I'm using Pages, along with ACF (Advanced Custom Fields) to develop the theme (in case that's relevant). I have a couple page templates, one for the homepage, and one for inner pages. I've told Wordpress to use the Page "News" (/news) as the index for the blog/posts pages.
So we're using something.com, and we'd like to have blog.something.com utilize the /news content, and, have all that content maintain the subdomain URL while browsing the content of the post(s).
Is this is a multi-site thing? Can it be done with DNS alone?
Any help is appreciated.
| |
doc_23533927
|
I follow the steps in the following blogs:
One size doesn't fit all: One-Way SSL with JAX-WS using JDeveloper 11gR1 and WLS 10.3.1
Gerard Davison's Blog: Security Policy Worked Example
All steps works fine for me. But the connection is not establish.
I have key store and self-signed certificate for both client and server. I exchange the certificates between the client and server. So, each one of them have the certificate of the other in his keystore file as trusted certificate.
From the client side I am trying to call the server from the auto generated port class by Jdeveloper where every thing is setup, all what I need is to fill the values for username, password, keyStore,...... etc.
But I am getting the following exception in the client side.
java.lang.SecurityException: Can not find public key for alias: "serversidecert"
at weblogic.wsee.security.util.CertUtils.getCertificate(CertUtils.java:106)
at testClient.TestWSPortClient.getBSTCredentialProvider(TestWSPortClient.java:97)
at testClient.TestWSPortClient.setPortCredentialProviderList(TestWSPortClient.java:71)
at testClient.TestWSPortClient.main(TestWSPortClient.java:41)
Note 1: I am not able to reach the server yet, this exception is happening at the client side.
Note 2: The error indicate that system could not find the public key of the specified alias. What I know that the public key is included in the certificate. So when the certificate is added to the trusted keystore everything should go smoothly(Correct me if I am wrong).
------------------------------- EDIT-------------------------------------
I figure out that I am doing something wrong in the code because the application worked from Http Analyzer in Jdeveloper. But I am not seeing what is wrong in the code.
The following is the auto generated port class from Jdeveloper and the values a fill it in:
Note 3: ClientSideKeyStore.jks is the keystore for the client and it contains the self-signed certificates for the client and the server certificate as trusted certificated
public class TestWSPortClient
{
@WebServiceRef
private static TestWSService testWSService;
public static void main(String[] args) {
try {
testWSService = new TestWSService();
TestWS testWS = testWSService.getTestWSPort();
Map<String, Object> requestContext = ((BindingProvider) testWS).getRequestContext();
setPortCredentialProviderList(requestContext);
Add your code to call the desired methods.
System.out.println("Client Side: "+testWS.sayhi("Testing Message"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Generated("Oracle JDeveloper")
public static void setPortCredentialProviderList(Map<String, Object> requestContext) throws Exception {
// TODO - Provide the required values
String username = "weblogic";
String password = "welcome1";
String clientKeyStore = "C:\\Client_Server\\ClietSide\\ClientSideKeyStore.jks";
String clientKeyStorePassword = "changeit";
String clientKeyAlias = "clientsidecert";
String clientKeyPassword = "changeit";
String serverKeyStore = "C:\\Client_Server\\ClietSide\\ClientSideKeyStore.jks";
String serverKeyStorePassword = "changeit";
String serverKeyAlias ="serversidecert";
List<CredentialProvider> credList = new ArrayList<CredentialProvider>();
// Add the necessary credential providers to the list
credList.add(getUNTCredentialProvider(username, password));
credList.add(getBSTCredentialProvider(clientKeyStore, clientKeyStorePassword, clientKeyAlias, clientKeyPassword, serverKeyStore, serverKeyStorePassword, serverKeyAlias, requestContext));
credList.add(getSAMLTrustCredentialProvider());
requestContext.put(WSSecurityContext.CREDENTIAL_PROVIDER_LIST, credList);
}
@Generated("Oracle JDeveloper")
public static CredentialProvider getSAMLTrustCredentialProvider() {
return new SAMLTrustCredentialProvider();
}
@Generated("Oracle JDeveloper")
public static CredentialProvider getUNTCredentialProvider(String username,
String password) {
return new ClientUNTCredentialProvider(username.getBytes(), password.getBytes());
}
@Generated("Oracle JDeveloper")
public static CredentialProvider getBSTCredentialProvider(String clientKeyStore,
String clientKeyStorePwd,
String clientKeyAlias,
String clientKeyPwd,
String serverKeyStore,
String serverKeyStorePwd,
String serverKeyAlias, Map<String, Object> requestContext) throws Exception {
List serverCertList =
CertUtils.getCertificate(serverKeyStore, serverKeyStorePwd, serverKeyAlias, "JKS");
List clientCertList =
CertUtils.getCertificate(clientKeyStore, clientKeyStorePwd, clientKeyAlias, "JKS");
final X509Certificate serverCert =
(serverCertList != null && serverCertList.size() > 0) ? (X509Certificate) serverCertList.get(0) : null;
final X509Certificate clientCert =
(clientCertList != null && clientCertList.size() > 0) ? (X509Certificate) clientCertList.get(0) : null;
requestContext.put(WSSecurityContext.TRUST_MANAGER, new TrustManager()
{
public boolean certificateCallback(X509Certificate[] chain,
int validateErr)
{
boolean result = (chain != null && chain.length > 0)
&& (chain[0].equals(serverCert) || chain[0].equals(clientCert));
return result;
}
});
return new ClientBSTCredentialProvider(clientKeyStore, clientKeyStorePwd, clientKeyAlias, clientKeyPwd, "JKS", serverCert);
}
}
A: Verify if the file C:\\Client_Server\\ClietSide\\ClientSideKeyStore.jks is readable by the client and if it really contains the certificate with the alias serversidecert:
keytool -list -v -keystore C:\\Client_Server\\ClietSide\\ClientSideKeyStore.jks -alias serversidecert
That said, are you sure that the client certificate ClientSideKeyStore is the server certificate that's needed here?
On the Weblogic doc, the server side certificates are (usually) initialized differently without the alias parameter. Perhaps you could try this as well:
X509Certificate serverCertInit = (X509Certificate) CertUtils.getCertificate(serverKeyStore);
| |
doc_23533928
|
Something like this?
$(document).ready(function(){
$('body').animate({backgroundColor:'#ffcc00'}, 500, function(){
$('body').animate({backgroundColor:'#eeeeee'}, 500, function(){
$('body').animate({backgroundColor:'#3b5998'}, 500);
});
});
});
Any idea?
A: $(document).ready(function(){
colors = ['#FFB30C', '#58EC00', '#0087EC', '#EEEEEE', '#FF5A00' ]
var i = 0;
animate_loop = function() {
$('body').animate({backgroundColor:colors[(i++)%colors.length]
}, 500, function(){
animate_loop();
});
}
animate_loop();
});
Demo: http://jsfiddle.net/bHEVr/
A: $(".elementsToAnimate").each(function setAnim(){
$(this).
animate({backgroundColor:'#ffcc00'},500).
animate({backgroundColor:'#eeeeee'},500).
animate({backgroundColor:'#3b5998'},500,setAnim);
});
A: I would rather use an event-driven approach:
$(document).ready(function(){
$('body').on('color1', function () {
$(this).animate({backgroundColor:'#ffcc00'}, 500, function(){
$(this).trigger('color2');
});
});
$('body').on('color2', function () {
$(this).animate({backgroundColor:'#eeeeee'}, 500, function(){
$(this).trigger('color3');
});
});
$('body').on('color3', function () {
$(this).animate({backgroundColor:'#3b5998'}, 500, function(){
$(this).trigger('color1');
});
});
// Kick-off the infinite loop by firing one of the events
$('body').trigger('color2');
});
Watch this solution in action:
http://jsfiddle.net/perituswebdesign/f5qeo6db/1/
A: Call the animate functions in the callback of animate().
See this example in the jQuery forum
jQuery.fn.fadeInOut = function() {
var newOpacity = this.is(":visible") ? 0 : 1;
this.animate({ opacity: newOpacity }, function() {
$(this).fadeInOut();
});
return this;
};
$("#mydiv").fadeInOut();
A: $(document).ready(function(){
function animate() {
$('body').animate({backgroundColor:'#ffcc00'}, 500, function(){
$('body').animate({backgroundColor:'#eeeeee'}, 500, function(){
$('body').animate({backgroundColor:'#3b5998'}, 500, function(){
animate();
});
});
});
}
animate();
});
A: You can eliminate the nesting, but the solution is a little fatter:
var cols = "#ffcc00,#eeeeee,#3b5998".split(",")
var cPos = 0
$(document).ready(function() {
swapC()
}
function swapC() {
$('body').animate({ backgroundColor:cols[cPos] }, 500)
cPos++
if (cPos == cols.length) {
cPos = 0
}
window.setTimeout(function() { swapC() }, 500)
}
A: function blabla(){
$('body').animate({backgroundColor:'#ffcc00'}, 500, function(){
$('body').animate({backgroundColor:'#eeeeee'}, 500, function(){
$('body').animate({backgroundColor:'#3b5998'}, 0,function (){
setTimeout(blabla,500);
});
});
});
}
UNTESTED
A: Try this : http://jsfiddle.net/hBBbr/
$(document).ready(function(){
animate_loop = function animate_loop(){
$( "#animated_banner" ).animate({
opacity: 0.1,
}, 1000,function(){
$( "#animated_banner").animate({ opacity: 1},1000)
animate_loop();
} );
}
animate_loop();
});
A: I highly recommend the jQuery timing plugin (2KB) (GitHub & Docs).
It provides easy-to-use infinite animations and much more. Have a look:
$(document).ready(function(){
$('body').animate({backgroundColor:'#ffcc00'}).wait(500)
.animate({backgroundColor:'#eeeeee'}).wait(500)
.animate({backgroundColor:'#3b5998'}).wait(500)
});
A: I know it's years later but I think this could still be a problem for someone just like it was for me with jquery v1.10.2.
Anyway, after a few hours of trying to deal with it, I ended up using the following code for multiple layered backgrounds with this plugin:
// Self-calling functions for animation auto-repeat
var cssanimfx={
bgb:function(o){
o=$(o?o:this);
o.css({backgroundPosition:'0px 0px'}).animate({backgroundPosition:"3000px -3000px"},500000,'linear',cssanimfx[o.attr('id')]);
},
bgm:function(o){o=$(o?o:this);o.css({backgroundPosition:'0px 0px'}).animate({backgroundPosition:"3000px -3000px"},250000,'linear',cssanimfx[o.attr('id')])},
bgf:function(o){o=$(o?o:this);o.css({backgroundPosition:'0px 0px'}).animate({backgroundPosition:"3000px -3000px"},50000,'linear',cssanimfx[o.attr('id')])}
// ...
}
// Initialize animation
for(id in cssanimfx)cssanimfx[id]('#'+id);
The naming scheme is as follows: I create nested DIVs and give them IDs in the HTML. In the JS part, the same IDs are used for keying the properties in the object containing all the self-calling-on-animation-finish functions. Demo here.
| |
doc_23533929
|
class B extends A
object B extends B
Where A is an abstract class in another file:
abstract class A {
def main(args: Array[String]): Unit = println("hey")
}
The above code is packaged into an uber-jar using the sbt assembly plugin, where the entry point is object B main method inherited from class B.
The above works fine. It runs. No problem at all.
Hoewver, sbt keeps warning:
[warn] B has the main method with parameter type Array[String], but B will not be a runnable program.
[warn] Reason: companion contains its own main method, which means no static forwarder can be generated.
[warn] object B extends B
*
*Do you know the meaning of this warning?
*And why sbt assurance that object B won't run, doesn't happen?
Thank you.
A: For a class to be runnable in java, main needs to be static. Yours isn't, so, the object isn't runnable. That's what compiler is telling you.
Just rename main in A to something else, and then add a main in the object, that calls it.
A: It does not run for me.
I have this file B.scala.
package foo.bar
abstract class A {
def main(args: Array[String]): Unit = println("hey")
}
class B extends A
object B extends B
When I try to run foo.bar.B I get an error:
sbt> runMain foo.bar.B
[info] running foo.bar.B
[error] (run-main-0) java.lang.NoSuchMethodException: foo.bar.B.main is not static
And the reason is exactly as the warning says. Class B contains a non-static main method which it inherited from class A. You can't have 2 methods with exactly the same name and type signature in one class, even if one is static and another in non-static. This means that the compiler cannot generate a static main method in class B that forwards to the non-static main method in object B.
Why it does run correctly for you I don't know.
It's not so hard to avoid this problem. Just don't use the companion object as an entrypoint. I.e. rename either class B or object B.
package foo.bar
abstract class A {
def main(args: Array[String]): Unit = println("hey")
}
class BClass extends A
object B extends BClass
| |
doc_23533930
|
This code worked perfectly in the 3.0 version of this app. I'm hoping someone can spot out what I'm missing. The first several files I've shown in the code below are configuration files. Again, this stuff worked fine in previous deploys. I'm baffled.
The "controller mixin" is a module that is mixed into any controller that wants to send mail. The controllers do almost exactly the same thing so all I have to change is the mailers and the views.
I'm stumped how to proceed even debugging this. I know I can specify more detailed smtp settings but this worked fine before and it is resilient once I prop this in DNS, not relying on a particular hostname.
Any thoughts are most appreciated!
production.rb
# other non-mailer stuff elided.
config.action_mailer.default_url_options = { :host => `hostname` }
ActionMailer::Base.default(:charset => 'utf-8')
ActionMailer::Base.perform_deliveries = true
config/initializers/setup_mail.rb
require 'development_mail_interceptor'
Mail.register_interceptor(DevelopmentMailInterceptor) if Rails.env.development?
lib/development_mail_interceptor.rb
class DevelopmentMailInterceptor
def self.delivering_email(message)
message.subject = "[#{message.to}] #{message.subject}"
message.to = "my.address@gmail.com"
end
end
Controller mixin (this is in a module that is mixed into controllers that do mail):
def send_detail_email
@detail_email = @mailer_klass.sent(@ar_obj, session)
end
def send_confirm_email
@confirm_email = @mailer_klass.confirm(@ar_obj, session)
end
def send_email
send_detail_email
# Field naming is inconsistent, so sniff out the contact type
contact_type = ''
contact_type = @ar_obj.contact if @ar_obj.respond_to?(:contact)
contact_type = @ar_obj.best_contact_method if @ar_obj.respond_to?(:best_contact_method)
contact_type = @ar_obj.contact_method if @ar_obj.respond_to?(:contact_method)
# If no contact type, then it's probably assumed a user object's email
contact_type = 'email' if @ar_obj.respond_to?(:user) &&
!@ar_obj.respond_to?(:contact) &&
!@ar_obj.respond_to?(:best_contact_method) &&
!@ar_obj.respond_to?(:contact_method)
send_confirm_email if contact_type == 'email'
end
| |
doc_23533931
|
app.post("/cb", (req, res) => {
const { loginuser, userid, ischecked } = req.body;
if (ischecked) {
console.log("flag is true");
db.transaction(trx => {
trx
.insert({
id: loginuser,
connections: userid
})
.into("networkusers")
.returning("id", "connections")
.then(() => {
console.log("committing");
trx.commit();
})
.catch(error => {
console.log("error", error);
trx.rollback();
});
}).catch(err => res.status(400).json(err));
} else {
console.log("flag is false");
db.transaction(trx => {
db("networkusers")
.where("id", "=", loginuser)
.andWhere("connections", "=", userid)
.del()
.returning("id", "connections")
.then(() => {
console.log("committing");
console.log(loginuser,userid)
trx.commit();
})
.catch(error => {
console.log("error", error);
trx.rollback();
});
}).catch(err => res.status(400).json(err));
}
});
And here is the components that have the checkbox logic:
import React, { useState } from "react";
const onUpdateCB = (ischecked, loginuser, userid, setisChecked,handleCheck) => {
console.log(ischecked, loginuser, userid);
fetch('http://localhost:3000/cb', {
method: 'post',
headers: {'Content-Type':'application/json'},
body:JSON.stringify({
loginuser,
userid,
ischecked: ischecked
})
}).then(setisChecked(ischecked));
return
};
const Card = props => {
const [isChecked, setisChecked] = useState(props.ischecked);
return (
<div
className="pointer bg-light-green dib br3 pa3 ma2 shadow-5"
onClick={() => props.handleClick(props.id)}
>
<div>
<h3>{props.name}</h3>
<p>{props.company}</p>
<p>{props.phone}</p>
<p>{props.email}</p>
<p>{props.city}</p>
</div>
<div>
My Network
<input
className="largeCheckbox"
type="checkbox"
checked={isChecked}
onChange={() =>
onUpdateCB(!isChecked, props.loginuser.id, props.id, setisChecked,props.handleCheck)
}
/>
</div>
</div>
);
};
export default Card;
NetworkArray component:
import React from "react";
import Card from "./Card";
const NetworkArray = ({
network,
networkusers,
handleChange,
handleClick,
loginuser
}) => {
console.log("in network array", networkusers);
const cardComponent = network.map((user, i) => {
const ischecked = networkusers.filter(n => {
var nw = n.id === loginuser.id && n.connections === network[i].id;
return nw;
});
console.log("is it checked", ischecked);
return (
<Card
key={network[i].id}
name={network[i].firstname + " " + network[i].lastname}
company={network[i].company}
phone={network[i].phone}
email={network[i].email}
city={network[i].city}
ischecked={ischecked.length}
handleChange={handleChange}
handleClick={handleClick}
id={network[i].id}
loginuser={loginuser}
/>
);
});
return <div>{cardComponent}</div>;
};
export default NetworkArray;
A: This doesn't look quite right:
db.transaction(trx => {
db("networkusers")
.where("id", "=", loginuser)
Normally you'd do:
db.transaction(trx => {
trx("networkusers")
.where("id", "=", loginuser)
or:
db.transaction(trx => {
db("networkusers")
.where("id", "=", loginuser)
.transacting(trx)
I suspect the issue is you're just not using the transaction object consistently. See overview.
You should also respond after your database operation succeeds (not just when it fails). So something like:
db
.transaction(trx => {
// ...query...
})
.then(() => res.json({ message: 'Success.' }))
.catch(err => res.status(400).json(err));
| |
doc_23533932
|
This is my online code : https://codesandbox.io/s/rwnloz44kq
you will see a Calendar and button in the end of the page .
When you press the Button, the Modal working normally and this is what i want to do
( but when I click on the event in the calendar, not when I click the button )
so then i will be able to popup the current event information in the Modal.
i used testClick() function with $("#myModal").modal("show"); as it showen in Bootstrap Doc, but it doesn't work.
Is there any direct way to run the bootstrap modal with an external function ?
Thank you
A: Thank for all who try to help i found a nice easy way to solve this trick, it is just kind of twisting but it solve my problem.
i gave the Modal button an id="datepicker" and i clicked this button in my function like so .
testClick() {
$("#datepicker").click()
}
and wow the Modal run normally.
The https://codesandbox.io/s/3nkq5zwy6 has been uapdated too .
Have a nice coding ^_^
| |
doc_23533933
|
The code I have below does work if the field is selected but if it's not then it doesn't display the rest of the content. Any ideas on how to not show this block if the field is selected but show the content if the field is not selected?
function remove_blocks() {
if ( is_single() && (get_field('article_style' ) == 'major') ) {
$blocks = parse_blocks( get_the_content() );
foreach ( $blocks as $block ) {
if ( 'acf/opby-cover-image' === $block['blockName'] ) {
continue;
} else {
echo render_block( $block );
}
}
}
}
add_filter( 'the_content', 'remove_blocks');
A: Do the conditional check maybe in the loop instead of before?
if ( is_single() ) {
$blocks = parse_blocks( get_the_content() );
foreach ( $blocks as $block ) {
if ( 'acf/opby-cover-image' === $block['blockName'] && (get_field('article_style' ) == 'major') {
continue;
} else {
echo render_block( $block );
}
}
}
| |
doc_23533934
|
public class SimpleNashornTester {
public static void main(String[] args) throws ScriptException, NoSuchMethodException {
ScriptEngine jsEngine = new ScriptEngineManager().getEngineByName("nashorn");
Compilable jsCompilable = (Compilable) jsEngine;
Invocable jsInvocable = (Invocable) jsEngine;
ScriptContext scriptCtxt = new SimpleScriptContext();
Bindings engineScope = scriptCtxt.getBindings(ScriptContext.ENGINE_SCOPE);
CompiledScript jsScript = jsCompilable.compile("function definition() {print(\"Hello\")}");
jsScript.eval(engineScope); // no error with jsScript.eval() !
jsInvocable.invokeFunction("definition", new Object[] {});
}
}
This yields the error:
Exception in thread "main" java.lang.NoSuchMethodException: No such function definition
at jdk.nashorn.api.scripting.ScriptObjectMirror.callMember(ScriptObjectMirror.java:204)
Without the parameter engineScope in the evaluation of the script the function is found and invoked. Can anybody explain this difference? How can I use bindings without getting an error?
A: You're using a new ScriptContext and it's associated ENGINE_SCOPE Bindings to compile the script. invokeFunction/invokeMethod use the default ScriptContext (and it's associated ENGINE_SCOPE Bindings) to search the function. Each different ENGINE_SCOPE Bindings is associated with its own ECMAScript global object (and it's own ECMAScript global objects).
So, you can fix your program by
*
*changing the default context to be the new context before invoke:
// change the default ScriptContext
jsEngine.setContext(scriptCtxt);
jsInvocable.invokeFunction("definition", new Object[] {});
*Use the default ScriptContext for compiled script as well. As in:
ScriptContext scriptCtxt = jsEngine.getContext(); // new SimpleScriptContext();
| |
doc_23533935
|
and i am thinking about an app that will prevent another app from opening
if the password is in-correcrt(another app crated by my on the cellphone- not another activity).
I thought about using a file but i think it wont work because you need to be specific on where the file is and i want my program to be dynamic.
| |
doc_23533936
|
*
*
*
*
On each image ProgressBar has different style from another ProgressBar's.
I want to know, how i can specify progress bar style/thin in my application.
I look at android.R.attr.progressBarStyleSmall but it just change a size of progress bar, not a thickness of a spinning circle.
Note : Don't post answers which suppose create a custom drawables. Libraries allow.
A: You may try this git library it will help you and give more customization ...
https://github.com/castorflex/SmoothProgressBar
mProgressBar.setIndeterminateDrawable(new SmoothProgressDrawable.Builder(context)
.strokeWidth(8f) //You should use Resources#getDimension
.build());
You can give any stroke width here.
A: Can't say whether you can deal with these default progress bars, but you can try with an alternative design your own progress image and perform animation over it like here,
Now add this in res/drawable/customprogress.xml
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="360" >
<shape
android:shape="oval"
android:useLevel="false" >
<size
android:height="48dip"
android:width="48dip" />
<gradient
android:centerColor="#ff000000"
android:centerY="0.50"
android:endColor="#ff00ff00"
android:startColor="#ff000000"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
and add this progressbar attribute
android:indeterminateDrawable="@drawable/customprogress"
| |
doc_23533937
|
I do not have the possibility to use Enterprise Manager, any applications, utilities or the like. I can only feed it with pure SQL.
What I am after is SQL code, like CREATE TABLE and so on. So that I just can paste this into a query and voila - tables, procedures, functions are created in DatabaseB.
I will not copy the data.
This partly does what I want, it gives me procedures and functions:
Select object_Name(object_ID),definition from sys.SQL_Modules
But not for tables.
A: You can use the command line or you can create a stored procedure to create a back up, then use that backup to create a new database. I have used the command line often. Here is a previous Stack question that has a command line example and a link to a stored procedure example.
A: You can generate scripts in SQL Server Management Studio for an entire database or specific database objects.
To do this, right click the database then select Tasks then select Generate Scripts.
It will then open a wizard which will give you the option to choose to script the full database or just specific database objects.
| |
doc_23533938
|
I have an EditText for decimal, hexadecimal, binary and octal. There a "convert from" button next to each of them. So if you click the button to convert from octal, it'll output the corresponding conversion to the others' EditText fields.
This is the improved version of the code I tried to use for the from decimal function that Lucifer suggested, but still does not solve the problem:
public void dec(View view) {
final EditText decimal = (EditText) findViewById(R.id.editDec);
final EditText hex = (EditText) findViewById(R.id.editHex);
final EditText bin = (EditText) findViewById(R.id.editBin);
final EditText oct = (EditText) findViewById(R.id.editOct);
String deci = decimal.getText().toString();
hex.setText(String.valueOf(Integer.parseInt(deci,16)));
bin.setText(String.valueOf(Integer.parseInt(deci,2)));
oct.setText(String.valueOf(Integer.parseInt(deci,8)));
}
The current error that I'm getting
02-08 00:04:32.143: E/AndroidRuntime(409): Caused by: java.lang.NumberFormatException: Invalid int: "54"
"54" being the number I tried to enter in the decimal EditText.
I think it's saying that it failed to find the resource with the id of the text input, but I'm not trying to fetch the text as an ID, I want it as text.
I'm assuming I've messed something simple up, but it eludes me.
Here's one of the EditTexts it is trying to fetch from
<EditText
android:id="@+id/editHex"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_weight="11.38"
android:textColor="#000000"
android:background="@android:drawable/editbox_background"
android:inputType="text" >
</EditText>
The decimal, binary, and octal inputs use an inputType of "number"
A: your code is in-correct,
You are trying to convert an Integer Value to Hexa,Binary & Octal Number, but,
Integer.parseInt(deci,16) Integer.parseInt(deci,2) Integer.parseInt(deci,8)
is used to convert deci variable in to Hexa, Binary and Ocatal, which means you were performing reverse operation bymistake.
Checkout my updated code, it is the output you wanted.
public void dec(View view)
{
try
{
EditText decimal = (EditText) findViewById(R.id.editDec);
EditText hex = (EditText) findViewById(R.id.editHex);
EditText bin = (EditText) findViewById(R.id.editBin);
EditText oct = (EditText) findViewById(R.id.editOct);
int deci = Integer.parseInt(decimal.getText().toString().trim());
System.out.println ( "Original " + deci );
System.out.println ( "Hexa : " + Integer.toHexString(deci) );
System.out.println ( "Deci :" + Integer.toBinaryString(deci));
System.out.println ( "Oct : " + Integer.toOctalString(deci) );
hex.setText(String.valueOf(Integer.toHexString(deci)));
bin.setText(String.valueOf(Integer.toBinaryString(deci)));
oct.setText(String.valueOf(Integer.toOctalString(deci)));
}
catch ( Exception e )
{
System.out.println ( "Exception : " + e.toString() );
}
}
when you are setting Text in to EditText make sure you are passing String format in it.
A: You are passing an int to setText, and so it thinks you're trying to tell it the id of a resource. You need to pass it a string instead (or more correctly a CharSequence, but a string will do fine), so something like
hex.setText(String.valueOf(Integer.parseInt(deci,16)));
A: hex.setText(Integer.parseInt(deci,16));
EditText.setText(int ResId), if you just pass an Integer value, it will accept it, in your case -> it accepts it as a resource id, and it's not available that's why the error occured.
http://developer.android.com/reference/android/widget/EditText.html
so convert the value to string and display it.
hex.setText(String.valueOf(Integer.parseInt(deci,16)));
A: here the method Integer.parseInt(deci,16) will be used to convert hexa to decimal.
to convert dec to hexa use toHexString(deci); but here decimal should be int.
please check the following code. it will works fine.
public void dec(View view) {
final EditText decimal = (EditText) findViewById(R.id.editDec);
final EditText hex = (EditText) findViewById(R.id.editHex);
final EditText bin = (EditText) findViewById(R.id.editBin);
final EditText oct = (EditText) findViewById(R.id.editOct);
String deci = decimal.getText().toString().trim();
hex
.setText(String.valueOf(Integer.toHexString(Integer
.parseInt(deci))));
bin.setText(String.valueOf(Integer.toBinaryString(Integer
.parseInt(deci))));
oct.setText(String.valueOf(Integer
.toOctalString(Integer.parseInt(deci))));
}
| |
doc_23533939
|
https://i.stack.imgur.com/le5Gl.png
I shold see something like this:
https://i.stack.imgur.com/HnoIx.png
I uninstall and install the IDE and nothing...
A: From your first image, click on the little eye icon on the top left hand of the image.
Select show layout decorations
Hope it helps!
Click me
| |
doc_23533940
|
A: MAF uses a web layer for the UI effectively similar to PhoneGap/Cordova so its not like writing your code in xcode. The app would be an HTML5 app wrapped in an xcode project with the JVM embedded within. As far as I know the embedded JVM uses an interpreter since JIT's are disallowed on iOS.
Disclaimer: I work for Codename One which does use native code for iOS development in Java thru AOT bytecode to C translation.
| |
doc_23533941
|
I'm trying to validate a class where only parent fields are annotated with constraints.
I can see that MOXy is skipping validation for this class, probably it is not looking into the parent class.
Can you advise on how to overcome this?
A: I found a quick workaround. It is about creating dummy constraints which will always pass. Then you can put it on any class. and MOXy will turn on validation.
Dummy constraints:
@Target( {ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PutItWhenYouDoNotHaveConstraintsButParentHas.Validator.class)
@Documented
public @interface PutItWhenYouDoNotHaveConstraintsButParentHas {
String message() default "{com.mycompany.constraints.checkcase}";
Class<? extends Payload>[] payload() default {};
Class<?>[] groups() default {};
public static class Validator implements ConstraintValidator<PutItWhenYouDoNotHaveConstraintsButParentHas, Object>{
@Override
public void initialize(PutItWhenYouDoNotHaveConstraintsButParentHas constraintAnnotation) {
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
return true;
}
}
}
Example usage:
public class IdoNotHaveConstraints extends ButMyParentHas{
@PutItWhenYouDoNotHaveConstraintsButParentHas
public IdoNotHaveConstraints (){
}
}
A: It's a known issue in 2.6.0. It is fixed in master (2.7.x) and will be backported to 2.6.2, backporting to 2.6.1 is not planned. Unfortunately these builds are not available for public yet. You should wait for 2-3 months.
As a workaround I can suggest moving BV annotations from superclass to all children. And yes, I agree that it's ugly. :(
| |
doc_23533942
|
// Card/styles.scss
@mixin spacing($property, $max, $space) {
@for $i from 1 to $max + 1 {
&#{$i}x {
#{$property}: $i * $space;
}
}
}
.Card {
...
&--margin-bottom- {
@include spacing(margin-bottom, 7, 4px);
}
}
I tried creating a utils file so I can import it using @use,
// utils.scss
@mixin spacing($property, $max, $space) {
@for $i from 1 to $max + 1 {
&#{$i}x {
#{$property}: $i * $space;
}
}
}
and importing is via:
// Card/styles.scss
@use '../utils' as utils;
.Card {
...
&--margin-bottom- {
@include utils.spacing(margin-bottom, 7, 4px);
}
}
but I keep getting this error:
Module build failed (from ./node_modules/sass-loader/lib/loader.js):
@include utils.spacing;
Invalid CSS after "@include utils": expected "}", was ".spacing;"in /Users/_MY
FOLDER_/Documents/GITHUB/src/components/Card/styles.scss
My question is, how do I create a utility mixin so I can use this in other components?
| |
doc_23533943
|
public static let Heading1: Font = system(size: 34, weight: .black, design: .default)
.smallCaps()
.italic()
}
I can make the font all caps OR italic - but not both. Anybody know how to get around this? Without typing the String out in caps to begin with. I even tried importing BlackItalic as a custom font and still had the same issue.
A: None of Apple platform built-in font support both italic-smallcap features combination. System San Francisco is the most font-feature capable font supports smallcap for regular and bold, but not for italic.
Small caps are rare feature, and rare fonts support it, but even more rare, unique, fonts support both.
Here is quotation from Wikipedia ref.. pay attention on last sentence.
Small capitals are not found in all fonts, as they were primarily used
within body text and so are often not found in fonts that are not
intended for this purpose, such as many sans-serif families.[6] Some
font families, especially digitisations of older metal type designs,
often lack small caps in bold or italics, only having them in the
regular or roman style.[7] This is because they were normally only
used in body text and cutting bold and italic small caps was thought
unnecessary.[a]
See also:
AHIG Typography
| |
doc_23533944
|
/*******************************************************************************/
/* Section 4: Contact Area */
#section4{
width:1903px;
}
#contact_area{
background-color:red;
/* max-width:750px; */
padding-top:80px;
padding-bottom:60px;
width:1903px;
}
.contact_container{
background-color:orange;
margin:0px 576.500px; /* centers the entire column in the center of the contact area section */
padding:0px 15px; /* puts padding around the left/right sides of the container */
max-width:750px;
}
#contact_row_1A{
display:table; /* changes the display property of the row to act as a table */
}
#contact_column_1{
float:left;
}
.contact_content_1A{
text-align:center; /* centers the header and the text */
}
#contact_row_1B{
display:table;
}
#contact_column_2{
float:left;
padding-left:15px;
padding-right:15px;
width:690px; /* makes the width of the column 690px */
}
/* controls the text above the input fields */
#contact_text{
background-color:rgba(242,242,242,0.4); /* adds a transparent background color behind the text */
border-radius:5px; /* rounds the borders around the input fields */
font-size:18px; /* changes the size of the text to 18px */
/* margin-bottom:20px; */
padding:15px 0px;
}
#contact_row_2A{
display:table; /* puts both rows into 1 table */
width:750px; /* controls the size of the row */
}
/* controls the column containing the input fields */
#contact_column_form_left{
float:left; /* puts the 3 input fields on the left */
padding-left:0px; /* makes the column w/ the input fields align with the text above them */ /* when set to 0, the columns stay side by side */
/* padding-right:15px; */
width:50%;
}
#contact_column_form_right{
float:left; /* puts the 3 input fields on the left */
padding-right:0px; /* makes the column w/ the input fields align with the text above them */ /* when set to 0, the columns stay side by side */
width:50%;
}
.form_control{
/* display:block; */
margin-bottom:15px; /* adds margins to the bottoms of the input fields to space then out */
/* width:100%; */
}
#name_input{
background-color:rgba(242,242,242,0.4); /* adds a transparent background color behind the input field */
border:none; /* removes the default border around the input field */
border-radius:4px; /* rounds the borders around the input fields */
padding:6px 12px; /* adds padding inside the input field */
width:100%; /* the width of the input field is the full length of the column it in */
}
#email_input{
background-color:rgba(242,242,242,0.4); /* adds a transparent background color behind the input field */
border:none; /* removes the border around the input field */
border-radius:4px; /* rounds the borders around the input fields */
padding:6px 12px; /* adds padding inside the input field */
width:100%; /* the width of the input field is the full length of the column it in */
}
#subject_input{
background-color:rgba(242,242,242,0.4); /* adds a transparent background color behind the input field */
border:none; /* removes the border around the input field */
border-radius:4px; /* rounds the borders around the input fields */
padding:6px 12px; /* adds padding inside the input field */
width:100%; /* the width of the input field is the full length of the column it in */
}
/* controls the textarea element */
textarea.form_control{
background-color:rgba(242,242,242,0.4);
border:none; /* removes the border around the input field */
border-radius:4px; /* rounds the borders around the input fields */
/* flex-direction:column; */
height:auto;
padding:6px 12px; /* adds padding inside the input field */
width:100%;
}
/* controls the contact form's button */
#contact_btn{
background:#262628; /* colors the button */
border:1px solid #ccc; /* changes the border around the button */
border-radius:10px; /* rounds the default border around the button */
color:#fff; /* colors the text of the button */
/* display:inline-block;*/
font-size:18px; /* changes the size of the font of the button */
/* margin-top:20px; /* adds a margin between the textarea and the button */
padding:10px 30px; /* adds padding between the button's text and its border */
}
.form_control{
width:100%;
}
<div id="section4">
<!-- section -->
<section id="contact_area">
<!-- container -->
<div class="contact_container">
<!-- row 1 -->
<div id="contact_row_1A">
<!-- column -->
<div class="contact_column_1">
<!-- column -->
<div class="contact_content_1A">
<h1>Contact Form</h1>
<!-- row 2 -->
<div id="contact_row_1B">
<!-- column -->
<div id="contact_column_2">
<p id="contact_text">Nunc diam leo, fringilla vulputate elit lobortis, consectetur vestibulum quam. Sed id
<br>
felis ligula. In euismod libero at magna dapibus, in rutrum velit lacinia.
<br>
Etiam a mi quis arcu varius condimentum.</p>
</div>
</div>
</div>
</div>
</div>
<!-- row 2 -->
<div id="contact_row_2A">
<!-- column -->
<div id="contact_column_3">
<!-- form -->
<form class="contact_form" action="#" method="post">
<!-- column -->
<div id="contact_column_form_left">
<!-- form group -->
<div class="form_group">
<!-- input field 1 -->
<input class="form_control" id="name_input" name="name" placeholder="Name" type="name">
<!-- input field 2 -->
<input class="form_control" id="email_input" name="email" placeholder="Email" type="email">
<!-- input field 3 -->
<input class="form_control" id="subject_input" name="subject" placeholder="Subject" type="name">
</div>
</div>
<!-- column -->
<div id="contact_column_form_right">
<!-- form group -->
<div class="form_group">
<!-- textarea -->
<textarea class="form_control" id="comment" name="message" rows="6" placeholder="Your message here..."></textarea>
<button id="contact_btn" type="submit">Send</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
</div>
Im building this practice website.
I have figured out most of the problems I have had, but im stuck on the current issue.
In the Contact section of the site, I want a group of input fields to sit right next to the textarea. But they keep overlapping.`
What should I do to stop them from overlapping, and to sit next to each other within the same div?
A: Add box-sizing: border-box to your CSS styles, to make the components' width and height also include the padding and border, not just the contents...
* { box-sizing: border-box; }
/*******************************************************************************/
/* Section 4: Contact Area */
#section4{
width:1903px;
}
#contact_area{
background-color:red;
/* max-width:750px; */
padding-top:80px;
padding-bottom:60px;
width:1903px;
}
.contact_container{
background-color:orange;
margin:0px 576.500px; /* centers the entire column in the center of the contact area section */
padding:0px 15px; /* puts padding around the left/right sides of the container */
max-width:750px;
}
#contact_row_1A{
display:table; /* changes the display property of the row to act as a table */
}
#contact_column_1{
float:left;
}
.contact_content_1A{
text-align:center; /* centers the header and the text */
}
#contact_row_1B{
display:table;
}
#contact_column_2{
float:left;
padding-left:15px;
padding-right:15px;
width:690px; /* makes the width of the column 690px */
}
/* controls the text above the input fields */
#contact_text{
background-color:rgba(242,242,242,0.4); /* adds a transparent background color behind the text */
border-radius:5px; /* rounds the borders around the input fields */
font-size:18px; /* changes the size of the text to 18px */
/* margin-bottom:20px; */
padding:15px 0px;
}
#contact_row_2A{
display:table; /* puts both rows into 1 table */
width:750px; /* controls the size of the row */
}
/* controls the column containing the input fields */
#contact_column_form_left{
float:left; /* puts the 3 input fields on the left */
padding-left:0px; /* makes the column w/ the input fields align with the text above them */ /* when set to 0, the columns stay side by side */
/* padding-right:15px; */
width:50%;
}
#contact_column_form_right{
float:left; /* puts the 3 input fields on the left */
padding-right:0px; /* makes the column w/ the input fields align with the text above them */ /* when set to 0, the columns stay side by side */
width:50%;
}
.form_control{
/* display:block; */
margin-bottom:15px; /* adds margins to the bottoms of the input fields to space then out */
/* width:100%; */
}
#name_input{
background-color:rgba(242,242,242,0.4); /* adds a transparent background color behind the input field */
border:none; /* removes the default border around the input field */
border-radius:4px; /* rounds the borders around the input fields */
padding:6px 12px; /* adds padding inside the input field */
width:100%; /* the width of the input field is the full length of the column it in */
}
#email_input{
background-color:rgba(242,242,242,0.4); /* adds a transparent background color behind the input field */
border:none; /* removes the border around the input field */
border-radius:4px; /* rounds the borders around the input fields */
padding:6px 12px; /* adds padding inside the input field */
width:100%; /* the width of the input field is the full length of the column it in */
}
#subject_input{
background-color:rgba(242,242,242,0.4); /* adds a transparent background color behind the input field */
border:none; /* removes the border around the input field */
border-radius:4px; /* rounds the borders around the input fields */
padding:6px 12px; /* adds padding inside the input field */
width:100%; /* the width of the input field is the full length of the column it in */
}
/* controls the textarea element */
textarea.form_control{
background-color:rgba(242,242,242,0.4);
border:none; /* removes the border around the input field */
border-radius:4px; /* rounds the borders around the input fields */
/* flex-direction:column; */
height:auto;
padding:6px 12px; /* adds padding inside the input field */
width:100%;
}
/* controls the contact form's button */
#contact_btn{
background:#262628; /* colors the button */
border:1px solid #ccc; /* changes the border around the button */
border-radius:10px; /* rounds the default border around the button */
color:#fff; /* colors the text of the button */
/* display:inline-block;*/
font-size:18px; /* changes the size of the font of the button */
/* margin-top:20px; /* adds a margin between the textarea and the button */
padding:10px 30px; /* adds padding between the button's text and its border */
}
.form_control{
width:100%;
}
<div id="section4">
<!-- section -->
<section id="contact_area">
<!-- container -->
<div class="contact_container">
<!-- row 1 -->
<div id="contact_row_1A">
<!-- column -->
<div class="contact_column_1">
<!-- column -->
<div class="contact_content_1A">
<h1>Contact Form</h1>
<!-- row 2 -->
<div id="contact_row_1B">
<!-- column -->
<div id="contact_column_2">
<p id="contact_text">Nunc diam leo, fringilla vulputate elit lobortis, consectetur vestibulum quam. Sed id
<br>
felis ligula. In euismod libero at magna dapibus, in rutrum velit lacinia.
<br>
Etiam a mi quis arcu varius condimentum.</p>
</div>
</div>
</div>
</div>
</div>
<!-- row 2 -->
<div id="contact_row_2A">
<!-- column -->
<div id="contact_column_3">
<!-- form -->
<form class="contact_form" action="#" method="post">
<!-- column -->
<div id="contact_column_form_left">
<!-- form group -->
<div class="form_group">
<!-- input field 1 -->
<input class="form_control" id="name_input" name="name" placeholder="Name" type="name">
<!-- input field 2 -->
<input class="form_control" id="email_input" name="email" placeholder="Email" type="email">
<!-- input field 3 -->
<input class="form_control" id="subject_input" name="subject" placeholder="Subject" type="name">
</div>
</div>
<!-- column -->
<div id="contact_column_form_right">
<!-- form group -->
<div class="form_group">
<!-- textarea -->
<textarea class="form_control" id="comment" name="message" rows="6" placeholder="Your message here..."></textarea>
<button id="contact_btn" type="submit">Send</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
</div>
| |
doc_23533945
|
*
*Ubuntu 10.04.4 LTS
*ruby 1.9.1
*ImageMagick 6.8.6-5
*RMagick 2.13.2
When I try to do require 'RMagick' in irb I have an error:
LoadError: /usr/local/lib/ruby/gems/1.9.1/gems/rmagick-2.13.2/lib/RMagick2.so: undefined symbol: XStringListToTextProperty - /usr/local/lib/ruby/gems/1.9.1/gems/rmagick-2.13.2/lib/RMagick2.so
from /usr/local/lib/ruby/1.9.1/rubygems/custom_require.rb:60:in `require'
from /usr/local/lib/ruby/1.9.1/rubygems/custom_require.rb:60:in `rescue in require'
from /usr/local/lib/ruby/1.9.1/rubygems/custom_require.rb:35:in `require'
from /usr/local/lib/ruby/gems/1.9.1/gems/rmagick-2.13.2/lib/RMagick.rb:11:in `<top (required)>'
from /usr/local/lib/ruby/1.9.1/rubygems/custom_require.rb:60:in `require'
from /usr/local/lib/ruby/1.9.1/rubygems/custom_require.rb:60:in `rescue in require'
from /usr/local/lib/ruby/1.9.1/rubygems/custom_require.rb:35:in `require'
from (irb):1
from /usr/local/bin/irb:12:in `<main>'
A: The solution was simple: just remove imagemagick completely!
Instead apt-get remove imagemagick use next steps:
wget imagemagick.org/download/ImageMagick.tar.gz
tar zxvf ImageMagick.tar.gz
cd ImageMagick-6.8.2-10
./configure
make uninstall
| |
doc_23533946
|
<div class="bg-image cover-bg" id="mobile-app" data-image-src="assets/img/slider-4.jpg" data-overlay="4"></div>
What I need is to change the value of data-image-src from "assets/img/slider-4.jpg" to "assets/img/vs-app.jpg" on click of a button which is made by <a> tag.
A: You can get and set your data attribute like below.
$('a').click(function(e) {
$('.bg-image').data('image-src', 'assets/img/vs-app.jpg');
console.log($('.bg-image').data('image-src'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="bg-image cover-bg" id="mobile-app" data-image-src="assets/img/slider-4.jpg" data-overlay="4">1234</div>
<a href='#'>Click to change<a/>
A: You can try this
<a href='http://www.test.com' onclick='return change()'>change</a>
<script type='text/javascript'>
function change()
{
//Change the value of data-image-src here
return false;
}
</script>
A: I would recommend using attr() because of compatibility with IE. Details here.
$("#click").on("click", function() {
$("#mobile-app").attr("data-image-src", "assets/img/vs-app.jpg");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="bg-image cover-bg" id="mobile-app" data-image-src="assets/img/slider-4.jpg" data-overlay="4"></div>
<a id="click" href="#">Click</a>
| |
doc_23533947
|
Is it best practice to require the image once at the top of the component as a variable and just use the variable 6-8 times instead of the calling require for each one of them?
A: Yes, requiring it once at the top is far superior.
But hey, you can go even further. If this is an icon you need to use across the app, it might be worth making a very very simplistic component that renders this image. It's easier to reference <GreenCheck/> than to require an image and stick it into an img tag repeatedly.
| |
doc_23533948
|
This is how it looks like now
Here are the errors
I’m obviously doing something wrong. But I can’t figure it out.
Here is my repo: https://github.com/Colawithrain/Collin_Blog
And here is the Github pages link: https://colawithrain.github.io/Collin_Blog/
Thank you in advance for any pointers.
Colin
A: It's a little confusing since it likely works locally (where you don't need a baseurl). It's one of the most common errors with Jekyll in combination with GitHub Pages. Here's the run down:
You are trying to load:
https://colawithrain.github.io/assets/css/main.css
However, the CSS file is being served at:
https://colawithrain.github.io/Collin_Blog/assets/css/main.css
You are currently requesting this in _includes/head.html with:
<link rel="stylesheet" href="/assets/css/main.css">
Fix this by changing it to:
<link rel="stylesheet" href="{{ site.baseurl }}/assets/css/main.css">
Then setting this in your _config.yml:
baseurl: /Collin_Blog
A: Have you tried setting url and baseurl in the config. Because it looks like the site expects it to be on the root domain and not at /Collin_Blog. For example, the CSS file is referenced at:
https://colawithrain.github.io/assets/css/main.css
But is actually at:
https://colawithrain.github.io/Collin_Blog/assets/css/main.css
| |
doc_23533949
|
res.set('Set-Cookie', cookie.serialize('access_token', token, {
httpOnly: true,
maxAge: 60 * 60 * 24 * 7 // 1 week
}));
Later, the user tries to make a socket.io connection and the server tries to retrieve the cookie data:
io.on('connection', function(socket) {
console.log("SOCKET CONNECTED");
console.log(socket.handshake.headers.cookie);
console.log(socket.request.headers.cookie);
});
Output
SOCKET CONNECTED
io=Y8-CmNDnIH1eOx0_AAAA
io=Y8-CmNDnIH1eOx0_AAAA
As you can see, the cookie only contains one property named io but not access_token. Though if the cookies are read on express request, they contain the token and the values are correct.
Why are the cookie headers set on express request are different from the ones on socket.io. How do I share cookies between socket.io and express?
A: For the socket.io connection to see your cookie, you have to make the socket.io connection from the client to exactly the same host name and port (same origin) as the one that you set the cookie on. The browser will only send previously saved cookies to the exact same origin they were set on. For example, you can't use an IP address in one place and locahost in another even if they resolve to the same physical server.
| |
doc_23533950
|
1 1 0 3
2 1 -1 1
3 -1 -1 2
-1 2 3 -1
I wrote the follwinng program,
#include <stdio.h>
#include <lapacke/lapacke.h>
int main (int argc, const char * argv[]) {
float a[4][4]={
{1,1,0,3},
{2,1,-1,1},
{3,-1,-1,2},
{-1,2,3,-1}
};
lapack_int m=4,n=4,lda=4,info;
int i,j;
lapack_int*ipiv=(lapack_int*)malloc(4*4*sizeof(lapack_int));
m = 4;
n = 4;
lda = 4;
info= LAPACKE_sgetrf(LAPACK_ROW_MAJOR,m,n,*a,lda,ipiv);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%lf ",a[i][j]);
}
printf("\n");
}
return(info);
}
This should give
L=
1 0 0 0
2 1 0 0
3 4 1 0
-1 3 0 1
and U=
1 1 0 3
0 -1 -1 -5
0 0 3 13
0 0 0 -13
But in the docs I read that L en U are returned in A. How? Maybe skip the 1's on the diagonal of L en merge the two. Is that true?
I do
$ gcc -Wall sgetrf.c -llapacke -llapack
I see a=
3.000000 -1.000000 -1.000000 2.000000
0.666667 1.666667 -0.333333 -0.333333
-0.333333 1.000000 3.000000 0.000000
0.333333 0.800000 0.200000 2.600000
I does not make sense to me.
A: Your program is perfectly correct and LAPACKE_sgetrf actually return an LU factorization of the matrix with partial pivoting. It returned :
3 -1 -1 2
2/3 5/3 -1/3 -1/3
-1/3 1 3 0
1/3 0.8 0.2 2.6
The L matrix is:
1 0 0 0
2/3 1 -1/3 -1/3
-1/3 1 1 0
1/3 0.8 0.2 1
The U matrix is:
3 -1 -1 2
0 5/3 -1/3 -1/3
0 0 3 0
0 0 0 2.6
The product is similar to A except for the permutation of the rows:
3 -1 -1 2
2 1 -1 1
-1 2 3 -1
1 1 0 3
The LU factorization you provided is correct (except for the last line of L, which must be -1 -3 0 1 instead of -1 3 0 1). But such a LU factorization is not always possible (See wikipedia). This is the reason why LAPACK compute a PLU factorization, where P is a permutation matrix, returned in ipiv. Indeed, such a factorization is always possible.
| |
doc_23533951
|
Thank you
A: Without a cluster (i.e. just one single mongrel instance), you can only handle one request at a time. So if ten people try to access your site at the same time, they each have to wait. And if one user does something that triggers a long process, no one else will have access to your site until it's done. So clustering/load balancing is always a good idea.
About the only time I wouldn't think it necessary is if you're building a site where there would never be more than one person using it at a time (or if you are totally fine with the potential waits/slow-downs).
| |
doc_23533952
|
'vsync' is deprecated and shouldn't be used. This field is now ignored. This feature was deprecated after v2.2.0-10.1.pre..
Try replacing the use of the deprecated member with the replacement.
child: AnimatedSize(
vsync: this,
curve: Curves.easeIn,
duration: Duration(seconds: 1),
child: Text("test"),
),
so what is the replacement?
A: Just remove the field, doesn't need it anymore,
the updated docs example also removed it AnimatedSize class
A: double _size = 50.0;
bool _large = false;
void _updateSize() {
setState(() {
_size = _large ? 250.0 : 100.0;
_large = !_large;
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => _updateSize(),
child: Container(
color: Colors.amberAccent,
child: AnimatedSize(
curve: Curves.easeIn,
duration: const Duration(seconds: 1),
child: FlutterLogo(size: _size),
),
),
);
}
More information AnimatedSize
| |
doc_23533953
|
So, how i can display receipt email using nodejs mailer
Example in letter :
Dear (syntax_to_display_email)
to
Dear someone@example.com
A: This has nothing to do with nodemailer. You need to prepare the string or html first. And, send it with nodemailer.
There are two solutions:
1. Use template library (handlebars, Mustache)
It provides placeholders like:
Dear {{email}}
Use any templating library, and pass the object having values. It will be replaced.
*Use string replace, or prepare your string message by concatenation.
let msg = 'Dear ' + obj.email;
OR
let msg = util.format('Dear %s', obj.email);
| |
doc_23533954
|
How can i get the real area size of this path?
The pathes (shapes) looks like this here:
link to the image
A: I found a solution. I generate a Region from the path and use a RegionIterator to get Rects inside the Region. With this Rects i can calculate the whole area of the path.
private void calculateArea(Region region) {
RegionIterator regionIterator = new RegionIterator(region);
int size = 0; // amount of Rects
float area = 0; // units of area
Rect tmpRect= new Rect();
while (regionIterator.next(tmpRect)) {
size++;
area += tmpRect.width() * tmpRect.height();
}
log.d("Rect amount=" + size);
log.d("Area Size / units of area=" + area);
}
A: This shows simply how to convert path to rectangle.
RectF getAreaFromPath(Path sourcePath){
RectF rectF = new RectF();
sourcePath.computeBounds(rectF, true);
//You can get width and height by calling rectF.width(), rectF.height()
return rectF;
}
| |
doc_23533955
|
this is the code
def trasformazione (original):
inProj = Proj(init='epsg:4326')
outProj = Proj(init='epsg:3395')
transformat=[]
for g in range (0,row_count-1):
x2,y2 = transform(inProj,outProj,original[g][0],original[g][1])
transformat.append([x2,y2])
return (transformat)
transformat=trasformazione (original)
print(trasformazione (original))
# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('campioni1.xlsx')
worksheet = workbook.add_worksheet()
# Start from the first cell below the headers.
row = 1
col=0
# Iterate over the data and write it out row by row.
worksheet.write(row, col,transformat)
row += 1
workbook.close()
Thanks for the support
| |
doc_23533956
|
// Index.cshmtl
@{
ViewBag.Title = "EventManagement List";
}
<hr/>
<hr/>
<hr/>
<h2>EventManagement List</h2>
<table id="EventManagementTable" class="display">
@*Semantic UI*@
@*<table id="EventManagementTable" class="ui celled table">*@
@*Bootstrap*@
@*<table id="EventManagementTable" class="table table-striped table-bordered">*@
<thead>
<tr>
<th>TrainingID</th>
<th>TrainingType</th>
<th>TrainingDescription</th>
<th>Price</th>
<th>Venue</th>
<th>Facilitator</th>
<th>WhoAttend</th>
<th>RSVP</th>
</tr>
</thead>
<tfoot>
<tr>
<th>TrainingID</th>
<th>TrainingType</th>
<th>TrainingDescription</th>
<th>Price</th>
<th>Venue</th>
<th>Facilitator</th>
<th>WhoAttend</th>
<th>RSVP</th>
</tr>
</tfoot>
</table>
<!--Normal DataTables-->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.20/datatables.min.css" />
<!---JQuery ThemeRoller-->
<link href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.15/css/dataTables.jqueryui.min.css" rel="stylesheet" />
<!--Semantic UI-->
<link href="//cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.6/semantic.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.15/css/dataTables.semanticui.min.css" rel="stylesheet" />
<!-- Bootstrap 4 -->
<link href="https://cdn.datatables.net/1.10.15/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
@section scripts{
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.jqueryui.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.semanticui.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0.0-alpha.6/css/bootstrap.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap4.min.js"></script>
<script>
$(document).ready(function () {
$("#EventManagementTable").DataTable(
{
"ajax": {
"url": "/EventManagement/GetList",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "TrainingID" },
{ "data": "TrainingType" },
{ "data": "TrainingDescription" },
{ "data": "Price" },
{ "data": "Facilitator" },
{ "data": "WhoAttend" },
{"data":"RSVP"}
],
"serverSide": "true",
"order": [0, "asc"],
"processing": "true",
"language": {
"processing":"processing...... please wait"
}
});
});
</script>
}
// Controller
[HttpPost]
public ActionResult GetList()
{
//Server side Parameter.
int start = Convert.ToInt32(Request["start"]);
int length = Convert.ToInt32(Request["length"]);
string searchValue = Request["search[value]"];
string sortColumnName = Request["columns[" + Request["order[0][column]"] + "][name]"];
string sortDirection = Request["order[0] [dir]"];
return View();
}
| |
doc_23533957
|
I've moved everything to a test page at www.cucharavillage.com/test.html just so I could play with different code options and try to figure it out.
It does not work in Firefox or IE. Any suggestions?
| |
doc_23533958
|
array[++i];
array[i++];
A: The ++i increments i before evaluating it.
The i++ inrements i after evaluating it.
If i=1 then array[++i] sets i=2 and then fetches array[2].
If i=1 then array[i++] fetches array[1] then sets i=2.
The post- and pre- operations happen after or before the expression they are involved in is evaluation.
I generally discourage the use of post and pre increment operators in expressions. They can lead to confusion at best and bugs at worst.
Consider what x = array[++i] + array[i--] ; should be. See how easy it is to confuse the programmer ( or the poor devil who has to fix your code ? :-) ).
Post and pre increment and decrement operations can also produce problems in macros, as you end up with the potential for an operation to be duplicated multiple times, especially with macros.
It is simpler and produces easier to maintain code to avoid post and pre increments in expressions, IMO.
A: So, you know i++ and ++i increment i with 1. Also, this instruction returns i, so you can put this somewhere in your code where you need the value of i.
The difference between the 2 is that i++ is post increment, and ++i is pre increment. What does this mean?
Well, let's say i is 6. When you do:
array[i++]
array[i]
You will actually be doing:
array[6]
array[7]
Because you use post increment: first return value, then increment i.
If you do:
array[++i]
array[i]
You'll basically be doing:
array[7]
array[7]
Because you use pre increment: first increment i, then return its value.
Now try to find what your code does ;-)
Hope this helps.
A:
Please explain these operations.
*
*array[++i]; - first increments i, then gives you element at the incremented index
equivalent to:
++i; // or i++
array[i];
*array[i++]; - also first increments i, but postfix operator++ returns i's value before the incrementation
equivalent to:
array[i];
++i; // or i++
They increment a variable inside array.
No, they don't. You could say they increment i within the call to array subscript operator.
A: array[++i]; - increments the value of i and then uses the incremented value as an index into array
array[i++]; -indexes into the array and then increments the value of i
A: I know your question was in the context of a queue, but I'm going to use a stack for illustration.
Imagine an array-based stack:
T stack[N]; // for some type T
size_t sp = N; // stack pointer
In this example, the stack grows "downwards", where index N-1 is the bottom of the stack and index 0 is the top.
A push operation looks like the following:
stack[--sp] = val;
--sp evaluates to sp - 1, and as a side effect decrements the value in sp, so the above statement is equivalent to writing
stack[sp - 1] = val;
sp = sp - 1;
with the caveat that sp may be updated before the assignment is complete.
A pop operation looks like this:
val = stack[sp++];
sp++ evaluates the the current value of sp, and as a side effect increments the value in sp, so it's equivalent to writing
val = stack[sp];
sp = sp + 1;
with the same caveat as above.
| |
doc_23533959
|
BN2.get(5).getParentNode().removeChild(BN2.get(5));
Note: BN2 is the ArrayList that contains the nodes.
File xmlFile = new File("Ex2.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
BN2.get(5).getParentNode().removeChild(BN2.get(5));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource domSource = new DOMSource(doc);
StreamResult streamResult = new StreamResult(new File("Ex2.xml"));
transformer.transform(domSource, streamResult);
XmL file: the is not showing although it is written here
<a>
<b>
<s>
<e>AAA</e>
<e>BBB</e>
<e>CCC</e>
</s>
<d>
<v>whatever</v>
<f>
</f>
</d>
</b>
| |
doc_23533960
|
$filename = APP . 'docs' . DS . 'reports' . DS . $Workbooks[0]['Report']['company'] . '.' . $Workbooks[0]['Report']['report_name'] . '.' . $Workbooks[0]['Report']['extension'];
$blacklist = array('Company Organogram');
$MasterFile = $this->PhpExcel->createMasterFile($filename,$company . '.' . $title,$colour);
foreach($Workbooks as $Workbook) :
if(!in_array($Workbook['Report']['report_name'],$blacklist)) {
$file = APP . 'docs' . DS . 'reports' . DS . $Workbook['Report']['company'] . '.' . $Workbook['Report']['report_name'] . '.' . $Workbook['Report']['extension'];
$MasterFile = $this->PhpExcel->addExternalWorksheet($MasterFile,$file,$company . '.' . $title,$colour);
#unlink($file);
}
endforeach;
$this->PhpExcel->saveToDisk(APP . 'docs' . DS . 'reports' . DS . 'Weekly Reports for Week ' . (date('W') + 1) . '.xlsx',$MasterFile);
I'm working with CakePHP, so there is a helper. saveToDisk simply saves the file to the disc after which it is attached and sent to a mailing list.
All the above works fine. But I'm having issues where the combining process draws in extra lines. For instance, this:
becomes this:
How would I fix this? Is there something I should set so it doesn't draw in all the lines?
| |
doc_23533961
|
A problem occurred evaluating project ':app'.
> Could not find method compile() for arguments [project ':react-native-orientation'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
I followed then, the manual instructions for linking react-native-orientation to the Android directory and it did nothing. I understand that pod-install is just for iOS, but react-native link is deprecated now, is it not? I can't even run it, as it just tells me that link is an unrecognized command. So if the manual linking won't work, and the auto-linking doesn't exist evidently, what course of action do I have?
A: Try using patch-package
The problem is that on gradlew 7, 'compile' keyword is deprecated in favor of 'implementation'.
And the proper way is not changing inside /node_modules/ folder, but making a patch.
In my case I had to manually modify the automated patch made by patch-package.
This issue helped me: https://github.com/yamill/react-native-orientation/issues/407
The patch is as bellow (do not copy the first 2 lines, let patch-package create those):
diff --git a/node_modules/react-native-orientation/android/src/main/java/com/github/yamill/orientation/OrientationModule.java b/node_modules/react-native-orientation/android/src/main/java/com/github/yamill/orientation/OrientationModule.java
index 85331ae..787f60f 100644
--- a/node_modules/react-native-orientation/android/build.gradle
+++ b/node_modules/react-native-orientation/android/build.gradle
@@ -16,5 +16,5 @@ android {
}
dependencies {
- compile "com.facebook.react:react-native:+"
+ implementation "com.facebook.react:react-native:+"
}
| |
doc_23533962
|
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 473, in spawn_worker
worker.init_process()
File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 100, in init_process
self.wsgi = self.app.wsgi()
File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 115, in wsgi
self.callable = self.load()
File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 33, in load
return util.import_app(self.app_uri)
File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 362, in import_app
__import__(module)
File "/home/hamid/projects/bfl/develop.py", line 4, in <module>
application = create_app(DevelopmentConfig)
File "/home/hamid/projects/bfl/project/application.py", line 56, in create_app
configure_blueprints(app)
File "/home/hamid/projects/bfl/project/application.py", line 97, in configure_blueprints
bp = __import__('project.apps.%s' % blueprint_name, fromlist=['views'])
File "/home/hamid/projects/bfl/project/apps/store/views/__init__.py", line 6, in <module>
from .store import *
File "/home/hamid/projects/bfl/project/apps/store/views/store.py", line 193, in <module>
@mod.route('/<page>/', defaults={'per_page': current_app.config['PAGE_SIZE']})
File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 338, in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/local.py", line 297, in _get_current_object
return self.__local()
File "/usr/local/lib/python2.7/dist-packages/flask/globals.py", line 34, in _find_app
raise RuntimeError('working outside of application context')
RuntimeError: working outside of application context
And here is my sample code:
@mod.route('/<page>/', defaults={'per_page': current_app.config['PAGE_SIZE']})
@mod.route('/<per_page>/<page>/')
@login_required
def index(per_page, page):
pagination_obj = Pagination(Store.objects(is_dealer=False), per_page, page)
return render('store/index.html', pagination=pagination_obj)
Any idea how can I get rout default values from current application config?
A: current_app can only access "config" dictionary within "request context".
To access config value outside request context, you can use this custom method :
from . import app
def getConfig(key):
with app.app_context():
if key in current_app.config:
return current_app.config.get(key)
else:
raise Exception("Custom Message")
A: You code looks ok.
As the error is raised in the line where you have current_app.config['PAGE_SIZE'], can you debug and confirm that this variable actually exists?
By the @mod decorator, I guess you are using blueprints. So maybe current_app is not the name of your app, or you haven't imported current_app properly. Or, yet, you are not setting the config variables for you app properly.
Finally, in what context you get this error? Accessing which URL? Or is it in a test environment?
In sum: the mistake probably is not in the bit of code you shared.
| |
doc_23533963
|
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
below is my query i just want to add PrePmt_Amount from table sales header with Amount column from sales line and store the result in column testing in Table sales header
note- sales header.No_ is the primary key similarly for sales line.[Document No_]
Query=>
update sales_header
set testing =
(select sales_header.PrePmt_Amount + sales_line.amount
from sales_header,sales_line
where sales_header.No_ = sales_line.[Document No_])
A: I think you intend:
update sales_header
set testing = (PrePmt_Amount +
(select sum(sl.amount)
from sales_line
where sales_header.No_ = sl.[Document No_]
)
);
A: Your SELECT statement is returning more than one record, that means that there is more than one record in sales_header, sales_line that matches your WHERE clause sales_header.No_ = sales_line.[Document No_]
| |
doc_23533964
|
i.e:
I tried:
<div class="Date">19.05.2017</div>
$date: //div[has-class("Date")]
@datetime(-2): $date
published_date: $@
but this has no effect on the date. What am I doing wrong? The telegram manuel is too brief.
A: I don't know how to deal with it, so I use this dirty work for my template
$date: //div[has-class("Date")]/text()
@debug # 19.05.2017
@replace("(\\d\\d)\\.(\\d\\d)\\.(\\d{4})", "$3/$2/$1"): $date
@debug # 2017/05/19
published_date: $@
@debug # 1495141200 (2017/05/19)
It convert 19.05.2017 to 2017/05/19, and then published_date can parse it.
| |
doc_23533965
|
When I built my model, I first considered all the features to go into my regression model. Once I have my model, I then ran Lasso regression on my model, with the hope that this will tackle any colinearity between the features. However, the Lasso regression kept both F1 and F2 in my model.
Two questions:
i) If F1 and F2 are highly correlated, but Lasso regression still kept both of them, what could this mean? Does it mean regularization doesn't work in some cases?
ii) How do I adjust my model or the Lasso regression model to kick out F1 or F2 in my model? (I am using sklearn.linear_model.LogisticRegression, and have set penalty = 'l1' or ‘elasticnet’, tried very large or very small C values, tried 'liblinear' or 'saga' solvers, and l1_ratio = 1, but I still can't kick out either F1 or F2 from my model)
A: Answers to your questions:
i) Lasso reduces coefficients gradually. You may find a nice picture in some books authored by Robert Tibshirani, the person behind the Lasso/Ridge, where you will see how some coefficients gradually fall to zero as regularization coefficient is increasing (you may perform such an experiment yourself). The fact the model still keeps both may mean two things: either the model deems both important or there no enough regularization to kill one of them.
ii) You're right you're going with Lasso with L1 regularization. It is C parameter. The way it's coded in sklearn: the smaller the C the higher the regularization parameter (inverse). Though in machine learning your task is not to totally exclude collinearity ("to kill F1 or F2" in your parlor), but to find a model (or a set of params if you wish) that will generalize best. That is done through model tuning via CV. Warning: higher regularization means more underfitting.
I would add though that collinearity is somewhat dangerous for linear regression because it may give rise to model instability (differing coefficients on different subsamples). So, with linear regression, you may wish to check this too.
| |
doc_23533966
|
How can I use the onTokenRefresh() method to notice the change of token continuously (even when the app is not opened) and send the new token to my backend server?
Thank you.
A: The code should look like this:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.instance.onTokenRefresh.listen((String token) {
print("New token: $token");
// sync token to server
});
String token = await FirebaseMessaging.instance.getToken();
// sync token to server
print("Token: $token");
//runApp(MyApp());
}
| |
doc_23533967
|
I got 2 specific columns which are called cs_start_time(Type:Datetime) and cs_time_length(Type:int (seconds)) in my table.
Now I want to delete these rows automatically when cs_start_time + cs_time_length < NOW() (Current Datetime) and Insert them into another table (of course it should be before deleting these rows).
Or I handle it when someone do a select query on these rows (Trigger alike)
Is this even possible with mysql ? (Im a newbie in mysql)
A: You can use MySQL event scheduler for this purpose:
I've simulated your scenario creating the main table where data initially stay. Later the expired data are archived in a table named archiveTable through an event scheduler.
*
*Main table structure and data:
-- ----------------------------
-- Table structure for `maintable`
-- ----------------------------
DROP TABLE IF EXISTS `maintable`;
CREATE TABLE `maintable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cs_start_time` datetime NOT NULL,
`cs_time_length` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
-- ----------------------------
-- Records of maintable
-- ----------------------------
INSERT INTO `maintable` VALUES ('1', '2016-05-01 12:00:00', '10');
INSERT INTO `maintable` VALUES ('2', '2016-05-02 12:00:00', '5');
INSERT INTO `maintable` VALUES ('3', '2016-05-03 12:00:00', '15');
*
*Archive table structure and data:
DROP TABLE IF EXISTS `archivetable`;
CREATE TABLE `archivetable` (
`id` int(11) NOT NULL,
`cs_start_time` datetime NOT NULL,
`cs_time_length` int(11) NOT NULL
);
*
*Set event scheduler ON first
SET GLOBAL event_scheduler = ON;
*
*Create the event:
DROP EVENT IF EXISTS `archiveEvent`;
delimiter $$
CREATE EVENT `archiveEvent` ON SCHEDULE EVERY 1 MINUTE STARTS '2016-05-02 00:00:00' ON COMPLETION PRESERVE ENABLE DO
BEGIN
INSERT INTO archivetable (
id,
cs_start_time,
cs_time_length
) SELECT
MT.id,
MT.cs_start_time,
MT.cs_time_length
FROM
maintable MT
WHERE
MT.cs_start_time + INTERVAL MT.cs_time_length SECOND < NOW() ;
DELETE
FROM
maintable
WHERE
cs_start_time + INTERVAL cs_time_length SECOND < NOW() ;
END$$
delimiter ;
Note: Look the event start time is set to 2016-05-02 00:00:00. After that the event will be scheduled in every one minute interval. You can change the schedule time in any interval unit as you like.
Suggestion:
Quoting from my comment:
You can use mysql event scheduler for this purpose. But I would
suggest you can filter out these entries in your select query. What's
the big deal of deleting those entries whereas you can easily bypass
these in your select query? You have to check every second through the
scheduler whether they meet the condition to be deleted or not;
A: What you are describing looks like a recurring process that runs on a clock - whenever the "now()" value reaches a certain point, you want to have some action executed.
One way to implement this is to write a CRON job. Cron is a built-in system in Unix/Linux that lets you run commands on a given schedule. For example, you could run a script every hour that executes your SQL query (select all records that should be moved over, move them, and delete them); and then output the results of the execution to the log file to monitor your process.
| |
doc_23533968
|
The code I want to vectorize looks like this :
#pragma omp parallel shared(in, out, lambda,dim,C) private(k)
{
#pragma omp for schedule(guided,dim/nthreads) nowait
for(k = 0;k < dim; k++){
in[k] = C*out[k]*lambda[k];
}
}
where out,lambda and in are double precision arrays.
But even if I include #pragma always vector, what the compiler answers is :
warning: ignoring #pragma always vector
Do you know if there is any workaround for this?
Thanks.
A: I looked through the User Guide for the PathScale compiler, and did not find neither #pragma always nor #pragma vector. So I think the compiler just tells you that it does not recognize this pragma, and ignores it.
However in section 7.4.5 I found the following options that should help you with vectorization:
Vectorization of user code ... is controlled by the flag -LNO:simd[=(0|1|2)], which enables or disables inner loop vectorization. 0 turns off the vectorizer, 1 (the default) causes the compiler to vectorize only if it can determine that there is no undesirable performance impact due to sub-optimal alignment, and 2 will vectorize without any constraints (this is the most aggressive).
-LNO:simd_verbose=ON prints vectorizer information (from vectorizing user code) to stdout.
As a side note (guessing where you could take that #pragma always vector from), Intel's compiler has #pragma vector with always being one possible parameter to the pragma. But pragmas are generally compiler-specific, except for few extensions (OpenMP being one) that are supported by multiple vendors.
| |
doc_23533969
|
I initially passed the object as props, but I don't want private information on the object to be easily exposed using browser extensions such as Vue DevTools. Now, I've been searching for a way to define global variables inside the Blade Template and access them in Vue:
Pass data from blade to vue component
https://forum.vuejs.org/t/accessing-global-variables-from-single-file-vue-component/638
https://zaengle.com/blog/layers-of-a-laravel-vue-application
Based on those links above, it seems like what I need to do is set the variables to the window object, but I'm unsure on what I'm doing something wrong to achieve this. When I define the variable in the Blade Template, I can see the variable is assigning properly by doing console.log() but the problem comes when I try to use it in Vue.
app.blade.php
@if(Auth::user())
<script>
window.User = {!! json_encode(Auth::user()) !!}
console.log(window.User)
</script>
@endif
component.vue
<script>
export default {
data: function() {
return {
user: window.User
}
}
}
</script>
I've tried setting the data as window.User, this.User, and simply just User but it always comes up as undefined. What am I missing? Or is there any other/better way to do this?
A: Try the following Vue Component:
<template></template>
<script>
export default {
data: function() {
return {
user: window.User
}
},
created(){
console.log(this.user)
},
}
</script>
I could see the user data from the console.log in Vue component.
| |
doc_23533970
|
Command I am using to copy FileUtils.cp(src_file, dest_file).
I can manually copy and paste file in the windows explorer.
| |
doc_23533971
|
The application is a NPAPI plugin which uses .Net components via UnmanagedExports. I designed it as a low integrity application and therefore it has to reside in the users 'LocalLow' directory.
In my application I used a dynamic assembly loading mechanism to load several assemblies at runtime. I used the following method to load an assembly,
MyInterface Instance;
Assembly assembly = Assembly.LoadFrom(AssemblyFile);
Type type = assembly.GetType(Identifier); // Identifier is implementing the MyInterface
Instance = Activator.CreateInstance(type) as MyInterface;
// Do something with the Instance
After modifying the project to .Net 4.0, I noticed that the plugin crashes when the binaries are placed inside the LocalLow directory (It works in other places). My next step was to create a minimalistic plugin with least possible code to figure out the issue. I noticed that the dynamic assembly loading failed with the following exception,
System.IO.FileLoadException: Could not load file or assembly '<assemblyPath>' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515 (COR_E_NOTSUPPORTED)) --->
System.NotSupportedException: An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=131738 for more information.
I tried the following approaches to create a separate domain and load the assemblies but with no luck,
*
*http://blogs.msdn.com/b/shawnfa/archive/2009/06/08/more-implicit-uses-of-cas-policy-loadfromremotesources.aspx
*http://www.west-wind.com/weblog/posts/2009/Jan/19/Assembly-Loading-across-AppDomains
Adding the configuration 'loadFromRemoteSources' did not work either. It seems that the .Net component does not load .dll.config files. (Could be because of UnmanagedExporting)
My questions are,
*
*Is it possible to dynamically load an assembly from LocalLow?
*Does the new CAS policy in CLR 4.0 apply to LocalLow as well? From what I understood so far it should affect only assemblies loaded over the network
*Is there any other way to overcome this issue?
A: While it doesn't address your LocalLow issue specifically, if you are able to "read a file" from the directory, you might be able to use the "work around" detailed here:
How can I get LabView to stop locking my .NET DLL?
| |
doc_23533972
|
Criteria criteria = session.createCriteria(Test.class);
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("Month"));
projList.add(Projections.property("Year"));
criteria.setProjection(Projections.distinct(projList));
Here I am trying to fetch distinct values using Month and year similar to
select distinct Month, Year from table;
And finally after complete query I am using list() to fetch the criteria as:
criteriaList = criteria.list();
Now I have the criteriaList as Object with two column data Month and Year. I want to list the results of the query in criteriaList with only Month into a List<Integer>.
I have tried looping through the criteriaList and converting the fetched Object to List<Integer>, but it didn't work. How can I get only first column (Month) from the returned two columns?
Note: Setting projections to only one column (Month) will not help as I need distinct on both Month and Year
Update:
I have used the following types:
List<Object[]> criteriaList = Collections.emptyList();
List<Integer> Month = Collections.emptyList();
And since the number of months returned would be varying, I would like to add the fetched Months into a List<Integer> to perform further operations on.
A: When using ProjectionList as you shown, hibernate returns List<Object[]> on criteria.list(). In your case, object array first element (0 index) is month, and second element (1 index) is year.
So you have to deal with a list of object array, as following:
List<Object[]> criteriaList = criteria.list();
List<Integer> monthList = Collections.emptyList();
for (Object[] row : criteriaList) {
try{
BigDecimal month = row[0];
monthList.add(month.intValueExact());
catch(Exception e){
//To deal with casting Exception, NPE and
//ArithmeticException if int conversion fails
}
//Do what you want ...
}
Of course, I am supposing Projections.property("Month") is an Integer object, but I don't know, so you have to cast properly. The same for Year.
Of course, you can also use a resultTransformer.
Edit
I just edited my suggested block after you give more information on your comments.
| |
doc_23533973
|
a_long_named_array = [1, 5]
[2, 6]
[3, 7]
I could create a subset of my array such that the 1st column is greater than 5 by writing
a_long_named_subarray = a_long_named_array[a_long_named_array[:,1] > 5]
How do I plot this subdata without making the aforementioned subarray? Please see below.
import numpy as np
import matplotlib.pyplot as plt
#Generate 2D array
arr = np.array([np.random.random_integers(0,10, 10), np.arange(0,10)])
#Transpose it
arr = arr.T
#----------------------------------------------------------------------------
#Plotting a Histogram: This works
#----------------------------------------------------------------------------
#Plot all the rows of the 0'th column
plt.hist(arr[:,0])
plt.show()
#----------------------------------------------------------------------------
#Plotting a conditional Histogram: This is what I am trying to do. This Doesn't work.
#----------------------------------------------------------------------------
#Plot all the rows of the 0th column where the 1st column is some condition (here > 5)
plt.hist(arr[:,0, where 1 > 5])
plt.show()
quit()
A: You just need to apply the boolean index (whatever > 5 returns a boolean array) to the first dimension.
You're currently trying to index the array along the third dimension with the boolean mask. The array is only 2D, so you're probably getting an IndexError. (Most likely "IndexError: too many indices".)
For example:
import numpy as np
# Your example data
arr = np.array([np.random.random_integers(0,10, 10), np.arange(0,10)])
arr = arr.T
# What you want:
print arr[arr[:,1] > 5, 0]
Basically, in place of the :, you just put in the boolean mask (something > 5). You might find it clearer to write:
mask = arr[:,1] > 5
result = arr[mask, 0]
Another way of thinking of this is:
second_column = arr[:,1]
first_column = arr[:,0]
print first_column[second_column > 5]
| |
doc_23533974
|
I have default scaffolding one controller of Question in the controller and in which I have QuitionDetails method which is responsible for the QuitionDetailsView and in this view I am making ajax request to my API controller VotesController when the user clicks on the up-vote or down-vote.
But I am getting this error
jquery-3.3.1.js:9600 PUT https://localhost:44389/Question/QuestionDetails/api/votes/3 404 not found
send @ jquery-3.3.1.js:9600
ajax @ jquery-3.3.1.js:9206
(anonymous) @ 2:230
dispatch @ jquery-3.3.1.js:5183
elemData.handle @ jquery-3.3.1.js:4991
here is my first default scaffolding controller Question
public ActionResult QuestionDetails(int Id)
{
QuestionDetailViewModel questionDetailViewModel = new QuestionDetailViewModel
{
Question = QBL.GetQuestions(Id),
UserId = User.Identity.GetUserId(),
QuestionId = Id,
};
return View(questionDetailViewModel);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult QuestionDetails(QuestionDetailViewModel questionDetailViewModel)
{
QBL.CreateAnswer(questionDetailViewModel);
return RedirectToAction("QuestionDetails", new { Id = questionDetailViewModel.QuestionId });
}
View Code is as Below
@model AskMe.Models.ViewModel.QuestionDetailViewModel
@{
ViewBag.Title = "QuestionDetails";
}
<h1>Question Details: </h1>
<h3>@Model.Question.Post.Title</h3>
@Html.Raw(Model.Question.Post.Content)
<hr />
<h3>Answers:</h3>
@foreach (var answer in Model.Question.Answers)
{
<div class="card bg-light m-1">
<div class="card-body">
<h5 class="card-title">Answered by: @answer.Post.CreatedBy.UserName</h5>
@Html.Raw(answer.Post.Content)
</div>
<div id="vote" class="col">
<div>
<button data-vote-id="@answer.Post.PostId" class="nav-link thumbs-up" href=""><i class="fa fa-thumbs-up" aria-hidden="true"></i></button>
</div>
<div>
</div>
<div>
<button data-vote-id="@answer.Post.PostId" class="nav-link thumbs-down" href=""><i class="fa fa-thumbs-down" aria-hidden="true"></i></button>
</div>
</div>
</div>
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h3>Contribute your answer: </h3>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.AnswerContent, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextAreaFor(m => m.AnswerContent, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
@Html.HiddenFor(m => m.UserId)
@Html.HiddenFor(m => m.QuestionId)
<input type="submit" value="Contribute now" class="btn btn-outline-primary" />
</div>
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval");
<script type="text/javascript">
$(document).ready(function () {
tinyMCE.init({
mode: "textareas",
});
$("#vote").on("click",".thumbs-up", function () {
console.log("in selection func");
$.ajax({
url: "api/vote/" + $(this).attr("data-vote-id"),
method: "PUT",
success: function () {
console.log("success");
}
})
})
});
</script>
}
And here is my votes API controller code
using AskMe.Models;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace AskMe.API
{
public class VotesController : ApiController
{
ApplicationDbContext _context = new ApplicationDbContext();
[HttpPut]
public IHttpActionResult UpVote(int postId)
{
var userId = User.Identity.GetUserId();
var user = _context.Users.Find(userId);
var post = _context.Posts.Find(postId);
var votes = post.Votes.ToList();
if (votes.FindAll(u => u.UserId == userId).Count == 0)
{
Votes vote = new Votes
{
VotedDateTime = DateTime.Now,
UserId = userId,
User = user,
Post = post,
PostId = postId,
};
post.Votes.Add(vote);
_context.SaveChanges();
return Ok();
}
return BadRequest();
}
}
}
I am not sure my api link should be like this https://localhost:44389/Question/QuestionDetails/api/votes/3
or
https://localhost:44389/api/votes/3
and my route config is routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
A: If you haven't changed the standard routing, you need to include the action/method name in your ajax call.
Try:
url: "api/vote/upvote/" + $(this).attr("data-vote-id")
Your route configuration should look like this:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
If you are using MVC5 with WebApi, which is my guess, you have to be careful. See this post for further information on how to do it.
A: Actually your error telling everything. When you requesting for 'UpVote' action it's looking into "basepath(localhost)/controller/action/Api/etc." and it does not exits. You must create request for https://localhost:44389/API/Votes/UpVote/3
| |
doc_23533975
|
new LineBasicMaterial({ color: '#ff1b00', linewidth: 1 }
But in scene the color has a different shade, when i use color picker - color is #db5100. Why? And how to fix it?
Set up webGlRender:
this.renderer = new WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true, powerPreference: 'high-performance', precision: 'highp' })
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.gammaOutput = true;
this.renderer.toneMapping = THREE.ACESFilmicToneMapping
this.renderer.toneMappingExposure = 0.7;
this.renderer.gammaFactor = 2.2
this.renderer.gammaOutput = true;
this.renderer.powerPreference = 'high-performance'
this.renderer.shadowMap.enabled = false;
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap; // default THREE.PCFShadowMap
this.dom.appendChild(this.renderer.domElement)
| |
doc_23533976
|
"DepartmantCodes": [
{
"DepartmentCode": "12",
"DivisionCode": [
"11",
"22"
]
},
{
"DepartmentCode": "22",
"DivisionCode": [
"21",
"23"
]
}
]
Array structure
[
['12','11'],
['12','22'],
['22','21'],
['22','23'],
]
A: Using Ext.each and an empty array you can iterate through the json object and create the required array:
var endArray = [];
Ext.each(departmentCodes,function(departmentCode){
Ext.each(departmentCode.DivisionCode,function(divisionCode){
endArray.push([departmentCode.DepartmentCode,divisionCode]);
});
});
I've double nested the foreach in the example because, although your code has only 2 division codes in each array, I assume there could be any number of division codes?
Here is a fiddle for a working demonstration.
| |
doc_23533977
|
Possible Duplicate:
Git - Whitelisting files in a complex directory structure
I'd like to have a git repository track only files named e.g. SOURCES while everything else shall be ignored (take e.g. a tree of pdf files where each SOURCES file lists their origins). The simplest shot would have been
*
!SOURCES
in .gitignore. However the exclusion of e.g. A/SOURCES is overridden by the *, requiring me to use git add -f. How can .gitignore be modified to ignore everything except files named SOURCES without requiring a forced add?
edit The solution posted here will not do since the directory structure is not fixed, i.e. new directories containing a SOURCES file should not have to be added to .gitignore by hand...
A: You can't achieve this using just .gitignore
Git doesn't track paths. It tracks objects (~ files) only.
So, why don't you reverse the tables:
git add -f -- */*/SOURCES */SOURCES
or
shopt -s globstar
git add -f -- **/SOURCES
Or get out the big guns:
git add -f -- $(find -type f -name SOURCES)
or even
find -type f -name SOURCES -exec git add -f -- {} \+
Untested idea Perhaps something like this could be in a pre-commit hook?
Update An idea for more automation:
Add this to .git/config
[alias]
ac = "!_() { git add -f -- */*/SOURCES && git commit \"$@\"; }; _"
Now, you can just say
git commit -m 'like you usually work'
and it will automatically add the */*/SOURCES
| |
doc_23533978
|
Last login: Tue Jan 21 16:59:52 on ttys002
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type md5
ERROR:root:code for hash sha1 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha1
ERROR:root:code for hash sha224 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha224
ERROR:root:code for hash sha256 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha256
ERROR:root:code for hash sha384 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha384
ERROR:root:code for hash sha512 was not found.
Traceback (most recent call last):
File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module>
globals()[__func_name] = __get_hash(__func_name)
File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor
raise ValueError('unsupported hash type ' + name)
ValueError: unsupported hash type sha512
I don't understand why uninstalling node and npm from my system induces errors in the python install.
Do you have any idea how to fix this? Thanks in advance!
| |
doc_23533979
|
//fun declaration
TBool EncryptL(const TDesC8 &aInput, TDes8 &aOutput);
//function calling
TBuf8<10> text;
TBuf8<10> cipher;
text.Copy(_L("Hello"));
iEncryptor.EncryptL(text,cipher); it shows error expression syntax error
//fun definition
TBool CRSAAlgo::EncryptL(const TDesC8 &aInput,TDes8 &aOutput)
{
if(iEncryptor)
{
TInt len = iEncryptor->MaxInputLength();
}
}
i want to know what is exact problem
A: The main issue here, the reason your compiler complains is that you are using iEncryptor as an object or a reference, while it probably is a C++ pointer.
To move to the next stage, try using:
iEncryptor->EncryptL(text,cipher);
A: As you did not post the exact error message you get from the compiler I have to guess.
I assume the problem is that the EncryptL function you show expects to get arguments of type TDesC8 and you pass a TBuf8<10> to it. Unless TDesC8 were a typedef to TBuf8<10> these are different and therefore for the compiler incompatible types.
Ypou are also using iEncryptor once as a pointer: iEncryptor->MaxInputLength(); and at the location where you see the error as an object: iEncryptor.EncryptL(text,cipher);. Only one form can be correct. As we don't have more code from you I don't know which, but given the fact that the latter has the error I suspect the latter.
| |
doc_23533980
|
But for some reason, I cannot check to see if that file exists, so every time the page loads it re-creates the file. Every example I look for talks about checking to see if the blob storage container exists, I just want to find this file.
A: If your blob container is public and you know the name of the blob, you can manually send a HTTP request for the blob (e.g. http://myaccount.blob.core.windows.net/mycontainer/myblob) and check the result. If the result is 404 (Not Found) error, that means the blob does not exist. However if the blob container is private, then what you could do is try and fetch the properties of the blob either by using REST API or Storage Client library. A 404 error would mean that the blob does not exist. However you would need to think about your storage account credentials as you mentioned it is a Flash application and you may not want to store the credentials in the application itself.
A: Is a tool like Cerebrata's Cloud Storage Studio something that would help? You can browse your Azure storage contents to see if that blob exists, and also see if your application is continuously creating new ones.
The Developer Edition is free.
| |
doc_23533981
|
function showDiagram(row){
var authCode = $("#authCode").text();
var header = "basic" + authCode;
console.log("In show diagram");
var id = row.children().eq(6).text();
openURL = restURL + "/service/runtime/process-instances/" + id + "/diagram";
console.log(openURL);
var xhr
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}
else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", openURL, false);
xhr.setRequestHeader("Authorization", "Basic " + authCode);
xhr.send();
console.log(xhr.status);
if(xhr.status==200){
callFancybox(openURL);
}else{
alert("The diagram cannot be shown!");
}
}
However, I have met two different error situations.
*
*The browser still ask me to enter username and password when I access the url for the first time, at the same time, console print out status = 200 and fancybox has already popped up, if I refuse to enter password, a GET 401(Unauthorized) error will be returned. If I entered the password, the diagram will show in fancybox and it will work well for all other url I am trying access.
*Console print out status = 200 and the fancybox will pop and show "The requested content cannot be loaded.
Please try again later." And a GET 401(Unauthorized) error will be returned.
Why this happening? What should I do to bypass auto login and display the url in fancybox? Thank you very much for any ideas!
A: You're not specifying what is on the server side, and the problem is there. You must modify your server so that it supports your header authentication. With your current implementation the server is ignoring the headers, and so it's challenging you to indentify in a different way.
Besides you'r not sending any kind of credentials or whatever. You must add headers with that information.
| |
doc_23533982
|
My header:
function Header () {
const [isOpen, setIsOpen] = useState(false)
return(
<>
<header className="header">
<div className="wrap">
<span className="btn-icon">
<IconPlus onClick={() => setIsOpen(true)} className="icon icon-plus js-modal-init"/>
</span>
</div>
<div className="header-inner">
<div className="wrap">
<img className="logo" src="images/pic.svg" alt="Pic"/>
<div className="date-wrap">
<IconCalendar className="icon icon-plus js-modal-init"/>
<time>02 / 08 / 2019</time>
</div>
</div>
</div>
</header>
<ModalWindow open={isOpen} onClose={() => setIsOpen(false)} />
</>
)
}
ModalWindow:
export const ModalWindow = ({open, onClose}) => {
if(!open) return null
return(
<div className="modal-wrap js-modal">
<div className="modal js-modal-inner">
<h2>Create a task:</h2>
<form action="">
<div className="field-wrap">
<label className="label" for="">Title:</label>
<input className="field" type="text" id="" placeholder="Enter title here..."/>
</div>
<div className="field-wrap">
<label className="label" for="">Hours:</label>
<input className="field" type="text" id="" placeholder="Add hours here..."/>
</div>
<div className="btn-wrap align-right">
<input onClick={onClose} className="btn" type="submit" value="Create"/>
</div>
</form>
</div>
</div>
)
}
css:
.modal-wrap {
display: flex;
visibility: visible;
position: fixed;
z-index: 1;
top: 0;
left: 0;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
transition: 350ms ease-in-out;
opacity: 0;
background-color: rgba(0, 0, 0, 0.7);
}
.modal {
position: relative;
width: 100%;
max-width: 700px;
padding: 50px 40px;
background-color: #fff;
box-shadow: 2px 2px 15px rgba(0, 0, 0, 0.2);
}
.modal h2 {
margin-top: 0;
margin-bottom: 1em;
color: #666;
font-size: 30px;
font-weight: 300;
}
.modal-wrap.is-visible {
visibility: visible;
opacity: 1;
}
A: In your Header component, try wrapping the "IconPlus" tag with a button and onClick attribute.
| |
doc_23533983
|
#include <stdio.h>
long long int decimal(long long int);
int power_2 (int);
long int power_10 (int);
int main(void){
long long int n;
while(1){
printf("Write down a binary number. \n");
scanf("%lld", &n);
long long int a = decimal(n);
printf("The binary number %lld converted into decimal is: %lld \n", n, a);
}
}
//Here what I realized is if let's say I have the number 1001, then I subtract 1 and divide by 10, the remainder is going to be 0, meaning it will "jump" on the second if statement. I don't really know how to solve it.
long long int decimal(long long int e){
long long int result;
long long int k = 0;
int i;
for(i=0; i>=0; i++){
if(e % 10 == 1){
k += power_2(i);
e--;
if(e != 0){
e /= 10;
}
}
if(e % 10 == 0){
e /= 10;
if(e==0){
break;
}
}
return(k);
}
//This function should work, so it's not a problem
int power_2(int n){
int base = 2, i, result = 1;
if(n>0){
for(i=1; i<=n; i++){
result *= base;
}
}
if(n=0){
result = 1;
}
return(result);
}
//This is just something I thought I would need but no
long int power_10(int n){
int base = 10, i, result = 1;
if(n>0){
for(i=1; i<=n; i++){
result *= base;
}
}
if(n=0){
result = 1;
}
return(result);
}
A: You can't use scanf with %lld to input a binary number string (e.g. 10101010101010101010101010101010101). It will interpret the number incorrectly.
You have to accept it as a char string (e.g).
char str[100];
scanf("%s",str);
But, scanf is problematic because it can overflow str. And, IMO, the "usual" remedy of:
scanf("%99s",str);
Is a hack [because if we ever change to (e.g.) char str[80]; then we have to manually change the scanf as well].
Better to use fgets:
char str[100];
fgets(str,sizeof(str),stdin);
str[strcspn(str,"\n")] = 0;
Then, loop on the string. No need for power* functions. You want:
long long int decimal(const char *e){
Loop on e and do: k <<= 1;
Here is the refactored code:
#include <stdio.h>
#include <string.h>
long long int
decimal(const char *e)
{
long long int result = 0;
for (int chr = *e++; chr != 0; chr = *e++) {
result <<= 1;
switch (chr) {
case '0':
case '1':
result += (chr - '0');
break;
default:
fprintf(stderr,"decimal: not a binary digit -- chr='%c'\n",chr);
break;
}
}
return result;
}
int
main(void)
{
char str[100];
while (1) {
printf("Write down a binary number.\n");
if (fgets(str,sizeof(str),stdin) == NULL)
break;
// strip newline
str[strcspn(str,"\n")] = 0;
long long int a = decimal(str);
printf("The binary number '%s' converted into decimal is: %lld (hex: %llX)\n",
str, a, a);
}
return 0;
}
Here is some sample output:
Write down a binary number.
110010111001
The binary number '110010111001' converted into decimal is: 3257 (hex: CB9)
Write down a binary number.
UPDATE:
Apart from the possibility of "overfilling" the register with bits (accepting a string that is more than 32 or 64 'bits'), someone here on SO recently pointed out that left shifting (possibly into the sign bit) a "signed" value can invoke UB... –
Fe2O3
I'm not sure it's UB (depending on the context). But, to keep the peace, here's a version that sets errno:
#include <stdio.h>
#include <string.h>
#include <errno.h>
#ifndef UNSIGNED
#define UNSIGNED 0
#endif
#if UNSIGNED
typedef unsigned long long num_t;
#define FMT "%llu"
#else
typedef long long num_t;
#define FMT "%lld"
#endif
num_t
decimal(const char *e)
{
int count = 0;
long long int result = 0;
errno = 0;
// NOTE: use of error codes is arbitrary
for (int chr = *e++; chr != 0; chr = *e++) {
result <<= 1;
if (++count > (63 + UNSIGNED)) {
fprintf(stderr,"decimal: too many digits\n");
errno = E2BIG;
break;
}
switch (chr) {
case '0':
case '1':
result += (chr - '0');
break;
default:
fprintf(stderr,"decimal: not a binary digit -- chr='%c'\n",chr);
errno = EINVAL;
break;
}
if (errno)
break;
}
return result;
}
int
main(void)
{
char str[100];
while (1) {
printf("Write down a binary number.\n");
if (fgets(str,sizeof(str),stdin) == NULL)
break;
// strip newline
str[strcspn(str,"\n")] = 0;
num_t a = decimal(str);
printf("The binary number '%s' converted into decimal is: " FMT " (hex: %llX)\n",
str, a, a);
}
return 0;
}
Caveat: The following is off topic for this question, but, in response to the comments below ...
Neither of those, although... No, the DV for braces (not an anonymous drive-by shooting!) was for stackoverflow.com/a/74010599/17592432, the most trivial game on the planet... :-) /sigh/ –
Fe2O3
I agree that leaving off the curly braces is not ambiguous. But, I would add them for human clarity. Note that GNU indent complains about premature EOF when trying to indent the code.
But, I eschew if/else ladder logic. In your block, using an if and then switch/case would be clearer, IMO.
And, I've never liked else if because to me, to properly indent it, we'd have:
if (user == robot)
printf("It's a tie!");
else
if (user == 1)
if (robot == 2)
printf("Robot wins by choosing Paper!");
else
printf("User wins by choosing Rock!");
else
if (user == 2)
if (robot == 1)
printf("User wins by choosing Paper!");
else
printf("Robot wins by choosing Scissors! ");
else
if (user == 3)
if (robot == 2)
printf("User wins by choosing Scissors!");
else
printf("Robot wins by choosing Rock!");
So, [to further muddy the waters] I prefer using do { ... } while (0):
do {
if (user == robot) {
printf("It's a tie!");
break;
}
if (user == 1) {
if (robot == 2)
printf("Robot wins by choosing Paper!");
else
printf("User wins by choosing Rock!");
break;
}
if (user == 2) {
if (robot == 1)
printf("User wins by choosing Paper!");
else
printf("Robot wins by choosing Scissors! ");
break;
}
if (user == 3) {
if (robot == 2)
printf("User wins by choosing Scissors!");
else
printf("Robot wins by choosing Rock!");
break;
}
} while (0);
UPDATE #2:
May at least want to mention POSIX and _t types (I'm guilty as charged on the use as well) –
David C. Rankin
Sigh, I was hoping to have a quiet day ;-)
First, I like [love] POSIX (vs. ISO/C). But, claiming all *_t and all _* as POSIX only is hubris.
The _* [for private functions] is quite common in other languages (e.g. python).
As to *_t types, I've been doing that for decades and never once hit a conflict. And, if I did, it's my responsibility as the programmer to fix that [by changing my code or the #include statements]. That is, assess the risks beforehand.
Worse, I also do (e.g.) typedef struct foo foo_t, *foo_p;. Note the *_p for a pointer type that seems to burn people here on SO.
But, it's arguably no worse that MS/Win's pType for pointers. And, it's my convention. And, it's passed code reviews plenty of times.
So, as Nixon once said (re. "Checkers"): Regardless of what they say about it, we're gonna keep it.
A: #ifndef MUST_REINVENT_THE_WHEEL
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
char str[100];
printf("Write down a binary number. \n");
fgets(str,100,stdin);
printf("Decimal: %ld\n", strtol(str,0,2));
}
#endif
A: You want to accept an integer value that is the sum of 10^x
Eg 10^6 + 10^4 + 10^2 + 10^1 = 1010110 (base 10)
Then interpret that as a series binary bits
2^6 + 2^4 + 2^2 + 2^1 = 1010110 (base 2)
You're on the right path with dividing by ten, but I get lost in the confusing code that you've written. Here's a simple sample that seems to work (using long with my 32 bit compiler.) It combines bit-shifting and divide-by-ten, and testing whether-or-not to set the current bit in the output accumulator.
int main() {
long in = 10110101, wrk = in;
unsigned long out = 0;
for( unsigned long bit = 1; wrk; wrk /= 10, bit <<= 1 )
if( wrk & 1 )
out |= bit;
printf( "in %ld out %ld (hex %X )\n", in, out, out );
return 0;
}
in 10110101 out 181 (hex B5 )
Testing for negative values seems silly in this "toy" application. There's no way the range of 2^32 can accommodate 10^32.
A: Turned out my program was pretty much correct. Only thing I missed is the second if in the decimal function should be an else if.
Here's the correct program:
#include <stdio.h>
long long int decimal(long long int);
int power_2 (int);
int main(void){
long long int n;
while(1){
printf("Write down a binary number. \n");
scanf("%lld", &n);
long long int a = decimal(n);
printf("The binary number %lld converted into decimal is: %lld \n", n, a);
}
}
long long int decimal(long long int e){
long long int k = 0;
int i;
for(i=0; i>=0; i++){
if(e % 10 == 1){
k += power_2(i);
e--;
if(e != 0){
e /= 10;
}
}
else if(e % 10 == 0){
e /= 10;
}
if(e==0){
break;
}
}
return(k);
}
int power_2(int n){
int base = 2, i, result = 1;
if(n>0){
for(i=1; i<=n; i++){
result *= base;
}
}
if(n=0){
result = 1;
}
return(result);
}
Example:
Write down a binary number.
100010101011
The binary number 100010101011 converted into decimal is: 2219
| |
doc_23533984
|
I would prefer it line up the arguments, like this:
Is there a setting somewhere to do this automatically, so I don't have to manually indent the code?
(I also want to do this for function calls.)
A: Probably check out some linters if they can do it for you. Search in Extensions for plugins such as eslint or tslint.
| |
doc_23533985
|
The following directory should be added to compiler include paths:
XXX/boost_1_52_0
The following directory should be added to linker library paths:
XXX/boost_1_52_0/stage/lib
How do I add a compiler include path and a linker library path in Xcode? Many thanks.
A: I should mention the following is for Xcode 4.5.2. You should likely mention which version of Xcode you're using in your question.
*
*In the Project Navigator select your project file (usually at the top)
*Given the two view choices of Basic or All, choose All in the view pane.
*Locate the Search Paths section in the settings list
*Locate the Header Search Paths subsection under Search Paths
*Add the path (absolute or relative to the source folder). You can do it for Debug, Release, or Both.
And in case you didn't see it, you can add addition library search paths here as well, same area, subsection Library Search Paths
Updated for Xcode 5.0.2
*
*In the Project Navigator select your project file (usually at the top)
*In the right pane is the project configuration panel. Toward the top-left are two sets of selectable radio options. One says Basic or All, choose All. The second says Combined or Levels, choose Combined.
*Locate the Search Paths section in the settings list
*Locate the Header Search Paths subsection under Search Paths
*Add the path (absolute or relative to the source folder). You can do it for Debug, Release, or Both.
| |
doc_23533986
|
public class Player extends MovieClip
{
private var playerHalfWidth:int = this.width/2;
I get this error:
1119:Access of possibly undefined property width through a
reference with static type class
A: You are trying to reference this even before Player object is created.
Moving it into the constructor, would be the correct way :
public class Player extends MovieClip {
private var playerHalfWidth:int;
public function Player() {
playerHalfWidth = this.width/2;
}
| |
doc_23533987
|
A: You need to look into the scripting object of UIWebView, and then do some work on the javascript side to send the data out of the web view, into your view controller. Then you can do whatever you want with it. Save as a document etc.
Please take a look at this: windowScriptObject
Unfortunately I think this is still a private API in iOS (unlike on the Mac). But looking at solutions around this topic, you may find something.
And please use interpunction.
| |
doc_23533988
|
public class SerialNumberGenerator {
private static volatile int serialNumber = 0;
public static int nextSerialNumber() {
return serialNumber++;
}
}
class CircularSet {
private int[] array;
private int len;
private int index = 0;
public CircularSet(int size) {
array = new int[size];
len = size;
for (int i = 0; i < size; i++) {
array[i] = -1;
}
}
synchronized void add(int i) {
array[index] = i;
index = ++index % len;
}
synchronized boolean contains(int val) {
for (int i = 0; i < len; i++) {
if (array[i] == val)
return true;
}
return false;
}
}
public class SerialNumberChecker {
private static final int SIZE = 10;
private static CircularSet serials = new CircularSet(1000);
private static ExecutorService exec = Executors.newCachedThreadPool();
static class SerialChecker implements Runnable {
@Override
public void run() {
while (true) {
int serial = SerialNumberGenerator.nextSerialNumber();
if (serials.contains(serial)) {
System.out.println("Duplicate: " + serial);
System.exit(0);
}
serials.add(serial);
}
}
}
public static void main(String[] args) throws Exception {
for (int i = 0; i < SIZE; i++) {
exec.execute(new SerialChecker());
}
}
}
example output:
Duplicate: 228
I don't understand how is it possible. Even method nextSerialNumber() is not synchronized and all thread generate different values each thread has own value of serial and each are different. So how is it possible to find duplicate. I cannot imagine of threads execution.
A: This example shows the post-increment operator is not atomic and not thread-safe.
What happens in this code is:
*
*many (up to 100) threads are started, each executing the same code
*in an infinite loop:
*
*an unsynchronized method nextSerialNumber is called, which returns the result of the post-increment operator called on a static variable
*a synchronized method contains is called, which checks if the returned value exists in the underlying collection
*if yes, the program is terminated
*if not, the value is added to the underlying collection
If the post-increment operation was thread-safe then the program would never print "Duplicate" and would never terminate,
since every thread would be getting a different serial number value. This is not the case as two threads
might get exactly the same serial number value.
| |
doc_23533989
|
function buildChart(targetDiv){
//grab the destination
var bc = dojo.byId(targetDiv);
//define the data for the series
var testData = [2,4,2,2,2,3,2,10,11,12,8,4];
var string = "2,4,2,2,2,3,2,10,11,12,8,4";
var convertedString = string.split(",");
console.log("Variable testData value is " + typeof(testData));
console.log("Variable convertedString value is " + typeof(convertedString));
//build the chart
dojo.attr(bc,"style","width:300px;height:200px;");
var chart = new dojox.charting.Chart2D(bc);
chart.addPlot("default", {type: "Lines"});
chart.addAxis("x");
chart.addAxis("y", {vertical: true});
//chart.addSeries("Series 1 works fine", testData);
chart.addSeries("Series 2 not working", convertedString);
chart.render();
}//buildChartenter code here
Notice that the testData variable works fine, but the convertedString variable does not. I must be missing something very simple. How would I cast an inbound string variable to work in this case?
A: Yep, it is easy: testData is the array of numbers, while convertedString is the array of strings.
You can convert those strings to numbers like that:
var convertedString = dojo.map(string.split(","), parseFloat);
Or you can do it manually:
var convertedString = string.split(",");
for(var i = 0; i < convertedString.length; ++i){
convertedString[i] = parseFloat(convertedString[i]);
}
PS: Using string as in identifier seems … wrong.
| |
doc_23533990
|
I have tried to use the following in both rabbitmq.config and advanced.config (anonymized so I could post it here). I have tried using rabbitmq_auth_backend_ldap and rabbit_auth_backend_ldap.
[
{rabbit, [{auth_backends, [rabbit_auth_backend_ldap]}]},
{rabbitmq_auth_backend_ldap,
{servers, ["server1", "server2"]},
{timeout, infinity},
{log, true},
{dn_lookup_attribute, "sAMAccountName"},
{dn_lookup_base, "DC=a,DC=b"},
{user_dn_pattern, "${username}@domain.com"},
{vhost_access_query, {in_group, "ou=${vhost}-users,ou=vhosts,dc=example,dc=com"}}
}
].
However in all cases, I get the following message in the logs.
2018-04-18 11:45:28.048 [warning] <0.452.0> LDAP plugin loaded, but rabbit_auth_backend_ldap is not in the list of auth_backends. LDAP auth will not work.~n
The log message reads rabbit_auth_backend_ldap regardless of whether I use rabbitmq_auth_backend_ldap or rabbit_auth_backend_ldap. The documentation mentions both rabbit_auth_backend_ldap and rabbitmq_auth_backend_ldap .
I have installed the plugin and see the following in the log.
2018-04-19 09:27:02.354 [info] <0.5.0> Server startup complete; 4 plugins started.
* rabbitmq_management
* rabbitmq_management_agent
* rabbitmq_auth_backend_ldap
* rabbitmq_web_dispatch
| |
doc_23533991
|
public class RateCodes
{
public int Id { get; set; }
//Unique Composite Key Field 1
public int Sequence { get; set; }
//Unique Composite Key Field 2
public int DivisionId { get; set; }
public Decimal RateCode { get; set; }
}
In our client we want to allow a user reorder the sequence of their rate codes.
However when I perform an update I get an exception
"System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details.
System.Data.SqlClient.SqlException: Violation of UNIQUE KEY constraint 'UX_RateCodes_Sequence'. Cannot insert duplicate key in object 'dbo.RateCodes'. The duplicate key value is (346, 3)
Despite the fact that I'm saving all at once, SQL is throwing a unique violation because SQL performs the unique key validation before all of the data is updated.
I don't want to delete my data before saving because other application could be operating on the table and I might not have all of the data in the current application. How can I solve this issue?
A:
How can I Solve this issue?
This is not a terribly easy problem to solve, as stated. Updating keys is inherently problematic, and unique constraints are not deferrable.
An easy way to solve this with modeling is to introduce a new, non-key attribute to store the ordering. This has the added benefit of allowing you to use a decimal or float for the ordering column, so you an always insert in item between two existing items.
Another idea is to use the new attribute to store the to-be ordering, after a series of updates and delete, issue a single
update RateCodes set sequence = sequence_new
where id = @id and sequence_new is not null
to perform the recording in a single statement. You could do the same pattern with a temp table that re-maps the values. But all of this requires some level of direct SQL coding.
| |
doc_23533992
|
Given a list of elements like this:
<div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
I would like to achieve the result in the picture above. I tried to use flexboxes using "flex:50%" for every child element but all I was able to achieve is this.
Is there a clean way to achieve this without using more divs ?
| |
doc_23533993
|
some of these projects are new initiative and some are incremental improvements over existing software that we built.
our senior management is looking for a sleek way to visualize all the projects going on including:
*
*Size of effort in time and resources
*ROI expected from the work
*Indicate incremental improvement versus new initiative.
the reason is that we probably want to move resources around to ensure top ROI but not all developer are fungible depending on their skill set.
in my head, this results in some type of heatmap or dashboard, but i wanted to see if there are any recommend solution or tools out there that attack this area.
right now we just have spreadsheets listing out each project and resources and somehow it doesn't really give a good visualization of whats actually happening.
any suggestions?
A: Agilefant is an open-source tool that "brings together the perspectives of long-term product and release planning and project portfolio management", and is being actively developed. I would try the 2.0-alpha release (accessible via the Downloads page) for improved visualization tools, but you can also try the live demo to get the idea of what Agilefant can do.
A: A classic consultant's technique... I would start by plotting them on a 2x2 graph. Make the vertical axis the ROI, with high at the top, make the horizontal axis two partitions of incremental improvement on the left and new initiative on the right - and I bet there are some projects which are a bit of both, so maybe you have a continuum. Plot each project on those axes as a circle and make the area of the circle represent the number of man days.
Stuff in the top right is high return, new initiatives, stuff in the bottom left is low return maintenance/incremental improvements. If you do one chart for current resource deployment and another for planned resource deployment you'll get a strong feel for how you are spending your manpower.
There are many variations on this and you can choose what you want to plot where to best show your story. It is simple and powerful as a visual aid and you can get 90 circles on your chart without losing the woods for the trees.
HTH and good luck.
A: G'day,
Have a read of Johanna Rothman's excellent book "Manage Your Project Portfolio" that addresses this very issue by providing an approach to evaluate multiple projects to determine a priority.
Edit: I forgot to say that I'm applying the technique myself across multiple work streams atm.
HTH
A: As I understand this question the solution is highly dependent on final goal which actually is unclear in most of similar cases.
Before doing some 'kanban-like diagrams' for this case especially having in mind declared goal (I suggest it is only mean, not a goal) to re-balance work force I'd recommend to think about next points:
*
*Every single developer's efficiency highly depends on many factors individual to current projects. There are 'refactoring-aware' people / 'support-likers' / e.t.c. So being placed in another environment ... this could change anything.
*Well, doing efforts re-balance. What happens to existing team structure? Good aligned teams with proper roles of every person are VERY RARE. Does it worth to break good team for some estimation (in the sky)?
So I'd recommend (instead or in addition to project efficiency tracking) to track developers efficiency / satisfaction / team efficiency / satisfaction and try to solve how to re-balance efforts not only because of ROI but to get most from people (at least unless projects are profitable not to put ROI estimations over all). Don't ruin successful (not so but yes) project just because someone needs one developer in other bright project.
OK, this is just my general opinion but it greatly helped me during last year. Hope it will help someone too.
| |
doc_23533994
|
When can the status be set to FAILED? Is it possible for it to transition to FAILED from one of the other statuses?
A: A transaction status of FAILED will occur if a transaction is authorized using delay_capture and when the Capture endpoint is called it will return an error of DELAYED_TRANSACTION_FAILED.
| |
doc_23533995
|
How do I prevent the drop in framerates? My display will need to occasional display the graph full screen, which causes the framerates to drop to an unacceptable value.
I heard the EVR (Enhanced Video Render) is much better than the VMR9. Will the EVR maintain the framerates when increasing the size of the display?
A: You should specify video compression codec (MediaSubType) when initializing directshow graph. I had the same problem when trying to capture video from web camera using default compression (in my case it was YUY2).
Example:
/// <summary>
/// Configures the DirectShow graph to play the selected video capture
/// device with the selected parameters
/// </summary>
private void SetupGraph()
{
...
if (UseYuv && !EnableSampleGrabbing)
{
/* Configure the video output pin with our parameters and if it fails
* then just use the default media subtype*/
if (!SetVideoCaptureParameters(graphBuilder, m_captureDevice, MediaSubType.YUY2))
SetVideoCaptureParameters(graphBuilder, m_captureDevice, Guid.Empty);
}
else
/* Configure the video output pin with our parameters */
SetVideoCaptureParameters(graphBuilder, m_captureDevice, MediaSubType.MJPG); // Change default compression to MJPG.
...
}
Example can be found in WPFMediaKit.DirectShow.MediaPlayers.VideoCapturePlayer.
| |
doc_23533996
|
I have an app that pulls data from Google Analytics using garb. After doing some number crunching with the data, the app will populate a Report model and display the report to the user.
Right now, I'm separating the Google Analytics logic using concerns. In my concerns folder, I have a GoogleAnalytics module that is responsible for pulling the data. The Report model includes the GoogleAnalytics module. Before the number crunching in the Report model takes place, I need to clean up and reformat the data. Should this be a responsibility of the GoogleAnalytics module or maybe a helper?
Is there a better practice for including third party services?
A: The reformatting should go on whatever is responsible for pulling the data from Google Analytics. None of the rest of your app should have to know the format of how Google Analytics returns it's data - the module should convert it into a sensible, standard interface and hide all of that from everyone else.
I would also strongly consider putting this stuff into a service object rather than a module. Including modules gets messy because you when you call a method on an object you don't know where that method is defined. I would only use this pattern if you were including the same module in lots of other models and it was a true DRY play.
A service object would look something like (depending on what params you need to use to pull the data):
class GoogleAnalyticsDataFetcher
attr_accessor :data
def new ga_id
@ga_id = ga_id
end
def fetch
@data = do_some_stuff
end
end
and then you could call it either from your controller or wrap it up inside the Report model somewhere. Then when you go GoogleAnalyticsDataFetcher.new(id).fetch it's incredibly obvious what is going on and where it is defined.
| |
doc_23533997
|
I got alarmed by it and quickly went to try it:
>>> def foo(): return "hello_world!"
...
>>> def bar(): foo()
...
I realize every function in python returns (either None or something else)
To my surprise when I tried the same logic in my previously learned languages, they seem to show similar behavior:
C:
#include<stdio.h>
char* foo(){return "hello_world!";}
int main(void){
foo(); // works!
return 0;
}
C++
#include<iostream>
#include<string>
using namespace std;
string foo(){return "hello_world!";}
int main(){
foo(); // works!
return 0;
}
Java:
public class Test{
public static String foo(){return "hello_world!";}
public static void main(String args[]){
foo(); // works!
System.exit(0);
}
}
All this time I was assuming if a function actually returns something, it SHOULD be set to some variable, otherwise where would the returned value go?!
A: It disappears.
In case of languages and runtimes in which an object is returned that would need to be garbage collected, the result of calling that function is eligible for collection as soon as the function returns.
In case of languages and runtimes that return an object that is reference counted, or similarly protected, to force an immediate cleanup when the object is no longer needed, that cleanup will occur when the function has returned.
Otherwise, for all intents and purposes, the value is just lost. There's no harm done and should be perfectly safe to do.
A:
All this time I was assuming if a function actually returns something, it SHOULD be set to some variable, otherwise where would the returned value go?!
It goes into the bit bucket. wikipedia article: http://en.wikipedia.org/wiki/Bit_bucket
An example:
std::set<std::string> set_of_strings;
...
set_of_strings.insert (some_string);
Here std::set::insert() returns a std::pair, an iterator pointing to the element in the set and a bool indicating whether an element was added. In this case that returned std::pair is just going to disappear. In many cases you just don't care whether an element with the same value was already present. In such cases there is no reason to check the second return value. In many cases you don't care about the iterator, either. So just let it go away.
Some overly pedantic programmers will type the above like this:
std::set<std::string> set_of_strings;
...
(void) set_of_strings.insert (some_string);
The (void) supposedly tells the compiler to ignore the return result. However, the compiler doesn't need to be told to do that. It will ignore the return result if it is not used. What the (void) supposed does do is to tell readers of the code that the return value is intentionally being ignored.
However, you would never do this:
(void) x = 42.0;
(void) a = b = c = 42;
Both of those assignment statements return a value. (You wouldn't be able to say a = b = c = 42 if it didn't.) This is just but one of many examples showing that you send data to the bit bucket all the time without knowing it.
My recommendation: Don't use (void) to announce that you are intentionally ignoring the return result. The compiler doesn't need it, a reasonable reader of the code doesn't needed, and it just makes the programmer who wrote it look like an arrogant know-it-all who most likely knows a lot less than they think they do.
A: In the case of C, implementation dependant. Often the result from a function will be placed in a machine register rather than on the stack. It is then up to the caller as to whether it is used or not.
| |
doc_23533998
|
timeStamp - sensor(tag) - value(field).
To query the values of more than one tag, the documentation provides the following:
SELECT value FROM measurement WHERE sensor=sensor_1 OR sensor=sensor_2 OR ...
Which results a single column of values.
But how to divide the result values by the different sensors(tags) in multiple columns, maybe something like this:
SELECT value.sensor_1, value.sensor_2 FROM measurement ideally this should be applicable with influxdb-java.
A: Don't use SELECT, but GROUP BY clause:
GROUP BY sensor
The result will be row per sensor.
Doc: https://docs.influxdata.com/influxdb/v1.6/query_language/data_exploration/#the-group-by-clause
| |
doc_23533999
|
The arc has a position, radius, minimum and maximum angles, and the width of the arc itself. The rectangle has a position, width and height, and rotation.
How would one determine whether the arc and rectangle are intersecting?
Provided is a visual aid that may increase clarity. The green rectangles are those that would be considered to be intersecting, while the red rectangles are not intersecting.
I have determined that it is common to check intersections on each line segment of the rectangle individually, but I am not yet certain as to how one would account for the rectangle being on the inside of the arc but not close enough to be intersecting it.
A: For rectangles being completely inside the arc you can check - whether any corner point (x, y) belongs to thick arc. For arc center (cx, cy), inner and outer radii r and R and angles a0,a1:
dist = length(x - cx, y - cy)
if dist lies in range r..R:
angle = atan2(y-cy, x-cx)
if angle in range a0..a1:
rectangle is inside
One more non-standard case: to find whether arc completely lies inside large rectangle - just check if any point of arc lies in that rectangle.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.