id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_600
|
POST http://localhost:8080/login.php 404 (Not Found)
server.js
var app = require('express')();
var server = require('http').createServer(app);
var webRTC = require('webrtc.io').listen(server);
var exec = require("child_process").exec;
var port = process.env.PORT || 8080;
server.listen(port);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
app.get('/login.php', function(req, res){
exec("wget -q -O - http://localhost/login.php", function (error, stdout, stderr) {res.send(stdout);});});
in index.html calls to login.php:
$("#login").click(function(){
username=$("#user_name").val();
password=$("#password").val();
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
success: function(html)
{......
I want to ask, it's neccessary to install another tool or something else ?
thank you.
A: Node.js won't execute your PHP code, the Apache server will.
As I understand your question you have an Apache server listening on port 80 and a Node.js server listening on 8080 and you want the HTML page served by Node.js to perform an Ajax post on the Apache served login.php. If this assertion is true then the problem is that your Ajax request point to localhost:8080 instead of localhost:80.
You must give an absolute URL to the Ajax request parameters to correctly point to the Apache server (port 80), giving a relative URL as you do it right now will perform the request to localhost:8080 which is your Node.js server.
So, replacing:
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
by
$.ajax({
type: "POST",
url: "http://localhost:80/login.php",
data: "name="+username+"&pwd="+password,
should do the trick.
You certainly want to get the server address from the actual page which you can do like this in JavaScript:
$.ajax({
type: "POST",
url: window.location.href.replace(/^(https?:\/\/[^\/]+/,'$1:80/') + "login.php",
data: "name="+username+"&pwd="+password,
A: To install to Node.js:
npm install node-php
Usage
To run WordPress with Node.js and Express, do this:
var express = require('express');
var php = require("php");
var path = require("path");
var app = express();
app.use("/", php.cgi("/path/to/wordpress"));
app.listen(9090);
console.log("Server listening!");
A: You need to define the routing using Express methods app object that correspond to HTTP methods.
var express = require('express')
var app = express()
// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
res.send('hello world')
})
| |
doc_601
|
The apps is effectively a file manager and does not reply on any DB.
My question is, what would be the best way to go about making this apps hosted.
My initial idea was to have a ZIP file containing the files of the hosted app, then when a user signed up this zip would be extracted to their user folder ( http://domain.com/username ), and the config file within this directory would then be editied to reflect their settings.
Is this overkill? If there more practical ways of doing this?
Any help / suggestions would be much appreciated.
Thanks.
A: The last thing you possibly want is to accumulate a new file for each new user, much less a complete new copy of your code base. Just imagine the mess you would will get into if when you need to fix a bug and have 1000 copies of your code base floating around. It's great that your app works without a database, but that's pretty impractical in a multi-user setup.
*
*Keep one copy of your code base that all users use.
*Make that code multi-user aware and dynamically pull its settings from somewhere for each user.
*The best solution for this somewhere is a database.
A: You shouldn't copy the code for every user. What you want to do is create one instance of the application, and give it the capability to handle multiple users independently. Give it a login system so that users can log in and manage/upload their files.
| |
doc_602
|
However, the IF statement does not work in Python3 but does in Python2!
Please may I ask what has changed (as I can't seem to find the answer)?
#import from library
import random
import sys
#display the python version
print(sys.version)
#computer selects two random numbers between 1 and 10
x = random.randint(1,10)
y = random.randint(1,10)
#print x and y values
print("For x =", x, "and y =", y)
#calculate the correct answer to the sum of the two numbers and store it in the variable named "correct"
correct = x + y
#ask the user what is the sum of the two random numbers and provide a response
answer = input("What is the sum of x plus y ? ")
if answer == correct:
print("well done")
else:
print("Incorrect. The correct answer is", correct)
A: Data type of answer is string, After changing it to int it will work fine
import random
import sys
#display the python version
print(sys.version)
#computer selects two random numbers between 1 and 10
x = random.randint(1,10)
y = random.randint(1,10)
#print x and y values
print("For x =", x, "and y =", y)
#calculate the correct answer to the sum of the two numbers and store it in the variable named "correct"
correct = x + y
#ask the user what is the sum of the two random numbers and provide a response
answer = input("What is the sum of x plus y ? ")
if(int(answer)==correct):
print("well done")
else:
print("Incorrect. The correct answer is", correct)
| |
doc_603
|
With the code below, if I
*
*enter incorrect data
*click save (the error message shows)
*then correct the data.
CanSave becomes true and SaveChangesCommand is executed - before the button is hit again. It's as though the previously blocked button press was queued until canExecute became true.
What am I missing?
Thanks :-)
public PersonalProfileModel()
{
this.SaveChangesCommand = ReactiveCommand.CreateAsyncTask(this.CanSave(), message => this.doAllThings(message as string));
this.ButtonClickedCommand = ReactiveCommand.Create(Observable.Return(true));
this.ButtonClickedCommand.InvokeCommand(this.SaveChangesCommand);
// ButtonClickedCommand.Subscribe(x => this.SaveChangesCommand.Execute("hello")); // tried this too
}
public ReactiveCommand<object> ButtonClickedCommand { get; set; }
public ReactiveCommand<string> SaveChangesCommand;
public IObservable<bool> CanSave()
{
var fieldsValid = this.WhenAnyValue(
x => x.Name,
x => x.Country,
(f1, f2) =>
f1 == "a"
&& f2 == "b");
return fieldsValid;
}
public Task<string> doAllThings(string message)
{
var result = Task.Run(() =>{return "hello " + message;});
return result;
}
A: How about this:
this.SaveChangesCommand = ReactiveCommand.CreateAsyncTask(
this.CanSave(),
message => this.doAllThings(message as string));
this.ButtonClickedCommand = ReactiveCommand.CreateAsyncObservable(
SaveChangesCommand.CanExecuteObservable.StartWith(true),
x => SaveChangesCommand.ExecuteAsync(x));
Now we're explicitly describing the relationship between the ButtonClicked's Command in terms of the SaveChangesCommand - "The ButtonClicked command is enabled when SaveChanges can be executed"
A: This turned out to be a misunderstanding in the behaviour of ReactiveCommands and canExecute.
See ReactiveCommand not respecting canExecute
| |
doc_604
|
from fastai.vision import *
data = (ImageList.from_df(train_df, path='/working/')
.split_by_rand_pct(0.2)
.label_from_df(label_delim=','))
learner = cnn_learner(data, models.resnet18, metrics=[accuracy])
I get the following error:
AttributeError Traceback (most recent call last)
AttributeError: device
How can I resolve this?
A: Try this:
*
*First convert the data into databunch
data = (ImageList.from_df(train_df, path='/working/').split_by_rand_pct(0.2).label_from_df(label_delim=',').databunch()))
*Depending on the hardware. (I am using using cpu for processing).
import torch
data.device = torch.device('cpu')
*Call the learner.
learner = cnn_learner(data, models.resnet18, metrics=[accuracy])
| |
doc_605
|
I have my rake tasks in lib/tasks, and I've declared a logger in both production.rb and developement.rb
Here's an example task:
namespace :some_namespace do
desc "a description"
task :scrape_info do
include Scraper
startTime = Time.now
Rails.logger.tagged("Scraper") { Rails.logger.info "Beginning scrape: #{startTime} " }
Scraper.scrape_info
endTime = Time.now
Rails.logger.tagged("Scraper") { Rails.logger.info "Finished scrape: #{endTime} " }
end
end
And an excerpt from development.rb where I have the logger defined:
config.logger = Logger.new(STDOUT)
config.log_level = :info
config.logger = ActiveSupport::TaggedLogging.new(logger)
Any idea how to incorporate the logger into rake tasks? I understand that I could simply use a puts statement to print to stdout, but eventually I'd like to have daily log files, and I would like my rake tasks to be included in those files
ANSWER:
Simply add the environment tag given in the answer from @Joel_Blum. Also, in development.rb, the line
config.logger = ActiveSupport::TaggedLogging.new(logger)
needs to be:
config.logger = ActiveSupport::TaggedLogging.new(config.logger)
A: Try adding the environment, this will have the effect of loading your rails app.
task :scrape_info => :environment do
...
end
| |
doc_606
|
This attribute must be stored on a graph and takes as value either the
style sheet itself as a string of characters or the URL of a file,
local, distant or packaged in a jar.
You can for example change the background color of the graph using a
style sheet given as a string this way:
graph.addAttribute("ui.stylesheet", "graph { fill-color: red; }");
But you can also specify an URL:
graph.addAttribute("ui.stylehseet",
"url('http://www.deep.in/the/site/mystylesheet')");
Or:
graph.addAttribute("ui.stylesheet",
"url(file:///somewhere/over/the/rainbow/stylesheet')");
However, I experimented with this, and came to the conclusion that GraphStream only supports absolute file paths for this attribute. This is an issue since I will ultimately be exporting the application as a JAR file, and although I have found that you can circumvent the issue by doing something like:
ClassLoader.getSystemClassLoader().getResource(".").getPath();
there is uncertainty associated with this method (i.e. it may not work on certain machines, such as Linux machines (?)).
In which case, my current hack is to store the 'stylesheet' as a long string, something like this:
private static final String GRAPH_DISPLAY_STYLESHEET =
"graph { fill-color: white; }" +
"node {" +
"fill-color: black;" +
"shape: rounded-box;" +
"shadow-mode: plain;" +
"shadow-color: #C8C8C8;" +
"shadow-width: 4;" +
"shadow-offset: 4, -4;" +
"text-background-mode: rounded-box;" +
"text-padding: 5;" +
"text-background-color: black;" +
"text-color: white;" +
"text-size: 20;" +
"size-mode: fit;}" +
"edge { fill-color: black; }";
which is frankly very unsightly.
Does anyone have any ideas about how to improve this situation? Thanks in advance!
A: Using an embedded-resource and getResource() is the way to go. To avoid file system vagaries, try one of these approaches:
*
*Use one of the approaches adduced here to convert each resource to a String suitable for addAttribute().
*Load an instance of java.util.Properties with your styles, as shown here and here, so that each style is available as a String suitable for addAttribute().
| |
doc_607
|
This is the part of my code that is causing the issue:
$snippet="<td id = \"content\">";
for($i=0;$i<count($content_types);$i++){
$type = $content_types[i];
if($type == "Video")
{
$pos_str = ((strlen($content_pos[i]) > 0) ? "class=\"".$content_pos[i]."\"" : "");
$file_type = $content_file_types[i];
$snippet .= "<video ".$pos_str." width=\"320\" height=\"240\" controls>
<source src=\"".$content[i]."\" type=\"video/".$file_type."\">
Your browser does not support the video tag.
</video>";
}
if($type == "Audio")
{
$pos_str = ((strlen($content_pos[i]) > 0) ? "class=\"".$content_pos[i]."\"" : "");
$file_type = $content_file_types[i];
$snippet .= "<audio ".$pos_str." controls>
<source src=\"".$content[i]."\" type=\"audio/".$file_type."\">
Your browser does not support the audio tag.
</audio>";
}
if($type == "Text")
{
$snippet .= "<p class=\"content_text\">
". urldecode($content[i]) ."
</p>";
}
if($type == "Image")
{
$pos_str = ((strlen($content_pos[i]) > 0) ? "class=\"".$content_pos[i]."\"" : "");
$snippet .= "<img src=\"
".$content[i]."
\" ".$pos_str."></img>";
}
}
$snippet .="</td>";
Each code segment for the different content types works correctly, it is only the concatenation of these values into a single string that is not functioning.
The two external '$snippet' concatenations that occur are represented in the output along with the final concatenation within the loop.
I've been working on this for hours and have not been able to figure out why only the final item is being added to the string.
I'm probably just too close to the code and therefore unable to see the obvious mistake that I've made.
Any help would be appreciated.
Thanks in advance.
A: You missing $ symbol at all the places you have used variable $i.
$type = $content_types[$i];
^
Note: Add error_reporting(E_ALL & E_STRICT); on top of the file it will show you errors & notices in such cases.
| |
doc_608
|
Profile 78 (NET45+WP8+Store): no problem with TPL,await/async and support for CallerMemberName attribute (used in BindableBase view model base class). But the Mono.Android project that refers such library fails to build complaining about non-present System.Runtime.dll that should be referenced.
Profile 104 (NET45+SL4+WP75+Store): await/async don't work, CallerMember name not found, but if I remove all references to them, Android project builds fine.
Profile 147 (NET403+SL5+WP8+Store): await/async don't work, CallerMember name not found, but if I remove all references to them, Android project builds fine.
Profile 158 (NET45+SL5+WP8+Store): await/async don't work, CallerMember name not found, but if I remove all references to them, Android project builds fine.
So I am not really sure what to choose. Profiles 78, 104, 147 are limited, profile 78 is the only one that supports both await/async and CallerMemberName used BindableBase, but it fails on Android complaining about System.Runtime.dll. So if you have an experience with what PCL profile is the best match for PCL targeting Mono, please share your thoughts.
A: Thinking about profile numbers is hard - I prefer to think in terms of the platforms.
Ideally I'd love my projects to support:
*
*.Net 3.5 and higher
*SL3 and higher
*WP7.x phone and higher
*MonoDroid 1.6 and higher
*MonoTouch iOS6 and higher
*(Mac desktop OSX Lion)
The main PCL project I support is MvvmCross - which requires Mvvm 'facilities' like ICommand. These facilities are only available in platforms for .Net 4.5 and higher... that's a hard limit - nothing I can do about it - so changes my needs to:
*
*.Net 3.5 and higher .Net 4.5
*SL3 and higher SL4 and higher
*WP7.x phone and higher
*MonoDroid 1.6 and higher
*MonoTouch iOS6 and higher
*(Mac desktop OSX Lion)
With this selection in place, then this leads me to a profile number - 104 (no idea how the platform decided this... gave up asking a long time ago!)
So I've targeted MvvmCross at profile 104 - and it will stay there while WP7.x support is still needed.
This selection does mean that MvvmCross cannot out-of-the-box support things like async/await and CallerMemberName - but this is a compromise we've decided to make - we have users who need WP7.
However, some people are asking about await/async...
To use these new features, there are some BCL.Async Nuget hacks to make them work in profile 104... or these users can target their apps at a newer profile (one that doesn't support WP7.x and SL4) - this leads them to build their apps in profile 78, but to add references to my profile 104 assemblies.
Neither of these sets of solutions works very well with the Xamarin twins at present - e.g. you hit issues like the missing System.Runtime.dll assembly. However, I anticipate that when Xamarin officially supports PCLs (and after some alpha/beta testing) then these problems will be resolved. This official support is due very soon now - which is why I don't bother expending too much of my time thinking about these problems...
I expect in the medium term that MvvmCross will drop support for WP7.x and SL4. When that happens, we may also move the core libraries to profile 78.
The only other large platform I know that has started PCL support is ReactiveUI. I believe this platform must use profile 78 because the PCL version of Reactive from Microsoft is targeting 78.
| |
doc_609
|
public ObjGeometry geometry(final Iterable<String> lines) throws IllegalArgumentException {
final List<Vector3f> vertices = Lists.newArrayList();
final List<Vector2f> textures = Lists.newArrayList();
final List<Vector3f> normals = Lists.newArrayList();
final List<Face> faces = Lists.newArrayList();
for (final String line : lines) {
final List<String> lineElements = Arrays.asList(line.split(" "));
final String token = lineElements.get(0);
switch (token) {
case VERTEX:
final Vector3f vertex = createVertex(lineElements);
vertices.add(vertex);
break;
case TEXTURE:
final Vector2f texture = createTexture(lineElements);
textures.add(texture);
break;
case NORMAL:
final Vector3f normal = createNormal(lineElements);
normals.add(normal);
break;
case FACES:
final Face face = createFace(lineElements);
faces.add(face);
break;
}
}
return ObjGeometry.from(vertices, textures, normals, faces);
}
The methods #createVertex,#createTexture,#createNormaland #createFace transforming a string to a special dataType (Vector2f, Vector3f or Face)
What i want to do is... to build a Map Map<TOKEN, Parser>, so I can iterate over that map and call the right parser for a special token (btw. TOKEN is a String like "v", "vt", "vn", or "f").
What i have is:
*
*abstract classExtractVector3f with method #vectorFrom(List<String>) - can transform a List<String> to Vector3f
*abstract classExtractVector2f with method #vectorFrom(List<String>) - can transform a List<String> to Vector2f
*abstract classExtractFace with method #faceFrom(List<String>) - can transform a List<String> to Face
*an interface LineParser
public interface LineParser<T> {
T apply(final List<String> lineElements);
}
*a class to parse a vertex
public class ParseVertex extends ExtractVector3f implements LineParser<Vector3f> {
@Override
public Vector3f apply(final List<String> lineElements) {
return vectorFrom(lineElements);
}
}
*a class to parse a normal
public class ParseNormal extends ExtractVector3f implements LineParser<Vector3f> {
@Override
public Vector3f apply(final List<String> lineElements) {
return vectorFrom(lineElements);
}
}
*a class to parse a texture
public class ParseTexture extends ExtractVector2f implements LineParser<Vector2f> {
@Override
public Vector2f apply(final List<String> lineElements) {
return vectorFrom(lineElements);
}
}
*and a class to parse a face
public class ParseFace extends ExtractFaces implements LineParser<Face> {
@Override
public Face apply(final List<String> lineElements) {
return faceFrom(lineElements);
}
}
The next step would be to build the map... something like
Map<String, LineParser> parsers = Maps.newHashMap();
parsers.put("v", new ParseVertex());
parsers.put("vt", new ParseTexture());
parsers.put("vn", new ParseNormal());
parsers.put("f", new ParseFace());
But now i get in trouble. LineParser in this map is a raw type and raw-types should be avoid.
My Question is:
How can i build a map, with POJOs in it - which return different data-types on the method which is defined via Interface?
A: I would not do this, actually. Even if the map is a good idea, done this way you lose the exact type of the objects you build. What are you gonna do with them after that ? How do you know to which collection adding them ? You can't, unless the parsers have access to all collections to pick the right one. This suggests the parsers should know your main class, or methods of this class.
I would just use lambdas :
Consumer<List<String>> handleTexture = args -> textures.add(parseTexture(args))
Consumer<List<String>> handleVertice = args -> vertices.add(parseVertice(args))
...
Map<String, Consumer<List<String>> handlers = new HashMap<>();
handlers.put("vf", handleTexture);
handlers.put("v", handleVertice);
...
for (final String line : lines) {
final List<String> lineElements = Arrays.asList(line.split(" "));
final String token = lineElements.get(0);
handlers.get(token).accept(lineElements.sublist(1, lineElements.size()));)
}
If you want to do it with Java 7 it is syntactically less nice, but the principle is the same. Create a interface like Consumer with a method accept (you can change all the names if you want to make the class more specific to your project, like Parser and parse, just keep the same signature for the method) :
public class Consumer<T> {
public void accept(T t);
}
Then, in your code
Consumer<List<String>> handleTexture = new Consumer<List<String>>() {
@Override
public void accept(List<String> args) {
textures.add(parseTexture(args));
}
}
The rest is just the same !
| |
doc_610
|
*
*The number of items that are considered for paging also include the group row which I want to exclude.
*Also when I click on the next button there are records from the previous page that are being shown.
*I have a select all checkbox and on the 2nd page when I check the select all checkbox the grouping is lost.
Can you please help me
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
// hide bottom pageBlockbuttons
$(".pbBottomButtons").last().hide();
});
function toggleBottomPageBlockButtons() {
setTimeout(function(){
var availableRows = $('table[id$="casesTable"] tr').not(":hidden").length;
if(availableRows > 12) {
$(".pbBottomButtons").last().show();
}
else {
$(".pbBottomButtons").last().hide();
}
},500);
}
</script>
<script type="text/javascript" charset="utf-8">
$('table[id$="casesTable"]').tablesorter({
sortList: [ [1, 0] ],
sortForce: [ [1, 0] ],
widgets: ["filter","group", "columns", "zebra" ],
widgetOptions : {
// css class applied to the table row containing the filters & the inputs within that row
filter_cssFilter : 'tablesorter-filter',
// filter widget: If there are child rows in the table (rows with class name from "cssChildRow" option)
// and this option is true and a match is found anywhere in the child row, then it will make that row
// visible; default is false
filter_childRows : false,
// Set this option to true to use the filter to find text from the start of the column
//
filter_startsWith : false,
group_collapsible : true,
group_collapsed : false,
group_count : " ({num})",
group_dateString : function(date) {
return date.toLocaleString();
},
group_formatter : function(txt, col, table, c, wo) {
return txt === "" ? "Empty" : txt;
},
group_callback : function($cell, $rows, column, table){
// var subtotal = 0;
// $rows.each(function(){
// subtotal += parseInt( $(this).find("td").eq(column).text() );
//});
//$cell.find(".group-count").append("; subtotal: " + subtotal );
},
group_complete : "groupingComplete"
}
}).tablesorterPager({container: $("#pager")});;
// check uncheck all functionality
$("#checkUncheckAll").click(function() {
$(".selectionCheckbox").not(":hidden").attr('checked', this.checked);
});
// uncheck all checkboxes when user clicks on next/previous page
$("#pager a img:not(.disabled)").click(function(){
$("#checkUncheckAll").attr('checked', false);
/* $(".selectionCheckbox").attr('checked', false); */
});
</script>
A: The demo you shared appears to be using the original pager from tablesorter.com, and therefore does not work well with the grouping widget.
In this updated demo, the following can be observed:
*
*Only the set number of rows are seen, the grouping header rows are included in addition to the set rows.
*The grouping widget only works on the currently visible rows. If a row appears on a different page, it will not be included in the group on another page.
*In order to update (apply) the grouping widget to a table after something was manipulated, like the checkboxes, just trigger the applyWidgets method.
$('table').trigger('applyWidgets');
I hope that covers the concerns you are having.
| |
doc_611
|
I am using an autoencoder model to train the unlabeled examples.
Now I want to train the encoder with labels. My doubt here is, by compiling the encoder model, am I creating a new model and not reusing the weights of the autoencoder?
Is the Encoder model a separate CNN model or is it still part of autoencoder?
x = Input(shape=(input_dim,))
encoder = Dense(output_dim)(x)
decoder = Dense(input_dim)(encoder)
autoencoder = Model(input=x, output=decoder)
out=dense(10,activation='softmax')(encoder)
supervised = Model(input=x, output=out)
autoencoder.compile(...)
supervised.compile(...)
autoencoder.fit(x1,x1)
supervised.fit(x2,y2)
supervised.predict(x3)
Thanks in advance
A: If by encoder part of autoencoder, you mean they share layers?
Yes, they do. However they can be differently compiled. This means you can have different optimisers, loss functions, etc. for them.
A simple way to check this is just predicting before and after training of a specific model like
x = Input(shape=(input_dim,))
encoder = Dense(output_dim)(x)
decoder = Dense(input_dim)(encoder)
autoencoder = Model(input=x, output=decoder)
out=dense(10,activation='softmax')(encoder)
supervised = Model(input=x, output=out)
autoencoder.compile(...)
supervised.compile(...)
weights_before = supervised.layers[1].get_weights()
autoencoder.fit(x1,x1)
weights_after = supervised.layers[1].get_weights()
print(weights_before, weights_after)
supervised.fit(x2,y2)
supervised.predict(x3)
You'll find the weights to be different while not training on supervised at all. This is because the Dense layer which outputs encodings is shared by both the models. Keep in mind, the models however are different objects with shared layers.
| |
doc_612
|
Based on read data in ItemReader, I spread indices to few separate directories.
If I specify, Step Task Executor to be a SimpleAsyncTaskExecutor , I don't get any issue as long as indices are always written to different directories but sometimes I get a locking exception. I guess, two threads tried to write to same Index.
If I remove SimpleAsyncTaskExecutor, I don't get any issues but write becomes sequential and slow.
Is it possible to use multi threading for a Lucene Index writer if indices are being written to a single directory?
Do I need to make index creator code to be thread safe to use SimpleAsyncTaskExecutor?
index creator code is in step processor.
A: I am using Lucene 6.0.0 and as per IndexWriter API Doc,
NOTE: IndexWriter instances are completely thread safe, meaning
multiple threads can call any of its methods, concurrently. If your
application requires external synchronization, you should not
synchronize on the IndexWriter instance as this may cause deadlock;
use your own (non-Lucene) objects instead.
I was creating multiple instances of writer and that was causing problems. Single writer instance can be passed to as many threads as you like provided rest of the code around that writer is thread safe.
I used a single writer instance and parallelized chunks. Each parallel chunk wrote to same directory without any issues.
To parallelize chunks, I had to made my chunk components - reader , processor and writer to be thread safe.
| |
doc_613
|
jQuery convert checkbox selections to array.
This works fine. I have modified it to match my requirements. My javascript is like below .
when a checkbox is checked I want to be added to the corresponding ID(which works fine) but when it is unchecked I want it to be removed..so I used pop. That works but it removed the last item ID rater than the unchecked item ID
` var arrayPgggoData = pgggoThisElem.parents('.elementor-widget-container').find('.pgggo-sort-container').attr('data-ajax-container');
var arrayPgggoData = JSON.parse(arrayPgggoData);
if ($(this).is(':checked')) {
const [_, taxonomy, __, attr] = $(this).attr('name').split('-');
arrayPgggoData[taxonomy] = arrayPgggoData[taxonomy] || [];
arrayPgggoData[taxonomy].push(attr.split('[')[0]);
} else {
const [_, taxonomy, __, attr] = $(this).attr('name').split('-');
arrayPgggoData[taxonomy] = arrayPgggoData[taxonomy] || [];
arrayPgggoData[taxonomy].pop(attr.split('[')[0]);
}`
Can someone help me out? :|
A: The pop function does as it is supposed which is basically removing the last element you have.
What you need here is splice(start, positions) but in this case you'd need to find the position in which the element appears. For this you would need to use indexOf(element).
You'd need something like this:
var index = indexOf(element);
arrayPgggoData.splice(index, 1);
You can check this article for more information on different ways to remove elements from arrays in JavaScript.
| |
doc_614
|
The situation is that I have a TableQuery and a Table where the user can add and remove new Rows. Each row has properties that can not be null. The problem is, if a user adds 2 new rows to the table and deletes one. The SQLContainer tries to commit everything and will throw an exception because 1 item has null values.
Is it possible that I can tell him only to commit the rows I want him to ?
rollback() would revert all changes. The problem is that the user can remove item that are already in the database or the ones that are only temporary in the memory.
Would it help to create a RowItem because that one has a commit method ?
A: You can commit after added evry of new created item by user. It is not optimal solution but it may solve your problem.
| |
doc_615
|
http://developer.android.com/reference/android/app/Activity.html#onBackPressed()
This doc say that "The default implementation simply finishes the current activity".
What does it means, does it mean the default onBackPressed() include the function finish()?
What is the implementation inside finish()?
Is that onDestroy()?
A: This is how implementation looks like:
public void onBackPressed() {
if (!mFragments.popBackStackImmediate()) {
finish();
}
}
Of course on Android 2.3 and lower it's like this:
public void onBackPressed() {
finish();
}
There was no Fragments API.
You can always check sources yourself in your IDE or on the web
| |
doc_616
|
C Code:
while((INT_STATUS() & ISR_RX_MASK)
||(event & TIMER_EXPIRED)
||(event & MEM_BLOCK_AVAILABLE))
{.........
Here:
event is UNT32 local variable in function
INT_STATUS() = Some Address location
ISR_RX_MASK = 0x01 (Some value in HEX)
TIMER_EXPIRED = 0x02 (Some value in HEX)
MEM_BLOCK_AVAILABLE = 0x03 (Some value in HEX)
Thank you.
A: The loop will execute while either bit 0 of INT_STATUS() is 1, or bit 1 of event, or bit 2 of event is set to 1
A: At first you will probably be interested in binary numbers representation.
And I suggest MEM_BLOCK_AVAILABLE is actually 0x04 and not 0x03, more below.
In binary (0x means the number is represented in hexadecimal, but since all numbers below are less than 10, they could as well be shown in decimal - but we usually use hexa or octal to write number literals which interest is their binary representation), we have
Hexa Binary
0x01 is 0001
0x02 is 0010
0x03 is 0011
0x04 is 0100 ...
And the bitwise operator & between two numbers A and B keeps the 1 that are, in binary, in both numbers at the same place
Like (binary representation)
dcba dcba
0110 & 0011 gives 0010 since only the 1 at position b is in both numbers
Finally the while( expr ) loops while expr is non zero. So doing & between two numbers gives a result (expr) with either at least one 1 (non zero) or no 1 (zero). Thus having the while looping (non zero) or ending (zero).
In your case, doing
while((INT_STATUS() & ISR_RX_MASK)
||(event & TIMER_EXPIRED)
||(event & MEM_BLOCK_AVAILABLE))
means while loops if any of the three expressions is non zero (true), || means logical OR. Provided that ISR_RX_MASK is 1, TIMER_EXPIRED is 2 and MEM_BLOCK_AVAILABLE is (I assume) 4, you get the while expression
(INT_STATUS() & 1)
||
(event & 2)
||
(event & 4)
meaning the while goes on if the result from INT_STATUS & 1, ie its first bit (right side) is 1 (or a in my dcba notation shown above), or if the second bit (or b in my dbca notation) of event is 1 (from the right), or if the third bit (or c in my dcba notation) of event is 1.
For instance if INT_STATUS is 14, ie 1110 in binary, its first bit is 0, thus the INT_STATUS() & 1 would yield 0.
The reason I assume MEM_BLOCK_AVAILABLE is 4 (or another power of 2 > 2) and not 3 is because if it is 3, or 0011 in binary, the previous event & 2 would always be true when event & 3 is true, and thus does not make sense in this context. And it doesn't seem MEM_BLOCK_AVAILABLE and TIMER_EXPIRED are related, based on their names, which is subjective, but...
A: while((INT_STATUS() & ISR_RX_MASK) ||(event & TIMER_EXPIRED) ||(event & MEM_BLOCK_AVAILABLE))
The looping is continued if any of the following condition occurs
1) Result after performing logical AND operation between the return value of INT_STATUS() function and ISR_RX_MASK is true, Which I assume is checking for some interrupt condition
2) Result after performing logical AND operation between between variable event(I assume this contains value of some register) with TIMER_EXPIRED hex value is TRUE. That is, indication flag for Timer Expire will be at 1st bit poition (0000 0010)
3) Result after performing logical AND operation between between variable event(I assume this contains value of some register) with MEM_BLOCK_AVAILABLE hex value is TRUE. That is the indication flag for Memory Block available will be at 0th and 1st bit poition (0000 0011)
| |
doc_617
|
The first time the autofocus works fine, but after hiding the form and displaying it again, the autofocus does not work anymore.
Is there a way to achieve this by jQuery? And what code do I need?
HTML:
<div class="header-search">
<div class="search-container">
<div class="overwrite-setting">
<i class="sf-icon-search"></i>
</div>
<div class="switcher-content">
<form id="search_mini_form" action="https://www.redable.nl/catalogsearch/result/" method="get">
<div class="form-search">
<input id="search" autofocus="autofocus" placeholder="Zoeken naar..." type="text" name="q" value="" class="input-text" maxlength="128" autocomplete="off">
<button type="submit" title="Zoek" class="search-button"><span><span><i class="fa fa-search"></i></span></span></button>
<div id="search_autocomplete" class="search-autocomplete" style="display: none;"></div>
</div>
</form>
</div>
</div>
</div>
jQuery:
jQuery('.header-setting .overwrite-setting').click(function() {
jQuery('.setting-switcher .switcher-content').toggle();
jQuery(this).toggleClass('active');
return false;
})
if(jQuery(window).width() > 1024){
jQuery('.header-maincart .icon-cart-header').click(function() {
jQuery('.header-maincart .cart-wrapper').toggle();
jQuery(this).toggleClass('active');
return false;
})
}
jQuery('.header-search .overwrite-setting').click(function() {
jQuery('.search-container .switcher-content').toggle();
jQuery(this).toggleClass('active');
return false;
})
jQuery(document).mouseup(function (e)
{
if(jQuery(window).width() > 1024){
if(jQuery('.header-maincart').has(e.target).length == 0 && jQuery('.cart-wrapper').has(e.target).length == 0 ){
jQuery('.header-maincart .cart-wrapper').hide();
jQuery('.header-maincart .icon-cart-header').removeClass('active');
}
}
if(jQuery('.header-search .overwrite-setting').has(e.target).length == 0 && jQuery('.search-container .switcher-content').has(e.target).length == 0){
jQuery('.search-container .switcher-content').hide();
jQuery('.header-search .overwrite-setting').removeClass('active');
}
if(jQuery('.header-setting .overwrite-setting').has(e.target).length == 0 && jQuery('.setting-switcher .switcher-content').has(e.target).length == 0){
jQuery('.setting-switcher .switcher-content').hide();
jQuery('.header-setting .overwrite-setting').removeClass('active');
}
});
A: Not sure how you hide/show the input, but you can use the focus function on the element after you show it:
$('button').click(function() {
$('#search').toggle().focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search" autofocus="autofocus" placeholder="Zoeken naar..." type="text" name="q" value="" class="input-text" maxlength="128" autocomplete="off">
<button>Click to hide/show the button</button>
| |
doc_618
|
$job = $_SESSION['job'];
$user_id = '1';
$name = 'allie';
$stmt = $mysqli->prepare("INSERT INTO
requests(name,job_info,user_id)
VALUES (?,?,?)");
$stmt->bind_param('sss', $name, $job, $user_id);
$stmt->execute();
A: see pdo bind_param
your parameter is incorrect:
change this:
$stmt->bind_param('sss', $name, $job, $user_id);
with this:
$stmt->bind_param(1, $name, PDO::PARAM_STR);
$stmt->bind_param(2, $job, PDO::PARAM_STR);
$stmt->bind_param(3, intval($user_id), PDO::PARAM_INT);
| |
doc_619
|
I've followed this Couchbase documentation and produced the following curl command:
curl -X POST http://Administrator:welcome@localhost:8091/settings/viewUpdateDaemon -d 'updateInterval=7000&updateMinChanges=1'
But I'm getting back an error:
{"updateInterval":5000,"updateMinChanges":5000,"replicaUpdateMinChanges":5000}'updateMinChanges'
is not recognized as an internal or externa l command, operable
program or batch file.
When I try to change only one parameter, for example:
curl -X POST http://Administrator:welcome@localhost:8091/settings/viewUpdateDaemon -d 'updateMinChanges=1'
It didn't give any error back but settings remained the same (produced in the response):
{"updateInterval":5000,"updateMinChanges":5000,"replicaUpdateMinChanges":5000}
I also tried to send fields in JSon format with the same outcome - no error but settings did't change.
curl -X POST http://Administrator:welcome@localhost:8091/settings/viewUpdateDaemon -d '{"updateInterval":7000,"updateMinChanges":100,"replicaUpdateMinChanges":100}'
So my question is: How one can change Couchbase's view settings via curl REST API?
I use latest Couchbase server v.2.0.1
A: Late to the game, but...
The content of the request is form data.
So you should post it as such.
Content could be (for your case):
updateInterval=7000&updateMinChanges=1
| |
doc_620
|
I am developing a Windows 8 app using JavaScript and HTML5. I need to restrict some functionality on the app depending of the active directory group where an user account is assigned.
The question is: how I can check if a user account belongs to a Active Directory group?
I have tried using Windows.System.UserProfile.UserInformation and Windows.Security.Credentials.UI.CredentialPicker, but none of them returns either a way to test if a user account belongs to a group, or the group where the user account is assigned.
Thanks in advance for your help.
A: I found a solution to perform this, which was the one I implemented, and it works. You can create a web service that validates the credentials against Active Directory, where you pass the domain, username and password, then call it from the app using WinJS.xhr. To ask for the credentials, you can use the CredentialPicker control, which returns, the domain, username, and password entered by the user.
Here is the code:
Web Service Code:
ValidateUserResult vur = new ValidateUserResult();
try
{
using (PrincipalContext context =
new PrincipalContext(ContextType.Domain, domain))
{
vur.UserCredentialsAreValid = context
.ValidateCredentials(username, password);
if (vur.UserCredentialsAreValid)
{
vur.ProcessMessageText = "Ok";
vur.ProcessMessageCode = 0;
}
else
{
vur.ProcessMessageText =
"Credenciales invalidas";
vur.ProcessMessageCode = -1;
}
}
}
catch (Exception ex)
{
vur.UserCredentialsAreValid = false;
vur.ProcessMessageText = ex.Message;
vur.ProcessMessageCode = ex.HResult;
}
return vur;
Windows 8 App:
WinJS.xhr({
type: "get"
, url: {Web Service Url}
+ "/json/{Web Service Method Name}?domain="
+ domain + "&username=" + username
+ "&password=" + password
}).then(
function (result) {
if (result.status === 200) {
// Place code here.
}
},
function (error) {
// If an error occurs, manage here
});
| |
doc_621
|
for (i=0,len=$clientsSections.length;i<len;i++) {
clientsSection = $clientsSections[i];
if (i == 0 || i == 3) {
finalTransitionTime = '600ms';
}
else if (i == 1 || i == 2) {
finalTransitionTime = '300ms';
}
clientsSection.style.webkitTransition = 'all ' + finalTransitionTime + ' linear';
clientsSection.style.OTransition = 'all ' + finalTransitionTime + ' linear';
clientsSection.style.msTransition = 'all ' + finalTransitionTime + ' linear';
clientsSection.style.MozTransition = 'all ' + finalTransitionTime + ' linear';
clientsSection.style.transition = 'all ' + finalTransitionTime + ' linear';
clientsSection.style.webkitTransform = 'translate3d(0,0,0)';
clientsSection.style.transform = 'translate3d(0,0,0)';
clientsSection.style.OTransform = 'translate3d(0,0,0)';
clientsSection.style.msTransform = 'translate3d(0,0,0)';
clientsSection.style.MozTransform = 'translate3d(0,0,0)';
}
What I want to do is run i == 0 and i == 3 immediately, but delay i == 1 and i == 2 by a couple hundred milliseconds. I am trying to figure out how to accomplish this, but I am struggling to make it happen with the for loop running 0,1,2,3.
A: CSS3 has a transition-delay property that may be what you want.
https://developer.mozilla.org/en-US/docs/Web/CSS/transition-delay
Ex: transition-delay: 200ms;
The transition property also supports a delay.
http://css-tricks.com/almanac/properties/t/transition/
Ex: transition: color 300ms 200ms; (delays for 200ms, then runs the animation for 300ms)
| |
doc_622
|
Anyhow here's what I want to do: we have a class called Loan like this:
@Document(collection = "Loans")
public class Loan{
@Id
private String id;
private String type;
private LoanApplication loanApplication;
private LoanDecision loanDecision;
private String loanAppId;
private String loanDecisionId;
private LocalDateTime receivedDate;
private LocalDate leadExpiry;
private Integer previousStatus;
private Integer status;
private Boolean isEligibleForRemove;
private String timeStamp;
private List<String> loanDecisions;
private String activeLoanDecision;
private String lenderReferenceNumber;
private String pdfName;
Because we have to perform various operations when querying this collection we therefor created an aggregation (the aggregation works for we created in Mongo Compass and then exported it into our code) in the LoanRepository:
@Repository
@EnableMongoRepositories
public interface LoanRepository extends MongoRepository<Loan, String> {
@Aggregation(pipeline = {"{$match: {\r\n" +
" 'status':{$in: ?0},\r\n" +
" 'loanApplication.mortgage.requested.lenderSubmission.lenderProfile.lenderCode': ?1\r\n" +
" }},{\r\n" +
" $project: {\r\n" +
" 'applicationId': '$loanApplication.deal.applicationId',\r\n" +
" 'cominedLtv': '$loanApplication.deal.combinedLtv',\r\n" +
" 'receivedDate': '$receivedDate',\r\n" +
//other fields to project
" }\r\n" +
" }\r\n" +
"}, {\r\n" +
" $unwind: {\r\n" +
" path: '$applicants'\r\n" +
" }\r\n" +
"}, {\r\n" +
" $match: {\r\n" +
" 'applicants.primaryApplicantFlag': 'Y'\r\n" +
" }\r\n" +
"}
//other aggregate methods
"})
public List<LoanProjection> findLeads(final List<Integer> leadsStatus, final String lenderCode);
}
The ideea is that after all the above operations we need to return just some fields from the whole Loans table (as can be seen in the $project step). I know that the return type of all the methods from this repository must be Loan and one solution would be to utilise spring projection. Thus i created the necessary projection interfaces (bellow you will find only the interfaces for the fields in the $project step):
public interface LoanProjection {
DealType getDealType();
LocalDate getReceivedDate();
}
public interface DealTypeProjection {
String getApplicationId();
String getcombinedLtv();
}
The problem is: when the findLeads() repository method is called the following error occurs:
java.lang.NullPointerException: null
at org.springframework.data.mongodb.core.mapping.MongoSimpleTypes$1.isSimpleType(MongoSimpleTypes.java:110) ~[spring-data-mongodb-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at org.springframework.data.mongodb.repository.query.StringBasedAggregation.isSimpleReturnType(StringBasedAggregation.java:119) ~[spring-data-mongodb-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at org.springframework.data.mongodb.repository.query.StringBasedAggregation.doExecute(StringBasedAggregation.java:81) ~[spring-data-mongodb-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at org.springframework.data.mongodb.repository.query.AbstractMongoQuery.execute(AbstractMongoQuery.java:101) ~[spring-data-mongodb-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:618) ~[spring-data-commons-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:605) ~[spring-data-commons-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80) ~[spring-data-commons-2.2.5.RELEASE.jar:2.2.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at com.sun.proxy.$Proxy130.findLeadsTest(Unknown Source) ~[na:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_231]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_231]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_231]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_231]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at com.sun.proxy.$Proxy130.findLeadsTest(Unknown Source) ~[na:na]
at com.filogix.lg.service.impl.LoanServiceImpl.retrieveLeads(LoanServiceImpl.java:261) ~[classes/:na]
at com.filogix.lg.api.LoanController.getLeads(LoanController.java:49) ~[classes/:na]
at com.filogix.lg.api.LoanController$$FastClassBySpringCGLIB$$54fe4fe8.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:769) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.validation.beanvalidation.MethodValidationInterceptor.invoke(MethodValidationInterceptor.java:120) ~[spring-context-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689) ~[spring-aop-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at com.filogix.lg.api.LoanController$$EnhancerBySpringCGLIB$$f692749f.getLeads(<generated>) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_231]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_231]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_231]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_231]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879) ~[spring-webmvc-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.31.jar:9.0.31]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
at com.filogix.lg.config.DecodingFilter.doFilter(DecodingFilter.java:35) ~[classes/:na]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.4.RELEASE.jar:5.2.4.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367) [tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1639) [tomcat-embed-core-9.0.31.jar:9.0.31]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.31.jar:9.0.31]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_231]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_231]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.31.jar:9.0.31]
at java.lang.Thread.run(Unknown Source) [na:1.8.0_231]
I first started trimming my Aggregation logic thinking that maybe there is a problem with it (the aggregation works fine in Mongo Compass and Atlass) and i ended up having only the $match operator (something very basic) and still the error persisted.
@Aggregation(pipeline = {"{$match: {\r\n" +
" 'status':{$in: ?0},\r\n" +
" 'loanApplication.mortgage.requested.lenderSubmission.lenderProfile.lenderCode': ?1\r\n" +
" }}"})
public List<LoanProjection> findLeadsTest(final List<Integer> leadsStatus, final String lenderCode);
Then I wanted to see if by utilising the @Query annotation i would receive the same error. Funny enough with this method the projection worked!!!
@Query(value = "{$and: [{'status': {$in: ?0}}, {'loanApplication.mortgage.requested.lenderSubmission.lenderProfile.lenderCode': ?1}]}")
public List<LoanProjection> findLeads(final List<Integer> leadsStatus, final String lenderCode);
Therefore my question is: is somehow spring projection not compatible with @Agregation or am i using it wrong (most likely)?
A: I think you would need to use a class instead of an interface and you need to add the @Id annotation in order to match the result from the aggregation
In your case is very hard to follow exactly what would be the id, because you didn't added any result from running the aggregation manually in mongo from CLI.
But if I try to guess then something like this probably would help you:
import org.springframework.data.annotation.Id;
// other imports
public class LoanProjection {
@Id
private DealType dealType;
private LocalDate receivedDate;
DealType getDealType() {
return dealType;
}
LocalDate getReceivedDate() {
return receivedDate;
}
}
public class DealTypeProjection {
@Id
private String applicationId;
private String combinedLtv;
public String getApplicationId() {
return applicationId;
}
public String getCombinedLtv() {
return combinedLtv;
}
}
Usually the result from an aggregation is very different than the Document used so you would need to have some unique identifier in order to map it to a new Projection. You could look at the result from aggregation like a new Document because this is the way spring matches the result with actual DTO.
More details here:
https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mongodb.repositories.queries.aggregation
| |
doc_623
|
I'm creating a prototype whose purpose is to figure out the right user experience, so it's OK if it's not going to scale to 300 million simultaneous users on IE6/Windows Millenium. ;-)
A: That's a rather complicated thing to do from scratch, so consider using a plugin. Wijmo is based on jQuery UI and has an open-source splitter widget. The documentation is decent as well.
While I don't see any methods to resize it, you may be able to add one and contribute it back to the project.
| |
doc_624
|
**Template:**
<nav>
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link active" data-target="#cars" data-toggle="tab" >Cars</a>
</li>
<li class="nav-item">
<a class="nav-link" data-target="#messages" data-toggle="tab" >Messages</a>
</li>
<li class="nav-item">
<a class="nav-link" data-target="#extras" data-toggle="tab" >Extras</a>
</li>
</ul>
</nav>
<div class="tab-content">
<div id="cars" class="tab-pane active">
SOME TAB 1 CONTENT
</div>
<div id="messages" class="tab-pane fade">
SOME TAB 2 CONTENT
</div>
<div id="extras" class="tab-pane fade">
SOME TAB 3 CONTENT
</div>
</div>
**Controller:**
/**
* @Route("/extra/{id}", name="extra_delete", methods={"POST"})
*/
public function extraDelete(Request $request, Extra $extra): Response
{
if ($this->isCsrfTokenValid('delete'.$extra->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($extra);
$entityManager->flush();
}
return $this->redirectToRoute('car_index');**
}
**I ve already tried this:
return $this->redirect($this->generateUrl('car_index').'#extras');
but doesnt work.
Thank you
A: For future reference the solution was indeed Javascript.
*
*In the controller I put a parameterized URL:
return $this->redirectToRoute('car_index', ['param' => 'extrakTab']);
*In the template I run this script:
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const parameter = urlParams.get('param')
if(parameter !== null){
let elements = [];
elements = document.getElementsByClassName('tab-pane');
toggleClass();
function toggleClass(){
for (let i = 0; i < elements.length; i++) {
elements[i].classList.remove('active');
elements[i].classList.add('fade');
}
}
var element = document.getElementById(parameter);
element.click();
}
| |
doc_625
|
It is not working now and I don't understand why: I get EOF = 1 that (rightfully, I think) halts the macro execution.
The only EOF-related similar question I found here is this one, which I couldn't use.
This is my code: I always get the error message "Something went wrong."
DBAutoQuery()
Dim oConn As ADODB.Connection
Dim RecSet As ADODB.Recordset
Dim Fld As ADODB.Field
Dim Col, Row As Integer
Dim ws As ThisWorkbook
Set ws = ThisWorkbook
Application.ScreenUpdating = False
Set oConn = New ADODB.Connection
Set RecSet = New ADODB.Recordset
oConn.ConnectionString = "driver={MySQL ODBC 5.3 ANSI Driver};Server=odbc-
staff-01.corp.booking.com;Database=staff;User=" & User & ";Password=" & Pw &
";ENABLE_CLEARTEXT_PLUGIN=1"
oConn.ConnectionTimeout = 30
oConn.Open
RecSet.Open mYsql, oConn, adOpenStatic, adLockOptimistic
If RecSet.EOF Then
MsgBox "Something went wrong."
RecSet.Close
oConn.Close
Exit Sub
End If
Sheets(TargetSheetName).Select
Row = 1
Col = 1
For Each Fld In RecSet.Fields
ActiveSheet.Cells(Row, Col).Value = Fld.Name
Col = Col + 1
Next
RecSet.MoveFirst
Row = Row + 1
Do While Not RecSet.EOF
Col = 1
For Each Fld In RecSet.Fields
ActiveSheet.Cells(Row, Col).Value = Fld
Col = Col + 1
Next
Row = Row + 1
RecSet.MoveNext
Loop
RecSet.Close
oConn.Close
LastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
End Sub
I went online have a grasp of what EOF is, but I don't know what its cause could be, when it's about a DB that I can query with no hassle using the very same query
For the record, the query is:
mYsql = "select emp.name, emp.email, emp.off_duty, emp.jobtitle_id,
emp.jobtitle, mgr.name, mgr.email from staff.Staff emp " & _
"join staff.Staff mgr on emp.manager_staff_id = mgr.id where
emp.manager_staff_id in (" & List & ");"
And in Workbench 6.3 runs just fine. Ah, the ODBC driver tests also succeeded.
A big thank you in advance, to whomever can give me a good hint. I'm lost :-/
Alessandro
| |
doc_626
|
Each city is displayed as a point but I want to name it and I couldn't find any way to do so.
Also, I would like to set style for name as in font-size, color, font-weight.
Please let me know.
Edit:
Below is a code snippet, I have city name in string currCity and it's location in a list of Double values(it just has 2 values, one is x' axis and other is y' axis). By using this location, I am able to plot the point but don't know how to name it. Basically I have a map for all cities where key is city name(unique in my case) and value is a list of cordinates. I am iterating over each key
String currCity = currEntry.getKey();
List<Double> currLocationList = currEntry.getValue();
stroke(255);
ellipse(currLocationList.get(0).intValue(), currLocationList.get(1).intValue(), w, h);
//w, h is width and height of circle (I am setting as just 1 to draw a point)
A: Questions like these are best answered by the Processing reference.
I want to name it and I couldn't find any way to do so.
You can display text using the text() function.
Also, I would like to set style for name as in font-size, color, font-weight.
See the textSize() function, the fill() and stroke() functions, and the various Typography functions.
| |
doc_627
|
I tried using the onTouchEvent() but couldn't stop the movement of the bar and setting manually the seekBar.setProgress() but it only jumps to that point and continue moving with the finger.
sb1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
sb1.setMax(Integer.parseInt(et.getText().toString()));
if (progress >= Integer.parseInt(et.getText().toString()) - sb2.getProgress() - sb3.getProgress())
sb1.setProgress(progress);
tv1.setText(String.valueOf(progress));
}
});
sb2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
sb2.setMax(Integer.parseInt(et.getText().toString()));
if (progress >= Integer.parseInt(et.getText().toString()) - sb1.getProgress() - sb3.getProgress())
sb2.setProgress(progress);
tv2.setText(String.valueOf(progress));
}
});
please help
A: You have
if (progress >= Integer.parseInt(et.getText().toString()) - sb2.getProgress() - sb3.getProgress())
sb1.setProgress(progress);
Inside your sb1 change listener. But that doesn't really make sense, because progress is already the progress of sb1. I think you should change this:
sb1.setProgress(progress);
To:
sb1.setProgress(Integer.parseInt(et.getText().toString()) - sb2.getProgress() - sb3.getProgress());
The value I got for that progress was from your if condition. Basically when the progress is greater than that value, you just set it to the value. So this way, it cannot be dragged past that point.
Do the same thing for your other listeners as well.
A: Disable the seekbar object after you have reached the desired progress:
sb1.setEnable (false)
| |
doc_628
|
var json = {
"id": "123456",
"cost_name":"john",
"line_item":[{
"item_name":"table", "quantity":"1", "properties":[{
"color":"black", "style":"rustic"
}]},
{
"item_name":"chair", "quantity":"3", "properties":[{
"color":"white", "style":"modern"
}]}],
"address":"123_street"
}
I need to get the item_name and quantity of each line_item and I also need the color and style of each
I'm receiving this JSON from a webhook so the order is never the same.
ADDED CONTEXT: (@Taineke's request)
I'm trying to write this to a google sheet with apps script here is my code.
function doPost(e) {
var ss = SpreadsheetApp.getActiveSheet();
var data = JSON.parse(e.postData.contents);
//extract data here
var I= item_name;
var Q = quantity;
var C = color;
var S = style;
ss.appendRow([I,Q,C,S])
}
HERE IS UPDATED e.postData.contents (that @Tanaike) requested from a test webhook
{"id":3175309607101,"email":"sample@sample.com","closed_at":null,"created_at":"2021-01-05T21:35:06-05:00","updated_at":"2021-01-05T21:35:08-05:00","number":1586,"note":"","token":"3491883c672f110eaab82f8dd8080052","gateway":null,"test":false,"total_price":"0.00","subtotal_price":"0.00","total_weight":0,"total_tax":"0.00","taxes_included":false,"currency":"USD","financial_status":"paid","confirmed":true,"total_discounts":"18.00","total_line_items_price":"18.00","cart_token":"a3c9cb049e2f631a8393cf37547623e2","buyer_accepts_marketing":false,"name":"#2586","referring_site":"","landing_site":"\/","cancelled_at":null,"cancel_reason":null,"total_price_usd":"0.00","checkout_token":"11d27a9399b514cb6ba246a3fffc7b23","reference":null,"user_id":null,"location_id":null,"source_identifier":null,"source_url":null,"processed_at":"2021-01-05T21:35:02-05:00","device_id":null,"phone":null,"customer_locale":"en","app_id":580111,"browser_ip":"172.58.238.224","client_details":{"accept_language":"en-US,en;q=0.9","browser_height":657,"browser_ip":"172.58.238.224","browser_width":1349,"session_hash":null,"user_agent":"Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/87.0.4280.88 Safari\/537.36"},"landing_site_ref":null,"order_number":2586,"discount_applications":[{"type":"discount_code","value":"100.0","value_type":"percentage","allocation_method":"across","target_selection":"all","target_type":"line_item","code":"adina"}],"discount_codes":[{"code":"adina","amount":"18.00","type":"percentage"}],"note_attributes":[{"name":"Checkout-Method","value":"pickup"},{"name":"Pickup-Location-Id","value":"105225"},{"name":"Pickup-Location-Company","value":"Evergreen Monsey"},{"name":"Pickup-Location-Address-Line-1","value":"59 NY-59"},{"name":"Pickup-Location-City","value":"Monsey"},{"name":"Pickup-Location-Region","value":"New York"},{"name":"Pickup-Location-Postal-Code","value":"10952"},{"name":"Pickup-Location-Country","value":"United States"}],"payment_gateway_names":[],"processing_method":"free","checkout_id":18478127907005,"source_name":"web","fulfillment_status":null,"tax_lines":[],"tags":"","contact_email":"sample@sample.com","order_status_url":"https:\/\/labelitlabels.com\/26375225421\/orders\/3491883c672f110eaab82f8dd8080052\/authenticate?key=46788d0320dc9961fed8c81630484581","presentment_currency":"USD","total_line_items_price_set":{"shop_money":{"amount":"18.00","currency_code":"USD"},"presentment_money":{"amount":"18.00","currency_code":"USD"}},"total_discounts_set":{"shop_money":{"amount":"18.00","currency_code":"USD"},"presentment_money":{"amount":"18.00","currency_code":"USD"}},"total_shipping_price_set":{"shop_money":{"amount":"0.00","currency_code":"USD"},"presentment_money":{"amount":"0.00","currency_code":"USD"}},"subtotal_price_set":{"shop_money":{"amount":"0.00","currency_code":"USD"},"presentment_money":{"amount":"0.00","currency_code":"USD"}},"total_price_set":{"shop_money":{"amount":"0.00","currency_code":"USD"},"presentment_money":{"amount":"0.00","currency_code":"USD"}},"total_tax_set":{"shop_money":{"amount":"0.00","currency_code":"USD"},"presentment_money":{"amount":"0.00","currency_code":"USD"}},"line_items":[{"id":9102143324349,"variant_id":31929214402637,"title":"Bold Monogram","quantity":30,"sku":"L21","variant_title":"2\"*2\" $0.60","vendor":"Label It Labels","fulfillment_service":"manual","product_id":4374255960141,"requires_shipping":true,"taxable":true,"gift_card":false,"name":"Bold Monogram - 2\"*2\" $0.60","variant_inventory_management":null,"properties":[{"name":"Shape","value":"Square Shape"},{"name":"Choose Background","value":"#030000"},{"name":"Initial","value":"D"},{"name":"_font size Initial","value":"300.00"},{"name":"Choose Text Color","value":"White"},{"name":"Spell Name","value":"DREW FAMILY"},{"name":"_font size Spell Name","value":"33.00"},{"name":"Additional Text (optional)","value":"dairy cholov yisroel"},{"name":"_font size Additional Text (optional)","value":"12.00"},{"name":"_6","value":"PROOF"},{"name":"_Preview","value":"https:\/\/cdn.shopify.com\/s\/files\/1\/0263\/7522\/5421\/uploads\/23b9fb4ba8eb01b7ff717d39d9672c2d.png?format=png\u0026png"},{"name":"_pdf","value":"https:\/\/cdn.shopify.com\/s\/files\/1\/0263\/7522\/5421\/uploads\/5c0c23d462aa998831b0f79aabd0b9eb.pdf"},{"name":"_pplr_preview","value":"_Preview"},{"name":"_ZapietId","value":"a3c9cb049e2f631a8393cf37547623e2"}],"product_exists":true,"fulfillable_quantity":30,"grams":0,"price":"0.60","total_discount":"0.00","fulfillment_status":null,"price_set":{"shop_money":{"amount":"0.60","currency_code":"USD"},"presentment_money":{"amount":"0.60","currency_code":"USD"}},"total_discount_set":{"shop_money":{"amount":"0.00","currency_code":"USD"},"presentment_money":{"amount":"0.00","currency_code":"USD"}},"discount_allocations":[{"amount":"18.00","discount_application_index":0,"amount_set":{"shop_money":{"amount":"18.00","currency_code":"USD"},"presentment_money":{"amount":"18.00","currency_code":"USD"}}}],"duties":[],"admin_graphql_api_id":"gid:\/\/shopify\/LineItem\/9102143324349","tax_lines":[{"title":"NJ State Tax","price":"0.00","rate":0.06625,"price_set":{"shop_money":{"amount":"0.00","currency_code":"USD"},"presentment_money":{"amount":"0.00","currency_code":"USD"}}}],"origin_location":{"id":1809674076237,"country_code":"US","province_code":"NJ","name":"Label It Labels.","address1":"155 Pressburg Ln","address2":"","city":"Lakewood","zip":"08701"}}],"fulfillments":[],"refunds":[],"total_tip_received":"0.0","original_total_duties_set":null,"current_total_duties_set":null,"admin_graphql_api_id":"gid:\/\/shopify\/Order\/3175309607101","shipping_lines":[{"id":2654542987453,"title":"Pick up in Lakewood only","price":"0.00","code":"Pick up in Lakewood only","source":"shopify","phone":null,"requested_fulfillment_service_id":null,"delivery_category":null,"carrier_identifier":null,"discounted_price":"0.00","price_set":{"shop_money":{"amount":"0.00","currency_code":"USD"},"presentment_money":{"amount":"0.00","currency_code":"USD"}},"discounted_price_set":{"shop_money":{"amount":"0.00","currency_code":"USD"},"presentment_money":{"amount":"0.00","currency_code":"USD"}},"discount_allocations":[],"tax_lines":[]}],"billing_address":{"first_name":"John","address1":"123 street","phone":"(234) 567-8901","city":"Any City","zip":"08701","province":"New Jersey","country":"United States","last_name":"Smith","address2":"","company":null,"latitude":40.0963651,"longitude":-74.2067389,"name":"John Smith","country_code":"US","province_code":"NJ"},"shipping_address":{"first_name":"John","address1":"123 street","phone":"(234) 567-8901","city":"Any City","zip":"08701","province":"New Jersey","country":"United States","last_name":"Smith","address2":"","company":null,"latitude":40.0963651,"longitude":-74.2067389,"name":"John Smith","country_code":"US","province_code":"NJ"},"customer":{"id":4602994983101,"email":"sample@sample.com","accepts_marketing":false,"created_at":"2021-01-05T21:31:39-05:00","updated_at":"2021-01-05T21:35:07-05:00","first_name":"John","last_name":"Smith","orders_count":1,"state":"disabled","total_spent":"0.00","last_order_id":3175309607101,"note":null,"verified_email":true,"multipass_identifier":null,"tax_exempt":false,"phone":null,"tags":"","last_order_name":"#2586","currency":"USD","accepts_marketing_updated_at":"2021-01-05T21:31:39-05:00","marketing_opt_in_level":null,"admin_graphql_api_id":"gid:\/\/shopify\/Customer\/4602994983101","default_address":{"id":5617895145661,"customer_id":4602994983101,"first_name":"John","last_name":"Smith","company":null,"address1":"123 street","address2":"","city":"Any City","province":"New Jersey","country":"United States","zip":"08701","phone":"(234) 567-8901","name":"John Smith","province_code":"NJ","country_code":"US","country_name":"United States","default":true}}}
HERE IS MY LATEST CODE. It works but maybe can be cleaner and faster. which I'm having issues with Shopify's 5 second wait time to refiring if no response is recieved.
function doPost(e){
var data = JSON.parse(e.postData.contents);
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var l = data.line_items.length;
for (var i=0;i<l;i++){
var prop = data.line_items[i].properties;
if (prop.length>0){
var pdf = prop.find(function(x) {if(x.name == "_pdf") return x});
if (!pdf){pdf = "Prop not found";}else{pdf = pdf.value};
var shape = prop.find(function(x) {if(x.name.toLowerCase() == "shape") return x});
if (!shape){shape = "Prop not found";}else{shape = shape.value};
}else{
var pdf = "N/A"
var shape = "N/A"
};
var count = "Item "+ (i+1) + " of " + l;
var qty = data.line_items[i].quantity;
var title = data.line_items[i].title;
var id = data.id.toString();
var email = data.email;
var totalPrice = data.total_price;
var discounts = data.total_discounts;
var acceptAds = data.buyer_accepts_marketing;
var orderStatus = data.order_status_url;
var addr = data.shipping_address.address1;
var city = data.shipping_address.city;
var state = data.shipping_address.province;
var zip = data.shipping_address.zip;
var phone = data.shipping_address.phone;
var firstName = data.shipping_address.first_name;
var lastName = data.shipping_address.last_name;
var orderNum = data.name;
var d = new Date(data.created_at).toLocaleString();
ss.appendRow([d,orderNum,email,count,title,shape,qty,totalPrice,discounts,pdf,firstName,lastName,addr,city,state,zip,phone,orderStatus]);
if (pdf != "N/A"){
if (pdf != "Prop not found"){
var res = UrlFetchApp.fetch(pdf);
var blob = res.getBlob();
var createFile = DriveApp.getFolderById('xxxxxxxxxxxxxxxx-').createFile(blob.getAs('application/pdf'));
var fileName = orderNum + " " + qty;
createFile.setName(fileName);
}}
};
}
A: I thought that from your title, in your json, = might be : in the value. If it's so, how about the following sample script?
Sample script:
var json = {
"id": 123456,
"cost_name": "john",
"line_item": [
{
"item_name": "table",
"quantity": 1,
"properties": [
{
"color": "black",
"style": "rustic"
}
]
},
{
"item_name": "chair",
"quantity": 3,
"properties": [
{
"color": "white",
"style": "modern"
}
]
}
],
"address": "123_street"
};
const res = json.line_item.map(({item_name, quantity, properties: [{color, style}]}) => [item_name, quantity, color, style]);
console.log(res)
Note:
*
*Unfortunately, I cannot understand about the result format you expect. So in above sample script, each values are put in an array. If above result format is not the result you expected, can you provide the sample output values? By this, I would like to modify it.
*In this case, please enable V8 runtime at the script editor.
Reference:
*
*map()
Added 1:
From your updated question, I understood that data is json in your above script and you want to append the values of item_name, quantity, color, style to the active sheet in Google Spreadsheet. For this, how about the following modification?
Modified script:
function doPost(e) {
var data = JSON.parse(e.postData.contents);
var res = data.line_item.map(({item_name, quantity, properties: [{color, style}]}) => [item_name, quantity, color, style]);
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(sheet.getLastRow() + 1, 1, res.length, res[0].length).setValues(res);
}
Note:
*
*It seems that you are using Web Apps. In this case, when the script of Web Apps is modified, please redeploy the Web Apps as new version. By this, the latest script is reflected to the Web Apps. Please be carful this.
Added 2:
From your updated question, it was found that your additional value is different from your initial question. And, I understood that you wanted to retrieve the values of Shape and _pdf in properties from the added value. So in this case, I would like to modify the script as follows.
Sample script:
In this case, data is your added values. Please be careful this.
function doPost(e) {
var data = JSON.parse(e.postData.contents);
const checkNames = ["Shape", "_pdf"];
const res = data.line_items.reduce((ar, {properties}) => {
if (properties) {
properties.forEach(({name, value}) => {
if (checkNames.includes(name)) ar.push([name, value]);
});
}
return ar;
}, []);
if (res.length > 0) {
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(sheet.getLastRow() + 1, 1, res.length, res[0].length).setValues(res);
}
}
*
*In this script, when the values of properties are not existing, setValues is not run. By this, no error occurs.
Note:
*
*In this script, your added value is used. So when the structure of value is different, the script might not be able to be used. So please be careful this.
*It seems that you are using Web Apps. In this case, when the script of Web Apps is modified, please redeploy the Web Apps as new version. By this, the latest script is reflected to the Web Apps. Please be carful this.
| |
doc_629
|
T(n) = 2T(n/2) + sqrt(n), where T(1) = 1, and n = 2^k
T(n) = 2[2T(n/4) + sqrt(n/2)] + sqrt(n) = 2^2T(n/4) + 2sqrt(n/2) + sqrt(n)
T(n) = 2^2[2T(n/8) + sqrt(n/4)] + 2sqrt(n/2) + sqrt(n)
= 2^3T(n/8) + 2^2sqrt(n/4) + 2sqrt(n/2) + sqrt(n)
In general
T(n) = 2^kT(1) + 2^(k-1) x sqrt(2^1) + 2^(k-2) x sqrt(2^2) + ... + 2^1 x sqrt(2^(k-1)) + sqrt(2^k)
Is this right so far? If it is, I can not figure out how to simplify it and reduce it down to a general formula.
I'm guessing something like this? Combining the terms
= 1 + 2^(k-(1/2)) + 2^(k-(2/2)) + 2^(k-(3/2)) + ... + 2^((k-1)/2) + 2^(k/2)
And this is where I'm stuck. Maybe a way to factor out a 2^k?
Any help would be great, thanks!
A: You're half way there.
The expression can be simplified to this:
A: If you want just a big-O solution, then Master Theorem is just fine.
If you want a exact equation for this, a recursion tree is good. like this:
The right hand-side is cost for every level, it's easy to find a general form for the cost, which is sqrt((2^h) * n). Then, sum up the cost you could get T(n).
*
*According to Master Theorem, it's case 1, so O(n).
*According to Recursion Tree, the exact form should be sqrt(n)*(sqrt(2n)-1)*(sqrt(2)+1), which corresponds with the big-O notation.
EDIT:
The recursion tree is just a visualized form of the so called backward substitution. If you sum up the right hand side, i.e. the cost, you could get the generalized form of T(n). All these methods could found in introduction to algorithm
| |
doc_630
|
Environment: Mojarra 2.2.0 (GlassFish 4.0), NetBeans 7.3.1, JDK 7
Steps to reproduce:
*
*create a new "Java EE 7 Web" project with JavaServer Faces and choose JSF 2.2 server library
*in index.html, select the HTML body text ("Hello from Facelets") and refactor into a composite component
Example source code:
index.html
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ez="http://xmlns.jcp.org/jsf/composite/ezcomp">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<ez:test/>
</h:body>
</html>
test.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:cc="http://xmlns.jcp.org/jsf/composite">
<!-- INTERFACE -->
<cc:interface>
</cc:interface>
<!-- IMPLEMENTATION -->
<cc:implementation>
Hello from Facelets
</cc:implementation>
</html>
Actual HTML output:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"><head id="j_idt2">
<title>Facelet Title</title></head><body><html xmlns="http://www.w3.org/1999/xhtml">
<!-- INTERFACE -->
<!-- IMPLEMENTATION -->
Hello from Facelets
</html></body>
</html>
This is not valid HTML as there is another <html> ... </html> present for the composite component. Is there an error in my JSF code?
A: Try using
<ui:component
xmlns="http://www.w3.org/1999/xhtml"
.....
>
See an example here: http://balusc.blogspot.co.uk/2013/01/composite-component-with-multiple-input.html
| |
doc_631
|
This however is a library that uses the REST capabilities of Neo4j. Now I am wondering if this isn't a performance issue compared to for example something like the Java JDBC-drivers (http://neo4j.com/developer/java/).
The applications I will be developing will be real-time and should be performant (noticable delays are not acceptable).
| |
doc_632
|
Now my question: Every time the user wants to import the database, he can import a SqlServerCe file (old backup) or SQLite (a new backup). How can I detect, which DbProviderFactory is needed for my DbConnection?
Old Method (needs an update)
/// <summary>
/// Verifies the db if it is not corrupt! If the return value is <see cref="Nullable"/>, the DB is corrupt!
/// </summary>
/// <returns><see cref="Array"/> of <see cref="int"/>. The 1. index is Components.Count(), the 2 index is the Recipes.Count()!!</returns>
[CanBeNull]
public static int[] ImportDB_Verify()
{
try
{
SqlCeProviderFactory provider = new SqlCeProviderFactory();
SqlCeConnectionStringBuilder connectionStringBuilder = new SqlCeConnectionStringBuilder
{
DataSource = "Path/to/foo.db"
};
int[] val = new int[2];
using (DbConnection dbConnection = provider.CreateConnection())
{
dbConnection.ConnectionString = connectionStringBuilder.ConnectionString;
dbConnection.Open();
using (DbCommand dbCommand = dbConnection.CreateCommand("SELECT Count(*) FROM Components"))
{
val[0] = (int)dbCommand.ExecuteScalar();
}
using (DbCommand dbCommand = dbConnection.CreateCommand("SELECT Count(*) FROM Recipes"))
{
val[1] = (int)dbCommand.ExecuteScalar();
}
}
return val;
}
catch (Exception ex)
{
_Logger.Error(ex);
return null;
}
}
Try Catch "solution"
If there is something better, please let me know!
/// <summary>
/// Verifies the db if it is not corrupt! If the return value is <see cref="Nullable"/>, the DB is corrupt!
/// </summary>
/// <returns><see cref="Array"/> of <see cref="int"/>. The 1. index is components.Count(), the 2 index is the recipes.Count()!!</returns>
[CanBeNull]
public static int[] ImportDB_Verify()
{
int[] val = new int[2];
Exception sqLiteException;
try
{
SQLiteFactory provider = new SQLiteFactory();
SQLiteConnectionStringBuilder connectionStringBuilder = new SQLiteConnectionStringBuilder
{
DataSource = Core.CommonAppDataPath + "tmp.HTdb"
};
using (DbConnection dbConnection = provider.CreateConnection())
{
dbConnection.ConnectionString = connectionStringBuilder.ConnectionString;
dbConnection.Open();
using (DbCommand dbCommand = dbConnection.CreateCommand("SELECT Count(*) FROM components;"))
{
val[0] = (int)dbCommand.ExecuteScalar();
}
using (DbCommand dbCommand = dbConnection.CreateCommand("SELECT Count(*) FROM recipes;"))
{
val[1] = (int)dbCommand.ExecuteScalar();
}
}
return val;
}
catch (Exception ex)
{
sqLiteException = ex;
}
try
{
SqlCeProviderFactory provider = new SqlCeProviderFactory();
SqlCeConnectionStringBuilder connectionStringBuilder = new SqlCeConnectionStringBuilder
{
DataSource = Core.CommonAppDataPath + "tmp.HTdb"
};
using (DbConnection dbConnection = provider.CreateConnection())
{
dbConnection.ConnectionString = connectionStringBuilder.ConnectionString;
dbConnection.Open();
using (DbCommand dbCommand = dbConnection.CreateCommand("SELECT Count(*) FROM Components;"))
{
val[0] = (int)dbCommand.ExecuteScalar();
}
using (DbCommand dbCommand = dbConnection.CreateCommand("SELECT Count(*) FROM Recipes;"))
{
val[1] = (int)dbCommand.ExecuteScalar();
}
}
return val;
}
catch (Exception ex)
{
_Logger.Error(ex, $"Error while verifying the database. The SQLite Exception: {sqLiteException}");
return null;
}
}
A: Open the file and read its "magic number". SQLite databases start with the ASCII string "SQLite format", SQL Server CE .SDF files start with 0x01 0x0F 0x00 0x00 as far as I can find, that is, if they look like .MDF files.
So something like this:
byte[] buffer = new byte[4];
using (var fileStream = File.OpenRead(databasefile))
{
fileStream.Read(buffer, 0, 4);
}
if (buffer[0] == 83 // S
&& buffer[1] == 81 // Q
&& buffer[2] == 76 // L
&& buffer[3] == 105) // i
{
// SQLite
}
else
{
// Assume SQL Server CE
}
Note that a user could still feed your code a text file that happens to begin with "SQLi" but isn't an SQLite file, so you cannot and should not remove your exception handling code using this approach.
A: Using @CodeCaster's answer:
public enum DBType { SQLite, SQLServerCe };
public static DBType GetDatabaseType(string filename)
{
byte[] buffer = new byte[4];
using (var fileStream = File.OpenRead(databasefile))
{
fileStream.Read(buffer, 0, 4);
}
if (buffer[0] == 83 // S
&& buffer[1] == 81 // Q
&& buffer[2] == 76 // L
&& buffer[3] == 105) // i
{
return DBType.SQLite;
}
else
{
return DBType.SQLServerCe;
}
}
public static int[] ImportDB_Verify()
{
string dbFilePath = "someDatabaseFile"
DBType detectedType = GetDatabaseType(dbFilePath);
if(detectedType == DBType.SQLite)
return VerifySQLiteDb(dbFilePath);
else
return VerifySQLServerCeDb(dbFilePath);
}
private static int[] VerifySQLiteDb(string dbFilePath)
{
//...
// exception handling etc.
}
private static int[] VerifySQLServerCeDb(string dbFilePath)
{
//...
// exception handling etc.
}
| |
doc_633
|
By inactivity, I mean that TCP connection is not being used for a certain amount of time.
I thought that I will use connection handlers for that purpose.
private val webClient = webClientBuilder
.build()
.mutate()
.filters(MutableList<ExchangeFilterFunction>::clear)
.clientConnector(
ReactorClientHttpConnector(
HttpClient.from(
TcpClient.create()
.option(CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT)
.doOnConnected { connection ->
connection
.addHandlerLast(
IdleStateHandler(
SOCKET_INACTIVITY_TIMEOUT,
SOCKET_INACTIVITY_TIMEOUT,
0
)
)
.addHandlerLast(CloseIdleConnectionHandler())
.addHandlerLast(ReadTimeoutHandler(READ_TIMEOUT))
.addHandlerLast(WriteTimeoutHandler(WRITE_TIMEOUT))
}
)
)
)
.build()
companion object {
const val SOCKET_INACTIVITY_TIMEOUT = 20
const val CONNECT_TIMEOUT = 5_000
const val READ_TIMEOUT = 5
const val WRITE_TIMEOUT = 5
}
private class CloseIdleConnectionHandler : ChannelDuplexHandler() {
override fun userEventTriggered(ctx: ChannelHandlerContext, evt: Any) {
if (evt is IdleStateEvent) {
ctx.disconnect()
}
}
}
The problem is that CloseIdleConnectionHandler does not get called after SOCKET_INACTIVITY_TIMEOUT.
Am I doing something wrong or I misuse IdleStateHandler?
A: You can use the ConnectionProvider.builder to configure these settings
ConnectionProvider connectionProvider =
ConnectionProvider.builder("my-connection-pool")
.maxConnections(100)
.pendingAcquireTimeout(Duration.ofMillis(100))
// this is the setting you're after
.maxIdleTime(Duration.ofMillis(1000))
.maxLifeTime(Duration.ofMillis(5000))
.build()
You would then pass in your connection provider in when constructing your tcp client
TcpClient.create(connectionProvider)
.options(..... // other custom configuration
See javadoc
| |
doc_634
|
A: Well on the surface it doesn't make your site less secure, as you are just requesting data from an external compromised data source.
However, if the API data source has been comprised the hackers could send data via the API which you might save to your database or display on your site, so hackers could potentially insert malicious scripts into your database or cause some reputational damage by sending all sorts of crap data (swear words, advertise porn sites etc) which you will display on your site.
In general the more complexity you add to any system (real life or virtual), the more ways it can be exploited, so it is always good to do some homework before you introduce any library or dependencies to your codebase.
EDIT
To add the above, OWASP do a great job by laying out all the risks with using a compromised API.
https://www.owasp.org/index.php/Top_10_2017-A9-Using_Components_with_Known_Vulnerabilities
A: A targeted attack would be possible but unlikely. When using an API you are making requests to some server, which inherently gives that server information on who you are in order to send a response back. With that, a hacker could use that information to attempt and send an attack to your address. This could be done by either using your address for an external program/script, or by sending malicious information back as a response instead of what was intended.
This entire scenario though is highly unlikely to ever occur though for many reasons. The main reason is, why would a hacker targeting specifically you go through trouble of taking control of another entity, their API, then attack you? It'd be much more likely for the hacker to attempt to gain access to the API owner's database and exploit information held there, rather than target people using their API.
So yes, if a hacker gained access to an API you use, there exists a chance they could make a targeted attack on you as well. Mind you that this chance exists with any foreign entity you connect with. Providing an entity information about who you are and where you are will always create some chance of an attack.
| |
doc_635
|
I've already set npm config set "strict-ssl" false -g and export NODE_TLS_REJECT_UNAUTHORIZED=0 but now it's failing with Error: Request failed with status code 403 after entering username and password.
Any help is appreciated. Thanks!.
| |
doc_636
|
if ( !empty ( $_POST ) ) {
$location_id = $_POST['restaurant_id'];
$content = $_POST['content'];
$query = "INSERT INTO restaurant_reviews
(location_id, text1, review_date)
VALUES
('$location_id', '$content', NOW())";
$execute = mysqli_query($dbc, $query);
print_r($_POST);
}
The issue is that when even fairly small amounts of text are submitted in the form (by small amounts I mean a max of 2/3 normal paragraphs) the record is not generated in MySQL. The form submits successfully every time with a few words of text in the tinyMCE field.
Irrespective of the amount of text submitted in the form, it all appears in the post array when it's echoed out by the print_r function, it just doesn't get as far as the DB. The text1 column is type longtext so sure this isn't the problem. Any ideas?
A: I recommend you use
$connection = mysqli_connect("database_host", "username", "password", "database_name");
$id = (int)mysqli_real_escape_string($connection, $_POST['restaurant_id']);
$content = mysqli_real_escape_string($connection, $_POST['content']);
to escape characters that may interfere with the SQL statement
| |
doc_637
|
Error:Gradle: Error converting bytecode to dex:
Cause: com.android.dex.DexException: Multiple dex files define Landroid/databinding/DataBindingComponent;
I assumed that there was some dependency errors and listed dependencies like this:
.\gradlew app:dependencies
And there was the strange thing: I am using databinding version 1.0-rc4, but in the listed dependencies there was 1.0-rc3:
default - Configuration for default artifacts.
+--- com.android.databinding:library:1.0-rc3
| +--- com.android.databinding:baseLibrary:1.0-rc3
| \--- com.android.support:support-v4:21.0.3 -> 23.1.1
| \--- com.android.support:support-annotations:23.1.1
+--- com.android.databinding:adapters:1.0-rc3
| \--- com.android.databinding:library:1.0-rc3 (*)
+--- com.android.support:appcompat-v7:23.1.1
| \--- com.android.support:support-v4:23.1.1 (*)
+--- com.android.support:recyclerview-v7:23.1.1
| +--- com.android.support:support-annotations:23.1.1
| \--- com.android.support:support-v4:23.1.1 (*)
+--- com.google.dagger:dagger:2.0
| \--- javax.inject:javax.inject:1
\--- com.trello:rxlifecycle-components:0.4.0
+--- com.trello:rxlifecycle:0.4.0
| +--- com.jakewharton.rxbinding:rxbinding:0.3.0
| | +--- com.android.support:support-annotations:23.1.0 -> 23.1.1
| | \--- io.reactivex:rxjava:1.0.14 -> 1.0.16
| \--- io.reactivex:rxjava:1.0.16
+--- com.android.support:appcompat-v7:23.1.1 (*)
\--- io.reactivex:rxjava:1.0.16
provided - Classpath for only compiling the main sources.
+--- com.android.databinding:compiler:1.0-rc4
| \--- com.android.databinding:baseLibrary:1.0-rc4
\--- javax.annotation:javax.annotation-api:1.2
Where did this 1.0-rc3 come from? There is no such string "rc3" in my whole project (except in generated dex-cache files).
UPD:
I think this is an android gradle-plugin issue, because same code works with gradle 1.5 but fails with gradle 2.0.0-beta2 and 2.0.0-beta4.
UPD2:
Solved the problem.
Project was relatively old and android-databinding plugin grown from beta since gradle 1.5.0-beta1
Now to enable databinding you should only add
dataBinding {
enabled = true
}
in your android{} section.
So if you face such problem, make sure you deleted these strings from your build.gradle files:
1) apply plugin: 'com.android.databinding'
2) classpath 'com.android.databinding:dataBinder:1.0-rc4'
3) apt 'com.android.databinding:compiler:1.0-rc4'
A: Solved the problem.
Project was relatively old and android-databinding plugin grown from beta since gradle 1.5.0-beta1
Now to enable databinding you should only add
dataBinding {
enabled = true
}
in your android{} section.
So if you face such problem, make sure you deleted these strings from your build.gradle files:
1) apply plugin: 'com.android.databinding'
2) classpath 'com.android.databinding:dataBinder:1.0-rc4'
3) apt 'com.android.databinding:compiler:1.0-rc4'
| |
doc_638
|
$.post(filterServiceUrl, data, onFilterProductsSuccess, "json");
Controller is getting called successfully
public @ResponseBody HomeLoanFilterServiceResponseDto filter(FilterModel model, ModelMap modelMap) {
List<LoanDetailsDto> loans = new ArrayList<LoanDetailsDto>();
LoanFilterServiceResponseDto response = new LoanFilterServiceResponseDto();
response.setSuccess(true);
response.setErrorMessage("");
//Business Logic
response.setLoans(loans);
return response
}
After getting the response making call to function
function onFilterProductsSuccess(serviceResponse) {
alert("serviceResponse.IsSuccess: "+ serviceResponse.isSuccess)
};
The function is showing alert box serviceResponse.IsSuccess: undefined
A: You can't access to an private attribute directly. Your method should be something like this:
public boolean isSuccess(){
return this.isSuccess;
}
So if you want to check if the response is succesful, you should add the () -call the public method which access the private one-
alert("serviceResponse.IsSuccess: "+ serviceResponse.isSuccess())
A: This is the Response class.
public class LoanFilterServiceResponseDto {
private boolean isSuccess;
private String errorMessage;
//private List<LoanDetailsDto> loans; //getteres & setters
//
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean success) {
isSuccess = success;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
This is the js method.
function onFilterProductsSuccess(serviceResponse) {
alert("serviceResponse.IsSuccess: "+ serviceResponse.isSuccess())
};
A: your return entity is
HomeLoanFilterServiceResponseDto
,but actually you return this
LoanFilterServiceResponseDto
try to change another class
| |
doc_639
|
E.g The page attributes area on the right when editing a page, is it possible to change the wording of "Parent", "Template" and "Order" and also add a little bit of help text.
The titles and help is all a bit techy, a lot of the people that will be using the CMS will be very basic users.
Ideally I'd like a plugin to make things a bit easier.
A: You would have to change the relevant admin pages in the backend.
Or just an idea, create a new localization for the changes you wish to see, as most text in the backend are output using the localization function.
A: Unfortunately I've yet to see any ability to fully customize the default backend (without hacking core). This is one area that still bothers me about WP, especially when custom themes and forms for the admin feature are so well implemented in other systems like Drupal and Expression Engine.
With WP 3.x there are some hooks (filters) for some of the admin panel. A quick google will reveal instructions on a variety of ways.
http://www.thinkoomph.com/thinking/2010-06/customizing-wordpress-admin/
Check out the 'White Label' plugin (> 2.8)
http://wordpress.org/extend/plugins/white-label-cms/
| |
doc_640
|
CORS is enabled in the Spring Boot and I use axios to send requests to the Spring Boot API.
When calling '/login', Spring Boot security kicks in and produces a JWT
token, which is passed back to ReactJS as the Authorization header. The
issue is that this header does not appear in the response received in the
React app then processing block. It does show correctly in the Developer
Tools Network tab. Below is the relevant code:
axios.post("http://localhost:8080/login", LoginRequest)
.then(response => {console.log("RRR ", response)});
The console output is as follows:
{data: "", status: 200, statusText: "", headers: {…}, config: {…}, …}
config:
adapter: ƒ xhrAdapter(config)
data: "{"username":"test@test.com","password":"test$2"}"
headers:
Accept: "application/json, text/plain, */*"
Content-Type: "application/json;charset=utf-8"
__proto__: Object
maxContentLength: -1
method: "post"
timeout: 0
transformRequest: {0: ƒ}
transformResponse: {0: ƒ}
url: "http://localhost:8080/login"
validateStatus: ƒ validateStatus(status)
xsrfCookieName: "XSRF-TOKEN"
xsrfHeaderName: "X-XSRF-TOKEN"
__proto__: Object
data: ""
headers: {pragma: "no-cache", cache-control: "no-cache, no-store, max-age=0, must-revalidate", expires: "0"}
request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: ""
What am I missing?
| |
doc_641
|
Refused to execute inline script because it violates the following
Content Security Policy directive: "default-src 'self'". Note that
'script-src' was not explicitly set, so 'default-src' is used as a
fallback.
Please note that Javascript is executed well if it's not an inline script.
For example, with an HTML file like below:
<htnl>
<head>
<script type="text/javascript" src="abc.js"></script>
</head>
<body>
<script type="text/javascript">
alert("This is inline script");
</script>
</body>
</html>
Script in abc.js is executed properly, but the inline script is refused to execute.
I understand that the webview refuses to execute inline Javascript due to "Contect Security Policy". But the webpage need to execute those inline scripts to function properly and I cannot make any change on the webpage.
This problem only KitKat (Android 4.4)
Is there any way to overcome this problem, modify "Content Security Policy" to allow inline script to be executed.
A: According to information from WebView developers, injected javascripts run in the host page itself, not in an isolated world as it is with Chromium extensions. This is why they should pass common security checkups imposed by Content Security Policy header (if it exists). As a result, it can be impossible to inject a script as a file via src attribute or inline, or in both ways, depending from the header directive (for example, if unsafe-inline is mentioned, you'll be unable to inject a script tag with inline code).
The workaround is to use loadUrl or evaluateJavascript methods to execute javascript code "as is", without adding a script tag. For example:
webview.loadUrl("javascript:alert('hello')");
will be executed successfully.
For Android 4.4 and up it's recommended to use the new evaluateJavascript method, because loadUrl has a side effect when your app is targeted to one of these newer Android versions (and I think this is the case for most projects nowadays): if the script returns a value - it will replace DOM content of the current page. On targets prior 4.4, both methods are the same except for the possibility to return a value via optional callback in evaluateJavascript.
One could think of other tricks but this should be enough to solve your problems.
| |
doc_642
|
My code:
package selenium_webdriver_api;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.ChromeDriverManager;
public class Topic_29_ManageBrowserVersion {
private WebDriver driver;
@BeforeClass
public static void setupClass() {
ChromeDriverManager.getInstance().version("2.33").setup();
// Or: ChromeDriverManager.getInstance().setup();
}
@Before
public void setupTest() {
driver = new ChromeDriver();
}
@After
public void teardown() {
if (driver != null) {
driver.quit();
}
}
@Test
public void test() {
driver.get("https://github.com/bonigarcia/webdrivermanager");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
}
A: WebDriverManager depends on several libraries such as slf4j-api, commons-io, gson, among others (see its pom.xml for the complete list). If you are using WebDriverManager without the help of a build tool (e.g. Maven, Gradle) you need to resolve these dependencies manually. The other option is to generate a fat jar from the source, for example using the maven-assembly-plugin (info here) or maven-shade-plugin (info here).
| |
doc_643
|
System: Windows 7, 64b
What i do?
1) Installed Python 2.7.2 (32bits)
2) Installed SetupTools (32 bits)
3) Installed VirtualEnv
E:\APPZ\Console2>C:\Python27\Scripts\easy_install.exe virtualenv
4) Created virtualenv:
E:\APPZ\Console2>virtualenv E:\CODE\wamp\www\AMBIENTES\env
5) Fine, now I created a ".bat" to use my env and put then in C:\Windows.
C:\Windows\python.bat
cmd.exe /k E:\CODE\wamp\www\AMBIENTES\env\Scripts\activate.bat
So far so good
Now I executed the python.bat and installed django:
E:\APPZ\Console2>python
E:\APPZ\Console2>cmd.exe /k E:\CODE\wamp\www\AMBIENTES\env\Scripts\activate.bat
(env) E:\APPZ\Console2>cd E:\CODE\wamp\www\AMBIENTES\Django-1.2.7
(env) E:\CODE\wamp\www\AMBIENTES\Django-1.2.7>python setup.py install
django installed (1.2.7) successfully.
And now, the problem:
(env) E:\CODE\wamp\www\AMBIENTES\Django-1.2.7>E:\CODE\wamp\www\AMBIENTES\env\Scripts\django-admin.py --version
Traceback (most recent call last):
File "E:\CODE\wamp\www\AMBIENTES\env\Scripts\django-admin.py", line 2, in <module>
from django.core import management
ImportError: No module named django.core
(env) E:\CODE\wamp\www\AMBIENTES\Django-1.2.7>
-
Does anyone know what I can do about it?
A: I know this question is old and maybe not actual anymore for author. But as far as it appears at Google's top, I would leave the answer that helped me.
Basically the correct answer is posted for the similar question.
Strictly speaking the wrong Python installation is called when you execute django-admin.py --version. in order to check which Python you use in the case, type ftype Python.File in "command line". If it's not the virtualenv's one, then you could reassociate the default Python:
ftype Python.File="E:\CODE\wamp\www\AMBIENTES\env\Scripts\python.exe" "%1" %*
Or unset the file association (from cmd.exe):
assoc .py=
ftype Python.File=
After you reassociate the .py extension program, you should specify full path to execute Python files:
E:\CODE\wamp\www\AMBIENTES\env\Scripts\python.exe E:\CODE\wamp\www\AMBIENTES\env\Scripts\django-admin.py --version
Or if you want, you could edit virtualenv's activate.bat to put specific .py association, using assoc and ftype command line utils, mentioned above.
A: I believe your problem is that using python setup.py install with the Django source is installing Django in your primary site-packages/dist-packages path instead of that of your virtual environment.
Instead, use pip or easy_install:
$ pip install Django==1.2.7 --OR -- $ easy_install Django==1.2.7
If you can't directly download from PyPi (corporate firewall, etc.) you can use the source you already have by modifying the command slightly:
$ pip install -f file:///E/CODE/wamp/www/AMBIENTES/ Django==1.2.7
(Converted Windows path may need some tweaking. I think that's right, but it's been awhile)
| |
doc_644
|
Can anyone help me with this like edit the dataset then save it and then render updated value into dataset it should not loose on page refresh.
| |
doc_645
|
"Can I do the equivalent of (test ? result : alternative) in Python?"
here's one of the options listed by him,
def if_(test, result, alternative=None):
"If test is true, 'do' result, else alternative. 'Do' means call if callable."
if test:
if callable(result): result = result()
return result
else:
if callable(alternative): alternative = alternative()
return alternative
And here's a usage example.
>>> fact = lambda n: if_(n <= 1, 1, lambda: n * fact(n-1))
>>> fact(6)
720
I understand how this works (I think), but I was just playing with the code, and decided to see what happens when I change the third argument in the definition of 'fact' above to
n * fact(n-1), that is, change it to a non-callable expression. On running it, the interpreter goes into a never ending loop. I have a pretty good idea of why that is happening, that is, the if_ function is returning back the same expression that it is receiving. But what is the type of that expression? What exactly is going on here? I am not looking for a detailed explanation , but just for some pointers to python's evaluation model which might help my understanding.
Thanks!
A: The reason the loop never terminates when you change fact to n * fact(n-1) is that n * fact(n-1) has to evaluate first (as the third argument to if). Evaluating it leads to another call to fact, ad infinitum (since there is no longer any base case to stop it).
Previously, you were passing a function object (lambda), which would not be evaluated until the body of if, and its result would be checked via test.
This is known (I believe) as eager evaluation, where function arguments are evaluated before they are passed to the function. In a lazy-evaluation scheme, the arguments would not be evaluated until they were used in the function body.
| |
doc_646
|
RAILS_ENV=production rails s
Then I go to http://localhost:3000 and the application comes up, but has no styling at all.
I did precompile the assets:
➜ myapp git:(master) ✗ bundle exec rake assets:precompile --trace
Invoke assets:precompile (first_time)
Execute assets:precompile
/Users/me/.rvm/rubies/ruby-1.9.3-p545/bin/ruby /Users/me/.rvm/gems/ruby-1.9.3-p545@myapp/bin/rake assets:precompile:all RAILS_ENV=production RAILS_GROUPS=assets --trace
Invoke assets:precompile:all (first_time)
Execute assets:precompile:all
Invoke assets:precompile:primary (first_time)
Invoke assets:environment (first_time)
Execute assets:environment
Invoke environment (first_time)
Execute environment
Invoke tmp:cache:clear (first_time)
Execute tmp:cache:clear
Execute assets:precompile:primary
Invoke assets:precompile:nondigest (first_time)
Invoke assets:environment (first_time)
Execute assets:environment
Invoke environment (first_time)
Execute environment
Invoke tmp:cache:clear (first_time)
Execute tmp:cache:clear
Execute assets:precompile:nondigest
This works just fine in Safari, can't figure out why Chrome won't load the stuff. I cleared out the browser cache also.
A: In config/environments/production.rb, make sure your application is configured to serve static assets:
config.serve_static_assets = true
By default, Rails assumes that your static assets will be served elsewhere (e.g. Apache, Nginx, etc.)
| |
doc_647
|
Here is my code:
sc.ConnectionString = ("Data Source=localhost\\SQLEXPRESS;Initial Catalog=Steripack;User ID=remote;Password=0925Greg#");
sc.Open();
com.Connection = sc;
com.CommandText = ("INSERT INTO tblOffsite (tagID, Hospital, Driver, datetime) SELECT tagID, Hospital, Driver, datetime FROM tblDelivery");
com.ExecuteNonQuery();
sc.Close();
sc.Open();
com.Connection = sc;
com.CommandText = ("DELETE FROM tblOnStock WHERE tagID = @tagID");
com.ExecuteNonQuery();
sc.Close();
A: Do you mean whatever you have inserted in tblOffsite should be deleted from tblOnStock?
In that case your SQL to delete should be:
DELETE FROM tblOnStock WHERE tagID IN (SELECT tagID FROM tblDelivery)
| |
doc_648
|
Using the instructions here, I downloaded and installed geniatagger and imported in my application.
However, when I try accessing parse functionality, I get the following error.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-25-867eea8ac07f> in <module>
1 my_bytes = "This is a pen.".encode()
2 print(type(my_bytes))
----> 3 x = tagger.parse(my_bytes)
~/anaconda3/envs/systreviewclassifi/lib/python3.6/site-packages/geniatagger_python-0.1-py3.6.egg/geniatagger.py in parse(self, text)
33 results = list()
34
---> 35 for oneline in text.split('\n'):
36 self._tagger.stdin.write(oneline+'\n')
37 while True:
TypeError: a bytes-like object is required, not 'str'
This is the code, I tried.
tagger = GeniaTagger('./geniatagger/geniatagger')
# option1: my_bytes = "This is a pen.".encode()
# option2: my_bytes = b"This is a pen."
# option3: my_bytes = bytes("This is a pen.")
my_bytes = "This is a pen.".encode('utf8')
print(type(my_bytes))
x = tagger.parse(my_bytes)
Currently, I get the above-given error as output. Technically, this should be the output.
>>> print tagger.parse('This is a pen.')
[('This', 'This', 'DT', 'B-NP', 'O'), ('is', 'be', 'VBZ', 'B-VP', 'O'), ('a', 'a', 'DT', 'B-NP', 'O'), ('pen', 'pen', 'NN', 'I-NP', 'O'), ('.', '.', '.', 'O', 'O')]
I will be grateful for any help.
A: It seems that the code is not fully Python 3 compatible.
You pass in a string encoded as bytes, but on line 35 (for oneline in text.split('\n')) the variable text is of type bytes but the argument to .split() ('\n') is a string. That causes the error.
You can reproduce the error in your interpreter like this:
>>> 'asdasd'.encode().split('d')
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
You can try to input a string instead of bytes in tagger.parse(), but no idea if that is going to work.
| |
doc_649
|
@if (isset($returns['Passive'])) //This is where the error is occuring
<ul class="list-group">
<li class="list-group-item"><span>Passive Income</span>
<ul class="list-group">
<li class="list-group-item"><span>Passive: {{ $returns['Passive'] }}</span></li>
</ul>
</li>
</ul>
@endif
I have no idea why it would cause an error, I have used isset on multiple pages before and it has never been an issue. Here is the error I am getting:
ErrorException: Undefined index: Passive (View: /home/unlikem5/public_html/myuladmin/resources/views/misc/paidPositions.blade.php) in /home/unlikem5/public_html/myuladmin/storage/framework/views/fc6ec53af49c1252e1698dacf9ac958b628485d5.php:16
A: Try this command and run again this will defenately solved your issue.
Clear all compiled view files:
php artisan view:clear
php artisan cache:clear
A: Laravel provides blade directives for isset and empty functions. Try this out -
Laravel 5.6 Docs
@isset($records)
// $records is defined and is not null...
@endisset
@empty($records)
// $records is "empty"...
@endempty
| |
doc_650
|
I cannot start the Project via F5:
The Output Window shows 0 errors:
I can see the same behavior when I create a new Blazor-WA project.
I have re-installed the SDK (Microsoft .NET Core SDK v3.1.403) which not solves the problem.
How can I solve this problem?
| |
doc_651
|
The problem I'm having is that I need to include the title of each page before each so you can easily identify which images come below which page. Normally I would just add this in, but the list items al use masonry and are positioned all over the page using some JS so they never appear beside the first image in the list.
I therefore will add the title of the page to every
<li> in the <ul> which will allow the title to run with each image but I don't know how to include this in the wp get attachment image function. Both the_title and wp_title doesn't work inside this loop. apply_filters( 'the_title', $attachment->post_title ); obviously takes the image title, but is there any good to take the page title?
Thanks in advance and hope this made sense,
R
<?php $postslist = get_pages('number=9999&sort_order=DESC&sort_column=post_date&child_of=8');
foreach ($postslist as $post) :
setup_postdata($post); ?>
<ul class="main-projects-list">
<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID,
'orderby' => 'menu_order',
'order' => 'ASC',
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<li class="each-image">';
echo wp_get_attachment_image( $attachment->ID, 'large' );
echo '<p>';
echo apply_filters( 'the_title', $attachment->post_title );
echo '</p></li>';
}
}
?>
</ul>
<?php endforeach; ?>
A: You can try this:
<?php $postslist = get_pages('number=9999&sort_order=DESC&sort_column=post_date&child_of=8');
foreach ($postslist as $post) :
setup_postdata($post); ?>
<ul class="main-projects-list">
<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID,
'orderby' => 'menu_order',
'order' => 'ASC',
);
$attachments = get_posts( $args );
if ( $attachments ) {
$post_title = get_the_title($post->ID); // We get the post title
foreach ( $attachments as $attachment ) {
$img_title = apply_filters( 'the_title', $post_title . ' - ' . $attachment->post_title ); // We create the image title with the 2 strings
echo '<li class="each-image">';
echo wp_get_attachment_image( $attachment->ID, 'large' , false, array('title' => $img_title));
echo '<p>';
echo $img_title;
echo '</p></li>';
}
}
?>
</ul>
<?php endforeach; ?>
| |
doc_652
|
I have tried to create a custum HTML to get some values but not the testcase value, defect owner
A: To set workspace on query request:
String workspaceRef = "/workspace/12345";
QueryRequest storyRequest = new QueryRequest("HierarchicalRequirement");
storyRequest.setWorkspace(workspaceRef);
To set project on query request:
String projectRef = "/project/3456";
QueryRequest defectRequest = new QueryRequest("Defect");
defectRequest.setProject(projectRef);
defectRequest.setScopedDown(true);
defectRequest.setScopedUp(false);
To set project on create request:
String projectRef = "/project/3456";
JsonObject newStory = new JsonObject();
newStory.addProperty("Project", projectRef);
Rally artifacts have two types of IDs: ObjectID that is unique across entire Rally stack, and FormattedID, which is unique only within a workspace.
This screenshot shows both. The ObjectID is the string in the URL: 28072723008, and FormattedID is TC1.
You may always find out ObjectID of any object in Rally in the WS API. Here is a query by username that returns the reference that contains user's ObjectID: 12868523447
| |
doc_653
|
fn foo() {
let items = vec![0.2, 1.5, 0.22, 0.8, 0.7, 2.1];
let mut groups: HashMap<u32, String> = HashMap::new();
let mut group = |idx: f32| -> &mut String {
let rounded = (idx / 0.2).floor() as u32;
groups
.entry(rounded)
.or_insert_with(|| format!("{}:", rounded))
};
for item in items.iter() {
group(*item).push_str(&format!(" {}", item))
}
}
and this code does not compile, with the following error:
error: captured variable cannot escape `FnMut` closure body
--> src/main.rs:9:9
|
5 | let mut groups: HashMap<u32, String> = HashMap::new();
| ---------- variable defined here
6 |
7 | let mut group = |idx: f32| -> &mut String {
| - inferred to be a `FnMut` closure
8 | let rounded = (idx / 0.2).floor() as u32;
9 | groups
| ^-----
| |
| _________variable captured here
| |
10 | | .entry(rounded)
11 | | .or_insert_with(|| format!("{}:", rounded))
| |_______________________________________________________^ returns a reference to a captured variable which escapes the closure body
|
= note: `FnMut` closures only have access to their captured variables while they are executing...
= note: ...therefore, they cannot allow references to captured variables to escape
Edit
As @Sven Marnach pointed out, the problem here is that I could create 2 mutable references to the same object:
fn foo() {
// ...
let ok = groups(0.1);
let problem = groups(0.1);
}
Original (incorrect)
I think that Rust is telling me, the closure group is mutably capturing the variable groups and then returning a reference to an object owned by groups. So the danger here is that the following code would return a dangling pointer (since groups is dropped when it goes out of scope after foo finishes).
fn foo() -> &String {
/* ... */ return groups(0.1); }
So is there any way to return a reference from a captured mutable HashMap like this?
A:
I think that Rust is telling me, the closure group is mutably capturing the variable groups and then returning a reference to an object owned by groups. So the danger here is that if I were to write:
then I would be returning a dangling pointer (since groups is dropped when it goes out of scope after foo finishes).
No. If that were the case Rust could (and would) warn about that.
The problem is that the lifetimes around function traits are problematic, because they don't have a way to match the lifetime of the result to the lifetime of the function itself.
As a result, rust blanket bans returning any reference to captured data from a closure.
As far as I can tell the solutions are:
*
*don't use a closure, instead pass in groups as an argument into the function (anonymous or named)
*use some sort of shared ownership and interior mutability e.g. have the map store and return Rc<RefCell<String>>
*desugar the closure to a structure with a method, that way the lifetimes become manageable:
use std::collections::HashMap;
struct F<'a>(&'a mut HashMap<u32, String>);
impl F<'_> {
fn call(&mut self, idx: f32) -> &mut String {
let rounded = (idx / 0.2).floor() as u32;
self.0
.entry(rounded)
.or_insert_with(|| format!("{}:", rounded))
}
}
pub fn foo() {
let items = vec![0.2, 1.5, 0.22, 0.8, 0.7, 2.1];
let mut groups: HashMap<u32, String> = HashMap::new();
let mut group = F(&mut groups);
for item in items.iter() {
group.call(*item).push_str(&format!(" {}", item))
}
}
Note that the above stores a reference to match the original closure, but in reality I see no reason not to move the hashmap into the wrapper entirely (and the struct can init itself fully without the need for a two-step initialisation as well):
use std::collections::HashMap;
struct F(HashMap<u32, String>);
impl F {
fn new() -> Self { Self(HashMap::new()) }
fn call(&mut self, idx: f32) -> &mut String {
let rounded = (idx / 0.2).floor() as u32;
self.0
.entry(rounded)
.or_insert_with(|| format!("{}:", rounded))
}
}
pub fn foo() {
let items = vec![0.2, 1.5, 0.22, 0.8, 0.7, 2.1];
let mut group = F::new();
for item in items.iter() {
group.call(*item).push_str(&format!(" {}", item))
}
}
| |
doc_654
|
vendor/something/src/UserServiceProvider.php
public function boot() {
$this->app->middleware([
SomeMiddleware::class
]);
}
vendor/something/src/Middlewares/SomeMiddleware.php
class SomeMiddleware {
public function handle(Request $request, \Closure $next) {
exit('here'); // this was never called
}
}
bootstrap/app.php
$app->register(\Something\UserServiceProvider::class);
However, when I tried registering it in bootstrap/app.php instead inside the UserServiceProvider.php class, it works fine.
bootstrap/app.php
// $app->register(\Something\UserServiceProvider::class);
// ...
$app->middleware([SomeMiddleware::class]);
Any advice?
| |
doc_655
|
Appreciate for help
A: SWIFT 2.0 : Use below code to convert pdf file to NSData. And use the POST service to upload the data to server.
let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
var filePath = documentDirectory.stringByAppendingString("/")
filePath = filePath.stringByAppendingString("final.pdf")
let pdfData = NSData(contentsOfFile: filePath)
Here, "filePath" is the path of the pdf file in document directory with name "final.pdf".
| |
doc_656
|
parent.fb.resize( {left: -360, width: true, height:true }, function () {
parent.location.reload( true );
}, 0.7 );
Ignore the fb.resize which is part of Floatbox. It's the callback function
parent.location.reload( true );
which I'm trying to improve upon. The function reloads the parent page from the server, and a PHP session variable controls the content of the parent page.
The problem I have is that the address bar only shows www.mywebsite.com/ so the user can't copy it as a link. Instead I would like it to show www.mywebsite.com/mypage.php?parameter=something. So I need the callback function to send the parameter with a GET, instead of relying on the seesion variable/ But, how?
A: I solved it in the way num8er suggested. The callback function became
parent.window.history.pushState(null, null, "mypage.php?parameter=<?php echo $_SESSION['something'] ?>");
parent.location.reload( true );
Then because there are times when the session parameter has not been set, I expanded it to
<?php if (isset($_SESSION['something'])) { ?>
parent.window.history.pushState(null, null, "mypage.php?parameter=<?php echo $_SESSION['something'] ?>");
parent.location.reload( true );
<?php }else{?>
parent.location.replace( "http://www.mywebsite.com/mypage.php" );
<?php }?>
| |
doc_657
|
I thought the best way to do this was to use XML, XSLT and Apache Cocoon. But I'm not sure if this is possible or if it's a good idea since I can't find any information of people doing anything similar. It cannot be an uncommon problem.
The idea came when I read about Cocoon converting XML through XSLT to PDF:
http://cocoon.apache.org/2.1/howto/howto-html-pdf-publishing.html
and being able to take in variables:
http://old.nabble.com/how-to-access-post-parameters-from-sitemap-td31478752.html
This is what I had in mind:
*
*A php file gets called by a user, the php file generates a source XML file with a specific name
*The php file then makes a request to Cocoon (on the same web server) to apply the user defined XSLT on the XML file. A parameter will be needed here to know which XSLT to apply.
*The request is handled by the PHP file and then saved as a PDF on the server, and can later be mailed away.
Will this work at all? Is there a better way to handle this?
The core problem is that the users need to be able to customize the layout on the PDFs themselves, and I need the server to save the PDF and to mail it later on. The users will use it for order confirmations, invoices, etc. And I wouldn't like to hard code the layout for each user.
A: I use webkithtml2pdf to generate my PDF:s. Just create a document with HTML and CSS for printing like you would usually do, the run it through the converter.
It works great for generating things like invoices. You can use SVG for logos and illustrations, and they will look great in print since they are vector based. Even rounded corners with dotted outlines works perfectly.
A minor gotcha is that the input html must have th htm or html file name suffix, so you can't use the default tempfile functions.
A: I've had some good results in the past by setting up JasperReports Server and creating reports using iReport Designer. They're both available in F/OSS ("community") editions, though you can pay for support and value-adds if you need those things.
This was a good solution for us, since we could access it via the Java API for our Java system, and via SOAP for our PHP system. The GUI designer made tweaking reports very easy for non-technical business staff too.
| |
doc_658
|
The problem arises when I SSH into the laptop and try to run git commands from the iMac. Git asks for my password on every command that interacts with remotes.
Both computers are setup with the same .gitconfig. I am using public keys for authentication with the laptop.
This is annoying. I know there are workarounds, but how do I fix this in particular?
A: You are using "public keys for authentication". Therefore you need your private key to authenticate to the server. If no private key is available, ssh will fall back to password authentication and ask for the password.
Did you store your private key on the Macbook or the iMac?
Assuming you have a copy on the Macbook and some ssh-agent running, ssh-add -L should print the correct public key.
In this case you can use ssh -A to forward the agent to your Macbook, where it can use that key for authentication.
| |
doc_659
|
Here is where I start from :
function varargout=fname(varargin)
% FNAME
% Usage: output=fname(input)
% Arguments check
if(nargin~=1 || nargout~=1)
disp('Function fname requires one input argument');
disp('and one output argument');
disp('Try `help fname`');
varargout(1:nargout)={0};
return;
end
input=varargin{1};
output=input;
varargout(1)={output};
end
However this does not work as I would like it to. Is there a way to write a function that :
*
*never throw a "wrong number of arguments" error (so that the rest of the execution can continue)
*accepts variable number of input and output arguments and checks them inside the function
*(maybe more tricky) if the number of input / output arguments is not correct, does not replace the value of the provided output arguments (so that any misplaced call does not erase the previous value of the output argument)
I am open to any suggestions / other methods.
Thank you for your help.
UPDATE: thanks to @Amro for his answer, I guess what I miss here is either a call by address of reference for Matlab functions or a way to interrupt a function without returning anything and without stopping the rest of the execution.
A: Here is one way to implement your function:
function varargout = fname(input,varargin)
%# FNAME
%# Usage: output=fname(input)
%%# INPUT
if nargin<1
varargout(1:nargout) = {[]};
warning('Not enough input arguments.'), return
end
if ~isempty(varargin)
warning('Too many input arguments.')
end
%%# YOUR CODE: manipulate input, and compute output
output = input;
%%# OUTPUT
varargout{1} = output;
if nargout>1
warning('Too many output arguments.')
varargout(2:nargout) = {[]};
end
end
Obviously you can customize the warning messages to your liking...
Also, if you want your function to simply print the message instead of issuing warnings, replace all WARNING calls with simple DISP function calls.
Examples of function call:
fname()
fname(1)
fname(1,2)
x = fname()
x = fname(1)
x = fname(1,2)
[x,y] = fname()
[x,y] = fname(1)
[x,y] = fname(1,2)
The above calls execute as expected (showing warning messages when applicable). One caveat though, in the last three calls, if the variable y already existed in the workspace prior to the calls, it would be overwritten by the empty value y=[] in each...
A: If I understand your question correctly, then the answer is no. If a caller calls a function like this:
[a, b, c] = fname('foo');
then fname is required to return (at least) three outputs. There's no way to tell MATLAB that it should leave b and c alone if fname only returns one output.
| |
doc_660
|
I tried so many times. I tried to upload from xcode too. But not working. Please help.
A: It was an internet issue. When it was too slow. That's why it was showing timeout again and again. I have changed nothing. Just tried it on another day and it worked.
| |
doc_661
|
When I try to delete files only the thumbnails get deleted but not the files from server.
I tried some ways but it just gives me the name of the image which was on client side and not the name on server side(both names are different, storing names in encrypted form).
Any help would be much appreciated..
A: Most simple way
JS file,this script will run when you click delete button
this.on("removedfile", function(file) {
alert(file.name);
$.ajax({
url: "uploads/delete.php",
type: "POST",
data: { 'name': file.name}
});
});
php file "delete.php"
<?php
$t= $_POST['name'];
echo $t;
unlink($t);
?>
A: The file will be deleteed when you click the "Remove" button :
Put this on your JS file or your HTML file (or your PHP view/action file):
<script type="text/javascript">
Dropzone.options.myAwesomeDropzone = {
// Change following configuration below as you need there bro
autoProcessQueue: true,
uploadMultiple: true,
parallelUploads: 2,
maxFiles: 10,
maxFilesize: 5,
addRemoveLinks: true,
dictRemoveFile: "Remove",
dictDefaultMessage: "<h3 class='sbold'>Drop files here or click to upload document(s)<h3>",
acceptedFiles: ".xls,.xlsx,.doc,.docx",
//another of your configurations..and so on...and so on...
init: function() {
this.on("removedfile", function(file) {
alert("Delete this file?");
$.ajax({
url: '/delete.php?filetodelete='+file.name,
type: "POST",
data: { 'filetodelete': file.name}
});
});
}}
</script>
..and Put this code in your PHP file :
<?php
$toDelete= $_POST['filetodelete'];
unlink("{$_SERVER['DOCUMENT_ROOT']}/*this-is-the-folder-which-you-put-the-file-uploaded*/{$toDelete}");
die;
?>
Hope this helps you bro :)
A: I've made it easier, just added new property serverFileName to the file object:
success: function(file, response) {
file.serverFileName = response.file_name;
},
removedfile: function (file, data) {
$.ajax({
type:'POST',
url:'/deleteFile',
data : {"file_name" : file.serverFileName},
success : function (data) {
}
});
}
A: Another way,
Get response from your server in JSON format or a plain string (then use only response instead of response.path),
dropzone.on("success", function(file, response) {
$(file.previewTemplate).append('<span class="server_file">'+response.path+'</span>');
});
Here, the server can return a json like this,
{
status: 200,
path: "/home/user/anything.txt"
}
So we are storing this path into a span that we can access when we are going to delete it.
dropzone.on("removedfile", function(file) {
var server_file = $(file.previewTemplate).children('.server_file').text();
alert(server_file);
// Do a post request and pass this path and use server-side language to delete the file
$.post("delete.php", { file_to_be_deleted: server_file } );
});
After the process, the preview template will be deleted by Dropzone along with file path stored in a span.
A: success: function(file, serverFileName)
{
fileList['serverFileName'] = {"serverFileName" : serverFileName, "fileName" : file.name };
alert(file.name);
alert(serverFileName);
},
removedfile: function(file, serverFileName)
{
fileList['serverFileName'] = {"serverFileName" : serverFileName, "fileName" : file.name };
alert(file.name);
alert(serverFileName);
}
A: When you save the image in upload from there you have to return new file name :
echo json_encode(array("Filename" => "New File Name"));
And in dropzone.js file :
success: function(file,response) {
obj = JSON.parse(response);
file.previewElement.id = obj.Filename;
if (file.previewElement) {
return file.previewElement.classList.add("dz-success");
}
},
And when the dropzone is initialize..
init: function() {
this.on("removedfile", function(file) {
var name = file.previewElement.id;
$.ajax({
url: "post URL",
type: "POST",
data: { 'name': name}
});
});
return noop;
},
Now you will receive new image file and you can delete it from server
A: You can add id number of uploaded file on the mockFile and use that id to delete from server.
Dropzone.options.frmFilesDropzone = {
init: function() {
var _this = this;
this.on("removedfile", function(file) {
console.log(file.id); // use file.id to delete file on the server
});
$.ajax({
type: "GET",
url: "/server/images",
success: function(response) {
if(response.status=="ok"){
$.each(response.data, function(key,value) {
var mockFile = {id:value.id,name: value.name, size: value.filesize};
_this.options.addedfile.call(_this, mockFile);
_this.options.thumbnail.call(_this, mockFile, "/media/images/"+value.name);
_this.options.complete.call(_this, mockFile);
_this.options.success.call(_this, mockFile);
});
}
}
});
Server Json return for getting all images already uploaded /server/images:
{
"data":[
{"id":52,"name":"image_1.jpg","filesize":1234},
{"id":53,"name":"image_2.jpg","filesize":1234},
]}
A: The way I handle this, is after each file is uploaded and stored on the server, I echo back the name I give the file on my server, and store it in a JS object, something like this:
PHP:
move_uploaded_file($_FILES['file']['tmp_name'], $newFileName);
echo $newFileName;
JS:
dropZone.on("success", function(file, serverFileName) {
fileList[serverFileName] = {"serverFileName" : serverFileName, "fileName" : file.name };
});
With this, you can then write a delete script in PHP that takes in the "serverFileName" and does the actual deletion, such as:
JS:
$.ajax({
url: "upload/delete_temp_files.php",
type: "POST",
data: { "fileList" : JSON.stringify(fileList) }
});
PHP:
$fileList = json_decode($_POST['fileList']);
for($i = 0; $i < sizeof($fileList); $i++)
{
unlink(basename($fileList[$i]));
}
A: In my case server sends back some ajax response with deleteUrl for every specific image.
I just insert this url as 'data-dz-remove' attribute, set in previewTemplate already.
As I use jquery it looks so:
this.on("success", function (file, response) {
$(file.previewTemplate).find('a.dz-remove').attr('data-dz-remove', response.deleteUrl);
});
Later this attr used to send ajax post with this url to delete file on server by removedfile event as mentioned above.
A: This simple solution will work for single files upload, no need for DOM manipulation.
PHP Upload Script
[...]
echo $filepath; // ie: 'medias/articles/m/y/a/my_article/my-image.png'
JS Dropzones
this.on("success", function(file, response) {
file.path = response; // We create a new 'path' index
});
this.on("removedfile", function(file) {
removeFile(file.path)
});
JS outside of Dropzone
var removeFile = function(path){
//SEND PATH IN AJAX TO PHP DELETE SCRIPT
$.ajax({
url: "uploads/delete.php",
type: "POST",
data: { 'path': path}
});
}
| |
doc_662
|
I want to know if there is a way that will enable me to access the class Position in the main.dart from the request.dart in such that the part where i add my api in the Uri.parse() the ${postion.latitude} and${position.longitude} won't be Undefined and refer to the Position class in the main.dart file. Thank you!
main.dart file
'''
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:provider/provider.dart';
import 'package:rider_app/AllScreens/searchScreen.dart';
import 'package:rider_app/AllWidgets/Divider.dart';
import 'package:rider_app/Assistants/assistantMethods.dart';
import 'package:rider_app/DataHandler/appData.dart';
class MainScreen extends StatefulWidget
{
static const String idScreen = "mainScreen";
const MainScreen({Key key}) : super(key: key);
@override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen>
{
Completer<GoogleMapController> _controllerGoogleMap = Completer();
GoogleMapController newGoogleMapController;
GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
Position currentPosition;
var geoLocator = Geolocator();
double bottomPaddingOfMap=0;
void locatePosition() async
{
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
currentPosition= position;
LatLng latLatPosition = LatLng(position.latitude, position.longitude);
//Camera move
CameraPosition cameraPosition = new CameraPosition(target: latLatPosition, zoom: 16);
newGoogleMapController.animateCamera(CameraUpdate.newCameraPosition(cameraPosition));
//newGoogleMapController.animateCamera(CameraUpdate.newCameraPosition(cameraPosition));
String address = await AssistantMethods.searchCoordinateAddress(position, context);
}
'''
request.dart file
'''
import 'dart:convert';
import 'dart:html';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:geolocator/geolocator.dart';
import 'package:http/http.dart' as http;
import 'package:rider_app/configMaps.dart';
import 'package:rider_app/lib/AllScreens/mainscreen.dart';
class RequestAssistant
{
static Future<dynamic> getRequest(url) async
{
var url = Uri.parse("https://maps.googleapis.com/maps/api/geocode/json?latlng=${position.latitude},${position.longitude}&key=$mapKey");
http.Response response = await http.get(url);
try
{
if(response.statusCode==200)
{
String jSonData = response.body;
var decodeData = jsonDecode(jSonData);
return decodeData;
}
else
{
return "failed";
}
}
catch(exp)
{
return "failed";
}
}
}'''
A: You can pass in getRequest method life
getRequest(Position position) async {...}
| |
doc_663
|
function moveColsWesbanco() {
var ss = SpreadsheetApp.getActive();
var sourceSheet = ss.getSheetByName('Sheet1');
var destSheet = ss.getSheetByName('New Entry');
var debitsCredits = sourceSheet.getRange('A7:D');
var values = debitsCredits.getValues();
let amounts2 = values.filter(o => o[0] != '').map(e => e[2] != '' ? e[3] = Number.parseFloat(e[2]) : Number.parseFloat(e[3]));
let allTypes = [];
for (val in amounts2) {
allTypes.push(typeof val)
};
Logger.log('Types within it: ' + allTypes)
return;
}
Here are the logs:
So...I wonder what I'm missing here. Thank you!
A: I think that when "for in" is used like for (val in amounts2) {}, val is the index. And, it's the string type. I think that this is the reason of your issue. In this case, how about using "for of" as follows?
Modified script:
for (var val of amounts2) {
allTypes.push(typeof val)
};
References:
*
*for...in
*for...of
| |
doc_664
|
Something similar to awesome_print, or maybe even Pretty Print.
It doesn't have to understand all the dialects possible or be super-advanced.
All I really want is to inspect the SQL generated by ActiveRecord easier.
Currently I just copy the SQL go online to format it which is obviously a productivity killer.
I really want to query.to_sql.pretty_format_sql and see the nicer output.
Thanks.
A: Six years later, here's another option: https://github.com/kvokka/pp_sql
"Replace standard ActiveRecord#to_sql method with anbt-sql-formatter gem for pretty SQL code output in console. Rails log will be formatted also."
Uses anbt-sql-formatter under the hood, but makes this the default behavior for .to_sql
A: Try this:
git clone https://github.com/sonota/anbt-sql-formatter
cd anbt-sql-formatter
rails setup.rb
Then, in a Rails initializer:
# config/initializers/pretty_format_sql.rb
class String
def pretty_format_sql
require "anbt-sql-formatter/formatter"
rule = AnbtSql::Rule.new
rule.keyword = AnbtSql::Rule::KEYWORD_UPPER_CASE
%w(count sum substr date).each{|func_name|
rule.function_names << func_name.upcase
}
rule.indent_string = " "
formatter = AnbtSql::Formatter.new(rule)
formatter.format(self)
end
end
Test:
rails console
# Some complex SQL
puts Recipe.joins(:festivity).where(['? BETWEEN festivities.starts_at AND festivities.ends_at', Time.utc(0,Time.now.month,Time.now.day,12,0,0)]).to_sql.pretty_format_sql
SELECT
"recipes" . *
FROM
"recipes" INNER JOIN "festivities"
ON "festivities" . "id" = "recipes" . "festivity_id"
WHERE
(
'0000-04-27 12:00:00.000000' BETWEEN festivities.starts_at AND festivities.ends_at
)
=> nil
I leave refining to you (refactoring: monkey-patching -> module, customized formatting, etc :-) )
A: The anbt-sql-formatter of the first answer is available as a gem, you can install it with:
gem install anbt-sql-formatter
Here an example of the usage:
require "anbt-sql-formatter/formatter"
rule = AnbtSql::Rule.new
formatter = AnbtSql::Formatter.new(rule)
[
"SELECT `col1`, `col2` FROM `table` WHERE ((`col1` = 1) AND (`col2` = 5))",
"SELECT `col1`, `col2` FROM `table` WHERE (`col1` = 1) AND (`col2` = 5)",
"SELECT `col1` FROM `table` WHERE (`col1` IN (SELECT * FROM `table21` WHERE (`col2` = 5)))",
"SELECT `col1` FROM `table` INNER JOIN `tab2` ON (`tab1`.`id` = `tab2`.`id1`) WHERE ((`id` >= 1) AND (`id` <= 5))",
].each{|sql_cmd|
puts "======"
puts sql_cmd
puts formatter.format(sql_cmd)
}
The result:
======
SELECT `col1`, `col2` FROM `table` WHERE ((`col1` = 1) AND (`col2` = 5))
SELECT
`col1`
,`col2`
FROM
`table`
WHERE
(
(
`col1` = 1
)
AND (
`col2` = 5
)
)
======
SELECT `col1`, `col2` FROM `table` WHERE (`col1` = 1) AND (`col2` = 5)
SELECT
`col1`
,`col2`
FROM
`table`
WHERE
(
`col1` = 1
)
AND (
`col2` = 5
)
======
SELECT `col1` FROM `table` WHERE (`col1` IN (SELECT * FROM `table21` WHERE (`col2` = 5)))
SELECT
`col1`
FROM
`table`
WHERE
(
`col1` IN (
SELECT
*
FROM
`table21`
WHERE
(
`col2` = 5
)
)
)
======
SELECT `col1` FROM `table` INNER JOIN `tab2` ON (`tab1`.`id` = `tab2`.`id1`) WHERE ((`id` >= 1) AND (`id` <= 5))
SELECT
`col1`
FROM
`table` INNER JOIN `tab2`
ON (
`tab1`.`id` = `tab2`.`id1`
)
WHERE
(
(
`id` >= 1
)
AND (
`id` <= 5
)
)
There is also the possibility to extend the rules, e.g.
# User defined additional functions:
%w(count sum substr date coalesce).each{|func_name|
rule.function_names << func_name.upcase
}
A: There is prettier-plugin-sql which has a nice output, e.g.
SELECT
DISTINCT "events".*
FROM
"events"
INNER JOIN "approvals" ON "approvals"."event_id" = "events"."id"
LEFT OUTER JOIN "attendances" ON "attendances"."event_id" = "events"."id"
WHERE
(
"approvals"."status" = ?
OR "events"."user_id" = ?
)
AND (
"attendances"."user_id" = ?
OR "events"."user_id" = ?
)
And if you copy your sql query after doing puts Event.something.to_sql, you can do:
pbpaste | prettier --parser sql
| |
doc_665
|
for (t in 1:6){
M= data[t:(t+3), ]
lpnorm(M)
}
when i loop the function it produces the correct output, however the vectors all appear to be independent
[1] 0.0003370998
[1] 0.0003379513
[1] 0.0002855089
[1] 0.0003535439
[1] 0.0003683093
[1] 0.0003443804
Therefore when i try to plot the data:
for (t in 1:6){
M= data[t:(t+3), ]
plot(t, lpnorm(M))
}
They all appear on separate diagrams
A: With out a reproducible example you could do the following:
res <- matrix(NA, nrow=6, ncol=2) ##intitialize a matrix to store the results
for (t in 1:6){
M <- data[t:(t+3), ]
res[t, ] <- c(t, lpnorm(M)) #for each value of t we save the results in the res matrix
}
plot(res[,1], res[, 2])
The reason you are getting a plot for each value of lpnorm(M) is because you are not saving the result of each iteration.
| |
doc_666
|
I know there is a general issue with changing the html that contains a selection, but I'm wondering if Angular has some solution to the problem that I'm just not aware of. Basically what I'm looking for is for only the HTML that actually changed being updated. I could do that if I was writing view code manually in jQuery, but every other part of doing it manually is awful
JS:
angular.module('items', [])
.factory('itemList', ['$http', function($http) {
var items = [];
var refresh = function() {
// imagine that this makes an HTTP call to get the new list
// of items
items.length = 0;
for (var i = 0; i < 10; i++) {
items.push("item " + Math.random(1, 10))
}
}
refresh();
return {
items: items,
refresh: refresh
};
}]);
var app = angular.module('app', [
'items'
]);
app.controller('ItemListController',
['$scope', 'itemList', '$interval',
function($scope, itemList, $interval) {
this.items = itemList.items;
$interval(itemList.refresh, 2000)
}
]);
HTML:
<body ng-app="app">
<div ng-controller="ItemListController as controller">
<h3>Items</h3>
<div ng-model="active">
<div ng-repeat="item in controller.items">
<div class="header">Header</div>
<div>{{item}}</div>
<hr/>
</div>
</div>
</div>
</body>
A: As you're wholesale replacing itemList on each refresh, angular has no option but to re-create all the elements in the ng-repeat, which is fine if you don't mind losing the selection and the refresh isn't too large and expensive. To prevent this though, you could try writing a merge in that factory that diffs the previous against the new and adds/removes items without replacing the whole reference. Then only if the item you selected no longer exists would you lose the selection.
Also, if the list is long and the differences from refresh to refresh are small, then this will probably be more efficient.
A: $interval refreshes entire DOM So selection is get refreshed and new value will appear.
if you want to select then cancel the interval for particular time $interval.cancel(milliseconds) then restart the timer with selected range.
$scope.$watch("refresh", function(){
$interval.cancel(5000);
p = $interval(itemsList.refresh(), 2000);
})
A: I figured it out. Thor's answer was on the right track. The issue was that I wasn't using "track by FOO" on my ng-repeat, so it had no way of knowing that the elements in my actual case with complex objects were the same and thus it redrew them
| |
doc_667
|
Dim db As New mydatabaseEntities
then using LINQ with one of my database tables: db.stations (type:DbSet(Of station)) shown below, the query works as expected:
Dim myDbSet1 = db.stations
Dim isQuerable1 = TypeOf myDbSet1 Is IQueryable
Dim query1 = myDbSet1.Where(Function(record) record.id = "677010")
However, if I specify the database table name as a string, and then use CallByName to get the DBSet(Of station) at run-time, I get an error:
Dim tableName As String = "stations"
Dim myDbSet2 = CallByName(db, tableName, CallType.Get)
Dim isQueryable = TypeOf myDbSet2 Is IQueryable
Dim query2 = myDbSet2.Where(Function(record) record.id = "677010")
In both cases, myDbSet1 and myDbSet2 have the IQueryable interface. But, in the second example, I get the following error:
System.MissingMemberException: 'Public member 'Where' on type 'DbSet(Of station)' not found.'
*
*Why are some of the interface methods missing in the second example?
*Will I have similar problems any time I use CallByName, or is the problem related either to interfaces, or to LINQ/Entity Framework?
A: The method Where is an Extension method on the IEnumerable(Of T) interface and by inheritance for the IQueryable(Of Out T) interface. The method does not really exist on the object. Its call is wired up by the compiler.
Depending on what your usage case is, either of the following should work. Just remember to null test myDbSet2 in case the cast fails.
Dim myDbSet2 = TryCast(CallByName(db, tableName, CallType.Get), IEnumerable(Of Station))
or
Dim myDbSet2 = TryCast(CallByName(db, tableName, CallType.Get), IQueryable(Of Station))
| |
doc_668
|
1)why i am getting that output when I directly called setInterval without useeffect 2)is there any way if I change setCount(line 9) and its gives correct output by use setInterval directly without useEffect(as I did)
3) if the use of setInterval is not possible without useEffcet than why it is not possible?
if i put setInterval in useEffect and render initially once( line 12,13,14) than it gives correct output.....
but I do not get the correct output when I use directly setInterval. what is diff bet them?
in both cases, I call setInterval once but the output is diff.
import React, {useEffect, useState } from 'react'
export default function IncorrectDependency() {
const [count,setCount]=useState(0)
const inc=()=>{
// console.log(count)
setCount(preVal=>preVal+1)
// setCount(count+1)
}
// useEffect(()=>{
// setInterval(inc,1000)},[]
// )
setInterval(inc,1000)
return (
<div>
<h1>{count}</h1>
</div>
)
}
A: When we do a set state, functional components will re-execute from top to bottom, how ever when we use useState, useCallbacks etc.. they will not re-initialize as variables, functions,
So in this case, setInterval will re-initialize on each and every setCount, because of the state got changed,
step by step
*
*in the 1st second there will be one setInterval, and call setCount and component is ready to rerender
*when re-redering, start executing functional component from top-to-bottom it sees setInterval again and it will trigger it, so now we have two setIntervals
*so on it will add multiple setIntervals on each second, because we don't clear it, so you should see the number printed in the browser will not take a second, but less than a second when time goes by.
You can achieve the expected result without useEffect by clearing the previous interval on each re-render which is happen due to setCount
create a variable to hold the set interval, code
const interval = null;
//this should be declare out side the component,
//because if we declare it inside the component it will redeclare,
//and the reference to the previous setInterval will be lost in that case no-way to clear the setInterval.
export default function IncorrectDependency() {
....
if (interval) {
clearInterval(interval);
}
interval = setInterval(inc, 1000);
....
}
alternatively react has a hook which can hold the same variables without re-initializing on each renderings, check it out useRef
here is a code-demo
const intvl = useRef(null);
....
if (intvl?.current) {
clearInterval(intvl.current);
}
intvl.current = setInterval(inc, 1000);
.....
A: when you directly use setInterval what is happening as this is a function it will be called on state change so again a setInterval will be triggered and so on which actually give you the incorrect result, so you shouldn't use setInterval without use effect, also on unmount you should clearthe interval
A: Dan Abramov explains why this isn't a good idea:
"it’s not the idiomatic way to do it. eg it won’t work correctly if you have multiple instances of the same component. it breaks the rules — it does a side effect (setInterval) during rendering, which the page said you should not do :) once you break the rules, all bets are off"
https://twitter.com/dan_abramov/status/1577395235340095501?s=20&t=nNnYyjLvHs5by_dqF5l8zg
| |
doc_669
|
A: It (form) will be stored in request object and request object will in memory.
you don't have to clear explicitly it
V8 is responsible for clearing unreachable objects in node
If you interested in how garbage collection works, you can check out
following links
Getting garbage collection for free
Generational garbage collection
Garbage collection in v8
| |
doc_670
|
When I run this code.
int imageResource = getResources().getIdentifier("image", "drawable", getPackageName()); //error here
System.out.println(imageResource); //doesn't get to this
The whole app crashes and I get this error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: net.mobiledevelopment.app, PID: 6663
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{net.mobiledevelopment.app/net.mobiledevelopment.app.Shop}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
I am declaring these variables outside of any function.
Any help is appreciated. Thanks!
A: The code works now.
I wasn't calling getResources() inside of the onCreate() method. This is important apparently.
| |
doc_671
|
Here is my code(updated):
var thisLock = new Object();
var list = new List<Person>();
Parallel.For(1, 10, x =>
{
request.Page = x;
response = Get(request); // call to client
lock(thisLock)
{
list.AddRange(response);
}
}
Any other ideas besides addRange or ConcurrentBag
A: I am making a few assumptions here, but it would appear that your problem is the fact that your request/response variables are not scoped within the Parallel.For call.
The problem is you make a (presumably) synchronous Get call which updates the response variable but given you have X threads all working with that very same response if that gets updated at any given point i.e. whilst another thread is adding it to the list, then that is going to very well lead to duplicate data.
Same goes for the request, you have an obvious race condition meaning that when one thread changes the request.Page and another thread is just about to pull the data then you are effectively pulling the same page across various threads.
The solution is simple, create your request/response objects locally
var list = new ConcurrentBag<T>();
Parallel.For(1, 10, x =>
{
var request = // create new request;
request.Page = x;
var response = Get(request); // call to client
foreach (var item in response) {
list.Add(item); // add it main list
}
}
A: This is a good candidate for PLINQ. You can then use SelectMany for flattening the sequences.
var list = ParallelEnumerable.Range(1, 10).SelectMany(x =>
{
var request = // create new request;
request.Page = x;
response = Get(request); // call to client
return response;
}).ToList();
| |
doc_672
|
A: You cannot use primitive types (byte, short, int, etc.). You must use the wrapper type which, in this case, is Integer
List<Integer>
This type of casting is called generics, and you can start learning more about them here.
A: List<int> doesn't work because Java generics doesn't deal with primitive types - only Objects (or subclasses thereof, like Integer). You aren't required to specify the type parameter when using a generic class, but the compiler will issue a warning and you'll be required to take care of all the type casting (including dealing with potential ClassCastExceptions) and such yourself.
A: Lists (and other collections) can keep only objects, not primitive types. So you can use List<Integer> but not List<int>. String is also an object — that's why it works.
And regarding the difference between List and List<String>: the difference exists only during the compilation. In runtime all both lists are identical.
| |
doc_673
|
clashApiClient
.clanByTag(tag)
.then((response) => {
var reply = "";
response.memberList.forEach((member) => {
var strike = "";
Player.findOne({ playerTAG: member.tag }, (err, player) => {
if (err) {
console.log(err);
callback("Error: ", err);
}
if (!player) {
strike = "Strike information doesn't exist.";
} else {
strike = player.strikeCount + "Strikes.";
}
});
reply = reply + member.name + ": " + strike + "\n";
});
callback("```" + response.name + " : \n\n" + reply + "```");
})
.catch(() => callback("Error: Something went wrong while getting data!"));
}
A: there are possible cases here to explore:
1.
Player must be a model, not a document- an instance of a model
just like User below:
const User = mongoose.model('User', mongoSchema);
module.exports = User;
*
check your import/require or export statement
3.
make sure there is playerTAG props/object is defined in the Schema
4.
Check your database to see if Player and playerTAG are there
5.
console.log or check the value of member.tag passed to playerTAG
*add await
*
check the error you see in the console to understand the problem
just know when the query/condition passed to Model.findOne() is not met, it returns null - that is why your strike value is empty
e.g.
// Find one adventure whose `country` is 'Croatia', otherwise `null`
await Adventure.findOne({ country: 'Croatia' }).exec();
| |
doc_674
|
Like that -> (searching : Product red ribbon )
that show other texts same
-product ribbon
-product red
-red ribbon
i want show only same search query ( product red ribbon ) and hide others
my code
<input type="text" class="live-search-box" placeholder="search here">
<script type="text/javascript">jQuery(document).ready(($) => {
const ENTER = 130000;
$('.live-search-list li').each(function(){
$(this).attr('data-search-term', $(this).text().toLowerCase());
});
$('.live-search-box').on('keyup', function(){
const searchTerm = $(this).val();
$('.live-search-list li').each(function(){
($(this).filter('[data-search-term *= ' + searchTerm + ']').length > 0 || searchTerm.length < 2)
? $(this).show()
: $(this).hide();
});
});
$('input[class=live-search-box]').keydown(function(e){
if(e.keyCode == ENTER){
e.preventDefault();
e.stopPropagation();
const toAdd = $('input[class=live-search-box]').val();
if (toAdd) {
$('<li/>' , {
'text': toAdd,
'data-search-term': toAdd(),
}).appendTo($('ul'));
$('input[class=live-search-box]').val('');
}
}
});
$(document).on('dblclick', 'li', function(){
$(this).fadeOut('slow',function(){
$(this).remove();
setTimeout(function() { $input.val(''); }, 5000);
});
});
});
</script>
| |
doc_675
|
import UIKit
let ImageFileDirectory : String = "Image-cache"
typealias ImageDownloadCallBackSuccess = ( String , UIImage) -> Void
class ImageManager: NSObject {
override init() {
super.init()
}
func downloadImageFile (imageData : Dictionary<String,AnyObject>, callback: ImageDownloadCallBackSuccess) -> Void {
let imageUrl : NSString = (imageData as NSDictionary).objectForKey("url") as! NSString
let imageId : Int = (imageData as NSDictionary).objectForKey("id") as! Int
let imageIDString : String = String(imageId)
let filemanager = NSFileManager.defaultManager()
if !filemanager.fileExistsAtPath(filePath(imageIDString)) {
var opManager : AFHTTPRequestOperationManager = AFHTTPRequestOperationManager()
opManager.responseSerializer = AFImageResponseSerializer()
opManager.requestSerializer.timeoutInterval = 180.0
let newOperation = opManager.HTTPRequestOperationWithRequest( NSURLRequest(URL: NSURL(string: imageUrl)!), success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) -> Void in
println("File Saved to ImageCacheDirectory")
let imageData : NSData = UIImageJPEGRepresentation(responseObject as! UIImage, 1.0)
imageData.writeToFile(self.filePath(imageIDString), atomically: true)
callback(imageIDString, responseObject as! UIImage)
}, failure: { (operation: AFHTTPRequestOperation!,error: NSError!) -> Void in
println("Couldn't save the file to ImageCacheDirectory")
})
newOperation.start()
}
else {
println("file exist for path")
}
}
class func filePathForImage (imageID: String) -> (String!) {
let documentsPath : String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0] as! String
let fileExtensionString = String(format:"/%@/", ImageFileDirectory)
let folderPath = documentsPath.stringByAppendingPathComponent("\(fileExtensionString)")
let filemanager = NSFileManager.defaultManager()
var err: NSErrorPointer = nil
if !filemanager.fileExistsAtPath(folderPath) {
filemanager.createDirectoryAtPath(folderPath, withIntermediateDirectories: true, attributes: nil, error: err)
}
var filePath = "\(folderPath)"
filePath += "/"
filePath += "\(imageID)"
filePath += "."
filePath += "jpg"
return filePath
}
func imageRootDirectory() -> String {
let documentsPath : String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0] as! String
let imageDirectory = String(format:"/%@/", ImageFileDirectory)
return documentsPath.stringByAppendingPathComponent("\(imageDirectory)")
}
func filePath (imageID :String) -> String {
let folderPath = imageRootDirectory()
var filePath = "\(folderPath)"
filePath += "/"
filePath += "\(imageID)"
filePath += "."
filePath += "jpg"
return filePath
}
func downloadAllImage () {
for imageObject in DataManager.sharedInstance.allImages {
downloadImageFile(imageObject, callback: { (imageString, imageData) -> Void in
})
}
}
}
typealias AudioDownloadHandler = (Double) -> Void
let AudioFileDirectory : String = "Audio-cache"
import UIKit
import AVFoundation
class AudioManager: NSObject ,AVAudioPlayerDelegate {
var audioID : Int?
var audioUrl : String?
var audioPlayer : AVAudioPlayer! // will be Optional, must supply initializer
override init() {
super.init()
}
init (audioId : Int , audioUrl: String) {
self.audioUrl = audioUrl
self.audioID = audioId
super.init()
}
func cacheAudioFile(callback:AudioDownloadHandler) -> Void {
let request: NSURLRequest = NSURLRequest(URL: NSURL(string: self.audioUrl!)!)
let audioDownloadOperation: AFHTTPRequestOperation = AFHTTPRequestOperation(request: request)
audioDownloadOperation.outputStream = NSOutputStream(toFileAtPath: filePathForAudio()!, append: false)
audioDownloadOperation.setDownloadProgressBlock({(bytesRead, totalBytesRead, totalBytesExpectedToRead) -> Void in
var total: CGFloat = CGFloat(totalBytesRead) / CGFloat(totalBytesExpectedToRead)
callback(Double(total))
})
audioDownloadOperation.start()
}
func filePathForAudio () -> (String!) {
let documentsPath : String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)[0] as! String
let fileExtensionString = String(format:"/%@/", AudioFileDirectory)
let folderPath = documentsPath.stringByAppendingPathComponent("\(fileExtensionString)")
let filemanager = NSFileManager.defaultManager()
var err: NSErrorPointer = nil
if !filemanager.fileExistsAtPath(folderPath) {
filemanager.createDirectoryAtPath(folderPath, withIntermediateDirectories: true, attributes: nil, error: err)
}
var filePath = "\(folderPath)"
filePath += "/"
filePath += "\(self.audioID!)"
filePath += "."
filePath += "\(self.audioUrl!.pathExtension)"
return filePath
}
func playAudioFile () {
var filePathUrl : NSURL = NSURL.fileURLWithPath(filePathForAudio())!
var error: NSError!
self.audioPlayer = AVAudioPlayer(contentsOfURL: filePathUrl, error: nil)
self.audioPlayer.delegate = self
if let player : AVAudioPlayer = self.audioPlayer as AVAudioPlayer?{
self.audioPlayer.prepareToPlay()
player.play()
}
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool) {
NSNotificationCenter.defaultCenter().postNotificationName("AudioFinishedPlaying", object: nil)
}
}
let imageManager = ImageManager()
imageManager.downloadAllImage ()
A: If you are creating a bunch of image download operations and then want to create one video download operation that you don't want backlogged being the image downloads, there are a couple of considerations to keep in mind:
*
*Using NSURLConnection, you are constrained by how many requests will actually be performed concurrently (5, I believe).
*You are manually calling start to the operations. Thus, you are taking advantage of neither (a) the ability to constrain how many concurrent operations are running; nor (b) the priority, dependencies, nor quality of service of the individual operations.
The basic idea is to use operation queues and operation properties to dictate the behaviors associated with when operations run.
I would therefore suggest that you don't call start anymore and rather add the operations to queues of your creation. You can either create an image download queue (with maxConcurrentOperationCount of something like 3) and a separate video download queue. Your NSURLConnection will therefore not be running more than 3 image download requests at a time, and thus you have the capacity to run a video download concurrently, not waiting for the image downloads.
The other approach is to have a single generic download queue, perhaps use a maxConcurrentOperationCount of 4 or 5, and when you create the image and video downloads, give the video operation a higher priority/QoS.
| |
doc_676
|
I have an NSTokenField in my app and I implemented the tokenField:completionsForSubstring:indexOfToken:indexOfSelectedItem: method.
Everything works fine but the present result look like this :
What I would like is to make it look like this: (similar to the completion in the Mail app)
Which means that I would like the completion list to take all the NSTokenField width.
Using the Accessibility Inspector, I can see that the hierarchy corresponding to the first sreenshot is:
AXScrollArea -> AXList -> AXTextField
while the one corresponding to the second screenshot is:
AXScrollArea -> AXTable -> AXRow:AXTableRow -> AXTextField
So I suppose I have to use an NSTableView to display the completion list, but I don't know how to achieve this. Does anybody know how is that possible?
Thanks in advance for your help.
EDIT
At least 2 people suggested that I implement the tokenField:menuForRepresentedObject: method and define the menu width with the appropriate NSMenu property. But this method is used to define a menu for a given token and I already implemented it:
def tokenField(tokenField, menuForRepresentedObject:representedObject)
theMenu = NSMenu.alloc.initWithTitle("Email address context menu")
item_0 = theMenu.insertItemWithTitle('add_to_address_book'.localized, action:'add_to_address_book', keyEquivalent:"", atIndex:0)
item_0.setTarget(self)
item_1 = theMenu.insertItemWithTitle('new_message'.localized, action:'new_message', keyEquivalent:"", atIndex:1)
item_1.setTarget(self)
theMenu
end
Which gives me something like this:
Something great but not what I am asking here.
| |
doc_677
|
{
const long BytesInKilobytes = 1024;
const long BytesInMegabytes = BytesInKilobytes * 1024;
const long BytesInGigabytes = BytesInMegabytes * 1024;
const long BytesInTerabytes = BytesInGigabytes * 1024;
Tuple<double, string> unit;
if (size < BytesInTerabytes)
if (size < BytesInGigabytes)
if (size < BytesInMegabytes)
if (size < BytesInKilobytes)
unit = Tuple.Create(size, "B");
else
unit = Tuple.Create(size / BytesInKilobytes, "KB");
else
unit = Tuple.Create(size / BytesInMegabytes, "MB");
else
unit = Tuple.Create(size / BytesInGigabytes, "GB");
else
unit = Tuple.Create(size, "TB");
return String.Format("{0} {1}",unit.Item1, unit.Item2);
}
In this case i see KB and what i get is: 116.1234567890 KB Im getting ten numbers after the point.
How can i make that it will give only two digits after the point ?
A: Just use any of the standard .NET formatting literals. To get a numeric value with two digits after the decimal point, you could use {0:n2}:
return String.Format("{0:n2} {1}", unit.Item1, unit.Item2);
This should give you:
116.12 KB
For more info, see the MSDN documentation on Standard Numeric Format Strings.
A: Use Math.Round
return String.Format("{0} {1}",Math.Round(unit.Item1, 2), unit.Item2);
| |
doc_678
|
I have a 100% width display: table container, and I'm trying to put a 16.666% width span, and a 83.3333% width input into it. But due to the strangest magic I'm ever seen, they don't fill the entire space. When inspecting the elements, I can see that the span width is calculated correctly, but the input width is far less than it should be, hence it doesn't fill the space that it should.
However, if I put two input elements (so an input instead of the span, it works as expected.
Please check out this DEMO fiddle
I've reproduced the issue in Chrome latest, and IE11 too, so I guess it's not a specific browser bug.
I'd like to know what's happening, and how to achieve my goal if not like this.
A: I would not use input as table-cell. Use something else instead and then set input to width 100% so it will fill the container.
Also added table-row:
<div class="w6">
<div style="display: table; background-color: brown;">
<div style="display: table-row" class="w12">
<span class="w2" style="display: table-cell; background-color: blue;"></span>
<!--<input type="text" class="w2"/>-->
<span class="w10">
<input type="text" />
</span>
</div>
</div>
</div>
https://jsfiddle.net/p4q40j22/1/
A: Set the css class for input as w12 so that the width is set to 100% of the remaining width
* {
box-sizing: border-box;
}
.w1 {
width: 8.33333333% !important;
}
.w2 {
width: 16.66666667% !important;
}
.w3 {
width: 25% !important;
}
.w4 {
width: 33.33333333% !important;
}
.w5 {
width: 41.66666667% !important;
}
.w6 {
width: 50% !important;
}
.w7 {
width: 58.33333333% !important;
}
.w8 {
width: 66.66666667% !important;
}
.w9 {
width: 75% !important;
}
.w10 {
width: 83.33333333% !important;
}
.w11 {
width: 91.66666667% !important;
}
.w12 {
width: 100% !important;
}
<div class="w6">
<div class="w12" style="display: table; background-color: brown;">
<span class="w2" style="display: table-cell; background-color: blue;"></span>
<!--<input type="text" class="w2"/>-->
<input type="text" class="w12"/>
</div>
</div>
| |
doc_679
|
For formating we are using AutoNumeric.js which is working fine.
What I need is to store value with default format which is sent to
backend on submit and display formated currency in input (for instance,
I want to display €10,000 to user and I should get value like 10000 to be
sent to backend). Values should be stored in it's own variables.
What is standard Angular way of doing this?
Thanks!
A: You can use simple own converter:
let yourValue = '€10,000'
let res = '';
for (let index of yourValue) {
if ( parseInt(el[index]) ) {
res += el[index]
}
}
console.log('your result = ', parseInt(numEl)) //your result = 10000
A: Angular already have a built-in currency pipe for it, all you need to play around it.
money = 10000; // backend value stored in DB
<!--display output in template '€10,000'-->
<div>{{ money | currency:'EUR':'symbol':'1.0'}}</div>
| |
doc_680
|
I appreciate some insights.
<ul>
<li><a class="menu-1" href="#"><i class="fa fa-home"></i> <span>1</span></a></li>
<li><a class="menu-1" href="#"><i class="fa fa-shopping-cart"></i> <span>2</span></a></li>
<li><a class="menu-1" href="#"><i class="fa fa-info"></i> <span>3</span></a></li>
<li><a class="menu-1" href="#"><i class="fa fa-circle-o-notch"></i> <span>4</span></a></li>
<li><a class="menu-1" href="#"><i class="fa fa-globe"></i> <span>5</span></a></li>
<li><a class="menu-1" href="#"><i class="fa fa-envelope"></i> <span>6</span></a></li>
</ul>
Here is my Jquery code:
$('nav ul li a').click(function(){
$('nav ul li .fa').eq($(this).index()).addClass('fa-spin').siblings().removeClass('fa-spin');
});
A: Your target elements are wrong - you need to add/remove the classes from the anchor elements
$('nav ul li a').click(function () {
$(this).addClass('fa-spin').parent().siblings().find('.fa-spin').removeClass('fa-spin');
});
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<nav>
<ul>
<li><a class="menu-1" href="#"><i class="fa fa-home"></i> <span>1</span></a></li>
<li><a class="menu-1" href="#"><i class="fa fa-shopping-cart"></i> <span>2</span></a></li>
<li><a class="menu-1" href="#"><i class="fa fa-info"></i> <span>3</span></a></li>
<li><a class="menu-1" href="#"><i class="fa fa-circle-o-notch"></i> <span>4</span></a></li>
<li><a class="menu-1" href="#"><i class="fa fa-globe"></i> <span>5</span></a></li>
<li><a class="menu-1" href="#"><i class="fa fa-envelope"></i> <span>6</span></a></li>
</ul>
</nav>
A: Try using the Web Animation API
Element.animate();
Then you won't need to add classes and remove classes
Simplest reference: http://updates.html5rocks.com/2014/05/Web-Animations---element-animate-is-now-in-Chrome-36
| |
doc_681
|
+-------+-----+
|country|prop1|
+-------+-----+
|RO | 1 |
|RO | 2 |
|UK | 1 |
|IT | 2 |
+-------+-----+
I want to count the rows for which the prop1 is not null and I use the following select:
SELECT `country`, COUNT(*) as number FROM table GROUP BY `country`;
this will return:
+-------+------+
|country|number|
+-------+------+
|RO | 2 |
|UK | 1 |
|IT | 1 |
+-------+------+
however I need the following:
+-------+------+
|country|number|
+-------+------+
|RO | 2 |
|UK | 1 |
|IT | 1 |
|FR | 0 |
+-------+------+
Do you think something like this can be possible to write directly in SQL? I was thinking something like specifying list of possible values for "country" and a default value (0) if it is not found in the table.
A: It's not obvious in your example where the FR comes from.
MySQL does not have a list of countries inside it, so country codes should be taken from somewhere.
If you have all countries inside mytable (with prop possibly set to NULL):
SELECT country, COUNT(prop) as number
FROM mytable
GROUP BY
country
If you have countries in a separate table (and a country may be missing in mytable):
SELECT c.id, COUNT(m.prop) as number
FROM countries c
LEFT JOIN
mytable m
ON m.country = c.id
GROUP BY
c.id
A: I think you will have to set up a table with all the countries. It will be best to alter your current table to use the keys of the countries. So that you can do a LEFT JOIN. That will give you all the countries, with NULL values if there are no props for that country.
| |
doc_682
|
This is my maze looks like
const App: React.FC = () => {
const Maze: MazeConstructor = MazeData;
const maze: IMaze = new Maze(mazeJson);
const [data, setData] = useState(maze.maze);
const handleClick = (): void => {
go(maze.entranceX, maze.entranceY);
}
const go = (x: number, y: number): void => {
let timer;
if (!maze.isInArea(x, y)) throw new Error('x or y is not inside the maze')
maze.visited![x][y] = true;
maze.path[x][y] = true;
maze.maze[x][y] = 1;
setData(Array.from(maze.maze))
if (x === maze.exitX && y === maze.exitY) return;
for (let i = 0; i < 4; i++) {
let newX = x + direction[i][0];
let newY = y + direction[i][1];
if (maze.isInArea(newX, newY) && maze.getCell(newX, newY) === MazeData.ROAD && !maze.visited![newX][newY]) {
setTimeout(()=>go(newX, newY),50);
}
}
if(timer) clearTimeout(timer);
}
return (
<div className="container">
<div className="wrapper">
{
data.map((item, index) =>
// to remove the gap between divs
<div style={{ fontSize: 0 }}>{
item.map(i => {
return <div className={classNames('cell', {
'wall': i === '#',
'path': i === 1,
'road': i === ' ',
})} />
}
)
}</div>
)
}
</div>
<button onClick={handleClick}>Solve</button>
</div>
);
}
In order to render the path only once at a time, I added a setTimeout to make it work. Otherwise, the path will be rendered without showing each step. However, I found out that it takes forever to finish the whole rendering. I am just wondering if it is the setTimeout that causes the problem or others. If so, is there any way to fix it of any other alternative to delay the recursion.
A: By adding setTimeout you have really changed the algorithm. Instead of the original depth-first search, it has become a breadth-first search.
As you iterate over neighbors, you invoke several setTimeout calls, which will be pending in parallel.
Because a call of go is scheduled with setTimeout without first setting visited to true for that cell, you will get situations where go will be scheduled to run on the same coordinates multiple times.
Also note that you never assign a value to timer, making the clearTimeout without use. This plan is also is not possible, because you are scheduling several timeouts simultaneously. So even after you have found the target, many timers will continue to timeout and still call go.
For introducing the pauses, I would suggest turning go into an async function, and to do an await on a setTimeout-based Promise. You would need to step away from recursion and implement an iterative solution instead, which could be based on a stack (so the search order could still be DFS).
Here is how that could look:
// Make function async:
const go = async (x: number, y: number): void => {
if (!maze.isInArea(x, y)) throw new Error('x or y is not inside the maze')
let stack = [[x, y]]; // A stack to replace the use of recursion
while (stack.length) {
let [x, y] = stack.pop();
if (maze.visited![x][y]) continue; // Already visited
maze.visited![x][y] = true;
maze.path[x][y] = true;
maze.maze[x][y] = 1;
setData(Array.from(maze.maze));
await new Promise(resolve => setTimeout(resolve, 10)); // Await 10ms
if (x === maze.exitX && y === maze.exitY) return;
// Reverse the direction of this loop to get the original DFS order
for (let i = 3; i >= 0; i--) {
let newX = x + direction[i][0];
let newY = y + direction[i][1];
if (maze.isInArea(newX, newY) && maze.getCell(newX, newY) === MazeData.ROAD
&& !maze.visited![newX][newY]) {
stack.push([newX, newY]);
}
}
}
}
As an alternative of setTimeout you could also use:
await new Promise(requestAnimationFrame); // Await next paint
The rendering of then thousand div elements at each step is quite demanding. A complete redesign where you would have a separate component for each cell, each with its own rendering and state, would improve the performance drastically.
| |
doc_683
|
Azure and now I want to connect to that database with using Azure connection string and my existing POCO clases.
My connection string:
<add name="CijenolomciContext" connectionString="Data Source=*.database.windows.net;Initial Catalog=NewCijenolomci;Persist Security Info=True;User ID=Bip*;Password=**;MultipleActiveResultSets=False"" providerName="System.Data.EntityClient" />
but this section of code happens to do nothing on the server:
Item i = new Item();
i.Name = "Cranberry";
i.OldPrice = new decimal(25.99);
i.NewPrice = new decimal(14.99);
i.SaleStarts = DateTime.Parse("2012-01-21");
i.CategoryID = 1;
context.Items.Add(i);
context.SaveChanges();
How to succesfully add it?
EDIT:
This approach happens to modify my local DB, not the Server one.
A: It doesn't look like you're connecting to an Azure database to me. I'd expect a connection string more like this.
Server=tcp:[serverName].database.windows.net;Database=myDataBase;User ID=[LoginForDb]@[serverName];Password=myPassword;Trusted_Connection=False;Encrypt=True;
Use 'username@servername' for the User ID parameter.
See Connection Strings for SQL Azure.
A: OK. Here it is. In DbContext i inherit base constructor:
public CijenolomciContext()
: base(*database name*)
{
//additional logic
}
and despite that i add my connection string in App.config he was always connecting to the local.
I hardcoded Connection string and just add it in the constructor. Now it works! :)
| |
doc_684
|
Heres the code I used to connect the tables:
Can someone please help me see where I've gone wrong?
Here are some screenshots of the three sets of data in my tables
, but when I do the search query, it shows me double the amount of data.
![See that it has doubles =][2]
A: You can use the DISTINCT key in sql if you need 'unique' results:
SELECT DISTINCT users.user_id, users.user_email, system.date, system.time, system.table_layout, details.party_size, details.children_no, details.diets,
details.occassion, details.more FROM users
Join system on users.user_id = system.id
Join details on system.id = details.ID
ORDER BY users.user_id
This however will not change your current result as it is already unique as pointed out by Gordon Linoff.
You can play around with the query
SELECT users.user_id, users.user_email, system.date, system.time, system.table_layout, details.party_size, details.children_no, details.diets,
details.occassion, details.more FROM users
Join system on users.user_id = system.id
Join details on system.id = details.ID
ORDER BY users.user_id
WHERE [table].[column] = (SELECT DISTINCT [column] FROM [table])
Where the [column] is the column that should be unique in the [table].
You can combine multiple WHERE x = (select y from z) clauses to refine your results.
A: Hey you just need to join the tables by the unique id so please use the below code you will get unique list
SELECT users.user_id, users.user_email, system.date, system.time, system.table_layout, details.party_size, details.children_no, details.diets, details.occassion, details.more FROM users Join system on users.user_id = system.user_id Join details on users.user_id = details.user_id ORDER BY users.user_id
A: How the value coming as "Other" in column occasion ?
I can see there are two set of rows created for same user but the columns Party_size, children_no, "occasion" have different values, so how can it be the duplicate rows?
| |
doc_685
|
How do I get rid of this 8.4 DB?
Here's a screenshot: http://imageupload.org/?d=4D9F98A51
And another: http://imageupload.org/?d=4D9F99391
Thank you
A: List of servers displayed by pgAdmin is (on OSX) located in:
~/Library/Preferences/pgadmin3 Preferences
Have fun editing this file manually :)
Look for a line Description=PostgreSQL 8.4 it will be included in a section called something like [Servers/1] or [Servers/2] remove the whole section and all sections called [Servers/n/*]
A: Select it first, then delete it?
Later . . .
Looks like a bug in pgadmin3. The suggestion seems to be moving in the direction of deleting a key from the registry on Windows. I'm not sure whether that will be in your preferences on OSX.
| |
doc_686
|
using retrofit, I think the reason is that the function getIndexRetrofit() is returned before the line execute data.value = res. So I wanna syncronize this, expecting the function to return not null but the response values.
Repository:
fun getIndexRetrofit(name:String) : MutableLiveData<UserModel>{
Retrofit2Service.getService().requestUserInfo(name).enqueue(object: Callback<UserModel> {
override fun onFailure(call: Call<UserModel>, t: Throwable) {
data.postValue(null)
}
override fun onResponse(call: Call<UserModel>, response: Response<UserModel>) {
if(response.body()!=null) {
var res = response.body()!!
data.value = res
}
}
})//Retrofit
return data
}
A: I can't say what getIndexRetrofit() suppose to do, but I believe you are misusing live data here. You are making asynchronous call Retrofit2Service.getService().requestUserInfo(name).enqueue It will be called, request will be made, but the result of execution is not yet received, at the same time return data will happen.
Understand that onFailure() and onResponse() are callbacks, and the code will not be executed immediately. You code is not meant to be read sequentially top to bottom. Sequence of execution will be next
*
*Retrofit2Service.getService().requestUserInfo(name).enqueue
*return data
*onResponse() or onFailure()
You should not return anything in getIndexRetrofit() instead refactor your function to look like that
fun getIndexRetrofit(name:String) {
Retrofit2Service.getService().requestUserInfo(name).enqueue(object: Callback<UserModel> {
override fun onFailure(call: Call<UserModel>, t: Throwable) {
data.postValue(null)
}
override fun onResponse(call: Call<UserModel>, response: Response<UserModel>) {
if(response.body()!=null) {
var res = response.body()!!
data.value = res
}
}
})
}
| |
doc_687
|
def copiarDirs():
items = list.curselection()
desti = tkFileDialog.askdirectory()
for dirs in os.walk(items, topdown=False):
for name in dirs:
#for i in items :
aux=root+"/"+list.get(i)
tryhard=("cp "+str(aux)+" "+str(desti))
os.system(tryhard)
A: Try this:
import os
def copyDirs(source, destination):
for subdir, dirs, files in os.walk(source):
for f in files:
dir = destination + os.path.join(subdir).split(':')[1]
if not os.path.exists(dir):
os.makedirs(dir)
sourceDir = 'D:\\Work\\'
destDir = 'D:\\Dest\\'
copyDirs(sourceDir, destDir) #calling function
| |
doc_688
|
A: You can access this interface from the New Cloud Control Panel by clicking your username in the upper-right of the control panel and selecting "Classic Cloud Control Panel, I think this answer is useful for you
| |
doc_689
|
Possible Duplicate:
Python split() without removing the delimiter
I wish to split a string as follows:
text = " T?e qu!ck ' brown 1 fox! jumps-.ver. the 'lazy' doG? !"
result -> (" T?e qu!ck ' brown 1 fox!", "jumps-.ver.", "the 'lazy' doG?", "!")
So basically I want to split at ". ", "! " or "? " but I want the spaces at the split points to be removed but not the dot, comma or question-mark.
How can I do this in an efficient way?
The str split function takes only on separator. I wonder is the best solution to split on all spaces and then find those that end with dot, comma or question-mark when constructing the required result.
A: You can achieve this using a regular expression split:
>>> import re
>>> text = " T?e qu!ck ' brown 1 fox! jumps-.ver. the 'lazy' doG? !"
>>> re.split('(?<=[.!?]) +',text)
[" T?e qu!ck ' brown 1 fox!", 'jumps-.ver.', "the 'lazy' doG?", '!']
The regular expression '(?<=[.!?]) +' means match a sequence of one or more spaces (' +') only if preceded by a ., ! or ? character ('(?<=[.!?])').
| |
doc_690
|
Thanks in advance.
A: class Singleton; // forward declaration
Singleton * s = NULL; // global object available to all threads
// Place this class in a location unavailable to all threads except Main thread
class ManageSingleton
{
public:
static void DestroySingleton(Singleton * s)
{
delete s;
}
}
class Singleton
{
friend class ManageSingleton;
protected:
~Singleton() {}
};
void main()
{
s = new Singleton;
while (...)
{
// other threads access Singleton object until program is finished
}
// Program is now finished; destroy Singleton object
ManageSingleton::DestroySingleton(s);
}
A: threading really works against this design, especially if you want a pure singleton. you can visualize it like so:
class t_singleton {
public:
static t_singleton& Get() {
/* thread safety is a consideration here: */
t_auto_ptr<t_singleton>& shared(Shared());
if (shared.isNull()) {
shared.setObject(new t_singleton);
}
/* and you should manage external references using another container type: */
return Shared().reference();
}
static void DestroyIt() {
/* thread safety is a consideration here: */
Shared().destroy();
}
private:
static t_auto_ptr<t_singleton>& Shared() {
static t_auto_ptr<t_singleton> s_Shared;
return s_Shared;
}
private:
t_singleton();
~t_singleton();
};
but this should also suggest many threading red flags with pure singletons.
If you really want to extend this and enforce a pure singleton, you would need proper reference counting containers -- this suggests a singleton is a bad solution for this problem in multiple ways, and just adds a ton of unnecessary complexity. good luck!
A: Make the destructor private and provide a Destroyer class that is responsible for destroying and cleaning up all the memory of the Singleton. It will need to be a friend of the Singleton class. To add to that, are you sure you absolutely need a singleton? Or is this another overuse scenario?
| |
doc_691
|
Occurs occasionally from 8/26.
GET https://graph.microsoft.com/v1.0/drives/{drive-id}/root:/{file-name}.xlsx:/content HTTP/1.1
SdkVersion: Graph-dotnet-1.4.0
Authorization: bearer {token}
Cache-Control: no-store, no-cache
Host: graph.microsoft.com
Connection: Keep-Alive
HTTP/1.1 200 OK
Date: Fri, 28 Aug 2020 03:20:43 GMT
Cache-Control: no-cache
Location: https://{tenant-name}-my.sharepoint.com/personal/{user-name}_onmicrosoft_com/_layouts/15/download.aspx?UniqueId={unique-id}&Translate=false&tempauth={tempauth}&ApiVersion=2.1
Strict-Transport-Security: max-age=31536000
request-id: {request-id}
client-request-id: {client-request-id}
x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"Japan East","Slice":"E","Ring":"2","ScaleUnit":"000","RoleInstance":"TY1PEPF00000CC9"}}
Content-Length: 0
| |
doc_692
|
A: A question I would ask.. What is the use case where you wouldn't want to display the wordcloud?
The libraries will generally rely on canvas to generate the word cloud so obviously it wont work unless its in the browser. If you are trying to generate something that is saved in an image then you would need a way to tally up each item, maybe in an array with its corresponding 'count' and then at the end print those words to and image with varying font sizes based on their 'count' in the array.
Again, without know the use case its hard to say for sure.
| |
doc_693
|
Is that the only way to do with dialog jqueryui?
A: You don't have to hide content. I think you are not using autoOpen attribute of jquery dialog. Jquery ui dialog hides the content if you use autoOpen:true.
<div id="dialog_content">
<p>Here goes your dialog content</p>
<input type="text" placeholder='sample text'>
</div>
<button id="click_me">
Click Me
</button>
and the script
$(document).ready(function(){
$('#dialog_content').dialog({
autoOpen:false
});
$('#click_me').click(function(){
$('#dialog_content').dialog('open');
});
});
Check this demo
If this is not what you mean, then please post issue with a code
A: <div id="dialog">
<p>
This is a text dialog
</p>
</div>
$('#dialog').dialog({
autoOpen: false
});
Even with autoOpen is set to false, it displays the text "This is a text dialog" inside the . I have to hide with CSS, but I think this is a issue I should be avoiding by using the JQueryUI dialog.
| |
doc_694
|
The documentation here states that the option sets:
the maximum time in seconds a script is allowed to run
How does this work for includes/requires?
Example:
file1.php
<?php
include("file2.php");
include("file3.php");
?>
file2.php
<?php
//some script that takes 6 minutes
?>
file3.php
<?php
echo "hello"
?>
If file2.php takes 6 minutes (and the max_execution_time is set to 5 minutes), does control pass back to file1.php and continue running, or does the whole file quit?
A: The execution breaks and throw a error.
A: Max execution time is the time your script can be executed. No matter how many includes do you have. So if if at any point of time the script will run out of time, everything will stop and you will receive
Fatal error: Maximum execution time of XX seconds exceeded
| |
doc_695
|
@IBAction func submitText(_ sender: Any) {
if let domain = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: domain)
}
llble.text = String(describing: result) + "\n"
UserDefaults.standard.set(llble.text, forKey: "name")
}
override func viewDidAppear(_ animated: Bool) {
let save : String? = UserDefaults.standard.object(forKey: "name") as? String
if let nameToDisplay = save {
llble.text = nameToDisplay
}
}
A: Swift 4:
if let domain = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: domain)
}
Swift 3:
if let domain = NSBundle.mainBundle().bundleIdentifier {
NSUserDefaults.standardUserDefaults().removePersistentDomainForName(
domain)
}
Objective-C:
NSString *domain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName: domain];
Calling this method is equivalent to initializing a user defaults object with init(suiteName:) passing domainName, and calling the removeObject(forKey:) method on each of its keys.
Also synchronize() is a legacy method and is unnecessary and shouldn't be used.
A: You should check the logic of result variable that is providing the string to the userdefault.
A: You can use the following approach in Swift. This would remove and delete all possible user defaults value.
UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!)
UserDefaults.standard.synchronize()
| |
doc_696
|
What is the best way to handle this situation to create sample builds for them?
Thanks in advance.
A: A service like testflight would be my starting point.
You build an adhoc build, register their devices, and distribute it to them to test it.
You don't need their Distribution profiles, and they don't need your code. Everyone's fairly happy!
A: I did some research on the Apple Developer Website and I think I have found the answer to my question
I am a contractor who wants to create an in-house app for my client. Can I join the iOS Developer Enterprise Program to do that?
No. The iOS Developer Enterprise Program is for companies/organizations to develop and distribute proprietary in-house apps to their employees.
Your client should enroll in the iOS Developer Enterprise Program and add the appropriate developers from your company to their iOS Development Team.
From reading that It sounds like I need to have them add me as a developer on the team which will give me some limited access.
A: You could add their testing device(s) to your own adhoc profile and distribute the app with your adhoc-certificate.
| |
doc_697
|
My initial collection
{
"campaigns": [
{
"name": "1st Campaign",
"campaignType": "Test Campaign",
"startDate": "2019/04/03",
"endDate": "2019/04/30",
"price": 1,
"books": [
{
"title": "\"If They Move . . . Kill 'Em!\"",
"bookdata": {
"batch": 2
}
},
{
"title": "!Click Song",
"bookdata": {
"batch": null
}
}
]
},
{
"name": "2nd cam",
"campaignType": "test type",
"startDate": "2019/04/10",
"endDate": "2019/04/10",
"price": 2.99,
"retailers": null,
"comments": null,
"books": [
{
"title": "\"Johnny, We Hardly Knew Ye\"",
"bookdata": {
"batch": null
}
},
{
"title": "'A Very Fine Commander'",
"bookdata": {
"batch": 2
}
}
]
}
]
}
For each campaign i need structure like following where books title is comma separated for each books under campaign
{
"campaigns": [
{
"name": "1st Campaign",
"campaignType": "Test Campaign",
"startDate": "2019/04/03",
"endDate": "2019/04/30",
"price": 1,
"booksname": "\"If They Move . . . Kill 'Em!\"","!Click Song"
"books": [
{
"title": "\"If They Move . . . Kill 'Em!\"",
"bookdata": {
"batch": 2
}
},
{
"title": "!Click Song",
"bookdata": {
"batch": null
}
}
]
},
{
"name": "2nd cam",
"campaignType": "test type",
"startDate": "2019/04/10",
"endDate": "2019/04/10",
"price": 2.99,
"retailers": null,
"comments": null,
"books": [
{
"title": "\"Johnny, We Hardly Knew Ye\"",
"bookdata": {
"batch": null
}
},
{
"title": "'A Very Fine Commander'",
"bookdata": {
"batch": 2
}
}
]
}
]
}
A: I was able to do it using
data.campaigns.map((item) => {
item.Booksname = _.map(item.books, 'title').join(',');
})
| |
doc_698
|
One major Feature that I need is a memorymappedfile! (for inter process communication)
So I tried to create one in Xamarin Projekt - but the .net Service could not find the memorymappedfile.
After that I tried to created the MemorymappedFile in the .net Service:
var CustomSecurity = new MemoryMappedFileSecurity();
CustomSecurity.AddAccessRule(new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>("Everyone", MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
using (var memoryMappedFile = MemoryMappedFile.CreateNew("test", 102400,MemoryMappedFileAccess.ReadWriteExecute,MemoryMappedFileOptions.None, CustomSecurity,System.IO.HandleInheritability.None))
{
var accessor = memoryMappedFile.CreateViewAccessor();
accessor.Write(0, 42);}
Now Xamarin can find the MemoryMappedFile, but when I run into an UnauthorizedAccessException:
var memoryMappedFile = MemoryMappedFile.OpenExisting("test");
var accessor = memoryMappedFile3.CreateViewAccessor();
But another none Xamarin.Forms Project (wpf projekt) can Access this memorymappedfile with the same Code!
I hope some one can help me or tell me how to use a MemoryMappedFile with Xamarin.
My Xamarin App use Xamarin.Forms with .net Standard 1.4 and I installed NuggetPackage: System.IO.MemoryMappedFile to get Access to MemoryMappedFile Basics (without MemoryMappedFileSecurity() )
Thanks a lot.
| |
doc_699
|
https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text%3D%27delhi%27&format=json
Result i received
{"query":{"count":0,"created":"2018-03-14T10:51:42Z","lang":"en-US","results":null}}
Even on https://developer.yahoo.com/weather/ it's showing null.
Is there any other way to get woeid for yahoo weather.
Best Regards, Ashish
A: I have the same problem!!
I have a scheduled script that cycles the temperatures of some cities and that has received data until this morning at 07:00 gmt + 1.
I think it depends on the yahoo service!
maybe they have modified some parameters
A: Should be working. I emailed yql-team@yahoo-inc.com yesterday about this issue being down, did not get a response but the issues is resolved on my end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.