id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23527100
|
File file = new File("in.txt");
try{
Scanner fileReader = new Scanner(file);
}
catch(Exception exp){
System.out.println(exp.getMessage());
}
I have an in.txt in the root of the project, src and bin directories in case I'm getting the location wrong. I have tried giving absolute paths as well. This line
Scanner fileReader = new Scanner(file);
always fails. Execution jumps to the end of main. If I misspell the name of the file, I get a FileNotFoundException. I'm on an Ubuntu 12.10 Java 1.7 with OpenJDK
A: If you do: File file = new File("in.txt"); in your java program
(let's assume it is named Program.java) then the file in.txt should
be in the working directory of your program at runtime. So if you
run your program like this:
java Program
or
java package1.package2.Program
and you are in /test1/test2/ when running this command,
then the file in.txt needs to be in /test1/test2/.
A: I am running on linux and this is how you need to do it
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Testing {
public static void main(String args[]) throws IOException {
Scanner s = null;
try {
//notice the path is fully qualified path
s = new Scanner(new File("/tmp/one.txt"));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
}
here is the result :
source from Java Docs
| |
doc_23527101
|
Sorry if this question is a little confuse, but i'm trying creating a API/webservice that works with MySql, so I have
in root (/) the file bd.js with the connection
bd.js:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'skey-9'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
then i add to /app.js and have the routes of diferente directories
app.js:
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const db = require('./bd');
const productRoutes = require('./api/routes/products');
const orderRoutes = require('./api/routes/order');
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json());
//Routes
app.use('/products', productRoutes);
app.use('/orders', orderRoutes);
in the final i'm trying to query a Select in /routes/products.js
products.js:
const express = require('express');
const router = express.Router();
var db = require('./../bd');
con.connect((err) => {
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
con.query('SELECT * FROM teste', (err,rows) => {
if(err) throw err;
console.log('Data received from Db:');
console.log(rows);
});
router.get('/', (req, res, next) => {
res.status(200).json({
message: 'handling GET requests to / products',
query: rows
});
});
module.exports = router;
but i'm getting a error i already tried to "playing" with the bd files.
the error:
C:\NODE\node-rest\server.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:957:15)
at Function.Module._load (internal/modules/cjs/loader.js:840:27)
at Module.require (internal/modules/cjs/loader.js:1019:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (C:\NODE\node-rest\api\routes\products.js:3:10)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Module.require (internal/modules/cjs/loader.js:1019:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\NODE\\node-rest\\api\\routes\\products.js',
'C:\\NODE\\node-rest\\app.js',
'C:\\NODE\\node-rest\\server.js'
]
My question is how can i do a "global" mysql connection to all the app I'm creating.
A: soo i have 2 subpath's, and for some reason i had to change
var db = require('./../bd'); "
to
var db = require('..\\..\\bd'); "
forget this dont resolve my problem, we have to run a connection to all the router's?
| |
doc_23527102
|
/**************CANVAS cropping img *********/
var canvas1 = document.getElementById('Canvas1');
var context1 = canvas1.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
// draw cropped image
var sourceX = 90;
var sourceY = 0;
var sourceWidth = 319;
var sourceHeight = 319;
var destWidth = sourceWidth;
var destHeight = sourceHeight;
var destX = canvas1.width / 2 - destWidth / 2;
var destY = canvas1.height / 2 - destHeight / 2;
context1.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
};
imageObj.src = 'OriginImg.jpg';
/**************CANVAS using cropping img *********/
var canvas2 = document.getElementById('Canvas2');
var context2 = canvas2.getContext('2d');
var img = new Image();
img.src = canvas1;
context2.drawImage(img, 10,10);
A: This isn't the standard way of drawing a canvas onto another one, and is discouraged, but if you want to use this method, you can always turn the first canvas into it's dataURL and use that as the src:
img.src = canvas1.toDataURL() will work just fine for you.
Check out the mdn page for .toDataURL().
The standard method would be to simply draw one of the canvases on the other:
ctx2.drawImage( canvas1, 0, 0 )
More information can be found in the mdn page for .drawImage()
| |
doc_23527103
|
There is no problem with the same module, if I do not nest it.
Here is a small example, where I display a table with data from input$
library(shiny)
# Selection module ----
select_module_ui <- function(id){
tagList(
selectInput(inputId = NS(id, "select1"),
label = "Select 1 from ui-section",
choices = c("Denmark", "Germany"),
selected = "Denmark"),
htmlOutput(outputId = NS(id, "select2_ui")),
tableOutput(outputId = NS(id, "myinputs"))
)
}
select_module_server <- function(id) {
moduleServer(id, function(input, output, session) {
all_inputs <- reactive({
myvalues <- NULL
for(i in 1:length(names(input))){
myvalues <- as.data.frame(rbind(myvalues,(cbind(names(input)[i],input[[names(input)[i]]]))))
}
names(myvalues) <- c("User Input","Last Value")
myvalues
})
output$select2_ui <- renderUI({
selectInput(inputId = NS(id, "select2"),
label = "Select 2 from server-section",
choices = c("Denmark", "Germany"),
selected = "Denmark")
})
output$myinputs <- renderTable({all_inputs()})
})
}
# Container module -----
container_module_ui <- function(id){
select_module_ui(id = NS(id, "select_module"))
}
container_module_server <- function(id) {
moduleServer(id, function(input, output, session) {
select_module_server(id = "select_module")
})
}
# Application -----
ui <- fluidPage(
h2("As a normal module"),
select_module_ui(id = "select_module_normal"),
hr(),
h2("As a submodule within a module"),
container_module_ui(id = "container_module")
)
server <- function(input, output, session) {
select_module_server(id = "select_module_normal")
container_module_server(id = "container_module")
}
shinyApp(ui, server)
Where there is input$ information when not nesting. And no information when nesting.
I suspect it is a problem with my use of NS(id, ...) call in the module_container_server, but the other server elements are displayed correctly (the selectInput and the renderTable). And it does not work to call the select_server using NS(id, ...)
container_module_server <- function(id) {
moduleServer(id, function(input, output, session) {
select_module_server(NS(id, "select_module"))
})
}
Thanks,
Lars
A: If you need to use NS() in server, then you need session$ns():
output$select2_ui <- renderUI({
selectInput(inputId = session$ns("select2"),
label = "Select 2 from server-section",
choices = c("Denmark", "Germany"),
selected = "Denmark")
})
| |
doc_23527104
|
Controller Code
[HttpPost]
public ActionResult Save(PersonInputModel inputModel) {
try{
Person person = new Person();
person.Name = inputModel.Name;
person.Age = inputModel.Age;
Add(person);
Save(person);
}
catch {
//handle the error
}
}
A: Well assuming you are sending an array (notice the [] brackets around the JSON string because what you have shown in your question is not valid JSON):
[{"Name": "Bob", "Age": "30"},{"Name": "Paul", "Age": "19"}]
you could take an array:
[HttpPost]
public ActionResult Save(PersonInputModel[] persons)
{
foreach (var person in persons)
{
var name = person.Name;
var age = person.Age;
...
}
...
}
| |
doc_23527105
|
import
.echo("test")
Output:
/home/user/anaconda3/envs/p36/lib/python3.6/site-packages//utils.py in echo(message, file, nl, err, color)
257
258 if message:
--> 259 file.write(message)
260 file.flush()
261
UnsupportedOperation: not writable
Has someone seen this before and knows how to work around? I have to use a lib via that uses . so not is not possible.
Update:
This commit to a jupyter branch of click solves the issue:
https://github.com/elgalu/click/commit/1cb7aaba8c9dd6ec760d3e7e414d0b4e5f788543#diff-d17772ee4f65879b69a53dbc4b3d42bd
A: I think that Jupyter hijacks and locks the STDOUT/STDERR (at least the one click is trying to use) and if you don't provide a stream to click.echo() it will attempt writing to the STDOUT/STDERR, hence the error.
You can work around it by passing an output stream like STDOUT yourself:
import click
import sys
click.echo("test", sys.stdout)
# test
A: In my case using Python 3 I wanted to preserve the click styling on my message both in the Jupyter notebook and when the code was run in the terminal. I handled it this way:
from io import UnsupportedOperation
import click
item = 'Your Name'
message = click.style('"{}"'.format(item), fg='red', bold=True)
try:
click.echo(message)
except UnsupportedOperation as err:
print('Error: "{}"'.format(err))
print(message)
The color is preserved in the notebook:
| |
doc_23527106
|
Project is linked to a lib which is integrating MKL. In the source code, I have this line
gaussNewton<5, 16>::myfunREE_33_GN_rsp_new(&inv_Controls,
&interOut, table_ENP3_local, coefForJacobian, interOut.vo);
when commented it is compiling, when uncommented there is this error...
error LNK2001: unresolved external symbol MKL_CBWR_Set
I suspect
*
*a link problem with MKL
*a problem related to visibility of template specialization
Have you seen such error before? What is this MKL_CBWR_Set ?
EDIT
Is there any issue related to call of static method with this syntax in case of template specialization:
gaussNewton<5, 16>::myfunREE_33_GN_rsp_new(&inv_Controls,
&interOut, table_ENP3_local, coefForJacobian, interOut.vo);
| |
doc_23527107
|
<form class="form-horizontal">
<button ng-click="approved()" class="unapproved" ng-if="article.current_revision.approved == false" ng-model="article.current_revision.approved">Unapproved</button>
</form>
What should I put in my controller to make this work?
A: It should be something like this where your controller has the approved fn which accepts the id.
ng-click="approved(article.id)"
Did I correctly understand your question? If not, please elaborate. A jsFiddle always helps tremendously too.
| |
doc_23527108
|
input = "abc12def34ghijklmno567pqrs"
numbers = /\d+/
input.gsub(numbers) { |m| p $~ }
Result is as requested:
⇒ #<MatchData "12">
⇒ #<MatchData "34">
⇒ #<MatchData "567">
Would someone break down what the answerer is doing in input.gsub(numbers) { |m| p $~ }?
Also, how would I access each of the MatchDatas?
A: Since I’m the answerer, I would try to explain.
$~ is one of Ruby predefined globals. It returns the MatchData from the previous successful pattern match. It may be accessed using Regexp.last_match as well.
As stated in the documentation, gsub with block is commonly used to modify string, but here we use the fact it calls the codeblock on every match. Block variable m there is a simple string for that match, so whether we need the whole MatchData instance, we should use the predefined global $~. In the mentioned example we simple print each MatchData with p $~.
The trick here is that $~ returns the last MatchData. So, everything you need is to use $~ variable despite it’s repulsive look. Or, you might set:
my_beauty_name_match_data_var = $~
and play with the latter. Hope it helps.
| |
doc_23527109
|
The syntax for cross referencing is found here
A label must precede the section in order to allow that section to be referenced from other areas of the documentation.
What I have is a .rst (ReStructeredText) file for one of my classes. It uses
.. autoclass:: classname
:members:
To generate documentation for the class.
My question is, how would I reference the auto-generated methods of the class from another .rst document in the documentation? If I try to place a label within the method's docstring, Sphinx complains. If I try to place a label before the method heading, Sphinx doesn't recognize it.
Is there a simple way to do this, or will I have to explicitly write in my class file the method name and precede that with a label?
Here is an example a reference within the [Python documentation2 doing what I need (I am assuming it used the autodoc feature, though I don't know for sure)
A: In addition to the excellent answer already provided:
To add an alias to the referenced module (method, function, attribute, etc.), the following syntax is used:
:mod:`Alias Name <package.module>`
This will appear as a reference to Alias Name in the docs, and link to the module provided.
A: You don't need to add labels. In order to refer to a Python class, method, or other documented object, use the markup provided by the Python domain.
For example, the following defines a cross-reference to the mymethod method:
:py:meth:`mymodule.MyClass.mymethod`
Or even simpler (since the Python domain is the default):
:meth:`mymodule.MyClass.mymethod`
The documentation of TextWrapper.wrap that you link to in the question includes two cross-references of this kind (click on "Show Source" to see the reST markup).
| |
doc_23527110
|
There are problems in current code with mixed data type and limitations of ODBC driver.
SO I am planning to use Jet OLE DB driver and use ADO
The code I have opens ADO connection and reads excel sheet.No issues here..
The biggest problem is everytime, Open() is called, it brings up the Excel sheet and displays to the user (if it is not already open).
I tried to look into the parameters, but did not find any suggestions to hide main excel window.
Any suggestions?
The connection string I am using is
Provider='Microsoft.JET.OLEDB.4.0';Data Source=temp.xls;Extended Properties="Excel 8.0;IMEX=1;HDR=NO"
A: Three options spring to mind:
*
*Use Automation to open the spreadsheet in a hidden window. I.e. you can create an instance of the Excel application, hide the main window, and open the spreadsheet in that window.
*Use the ISAM driver instead of the JET driver. That may change the behaviour in undesirable ways though.
*Live with it.
| |
doc_23527111
|
kubectl run bb --image=busybox --generator=run-pod/v1 --command -- sh -c "echo hi"
Pod is getting created repeatedly
bb 1/1 Running 1 7s
bb 0/1 Completed 1 8s
bb 0/1 CrashLoopBackOff 1 9s
bb 0/1 Completed 2 22s
bb 0/1 CrashLoopBackOff 2 23s
bb 0/1 Completed 3 53s
exit code is 0
k describe pod bb
...
State: Waiting
Reason: CrashLoopBackOff
Last State: Terminated
Reason: Completed
Exit Code: 0
Started: Thu, 29 Aug 2019 22:58:36 +0000
Finished: Thu, 29 Aug 2019 22:58:36 +0000
Ready: False
Restart Count: 7
Thanks
A: kubectl run defaults to setting the "restart policy" to "Always". It also sets up a Deployment in this case, to manage the pod.
--restart='Always': The restart policy for this Pod. Legal values
[Always, OnFailure, Never]. If set to 'Always' a deployment is created,
if set to 'OnFailure' a job is created, if set to 'Never', a regular pod
is created. For the latter two --replicas must be 1. Default 'Always',
for CronJobs `Never`.
If you change the command to:
kubectl run bb \
--image=busybox \
--generator=run-pod/v1 \
--restart=Never \
--command -- sh -c "echo hi"
A Job will be setup and the pod won't be restarted.
Outside of kubectl run
All pod specs will include a restartPolicy, which defaults to Always so must be specified if you want different behaviour.
spec:
template:
spec:
containers:
- name: something
restartPolicy: Never
If you are looking to run a task to completion, try a Job instead.
A: Please see the Last state reason which is Completed.
Terminated: Indicates that the container completed its execution and has stopped running. A container enters into this when it has successfully completed execution or when it has failed for some reason. Regardless, a reason and exit code is displayed, as well as the container’s start and finish time. Before a container enters into Terminated, preStop hook (if any) is executed.
...
State: Terminated
Reason: Completed
Exit Code: 0
Started: Wed, 30 Jan 2019 11:45:26 +0530
Finished: Wed, 30 Jan 2019 11:45:26 +0530
...
Please see more details here. And you can try something like this will show the difference.
kubectl run bb --image=busybox --generator=run-pod/v1 --command -- sh -c "sleep 1000"
| |
doc_23527112
|
I'm trying to run a unit test (MS unit tests) from the command line. It's my first time attempting this.
My command works fine (no syntax errors), which is
mstest /testcontainer:C:\Users\me\source\repos\Test03\UnitTestProject1\bin\debug\UnitTestProject1.dll
The problem is I always get the following response in the console
Loading C:\Users\me\source\repos\Test03\UnitTestProject1\bin\debug\UnitTestProject1.dll...
Starting execution...
No tests to execute.
My unit test is simply
namespace UnitTestProject1
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void AddPositive()
{
var bll = new ConsoleApp1.Bll();
var result = bll.Add(2, 5);
Assert.IsTrue(result == 7);
}
}
Why does it not find the test as I've followed the instructions from https://msdn.microsoft.com/en-us/library/ms182489.aspx#testcontainer?
The solution as a whole targets 4.6.1 , I'm using VS 2017 Enterprise
A: If you want to use mstest.exe, you need following reference in your project file:
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
If you have instead (which seems to be the default for newly created test projects):
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\MSTest.TestFramework.1.3.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll</HintPath>
</Reference>
<Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\..\packages\MSTest.TestFramework.1.3.2\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll</HintPath>
</Reference>
you need to use vstest.console.exe
Please note that VSTest.Console.exe is optimized for performance and is used in place of MSTest.exe in Visual Studio 2012.
A: I ran into the same problem and it took me some time to figure out. The actual solution is in the comments.
My Tests are getting discorvered using vstest.console.exe:
Visual Studio Enterprise 2017:
"C:\Program Files (x86)\Microsoft Visual
Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe"
See https://learn.microsoft.com/en-us/visualstudio/test/vstest-console-options for further info.
| |
doc_23527113
|
I/zygote (11465): Rejecting re-init on previously-failed class java.lang.Class<com.google.android.gms.maps.model.CameraPosition>: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/internal/safeparcel/zza;
I/zygote (11465): at void com.apptreesoftware.mapview.MapViewPlugin.<clinit>() (MapViewPlugin.kt:-1)
I/zygote (11465): at void com.apptreesoftware.mapview.MapViewPlugin.registerWith(io.flutter.plugin.common.PluginRegistry$Registrar) (MapViewPlugin.kt:-1)
I/zygote (11465): at void io.flutter.plugins.GeneratedPluginRegistrant.registerWith(io.flutter.plugin.common.PluginRegistry) (GeneratedPluginRegistrant.java:32)
I/zygote (11465): at void com.rumblewayne.scottandvikiapp.MainActivity.onCreate(android.os.Bundle) (MainActivity.java:12)
I/zygote (11465): at void android.app.Activity.performCreate(android.os.Bundle, android.os.PersistableBundle) (Activity.java:7009)
I/zygote (11465): at void android.app.Activity.performCreate(android.os.Bundle) (Activity.java:7000)
I/zygote (11465): at void android.app.Instrumentation.callActivityOnCreate(android.app.Activity, android.os.Bundle) (Instrumentation.java:1214)
I/zygote (11465): at android.app.Activity android.app.ActivityThread.performLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent) (ActivityThread.java:2731)
I/zygote (11465): at void android.app.ActivityThread.handleLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:2856)
I/zygote (11465): at void android.app.ActivityThread.-wrap11(android.app.ActivityThread, android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:-1)
I/zygote (11465): at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1589)
I/zygote (11465): at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:106)
I/zygote (11465): at void android.os.Looper.loop() (Looper.java:164)
I/zygote (11465): at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6494)
I/zygote (11465): at java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) (Method.java:-2)
I/zygote (11465): at void com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run() (RuntimeInit.java:438)
I/zygote (11465): at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:807)
I/zygote (11465): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.internal.safeparcel.zza" on path: DexPathList[[zip file "/data/app/com.rumblewayne.scottandvikiapp-GNTruwp_-c2PU_b1tngU3w==/base.apk"],nativeLibraryDirectories=[/data/app/com.rumblewayne.scottandvikiapp-GNTruwp_-c2PU_b1tngU3w==/lib/x86, /data/app/com.rumblewayne.scottandvikiapp-GNTruwp_-c2PU_b1tngU3w==/base.apk!/lib/x86, /system/lib, /vendor/lib]]
I/zygote (11465): at java.lang.Class dalvik.system.BaseDexClassLoader.findClass(java.lang.String) (BaseDexClassLoader.java:125)
I/zygote (11465): at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:379)
I/zygote (11465): at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:312)
I/zygote (11465): at void com.apptreesoftware.mapview.MapViewPlugin.<clinit>() (MapViewPlugin.kt:-1)
I/zygote (11465): at void com.apptreesoftware.mapview.MapViewPlugin.registerWith(io.flutter.plugin.common.PluginRegistry$Registrar) (MapViewPlugin.kt:-1)
I/zygote (11465): at void io.flutter.plugins.GeneratedPluginRegistrant.registerWith(io.flutter.plugin.common.PluginRegistry) (GeneratedPluginRegistrant.java:32)
I/zygote (11465): at void com.rumblewayne.scottandvikiapp.MainActivity.onCreate(android.os.Bundle) (MainActivity.java:12)
I/zygote (11465): at void android.app.Activity.performCreate(android.os.Bundle, android.os.PersistableBundle) (Activity.java:7009)
I/zygote (11465): at void android.app.Activity.performCreate(android.os.Bundle) (Activity.java:7000)
I/zygote (11465): at void android.app.Instrumentation.callActivityOnCreate(android.app.Activity, android.os.Bundle) (Instrumentation.java:1214)
I/zygote (11465): at android.app.Activity android.app.ActivityThread.performLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent) (ActivityThread.java:2731)
I/zygote (11465): at void android.app.ActivityThread.handleLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:2856)
I/zygote (11465): at void android.app.ActivityThread.-wrap11(android.app.ActivityThread, android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:-1)
I/zygote (11465): at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1589)
I/zygote (11465): at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:106)
I/zygote (11465): at void android.os.Looper.loop() (Looper.java:164)
I/zygote (11465): at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6494)
I/zygote (11465): at java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) (Method.java:-2)
I/zygote (11465): at void com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run() (RuntimeInit.java:438)
I/zygote (11465): at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:807)
I/zygote (11465):
F/flutter (11465): [FATAL:flutter/shell/platform/android/platform_view_android_jni.cc(60)] Check failed: CheckException(env).
F/libc (11465): Fatal signal 6 (SIGABRT), code -6 in tid 11465 (scottandvikiapp), pid 11465 (scottandvikiapp)
*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
Build fingerprint: 'google/sdk_gphone_x86/generic_x86:8.1.0/OSM1.180201.021/4741582:userdebug/dev-keys'
Revision: '0'
ABI: 'x86'
pid: 11465, tid: 11465, name: scottandvikiapp >>> com.rumblewayne.scottandvikiapp <<<
signal 6 (SIGABRT), code -6 (SI_TKILL), fault addr --------
Abort message: '[FATAL:flutter/shell/platform/android/platform_view_android_jni.cc(60)] Check failed: CheckException(env).
'
eax 00000000 ebx 00002cc9 ecx 00002cc9 edx 00000006
esi f29abd10 edi 00002cc9
xcs 00000023 xds 0000002b xes 0000002b xfs 0000006b xss 0000002b
eip f720aaf0 ebp aca5a3d9 esp ff86e8b8 flags 00000296
backtrace:
#00 pc 00000af0 [vdso:f720a000] (__kernel_vsyscall+16)
#01 pc 0001edf8 /system/lib/libc.so (syscall+40)
#02 pc 0001f073 /system/lib/libc.so (abort+115)
#03 pc 00330ffe /data/app/com.rumblewayne.scottandvikiapp-GNTruwp_-c2PU_b1tngU3w==/lib/x86/libflutter.so
#04 pc 00331733 /data/app/com.rumblewayne.scottandvikiapp-GNTruwp_-c2PU_b1tngU3w==/lib/x86/libflutter.so
#05 pc 00083d2a /data/app/com.rumblewayne.scottandvikiapp-GNTruwp_-c2PU_b1tngU3w==/lib/x86/libflutter.so
#06 pc 000821fe /data/app/com.rumblewayne.scottandvikiapp-GNTruwp_-c2PU_b1tngU3w==/lib/x86/libflutter.so
#07 pc 000d2993 /data/app/com.rumblewayne.scottandvikiapp-GNTruwp_-c2PU_b1tngU3w==/lib/x86/libflutter.so
#08 pc 0009329c /data/app/com.rumblewayne.scottandvikiapp-GNTruwp_-c2PU_b1tngU3w==/lib/x86/libflutter.so
#09 pc 00092e5a /data/app/com.rumblewayne.scottandvikiapp-GNTruwp_-c2PU_b1tngU3w==/lib/x86/libflutter.so
#10 pc 00097a76 /data/app/com.rumblewayne.scottandvikiapp-GNTruwp_-c2PU_b1tngU3w==/lib/x86/libflutter.so
#11 pc 00014af7 /system/lib/libutils.so (android::SimpleLooperCallback::handleEvent(int, int, void*)+39)
#12 pc 00015936 /system/lib/libutils.so (android::Looper::pollInner(int)+982)
#13 pc 000154d6 /system/lib/libutils.so (android::Looper::pollOnce(int, int*, int*, void**)+118)
#14 pc 000e262b /system/lib/libandroid_runtime.so (android::android_os_MessageQueue_nativePollOnce(_JNIEnv*, _jobject*, long long, int)+59)
#15 pc 007d5428 /system/framework/x86/boot-framework.oat (offset 0x606000) (android.app.NativeActivity.onWindowFocusChangedNative [DEDUPED]+136)
#16 pc 0000371e /dev/ashmem/dalvik-jit-code-cache (deleted)
#17 pc 4f293241 <unknown>
#18 pc 0d3fffff /dev/ashmem/dalvik-main space (region space) (deleted)
#19 pc 0d3fffff /dev/ashmem/dalvik-main space (region space) (deleted)
Lost connection to device.
Ive read in other posts that you need to make sure your dependencies match etc but i can seem to get this to work when i try exactly what was shown in linked post.
My current dependencies look like this:
dependencies:
map_view: ^0.0.12
image_picker: ^0.4.1
url_launcher: ^3.0.0
firebase_storage: ^0.3.7
firebase_database: ^1.0.1
shared_preferences: ^0.4.1
transparent_image: ^0.1.0
chewie: ^0.6.0
camera: ^0.2.1
video_player: ^0.6.0
path_provider: ^0.4.0
connectivity: ^0.3.1
zoomable_image: ^1.2.0
json_annotation: ^0.2.4
firebase_messaging: ^1.0.2
image: ^1.1.33
path: ^1.5.1
uuid: ^1.0.0
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
dev_dependencies:
build_runner: ^0.8.0
json_serializable: ^0.5.2
flutter_launcher_icons: ^0.3.2
flutter_test:
sdk: flutter
Can anyone insight into how to fix this?
Update:
import 'package:map_view/map_view.dart';
import 'CompositionSubscription.dart';
import 'package:flutter/material.dart';
class CustomMap extends StatefulWidget {
String mapTitle;
List markers;
CameraPosition initialPosition;
CustomMap(this.mapTitle, this.markers, this.initialPosition);
@override
CustomMapState createState() => new CustomMapState(this.mapTitle, this.markers, this.initialPosition);
}
class CustomMapState extends State<CustomMap> {
final String mapTitle;
final List<Marker> markers;
final CameraPosition initialPosition;
CustomMapState(this.mapTitle, this.markers, this.initialPosition);
MapView mapView = new MapView();
var compositeSubscription = new CompositeSubscription();
@override Widget build(BuildContext context) {
mapView.show(
new MapOptions(
mapViewType: MapViewType.normal,
showUserLocation: true,
initialCameraPosition: initialPosition,
title: mapTitle),
toolbarActions: [new ToolbarAction("Back", 1)]
);
var setMarkers = mapView.onMapReady.listen((_) {
mapView.setMarkers(markers);
mapView.zoomToFit(padding: 100);
});
compositeSubscription.add(setMarkers);
var toolbarAction = mapView.onToolbarAction.listen((id) {
if (id == 1) {
Navigator.pop(context);
mapView.dismiss();
compositeSubscription.cancel();
}
});
compositeSubscription.add(toolbarAction);
return new Scaffold();
}
}
in the previous screen where the map is tapped.
var churchStaticMarkers = [ new Marker("Church", "St Dunstan's Church", 51.0206245,0.2605629, color: Colors.red)];
var churchLocation = new Location(51.0206245, 0.2605629);
var staticMapProvider = new StaticMapProvider("XXXXX");
var churchStaticMapUri = staticMapProvider.getStaticUriWithMarkers(
churchStaticMarkers,
maptype: StaticMapViewType.roadmap,
center: churchLocation
);
var churchMapContainer = new Container(
child: new InkWell(
child: new Stack(
children: <Widget>[
new Container(
child: new Center(
child: new CircularProgressIndicator(),
),
padding: new EdgeInsets.all(16.0),
),
new Center(
child: new FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: churchStaticMapUri.toString(),
),
),
],
),
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new CustomMap(churchMapTitle, churchMapMarkers, churchPosition)),
);
},
),
margin: new EdgeInsets.only(left: 8.0, top: 8.0, right: 8.0),
);
A: Even though Flutter is made for cross platforming not everything is written in Dart. Some parts need platform specific (native) code. So there are some things that needs to be added to your code (see pub.dartlang.org)
Android
You will be making multiple edits to your AndroidManifest.xml file. In your Flutter project, you can find this file location under android/app/src/main
In your AndroidManifest.xml, add the following uses-permission above the tag.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
In your AndroidManifest.xml, add the following lines inside of the application tag. Be sure to replace your_api_key with the one you generated.
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="your_api_key"/>
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/>
Add the MapActivity to your AndroidManifest.xml
<activity android:name="com.apptreesoftware.mapview.MapActivity" android:theme="@style/Theme.AppCompat.Light.DarkActionBar"/>
In your android/build.gradle file. Under buildScript dependencies add:
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.2-4'
Run your application on an Android device or simulator. Confirm that when you display the map you see map detail. If you only see a beige screen it's possible that your API key is incorrect.
iOS
The maps plugin will request your users location when needed. iOS requires that you explain this usage in the Info.plist file
Set the NSLocationWhenInUseUsageDescription in ios/Runner/Info.plist.
Example:
<key>NSLocationWhenInUseUsageDescription</key>
<string>Using location to display on a map</string>
EDIT:
Also you should wrap the MapOptions initialCameraPosition Location in CameraPosition
initialCameraPosition: new CameraPosition(initialPosition)
| |
doc_23527114
|
I have a string coming from some Api call like below :
And I want to split based on [DART1].
String value = "University[DART1]BUCKKKKK";
String[] splitData = value.split("DART1");
String firstWord = splitData[0].substring(0, splitData[0].length() - 1);
String secondWord = splitData[1].substring(1);
I did a split and removed those special characters from the string, but I was doing lot of operation on string.
Is there a better way of doing this?
A: Split based on "\\[DART1]"
String[] result = value.split("\\[DART1]");
*
*The \\ is required to escape the [ otherwise the compiler would think you want to split on anything that's either D, A, R, T or 1.
Then you can access the individual elements by indexing into the result array.
| |
doc_23527115
|
I have begun working on a website developed about one year ago it is currently deployed, but I'm starting to become curious that the code in the deployment folder isn't buildable? I worked on some stuff locally (directly cloning the deploy folder on the server) and it doesn't really work properly, but I assumed it was because the environment is different.
I tested this tiny change locally (slightly alters the data that is being inserted into the database) and it was working perfect. I tried to deploy it and it doesn't work correctly. After pulling in the one file I changed, the website still operates exactly the same as before.
My question is, what happens with an IIS deployed app if you make a change that makes the app unbuildable (some type of compile-time error like a syntax thing, even)? Does it continue running the previously buildable version? I feel like that would make sense, but I am unfamiliar with how things work in this environment.
| |
doc_23527116
|
THE FOLLOWING IS JUST A THOUGHT/EXAMPLE:
I'm think that something like //[reference_X] would work (pseudocode):
module counter (clk,rst,enable,count);
input clk, rst, enable;
output [3:0] count; //[count]
reg [3:0] count;
always @ (posedge clk or posedge rst)
if (rst) begin
count <= 0;
end else begin : COUNT
while (enable) begin
count <= count + 1;
disable COUNT;
end
end
endmodule
/**
* [count]: just an example, this register acts
* as something that explains what the asker is
* looking for.
*/
My main tool is Eclipse but I have DVT Eclipse on if that helps (can't find tag for it).
Target language is system-verilog.
A: Starting with DVT 18.1.15 you can use hyperlinks in comments (https://dvteclipse.com/documentation/sv/Hyperlinks_in_Comments.html)
You just need to write @link element or @see element and DVT will go to the declaration of that element. To trigger this, simply hold the CTRL key while hovering the element name in the comment.
There are several ways you can specify an element to be referenced. If DVT cannot detect a unique element, it will suggest more hyperlinks.
| |
doc_23527117
|
I have designed a dialog for user to enter there email id and password for creating their new account.
I want the the user input to be validated on the "next" button of the dialog.
I have written a JavaScript for it as shown below and added a custom action in "do action" of my dialog button.
function validatePassword(str szPasswordportal)
{
var newPassword = szPasswordportal;
var minNumberofChars = 6;
var maxNumberofChars = 20;
var regularExpression = /^[A-Za-z0-9`~!@%]{6,20}$/;
alert(newPassword);
if(newPassword = "") //if null
return false;
if(newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars)
{
return false;
}
if(!regularExpression.password(newPassword))
{
alert("password should contain atleast one number ,one alphabet and one special character");
return false;
}
return true;
}
But this JS is not getting executed successfully.
Can someone help me out with this or with some other suggestion?
A: Your if condition have a syntax mistake.
if(newPassword = "")
= is assigning operator. If you want to check the value you have to use conditional operator == like below.
if(newPassword == "")
Also you have to add all the condition on else part, then only it will check the validation one by one, otherwise at the end it will automatically return the true value. Change your script like below.
function validatePassword(str szPasswordportal)
{
var newPassword = szPasswordportal;
var minNumberofChars = 6;
var maxNumberofChars = 20;
var regularExpression = /^[A-Za-z0-9`~!@%]{6,20}$/;
alert(newPassword);
if(newPassword == "" || newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars)
{
return false;
} else if(!regularExpression.password(newPassword))
{
alert("password should contain atleast one number ,one alphabet and one special character");
return false;
} else {
return true;
}
}
| |
doc_23527118
|
I inserted this code in MainPage.xaml :
xmlns:UI="using:Microsoft.Advertising.WinRT.UI"
And my Grid tag:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<UI:AdControl
ApplicationId="----------------------"
AdUnitId="------"
HorizontalAlignment="Left"
Height="500"
Margin="0,0,0,0"
VerticalAlignment="Top"
Width="200"/>
</Grid>
Why do I get this error?
AdControl not exist in namespace "using: Microsoft.Advertising.WinRT.UI"
Errore2 type 'UI: AdControl' not found. Check for missing a reference to an assembly and all assembly to which you refer have been compiled
A: Right click on Reference in your Solution Explorer window and select Add Reference.
WINDOWS RT (UNIVERSAL APPS)
Then move on Windows Phone 8.1 Tab and select 'Extensions'. You should find Microsoft Advertising SDK for Windows Phone 8.1 XAML. Select it and click ok, then rebuild (F6)
WINDOWS PHONE SILVERLIGHT
Move on Assemblies tab, then click on Extensions and add these 2 references:
*
*Microsoft.Advertising.Mobile
*Microsoft.Advertising.Mobile.UI
Then you have to add in the XAML page this namespace:
xmlns:adv="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
and finally add the advertising control to your page:
<adv:AdControl ApplicationId="YOUR_APPLICATION_ID" AdUnitId="YOUR_AD_UNIT_ID"
Width="480" Height="80"/>
If you're not able to find references, it's beacuse you didn't install the SDK on your computer. Go here, download the right version according to your needs and install it, then repeat the steps.
Let me know if it works!
| |
doc_23527119
|
abcd | 89 | 65
ebcd | 39 | 105
fbcd | 23 | 45
gbcd | 89 |
hbcd | 89 | 65
ibcd | | 65
jbcd | 50 | 50
sql+php
how to get low price of each product using php script after fetching mysql records like
for abcd $price = 65
for fbed $price = 23
for gbcd $price = 89
etc
A: min($bprice,$fprice) should do what you need.
Edit: Fix to handle null
if (is_null($bprice)) {
$price = $fprice;
} elseif (is_null($fprice)) {
$price = $bprice;
} else {
$price = min($bprice,$fprice);
}
A: Use the group by statement:
SELECT MAX(bprice) AS maxbprice, MAX(fprice) AS maxfprice
FROM products
GROUP BY Product
A: $query = "SELECT * FROM product group by product";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_object($result))
{
if($row->bprice > $row->fprice)
{
$low=$row->fprice;
}
else
{
$low=$row->bprice;
}
}
| |
doc_23527120
|
The service allows retrying for failed requests, but needs a transaction ID in the soap header in order to detect the repeated calls.
I was able to add the transaction ID by creating a GUID in an IClientMessageInspector. And my plan was to use Polly for retrying.
My problem is: Polly knows nothing about the IClientMessageInspector, and the inspector doesn't know if the request is a retry.
Is there a way to pass that information along, or is there an alternative way of changing the SOAP header? Can Visual Studio be configured to do that?
A: Found the solution here:
Instead of using IClientMessageInspector, SOAP metadata can be accessed via OperationContextScope(client.InnerChannel).
For convenience, this can then be wrapped in a custom proactive Polly policy.
| |
doc_23527121
|
I can enable the NLCD from preferences, but nothing seems to change. Additionally, the following is printed in my console:
nlcd[935]: Process not entitled for this action
System Preferences[1167]: connection to NLCd failed
I also tried to run nlcd directly from /usr/libexec, but it just prints the following:
<Notice>: Checkin with launchd failed, no port to listen on
I've seen a number of threads talking about this tool not working, but none with the same symptoms as this.
A: I removed the preference pane and installed it again to fix the problem.
| |
doc_23527122
|
This would be required for production purposes.
Thanks.
A: For your use-case, be certain you need multiple clusters. It's not likely that you'll need separate clusters if you instead structured your data to either span multiple buckets in a single cluster (and hence with one instance per machine). Even combining data that doesn't logically group into single buckets (differentiating different document categories by some sort of key prefix) would be a far better solution. If your concern is that only certain applications need to access certain clusters (well, groups of data), they can still connect to the same cluster, albeit different buckets (or even looking for specific keys in the same bucket), and less considerations would need to make to ensure the virtual machines behaved as expected.
If you absolutely require separate clusters, it is possible, to run multiple Couchbase instances on the same hardware with the use of virtual machines. Your approach to keep nodes within a cluster on separate physical machines is perfect (as it maintains availability with replicas on separate hardware).
For some considerations with regards to running Couchbase Server on virtual machines, there is a good blog post outlining some sizing considerations as to how you would spec such a cluster. There is also a guide on how to deploy Couchbase on Windows Azure virtual machines that may also prove useful.
| |
doc_23527123
|
if($bg_img){
list($img_width, $img_height, $img_type, $img_attr) = getimagesize('./images/'.$bg_img);
}
// Use image in background
$im = imagecreatefrompng(IS_DIR."/images/".$bg_img);
$fn = rgb2array($font_color);
$font_color = imagecolorallocate($im, $fn[0], $fn[1], $fn[2]);
This creates the image then assigns a font colour, and later in the code, text is added etc. All that works fine.
I have a strange issue though. I have two 8 bit PNG's. One of them is just a plain grey colour, the other one is an actual graphical image with a logo on it. If I use the basic one, the text uses the colour I have defined in $font_color (which comes from DB) without issues. If I use the more graphical one, the colour is incorrect and the imagecollorallocate doesn't seem to return a set of RGB values.
Is there something that needs to be done with certain types of PNG?
| |
doc_23527124
|
Please refer to the following jsFiddle: http://jsfiddle.net/persianturtle/yawTb/1/
Basic HTML:
<img class="mobile-title-size" src="http://zx85.dyndns.org/raphtest/img/title.png" alt="Logo">
Basic CSS:
.mobile-title-size {
position: absolute;
top: 2.5%;
left: 6%;
width: 70%;
max-width: 300px;
}
This is the mobile header that uses the same image that is displayed on tablet and desktop viewports. Since the image is already being loaded anyway, I am looking to use this same image, resize it smaller and vertically align it so that I can use one image for all viewports.
The Problem: On browser resize, the image does get smaller, but it does not vertically align in the center.
The Goal: Even though the width overlaps badly in this example, it is not an issue on my site. The goal is only to vertically center the image as the browser resizes.
I am okay with using a javascript/jQuery solution but of course, simple CSS is preferred.
Any help is greatly appreciated!
A: There are several ways to do it - purely CSS or a JS-based method.
Updated answer
Update: With the advent of CSS transform support, here is a rather elegant solution of positioning elements using pure CSS. With the given markup:
<div class="container">
<img src="..." alt="..." title="..." />
</div>
For your CSS:
.container {
/* The container has to have a predefined dimension though */
position: relative;
}
.container img {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
Updated JSFiddle
Old answer
For CSS, you can construct a ghost element within the container of the <img> element. Chris Coyier did an excellent write up on this technique. Let's say your HTML code looks like this:
<div class="container">
<img src="..." alt="..." title="..." />
</div>
Then your CSS would be:
.container {
font-size: 0;
text-align: center;
}
.container:before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
}
.container > img {
display: inline-block;
vertical-align: middle;
}
The functional CSS fix can be seen working in this fiddle - http://jsfiddle.net/teddyrised/yawTb/8/
Or, you can use a JS-based method:
$(document).ready(function() {
$(window).resize(function() {
$(".container > img").each(function() {
var cHeight = $(this).parent(".container").height(),
cWidth = $(this).parent(".container").width(),
iHeight = $(this).height(),
iWidth = $(this).width();
$(this).css({
top: 0.5*(cHeight - iHeight),
left: 0.5*(cWidth - iWidth)
});
});
}).resize(); // Fires resize event when document is first loaded
});
But you will have to use the following CSS:
.container {
position: relative;
}
.container img {
position: absolute;
z-index: 100;
}
[Edit]: For the JS-based method where you absolutely position the image element, you will have to explicitly state the dimensions of the .container element, or have some content in it (but it kind of defeats the purpose because the image will be above the content). This is because the image element has been taken out of the document flow, and therefore its dimensions will not affect the size of the parent container.
The working example of the JS version is here - http://jsfiddle.net/teddyrised/yawTb/7/
A: The solution you've got works for old browsers but in the near future (right now has around the 80% of the browser support) you can do this, a much simpler and elegant solution:
.container img{
width: 100%;
height: auto;
}
@supports(object-fit: cover){
.container img{
height: 100%;
object-fit: cover;
object-position: center center;
}
}
A: So, I found something that works exactly as I wanted: http://jsfiddle.net/fmwzT/
The problem is that it ONLY works with bootstrap's newest version 2.3.1 and I have no idea why (I have 2.3.0 on my site).
So now I have answered my question and raised an even bigger question, what is causing this to work?
Note, it does use the following code:
HTML
<div id="f1"><div id="outer-element"><img id="inner-element" src="http://zx85.dyndns.org/raphtest/img/title.png" alt="Logo"></div></div>
CSS
#fl {
float: left;
}
#outer-element {
display: table-cell;
vertical-align: middle;
height: 40px;
max-width: 300px;
}
#inner-element {
display: inline-block;
margin-left: -20px;
}
NOTE: This does NOT work without Bootstrap's neweste 2.3.1 version.
I will be posting a question to see if anyone knows!
| |
doc_23527125
|
That is same thing as do: Windows 10 - Microsoft Print to PDF, the result is a new PDF with same aspect but made of images.
But I need to do this programatically. Is there any way I could do similar conversion that Microsoft Print to PDF does in C#?
| |
doc_23527126
|
A: 255 bytes, so basically 255 utf-8 characters.
| |
doc_23527127
|
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_custom_checkbox
A: change the css of .container. padding-left from 35px to 25 px. It will remove white space.
.container {
display: block;
position: relative;
padding-left: 25px;
margin-bottom: 12px;
cursor: pointer;
font-size: 22px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
A: Try using ul, li
Use li to display line by line
then have your labels wrapped inside.
Making label(.container) to display as "inline-block" will help to take auto width
.container {
width: auto;
display: inline-block;
}
Remove list styles on li's
li {
list-style: none;
}
Refer: https://codepen.io/sprushika/pen/oqReEO
A: Just add a width: 25px; to the container's style. The width should be just large enough to cover every checkbox (see snippet below):
/* Stylesheet */
/* The container */
.container {
display: block;
position: relative;
padding-left: 35px;
width: 25px; /* this was added to fix the issue */
margin-bottom: 12px;
cursor: pointer;
font-size: 22px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* Hide the browser's default checkbox */
.container input {
position: absolute;
opacity: 0;
cursor: pointer;
}
/* Create a custom checkbox */
.checkmark {
position: absolute;
top: 0;
left: 0;
height: 25px;
width: 25px;
background-color: #eee;
}
/* On mouse-over, add a grey background color */
.container:hover input~.checkmark {
background-color: #ccc;
}
/* When the checkbox is checked, add a blue background */
.container input:checked~.checkmark {
background-color: #2196F3;
}
/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after {
content: "";
position: absolute;
display: none;
}
/* Show the checkmark when checked */
.container input:checked~.checkmark:after {
display: block;
}
/* Style the checkmark/indicator */
.container .checkmark:after {
left: 9px;
top: 5px;
width: 5px;
height: 10px;
border: solid white;
border-width: 0 3px 3px 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
<!DOCTYPE html>
<html>
<body>
<h1>Custom Checkboxes</h1>
<label class="container">One
<input type="checkbox" checked="checked">
<span class="checkmark"></span>
</label>
<label class="container">Two
<input type="checkbox">
<span class="checkmark"></span>
</label>
<label class="container">Three
<input type="checkbox">
<span class="checkmark"></span>
</label>
</body>
</html>
After applying this fix, if you hover over each item with the mouse you will see that the hand icon changes to an arrow as soon as you leave the checkbox + text area.
| |
doc_23527128
|
Output: print word which has the highest number of occurrences of given char or words if there are the same number of occurrences.
Need to find word or words which have the most number of occurrences of given char.
I wrote a program that finds and prints the word with the highest number of occurrences.
But I can't understand how to find word with given char.
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char array[]="this is text. Useuuu it for test. Text for test.";
char* buf = strtok(array," .,!?;:");
char *word;
int max = 0;
char c;
while(buf) {
int n = strlen(buf);
for(int i = 0; i < n; i++) {
int counter=0;
for(int j = 0; j < n ; j++) {
if(buf[i]==buf[j] && i != j)
counter++;
if(counter>max) {
max=counter;
word=buf;
}
}
}
buf=strtok(0," .,!?;:");
}
cout << "Result: " << word << endl;
return 0;
}
In this program result is word "Useuuu"
I'm sorry for my English.
A: Here is a solution to your problem that attempts to change your code the least possible:
#include <iostream>
#include <cstring>
#include <list>
using namespace std;
int main() {
char array[]="this is text. Useuuu it for test. Text for test.";
char* buf = strtok(array," .,!?;:");
std::list<const char*> words{};
int max = 0;
int wrd_counter = 0;
char c;
std::cout << "Input char: ";
std::cin >> c;
while(buf) {
int n = strlen(buf);
int counter=0;
for(int j = 0; j < n ; j++) {
if(buf[j]==c)
counter++;
}
if(counter>max) {
max=counter;
words.clear();
words.push_back(buf);
}
else if(counter == max){
words.push_back(buf);
}
buf=strtok(0," .,!?;:");
}
cout << "Results: ";
for(const char* ccp: words){
std::cout << ccp << " ";
}
return 0;
}
Explanation: In the code, instead of having a single char* word, I use a doubly-linked list to store multiple words. I iterate through each word and find the number of occurrences of the char. I then compare to see if the word belongs in the list.
Notes: this code is rough and could be optimized. Also, if the order of the words doesn't matter, you could use forward_list.
| |
doc_23527129
|
import pandas as pd
from io import StringIO
df = pd.read_csv(StringIO('''Sentence, A1, A2, A3
text, 0.23, 0.54, 39
text, 0.33, 0.7, 36
text, 0.8, 0.41, 29'''), sep=',')
print(df.corr())
Result:
A1 A2 A3
A1 1.000000 -0.732859 -0.991352
A2 -0.732859 1.000000 0.637235
A3 -0.991352 0.637235 1.000000
A: Continuing the example and using numpy:
c = df.corr()
import numpy as np
threshold = .99
np.abs(c.values) > threshold
This gives:
array([[ True, False, True],
[False, True, False],
[ True, False, True]])
You can get the indices of the significant values which are off-diagonal via:
[(i, j) for i,j in zip(*np.where(np.abs(c.values) > threshold)) if i!=j]
This gives:
[(0, 2), (2, 0)]
Update:
Making use of the symmetry of the correlation matrix and one can get a list of readable strings with the column names:
[f"{c.columns[i]} and {c.columns[j]}" for i, j in zip(*np.where(np.abs(c.values) > threshold)) if i < j]
->
[' A1 and A3']
A: if you need the pairs with higest correlation then you need to stack then find the pairs with highest by stack this is the way
import pandas as pd
from io import StringIO
df = pd.read_csv(StringIO('''Sentence, A1, A2, A3
text, 0.23, 0.54, 39
text, 0.33, 0.7, 36
text, 0.8, 0.41, 29'''), sep=',')
df.drop(['Sentence'],1, inplace=True)
print(df.corr())
def get_red_pair(df):
pairs_to_drop = set()
cols = df.columns
for i in range(0, df.shape[1]):
for j in range(0, i+1):
pairs_to_drop.add((cols[i], cols[j]))
return pairs_to_drop
def get_largest_correlations(df, n=5):
au_corr = df.corr().abs().unstack()
labels_to_drop = get_red_pair(df)
au_corr = au_corr.drop(labels=labels_to_drop).sort_values(ascending=False)
return au_corr[0:n]
corr = get_largest_correlations(df)
print(corr)
to get only the first one, then to the function make sure you pass n as 1 because by default it expect 5
if this is not what you are looking for then framing your question well might help
this gives
A1 A2 A3
A1 1.000000 -0.732859 -0.991352
A2 -0.732859 1.000000 0.637235
A3 -0.991352 0.637235 1.000000
A1 A3 0.991352
A2 0.732859
A2 A3 0.637235
| |
doc_23527130
| ||
doc_23527131
|
chrome.runtime.onMessage.addListener(msgObj => {
if (msgObj.action == "getData") {
var annotations = msgObj.annotations;
// Messaging 2
chrome.runtime.sendMessage({ action: "getURL" }, (response) => {
alert(response.data)
});
// I want to have current tab url here...
}
// ...
});
And my "eventPage.js" is
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
// Messaging 1
// ...
// Messaging 2
if (request.action === "getURL") {
chrome.tabs.query({ 'active': true, 'lastFocusedWindow': true }, function (tabs) {
// I want url_ to be transferred to highlight.js but no luck so far...
const url_ = tabs[0].url;
sendResponse({ data: url_ });
return true;
});
}
});
And my manifest file is:
{
"manifest_version":2,
"name":"Annotation Reader",
"version": "1.0",
"description":"An annotation reader extension!",
"icons": {
"128": "icon128.png",
"48": "icon48.png",
"16":"icon16.png"
},
"browser_action": {
"default_icon": "icon128.png",
"default_popup": "popup.html"
},
"background": {
"scripts": [
"jquery-3.4.1.min.js",
"eventPage.js"
],
"persistent":false
},
"permissions": [
"tabs",
//...
],
"content_scripts": [
{
"matches":
[
// ...
],
"js": [
"jquery-3.4.1.min.js",
"jquery.highlight.js",
"highlight.js"
],
"css": ["highlight.css"]
}
]
}
Thank you in advance!
A: *
*There's no need for messaging, simply use location.href in the content script. Each matching tab/frame runs its own instance of the content script so things like DOM document or window or location belong to the tab/frame.
*Although you don't need it here, but when sendResponse is used asynchronously (callbacks in chrome extension API are always called asynchronously), the messaging port needs to be kept open by returning true from the onMessage listener, not from the nested callback.
if (something) {
asyncCall(params, result => {
sendResponse(result);
});
return true;
}
*Content scripts are running in all matching tabs/frames, not just the active tab, so messages can come from an inactive tab. It means that chrome.tabs.query is the wrong approach. The correct solution is to use sender.url directly if the URL is needed. Use the documentation to learn about the parameters so you don't have to reinvent the wheel.
| |
doc_23527132
|
{
'id':'99876983ydbhdu3739',
'category':'Spa',
'latitude':'33.498',
'longitude':'32.332',
'name':'Studio'
}
I have multiple such values. This is one record, an example of what I want to insert. Following is what I am trying:
table = dynamodb.create_table(
TableName='Trial',
KeySchema=[
{
'AttributeName': 'facebook_id',
'KeyType': 'HASH' #Sort key
},
{
'AttributeName': 'latitude',
'KeyType': 'RANGE' #Sort key
},
],
AttributeDefinitions=[
{
'AttributeName':'id',
'AttributeType':'S'
},
{
'AttributeName': 'category',
'AttributeType': 'S'
},
{
'AttributeName': 'latitude',
'AttributeType': 'S'
},
{
'AttributeName': 'longitude',
'AttributeType': 'S'
},
{
'AttributeName': 'name',
'AttributeType':'S'
}
],
ProvisionedThroughput={
'ReadCapacityUnits': 10,
'WriteCapacityUnits': 10
}
)
I get the following error:
An error occurred (ValidationException) when calling the CreateTable operation: The number of attributes in key schema must match the number of attributesdefined in attribute definitions.
A: You can just create the table with HASH and RANGE key attributes alone while creating the table. DynamoDB doesn't expect to define all the other attributes as DynamoDB is a key-value pair table. Please try the below code. You should be able to create the table.
While inserting an item, you can include any attributes as per your requirement.
Create Table :-
var AWS = require("aws-sdk");
AWS.config.update({
region : "us-west-2",
endpoint : "http://localhost:8000"
});
var dynamodb = new AWS.DynamoDB();
var params = {
TableName : "Trail",
KeySchema : [ {
AttributeName : "facebook_id",
KeyType : "HASH"
}, //Partition key
{
AttributeName : "latitude",
KeyType : "RANGE"
} //Sort key
],
AttributeDefinitions : [ {
AttributeName : "facebook_id",
AttributeType : "N"
}, {
AttributeName : "latitude",
AttributeType : "S"
} ],
ProvisionedThroughput : {
ReadCapacityUnits : 10,
WriteCapacityUnits : 10
}
};
dynamodb.createTable(params, function(err, data) {
if (err) {
if (err.code === "ResourceInUseException"
&& err.message === "Cannot create preexisting table") {
console.log("message ====>" + err.message);
} else {
console.error("Unable to create table. Error JSON:", JSON
.stringify(err, null, 2));
}
} else {
console.log("Created table. Table description JSON:", JSON.stringify(
data, null, 2));
}
});
Create Item:-
var AWS = require("aws-sdk");
AWS.config.update({
region : "us-west-2",
endpoint : "http://localhost:8000"
});
var docClient = new AWS.DynamoDB.DocumentClient();
var table = "Trail";
var params = {
TableName : table,
Item : {
"facebook_id" : 1,
"latitude" : 'lat',
"longitude" : 'long',
"name" : 'facebook',
"category" : 'social_media'
}
};
console.log("Adding a new item...");
docClient.put(params, function(err, data) {
if (err) {
console.error("Unable to add item. Error JSON:", JSON.stringify(err,
null, 2));
} else {
console.log("Added item:", JSON.stringify(data, null, 2));
}
});
A: For Boto3 Users in Python:
ddb_client.create_table(
TableName=DDB_TABLE_NAME,
AttributeDefinitions=[
{
'AttributeName': 'id',
'AttributeType': 'S'
},
{
'AttributeName': 'latitude',
'AttributeType': 'S'
},
],
KeySchema=[
{
'AttributeName': 'id',
'KeyType': 'HASH'
},
{
'AttributeName': 'latitude',
'KeyType': 'RANGE'
}
],
BillingMode='<your_value>'
)
response = ddb_client.put_item(
TableName=DDB_TABLE_NAME,
Item={
'id': {'S': '1'},
'latitude': {'S': '33.498'},
'longitude': {'S': '32.332'},
'category': {'S': 'Spa'},
'name': {'S': 'Studio'}
}
)
| |
doc_23527133
|
return str(reaction.emoji) == '' and user != bot.user
try:
reaction, user = await bot.wait_for('reaction_add', timeout=3600.0, check=green_check)
except asyncio.TimeoutError:
await concept_msg.delete()
await ctx.author.send("No moderator responded, wait some time and try again.")
return
else:
concept_embed_dict = concept_embed.to_dict()
A: Assuming you just want your message to have an initial reaction by your bot, you can use Message.add_reaction().
await concept_msg.add_reaction('')
| |
doc_23527134
|
Is there any schema which will give idea about type of DB2?
A: You can use DatabaseMetaData.getDatabaseProductName() and DatabaseMetaData.getDatabaseProductVersion(). For example, on Linux for Db2 10.5 fix pack 7 they return DB2/LINUXX8664 and SQL10057 respectively.
Sample code:
import java.sql.*;
class Test {
public static void main(String args[]) {
if (args.length == 0 ) {
System.out.println("need url");
System.exit(1);
}
String url = args[0];
try {
Class.forName("com.ibm.db2.jcc.DB2Driver");
Connection c = DriverManager.getConnection(url);
if (c != null) {
DatabaseMetaData meta = c.getMetaData();
if (meta != null) {
System.out.println( String.format(
"Connected to %s %s (%d.%d)",
meta.getDatabaseProductName(),
meta.getDatabaseProductVersion(),
meta.getDatabaseMajorVersion(),
meta.getDatabaseMinorVersion()
)
);
}
else {
System.out.println("Metadata is null");
}
}
c.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
System.exit(1);
}
}
}
A: How to know which flavor of Db2 server you are connected to using JDBC is documented by IBM here. As you can see it is from the Db2 from z/OS guide, haven't found it documented elsewhere.
Assuming you have extracted a DatabaseMetaData object using
Connection.getMetaData(), then you can do as follows:
String databaseProductName = databaseMetaData.getDatabaseProductName();
String databaseProductVersion = databaseMetaData.getDatabaseProductVersion();
String databaseProductNameLower = databaseProductName.toLowerCase(Locale.US);
// Detect IBM Db2 flavors
// According to IBM's documentation the database engine must be detected
// primarily from the ProductVersion value whereas IBM makes no real
// promise on the value of the ProductName. This is why we use the ProductName
// with some caution below.
if (databaseProductNameLower.equals("db2")
|| databaseProductNameLower.matches("db2[.-/ ].*")) {
if (databaseProductVersion != null && databaseProductVersion.length() > 3) {
String ppp = databaseProductVersion.substring(0, 3);
switch (ppp) {
case "DSN":
return DB2_ZOS; // Db2 for z/OS
case "SQL":
return DB2_LUW; // Db2 on Linux, UNIX, and Windows systems
case "QSQ":
return DB2_I; // Db2 for IBM i
case "ARI":
return DB2_VM; // Db2 Server for VM and VSE
default:
}
}
}
(In my case I use the above as part of something bigger so not returning a value from the above is acceptable. YMMV)
| |
doc_23527135
|
ALTER INDEX [spt_valuesclust] ON [dbo].[spt_values] REORGANIZE( FILLFACTOR=80 )
The above query is, unfortunately, not being executed. Can I use fill factor while re-organizing?
Thanks in advance.
A:
Can I use fill factor while re-organizing?
Fillfactor only applies when
*
*Index is first created
*Or when Index is rebuilt, not during reorganize.
With above operation you are setting new fill factor and reorganize cannot be used to set new fill factor.
Reorganizing an index uses minimal system resources. It defragments the leaf level of clustered and nonclustered indexes on tables and views by physically reordering the leaf-level pages to match the logical, left to right, order of the leaf nodes. Reorganizing also compacts the index pages. Compaction is based on the existing fill factor value.
Index rebuild drops your current index and creates a new one. Reorganize does not drops any index it just removes fragmentation.
Please read 5 things about fill factor
| |
doc_23527136
|
@Override
protected void configureStompEndpoints(StompEndpointRegistry registry) {
registry
.addEndpoint("/hello")
.addInterceptors(new HttpSessionHandshakeInterceptor() {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession session = servletRequest.getServletRequest().getSession();
attributes.put("sessionId", session.getId());
}
return true;
}
})
.withSockJS()
.setSessionCookieNeeded(true);
}
I @EnableRedisHttpSession in my redis config and the source code above safely stores http session in redis but even though I flushed my redis database, I can still send and receive my messages to my connected clients.
My speculation is that HttpSession is different from WebSocket session. How should I "intelligently" ask spring to store and maintain websocket related sessions in redis if you are using token based authentication?
UPDATE 1
StompHeaderAccessor accessor =
MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
List<String> tokenList = accessor.getNativeHeader("username");
accessor.removeHeader("username");
String username = null;
if (tokenList != null && tokenList.size() > 0) {
username = tokenList.get(0);
}
AuthenticationToken authToken = new AuthenticationToken(username);
SecurityContextHolder.getContext().setAuthentication(authToken);
switch(accessor.getCommand()) {
case CONNECT:
Principal auth = username == null ? null : authToken;
accessor.setUser(auth);
return MessageBuilder.createMessage(message.getPayload(), accessor.getMessageHeaders());
case CONNECTED:
System.out.println("Stomp connected");
break;
case DISCONNECT:
System.out.println("Stomp disconnected");
break;
case SEND:
break;
default:
break;
}
return message;
UPDATE 2
I think Websocket over STOMP relies on SimpSessionId not HttpSession created during the Handshake Interceptor.
StompHeaderAccessor [headers={simpMessageType=MESSAGE, stompCommand=SEND, nativeHeaders={username=[*******], destination=[/app/feed], content-length=[81]}, simpSessionAttributes={SPRING.SESSION.ID=187912de-a875-45ef-995a-7723fd8715c8}, simpHeartbeat=[J@6e9173e4, simpUser=***.AuthenticationToken@1767840c: Principal: *******; Credentials: [PROTECTED]; Authenticated: true; Details: null; Not granted any authorities, simpSessionId=d686qam8, simpDestination=/app/feed}]
UPDATE 3
SimpUserRegistry says this is "A registry of currently connected users." Might be this is the answer?
UPDATE 4
I am using RabbitMQ. Does that mean what I am doing is completely useless?
| |
doc_23527137
|
def debugp; return nil; end
in the view file that uses the original debugp... but it seems that this new definition cannot override the original definition of debugp (because debug info is still printed out). Is there a way to override it? There are other methods to disable the printing, but I'd like to find out the part about override a method in the application helper. Thanks.
A: You can't override the method in the view file, however you can override it in the corresponding helper - if you used the Rails generator to generate your controller, then it would have generated a helper too, for example, a "people" controller would have these files:
*
*app/controllers/people_controller.rb
*app/views/people/*.html.erb
*app/helpers/people_helper.rb
So to override a helper method from the application helper, put your helper method definition not in the view, but in the helper:
module PeopleHelper
def debugp; return nil; end
end
Hope that helps,
| |
doc_23527138
|
/foo/bar/
In my python code I have the following path:
/foo/bar/baz/quix/
How can I tell that only the /foo/bar/ part of the path exists?
I can walk the path recursively and check it step by step, but is there an easier way?
A: No easy function in the standard lib but not really a difficult one to make yourself.
Here's a function that takes a path and returns only the path that does exist.
In [129]: def exists(path):
...: if os.path.exists(path): return path
...: return exists(os.path.split(path)[0])
...:
In [130]: exists("/home/sevanteri/src/mutta/oisko/siellä/jotain/mitä/ei ole/")
Out[130]: '/home/sevanteri/src'
A: I think a simple while loop with os.path.dirname() will suffice the requirement
path_string = '/home/moin/Desktop/my/dummy/path'
while path_string:
if not os.path.exists(path_string):
path_string = os.path.dirname(path_string)
else:
break
# path_string = '/home/moin/Desktop' # which is valid path in my system
A: I don't actually get your requirements as whether you want every path to be checked or upto some specific level.But for simple sanity checks you can just iterate through the full path create the paths and check the sanity.
for i in filter(lambda s: s, sample_path.split('/')):
_path = os.path.join(_path, i)
if os.path.exists(_path):
print "correct path"
A: Well, I think the only way is to work recursively... Though, I would work up the directory tree. The code isn't too hard to implement:
import os
def doesItExist(directory):
if not os.path.exists(directory):
doesItExist(os.path.dirname(directory)
else:
print "Found: " + directory
return directory
| |
doc_23527139
|
Here is how it's supposed to look like:(Excuse the scaling of screenshot that I did for posting here)
Here is how it looks like:
Now, you can see here that the Following Button is overlapping the TextViews. On other devices, the text is small and so there is no overlap. I haven't configured programmatically any property of the TextViews separately and it looks okay on many other devices. What could be causing such an issue?
The text on other devices is smaller than this one so that the button doesn't overlap. Nexus somehow is showing a larger text.
I have tried setting the text size to 12sp instead of dp with no success and also there isn't preference set in the phone to have a bigger text.
Here is the layout for reference:
<RelativeLayout
android:id="@+id/relativeStudentProfilefollowlayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:gravity="left|center_vertical"
android:orientation="horizontal" >
<LinearLayout
android:id="@+id/linearStudentProfiletotalfollower"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="@dimen/lef_margin"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/otheruser_followers_label"
android:textColor="@color/header_follow_label_color"
android:textSize="12dp" />
<TextView
android:id="@+id/txtStudentProfiletotalfollower"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/view_margin_1dp"
android:text="0"
android:textColor="@color/header_follow_label_color"
android:textSize="12dp" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearStudentProfiletotalfollowing"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="@dimen/lef_margin"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="@string/otheruser_following_label"
android:textColor="@color/header_follow_label_color"
android:textSize="12dp" />
<TextView
android:id="@+id/txtStudentProfiletotalfollowing"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/view_margin_1dp"
android:text="0"
android:textColor="@color/header_follow_label_color"
android:textSize="12dp" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearStudentProfiletotalvisit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="@string/otheruser_views_label"
android:textColor="@color/header_follow_label_color"
android:textSize="12dp" />
<TextView
android:id="@+id/txtStudentProfilevisit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="@dimen/view_margin_1dp"
android:text="0"
android:textColor="@color/header_follow_label_color"
android:textSize="12dp" />
</LinearLayout>
</LinearLayout>
<Button
android:id="@+id/btnStudentProfilefollow"
style="@style/btnStyleFollwingView"
android:layout_width="wrap_content"
android:layout_height="@dimen/btn_height"
android:layout_alignParentRight="true"
android:button="@null"
android:text="Follow"
android:textSize="12dp"
android:visibility="gone" />
</RelativeLayout>
A: Text size is not given in dp but in sp so use this -
android:textSize="12sp"
You can apply this approach -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="5"
>
<RelativeLayout
android:layout_width="@dimen/zeroDp"
android:layout_height="wrap_content"
android:id="@+id/rl1"
android:layout_weight="4"></RelativeLayout>
<RelativeLayout
android:layout_width="@dimen/zeroDp"
android:layout_height="wrap_content"
android:id="@+id/rl2"
android:layout_weight="1"></RelativeLayout>
</LinearLayout>
inside rl2 define layout for your button , inside rl1 define followers layout
A: Make sure you are not using dp for text-size in whole layout xml.
If still overlapping; it may be due to device width which might be little less to fit your content. In that case try reducing text-size or you can use linear layout weight property to solve your problem.
| |
doc_23527140
|
I've tried one approach by counting number of items in List and then tracking if it gets increased by one then shoot the message, but that didn't work.
This is my code:
stream: FirebaseDatabase.instance.reference().child('PendingOrders').child('78945615').onValue,
builder: (context, snapshot){
if(snapshot.hasData && !snapshot.hasError && snapshot.data.snapshot.value!=null) {
DataSnapshot snapshot1 = snapshot.data.snapshot;
List<
PendingOrderLoader> pendingOrderLoaderList = [
];
int counter = 0;
final key = snapshot1.value.keys;
for (var i in key) {
PendingOrderLoader pendingOrderLoader1 = new PendingOrderLoader(
snapshot1.value[i]['ContactNumber'],
snapshot1.value[i]['TotalPrice'],
snapshot1.value[i]['Date'],
snapshot1.value[i]['Time'],
snapshot1.value[i]['Address']['Line1'],
snapshot1.value[i]['Address']['Line2'],
);
pendingOrderLoaderList.add(pendingOrderLoader1);
pendingOrderLoaderList.sort((a, b) =>
a.Counter.compareTo(b.Counter));
counter = counter+1;
}
return
snapshot.data.snapshot.value == null
? SizedBox()
:
ListView.builder
(
shrinkWrap: true,
scrollDirection: Axis.vertical,
itemCount: pendingOrderLoaderList.length,
itemBuilder: (context, index) {
return pendingOrderLoaderList.length == 0
? Container(
child: Text("No Pending Items"),)
: Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () {
Navigator.push(
context, MaterialPageRoute(
builder: (context) =>
PendingOrderDetails(
orderID: pendingOrderLoaderList[index]
.OrderID,
totalPrice: pendingOrderLoaderList[index]
.TotalPrice,
contactNumber: pendingOrderLoaderList[index]
.ContactNumber,
line1: pendingOrderLoaderList[index]
.Line1,
line2: pendingOrderLoaderList[index]
.Line2,
Date: pendingOrderLoaderList[index]
.Date,
Time: pendingOrderLoaderList[index]
.Time,
PaymentMethod: pendingOrderLoaderList[index]
.PaymentMethod,
)
));
},
child: Column(
crossAxisAlignment: CrossAxisAlignment
.start,
children: <Widget>[
Container(
margin: EdgeInsets.only(
left: 10, top: 10),
decoration: BoxDecoration(
borderRadius: BorderRadius
.circular(10),
color: Colors.cyan),
child: Padding(
padding: const EdgeInsets.all(
8.0),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment
.spaceEvenly,
children: <Widget>[
Text(
(pendingOrderLoaderList[index]
.Counter)
.toString()),
Text(
pendingOrderLoaderList[index]
.PaymentMethod),
Text(
pendingOrderLoaderList[index]
.OrderID),
Text(
pendingOrderLoaderList[index]
.Time),
],
),
],
),
)
),
],
),
),
);
}
);
}else{
return Center(child: CircularProgressIndicator()
);
}
})```
A: I think you can use ConnectionState for this. Check your snapshot's connectionState.If this turns 'done' to 'active', that means something added.
A: just check length of fetched data and make a alert(or a sound)
Stream<List<MESSAGELIST>> chatStream() async* {
while (true) {
await Future.delayed(Duration(milliseconds: 500));
List<MESSAGELIST> someChat = await getMessageList(bid);
if(someChat.length > dataLength) { setState(() {
sound.play('ding.mp3');
createChatNotifications();
dataLength = someChat.length;
});}
yield someChat;
}
}
| |
doc_23527141
|
I am receiving a series of long integers (32 bits) by popping them off a stack. I need to assemble these into 4 word(16 byte) packets. The struct I recreated below resembles the first word of a given packet. The difficulty I am having is that in order to determine which word is the starting packet, as well as which type of packet is which I need to be able to read the octal value of the data in the s5 member of the struct.
Simply put, for each message, I need to interpret bits 16-31 as a 16 bit integer regardless if it crosses bit boundaries on other messages.
I would have thought this would be a much easier task, but I cannot seem to get it to work. Here is what I have tried. I'm just getting Null values.
struct S
{
uint8_t s1 :8;
short s2 :2;
bool s3 :1;
int s4 :5;
uint16_t s5 :16;
};
int main() {
S s;
s.s1 = 3;
s.s2 = 2;
s.s3 = true;
s.s4 = 1;
s.s5 = 02050;
long l;
memcpy(&l, &s, sizeof(S));
std::deque<long> d;
d.push_back(l);
cout << *((uint16_t*)(&d.front()+2)) <<endl;
A: If you already have the long value from your stream, why not just use bit shifting?
Assuming the data is big-endian, you could just shift off the first 16 bits, to get your octal value:
// 69733891 is the big-endian integral value represented by
// your posted sample data, so the octal value should be 02050,
// or as an int 1064
long l = 69733891;
uint16_t s5 = l >> 16; // shift off to get the high value (s5)
For little endian (as is implied in your post), you could use a bitwise AND:
uint16_t s5 = l & 0xFFFF;
And for a quick comparison of the assembly generated for a bit shift, versus a pointer alias, here's what GCC generated (no optimizations):
Assembly generated for bit shift (note that SAR is the single instruction to perform a right bit shift):
' uint16_t s5 = l >> 16;
mov rax,QWORD PTR [rbp-0x18]
sar rax,0x10
mov WORD PTR [rbp-0x1a],ax
Assembly generated for pointer alias:
' uint16_t s5 = *((uint16_t*)&d[0]);
lea rax,[rbp-0x20]
mov esi,0x0
mov rdi,rax
call 4e <main+0x4e>
movzx eax,WORD PTR [rax] ' this is the "4e" address called
mov WORD PTR [rbp-0x12],ax
Hope that can help.
A: You are facing multiple issues here:
*
*The bitfield packing is implementation defined
*Reinterpreting your long as S* or S& violates the strict aliasing rule
If you stick with the long value, you either have to use assumptions about your compiler, e.g. endianess, bit-packing order, etc, or maybe disable string aliasing (which I wouldn't recommend).
Solution
If l was created by a memcpy from an instance of struct S, then copying the value back into a different instance of struct S should result in the exact same bit layout.
So, we can make a copy of the front object inside the deque into an instance of struct S and check it's s5 member:
long f = d.front();
S sf;
memcpy(&sf, &f, sizeof(sf));
std::cout << std::oct << sf.s5 << std::endl;
| |
doc_23527142
|
It iterates through the word/plaintext string plaintext that I want to obfuscate. It should iterate plaintextLength-many times. The if-Statements inside the for- Loop make sure that only alphabetical characters are obfuscated. All non-alphabetical characters should just be copied over.
When I input a e.g. keyword baz and e.g. a plaintext barfoo then, my code should take the first character of plaintext, which would be character b (ASCII: 98) and shift it by the first character of keyword, which would happen to be also an character b. So b in plaintext should be shifted by number 1, since b in keyword is the second character in the alphabet and therefor has an index of 1 (i.e. a/A = 0, b/B = 1, c/C = 2, ..., z/Z = 25). b in plaintext will become a c (ASCII 99) and this character c will be saved in the array cipher[0]. The index, by which a character in plaintext should be shifted, is calculated by the function addIndex().
However, it all works fine until it gets over ASCII 122. E.g. if we get to the third character r (ASCII: 114) in plaintext, shifting it by z (= 25) would result in ASCII being 139. Therefore when it reaches the end of the alphabet (ASCII 122), it should start again from a respectively ASCII 97. This line of code cipher[i] = 97 + (ascii - 122); should do this job. But when I run the program, it doesn´t calculate it and saves ascii (which is has the value 139) straight in cipher[2].
I think that there is a problem with typecasting but can´t grasp it as to why this happens. I mean ascii is an integer value so adding 97 and substracting 122 from 139 shouldn´t be a problem. The result of this calculation would be implicitely casted to an character in order to be saved in the array cipher[].
Any help would be greatly appreciated.
(...)
int plaintextLength = strlen(plaintext);
char cipher[plaintextLength];
int ascii;
for (int i = 0; i < plaintextLength; i++)
{
/* capital letter (ASCII range 65 - 90) */
if (plaintext[i] >= 'A' && plaintext[i] <= 'Z')
{
(...)
}
/* small letter (ASCII range 97 - 122) */
else if (plaintext[i] >= 'a' && plaintext[i] <= 'z')
{
ascii = plaintext[i] + addIndex(lowerCaseKeyword[i % keywordLength]);
if (ascii > 'z')
{
cipher[i] = 97 + (ascii - 122); // it doesnt calculate it. Why?
}
else
{
cipher[i] = ascii;
}
}
/* copy over non-aphabetical character */
else
{
(...)
}
}
(...)
int addIndex(char character)
{
string abc = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < 26; i++)
{
if (character == abc[i])
{
return i;
}
}
return 0; // ATTETNTION: might return false information but is needed due to compiler bitching around
}
| |
doc_23527143
|
For example, the following does not work:
html, body, textarea {
margin: 0;
padding: 0;
border: 0;
width: 100%;
height: 100%;
}
<textarea>Text goes here</textarea>
jsFiddle
Because it consumes slightly over 100% of the window, causing a scrollbar to appear:
How do i make a <textarea> consume 100% of the space?
Bonus Reading
*
*How to set width and height of textarea
*How to set a Textarea to 100% height in Bootstrap 3?
*I want to set the height of a TextArea to 100% of a Table Cell in XHTML 1.0 Transitional
*I have a textarea that won't have 100% in width when I set it in CSS or plain HTML?
*How can I make a TextArea 100% width without overflowing when padding is present in CSS?
*Textarea to fill a parent container exactly, with padding
*How to have a textarea at 100% width and keep its margin?
*100% textarea problem
A: This will work. or just add display:block to textarea in your fiddle.
html, body {
margin: 0;
padding: 0;
border: 0;
}
* {
box-sizing: border-box;
}
textarea {
width: 100%;
height: 100vh;
display: block;
}
<textarea placeholder="message"></textarea>
A: The issue is the common white space issue of inline-block/inline element due to vertical alignment. If you check dev tools of google you will see this:
So to fix it you simply need to adjust vertical alignment or make the textarea a block element (like provided in the other answers):
html, body, textarea {
margin: 0;
padding: 0;
border: 0;
width: 100%;
height: 100%;
}
textarea {
vertical-align:top;
}
<textarea>Text goes here</textarea>
A:
html, body {
margin: 0;
padding: 0;
border: 0;
width: 100%;
height: 100%;
}
textarea {
margin: 0;
padding: 0;
border: 0;
width: 100%;
height: 100%;
display:block;
resize:none;/*Add this if you dont want users to resize */
}
<textarea>Text goes here</textarea>
A: Just remove width and height for html and body tag.
Thank me later
| |
doc_23527144
|
Q: How SQL server connection should be changed to Production from Development automatically/dynamically without editing the script manually? Is there a way that it should get/read Production environment?
Please help me out with this, thank you.
A: sys.argv and pass it as a command line parameter.
Pull it from an environment variable value os.environ
Read from a config file with configparser
Without any sample code, it's hard to say what the right approach should be but I would favor a command line parameter as that allows you to provide the value from the SSIS package (instead of defining configurations in both SSIS space and python space)
| |
doc_23527145
|
Thanks in advance.
A: Call groupby with a lambda and iterate over the group object to separate them out into a list of DataFrames:
df_list = [g for _, g in df.groupby(by=lambda x: x[:3], axis=1)]
If you want a mapping of {prefix : dataFrame} instead, you can create a dictionary:
df_dict = {k: g for k, g in df.groupby(by=lambda x: x[:3], axis=1)}
| |
doc_23527146
|
I've not freshly created this project, I've worked on it a long time and only now get how to use Gradle.
Anyone have any suggestions on what might be wrong?
A: Thanks for everyone who viewed!
It was a very weird error. It resolved after I cut the project out of my workspace, repeated the process (then it worked). I put it back into my workspace to see if it would work and in fact it did.
| |
doc_23527147
|
import android.os.Bundle;
import android.support.v4.app.FragmentActivity
public class MyList extends FragmentActivity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.myfragment);
}
}
And here's my code for the fragment:
import android.app.ListFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v4.app.LoaderManager;
import android.view.View;
import android.widget.ListView;
@SuppressWarnings("hiding")
public class ListFrag<Cursor> extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TABLE_BASEPATH = "MyTable_tbl";
private static final String AUTHORITY = "SQLData";
public static final Uri MY_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE_BASEPATH);
private static final String[] PROJECTION = new String[] { "_id", "fieldname" };
private SimpleCursorAdapter mAdapter;
private static final int LOADER_ID = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@SuppressWarnings("unchecked")
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Intent myData = getActivity().getIntent();
Bundle info = myData.getExtras();
SimpleCursorAdapter adapter;
String[] dataColumns = { "fieldname" };
int[] viewIDs = { R.id.mydetails };
adapter = new SimpleCursorAdapter(getActivity(), R.layout.mylist, null, dataColumns, viewIDs, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
getLoaderManager().initLoader(0, info, (LoaderCallbacks<Cursor>) this);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
DetailFrag frag = (DetailFrag) getFragmentManager().findFragmentById(R.id.frag_detail);
if (frag != null && frag.isInLayout()) {
frag.setText(item);
}
}
@SuppressWarnings("unchecked")
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String selection = "level='" + args.getString("Level") + "'";
return (Loader<Cursor>) new CursorLoader(getActivity(), MY_URI,
PROJECTION, selection, null, null);
}
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
switch (loader.getId()) {
case LOADER_ID:
mAdapter.swapCursor((android.database.Cursor) cursor);
break;
}
}
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
}
Just saw your comment about LogCat. Oops. Here's my entire LogCat:
11-05 15:47:27.953: D/dalvikvm(553): Not late-enabling CheckJNI (already on)
11-05 15:47:28.643: I/dalvikvm(553): threadid=3: reacting to signal 3
11-05 15:47:28.683: I/dalvikvm(553): Wrote stack traces to '/data/anr/traces.txt'
11-05 15:47:29.143: I/dalvikvm(553): threadid=3: reacting to signal 3
11-05 15:47:29.153: I/dalvikvm(553): Wrote stack traces to '/data/anr/traces.txt'
11-05 15:47:29.643: I/dalvikvm(553): threadid=3: reacting to signal 3
11-05 15:47:29.653: I/dalvikvm(553): Wrote stack traces to '/data/anr/traces.txt'
11-05 15:47:30.143: I/dalvikvm(553): threadid=3: reacting to signal 3
11-05 15:47:30.153: I/dalvikvm(553): Wrote stack traces to '/data/anr/traces.txt'
11-05 15:47:30.643: I/dalvikvm(553): threadid=3: reacting to signal 3
11-05 15:47:30.693: D/gralloc_goldfish(553): Emulator without GPU emulation detected.
11-05 15:47:30.693: I/dalvikvm(553): Wrote stack traces to '/data/anr/traces.txt'
11-05 15:47:32.843: E/ActivityThread(553): Failed to find provider info for SQLData
11-05 15:47:32.883: D/AndroidRuntime(553): Shutting down VM
11-05 15:47:32.883: W/dalvikvm(553): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
11-05 15:47:32.903: E/AndroidRuntime(553): FATAL EXCEPTION: main
11-05 15:47:32.903: E/AndroidRuntime(553): java.lang.NullPointerException
11-05 15:47:32.903: E/AndroidRuntime(553): at com.MyKnitCards.project.ListFrag.onLoadFinished(ListFrag.java:71)
11-05 15:47:32.903: E/AndroidRuntime(553): at android.support.v4.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:425)
11-05 15:47:32.903: E/AndroidRuntime(553): at android.support.v4.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:393)
11-05 15:47:32.903: E/AndroidRuntime(553): at android.support.v4.content.Loader.deliverResult(Loader.java:103)
11-05 15:47:32.903: E/AndroidRuntime(553): at android.support.v4.content.CursorLoader.deliverResult(CursorLoader.java:81)
11-05 15:47:32.903: E/AndroidRuntime(553): at android.support.v4.content.CursorLoader.deliverResult(CursorLoader.java:35)
11-05 15:47:32.903: E/AndroidRuntime(553): at android.support.v4.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:221)
11-05 15:47:32.903: E/AndroidRuntime(553): at android.support.v4.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:61)
11-05 15:47:32.903: E/AndroidRuntime(553): at android.support.v4.content.ModernAsyncTask.finish(ModernAsyncTask.java:461)
11-05 15:47:32.903: E/AndroidRuntime(553): at android.support.v4.content.ModernAsyncTask.access$500(ModernAsyncTask.java:47)
11-05 15:47:32.903: E/AndroidRuntime(553): at android.support.v4.content.ModernAsyncTask$InternalHandler.handleMessage(ModernAsyncTask.java:474)
11-05 15:47:32.903: E/AndroidRuntime(553): at android.os.Handler.dispatchMessage(Handler.java:99)
11-05 15:47:32.903: E/AndroidRuntime(553): at android.os.Looper.loop(Looper.java:137)
11-05 15:47:32.903: E/AndroidRuntime(553): at android.app.ActivityThread.main(ActivityThread.java:4424)
11-05 15:47:32.903: E/AndroidRuntime(553): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 15:47:32.903: E/AndroidRuntime(553): at java.lang.reflect.Method.invoke(Method.java:511)
11-05 15:47:32.903: E/AndroidRuntime(553): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-05 15:47:32.903: E/AndroidRuntime(553): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-05 15:47:32.903: E/AndroidRuntime(553): at dalvik.system.NativeStart.main(Native Method)
11-05 15:47:33.213: I/dalvikvm(553): threadid=3: reacting to signal 3
11-05 15:47:33.233: I/dalvikvm(553): Wrote stack traces to '/data/anr/traces.txt'
11-05 15:47:33.513: I/dalvikvm(553): threadid=3: reacting to signal 3
11-05 15:47:33.533: I/dalvikvm(553): Wrote stack traces to '/data/anr/traces.txt'
A: First try switching these imports to the support library versions. Change:
import android.app.ListFragment;
import android.app.LoaderManager.LoaderCallbacks;
to:
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
Next make sure you are asking for the support fragment manager:
DetailFrag frag = (DetailFrag) getActivity().getSupportFragmentManager().findFragmentById(R.id.frag_detail);
// ^^^^^^^
(This might not solve everything, if you still need help post the LogCat errors from these changes so we can see exactly what is happening.)
Addition
mAdapter is null, change adapter to mAdapter here:
mAdapter = new SimpleCursorAdapter(getActivity(), R.layout.mylist, null, dataColumns, viewIDs, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
A: You should check Sherlock, they offer different versions of loaders working with fragments. You just have to download their package and inside you can find the samples working.
Ups, I just saw this is seven months old. Hope it is still usefull.
| |
doc_23527148
|
I have looked into the following methods, I'm hoping someone knows a bit more to extend on them if it is possible, or to offer others:
*
*Use photogrammetry by taking multiple photos to build a 3d image (but ideally I want to only take 1 photo)
*Analyse lighting/levels of the photo
*Detect depth in the photo
A: We could not distinguish the photo of a 3D object from a second photo of the 1st photo.
The geometric relationship between the 3D object and the 1st photo is described by perspective transformation, while the relationship between the 2nd photo and the 1st photo by projective transformation. The projective transformation is invertible, so the distortions on the two photos are similar.
If the 2nd photo is obtained by a parallel projection, it could be achievable to detect their difference.
here is a good introduction to the concepts:
http://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/BEARDSLEY/node3.html
| |
doc_23527149
|
A: You can use
$mpdf = new Mpdf\Mpdf();
$pageNumber = count($mpdf->pages);
But the $pages property of the object is internal and access to it may be disabled in future versions.
| |
doc_23527150
|
*
*if only one thread try to insert or remove an element, it will be able to;
*if two or more threads are trying at the same time, one will be able to, and the next one will execute its operations when the first one finishes.
I made it using synchronized blocks, just like that:
import java.util.ArrayList;
import java.util.Random;
public class EditorThread extends Thread {
static int N = 10; // number of threads
static queue Q = new queue(); // shared queue
private int number; //number of the thread
public EditorThread(int n) {
number = n;
}
@Override
public void run() {
Random r = new Random();
while (true) {
int t = r.nextInt(2);
if (t == 1) {
int value = Q.get();
if (value == -1) {
System.out.println("The Thread " + number + " couldnt get any element (empty queue)");
}
else {
System.out.println("The Thread " + number + " got the element " + value );
}
}
else {
int n = r.nextInt(100);
Q.put(n);
System.out.println("The Thread " + number + " inserted the element " + n);
}
}
}
public static void main(String[] args) {
for (int i = 0; i < N; i++) {
Thread t = new EditorThread(i);
t.start();
}
}
}
class queue {
node head;
node tail;
queue() {
head = tail = null;
}
public synchronized int get() {
if (head == null)
return -1;
int r = head.value;
if (head != tail)
head = head.next;
else
head = tail = null;
return r;
}
public synchronized void put(int i) {
node n = new node(i);
if (head == null)
head = tail = n;
else {
tail.next = n;
tail = n;
}
}
}
class node {
int value;
node next;
public node(int value) {
this.value = value;
}
}
the run void is simple, it just loops forever while inserts or removes elements.
My question is, how can I follow that conditions without using synchronized?
How is it possible to guarantee mutual exclusion without the synchronized blocks?
EDIT: I cannot use things similar to synchronized (just like locks)
A: No, and yes.
Fundamentally you need to use some form of synchronization to do this. There is no way to do it yourself without.
However there are classes in the java.util.concurrent package that provide exactly the sort of behaviour you need and do it while minimizing locking and the cost of synchronization as much as possible.
For example LinkedBlockingQueue. https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedBlockingQueue.html
If you really want to understand how this stuff works though you should also read up on Non Blocking Algorithms. The wiki page is a good start. In general a lot of very smart people who know exactly what they are doing have worked on the concurrent package though. Threading is hard to get right.
https://en.wikipedia.org/wiki/Non-blocking_algorithm
| |
doc_23527151
|
Here's my code
p_n <- ggplot(n,aes(x=Time,y=n)) +
geom_boxplot() + geom_jitter(position = position_jitter(height = 0,width=0.1), size = 0.5) +
ylim(1.5,3) + labs(x = ' ', y='n') +
geom_signif(comparisons = list(c('Initial','Final')), map_signif_level = TRUE, text_size = 6)
Any help is appreciated.
| |
doc_23527152
|
The program includes getting input from the user but when I enter the input to the console it won't ever continue running the code (it'll keep asking for input).
I can't debug without fixing this and would appreciate some help.
Thank you.
The code gets stuck on the while loop fgets:
int main(int argc, const char**argv) {
FILE* inputFile = NULL;
setlocale(LC_ALL, "");
if(argc == 2){
inputFile = fopen(argv[1], "r");
if (inputFile == NULL){
printf("Problem opening file %s, make sure correct path name is given.\n", argv[1]);
return 0;
}
}
else {
inputFile = stdin;
}
char buffer[MAX_STRING_INPUT_SIZE];
// Reading commands
while ( fgets(buffer, MAX_STRING_INPUT_SIZE, inputFile) != NULL ) {
fflush(stdout);
if ( parser(buffer) == error ){
printf("ERROR\n");
break;
}
};
fclose(inputFile);
return 0;
}
A: The issue comes from Eclipse buffering the console inputs.
One way to fix it is to force Eclipse to debug using a Windows/DOS native console.
The procedure is described in details here, but in brief :
*
*Create your Hello World C++ command line project, from the Eclipse menu File > New > C++ Project
*In your project folder, create a ".gdbinit" text file. It will contain your gdb debugger configuration
*Edit ".gdbinit", and add the following line (without quotes) : "set new-console on"
*In Eclipse, go to menu Run > "Debug Configurations", and select your application name in the left pane
*In the "debugger" tab, ensure the "GDB command file" now points to your « .gdbinit » file. Else, input the path to your ".gdbinit" configuration file
*Click « Apply » and « Debug ». You’re done ! A native DOS command line should be launched.
A: Well I know that Eclipse console buffer doesn't always work as it should - in my experiences, it's the worst when using C or C++.
If you want to run your compiled code in Eclipse, this will greatly help but not eliminate the display issues you might encounter in Eclipse:
setvbuf(stdout, NULL, 0, _IONBF);
However, I don't know how this affects debugging in Eclipse while using stdin. Your best option is to use Nicolas's answer to run through the DOS console. A bit more work, but it will suffice I believe.
And please note that the above line should only be used while running your code through Eclipse, in order to have some kind of sane output buffer without several messy in-code workarounds. This line needs to be commented out when compiling for actual use.
| |
doc_23527153
|
i have dynamic elements in my android app and there is nothing to find it out .Please check screen shot of my app and attributes and let me how can we do it.
I have tried with the given attributes
I just want ti find these elements and send keys
A: Try find element by xpath with this value:
//*[contains(@class,'android.widget.EditText')]
It will return the first element if there are many elements with same class.
If you want other element with class EditText, you can add count like this:
(//*[contains(@class,'android.widget.EditText')])[2]
The above for second element.
A: I tried this way of finding element:
List name = driver.findElements(By.xpath("android.widget.EditText"));
name.get(0).click();
But i am getting bellow error:-
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
Please let me know what is the issue?
A: I found one of my dynamic element through this method :-
findElementByXPath("//android.widget.FrameLayout[@index='0']/android.widget.EditText[@index='0']")
but for second element also , these details are same, so if i am putting same method to find second element , it search the first one only.
Than i printed size of the element with this find method
Size is coming like this
(996, 89)
Please let me know how can i find second element , because it has same details.
| |
doc_23527154
|
from functools import lru_cache
class foo:
_cached_funcs = set()
@register_data_reader # adds the LRU DECORATED func to _cached_funcs
@lru_cache(maxsize=16)
def reads_data_somewhere(self, ...)
...
return data
def clear_cache(self):
for f in _cached_funcs:
f.cache_clear()
A: Just a thought on how to implement this... Why even bother registering the methods with a decorator and tracking them in _cache_funcs? Instead iterate over the classes methods and try to run .cache_clear() on them?
class Foo:
@lru_cache(maxsize=16)
def reads_data_somewhere(self):
return 2 + 2
def clear_cache(self):
for method in dir(self):
try:
getattr(self, method).cache_clear()
except AttributeError:
pass
f = Foo()
print(f.reads_data_somewhere())
print(f.reads_data_somewhere())
print(f.reads_data_somewhere())
print(f.reads_data_somewhere())
print(f.reads_data_somewhere.cache_info())
f.clear_cache()
print(f.reads_data_somewhere.cache_info())
Output:
4
4
4
4
CacheInfo(hits=3, misses=1, maxsize=16, currsize=1)
CacheInfo(hits=0, misses=0, maxsize=16, currsize=0)
A: Thanks Terry, that was useful.
In the end, I am running the following method in the init of my class, inspired by yours. It allowed me to bypass throwing an exception, and I'm registering once cached methods, as there are relatively few compared to the total number.
Class foo:
...
def _register_cache(self):
lst = dir(self)
for method in lst:
if hasattr(getattr(self, method), "cache_info"):
self._cached_methods.add(method)
| |
doc_23527155
|
Can someone explain me what exactly happens with my code and why it gives me an incorrect result.
This is my code:
age=20
while age >= 10:
age=int(input("what is your age?"))
print("your age is >= 10")
and response is this:
what is your age? 9
"your age is >= 10"
I am not understanding this. I am using windows7 & python3
A: The problem is you are printing "your age is >= 10" after asking the age, but not actually checking what age they entered first. You should use a conditional statement around the print to prevent it from printing if the age isn't >= 10.
age=20
while age >= 10:
age=int(input("what is your age?"))
if age >= 10:
print("your age is >= 10")
A: Have you tried running this code? It would help clarifying.
Input is a function that takes the string "what is your age?", prompts the user, and returns the answer the user inputs in the command line. The function int() then casts the user answer from string into an integer. After, this integer is assigned to the variable age age=, and then prints a message saying "your age is >= 10"
What happens is every time the loop runs, the program asks the user for his age, and assign it to the variable age. Then the while loop checks for the condition: is age equal or larger than 10? age >= 10. If it is not, it keeps looping. It will only exit the loop if the user inputs an age that is smaller than 10.
Hope it helps.
| |
doc_23527156
|
(link to YT official way - NB: now
broken, but YT hasn't (bothered to) correct this page:
http://apiblog.youtube.com/2009/02/youtube-apis-iphone-cool-mobile-apps.html)
In July 2010, they deliberately removed that - it no longer works (I've got an app that worked fine prior to the change, and now doesn't, using YT's own code).
There's a "new" way that the YouTube folks described as "experimental" - but it's only partially working. Where you could previously put YT videos into your iPhone GUI, now you cannot - they are "required" to be given an entire screen to themselves.
(link to YT official "new" way:
http://apiblog.youtube.com/2010/07/new-way-to-embed-youtube-videos.html)
(link to YT official thread, that ends
with "it might work... eventually":
http://code.google.com/apis/youtube/forum/discussion.html?place=topic%2Fyoutube-api-gdata%2FtMYvulpGUow%2Fdiscussion)
Worse, YouTube engineers didn't provide any user feedback; when the user clicks on a button, you have to wait for the YT servers to process a couple of web lookups (you can see this if you look at your console log files).
All the user sees is: "this app appears to have crashed".
Argh! Is there any other way? What are other people using here that's working still - on OS 3.x + 4.x - since the recent YT changes?
A: I currently use code similar to this for embedding youtube videos into apps. However, when a user taps on the video (generates a thumbnail the user can tap on in the webview) it goes full screen, so may not be what you're looking for.
NSMutableString* urlString = [NSMutableString stringWithFormat:@"http://gdata.youtube.com/feeds/api/videos/%@?v=2&alt=jsonc", youtubeId];
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
NSURLResponse* response = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// Extract JSON from data into an NSDictionary
NSDictionary* jsonDict = /* however you want to do it */
// Make sure that the video hasn't been flagged as restricted, otherwise the user won't know what's going on. Later check restricted and present an error as appropriate.
BOOL restricted = youtubeVideoRestricted(jsonDict);
If restricted is NO, then I feed the web view some html like this:
embedSrc = @"<object width=\"640\" height=\"385\">"
"<param name=\"movie\" value=\"http://www.youtube.com/v/%@\"></param>"
"<embed src=\"http://www.youtube.com/v/%@\" type=\"application/x-shockwave-flash\" width=\"640\" height=\"385\"></embed>"
"</object>";
embedSrc = [NSString stringWithFormat:embedSrc, youtubeId, youtubeId];
I have this in an app on the store right now, works fine. That said, I've learned to keep the video up. So in case of problems with the youtube feed, it falls back to the blip.tv service where the video lives as well. User doesn't notice something failed on youtube. But that's beyond the scope of your question.
| |
doc_23527157
|
<input type="checkbox" name="vehicle" value="Bike"
onclick="javascript:selectCustomers(${sessionScope.custId});">
Getting the following error:
org.apache.jasper.JasperException: customer.jsp(1419,33) According to TLD or attribute directive in tag file,
attribute onclick does not accept any expressions
Can we not use expression language in JavaScript (in my case under onClick() Event)?
A: When a JSP page is called, the following happens, in this order:
*
*Server checks to see if the .jsp has already been compiled and whether or not it has changed since it was last compiled.
*Server runs the jsp through the Jasper compiler, which interprets the jsp into Java code, anything that is not Java (CSS, HTML, JavaScript, etc) is placed in a String.
*The Java code is compiled and executed.
*The results are placed in the response and sent to the user.
So, your statement: ${sessionScope.custId} is executed before the the HTML is sent to the user, and the input of selectCustomers() function is already set to before calling it.
For more info have a look at my another post JSP inside ListItems onclick
How to verify it?
Right click in the browser and look at the view source.
Try below sample code that might help you.
Enclose ${...} inside the single quotes.
<c:set var="custId" value="1234" scope="session" />
Before :
<c:out value="${sessionScope.custId}"></c:out>
<input type="checkbox" name="vehicle" value="Bike"
onclick="javascript:selectCustomers('${sessionScope.custId}');">
<c:set var="custId" value="4321" scope="session" />
After:
<c:out value="${sessionScope.custId}"></c:out>
View Source code: (Right click in browser to view it)
Before : 1234
<input type="checkbox" name="vehicle" value="Bike"
onclick="javascript:selectCustomers('1234');">
After: 4321
A: Try this:
<input type="hidden" id="custId" name="custId" value="${sessionScope.custId}">
<input type="checkbox" name="vehicle" value="Bike" onclick="javascript:selectCustomers();">
function selectCustomers(){
var custId = document.getElementById('custId').value;
}
| |
doc_23527158
|
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class JavaCopyFile {
public static void main(String[] args) throws InterruptedException, IOException {
int i=0,count=0;;
while(i<15) {
File source = new File("error.txt");
File dest = new File("criteria.txt");
// copy file conventional way using Stream
//long start = System.nanoTime();
copyFileUsingStream(source, dest);
//System.out.println("Time taken by Stream Copy = " + (System.nanoTime() - start));
if(i<15) {
count++;
}
i++;
}
System.out.println(count);
}
private static void copyFileUsingStream(File source, File dest)
throws IOException {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(source);
output = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
}catch(Exception e) {
System.out.println("File not found exception");/*finally {
input.close();
output.close();
*/
}
}
}
I have written code as above - for testing purpose I set count variable. count is giving 15 it is perfect. But file is copying once only. I want to copy the file for 15 times to the same destination file. Please help me to solve this problem. I am a beginner in java programming.
A: As suggested in the comments, your logic is correct but you are re-writing the destination file every time.
Use the variable i to denote each tiem you are writing to a new destination file as shown below :
File dest = new File("criteria" + i + ".txt");
This will create 15 files in the destination and thus avoids re-writing the same destination.
EDIT :
As per your latest comment change the code to as follows :
public static void main(String[] args) throws InterruptedException, IOException {
int i = 0, count = 0;
File source = new File("error.txt");
File dest = new File("criteria.txt");
OutputStream output = new FileOutputStream(dest);
while (i < 15) {
copyFileUsingStream(source, output);
if (i < 15) {
count++;
}
i++;
}
System.out.println(count);
}
private static void copyFileUsingStream(File source, OutputStream output)
throws IOException {
InputStream input = null;
try {
input = new FileInputStream(source);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
} catch (Exception e) {
System.out.println("File not found exception");
}
}
Instead of creating the OutputStream in each iteration of the loop, create it once and pass it to copyFileUsingStream every time so that the previous stream is maintained.
| |
doc_23527159
|
Would someone be able to explain the differences between adding a Programmable SMS/Messaging Service via me logging into the twilio.com/console and creating a service resource via the API, https://www.twilio.com/docs/sms/services/api#create-a-service-resource.
When I'm logged into the console and click the + to add a new messaging service I'm prompted for USE CASE, with many options: "Mixed", "Marketing, Outbound Only", ...
but the API does not have such a parameter.
What I'd like to know is which settings are set when creating a messaging service for each of the options and what are the values of these settings. Given there are currently nine options, I'd rather not have to create nine different Messaging Services in order to discern the differences.
Thanks
A: The options in that Twilio Console drop down of the Create a New Messaging Service dialog, "Mixed", "Marketing, Outbound Only", etc have no impact on the behavior of the messaging service. They are an artifact of the GUI and can be safely ignored.
| |
doc_23527160
|
A: It is hard to give a concrete answer to such an abstract question, but I'll give it a try:
Image files are usually compressed: a .png or .jpg of size h by w by 3 takes far less disk space than h*w*3 bytes due to compression. On the other hand, for processing the image in a neural network (or any other ML software for that matter) you need to work with the un-compressed representation of the image. Therefore, lmdb, leveldb, hdf5 datasets used by caffe stores the input images in an uncompressed manner using 32bit float numbers for each pixels (instead of uint8) thus the drastic increase in file size.
| |
doc_23527161
|
A: No, you need to define them. To do so you can provide your own profile in which you define all the Datatypes you need, this will be your types library model. And then you can use this types in any other model by referencing the types from your libray.
To define the types you juste create a model as you do usually and then to use them in another model you can reference the profile by clicking on Project Dependencies in the Model Explorer and then on Add Model:
A dialog box opens, and then you have to select on your file system the .uml model which definies the types:
In my example this file is named types.uml:
Then you validate and you can see in the Model Explorer your profiles un the Project Dependencies.
Now you can use the types in your model. For example, I created a class with a property and I want to set the property type to Date. Then I clixk on the + utton in the properties view and this open a dialog which by default is on the Model REsource tab. I select the All Resources tab and then I am able to select the Date type.
In the end I got a property with Date as type:
| |
doc_23527162
|
But I am not getting the edits saved during the form and I am getting error. Kindly let me know how to fix this!
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label mb-10">Google Analytics Code</label>
<textarea class="form-control" rows="10" id="ganalytics" class="form-control" name="ganalytics"><?php echo $ganalytics;?>"</textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label mb-10">Facebook Pixel Code</label>
<textarea class="form-control" rows="10" id="fbpixel" class="form-control" name="fbpixel"><?php echo $fbpixel;?>"</textarea>
</div>
</div>
</div>
PHP Code:
if (isset($_POST['save']))
{
$fbpixel= $_POST['fbpixel'];
$ganalytics= $_POST['ganalytics'];
echo $fbpixel;
echo $ganalytics;
}
A: You have typo an " is floating on your code
change
<textarea class="form-control" rows="10" id="fbpixel" class="form-control" name="fbpixel"><?php echo $fbpixel;?>"</textarea>
to
<textarea class="form-control" rows="10" id="fbpixel" class="form-control" name="fbpixel"><?php echo $fbpixel;?></textarea>
and this
<textarea class="form-control" rows="10" id="ganalytics" class="form-control" name="ganalytics"><?php echo $ganalytics;?>"</textarea>
to
<textarea class="form-control" rows="10" id="ganalytics" class="form-control" name="ganalytics"><?php echo $ganalytics;?></textarea>
| |
doc_23527163
|
>> d = gpuDevice
d =
CUDADevice with properties:
Name: 'GeForce 800M'
Index: 1
ComputeCapability: '2.1'
SupportsDouble: 1
DriverVersion: 6
ToolkitVersion: 5
MaxThreadsPerBlock: 1024
MaxShmemPerBlock: 49152
MaxThreadBlockSize: [1024 1024 64]
MaxGridSize: [65535 65535 65535]
SIMDWidth: 32
TotalMemory: 2.1475e+09
FreeMemory: 1.9886e+09
MultiprocessorCount: 1
ClockRateKHz: 1475000
ComputeMode: 'Default'
GPUOverlapsTransfers: 1
KernelExecutionTimeout: 1
CanMapHostMemory: 1
DeviceSupported: 1
DeviceSelected: 1`
I try use gpu in neuralnetwork train, but my gpu slower than cpu.
If I try use gpuArray, gpu is faster than cpu, but I haven't speed acceleration in neural network training.
For example
>> a1 = rand(1000); b1 = rand(1000); tic; c1 = a1 * b1; toc;
Elapsed time is 0.044095 seconds.
>> a2 = gpuArray(rand(1000)); b2 = gpuArray(rand(1000)); tic; c2 = a2 * b2; toc;
Elapsed time is 0.000416 seconds.
But in code
net = newff(H, F, Layers, { 'tansig' 'tansig'}, 'traingdx', 'learngdm', 'mse');
net.trainParam.epochs = Epochs;
net.trainParam.show = 500;
net.trainParam.time = 495;
net.trainParam.goal = 2.0000e-11;
net.trainParam.max_fail = 200000;
net.trainParam.min_grad = 1.0000e-050;
net.performParam.regularization = 0.05;
net.divideParam.trainRatio = 1;
net.divideParam.valRatio = 0;
net.divideParam.testRatio = 0;
net.trainParam.showWindow = 0;
net.trainParam.showCommandLine = 0;
if Gpu1 == 1
net = train(net, H, F, 'useGPU', 'yes', 'showResources','yes');
else
net = train(net, H, F, 'showResources','yes');
end;
tic; net = net_example(300, [23, 9], rand(100, 1000), rand(1, 1000), 1); toc;
Computing Resources:
GPU device #1, GeForce 800M
works slower than
tic; net = net_example(300, [23, 9], rand(100, 1000), rand(1, 1000), 0); toc;
Computing Resources:
MEX2
| |
doc_23527164
|
function loadNotification(searchOption, searchKey) {
var url = '@URLs.API.Notifications.Past' + '?searchOption=' + searchOption + '&searchValue=' + searchKey;
$.getJSON(url)
.done(function (nData) {
//some code here
})
.fail(function (jqXHR, status, error) {
showError('There was an error while fetching the records. Please try after some time. (' + jqXHR.status + ':' + jqXHR.statusText + ')');
});
}
Using jasmine, how do I test if the json file fails or not? I was thinking of using .done and .fail but I'm not sure if it's possible. I don't know much about json. Can anyone help me out?
A: when testing AJAX requests (and similar, fetching json file etc.), it's always a good idea to check that your code can handle both done and fail. You should also mock the data that you test, don't rely much on actual endpoints in your application or files that it tries to download. You want the test to run as fast as possible.
Using Jasmine you can do a few things:
using a spy:
spyOn is a function that can stub a given function and track what kind of arguments were passed to it, can see what other function called it and even return a specific value when the code that it's spied on executes.
You could use a spy to see that the $.get request will happen, and then you can say return a specific value, and continue testing the program.
using Jasmine Ajax plugin
This is what I like to use in my tests. Jasmine has a very nice plugin ajax.js. It simplifies testing any ajax functionality. What I like to do is to mock the actual request, so when your code would tries to get a file/response, the code will ignore the actual call and mock it, returning fake data that you can specify.
Before I start, I also like to have my ajax method in a separate function, it will just return a promise. It's much easier to read/test/maintain, so for example you could rewrite it like:
this.loadNotificationCall = function(searchOption, searchKey) {
var url = '@URLs.API.Notifications.Past' + '?searchOption=' + searchOption + '&searchValue=' + searchKey;
return $.getJSON(url)
}
this.loadNotification() {
return this.loadNotificationCall()
.done(function (nData) {
//some code here
})
.fail(function (jqXHR, status, error) {
showError('There was an error while fetching the records. Please try after some time. (' + jqXHR.status + ':' + jqXHR.statusText + ')');
});
}
If you load your test app with dummy data, I guess you expect the ajax request file to have a specific path.
You're looking at most basic, default version of what you can output from
'@URLs.API.Notifications.Past' + '?searchOption=' + searchOption + '&searchValue=' + searchKey;
Let's say it's something like
//'someapi?searchOption=1&searchValue=abc'
That url needs to exactly match to what will your application would attempt to contact. Check your debug/fiddler and see what is that just in case. If it's not matched (including the data it's trying to send) the mock will fail, and test will timeout. The error usually looks like Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
Once you get that right, you can mock that url in the following example:
describe('when user gets the data', function() {
var sut = null;
var testCall = null;
var dummyData = {
name: 'Jon Snow'
};
beforeEach(function() {
jasmine.Ajax.install();
jasmine.Ajax.stubRequest("someapi?searchOption=1&searchValue=abc").andReturn({
responseText: JSON.stringify(dummyData)
});
sut = new yourApplication();
testCall = sut.loadNotification();
});
afterEach(function() {
jasmine.Ajax.uninstall();
});
// actual tests here
});
I'm also pretty sure that you can use wildcards in those mock urls, so this should also be valid: jasmine.Ajax.stubRequest("someapi?(.*)").andReturn(//
So what happens now is, if you test something that will call your method with $.get, the request won't happen to your server, but instead it will be mocked and our dummy data will be returned. In this example it's a simple object with name: 'Jon Snow'
Now, you want to have a test that looks something like this:
it('should populate name', function(done) {
testCall
.done(function() {
expect(sut.name).toEqual('Jon Snow');
done();
});
});
You pass done argument to the test, so that it won't finish until the call is finished. If you debug it in your browser, you will see that code in your file will go inside done method and continue working as it was a real request. The data in done(nData) will become our dummy object with name: Jon Snow.
If you wanted to test a failing code, you can add some additional settings to ajax plugin:
jasmine.Ajax.stubRequest("someapi?searchOption=1&searchValue=abc").andReturn({
status: 500,
responseText: "{}"
});
I hope I didn't bore you with this much, I know that there are simplier methods (such as just doing $.spy on 'ajax' and seeing the most recent call etc. but I like my method, has worked very well and I can test multiple calls, chained calls, and many more cool scenarios.
| |
doc_23527165
|
Maybe fetch the record, and timeDiff it with updatedAt - date()
I'm very confused, any tips would be greatly appreciated.
| |
doc_23527166
|
navigator.credentials.create() and navigator.credentials.get().
I have no problem when I execute my code on localhost, and the webapp is asking for my security key. But when I am on my local server, with the exact same code, navigator.credentials is undefined although I am using the same browser.
Uncaught TypeError: Cannot read property 'create' of undefined
(window.PasswordCredential || window.FederatedCredential) returns false, only on my server 192.168.x.x but I don't know why. I am on Chrome 74.
How could I resolve this problem ?
Thank you for your help.
A: WebAuthn javascript will work only when used with HTTPS or on the localhost hostname (in this case HTTPS is not required).
It seems that you are using an IP address.
| |
doc_23527167
|
error
Internal Server Error: /team/
Traceback (most recent call last):
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/rest_framework/views.py", line 489, in dispatch
response = self.handle_exception(exc)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/rest_framework/views.py", line 449, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/rest_framework/views.py", line 486, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/rest_framework/generics.py", line 244, in post
return self.create(request, *args, **kwargs)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/rest_framework/mixins.py", line 21, in create
self.perform_create(serializer)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/rest_framework/mixins.py", line 26, in perform_create
serializer.save()
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/rest_framework/serializers.py", line 215, in save
self.instance = self.create(validated_data)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/rest_framework/serializers.py", line 916, in create
instance = ModelClass.objects.create(**validated_data)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 394, in create
obj.save(force_insert=True, using=self.db)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/base.py", line 806, in save
force_update=force_update, update_fields=update_fields)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/base.py", line 836, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/base.py", line 922, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/base.py", line 961, in _do_insert
using=using, raw=raw)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 1061, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1099, in execute_sql
cursor.execute(sql, params)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/backends/utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 101, in execute
return self.cursor.execute(query, args)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/MySQLdb/cursors.py", line 250, in execute
self.errorhandler(self, exc, value)
File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler
raise errorvalue
IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`peaceapp`.`peace_teammember`, CONSTRAINT `peace_teammember_owner_id_2c587836_fk_auth_user_id` FOREIGN KEY (`owner_id`) REFERENCES `auth_user` (`id`))')
model
class PeaceHero(models.Model):
first_name = models.CharField(max_length=100, blank=False)
last_name= models.CharField(max_length=100, blank=False)
owner = models.ForeignKey('auth.User', related_name = 'peacehero', on_delete=models.CASCADE, default='1')
class TeamMember(models.Model):
first_name = models.CharField(max_length=100, blank=False)
last_name= models.CharField(max_length=100, blank=False)
owner = models.ForeignKey('auth.User', related_name = 'captain', on_delete=models.CASCADE, default='1')
serliazer
class PeaceHeroSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source='owner.id')
class Meta:
model = PeaceHero
fields = ('url','id', 'first_name','last_name','quote','owner')
class UserSerializer(serializers.HyperlinkedModelSerializer):
peacehero = serializers.HyperlinkedRelatedField(many=True, view_name='peacehero-detail', read_only=True)
captain = serializers.HyperlinkedRelatedField(many=True, view_name='team-details',read_only=True)
class Meta:
model = User
fields = ('url','id','username', 'password','peacehero','captain')
class TeamMemberSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source='owner.id')
class Meta:
model = TeamMember
fields = ('id','first_name','last_name','owner')
view
class PeaceHeroList(generics.ListCreateAPIView):
queryset = PeaceHero.objects.all()
serializer_class = PeaceHeroSerializer
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
#retrieve or delete or update pece heroes.
class PeaceHeroDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = PeaceHero.objects.all()
serializer_class = PeaceHeroSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
#list all registered users
class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
#retrieve a user from database
class UserDetail(generics.RetrieveDestroyAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
#retrieve a team member
class TeamList(generics.ListCreateAPIView):
queryset = TeamMember.objects.all()
serializer_class = TeamMemberSerializer
A: It sounds like there's a row in peace_teammember that has a owner_id value that doesn't have a corresponding record in auth_user.
Find the team members that have a owner_id that doesn't exist in the users table. Delete them or create the corresponding users, then create the foreign key.
A: You are on the right path but here is the case that the database is expecting an owner id with its respective user. I am quite sure you migrated the peace_teammember later in the project. Delete the tables if possible the database and retry.
| |
doc_23527168
|
Here I am dealing with an inventory management system. I downloaded an open source project from the web. I want to edit/remove the VAT feature from this project. I changed the way of calculating vat from this,
// vat
var vat = (Number($("#subTotal").val())/100) * 13;
vat = vat.toFixed(2);
$("#vat").val(vat);
$("#vatValue").val(vat);
// total amount
var totalAmount = (Number($("#subTotal").val()) + Number($("#vat").val()));
totalAmount = totalAmount.toFixed(2);
$("#totalAmount").val(totalAmount);
$("#totalAmountValue").val(totalAmount);
to this
// vat
var vat = (Number($("#subTotal").val())/100) * 2;
vat = vat.toFixed(2);
$("#vat").val(vat);
$("#vatValue").val(vat);
// total amount
var totalAmount = (Number($("#subTotal").val()) + Number($("#vat").val()));
totalAmount = totalAmount.toFixed(2);
$("#totalAmount").val(totalAmount);
$("#totalAmountValue").val(totalAmount);
but it's always calculating 13% of VAT. Please help me solve this problem.
A: If you want to calculate VAT dynamically then add an input
<input type="text" value="0" id="vat-percentage" name="vat-percentage" />
and then replace this
var vat = (Number($("#subTotal").val())/100) * 13;
with that
var vat = (Number($("#subTotal").val())/100) * Number($('#vat-percentage').val());
| |
doc_23527169
|
import React, { useEffect, useState } from 'react'
import useAxios from 'axios-hooks'
import { Table, Space } from 'antd'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faEdit, faCalendar, faUserPlus, faTimes } from '@fortawesome/free-solid-svg-icons'
export const RemoveProjectButton = ({ project, updateProjects }) => {
const [, execute] = useAxios(
{
url: `${process.env.REACT_APP_API_URL}/projects/${project.key}/`,
method: 'delete'
},
{
manual: true
}
)
const removeProject = async (project) => {
await execute()
updateProjects(project)
}
return <a data-testid={`project-${project.key}`} onClick={() => { removeProject(project) }}><FontAwesomeIcon icon={faTimes} /></a>
}
export const Projects = () => {
const [projects, setProjects] = useState([])
const [{ data, loading, error }] = useAxios(
`${process.env.REACT_APP_API_URL}/projects/`
)
useEffect(() => {
setProjects(data)
}, [data])
useEffect(() => {}, [projects])
const updateProjects = (projectToDelete) => {
setProjects(() => projects.filter(project => project.key !== projectToDelete.key))
}
if (loading) return <p data-testid='loading'>Loading...</p>
if (error) return <p data-testid='error'>Error!</p>
const columns = [
{
title: 'Title',
dataIndex: 'title',
key: 'title',
render: title => <a>{title}</a>
},
{
title: 'Start Date',
dataIndex: 'startDate',
key: 'startDate'
},
{
title: 'Description',
dataIndex: 'description',
key: 'description',
render: description => `${description.substring(0, 50)}...`
},
{
title: 'Team',
dataIndex: 'team',
key: 'team'
},
{
title: 'Action',
key: 'action',
render: (text, record, index) => (
<Space size='middle'>
<FontAwesomeIcon icon={faEdit} />
<FontAwesomeIcon icon={faCalendar} />
<FontAwesomeIcon icon={faUserPlus} />
<RemoveProjectButton project={record} updateProjects={updateProjects} />
</Space>
)
}
]
return (
<Table
data-testid='project-table'
columns={columns}
dataSource={projects}
pagination={false}
/>
)
}
and this is my test:
import React from 'react'
import { render, cleanup, fireEvent } from '@testing-library/react'
import { Projects, RemoveProjectButton } from '../Projects'
import useAxios from 'axios-hooks'
jest.mock('axios-hooks')
const TABLE_TEST_ID = 'project-table'
const fakeData = [
{
key: 1,
title: 'Testing Project Alpha',
startDate: '2020-04-18',
description: 'This is just for testing',
team: 'A, B, C'
},
{
key: 2,
title: 'Testing Project Beta',
startDate: '2020-04-19',
description: 'This is just for testing too',
team: 'X, Y, Z'
}
]
describe('projects table', () => {
let projects
beforeEach(() => {
projects = JSON.parse(JSON.stringify(fakeData))
useAxios.mockReturnValue([{
data: projects,
loading: false,
error: null
}])
})
it('removes project when clicking on X button in row', async () => {
const { getByTestId, queryByTestId } = render(<Projects />)
const executeMock = jest.fn()
useAxios.mockReturnValue([{
data: projects,
loading: false,
error: null
}])
.mockReturnValue([{}, executeMock])
.mockReturnValue([{}, executeMock])
expect(getByTestId(TABLE_TEST_ID)).toHaveTextContent('Testing Project Alpha')
await fireEvent.click(getByTestId('project-1'))
expect(queryByTestId('project-1')).toBeNull()
expect(getByTestId(TABLE_TEST_ID)).not.toHaveTextContent('Testing Project Alpha')
})
})
However, I am getting the following error:
TypeError: execute is not a function
16 | )
17 | const removeProject = async (project) => {
> 18 | await execute()
| ^
19 | updateProjects(project)
20 | }
21 |
I understand that the problem is that I am not passing the correct mock for the component RemoveProjectButton. However, I have no idea how I can achieve this because useAxios is being called in different components, and it should have with different returns values. I have also tried using mockImplementationOnce, but it seems the component Projects gets rendered several times before rendering the component RemoveProjectButton, so I feel that I am like guessing the number of times I will have to use mockImplementationOnce.
A: Maybe just use mockImplementation then you can return different value according to the params.
useAxios.mockImplementation((...args) => {
if (match1(args)) {
return result1;
}
if (match2(args)) {
return result2;
}
return result3;
});
A: I took the approach suggested by @Mirone's answer, but I got another issue after the mocking issue was solved, so I will add my complete answer in case somebody else experiences the same:
it('removes project in table when clicking on X', async () => {
const executeMock = jest.fn()
useAxios.mockImplementation((...args) => {
// This mocking was inspired on Mirone's answer
switch (args.length) {
case 1:
return [{
data: projects,
loading: false,
error: null
}]
case 2:
return [{}, executeMock]
default: break
}
})
const { getByTestId, findByTestId } = render(<Projects />)
expect(getByTestId('project-table')).toHaveTextContent('Testing Project Alpha')
fireEvent.click(getByTestId('project-1'))
const table = await findByTestId('project-table')
expect(table).not.toHaveTextContent('Testing Project Alpha')
})
After the mocking issue was solved, I was getting an error:
Warning: An update to Projects inside a test was not wrapped in act(...).
This was solved by adding:
const table = await findByTestId('project-table')
The previous line was waiting until the element with data-testid="project-table" was re-rendered, but I got one more error:
MutationObserver is not a constructor
I found an issue on Github that provided the solution for this. Briefly speaking, the problem is that CRA is not using the latest version of jsdom, so the solution was so install jest-environment-jsdom-sixteen as follows:
yarn add jest-environment-jsdom-sixteen --dev
and also to set it up in package.json:
"scripts": {
...
"test": "react-scripts test --env=jest-environment-jsdom-sixteen",
...
}
I hope my answer helps someone else who might experience the same issues.
| |
doc_23527170
|
It appears me this: The method setLayout(LayoutManager) in the type JFrame is not applicable for the arguments (BorderLayout)
I´m a beginner and I was following a video but this does not work and I already watched different videos, thank you so much for your help.
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BorderLayout {
public static void main(String []args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLayout(new BorderLayout());
frame.setVisible(true);
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
panel1.setBackground(Color.red);
panel2.setBackground(Color.green);
panel3.setBackground(Color.yellow);
panel4.setBackground(Color.magenta);
panel5.setBackground(Color.blue);
panel1.setPreferredSize(new Dimension(100, 100));
panel2.setPreferredSize(new Dimension(100, 100));
panel3.setPreferredSize(new Dimension(100, 100));
panel4.setPreferredSize(new Dimension(100, 100));
panel5.setPreferredSize(new Dimension(100, 100));
frame.add(panel1, BorderLayout.NORTH);
frame.add(panel2, BorderLayout.WEST);
frame.add(panel3, BorderLayout.EAST);
frame.add(panel4, BorderLayout.SOUTH);
frame.add(panel5, BorderLayout.CENTER);
}
}
A: Move frame.setVisible(true); to the end of your method. Swing layouts are lazy, they won't "magically" update by themselves, instead, you need to tell it when you want a container to be updated, using revalidate and repaint to schedule a new layout and pass pass, but, as I've said, the easiest thing to do in your case, is simply setup the window before you make it visible.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.EventQueue;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JPanel panel5 = new JPanel();
panel1.setBackground(Color.red);
panel2.setBackground(Color.green);
panel3.setBackground(Color.yellow);
panel4.setBackground(Color.magenta);
panel5.setBackground(Color.blue);
panel1.setPreferredSize(new Dimension(100, 100));
panel2.setPreferredSize(new Dimension(100, 100));
panel3.setPreferredSize(new Dimension(100, 100));
panel4.setPreferredSize(new Dimension(100, 100));
panel5.setPreferredSize(new Dimension(100, 100));
frame.add(panel1, BorderLayout.NORTH);
frame.add(panel2, BorderLayout.WEST);
frame.add(panel3, BorderLayout.EAST);
frame.add(panel4, BorderLayout.SOUTH);
frame.add(panel5, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
});
}
}
A: That's because the name of your class is the same as BorderLayout layout. Change name of your class and it should work perfectly fine. Never use a keyword or something like that in naming an object/class/method etc.
| |
doc_23527171
|
Function is unused
This is whole working func:
fileprivate func attemptToChangePassword() {
passwordChanger.change(securityToken: securityToken, oldPassword: oldPassword.text ?? "", newPassword: newPassword.text ?? "", onSuccess:{[weak self] in
self?.hideSpinner()
let alertController = UIAlertController(
title: nil,
message: "Your password has been successfully changed.",
preferredStyle: .alert)
let okButton = UIAlertAction(
title: "OK",
style: .default) { [weak self] _ in
self?.dismiss(animated: true)
}
alertController.addAction(okButton)
alertController.preferredAction = okButton
self?.present(alertController, animated: true)
}, onFailure: {[weak self] message in
self?.hideSpinner()
self?.showAlert(message: message) { [weak self] _ in
self?.oldPassword.text = ""
self?.newPassword.text = ""
self?.confirmPassword.text = ""
self?.oldPassword.becomeFirstResponder()
self?.view.backgroundColor = .white
self?.blurView.removeFromSuperview()
self?.cancel.isEnabled = true
}
})
}
This is how I extracted last closure to method:
fileprivate func startOver() -> (UIAlertAction) -> Void {
return { [weak self] _ in
self?.oldPassword.text = ""
self?.newPassword.text = ""
self?.confirmPassword.text = ""
self?.oldPassword.becomeFirstResponder()
self?.view.backgroundColor = .white
self?.blurView.removeFromSuperview()
self?.cancel.isEnabled = true
}
}
If I try this, the error "Function is unused" shows up:
onFailure: { [weak self] message in
self?.hideSpinner()
self?.showAlert(message: message) { [weak self] _ in
self?.startOver()//FUNCTION IS UNUSED
}
})
Edit:
Here is alert method that is used:
fileprivate func showAlert( message: String, okAction: @escaping (UIAlertAction) -> Void) {
let ac = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler:okAction)
ac.addAction(ok)
ac.preferredAction = ok
self.present(ac, animated: true)
}
If I add back alert action button it works:
let okButton = UIAlertAction(
title: "OK",
style: .default,
handler:startOver())
A: You're currently calling that function inside of the action you pass to your showAlert function but then throwing away the action it returns. Instead, you want to pass the action that it returns directly to your showAlert method rather than wrapping it inside another action with the trailing closure syntax:
self?.showAlert(message: message, okAction: self!.startOver())
| |
doc_23527172
|
In C++ marking a method as virtual causes the objects to use more
memory - for every additional virtual method the memory for a pointer
(4 - 8 bytes) more. How does Java deals with this, where all methods
by default are virtual?
A: Your basic assumption is incorrect. The size of the object does not increase with the number of virtual functions.
If the class has ANY virtual functions then it has a single pointer to a vtable for that class. The size of the object won't change beyond that regardless how many virtual functions:
struct s0 {};
struct s1
{
virtual void f1() {}
};
struct s2
{
virtual void f1() {}
virtual void f2() {}
};
struct s3
{
virtual void f1() {}
virtual void f2() {}
virtual void f3() {}
};
int main()
{
std::cout << "s0: " << sizeof(s0) << '\n';
std::cout << "s1: " << sizeof(s1) << '\n';
std::cout << "s2: " << sizeof(s2) << '\n';
std::cout << "s3: " << sizeof(s3) << '\n';
}
RESULTS:
s0: 1
s1: 8
s2: 8
s3: 8
A: Are you sure that objects are using more memory? I would say that you are using more space with the virtual function table but not with each object.
| |
doc_23527173
|
I've organized the content into a series of tables, and I'm attempting to use the page-break-inside and page-break-after CSS attributes to control the printed appearance of the report. The intention is that report items should only be broken across pages if their content is too long to fit on a single page.
Simplified down significantly, the structure of my page is vaguely as follows:
<div class="body-block">
<div class="inner-block">
<div class="report-block">
<div class="report-entry">
<table>
<tr>
<th>Header</th>
</tr>
<tr>
<td>Row</td>
</tr>
<tr>
<td>Row</td>
</tr>
<tr>
<td>Row</td>
</tr>
</table>
</div>
<div class="report-entry">
<table>
<tr>
<th>Header</th>
</tr>
<tr>
<td>Row</td>
</tr>
<tr>
<td>Row</td>
</tr>
<tr>
<td>Row</td>
</tr>
</table>
</div>
</div>
</div>
</div>
The (simplified) CSS for the page looks like this:
.body-block {
display: block;
min-width: 700px;
min-height: 100%;
margin: 0 auto;
}
.inner-block {
width: 700px;
min-height: 100px;
margin: 18px 0 10px 0;
float: left;
}
.report-block {
margin-bottom: 50px;
page-break-after: always;
}
.report-entry table {
width: 100%;
border-collapse: collapse;
border-bottom: 2px solid #333;
page-break-after: auto;
page-break-inside: avoid;
}
.report-entry td, .report-entry th {
page-break-inside: avoid;
page-break-after: avoid;
}
However, browser compatibility is causing me no end of headaches:
*
*Firefox displays everything perfectly and prints out without issue. Unfortunately, Firefox is not allowed by company policy for standard machines.
*Chrome just completely ignores the page-break-inside and page-break-after properties, and inserts page breaks wherever it feels like it.
*IE 11, the company standard browser, does recognize the page-break-inside tag but messes up completely if the content of a table/row/cell spans for more than one page (which happens when people try to copy-paste in entire emails). Whenever it runs across one, it will throw in an extra blank page before the table.
This JSFiddle shows off the issue. A direct link to the printable version is available here, but doesn't seem to work on IE for some reason.
How can I get either Chrome or IE (11) to co-operate with me and handle page breaks properly?
A: To fix the browser differences you should user reser.css or normalize.css
Refer CSS reset - What exactly does it do?
Refer Firefox/IE Padding/Margin Fix
Refer How do I fix CSS padding issues between Firefox & Chrome?
try this fix
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<style type="text/css">
tr {
page-break-inside: initial;
page-break-after: always;
page-break-inside: auto;
}
td {
page-break-inside: initial;
page-break-after: always;
page-break-inside: auto;
}
</style>
try all possible values for page-break-inside: auto|avoid|initial|inherit;
Also try <br> and ::after or ::before
| |
doc_23527174
|
Is there some good way to disable the cache during unit tests? I'm using pytest==3.5.0
Eg. this fails because the old entry is returned from cache:
def test_updating_biography(self):
"""Should update the current newest entry with the data in the JSON."""
response = self.app.put(
"/api/1.0/biography/",
data=json.dumps(
dict(
short="UnitTest Updated newest short",
full="UnitTest Updated newest full",
)
),
content_type="application/json"
)
get_bio = self.app.get("/api/1.0/biography/")
biodata = json.loads(get_bio.get_data().decode())
self.assertEquals(200, response.status_code)
self.assertEquals(200, get_bio.status_code)
> self.assertEquals("UnitTest Updated newest short", biodata["biography"][0]["short"])
E AssertionError: 'UnitTest Updated newest short' != 'UnitTest fourth short'
E - UnitTest Updated newest short
E + UnitTest fourth short
tests/biography/test_biography_views.py:100: AssertionError
I tried for example:
def setUp(self):
app.config["CACHE_TYPE"] = None
app.config["CACHE_REDIS_URL"] = ""
self.app = app.test_client()
And also app.config["CACHE_TYPE"] = "null" and app.config["CACHE_TYPE"] = "", but it is still using the cache in the unit test.
I tried this one, but it's of course outside of app context:
@cache.cached(timeout=0)
def test_updating_biography(self):
A: As mentioned in the comment, sytech's idea works for me since I only test a single app with this redis. Obviously if you use a shared redis for multiple apps, this might not work for you. But for my case, it worked perfectly and can be repeated without issues:
import unittest
from flask_caching import Cache
from app import app, db
class TestBiographyViews(unittest.TestCase):
def setUp(self):
"""Add some test entries to the database, so we can test getting the latest one."""
# Clear redis cache completely
cache = Cache()
cache.init_app(app, config={"CACHE_TYPE": "redis"})
with app.app_context():
cache.clear()
self.app = app.test_client()
The above is all you need. The rest of the test cases can be as normal. Works for me.
| |
doc_23527175
|
So I wanted following to get:
*
*ToggButton Click (IsChecked = true) --> ScrollViewer animates/changes trough Storyboard (StoryBoard1)
*ToggButton Click Again (IsChecked = false) --> ScrollViewer animates/changes back trough Storyboard (StoryBoard2)
Here's my XAML:
<Window x:Class="myProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ignore="http://www.galasoft.ch/ignore"
xmlns:view="clr-namespace:Messenger4u.View"
mc:Ignorable="d ignore">
<Window.Resources>
<ResourceDictionary>
<Storyboard x:Key="Storyboard1" SpeedRatio="3">
<ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)"
Storyboard.TargetName="ScrollViewer">
<EasingThicknessKeyFrame KeyTime="0" Value="0,2,0,0"/>
<EasingThicknessKeyFrame KeyTime="0:0:1" Value="200,2,0,0"/>
</ThicknessAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="Storyboard2" SpeedRatio="3">
<ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)"
Storyboard.TargetName="ScrollViewer">
<EasingThicknessKeyFrame KeyTime="0" Value="200,2,0,0"/>
<EasingThicknessKeyFrame KeyTime="0:0:1" Value="0,2,0,0"/>
</ThicknessAnimationUsingKeyFrames>
</Storyboard>
</ResourceDictionary>
</Window.Resources>
<Grid Background="White">
<Grid.RowDefinitions>
<RowDefiniton/>
<RowDefiniton/>
</Grid.RowDefinitions>
<ToggleButton Width="44" Height="34"
Margin="8, 0, 0, 0"
HorizontalAlignment="Left"
IsChecked="{Binding IsMenuOpen}"
IsEnabled="{Binding IsLoggedIn}">
<ToggleButton.Style>
<Style>
<Setter Property="ToggleButton.Background">
<Setter.Value>
<ImageBrush ImageSource="Skins/Images/btn-top-menu.png"/>
</Setter.Value>
</Setter>
</Style>
</ToggleButton.Style>
<ToggleButton.Template>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border CornerRadius="3" Background="{TemplateBinding Background}">
<ContentPresenter Margin="3"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="Skins/Images/btn-top-menu-hover.png"/>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Trigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource Storyboard1}"/>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard Storyboard="{StaticResource Storyboard2}"/>
</Trigger.ExitActions>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
<ScrollViewer x:Name="ScrollViewer" Grid.Row="1"
Margin="0, 2, 0, 0"
HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Auto">
<Grid>
<ContentControl Content="{Binding CurrentPageViewModel}"/>
</Grid>
</ScrollViewer>
</Grid>
</Window>
A: It's the usual problem with Controltemplate & XAML structure. try below code.:
<Window.Resources>
<ResourceDictionary>
<ScrollViewer x:Key="ScrollViewer"
Margin="0, 2, 0, 0"
HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Auto">
<ContentControl Content="{Binding CurrentPageViewModel}"/>
</ScrollViewer>
<Storyboard x:Key="Storyboard1" SpeedRatio="3" >
<ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)"
Storyboard.Target="{StaticResource ScrollViewer}">
<EasingThicknessKeyFrame KeyTime="0" Value="0,2,0,0"/>
<EasingThicknessKeyFrame KeyTime="0:0:1" Value="200,2,0,0"/>
</ThicknessAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="Storyboard2" SpeedRatio="3">
<ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)"
Storyboard.Target="{StaticResource ScrollViewer}">
<EasingThicknessKeyFrame KeyTime="0" Value="200,2,0,0"/>
<EasingThicknessKeyFrame KeyTime="0:0:1" Value="0,2,0,0"/>
</ThicknessAnimationUsingKeyFrames>
</Storyboard>
</ResourceDictionary>
</Window.Resources>
<Grid Background="White">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition/>
</Grid.RowDefinitions>
<ToggleButton Width="44" Height="34"
Margin="8, 0, 0, 0"
HorizontalAlignment="Left"
IsChecked="{Binding IsMenuOpen}"
IsEnabled="{Binding IsLoggedIn}">
<ToggleButton.Style>
<Style>
<Setter Property="ToggleButton.Background">
<Setter.Value>
<ImageBrush ImageSource="Resources/SOF.gif"/>
</Setter.Value>
</Setter>
</Style>
</ToggleButton.Style>
<ToggleButton.Template>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border CornerRadius="3" Background="{TemplateBinding Background}">
<ContentPresenter Margin="3"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="Resources/SOF.gif"/>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Trigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource Storyboard1}"/>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard Storyboard="{StaticResource Storyboard2}"/>
</Trigger.ExitActions>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
<ContentControl Content="{StaticResource ScrollViewer}" Grid.Row="1"/>
</Grid>
I've defined the ScrollViewer as a Resource and then use
StoryBoard.target property to animate. and it works fine.
A: You can directly give a name for the togglebutton and use it in the Storyboard.
<ToggleButton x:Name="myToggle"
Width="44" Height="34"
Margin="8, 0, 0, 0"
HorizontalAlignment="Left"
IsChecked="{Binding IsMenuOpen}"
IsEnabled="{Binding IsLoggedIn}">
<Storyboard x:Key="Storyboard1" SpeedRatio="3">
<ThicknessAnimationUsingKeyFrames Storyboard.TargetName="myToggle"
Storyboard.TargetProperty="(FrameworkElement.Margin)" Storyboard.TargetName="ScrollViewer">
<EasingThicknessKeyFrame KeyTime="0" Value="0,2,0,0"/>
<EasingThicknessKeyFrame KeyTime="0:0:1" Value="200,2,0,0"/>
</ThicknessAnimationUsingKeyFrames>
</Storyboard>
| |
doc_23527176
|
A
/ \
O M
\ /
B
O = Original commit
A = Commit on Branch 1 (main)
B = Commit on Branch 2
M = Merge Commit
MyFile (Commit = O)
======
line1
line2
line3
MyFile (Commit = A ... only modifies line1)
======
line1 - commit A modification
line2
line3
MyFile (Commit = B ... only modifies line2)
======
line1
line2 - commit B modification
line3
Why does this result in a merge conflict - when these changes are not overlapping?
In stark contrast however, in the very similar scenario - where we modify line3 instead of line2 in commit B... we then DON'T have a merge conflict.
Does anybody have a clear explanation what git is doing to identify the first case as a merge conflict? Neither have overlapping changes.
The best explanation of how git calculates merges was the answer from this post, but it does not help explain my first case's conflict.
A: Summary of answer = "You get a merge conflict if there are no unmodified lines between the changes" - (@Chris Dodd)
More detailed reason why this is the case =
I have rationalised the reason for this logic to myself, and I will try and convey this below (probably could do so more concisely, but here goes) ...
Although it seems the two separate "modified / replaced" lines are not overlapping - actually, due to there being no unmodified lines seperating these "new lines", the order Git should place them in is in fact indeterminable (ambiguous). The ambiguity comes from the second possible intention Git considers (that the OP (I) did not) which reveals an overlap. Had there been a seperating unmodified line to clearly mark a sepration between the two changes there would not be any such overlap...
Possible Intention 1
(the "replacement of lines" intention - the OP (I) thought this was the only way Git could interpret the commits / merge)
The two new lines (one per commit) are intended as replacement lines for their respective deleted lines. This intention does indeed have a determinable / unambiguous merge outcome - so considering this intention - there would be no conflict ...
The DIFFs to reflect this intention ...
MyFile - Commit A (DIFF from base)
---------------------------------
- item1
+ new line A (item1 replacement)
item2
MyFile - Commit B (DIFF from base)
---------------------------------
item1
- item2
+ new line B (item2 replacement)
(The above could seem possibly not conflicting)
Possible Intention 2 (other intention)
(the "addition and deletion" seperately - i.e. no intended direct replacements)
The commitA intends for the "new line" simply to be added after the line "item1" - and then the line "item1" happens to be deleted (ie the "new line" is not intended as line "item1" replacement). The commitB intends for it's "new line" to be added before the line "item2" - and then the line "item2" deleted. This intention results in the two (different) "new lines" (one per commit) sitting side by side ... Git does not know which to place first, thus Git see's a conflict.
The two DIFFs (below) although Commit B's "new line" placement is shuffled to above its "item2" deletion - it is still the equivilant DIFF (as presented before (above in Intention 1), but perhaps now better shows where the conflict comes from. We can now clearly see the new lines overlap, thus order is ambiguous.
MyFile - Commit A (DIFF from base)
---------------------------------
- item1
+ new line A (placed after item1)
item2
MyFile - Commit B (DIFF from base)
---------------------------------
item1
+ new line B (placed before item2)
- item2
TAKEAWAYS -
(1) Just because a line addition (+) follows a line deletion (-)... Git does not assume they are intimately connected (bound as a replacement pair). They are not. Their love means nothing. Is not real. Just a figment of the users imagination.
(2) To reinforce the above - and to help further this understanding, I affirm the following law (I just created, but pretty sure is valid - please correct me if I'm wrong).
MY LAW:
DIFFs can be shuffled in the following ways (and still retain the same meaning, validity, equivilance)
First, some definitions:
"An island of changes": A group of (+) or (-) line changes, which are not seperated by other unmodified lines.
The Law:
Within a DIFF, within an island of changes - we can shuffle the changes in any order - so long as the (+) changes are presented in the correct / same order.
Shuffling the DIFF as such will retain the exact same meaning and continue to be a valid and equivilant DIFF.
EXAMPLES of One DIFF - with equivilent but different orders
This order reflects the order in which I actually made some hyperthetical changes
...
item1
+ new line A <- I
- item2 <- S
+ new line B <- L
- item3 <- A
+ new item C <- N
+ new item D <- D
item4
This is the order Git seems to present the changes - it groups the (-) changes first and then the (+) changes second ...
item1
- item2 <- I
- item3 <- S
+ new line A <- L
+ new line B <- A
+ new item C <- N
+ new item D <- D
item4
This order groups the (+) first and then the (-) second ...
item1
+ new line A <- I
+ new line B <- S
+ new item C <- L
+ new item D <- A
- item2 <- N
- item3 <- D
item4
This order mixes (-) into (+) - but preserves order of each type ...
item1
+ new line A <- I
+ new line B <- S
- item2 <- L
+ new item C <- A
- item3 <- N
+ new item D <- D
item4
This order mixes (-) into (+) AND furthermore the order of (-) is different, but this is still valid and equivilant, as it is irrelevant which order lines disappear, so long as they disappear, however the order of (+) changes MUST be preserved (as this is still very relevant) ...
item1
+ new line A <- I
+ new line B <- S
- item3 <- L
+ new item C <- A
- item2 <- N
+ new item D <- D
item4
| |
doc_23527177
|
My test:
@Test
public void testRetrieveAllOrders() {
// Given
User user = new User("John","Smith");
Cart cart1 = new Cart(user);
Cart cart2 = new Cart(user);
Cart cart3 = new Cart(user);
Order order1 = new Order(cart1, OrderStatus.CREATED);
Order order2 = new Order(cart2, OrderStatus.CREATED);
Order order3 = new Order(cart3, OrderStatus.CREATED);
orderRepository.save(order1);
orderRepository.save(order2);
orderRepository.save(order3);
// When
List<Order> savedOrders = (List<Order>) orderRepository.findAll();
// Then
assertEquals(3,savedOrders.size());
orderRepository.deleteById(order1.getId());
orderRepository.deleteById(order2.getId());
orderRepository.deleteById(order3.getId());
}
User Relation:
@OneToMany(targetEntity = Cart.class,
mappedBy = "user",
cascade = CascadeType.ALL,
fetch = FetchType.LAZY
)
private List<Cart> carts = new ArrayList<>();
Cart relation:
@ManyToOne(cascade = {CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REFRESH})
@NotNull
@JoinColumn(name = "USER_ID")
private User user;
Exception:
detached entity passed to persist: com.project.ecommercee.domain.User; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.ecommercee.domain.User
org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.project.ecommercee.domain.User; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.ecommercee.domain.User
| |
doc_23527178
|
A: You can use following code snippet to get your desired results.
<?php
$terms = get_terms( 'category', array(
'orderby' => 'count',
'hide_empty' => 0,
) );
foreach($terms as $term){
echo $term->name;
echo $term->description;
}
?>
You will replace category with your own taxonomy name and you can use your data as you want, for further reading visit codes page
Hope that makes sense by now
| |
doc_23527179
|
$scope.colors=['color1','color2','color3']
My colors array length is 2. I want to bind class in my ng-repeat list colors array 0 to 2 length. When it reach max of it's length then reset it to 0 and again repeat. I can implement it other place like php,jquery etc but i can't implement it on angular view.
<!-- single cat -->
<div ng-repeat="cat in contacts|filter:search.name">
<div class="item item-divider">
{{cat.name}} <span class="badge badge-positive">{{cat.data.length}}</span>
</div>
<!-- cat contact single -->
<a class="item" href="#" ng-repeat="p in cat.data">
<h2 class="letter colors[customerCounterIndex]">{{p.name.charAt(0)}}</h2>
<span class="name">{{p.name}}</span>
<p>{{p.phone}}</p>
</a>
<!-- end cat contact single -->
</div>
<!-- end single cat -->
A: Try this, <h2 class="letter" ng-class="colors[$index % colors.length]">
| |
doc_23527180
|
What I am currently doing is this:
std::vector<std::vector<std::string>> obj;
for(auto i:obj) {
for(auto j:i)
j.~basic_string();
i.clear();
}
But this of course only clears the objects and does not release the memory they hold.
Does std::vector use any memory for a base instance of itself? And how can I guarantee that this memory is released so it can be used for something else, or will this happen automatically?
A: Your code is broken. You are destroying objects while they are still owned by a container. It's not clear what it is you think you need to do, but there shouldn't be anything you need to do. These containers own the objects they contain, and when the container is destroyed, so is everything in it.
A: If your containers contain pointers, then you're responsible for dealing with their lifetimes. Otherwise, you're not.
You are currently invoking undefined behaviour. The containers involved are responsible for their own memory management - they will destroy their own contents, you are causing the destructor to be run twice (with undefined consequences).
As general rules:
*
*You only need to call destructors explicitly if you used placement new to create those objects.
*You only need to call delete/free if you called new/malloc and you didn't pass the result of new/malloc to a type designed to automatically manage the lifetime of those allocations for you.
*These circumstances should be extremely rare within any program you write.
| |
doc_23527181
|
select
CASE
WHEN Count(*) > 1
THEN 'Archiving task was executed succesfully!'
ELSE 'Archiving task was not executed succesfully for day: ' || Days
END CASE
from
(select substr(table_name,12,8) as Days from user_tables
where table_name like 'CDR_DETAIL_%' AND SubStr(table_name,12,8) IN ( SELECT * FROM tmp_archive_process_ict )
OR SubStr(table_name,12,8) IS null
order by 1 asc )
where rownum <= 7
GROUP BY Days
;
That returns the following result in sql tools:
CASE
Archiving task was not executed succesfully for day: 20130819
Archiving task was executed succesfully!
Archiving task was not executed succesfully for day: 20130821
Archiving task was not executed succesfully for day: 20130820
Using sqlplus in a shell, i am trying to return the result from the sql previously shown, into a file:
Part of unix shell:
#Make oracle conneciton
-oracle connection sqlplus
SET PAGESIZE 0;
SET ECHO OFF;
SET SPACE 0;
SET FEEDBACK OFF;
SET HEADING OFF;
SPOOL /bmd/mail_check.txt
select
CASE
WHEN Count(*) > 1
THEN 'Archiving task was executed succesfully!'
ELSE 'Archiving task was not executed succesfully for day: ' || Days
END CASE
from
(select substr(table_name,12,8) as Days from user_tables
where table_name like 'CDR_DETAIL_%' AND SubStr(table_name,12,8) IN ( SELECT * FROM tmp_archive_process_ict )
OR SubStr(table_name,12,8) IS null
order by 1 asc )
where rownum <= 7
GROUP BY Days
;
SPOOL OFF;
EXIT;
EOF
The script works, it generates the file but when i check the file ( cat /bmd/mail_check.txt ) it shows me just:
Archiving task was executed succesfully!
I don't understand why it doesn't show me the other results from the sql select into the file specified.:
Archiving task was not executed succesfully for day: 20130819
Archiving task was not executed succesfully for day: 20130821
Archiving task was not executed succesfully for day: 20130820
What i am doing wrong?
Thank you in advance.
Best regards,
| |
doc_23527182
|
int countEmptyLines(String s) {
int result=0;
Pattern regex = Pattern.compile("(?m)^\\s*$");
Matcher testMatcher = regex.matcher(s);
while (testMatcher.find())
{
result++;
}
return result;}
What am I doing wrong or is there a better way to do it?
A: Try this:
final BufferedReader br = new BufferedReader(new StringReader("hello\n\nworld\n"));
String line;
int empty = 0;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()) {
empty++;
}
}
System.out.println(empty);
A: I found a way to fix my own regex while I was at lunch:
Pattern regex = Pattern.compile("(?m)^\\s*?$");
The '?' makes the \s* reluctant, meaning it will somehow not match the character that '$' will match.
A: \s matches any whitespace, which is either a space, a tab or a carriage return/linefeed.
The easiest way to do this is to count chains of successive EOL characters. I write EOL, because you need to determine which character denotes the end of line in your file. While under Windows, an end of line amounts to a Carriage Return and a Linefeed character. Under Unix, this is different, so for a file written under Unix your programm will have to be adjusted.
Then, count every the successive number of the end of line character(s) and each time add this number minus 1 to a count. At the end, you will have the empty line count.
| |
doc_23527183
|
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
I am using version 1.5.3.RELEASE of Spring Boot. Here's my swagger config file:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket swagger() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
Here's my WebSecurityConfig.java:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**");
}
When I do a get from the endpoint http://localhost:8080/v2/api-docs I get my JSON back:
{
"swagger": "2.0",
"info": {
"description": "Api Documentation",
"version": "1.0",
"title": "Api Documentation",
"termsOfService": "urn:tos",
"contact": {},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0"
}
},
"host": "localhost:8080",
"basePath": "/",
//ETC
}
But when I try to access the UI at localhost:8080/swagger-ui.html I get a blank page that looks like this:
If I click on the page, I get promoted with this
What am I doing wrong? Is this some sort of spring security issue?
A: You can suggest API description path to Swagger in application config, using springfox.documentation.swagger.v2.path property, e.g.
springfox.documentation.swagger.v2.path: /rest/docs in application.yml.
I've posted an example on github.
A: if You use Version - V3 || io.springfox >= 3.0.0
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
Java code
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("Your Controller package name"))
.paths(PathSelectors.any()).build();
}
}
V3 browser URL -> http://localhost:8080/swagger-ui/#/
Run (Must need) : Mvn clean
A: Its very likely spring-security is not allowing/preventing your endpoints to be discovered. Try changing your ant matchers to the following and see if that helps. The security/ui configuration endpoints were incorrect.
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(
"/v2/api-docs",
"/swagger-resources/configuration/ui",
"/swagger-resources",
"/swagger-resources/configuration/security",
"/swagger-ui.html",
"/webjars/**");
}
A: change the swagger version to 2.9.2 it will work.
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
| |
doc_23527184
|
But, for some odd reason, i get a error in the debugging console of "$ is not defined".
My code is as follows:
<script>
$LAB.script("http://use.typekit.com/blah.js").script("/assets/js/libs/jquery-1.5.1.min.js").script("/assets/js/libs/basic-jquery-slider.min.js").wait().script("/assets/js/libs/modernizr-1.7.min.js").script("/assets/js/libs/jquery.watermarkinput.js").wait().script("/assets/js/libs/jquery-ui-1.8.14.custom.min.js").wait().script("/assets/js/effects.js").wait(function(){});
And in my effects.js i have.
try{Typekit.load();}catch(e){}
$('#banner').bjqs({
'width' : 980,
'height' : 212,
'showMarkers' : false,
'showControls' : false,
'centerMarkers' : false
});
Everything works, but i get the aforementioned error. I don't understand why, the jquery object should be there (and must be as everything works) so why the error?
Any ideas? I'm sure i'm using labjs correctly but i think this error is upsetting IE7 :(
I should probably be adding a $(document).ready round the latter code? but that seems to upset labjs.
Thanks for any help in advance!
A: Try this:
<script>
$LAB
.script("http://use.typekit.com/blah.js")
.script("/assets/js/libs/jquery-1.5.1.min.js").wait() // <---- ADD THIS .wait()
.script("/assets/js/libs/basic-jquery-slider.min.js").wait()
.script("/assets/js/libs/modernizr-1.7.min.js")
.script("/assets/js/libs/jquery.watermarkinput.js").wait()
.script("/assets/js/libs/jquery-ui-1.8.14.custom.min.js").wait()
.script("/assets/js/effects.js").wait(function(){});
</script>
Some other notes:
*
*Remove that final empty/noop .wait() function, it isn't needed (anymore).
*modernizr shouldn't be loaded by LABjs... you should load that per the docs which IIRC say that it should be in a normal <script> tag at the top of your document.
*My guess is some of the .wait()'s you have in this chain are unnecessary. For instance, my guess is there's no need for them after "jquery-slider" and "jquery-watermark" script() calls, as I bet they are not dependent on each other and thus can run in any ASAP order with respect to each other, as long as they have made sure to run after jQuery finishes (which is why i made the comment in the snippet to add in a .wait() call!)
A: I've just realised that hidden in an include in the footer is another call to my effects.js file. But this is in normal script tags. That would explain why it's running with an error then working as it's being called twice, once inside labjs and once not. What an idiot :( Thanks for trying though everyone! And sorry!
| |
doc_23527185
|
var request = require('request');
request('http://www.google.com', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
However, I also a route to serve in my node app and the response I get is out of scope in the route. I want to add the values from my request into view using EJS but with EJS i have to define the values to be used by the file in the .render() and getting those values just seems to not be possible.
My app.js looks like this
const express = require('express');
var request = require('request');
const path = require('path');
const chalk = require('chalk');
const app = express();
const port = process.env.PORT || 3000; // Port number
// var url = 'http://api.openweathermap.org/data/2.5/forecast?id=1253573&APPID=56e2043a628c776ab619d9d393c2b568&units=metric'; // API Request URL
app.use(express.static(path.join(__dirname, '/public/')));
app.use('/css', express.static(path.join(__dirname, '/node_modules/bootstrap/dist/css')));
app.use('/js', express.static(path.join(__dirname, '/node_modules/bootstrap/dist/js')));
app.use('/js', express.static(path.join(__dirname, '/node_modules/jquery/dist')));
app.set('views', './views');
app.set('view engine', 'ejs');
function apiCall(callback) {
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
var result = JSON.parse(body);
// console.log(result);
return callback(result, false);
} else {
return callback(null, error);;
}
});
}
app.get('/', (req, res) => {
const url = 'http://api.openweathermap.org/data/2.5/forecast?id=1253573&APPID=56e2043a628c776ab619d9d393c2b568&units=metric'; // API Request URL
const x = request(url, function (error, response, body){
const result = JSON.parse(x.body);
console.log(result);
});
res.render('index',{
//temp: data.list[0].main.temp,
place : result.city['name'] // || data.city['name'],
//wind: data.list[0].wind.speed,
//desc: data.list[0].weather[0].description,
}
);
});
app.listen(port, () => {
console.log(`listening on port ${chalk.green(port)}`);
});
any help would be really appreciated!
A:
const request = require('request');
const express = require('express');
const path = require('path');
const chalk = require('chalk');
const app = express();
const port = process.env.PORT || 3000; // Port number
app.use(express.static(path.join(__dirname, '/public/')));
app.use('/css', express.static(path.join(__dirname, '/node_modules/bootstrap/dist/css')));
app.use('/js', express.static(path.join(__dirname, '/node_modules/bootstrap/dist/js')));
app.use('/js', express.static(path.join(__dirname, '/node_modules/jquery/dist')));
app.set('views', './views');
app.set('view engine', 'ejs');
function apiCall(url, callback) {
request(url, function(error, response, body) {
if (!error && response.statusCode == 200) {
var result = JSON.parse(body);
// console.log(result);
return callback(null, result);
} else {
return callback(error, null);;
}
});
}
app.get('/', (req, res) => {
const url = 'http://api.openweathermap.org/data/2.5/forecast?id=1253573&APPID=56e2043a628c776ab619d9d393c2b568&units=metric'; // API Request URL
apiCall(url, (err, body) => {
if(err) {
// handle error
return;
}
res.render('index', {
//temp: data.list[0].main.temp,
place: body.city['name'] // || data.city['name'],
//wind: data.list[0].wind.speed,
//desc: data.list[0].weather[0].description,
});
});
})
app.listen(port, () => {
console.log(`listening on port ${chalk.green(port)}`);
});
if you are trying to render after the api call is finished.
| |
doc_23527186
|
const [expanded, setExpanded] = React.useState(false);
var searchHistory = [];
const _retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('searchHistory');
if (value !== null) {
searchHistory = JSON.parse(value);
}
}
catch (error) {
console.log("_retrieveData failed!! " + error);
}
}
_retrieveData();
const expandedSearch = () => {
if(expanded) {
return (
<View style={styles.container}>
<FlatList
data={searchHistory}
renderItem={renderHistoryItem}
/>
</View>
);
}
else {
return null;
}
}
...
{expandedSearch()}
I have a toggled View (expandedSearch) that displays a FlatList of search history items. For some reason the searchHistory array is blank when the FlatList gets rendered, even when the expandedSearch view is toggled...which should re-render the Flatlist?
A: For some reason the searchHistory array is blank when the FlatList gets rendered
=> because of your definition of var searchHistory = [];
AsyncStorage.getItem('searchHistory'); is an await function, so it takes time to get the response.
Your component will render like that:
Init searchHistory with empty array, then render FlatList, then fill searchHistory with response from AsyncStorage. Because searchHistory is a variable, not a state, so that when its value changes, component will not rerender.
=> Solution:
Change var searchHistory = []; => const [searchHistory,setSearchHistory] = useState([])
and change searchHistory = JSON.parse(value); => setSearchHistory(JSON.parse(value))
A: you need to do this changes
replace var searchHistory = []; with [searchHistory, setSearchHistory] = React.useState([]);
replace searchHistory = JSON.parse(value); with setSearchHistory(JSON.parse(value));
and this the Explanition
you use promise async/await to get data
so you need to rerender component after data is ready to notifiy flatlist with data,
you can do this by call setSearchHistory and this will rerender your component
| |
doc_23527187
|
<iframe src="https://player.vimeo.com/video/220535146?controls=0&hd=1&autoplay=1&player_id=banneroneVid&api=1" width="640" height="360" frameborder="0" title="reebok_short_loop" webkitallowfullscreen mozallowfullscreen allowfullscreen frameborder="0" id="banneroneVid" ></iframe>
to
<iframe src="https://player.vimeo.com/video/220535146?background=1" width="640" height="360" frameborder="0" title="reebok_short_loop" webkitallowfullscreen mozallowfullscreen allowfullscreen frameborder="0" id="banneroneVid" ></iframe>
Ideally i would like this to happen as the page is loading.
thank you
A: Use media queries to load the iframe you want depending on the device.
Something like this: (e.g. if you're using bootstrap)
<!-- bigger screens -->
<div class="hidden-xs col-sm-12 col-md-12 col-lg-12">
<iframe src="https://player.vimeo.com/video/220535146?controls=0&hd=1&autoplay=1&player_id=banneroneVid&api=1" width="640" height="360" frameborder="0" title="reebok_short_loop" webkitallowfullscreen mozallowfullscreen allowfullscreen frameborder="0" id="banneroneVid" ></iframe>
</div>
<!-- mobile devices with max-width: 768px -->
<div class="col-xs-12 hidden-sm hidden-md hidden-lg">
<iframe src="https://player.vimeo.com/video/220535146?background=1" width="640" height="360" frameborder="0" title="reebok_short_loop" webkitallowfullscreen mozallowfullscreen allowfullscreen frameborder="0" id="banneroneVid" ></iframe>
</div>
| |
doc_23527188
|
I found out that they are not implemented in mono yet. I tried this reference design from Microsoft:
http://referencesource.microsoft.com/#System.Core/System/Security/Cryptography/ECDsaCng.cs,27778745e2b25dfa
But a lot of libraries are missing afterwards, and it gets a never ending story. (I added a lot bet then it says that some stuff is already implemented in the namespace)
Do you have any ideas what I could try else?
Should I just compile it with MS and then try it with Wine?
| |
doc_23527189
|
Every service works fine and there are no problems. There is a problem only with LogsService. LogsService is implemented the same way as other services such as StaticPageService.
In order to log in a user must use method "onLoginClicked" from LoginViewModel class.
LoginViewModel class:
package com.flyingdynamite.jvmbackend.views.login
import com.flyingdynamite.jvmbackend.data.constants.LogCategory
import com.flyingdynamite.jvmbackend.extensions.isNotNull
import com.flyingdynamite.jvmbackend.security.hash.Hash
import com.flyingdynamite.jvmbackend.service.AdminAuthorizationService
import com.flyingdynamite.jvmbackend.service.LogsService
import com.flyingdynamite.jvmbackend.service.UserModelService
import com.flyingdynamite.jvmbackend.util.SystemInformation
import com.flyingdynamite.jvmbackend.util.base.validation.Argon2PasswordHash
import com.flyingdynamite.jvmbackend.util.generator.ApiAccessCredentialsGenerator
import com.flyingdynamite.jvmbackend.util.generator.TextIdGenerator
import com.flyingdynamite.jvmbackend.views.AdminPanelRoute
import com.flyingdynamite.jvmbackend.views.BaseViewModel
import com.flyingdynamite.jvmbackend.views.dashboard.DashboardView
import kotlinx.coroutines.*
import org.apache.commons.lang3.RandomStringUtils
import org.apache.commons.lang3.time.StopWatch
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Component
import org.springframework.util.unit.DataSize
import java.time.LocalDateTime
import java.time.ZoneId
import java.util.*
import java.util.concurrent.TimeUnit
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
open class LoginViewModel : BaseViewModel() {
private val TAG = "LoginViewModel"
@Autowired(required = true)
private lateinit var logsService: LogsService
@Autowired(required = true)
private lateinit var userModelService: UserModelService
@Autowired(required = true)
private lateinit var adminAuthorizationService: AdminAuthorizationService
private var loginJob: Job? = null
private var developerTasksJob: Job? = null
init {
viewModelScope.launch {
setPageTitle("Login")
}
}
override fun onCleared() {
loginJob?.cancel("onCleared")
developerTasksJob?.cancel("onCleared")
}
// @PostConstruct
private fun runScheduledDeveloperTask() {
logger.warn("runScheduledDeveloperTask")
if (productionMode) {
return
}
Timer(TAG).schedule(object : TimerTask() {
override fun run() {
logger.warn("runDeveloperComputationTask")
runDeveloperComputationTask()
}
}, Date.from(LocalDateTime.now().plusHours(6).atZone(ZoneId.systemDefault()).toInstant()))
}
fun onLoginClicked(login: String?, password: String?) {
if (loginJob != null) {
return
}
loginJob = computationViewModelScope.launch {
logsService.enqueue(TAG, LogCategory.INFO, "onLoginClicked / login _> ${login} / password _> ${password}")
println("$TAG -> onLoginClicked / login _> ${login} / password _> ${password}")
setIsLoading(true)
setErrorText(null)
val inputValuesErrorText = inputValuesErrorText(login, password)
println("$TAG -> onLoginClicked / inputValuesErrorText _> ${inputValuesErrorText} / isEmpty _> ${inputValuesErrorText.isEmpty()}")
val authorized = adminAuthorizationService.isAuthorized(login!!, password!!)
val resultError = if (inputValuesErrorText.isNotNull()) {
inputValuesErrorText
} else {
if (authorized) null else localizedTexts.getOrEmpty("wrong_credentials")
}
println("$TAG -> onLoginClicked / resultError _> ${resultError}")
setErrorText(resultError)
delay(100)
setIsLoading(false)
setNavigateTo(
if (authorized) Triple(
DashboardView::class.java,
AdminPanelRoute.DASHBOARD,
userModelService.getUserByUsernameOrThrow(login)
) else null
)
loginJob = null
// setNavigateTo(null)
}
}
userModelService and adminAuthorizationService have no issues.
LogsService class:
package com.flyingdynamite.jvmbackend.service
import com.flyingdynamite.jvmbackend.data.constants.LogCategory
import com.flyingdynamite.jvmbackend.data.model.LogItem
import com.flyingdynamite.jvmbackend.repository.jpa.LogsJpaRepository
import com.flyingdynamite.jvmbackend.service.exception.NotFoundException
import com.flyingdynamite.jvmbackend.util.AppInfo
import com.flyingdynamite.jvmbackend.util.LogUtils
import com.vaadin.flow.server.WebBrowser
import kotlinx.coroutines.*
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.config.ConfigurableBeanFactory
import org.springframework.context.annotation.Scope
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.Duration
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.util.*
import java.util.concurrent.TimeUnit
import javax.persistence.EntityManager
import javax.persistence.EntityManagerFactory
import javax.persistence.PersistenceContext
import javax.persistence.criteria.CriteriaBuilder
import javax.persistence.criteria.Predicate
import java.util.concurrent.ConcurrentLinkedQueue
@Service
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
open class LogsService : BaseService() {
private val TAG = "LogService"
@Autowired(required = true)
private lateinit var appInfo: AppInfo
@Autowired(required = true)
private lateinit var logRepository: LogsJpaRepository
@Autowired(required = true)
@PersistenceContext
private lateinit var entityManager: EntityManager
@Autowired(required = true)
private lateinit var entityManagerFactory: EntityManagerFactory
private val queue: ConcurrentLinkedQueue<LogItem> = ConcurrentLinkedQueue<LogItem>()
private val cmdLog: Logger by lazy {
LoggerFactory.getLogger(this::class.java)
}
// private val queue: ConcurrentLinkedQueue<LogItem> by lazy {
// ConcurrentLinkedQueue<LogItem>()
// }
private var deleteOlderDays: Int = 30
private var insertMinLogItemsCount: Int = 100
private var insertMaxSecondsDifference: Int = 5
private var isActive: Boolean = true
private var queueJob: Job? = null
private val terminatingMessage: String = "TERMINATING !"
private var displayInCMD: Boolean = true
@Synchronized
fun enableDisplayInCMD() {
displayInCMD = true
if (isActive) {
startQueueThreadIfPossible()
}
}
@Synchronized
fun disableDisplayInCMD() {
displayInCMD = false
if (isActive) {
startQueueThreadIfPossible()
}
}
@Synchronized
fun activate() {
if (displayInCMD) {
cmdLog.trace("activating _ !")
}
isActive = true
startQueueThreadIfPossible()
}
@Synchronized
fun deactivate() {
if (displayInCMD) {
cmdLog.warn("DEACTIVATED _ ! ")
}
onCleared()
}
@Synchronized
fun onCleared() {
isActive = false
queueJob?.cancel("onCleared")
queueJob = serviceScope.launch {
delay(TimeUnit.SECONDS.toMillis(2))
if (displayInCMD) {
cmdLog.warn("inserting queue all remaining items -> ${queue.size} ")
}
insertList(queue.toList())
queue.clear()
queueJob = null
}
}
}
BaseService class:
package com.flyingdynamite.jvmbackend.service
import com.flyingdynamite.jvmbackend.extensions.FD_CPU_INTENSIVE_LIMITLESS
import com.flyingdynamite.jvmbackend.extensions.FD_IO_LIMITLESS
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
open class BaseService() {
protected val serviceScope:CoroutineScope = CoroutineScope(Dispatchers.FD_IO_LIMITLESS)
protected val serviceComputationScope: CoroutineScope = CoroutineScope(Dispatchers.FD_CPU_INTENSIVE_LIMITLESS)
protected fun onException(e: Exception) {
println("[Exception] -> ${e.message}")
e.printStackTrace()
}
}
When user executes onLoginClicked this error occurs:
Exception in thread "pool-2-thread-1" java.lang.NullPointerException
at com.flyingdynamite.jvmbackend.service.LogsService.enqueue(LogsService.kt:171)
at com.flyingdynamite.jvmbackend.service.LogsService.enqueue(LogsService.kt:162)
at com.flyingdynamite.jvmbackend.views.login.LoginViewModel$onLoginClicked$1.invokeSuspend(LoginViewModel.kt:81)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
LogsService.kt:171 -> queue.offer(log) in method enqueue from LogsService class.
If I change the code and execute for example something with serviceScope variable the same error occurs. Then serviceScope is null. Every variable inside LogsService is null when I am trying to use it.
Please help mi with this. Where is the mistake ?
A: Resolved !
Issue was in the logs but only when logging.level.root=DEBUG was set in application.properties
After long search this was somewhere in the logs:
cannot get proxied via CGLIB: Calls to this method will NOT be routed to the >target instance and might lead to NPEs against uninitialized fields in the >proxy instance.
After adding "open" to every method of LogsService class - log entry is not displaying anymore. Seems it is fixed. Not getting any NPE anymore.
| |
doc_23527190
|
list1 = "A", "B", "C"
list2 = "1", "2", "3"
list3 = "Dog"
...
then I get a list with
newList = "A1Dog", "A2Dog", "A3Dog", "B1Dog", "B2Dog", "B3Dog", "C1Dog",
"C2Dog", "C3Dog"
Is there a way to do this with LINQ or is there a better way to do it?
A: Yes, you can simply use multiple from clauses:
var result =
from x in list1
from y in list2
from z in list3
select x+y+z;
In the csharp interactive shell, this gives:
csharp> var list1 = new string[] {"A", "B", "C"};
csharp> var list2 = new string[] {"1", "2", "3"};
csharp> var list3 = new string[] {"Dog"};
csharp> var result =
> from x in list1
> from y in list2
> from z in list3
> select x+y+z;
csharp> result
{ "A1Dog", "A2Dog", "A3Dog", "B1Dog", "B2Dog", "B3Dog", "C1Dog", "C2Dog", "C3Dog" }
| |
doc_23527191
|
My first instinct would be to split it into 3 components:
*
*the nav-bar on top
*simple div containing some text
and for the bottom I was stuck. After searching I opted for a svg path component and combined all 3 in a parent component.
Any other components will be rendered below the curve.
So far it works. But I am curious if there are other, maybe better, solutions to this (which I am sure there are).
Thanks in advance
A: Another way to achieve this would be to add an ::after element to the navbar with some border-radius to make the curve. Here is an example:
#navbar {
position: relative;
background-color: lightblue;
padding: 30px;
}
#navbar::after {
content: "";
position: absolute;
height: 30px;
width: 100%;
background-color: lightblue;
bottom: 0;
left: 0;
transform: translateY(50%);
border-radius: 0 0 100% 100%;
}
<div id="navbar">
Website
</div>
| |
doc_23527192
|
species1 <- lmer(respiration ~ treatment + (1+time|litterbag_ID))
where respiration is the response variable and there are two levels to the dependent variable (treatment). I have also included the random effect to account for repeated measures made over six time points.
Each of the four species has a model like this, however the respiration data is distributed slightly different for each species. My question is, can I apply different models to different species? For example, would I be correct in using the above model for species 1, whilst using the below GLMM for another species, if I find that it improves model fit using qqplots and AIC values?
species2 <- glmer(respiration ~ treatment + (1+time|litterbag_ID), family = (gaussian(link = "log"))
| |
doc_23527193
|
I`ve tried:
DebugKit::write('log','got here');
..but it errors out with a 500.
...btw
CakeLog::write('debug', 'Got here');
works just fine.
I feel kind of dubm asking this, but I can`t find any references.
Appreciate some wisdom here.
Shaun
A: You can use CakeLog::write('debug', 'Got here');
and DebugKit will display it in Log tab.
Worked fine for me on CakePHP 2.10
| |
doc_23527194
|
{
"0": {
"name": "Chunk",
"type": "magic",
"item": "Chestplate",
"item_min_lvl": "70",
"id": {
"health": "0.3",
"spell": "24%",
"life": "0.1",
"xp": "24%",
"loot": "22%"
},
"def": "67"
},
"1": {
"name": "Thor",
"type": "normal",
"item": "Shoe",
"item_min_lvl": "12",
"id": {
"xp": "24%"
},
"def": "12"
},
"2": {
"name": "Clipper",
"type": "normal",
"item": "Sword",
"item_min_lvl": "51",
"id": {
"health": "1",
"life": "0.12",
"xp": "4%"
},
"min_dam": "11",
"max_dam": "7"
}
}
Here is my code:
java.lang.reflect.Type type = new TypeToken<ArrayList<Map<String, Object>>>(){}.getType();
ArrayList<Map<String, Object>> list = gson.fromJson(json, type);//Error here
for(Map<String, Object> m : list)
{
//blah
}
It returns this error Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
Can anyone help me to solve this error? I am new to JSON and GSON. Please note, some of the the "items" aren't the same so I have to use TypeToken.
A: You json does not include arrays (with syntax []) but objects (with syntax {}).
You probably need to use new TypeToken<Map<String, <Map<String, Object>>>>(){}.getType();
| |
doc_23527195
|
im trying to format week and day hours in fullCalendar, but nothing works.
$scope.initCalendar = function() {
/* config object */
$scope.uiConfig = {
calendar: {
height: '450',
editable: false,
header: {
left: 'agendaWeek',
center: 'title',
right: false
},
slotLabelFormat:"HH:mm",
axisFormat: 'h:mm a',
timeFormat: 'hh:mm a',
minTime: '00:00',
maxTime: '23:00',
eventSources: [$scope.events],
titleFormat: 'MMM',
columnFormat: 'MMM',
eventClick: function(event, jsEvent, view) {
$scope.title = (event.title);
$scope.note = (event.note);
$scope.eventDate = (event.date);
$scope.userInfo = (event.displayname);
$scope.url_code = (event.url_code);
$('#event-modal').modal({
show: true
});
var index = $scope.events.indexOf(event);
$scope.remove = function(index){
$calendar.fullCalendar('removeEvents', function (ev) {
return (ev._id == event._id);
});
};
$scope.isDone = function () {
event.backgroundColor = 'green';
$calendar.fullCalendar( 'rerenderEvents' );
};
$calendar.fullCalendar('updateEvent', event);
}
}
}
};
this is how it look like:
2017-07-16T06:00:00:2017-07-16T06:00:002017-07-16T06:00:00
tried, slot, axis, timeformat, still no success.
trying to make it from 6am to 11pm
thank you!
| |
doc_23527196
|
How to: Host WCF in a Windows Service Using TCP
If you follow the example through and place the Consumer application within the same solution then it runs successfully - even if the service is turned off !
If the service is switched on and the consumer application is published to say a different network drive then it will not run because the WCF is not listening.
The following piece of code in the walk-through is the culprit:
protected override void OnStart(string[] args)
{
if (myServiceHost != null)
{
myServiceHost.Close();
}
myServiceHost = new ServiceHost(typeof(Service1));
myServiceHost.Open();
}
My friend noticed that if we change new ServiceHost(typeof(Service1)); to new ServiceHost(typeof(WcfServiceLibrary1.Service1)); then the WCF will actually start to listen!
Easy to see it's confusion as there is a class called Service1 within the windows service project aswell as the WCF project so the full qualification is required.
Did anyone else encounter this?
A: I had the same issue (as you know from the original post in stackoverflow).
Alternatively, you can rename the class Service1 in the namespace WcfServiceLibrary1 to avoid conflicts.
A: you have to put using WcfServiceLibrary1; at the top
A: I also found that the the article references the wrong Service Name. When I tried it I had to use:
net.tcp://localhost:8526/Service1/mex
in step 8 instead of what was listed.
net.tcp://localhost:8526/Service1
| |
doc_23527197
|
I have an item table that has a few item specifics, such as weight. My problem lies with the rest of the tables that I was planning on creating. I essentially want the program I am making to decide what the best postage service is, based on the item weight, package weight and how many items can fit into the package.
I'm not sure how to go about implementing the postal service and packaging. The postal service table would have information such as first/second class and max weight. The packaging table would essentially be like the items table, in the sense that it too has its own weight (as total weight of the package needs to be calculated), however, each package may fit a different number of items in it from the items table.
Would I essentially have to implement in a way where I cross-referenced the item in the packaging table so that there would be a column stating how much of each item fits in each package? I wouldn't then be sure how to reference the service table to get the max weight from the service.
I thought implementing it like so would be an okay attempt:
Items
id INTEGER, title TEXT, sku TEXT, weight DOUBLE
Packaging
id INTEGER, stock_id INTEGER, title TEXT, weight DOUBLE, max_qty INTEGER, FOREIGN KEY(stock_id) REFERENCES items(id)
Services
id INTEGER, class_type TEXT, max_weight DOUBLE, cost DOUBLE
However, the above means that for every item I was to create, I'd have to create a new row in the packages table for each package the item could use.
I'd just like to know what the best way to go about this would be and possibly some advice to go a long with it if possible.
A:
Would I essentially have to implement in a way where I cross-referenced the item in the packaging table so that there would be a column stating how much of each item fits in each package?
Yes, but instead of putting the cross-reference in the packaging table, use a junction table:
The junction table (Item Packaging) has one row for each relationship between an item and a package.
For example, say you have three items:
*
*Whatsit (ID 1)
*Thingamabob (ID 2)
*Doohickey (ID 3)
And you have two package types:
*
*Small Box (ID 1)
*Large Box (ID 2)
Also say that this is how many items can fit into each packaging type:
*
*3 Whatsits in a Small Box
*6 Whatsits in a Large Box
*1 Thingamabob in a Small Box
*3 Thingamabobs in a Large Box
*1 Doohickey in a Large Box
In that case, you would insert these rows into Item Packaging:
---------------------------------------------------
Item ID Packaging ID Item Quantity
---------------------------------------------------
1 1 3
1 2 6
2 1 1
2 2 3
3 2 1
Your program would include the junction table in its queries to determine how much of the specified item could fit into the specified package and calculate the total weight. Then you could compare the calculated weight to the maximum weight of each postal service.
For instance, to get the total weight of each package holding as many Whatsits as it's capable of:
SELECT (item.weight * item_packaging.item_quantity + packaging.weight) AS total_weight FROM item JOIN item ON item_packaging.item_id = item.id JOIN packaging ON item_packaging.packaging_id = packaging.id WHERE item_packaging.item_id = 1;
| |
doc_23527198
|
public static void main(String[] args) {
Object ar []= new Object [4];
ar[0]= 12;
}
}
when I write ar[0]= 12; I am getting the error: "Type mismatch: cannot convert from int to Object"
A: To convert 12 into an object you need al least Java 1.5, this is called Autoboxing
Autoboxing and unboxing was introduced in Java 1.5 to automatically convert primitive type into boxed primitive( Object or Wrapper class)
So be sure to have on both machines a Java version >= 1.5
| |
doc_23527199
|
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
file.stream.seek(0)
myfile = file.file
dataframe = pd.read_csv(myfile)
return
else:
return "Not Allowed"
return render_template("home.html")
This is my form
<form action="" method=post enctype=multipart/form-data>
<input type=file name="file[]" multiple>
<input type=submit value=Upload>
</form>
exception occurred here
NameError: name 'allowed_file' is not defined
Any idea about this kind of issue ?
A: I think you are using this part of documentation : (http://flask.pocoo.org/docs/0.12/patterns/fileuploads/)
But you have to add the function :
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS`
A: Have you created a function called allowed_file() in your module? Or have you created it in another module and forgotten to import it? You’re feeding your filename into the function allowed_file() so that it can check whether the filename is permitted, but the NameError indicates that the function allowed_file() cannot be found.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.