id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23532300
|
I am using VS 2015.
A: This is the default behavior of EF Core (filling up the DbParameterLogData.Value property with "?").
In order to get the real parameter values, you need to enable sensitive data logging by using DbContextOptionsBuilder.EnableSensitiveDataLogging method:
Enables application data to be included in exception messages, logging, etc. This can include the values assigned to properties of your entity instances, parameter values for commands being sent to the database, and other such data. You should only enable this flag if you have the appropriate security measures in place based on the sensitivity of this data.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.EnableSensitiveDataLogging();
// ...
}
| |
doc_23532301
|
ActiveRecord::InvalidForeignKey in TagsController#destroy
Here are my code for delete tag in controller:
def destroy
@tag = Tag.find(params[:id])
@tag.destroy
flash.notice = "Tag '#{@tag.name}' Deleted!"
redirect_to tags_path
end
This is the schema.rb
ActiveRecord::Schema.define(version: 2021_03_20_115719) do
create_table "articles", force: :cascade do |t|
t.string "title"
t.text "body"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "comments", force: :cascade do |t|
t.string "author_name"
t.text "body"
t.integer "article_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["article_id"], name: "index_comments_on_article_id"
end
create_table "taggings", force: :cascade do |t|
t.integer "tag_id", null: false
t.integer "article_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["article_id"], name: "index_taggings_on_article_id"
t.index ["tag_id"], name: "index_taggings_on_tag_id"
end
create_table "tags", force: :cascade do |t|
t.string "name"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
add_foreign_key "comments", "articles"
add_foreign_key "taggings", "articles"
add_foreign_key "taggings", "tags"
end
A: A failed FOREIGN KEY constraint usually means that you have another record in your database that still has a belongs_to association set to this record and therefore you cannot delete it.
In your example, there is an article tagged with the tag you are trying to delete.
create_table "taggings", force: :cascade do |t|
t.integer "tag_id", null: false # << here the association
t.integer "article_id", null: false
# in combination with
add_foreign_key "taggings", "articles"
add_foreign_key "taggings", "tags" # << here the foreign key constraint
Your schema.rb shows that you have a taggings join table that connects articles with tags and in this table, both attributes (the tag_id and the article_id) cannot be nil and must contain a valid id that identifies a record on the associated table.
That means when you want to delete a specific tag then you have to remove the tag from the taggings join table first. The following code should work:
def destroy
@tag = Tag.find(params[:id])
@tag.articles.clear # << add this line
@tag.destroy
flash.notice = "Tag '#{@tag.name}' Deleted!"
redirect_to tags_path
end
Read about collection.clear and the usage of the has_and_belongs_to association in general in the Rails Guides.
| |
doc_23532302
|
dict[dict[str, str]]
But what if I want to make hints for dict of unknown depth?
For example, I want to write a function, which construct tree in dict form from list of tuples (parent, offspring):
source = [('a', 'b'), ('b', 'c'), ('d', 'e')]
target = {'a': {'b': {'c': {}}}, 'd': {'e': {}}}
def tree_form(source: list[tuple[str, str]]) -> ???:
"""code"""
pass
What should I write instead of '???'?
A: You can use a type alias with a forward reference to itself:
from typing import TypeAlias
NestedDict: TypeAlias = dict[str, str | 'NestedDict']
def tree_form(source: list[tuple[str, str]]) -> NestedDict:
return {'a': {'b': {'c': {}}}, 'd': {'e': {}}}
print(tree_form([('a', 'b'), ('b', 'c'), ('d', 'e')]))
Demo of this code passing mypy:
https://mypy-play.net/?mypy=latest&python=3.10&gist=6d359c16ab3f5e82b5cd2cdf9e142a6d
| |
doc_23532303
|
Object.prototype.toString("foo"); // output: "[object Object]"
Object.prototype.toString.call("foo"); // output: "[object String]"
I think I may have a faint idea but I can't express in words... can anyone explain?
A: The two calls are NOT equivalent.
The first call:
Object.prototype.toString("foo");
calls the toString method in the context of Object.prototype, with an additional "foo" parameter (unused), and Object.prototype is an Object, so the result is [object Object]
The second call:
Object.prototype.toString.call("foo");
calls the toString method in the context of "foo", and Object.prototype.toString builds an object from it (new String("foo")), so the result is [object String]
A: The first parameter of call is the object that will be this inside the function, not the first parameter of the function:
"use strict";
function test(a,b) {
console.log(this, a, b);
};
var obj = {
'func' : test
}
test(1,2) // outputs undefined 1 2
test.call(1,2); // outputs 1 2 undefined
obj.func(1,2) // outputs obj 1 2
obj.func.call(1,2) // outputs 1 2 undefined
| |
doc_23532304
|
<select multiple="" name="playerNames" id="playerNames" class="">
<option value="">-- Select --</option>
<option value="4">Rakesh</option>
<option value="5">Suresh</option>
<option value="2">Mahesh</option>
<option value="6">Dilip</option>
<option value="1">Ramesh</option>
<option value="3">Dinesh</option>
</select>
<script type="text/javascript">
$('#playerNames').on('change',function(){
var selected = $('#playerNames:selected').map(function(){return $(this).val();}).get();
alert(selected.length);
if(jQuery.inArray("Mahesh", selected) !== -1){
var maheshSelected = true;
}
if(jQuery.inArray("Dilip", selected) !== -1){
var dilipSelected = true;
}
if(maheshSelected == true && dilipSelected == true){
var alertMessage = "You cannot choose Mahesh + Dilip. Please select either Mahesh or Dilip.";
alert(alertMessage);
if (confirm(alertMessage)) {
//code to deselect both
}
}
});
A: You can select the options using $('option:contains(Mahesh), option:contains(Dilip)') and deselect them using .prop('selected', false):
$('#playerNames').on('change', function(){
const selected = $('#playerNames :selected').map(function() {return $(this).text()}).get()
if (selected.includes('Mahesh') && selected.includes('Dilip')) {
alert('You cannot choose Mahesh + Dilip. Please select either Mahesh or Dilip.')
$('option:contains(Mahesh), option:contains(Dilip)').prop('selected', false)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="" name="playerNames" id="playerNames" class="">
<option value="">-- Select --</option>
<option value="4">Rakesh</option>
<option value="5">Suresh</option>
<option value="2">Mahesh</option>
<option value="6">Dilip</option>
<option value="1">Ramesh</option>
<option value="3">Dinesh</option>
</select>
Here's a cross-browser solution (works on Internet Explorer 9+):
$('#playerNames').on('change', function(){
var selected = $('#playerNames :selected').map(function() {return $(this).text()}).get()
if (selected.indexOf('Mahesh') > -1 && selected.indexOf('Dilip') > -1) {
alert('You cannot choose Mahesh + Dilip. Please select either Mahesh or Dilip.')
$('option:contains(Mahesh), option:contains(Dilip)').prop('selected', false)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="" name="playerNames" id="playerNames" class="">
<option value="">-- Select --</option>
<option value="4">Rakesh</option>
<option value="5">Suresh</option>
<option value="2">Mahesh</option>
<option value="6">Dilip</option>
<option value="1">Ramesh</option>
<option value="3">Dinesh</option>
</select>
| |
doc_23532305
|
I have following code to get the previous date from the current date.
-(NSDate*)previousDateFromDate:(NSDate*)date {
NSDate *now = date;
int daysToAdd = -1;
// set up date components
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:daysToAdd];
// create a calendar
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:GregorianCalendar];
return [gregorian dateByAddingComponents:components toDate:now options:0];
}
How can I achieve this ? Is it by calculating difference of index of the current day ?
A: You've got the right idea and using the weekday number is the way to go, comments in code:
-(NSDate*)previousDateFromDate:(NSDate*)date
{
// Get the current calendar
NSCalendar *currentCal = [NSCalendar currentCalendar];
// Get current weekday, Sunday = 1
NSDateComponents *comps = [currentCal components:NSWeekdayCalendarUnit fromDate:date];
NSInteger weekday = comps.weekday;
// Determine the number of days to go back, assuming Sat -> Mond should go to Fri
NSInteger deltaDays = weekday == 1 ? -2 : (weekday == 2 ? -3 : -1);
// Create componets with the offset
NSDateComponents *offset = [NSDateComponents new];
offset.day = deltaDays;
// Calculate the required date
return [currentCal dateByAddingComponents:offset toDate:date options:0];
}
This assumes the current calendar is the Gregorian one, you'll have to figure out if it works for others.
HTH
A: -(NSDate*)previousDateFromDate:(NSDate*)date {
NSCalendar* cal = [NSCalendar currentCalendar];
NSDateComponents* comp = [cal components:NSWeekdayCalendarUnit fromDate:date];
//[comp weekday] = 1 = Sunday, 2 = Monday, etc.
NSDate * returnDate;
if([comp weekday] == 1){
returnDate = [[NSDate date]dateByAddingTimeInterval:(-86400 * 2)];
}else {
returnDate = [[NSDate date]dateByAddingTimeInterval:-86400];
}
return returnDate;
}
| |
doc_23532306
|
Which is better in terms of processing speed
*
*when there are many records?
*when there is small number of records?
CODE
string entryValue = "A,B, a , b, ";
if (!String.IsNullOrEmpty(entryValue.Trim()))
{
//APPROACH 1
bool isUnique = true;
//Hash set is unique set -- Case sensitivty Ignored
HashSet<string> uniqueRecipientsSet = new HashSet<string>(entryValue.Trim().Split(',').Select(t => t.Trim()),StringComparer.OrdinalIgnoreCase );
//List can hold duplicates
List<string> completeItems = new List<string>(entryValue.Trim().Split(',').Select(t => t.Trim()));
if (completeItems.Count != uniqueRecipientsSet.Count)
{
isUnique = false;
}
//APPROACH 2
bool isUniqueCheck2 = true;
string[] words = entryValue.Split(',');
Array.Sort(words);
for (int i = 1; i < words.Length; i++)
{
if (words[i].ToLower().Trim() == words[i - 1].ToLower().Trim())
{
isUniqueCheck2 = false;
break;
}
}
bool result1 = isUnique;
bool result2 = isUniqueCheck2;
}
REFERENCES:
*
*Split comma separated string to count duplicates
*MSDN Blog - Find Duplicates using LINQ
A: You can simplify your first approach:
List<string> completeItems = new List<string>(entryValue.Trim().Split(',').Select(t => t.Trim()));
isUnique = completeItems.Count == completeItems.Distinct().Count();
This would eliminate multiple splitting, and hide the hash set behind the call of Distinct(). Note that the if statement is also unnecessary.
A: The hashset approach is O(n); the sort approach is O(n log n).
However, an even quicker option would be to short-circuit the hashset approach by stopping as soon as you first see a duplicate:
HashSet<string> uniqueRecipientsSet
= new HashSet<string>(StringComparer.OrdinalIgnoreCase);
bool isUnique = true;
foreach(var item in entryValue.Split(',').Select(t => t.Trim()))
{
if (!uniqueRecipientsSet.Add(item))
{
isUnique = false;
break;
}
}
You could hide the foreach loop in LINQ:
HashSet<string> uniqueRecipientsSet
= new HashSet<string>(StringComparer.OrdinalIgnoreCase);
bool isUnique = entryValue.Split(',').Select(t => t.Trim())
.All(i => uniqueRecipientsSet.Add(i));
This is "LINQ-with-side-effects" but it does reduce the whole thing to two lines.
You could write your own AreAllDistinct extension method to avoid the side-effect-iness:
public static bool AreAllDistinct<T>(
this IEnumerable<T> source, IEqualityComparer<T> comparer)
{
HashSet<T> checker = new HashSet<T>(comparer);
foreach (var t in T)
if (!checker.Add(t))
return false;
return true;
}
bool isUnique = entryValue.Split(',').Select(t => t.Trim())
.AreAllDistinct(StringComparer.OrdinalIgnoreCase);
A: You could have used StopWatch yourself. The first approach is a little bit faster:
1) 00:00:00.0460701 2) 00:00:00.0628364
Each approach 10000 repitions (just a simple way to measure the time)
| |
doc_23532307
|
const [netflixData, setNetflixData] = useState({});
const [page, setPage] = useState(1);
const countPerPage = 10;
const getNetflixData = () => {
axios.get(`/netflix/ranks/?page=${page}`, config).then(res => {
setNetflixData(res.data);
}).catch(err => {
setNetflixData({});
});
};
const options = {
filter: true,
filterType: 'multiselect',
serverSide: true,
count: netflixData.count,
rowsPerPage: countPerPage,
rowsPerPageOptions: [],
onTableChange: (action, tableState) => {
if (action === 'changePage') {
setPage(tableState.page);
} else {
console.log('action not handled.');
}
},
};
useEffect(() =>{
getNetflixData()
}, [page]
);
<MUIDataTable
title={"Netflix Rankings"}
data={netflixData.results}
columns={columns}
options={options}
/>
Basically, on page load tableState.page should be 1, but, nothing happens, so when I click 'next page', it changes to 1, 3rd page, tableState.page is 2, so if I go back twice, it'll be 0, which doesn't exist.
I tried adding the option, page: 1, but that just defaults me to the second page of the table. Any ideas on how to set tableState.page = 1 on page/table load?
A: Try using setPage(tableState.page + 1). Your page number on the state will be one-based and on the datatable it will be zero-based. I don't know if you can make the datatable paging one-based.
| |
doc_23532308
|
for row in c:
print(row)
Whenever I go this, the output is always:
('text field 1', 'text field 2', 'text field 3', 'text field 4')
I've been googling and cannot find the answer, is there a way I can make it like
text field 1, text field 2, text field 3, text field 4
?
A: You printed the whole row, which is a tuple. To print it with a little formatting, you could use ''.join():
', '.join(row)
A: or you can use this
from itertools import imap
",".join(imap(str, row))
| |
doc_23532309
|
The result change using different joins and declared variables or costants.
What's going on?
declare @inserted table
(id int,
tnumber nvarchar(50),
id_prod_inesito int
);
insert into @inserted
values
(41649,'0438492300',172400);
select pic.ID
,PIC.ID_PROD_INESITO
,pic.NUMERO_TELEFONO
,pic.IS_REQUESTED
,ins.*
,min(pic.id) over(partition by pic.numero_telefono) as min_id
from prod_ivr_call as pic
inner join prod_inesito as pin
on pic.ID_PROD_INESITO = pin.ID
left join @inserted as ins
on ins.ID_PROD_INESITO = pin.ID
where pic.is_requested = 0;
If I change the join in a inner join
select pic.ID
,PIC.ID_PROD_INESITO
,pic.NUMERO_TELEFONO
,pic.IS_REQUESTED
,ins.*
,min(pic.id) over(partition by pic.numero_telefono) as min_id
from prod_ivr_call as pic
inner join prod_inesito as pin
on pic.ID_PROD_INESITO = pin.ID
join @inserted as ins
on ins.ID_PROD_INESITO = pin.ID
where pic.is_requested = 0;
or
select pic.ID
,PIC.ID_PROD_INESITO
,pic.NUMERO_TELEFONO
,pic.IS_REQUESTED
,ins.*
,min(pic.id) over(partition by pic.numero_telefono) as min_id
from prod_ivr_call as pic
inner join prod_inesito as pin
on pic.ID_PROD_INESITO = pin.ID
left join @inserted as ins
on ins.ID_PROD_INESITO = pin.ID
where pic.is_requested = 0
and ins.id is not null;
instead writing
select pic.ID
,PIC.ID_PROD_INESITO
,pic.NUMERO_TELEFONO
,pic.IS_REQUESTED
,ins.*
,min(pic.id) over(partition by pic.numero_telefono) as min_id
from prod_ivr_call as pic
inner join prod_inesito as pin
on pic.ID_PROD_INESITO = pin.ID
left join @inserted as ins
on ins.ID_PROD_INESITO = pin.ID
where pic.is_requested = 0
and numero_telefono = '0438492300';
finally writing
select pic.ID
,PIC.ID_PROD_INESITO
,pic.NUMERO_TELEFONO
,pic.IS_REQUESTED
,ins.*
,min(pic.id) over(partition by pic.numero_telefono) as min_id
from prod_ivr_call as pic
inner join prod_inesito as pin
on pic.ID_PROD_INESITO = pin.ID
left join @inserted as ins
on ins.ID_PROD_INESITO = pin.ID
where pic.is_requested = 0
and numero_telefono = ins.tnumber;
A: Of course it changes.
You are finding the min prod_ivr_call.id value from the list of values returned by your query, not the table as a whole. By adding the additional filters that remove the non-matched values from this table (ie: where @inserted.id is null), the min value will be different.
What has happened here is that you have misunderstood how windowed functions work.
| |
doc_23532310
|
<c:forEach var="l" value="${logs}">
...
</c:forEach>
and it says:
Attribute value invalid for tag forEach according to TLD
A: The forEach tag does not support the value attribute. I.e. the <c:forEach value> is not recognized. Really, that's basically what the error is trying to tell you.
If you consult the documentation of the forEach tag, then you'll see that the value attribute is indeed not mentioned in the attributes table. Only the following attributes are listed:
*
*items - Collection of items to iterate over.
*begin - If items specified: Iteration begins at the item located at the specified index. First item of the collection has index 0. If items not specified: Iteration begins with index set at the value specified.
*end - If items specified: Iteration ends at the item located at the specified index (inclusive). If items not specified: Iteration ends when index reaches the value specified.
*step - Iteration will only process every step items of the collection, starting with the first one.
*var - Name of the exported scoped variable for the current item of the iteration. This scoped variable has nested visibility. Its type depends on the object of the underlying collection.
*varStatus - Name of the exported scoped variable for the status of the iteration. Object exported is of type javax.servlet.jsp.jstl.core.LoopTagStatus. This scoped variable has nested visibility.
Guess which one you actually need. In case you're unsure, the Java EE tutorial may help.
| |
doc_23532311
|
...
<asp:DataList ID="DataListDziennik" runat="server"
DataSourceID="SqlDataSourcePrzedmioty">
<ItemTemplate>
<asp:Label ID="LabelPrzedmiot" runat="server" Text='<%# Eval("przedmiot") %>' />
...
<asp:DataList ID="DataListOceny" runat="server"
DataSourceID="SqlDataSourceOceny"
RepeatDirection="Horizontal"
OnItemCommand="DataListOceny_ItemCommandOceny"
OnEditCommand="DataListOceny_EditCommandOceny">
<EditItemTemplate>
<asp:TextBox ID="TextBoxOcena" runat="server" Text='<%# Bind("lista") %>' />
<td><asp:Button ID="ButtonZapisz" CommandName="Update" runat="server" Text="Zapisz" /></td>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox Width="20" ID="TextBoxOcena" ReadOnly="true" Text='<%# Eval("lista") %>' runat="server"></asp:TextBox>
<td><asp:Button ID="ButtonEdytuj" CommandName="Edit" runat="server" Text="Edytuj" /></td>
</ItemTemplate>
</asp:DataList>
</td>
</ItemTemplate>
</asp:DataList>
When I write this in code behind:
protected void DataListOceny_EditCommand(object source, DataListCommandEventArgs e)
{
DataListOceny.EditItemIndex = e.Item.ItemIndex;
DataListOceny.DataBind();
}
...Visual Studio tells me that DataListOceny does not exist in current content. I just want to be able edit items on DataListOceny after clicking the "edit" button, it can be placed anywhere on website. Do you know any solution for this problem?
A: Because DataListOceny is a control inside of another control, you have to make a reference to it by doing something like:
DataList DataListOceny = (DataList)e.Item.FindControl("DataListOceny");
Once you do that, you can use the DataListOceny variable. Hope this helps.
| |
doc_23532312
|
e.g
<html>
<body>
<div>
<div>
<script async src="https://tag.simpli.fi/sifitag/f8386e60-0805-0135-53dd-0cc47a63c1a4"></script>
</div>
</div>
</body>
</html>
A: This forces your browser to stop processing the HTML, immediately download, and execute the JavaScript before continuing. It's an inefficient way to deal with scripts.
If this script relies on this behavior, it probably isn't following best practices by using document.write() and such.
Also don't forget that script tags need a closing </script>.
| |
doc_23532313
|
I need a boolean value in the model, but the database saves it as VARCHAR2(1 CHAR) with t or f. How can I access and write t/f on Oracle side and use it as boolean in Symfony?
Thanks!
Mitja
A: Like this in your entity:
/**
* @var string
*
* @ORM\Column(name="somefield", type="string", length=1)
*/
private $someField;
/**
* Set someField
*
* @param boolean $someField
* @return ...
*/
public function setSomeField(bool $someField)
{
$this->someField = 'f';
if($someField)
$this->someField = 't';
return $this;
}
/**
* Get someField
*
* @return boolean
*/
public function getSomeField()
{
if($this->someField == 't')
return true;
return false;
}
| |
doc_23532314
|
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
We receive the following default output if no command is ready to run:
# No scheduled commands are ready to run.
How to disable this default Laravel5 message? We don't want to have an output if there is no command ready to run. The best would be, when we were able to configure that message and return code on our self.
A: You can create a new command in app/Console/Commands similar to below, which extends the default schedule:run command.
It overrides the handle method while leaving everything else as-is to avoid having Laravel output the "No scheduled commands are ready to run." line when it didn't do anything.
By using a different name there's no need to worry about conflicts, and you can still run the original php artisan schedule:run command at any time if you so desire.
<?php
namespace App\Console\Commands
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Console\Scheduling\ScheduleRunCommand;
class RunTasks extends ScheduleRunCommand
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'run:tasks';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Custom task runner with no default output';
/**
* Create a new command instance.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
public function __construct(Schedule $schedule)
{
parent::__construct($schedule);
}
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
foreach ($this->schedule->dueEvents($this->laravel) as $event) {
if (! $event->filtersPass($this->laravel)) {
continue;
}
if ($event->onOneServer) {
$this->runSingleServerEvent($event);
} else {
$this->runEvent($event);
}
$this->eventsRan = true;
}
if (! $this->eventsRan) {
// Laravel would output the default text here. You can remove
// this if statement entirely if you don't want output.
//
// Alternatively, define some custom output with:
// $this->info("My custom 'nothing ran' message");
}
}
}
Verify that Laravel sees your new command:
php artisan | grep run:tasks
Finally update your cron to run the new command:
* * * * * cd /path-to-your-project && php artisan run:tasks >> /dev/null 2>&1
A: As I mentioned in the comments I see two possibilities
You can filter the output by removing what you don't want
* * * * * cd /path-to-your-project && php artisan schedule:run | awk '{ if (/No scheduled commands are ready to run./ && !seen) { seen = 1 } else print }'
Or you can override with your own command:
$ php artisan make:command ScheduleRunCommand
By making your own command (mostly copy/past from ScheduleRunCommand) or extending the ScheduleRunCommand as @dave-s proposed
And if you want to still run php artisan schedule:run with your new command,
you need to register it in a service provider
$this->app->extend('schedule.run', function () {
return new \App\Console\Commands\ScheduleRunCommand;
});
A: If you look at the code for Laravel at https://github.com/laravel/framework/blob/78505345f2a34b865a980cefbd103d8eb839eedf/src/Illuminate/Console/Scheduling/ScheduleRunCommand.php#L82
public function handle()
{
foreach ($this->schedule->dueEvents($this->laravel) as $event) {
if (! $event->filtersPass($this->laravel)) {
continue;
}
if ($event->onOneServer) {
$this->runSingleServerEvent($event);
} else {
$this->runEvent($event);
}
$this->eventsRan = true;
}
if (! $this->eventsRan) {
$this->info('No scheduled commands are ready to run.');
}
}
You see that it's handled via $this->info handler.
The info handler is defined in Command.php Which calls the line method, which calls the output handler which is defined in the run command
So in essence to be able to intercept this you should be able to override the OutputStyle which is based on the symfonystyle by binding your own output handler before running the commands in the file you call in your cron job.
The best working scenario I can think of is by using an OutputFormatter where you simply return null when the string matches your target string.
$this->output->setFormatter( new MyCatchemAllFormatter() );
And in the class you would define something along the lines of:
use Symfony\Component\Console\Formatter\OutputFormatter;
class MyCatchemAllFormatter extends OutputFormatter
{
public function formatAndWrap(string $message, int $width)
{
if($message != 'No scheduled commands are ready to run.') {
return parent::formatAndWrap($message, $width);
}
return null;
}
}
A:
I understand that my solution is DIRTY and I'll get downvotes by most of SO users, but it's quick to do without registering additional service providers, modifying classes and etc.
I've checked sources and found this at line 81 of ScheduleRunCommand which is
public function handle()
{
foreach ($this->schedule->dueEvents($this->laravel) as $event) {
if (! $event->filtersPass($this->laravel)) {
continue;
}
if ($event->onOneServer) {
$this->runSingleServerEvent($event);
} else {
$this->runEvent($event);
}
$this->eventsRan = true;
}
if (! $this->eventsRan) { // L81
$this->info('No scheduled commands are ready to run.'); // L82
}
}
The quickest way to "cheat" with it is to copy that class to app/Console/ScheduleRunCommand.php and copy that file to original source path every-time when composer dump-autoload called.
1) Copy original file to app/Console folder:
cp vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleRunCommand.php patch/ScheduleRunCommand.php app/Console/ScheduleRunCommand.php
2) add such line in composer.json scripts:post-autoload-dump section:
cp app/Console/ScheduleRunCommand.php vendor/laravel/framework/src/Illuminate/Console/Scheduling/ScheduleRunCommand.php
3) modify Your message in app/Console/ScheduleRunCommand.php (L82):
if (! $this->eventsRan) {
$this->info('NOTHING');
}
4) run: composer dump
and result:
| |
doc_23532315
|
Details
I have a login.html. It links to validation.jsp. It checks for password and then redirects to the following page.
But I want that this following page to be displayed only when the
validation is true. Otherwise if someone enters the link to the page
and finds that the page has not been logged into, it will prompt to
do it so.
It worked fine in the servlet. I created a new session in validation page
and set request.getSession(false) in the home page.
but this doesnt seem to work in jsp. If I set session=false in the page
directive, then I can not access session object at all. and if I
explicitly do what I have done in the page, it still doesn't work!!
<%@ page language="java" import="java.io.*"
contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"
import="java.util.*;"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
session=request.getSession(false);
if(session==null)
{
out.println("please login");
}
else
{
out.println("how did it run!!! ??");
out.println(application.getAttribute("one"));
out.println(session.isNew());
out.println(session.getId());
out.println("<form action='logout.jsp' method='post'>");
out.println("<input type='submit'>");
out.println("</form>");
}
%>
</body>
</html>
A: A JSP creates a session by default. If you don't need session then use following
<%@ page session="false" %>
A: You don't use if(session==null) to determine if someone is logged in. Sessions are generally created automatically, and besides, you might want to use a session for something even before login. You check for a specific session attribute.
String userid = (String)session.getAttribute("userid");
if(userid!=null)
{
out.print("logged in as:" + userid);
}
Of course in the login code you have to set it:
session.setAttribute("userid", userid);
There is also no need to call request.getSession in JSP. In a servlet you would need to, but in JSP the session object is already populated with request.getSession for you.
Edit:
When you do the session=false directive then the session object isn't declared so you'll need not just to set it but actually declare it: HttpSession session = request.getSession(false); Then you will get session=null, but its dangerous to rely on this for security, as going to a page where you didn't set session=false will create the session, and your code will then think someone was validly logged in, when they were not. Even if you are certain that you put session=false everywhere, you might miss a spot, or more likely, the next developer after you will not understand you did it this way, and a security disaster is just waiting to happen.
Using session=false is intended for performance boost not security. E.g. you have a faq page that doesn't care about sessions, set session=false so people going to that link doesn't create sessions and waste memory.
| |
doc_23532316
|
Bu I need to check two servers and have a loop at end for this and I check it but I get only the last result inside output.xml file.
I would need to merge the json.dumps(data) in one dictionary or whatever xmltodict produces and then parse into one xml.
I have tried some dictionary update but it did not work.
The code is here:
def get_output_dict():
if vendor == 'HP':
data = xml_to_dict(xml_doc='hp_input.xml')
elif vendor == 'Dell':
data = xml_to_dict(xml_doc='dell_input.xml')
for test in data['platform']['vendor']['tests']:
command = test.get('command') #continue if command is not present
output = remote(command)
str1 = ''.join(str(e) for e in output)
for key in test.keys():
if key == 'command':
test[key] = str1
#Change command key name with result using .pop
test['Result'] = test.pop('command')
return json.loads(json.dumps(data))
def get_output_xml(output_dict):
#dicttoxml.set_debug()
output_xml = dicttoxml.dicttoxml(output_dict,custom_root='output',attr_type=False,root=False)
if vendor == 'HP':
filename = 'hp_output-{}.xml'.format(host)
elif vendor == 'Dell':
filename = 'dell_output-{}.xml'.format(host)
tree = etree.fromstring(output_xml)
output_xml_string = etree.tostring(tree, pretty_print=True)
with open(filename, 'wb') as f:
f.write(output_xml_string)
print('Output for hostname server: {} written to:
{}'.format(host,filename))
return output_xml
for x in range(3, len(sys.argv)):
print("Checking Server: %s" % (sys.argv[x]))
remote = myssh(sys.argv[x], username, password)
data = get_output_dict()
xml = get_output_xml(data)
The result should be that I at get_output_xml(data) get the data merged from two iterations of two servers, and maybe later on 3 servers.
| |
doc_23532317
|
Error message(s) Im getting:
DEBUG o.a.kafka.clients.NetworkClient - Sending metadata request {topics=[kafka_test1-write_aggregate-changelog]} to node 100
DEBUG org.apache.kafka.clients.Metadata - Updated cluster metadata version 6 to Cluster(nodes = [12.34.56.78:9092 (id: 100 rack: null)], partitions = [Partition(topic = kafka_test1-write_aggregate-changelog, partition = 1, leader = 100, replicas = [100,], isr = [100,], Partition(topic = kafka_test1-write_aggregate-changelog, partition = 0, leader = 100, replicas = [100,], isr = [100,]])
DEBUG o.a.k.c.consumer.internals.Fetcher - Attempt to fetch offsets for partition kafka_test1-write_aggregate-changelog-0 failed due to obsolete leadership information, retrying.
The cluster metadata # keeps advancing indefinitely.
Code:
KStreamBuilder kStreamBuilder = new KStreamBuilder();
KStream<String, String> lines = kStreamBuilder.stream(TOPIC);
KTable<Windowed<String>, String> dbwriteTable = lines.aggregateByKey(
new DBAggregateInit(),
new DBAggregate(),
TimeWindows.of("write_aggregate", 10000));
dbwriteTable.toStream().print();
KafkaStreams kafkaStreams = new KafkaStreams(kStreamBuilder, streamsConfig);
kafkaStreams.start();
Where DBAggregateInit and DBAggregate are stubbed out to log to DEBUG when anything hits them. No other function.
None of these stubbed functions ever gets hit.
Not sure what step(s) I've missed here. If I .foreach() or do a simple read on this topic it seems to work ok.
FWIW:
Ive had similar issues with partitions when I let kafka create my topic instead of using kafka-topic --create --topic ....
A: I believe this sort of error is due to the fact that I was running zookeeper and kafka as different users and there were likely permissions issues in the various data folders.
Once both services were run as root and all relevant data files were erased / recreated these errors went away.
| |
doc_23532318
|
Please suggest how should I proceed. Thanks in advance.
{
PdfReader.unethicalreading = true;
string pdfFile = @"C:\TestPdf.pdf";
PdfReader reader = new PdfReader(pdfFile);
long quality = 50L;
int n = reader.XrefSize;
for (int i = 0; i < n; i++)
{
PdfObject obj = reader.GetPdfObject(i);
if (obj == null || !obj.IsStream()) { continue; }
PdfDictionary dict = (PdfDictionary)PdfReader.GetPdfObject(obj);
PdfObject pdfcolorspace = dict.Get(PdfName.COLORSPACE);
PdfName subType = (PdfName)PdfReader.GetPdfObject(dict.Get(PdfName.SUBTYPE));
if (!PdfName.IMAGE.Equals(subType)) { continue; }
PRStream stream = (PRStream)obj;
try
{
PdfImageObject image = new PdfImageObject(stream);
PdfName filter = (PdfName)image.Get(PdfName.FILTER);
if ( PdfName.JBIG2DECODE.Equals(filter) || PdfName.JPXDECODE.Equals(filter) || PdfName.CCITTFAXDECODE.Equals(filter) || PdfName.FLATEDECODE.Equals(filter))
continue;
System.Drawing.Image img = image.GetDrawingImage();
if (img == null) continue;
var ll = image.GetImageBytesType();
int width = img.Width;
int height = img.Height;
using (System.Drawing.Bitmap dotnetImg = new System.Drawing.Bitmap(img))
{
System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter( System.Drawing.Imaging.Encoder.Quality, quality);
using (MemoryStream msImg = new MemoryStream())
{
dotnetImg.Save(msImg, codec, eParams);
msImg.Position = 0;
stream.Clear();
if (pdfcolorspace == PdfName.DEVICECMYK)
{
img.Save(msImg, ImageFormat.Jpeg);
stream.Put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
}
else
{
stream.Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
}
stream.SetData( msImg.ToArray(), true, PdfStream.BEST_COMPRESSION);
stream.Put(PdfName.TYPE, PdfName.XOBJECT);
stream.Put(PdfName.SUBTYPE, PdfName.IMAGE);
stream.Put(PdfName.FILTER, PdfName.DCTDECODE);
stream.Put(PdfName.WIDTH, new PdfNumber(width));
stream.Put(PdfName.HEIGHT, new PdfNumber(height));
stream.Put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
}
}
}
catch (Exception ex)
{
}
finally
{
reader.RemoveUnusedObjects();
}
}
PdfStamper stamper = new PdfStamper(reader, new FileStream(@"C:\Compress.pdf", FileMode.Create), PdfWriter.VERSION_1_5);
stamper.FormFlattening = false;
stamper.SetFullCompression();
stamper.Close();
reader.Close();
}
| |
doc_23532319
|
I am using SQL Server Express 2017, and I know how to perform this task manually by right clicking on the database->tasks->generate scripts
Is there a .exe being called here, in older versions of SQL Server this would call sqlpubwiz.exe, and you could call this .exe from a cli, and put into a batch file. I am looking to replace this behavior. Can someone let me know the exe that is being called, and let me know how to script against it.
A: you can use SQL Dumper, easiest way to export the script data (with Insert query)
for more information :
https://support.microsoft.com/en-in/help/917825/use-the-sqldumper-exe-utility-to-generate-a-dump-file-in-sql-server
to download the utility
https://download.cnet.com/SQL-Dumper/3000-10254_4-10514574.html
| |
doc_23532320
|
RegexpError - undefined (?...) sequence: /(?<=(LIST ALL SELECTED ))\w/:
The line of code where the occurs is
match = data.match('(?<=(LIST ALL SELECTED ))\w')[0]
What I am trying to do is capture the next letter directly after 'LIST ALL SELECTED '
Any insite to what this means would be greatly appreciated.
Thanks.
A: That's what's called a positive lookbehind. Ruby doesn't support them, but if that's the whole regexp, you don't need it.
match = data.match(/LIST ALL SELECTED(\w)/)[0]
Ben (look down, in the comments) says your regexp with the lookbehind does indeed work on Ruby 1.9.2. Heroku must be using 1.8.6 or 1.8.7, which doesn't have lookbehinds.
| |
doc_23532321
|
I am just trying to make a simple Song class, then add and display an instance of the song object.
The error is saying that allot of my Methods are already defined in projectName.obj. I am also getting unresolved external symbol on IDSeed.
I am using visual studio 2017.
Main
#include "stdafx.h"
#include "Song.h"
#include "Song.cpp"
int main()
{
Song testSong("Evil Tram", "Catz N dogz");
testSong.setGenre("Tech House");
testSong.display();
return 0;
}
Song.cpp
#include "stdafx.h"
#include "Song.h"
Song::Song()
{
m_title = "";
m_album = "";//change to class
m_artist = "";//change to class
m_genre = "";//change to enum
m_ID = 0;
IDSeed = 0;
}
Song::Song(string title, string artist)
{
m_title = title;
m_album = "No Album";
m_genre = "No Genre";
m_artist = artist;
IDSeed++;
m_ID = IDSeed;
}
string Song::getTitle() const
{
return m_title;
}
string Song::getAlbum() const
{
return m_album;
}
string Song::getArtist() const
{
return m_artist;
}
string Song::getGenre() const
{
return m_genre;
}
int Song::getID() const
{
return m_ID;
}
void Song::setTitle(string title)
{
m_title = title;
}
void Song::setAlbum(string album)
{
m_album = album;
}
void Song::setArtist(string artist)
{
m_artist = artist;
}
void Song::setGenre(string genre)
{
m_genre = genre;
}
void Song::setID(int id)
{
m_ID = id;
}
void Song::display() const
{
cout << m_title << ", " << m_album << ", "
<< m_artist << ", " << m_genre << endl;
}
Song::~Song()
{
}
ostream & operator<<(ostream & out, Song & s)
{
out << s.m_title << ", " << s.m_album << ", "
<< s.m_artist << ", " << s.m_genre << endl;
return out;
}
istream & operator>>(istream & in, Song & s)
{
in >> s.m_title >> s.m_album >> s.m_artist >> s.m_genre;
return in;
}
Song.h
#pragma once
#include <iostream>
#include <string>
#include <ostream>
using std::string;
using std::cout;
using std::endl;
using std::ostream;
using std::istream;
class Song
{
private:
#pragma region Variables
string m_title;
string m_album;//change to class
string m_artist;//change to class
string m_genre;//change to enum
int m_ID;
static int IDSeed;
#pragma endregion
public:
Song();
Song(string title, string artist);
#pragma region Getters
string getTitle() const;
string getAlbum()const;
string getArtist()const;
string getGenre()const;
int getID()const;
#pragma endregion
#pragma region Setters
void setTitle(string title);
void setAlbum(string album);
void setArtist(string artist);
void setGenre(string genre);
void setID(int id);
#pragma endregion
#pragma region Methods
void display() const;
#pragma endregion
friend ostream& operator<<(ostream& out,
Song& s);
friend istream& operator>>(istream& in,
Song& s);
~Song();//destructer
};
A: Solved by removing the #include song.cpp and placing the static keyword in the cpp file instead of the .h
| |
doc_23532322
|
When I go to http://example.com, I get this response for the GET http://example.com request:
Cache-Control:no-cache, must-revalidate
CF-RAY:2b8d0490837f2828-SJC
Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html; charset=UTF-8
Date:Sun, 26 Jun 2016 01:52:05 GMT
Expires:0
Pragma:no-cache
Server:cloudflare-nginx
Transfer-Encoding:chunked
Vary:Accept-Encoding
X-Powered-By:Express
Notice that the response has no ETag header, even though it's enabled on my origin server.
When I go to the origin server directly, e.g. GET http://01.23.456.789/, I get this response:
Accept-Ranges:bytes
Cache-Control:no-cache, must-revalidate
Connection:keep-alive
Date:Sun, 26 Jun 2016 01:56:53 GMT
ETag:W/"4cf8-1558a5557a0"
Expires:0
Pragma:no-cache
X-Powered-By:Express
Does anyone know why Cloudflare wouldn't be forwarding the ETag header? How can I make Cloudflare forward the ETag? Cloudflare isn't caching the GET http://example.com request by default since it's an HTML page.
A: I spoke with a Cloudflare Tech Support Engineer and he helped fixed my issue. For anyone in the future who might have this same problem, here's what fixed it:
I had Email Obfuscation enabled for the URL in question (that was getting its ETag header removed). According to https://support.cloudflare.com/hc/en-us/articles/218505467-Does-CloudFlare-support-ETag-headers-,
Email Obfuscation will need to be disabled, otherwise the ETag headers
will be removed from the response. Email Obfuscation modifies the code
significantly enough it cannot be considered semantically equivalent.
Disabling Email Obfuscation still didn't fix it, though. Turns out I had an app enabled that would modify the HTML, so the ETag had to be invalidated. In the end, setting a Page Rule with Disable Security, Disable Apps, Disable Performance for that URL did the trick.
A: disable Email Obfuscation and Automatic HTTPS Rewrites, as documented at Cloudflare support:
When using weak ETag headers, disable Email Obfuscation and Automatic
HTTPS Rewrites to ensure Cloudflare doesn't remove the ETag headers
set by your origin web server.
A: In my case, I encountered the same situation.
Disabling Email Obfuscation and Automatic HTTPS Rewrites is not enough for me, because I have installed 'A Better Browser' app (https://www.cloudflare.com/apps/a-better-browser) on Cloudflare Apps.
After uninstalling that app, the Etag shows up.
| |
doc_23532323
|
ClassA.java
public class ClassA implements XYZ{
public ClassA() {
Abc();
}
}
ClassB.java
public class ClassB {
public ClassB Abc{
}
}
A: Another things you can declare in the ClassA variable to access the methods and attribute in ClassB like this:
public ClassA() {
ClassB classB = new ClassB();
classB.Abc();
}
or
public ClassA() {
new ClassB().Abc();
}
A: If you want ClassB to have ClassA functionality, you should enhance ClassB either through inheritance or through composition. For example:
Inheritance:
public class ClassB extends ClassA {
// now can use or override ClassA methods.
}
Composition:
public class ClassB {
private ClassA classA = new ClassA();
// now we can use classA instance throughout this class
}
As a general rule, I try to favor composition over inheritance. An example of composition is giving your class a Scanner or ArrayList object, and using the Scanner or ArrayList in the methods of the class. As you can see, it would make no sense to try to have your class extend either of these two entities except in very peculiar circumstances.
Otherwise your question is still quite unclear and if you're still having problems and need our help, you would do well to give concrete examples of what you're trying to achieve.
A: Though your code is totally unclear, I feel you want this
public class ClassB extends ClassA{
super.Abc(); //calls parent class method
}
A: public class ClassB extends ClassA
will get you to your point
| |
doc_23532324
|
I'm trying to remake the frogger game, and I'm kinda stuck with putting the cars on the screen.
For those of you who don't know frogger: http://www.actionscript.org/showMovie.php?id=1157, but I'm not implementing the logs.
The big problem is that I have 3 cars, all of which are movieclips in the library, I won't place any of them on the stage. Multiple instances must appear at the same time. These cars need to drive in both directions and all 3 cars must appear in all lanes(I have 4 lanes)
Of course, 1 lane only has 1 direction.
I can use hitTest() to see if my frog has hit one of the cars, but I need to make it realistic, meaning I can't hard-code the amount of cars on each lane.
I also can't seem to find how to rotate a movieclip around its center...
A: Well, there are a couple things I can suggest.
For the cars, create each car as a separate object in the Library (don't put them on the stage). When you need to have one appear on the screen use attachMovie() to create an instance of the car you want.
For making them face different directions (I believe you just need left and right), you could either create 2 copies of each car in the Library, one facing each direction. Or, I think if you set xScale value to -100% I think that will flip it horizontally, so you could use the same Library instance for both. However, it would probably be easier to deal with if you had separate Library instances for each direction, instead of doing rotations on one.
A: to answer your question about rotation, movie clips rotate around their registration point, not around their visual center. So when you create your clips, make sure that the crosshairs on the symbol-editing screen appear in the center. The crosshairs is the registration point, which basically defines where x:0,y:0 is on the clip.
It sounds like your question is really about how to use hitTest to see if the frog has hit any of the cars, regardless of which one, how many are on stage, etc. So what I would do is create a class for the car with a static member that can be a pointer to the frog, and then have the class check for whether it is hitting the frog.
So to start out:
public class Car extends MovieClip{
public static var frog:MovieClip;
private var interval;
public function Car(){
super();
interval = setInterval(checkHit,500);
}
private function checkHit(){
if(this.hitTest(frog)){
trace("the frog hit the car");
clearInterval(interval);
//do what you need to do when the frog gets hit
}
}
}
For each individual car, you can extend the Car class:
class Truck extends Car{
public function Truck(){
super();
}
}
class Volkswagen extends Car{
public function Volkswagen(){
super();
}
}
class Bus extends Car{
public function Bus(){
super();
}
}
After creating the individual classes, use Linkage on your Library symbols for each car. (rightclick on the symbol, select Linkage, and type your class name in the Class field).
Finally, set the frog member to your frog on stage
var frog:MovieClip = attachMovie("frog_mc", frogMC, _root.getNextHighestDepth())
Car.frog = frog; //set the static var "frog" to your frog instance
And now your cars should all check themselves for whether they're hitting the frog.
The other option is to code that checkHit() function on the first frame of each different car movieclip, rather than using classes for each:
this.onEnterFrame = function(){
if(this.hitTest(_root.frog)){
trace("the frog hit the car");
//do what you need to do when the frog gets hit
delete this.onEnterFrame;
}
}
| |
doc_23532325
|
I have a page where you can check if rooms are available for a specific room category and date
I know that you have to do a inner join. I have used google but I don't have a clue how to do it.
This is in my hotel database:
I have a rooms table:
TABLE `rooms` (
`roomNR` int(11) NOT NULL,
`catagory` varchar(11) DEFAULT NULL,
`picLocation` varchar(50) DEFAULT NULL,
PRIMARY KEY (`roomNR`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
And I have a reservation table where all the reservations are stored.
TABLE `reservation` (
`reservationID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`userID` int(11) NOT NULL,
`roomNR` int(11) NOT NULL,
`start` date NOT NULL,
`end` date NOT NULL,
`price` float NOT NULL,
PRIMARY KEY (`reservationID`),
UNIQUE KEY `userID` (`userID`),
UNIQUE KEY `roomNR` (`roomNR`),
CONSTRAINT `reservation_ibfk_1` FOREIGN KEY (`roomNR`) REFERENCES `rooms` (`roomNR`),
CONSTRAINT `reservation_ibfk_2` FOREIGN KEY (`userID`) REFERENCES `users` (`userID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
This is the form that I use:
<form action="" method="GET">
<div>
<label for="StartDate">From</label>
<input type="input" name="startDate" id="startDate" readonly=""> <label for="EndDate">Till</label> <input readonly="" type="input" name="endDate" id="endDate">
<label for="Catagory">Catagory:</label>
<select name="Catagory" id="Catagory">
<?php
$catagorys = DB::Getinstance()->query('SELECT * FROM catagory');
if ($catagorys->count()) {
foreach($catagorys->results() as $catagory){?>
<option value="<?php echo $catagory->name; ?>"><?php echo $catagory->name; ?></option>
<?php }
}
?>
</select> <input type="submit" value="get available rooms" class="btn btn-default">
</div>
</form>
I hope some one can help me!
thank you in advance!
-- edit
Now that I'm looking at the reservation table wouldn't it be better to store also the catagory in there?
A: Part 1: Rooms that are not reserved
It is a good practice to first streamline the task into simple words:
Select those rooms, which are not referred to in any reservation entry, and are from a given category.
What you in fact need here is not an INNER JOIN. At least not for this part of the task. INNER JOIN will be used to "link" with catagory later.
Using INNER JOIN here could easily select rooms that are already reserved: SELECT rooms.roomNR FROM rooms INNER JOIN reservation ON rooms.roomNR=reservation.roomNR WHERE catagory=$category_id. Of course you could process this information in PHP and use that to select the remaining rows in your table pretty efficiently, but there is a much better way.
You need a subquery.
SELECT roomNR FROM `rooms` WHERE catagory=$category_id AND roomNR NOT IN (SELECT roomNR FROM `reservation`)
It is a fortunate feature of MySQL (or SQL, in general), that the language syntax tries to resemble english written language as much as possible. Query explanation: we SELECT the roomNR of those rooms that are not in the SELECT roomNR FROM reservation result (or, simply put, the reservation table).
For syntax and more information regarding subqueries, please check out http://dev.mysql.com/doc/refman/5.1/en/subqueries.html.
Part 2: PHP Implementation
To take this one step further, and follow your business logic, the following can be said:
Select those categories, that have rooms (at least one room) not referenced in reservation
And this is where you can implement an INNER JOIN. Translating our problem to MySQL - assuming you have id and name fields for catagory - we have:
SELECT catagory.name FROM catagory INNER JOIN rooms ON catagory.id=rooms.catagory WHERE rooms.roomNR NOT IN (SELECT roomNR FROM reservation);
If I'm not mistaken, this query should query a given catagory name if there is at least one room with that catagory id not referenced in reservations. Please check back if this works for you, I'm not in an environment where I could test this right now.
EDIT: DISTINCT keyword
If the query, by any means, returns a given catagory multiple times, please use the DISTINCT keyword:
SELECT DISTINCT catagory.name FROM catagory ...
Part 3: Filter results by start and end date
To filter by start and end date, we come to the following problem:
Select those categories, that have at least one room not referenced in
reservations. Reservations that are outside our time scope (example:
reservation has already expired by the time the next user begins their
own reservation) can be ignored, since their rooms are free, so they
no longer limit our possibilities.
Variables used in the next query are these:
$start_date = $_POST['startDate'];
$end_date = $_POST['endDate'];
To make it into SQL:
SELECT catagory.name FROM catagory INNER JOIN rooms ON catagory.id=rooms.catagory WHERE rooms.roomNR NOT IN (SELECT roomNR FROM reservation WHERE end<$start_date OR start>$end_date);
As you can see, we use an inverse logic in the subquery. When we are checking if a given room is already reserved (already in reservation), we ignore those reservations that do not fall into time criteria: it has ended before next reservation begins, or starts before the next reservation ends. Therefore it won't be a limiting element for the NOT IN clause.
A: No, you don't need to save the category on the reservation table too, it would be redundant.
to get the reservations made for that category, and room info about the reservation you will need a query like this:
SELECT rooms.roomNR, rooms.category, rooms.picLocation,
res.reservationID, res.userID, res.start, res.end, res.price
FROM rooms
INNER JOIN reservations res ON rooms.roomNR = res.roomNR
WHERE rooms.category = 'your_category_selection'
| |
doc_23532326
|
https://www.googleapis.com/upload/plusDomains/v1/people/".$unique_id."/media/cloud
And passing header like this:
"Authorization: OAuth $ACCESS_TOKEN"
"Content-Type: image/jpeg"
And passing image url as parameter. But I'm getting this error:
"domain": "global",
"reason": "badContent",
"message": "Media type 'application/x-www-form-urlencoded' is not supported. Valid media types: [image/*, video/*]"
Anyone please help me to solve this.
| |
doc_23532327
|
I'm creating 3 threads, 3 timers, 3 events and 3 timerspecs.
What I'm trying to do is have each thread set a timer, wait for the timer to expire (which releases an unsafe lock) and finish the threads.
However, when I run the following program only the first timer expires which leads me to believe that perhaps it's not possible to have more than one timer per process. Is something wrong?
handle(union sigval params) is the callback for each timer when they expire.
threadTask(void *params) is the callback executed by each thread.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <pthread.h>
typedef struct TH_PARAMS
{
uint threadNum;
pthread_t tid;
timer_t *timer;
struct sigevent *event;
} ThreadParams_t;
static timer_t timers[3];
static struct itimerspec timeToWait[3];
static struct sigevent events[3];
static ThreadParams_t thParams[3];
static char wait[3];
static void handle(union sigval params)
{
ThreadParams_t *threadParams = (ThreadParams_t *) params.sival_ptr;
printf("Timer %d expired. Thread num which sent %d. Thread %ld. Pthread %ld.\n",
*((int*) *(threadParams->timer)), threadParams->threadNum,
syscall(SYS_gettid), pthread_self());
wait[threadParams->threadNum] = 0;
}
static void *threadTask(void *params)
{
ThreadParams_t *threadParams = (ThreadParams_t *) params;
printf("Thread num %d. Thread %ld. Pthread %ld.\n",
threadParams->threadNum, syscall(SYS_gettid),
pthread_self());
if (0 != timer_settime(threadParams->timer, 0, &timeToWait[threadParams->threadNum], NULL))
{
printf("Failed to set timers. Error %d.\n", errno);
pthread_exit(NULL);
}
while(wait) sleep(1);
pthread_exit(NULL);
}
int main()
{
int i;
printf("Main thread started. Thread: %ld. Pthread: %ld\n", syscall(SYS_gettid), pthread_self());
for (i = 0; i < 3; ++i)
{
timeToWait[i].it_value.tv_sec = 2;
timeToWait[i].it_value.tv_nsec = 0;
timeToWait[i].it_interval.tv_sec = 0;
timeToWait[i].it_interval.tv_nsec = 0;
events[i].sigev_notify = SIGEV_THREAD;
events[i].sigev_notify_function = handle;
events[i].sigev_value.sival_ptr = &thParams[i];
if (0 != timer_create(CLOCK_MONOTONIC, &events[i], &timers[i]))
{
printf("Failed to create timers. Error %d.\n", errno);
return 1;
}
wait[i] = 1;
thParams[i].threadNum = i;
thParams[i].event = &events[i];
thParams[i].timer = &timers[i];
if (0 != pthread_create(&thParams[i].tid, NULL, threadTask, (void *) &thParams[i]))
{
printf("Failed to create thread. Error %d.\n", errno);
for (i = 0; i < 3; ++i)
{
if (timers[i])
{
timer_delete(timers[i]);
}
}
return 1;
}
}
for (i = 0; i < 3; ++i)
{
pthread_join(thParams[i].tid, NULL);
}
for (i = 0; i < 3; ++i)
{
if (timers[i])
{
timer_delete(timers[i]);
}
}
printf("Main thread finished. Thread: %ld.\n", syscall(SYS_gettid));
return 0;
}
A: Okay, so I found my mistake. I was not dereferencing the timer pointer.
In function threadTask, specifically in the timer_settime the first argument should be *threadParams->timer, emphasis on the *.
| |
doc_23532328
|
I would like to modify the non-editable cells based on the editable cells, with some formulas.
I tried the following:
int input_column = 0;
int output_column = 5;
table.getModel().addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
int rowIndex = pricestable.getSelectedRow();
int columnIndex = pricestable.getSelectedColumn();
if (columnIndex == input_column) {
String value1 = table.getModel().getValueAt(rowIndex, input_column).toString();
//do some operations with value1 convert, it to outputvalue
table.setValueAt(outputvalue, rowIndex, output_column);
}
}
});
The problem is, that the tablechanged event will be called recursively...
Does anyone know what am I doing wrong, or do have any better solution?
I have seen some solutions with overwriting the setValueAt() method,
but sometimes I need to use the combined value of two input cells to generate the output cell value, and I can add this listener after I populate the table, but can't do it if I overwrite the setValueAt()...
A: I have a simple solution to overcome the recursive calls. The column which will be changed by your program, shouldn't be in interest of addTableListener.
'colDirty' is a column with width 0px;
Sample code:
private void addTableListener() {
tableModel.addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent tme) {
if (tme.getType() == TableModelEvent.UPDATE) {
if (tme.getColumn()!=colDirty) { // colDirty = column no which I changed value programatically
tableModel.setValueAt(true, tme.getFirstRow(), colDirty);
}
}
}
});
}
| |
doc_23532329
|
I delete old data in the database:
t@konrad:~/neo4j$ rm -rf ./data/
I start the application:
t@konrad:~/neo4j$ ./bin/neo4j console
: Max 1024 open files allowed, minimum of 40 000 recommended. See the
Neo4j manual. Starting Neo4j Server console-mode...
/home/triptop/neo4j/data/log was missing, recreating... Using
additional JVM arguments: -server -XX:+DisableExplicitGC
-Dorg.neo4j.server.properties=conf/neo4j-server.properties -Djava.util.logging.config.file=conf/logging.properties -Dlog4j.configuration=file:conf/log4j.properties -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled 2014-04-02 10:10:01.149+0000 INFO [API] Setting startup timeout to: 120000ms
based on -1 2014-04-02 10:12:29.005+0000 ERROR [org.neo4j]: Exception
when stopping
org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource@4ec143d8
java.nio.channels.ClosedByInterruptException
java.lang.RuntimeException:
java.nio.channels.ClosedByInterruptException
at org.neo4j.kernel.impl.transaction.xaframework.LogBackedXaDataSource.stop(LogBackedXaDataSource.java:73)
at org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource.stop(NeoStoreXaDataSource.java:448)
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.stop(LifeSupport.java:523)
at org.neo4j.kernel.lifecycle.LifeSupport.stop(LifeSupport.java:155)
at org.neo4j.kernel.impl.transaction.XaDataSourceManager.stop(XaDataSourceManager.java:185)
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.stop(LifeSupport.java:523)
at org.neo4j.kernel.lifecycle.LifeSupport.stop(LifeSupport.java:155)
at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:123)
at org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:307)
at org.neo4j.kernel.EmbeddedGraphDatabase.(EmbeddedGraphDatabase.java:63)
at org.neo4j.graphdb.factory.GraphDatabaseFactory$1.newDatabase(GraphDatabaseFactory.java:92)
at org.neo4j.graphdb.factory.GraphDatabaseBuilder.newGraphDatabase(GraphDatabaseBuilder.java:198)
at org.neo4j.server.database.CommunityDatabase.createDb(CommunityDatabase.java:62)
at org.neo4j.server.database.CommunityDatabase.start(CommunityDatabase.java:120)
at org.neo4j.server.AbstractNeoServer.start(AbstractNeoServer.java:158)
at org.neo4j.server.Bootstrapper.start(Bootstrapper.java:87)
at org.neo4j.server.Bootstrapper.main(Bootstrapper.java:50) Caused by: java.nio.channels.ClosedByInterruptException
at java.nio.channels.spi.AbstractInterruptibleChannel.end(AbstractInterruptibleChannel.java:202)
at sun.nio.ch.FileChannelImpl.writeInternal(FileChannelImpl.java:743)
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:723)
at org.neo4j.kernel.impl.transaction.xaframework.DirectMappedLogBuffer.writeOut(DirectMappedLogBuffer.java:164)
at org.neo4j.kernel.impl.transaction.xaframework.DirectMappedLogBuffer.force(DirectMappedLogBuffer.java:178)
at org.neo4j.kernel.impl.transaction.xaframework.XaLogicalLog.releaseCurrentLogFile(XaLogicalLog.java:700)
at org.neo4j.kernel.impl.transaction.xaframework.XaLogicalLog.close(XaLogicalLog.java:725)
at org.neo4j.kernel.impl.transaction.xaframework.LogBackedXaDataSource.stop(LogBackedXaDataSource.java:69)
... 16 more 2014-04-02 10:12:29.037+0000 ERROR [org.neo4j]: Exception when stopping
org.neo4j.kernel.impl.transaction.XaDataSourceManager@2bf11e9f
Component
'org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource@4ec143d8' failed
to stop. Please see attached cause exception.
org.neo4j.kernel.lifecycle.LifecycleException: Component
'org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource@4ec143d8' failed
to stop. Please see attached cause exception.
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.stop(LifeSupport.java:528)
at org.neo4j.kernel.lifecycle.LifeSupport.stop(LifeSupport.java:155)
at org.neo4j.kernel.impl.transaction.XaDataSourceManager.stop(XaDataSourceManager.java:185)
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.stop(LifeSupport.java:523)
at org.neo4j.kernel.lifecycle.LifeSupport.stop(LifeSupport.java:155)
at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:123)
at org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:307)
at org.neo4j.kernel.EmbeddedGraphDatabase.(EmbeddedGraphDatabase.java:63)
at org.neo4j.graphdb.factory.GraphDatabaseFactory$1.newDatabase(GraphDatabaseFactory.java:92)
at org.neo4j.graphdb.factory.GraphDatabaseBuilder.newGraphDatabase(GraphDatabaseBuilder.java:198)
at org.neo4j.server.database.CommunityDatabase.createDb(CommunityDatabase.java:62)
at org.neo4j.server.database.CommunityDatabase.start(CommunityDatabase.java:120)
at org.neo4j.server.AbstractNeoServer.start(AbstractNeoServer.java:158)
at org.neo4j.server.Bootstrapper.start(Bootstrapper.java:87)
at org.neo4j.server.Bootstrapper.main(Bootstrapper.java:50) Caused by: java.lang.RuntimeException:
java.nio.channels.ClosedByInterruptException
at org.neo4j.kernel.impl.transaction.xaframework.LogBackedXaDataSource.stop(LogBackedXaDataSource.java:73)
at org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource.stop(NeoStoreXaDataSource.java:448)
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.stop(LifeSupport.java:523)
... 14 more Caused by: java.nio.channels.ClosedByInterruptException
at java.nio.channels.spi.AbstractInterruptibleChannel.end(AbstractInterruptibleChannel.java:202)
at sun.nio.ch.FileChannelImpl.writeInternal(FileChannelImpl.java:743)
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:723)
at org.neo4j.kernel.impl.transaction.xaframework.DirectMappedLogBuffer.writeOut(DirectMappedLogBuffer.java:164)
at org.neo4j.kernel.impl.transaction.xaframework.DirectMappedLogBuffer.force(DirectMappedLogBuffer.java:178)
at org.neo4j.kernel.impl.transaction.xaframework.XaLogicalLog.releaseCurrentLogFile(XaLogicalLog.java:700)
at org.neo4j.kernel.impl.transaction.xaframework.XaLogicalLog.close(XaLogicalLog.java:725)
at org.neo4j.kernel.impl.transaction.xaframework.LogBackedXaDataSource.stop(LogBackedXaDataSource.java:69)
... 16 more 2014-04-02 10:12:29.057+0000 ERROR [org.neo4j]: Lifecycle exception Component
'org.neo4j.kernel.impl.transaction.XaDataSourceManager@2bf11e9f'
failed to stop. Please see attached cause exception.
org.neo4j.kernel.lifecycle.LifecycleException: Component
'org.neo4j.kernel.impl.transaction.XaDataSourceManager@2bf11e9f'
failed to stop. Please see attached cause exception.
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.stop(LifeSupport.java:528)
at org.neo4j.kernel.lifecycle.LifeSupport.stop(LifeSupport.java:155)
at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:123)
at org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:307)
at org.neo4j.kernel.EmbeddedGraphDatabase.(EmbeddedGraphDatabase.java:63)
at org.neo4j.graphdb.factory.GraphDatabaseFactory$1.newDatabase(GraphDatabaseFactory.java:92)
at org.neo4j.graphdb.factory.GraphDatabaseBuilder.newGraphDatabase(GraphDatabaseBuilder.java:198)
at org.neo4j.server.database.CommunityDatabase.createDb(CommunityDatabase.java:62)
at org.neo4j.server.database.CommunityDatabase.start(CommunityDatabase.java:120)
at org.neo4j.server.AbstractNeoServer.start(AbstractNeoServer.java:158)
at org.neo4j.server.Bootstrapper.start(Bootstrapper.java:87)
at org.neo4j.server.Bootstrapper.main(Bootstrapper.java:50) Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component
'org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource@4ec143d8' failed
to stop. Please see attached cause exception.
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.stop(LifeSupport.java:528)
at org.neo4j.kernel.lifecycle.LifeSupport.stop(LifeSupport.java:155)
at org.neo4j.kernel.impl.transaction.XaDataSourceManager.stop(XaDataSourceManager.java:185)
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.stop(LifeSupport.java:523)
... 11 more Caused by: java.lang.RuntimeException: java.nio.channels.ClosedByInterruptException
at org.neo4j.kernel.impl.transaction.xaframework.LogBackedXaDataSource.stop(LogBackedXaDataSource.java:73)
at org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource.stop(NeoStoreXaDataSource.java:448)
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.stop(LifeSupport.java:523)
... 14 more Caused by: java.nio.channels.ClosedByInterruptException
at java.nio.channels.spi.AbstractInterruptibleChannel.end(AbstractInterruptibleChannel.java:202)
at sun.nio.ch.FileChannelImpl.writeInternal(FileChannelImpl.java:743)
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:723)
at org.neo4j.kernel.impl.transaction.xaframework.DirectMappedLogBuffer.writeOut(DirectMappedLogBuffer.java:164)
at org.neo4j.kernel.impl.transaction.xaframework.DirectMappedLogBuffer.force(DirectMappedLogBuffer.java:178)
at org.neo4j.kernel.impl.transaction.xaframework.XaLogicalLog.releaseCurrentLogFile(XaLogicalLog.java:700)
at org.neo4j.kernel.impl.transaction.xaframework.XaLogicalLog.close(XaLogicalLog.java:725)
at org.neo4j.kernel.impl.transaction.xaframework.LogBackedXaDataSource.stop(LogBackedXaDataSource.java:69)
... 16 more 2014-04-02 10:12:29.080+0000 ERROR [org.neo4j]: Chained lifecycle exception Component
'org.neo4j.kernel.extension.KernelExtensions@55aa75c1' was
successfully initialized, but failed to start. Please see attached
cause exception. org.neo4j.kernel.lifecycle.LifecycleException:
Component 'org.neo4j.kernel.extension.KernelExtensions@55aa75c1' was
successfully initialized, but failed to start. Please see attached
cause exception.
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:509)
at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:115)
at org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:307)
at org.neo4j.kernel.EmbeddedGraphDatabase.(EmbeddedGraphDatabase.java:63)
at org.neo4j.graphdb.factory.GraphDatabaseFactory$1.newDatabase(GraphDatabaseFactory.java:92)
at org.neo4j.graphdb.factory.GraphDatabaseBuilder.newGraphDatabase(GraphDatabaseBuilder.java:198)
at org.neo4j.server.database.CommunityDatabase.createDb(CommunityDatabase.java:62)
at org.neo4j.server.database.CommunityDatabase.start(CommunityDatabase.java:120)
at org.neo4j.server.AbstractNeoServer.start(AbstractNeoServer.java:158)
at org.neo4j.server.Bootstrapper.start(Bootstrapper.java:87)
at org.neo4j.server.Bootstrapper.main(Bootstrapper.java:50) Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component
'org.neo4j.index.lucene.LuceneKernelExtension@287c20ab' was
successfully initialized, but failed to start. Please see attached
cause exception.
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:509)
at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:115)
at org.neo4j.kernel.extension.KernelExtensions.start(KernelExtensions.java:118)
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:503)
... 10 more Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component
'org.neo4j.index.impl.lucene.LuceneDataSource@2f4c076f' was
successfully initialized, but failed to start. Please see attached
cause exception.
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:509)
at org.neo4j.kernel.lifecycle.LifeSupport.bringToState(LifeSupport.java:411)
at org.neo4j.kernel.lifecycle.LifeSupport.add(LifeSupport.java:324)
at org.neo4j.kernel.impl.transaction.XaDataSourceManager.registerDataSource(XaDataSourceManager.java:236)
at org.neo4j.index.lucene.LuceneKernelExtension.start(LuceneKernelExtension.java:79)
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:503)
... 13 more Caused by: java.lang.RuntimeException: java.nio.channels.ClosedByInterruptException
at org.neo4j.kernel.impl.index.IndexProviderStore.(IndexProviderStore.java:85)
at org.neo4j.index.impl.lucene.LuceneDataSource.newIndexStore(LuceneDataSource.java:302)
at org.neo4j.index.impl.lucene.LuceneDataSource.start(LuceneDataSource.java:225)
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:503)
... 18 more Caused by: java.nio.channels.ClosedByInterruptException
at java.nio.channels.spi.AbstractInterruptibleChannel.end(AbstractInterruptibleChannel.java:202)
at sun.nio.ch.FileChannelImpl.position(FileChannelImpl.java:290)
at org.neo4j.kernel.impl.index.IndexProviderStore.write(IndexProviderStore.java:169)
at org.neo4j.kernel.impl.index.IndexProviderStore.create(IndexProviderStore.java:153)
at org.neo4j.kernel.impl.index.IndexProviderStore.(IndexProviderStore.java:61)
... 21 more 2014-04-02 10:12:29.141+0000 DEBUG [API] Failed to start database. 2014-04-02 10:12:29.144+0000 DEBUG [API]
org.neo4j.server.ServerStartupException: Startup took longer than
120000ms, and was stopped. You can disable this behavior by setting
'org.neo4j.server.startup_timeout' to 0. Error code: 1
at org.neo4j.server.AbstractNeoServer.start(AbstractNeoServer.java:211)
~[neo4j-server-2.0.1.jar:2.0.1]
at org.neo4j.server.Bootstrapper.start(Bootstrapper.java:87) [neo4j-server-2.0.1.jar:2.0.1]
at org.neo4j.server.Bootstrapper.main(Bootstrapper.java:50) [neo4j-server-2.0.1.jar:2.0.1] 2014-04-02 10:12:29.180+0000 DEBUG
[API] Failed to start Neo Server on port [7478]
Any ideas why this may happen?
My java is:
$ java -version
java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode)
A: Your system only allow 1024 open files. Read the first line of your startup message:
Max 1024 open files allowed, minimum of 40 000 recommended. See the Neo4j manual
see http://docs.neo4j.org/chunked/stable/linux-performance-guide.html#_setting_the_number_of_open_files for details.
| |
doc_23532330
|
if I go to the view "people" in the notesclient and do a search for FIELD DEPARTMENT = "Finance" I get back several results.
..and when I print out the query in on the web it is exactly the same as when I enter it in the client: FIELD DEPARTMENT = "Finance" but still no result is retrieved.
var dc:NotesDocumentCollection = database.getView("people").getAllDocumentsByKey("people",true);
q = "\"" + r + "\""
query = "FIELD DEPARTMENT Contains " + q
dc.FTSearch(query);
also tried this
query = "[DEPARTMENT] Contains \"" + r + "\"";
dc.FTSearch(query);
if I return "dc" without the search i get several results
My queries seem to work for view.FTSearch and db.FTSearch but not dc.FTSearch.
any ideas?
A: I think I fell into the same trap: you MUST use the 2nd parameter of FTSearch, e.g.
dc.FTSearch(query, 0)
A: I solved it, it works now. not sure it was because I added "return" or if it was that I added a new return line. the lines below works
var dc:NotesDocumentCollection = database.getView("people").getAllDocumentsByKey("people",true);
query = "[DEPARTMENT] Contains \"" + r + "\"";
dc.FTSearch(query);
return dc
| |
doc_23532331
|
mymap.insert(std::make_pair("ELEMENTTYPE", "NEWINTERFACE"));
mymap.insert(std::make_pair("STYLEFILE", "Style_Light.txt"));
mymap.insert(std::make_pair("ELEMENTNAME", "IN1"));
mymap.insert(std::make_pair("POSITIONX", "0"));
mymap.insert(std::make_pair("POSITIONY", "0"));
mymap.insert(std::make_pair("SIZEX", "50"));
mymap.insert(std::make_pair("SIZEY", "50"));
I expected the map to have those elements in that order, but instead, it is :
-SIZEY
-ELEMENTTYPE
-STYLEFILE
-SIZEX
-POSITIONX
-POSITIONY
I am very confused; why is the std::unordered_map ordering my elements?
A: The term unordered in std::unordered_map means that the order is unspecified. You cannot rely on the order of an unordered_* container. All associative containers (containers which map a value to a key) will mess with the order of the elements because this order allows them to achieve better performance when searching by key, which is usually the goal of using a map.
If you want to control the order yourself, you can use std::vector<std::pair<std::string, std::string>>. You'll have a set of pairs, ordered the way you want, but you forfeit the fast find implementations associative containers provide.
A: You want a specific arbitrary order
std::unordered_map has no particular order that you can control
std::map sorts the keys according to a function
If you want something like python's OrderedDict in c++ here are some duplicate answers:
C++ dictionary/map with added order
A std::map that keep track of the order of insertion?
Perhaps you are trying to be too fancy, when all you really need is a basic struct object. It's just a variable and its members are just variables that you get when and how you want.
#include <vector>
#include <string>
enum elementtype_enum { NEWINTERFACE, OTHER };
struct my_element_type {
std::string name;
elementtype_enum type;
std::string style_file;
int positionx, positiony, sizex, sizey;
};
int main() {
std::vector<my_element_type> elements;
my_element_type e { "IN1", NEWINTERFACE, "Style_Light.txt", 0, 0, 50, 50 };
elements.push_back(e);
return 0;
}
A: By its very name, a std::unordered_map is unordered. The order of its elements is unspecified, and will be dependent on the hash of the Key values.
If the order of the elements is important to you, use std::map instead. By default, it uses the Key's operator< for ordering, but you can optionally provide a custom Compare type if you want to order the elements yourself.
| |
doc_23532332
|
Is there anywhere I can populate the alt tag ? The lightbox image is opened like so
<a href="img/image-1.jpg" data-lightbox="image-1" title="My caption">image #1</a>
How would I pass an alt tag to the lightbox ?
A: In your javascript attach the alt tag afterwards, something like:
$("light_box_img").attr("alt", $("original_img").attr("alt"));
I can help with a more detailed solution, but will need you to post some code...
| |
doc_23532333
|
var d = new Date();
d.setMonth(given_month, 1);
return d.toISOString();
}
function lastDayOfMonth(given_month) {
var d = new Date();
d.setMonth(given_month + 1, 0);
return d.toISOString();
}
var temp = {
firstDayOfMonth: firstDayOfMonth(given_month),
lastDayOfMonth: lastDayOfMonth(given_month)
}
console.log(JSON.stringify(temp))
Trying to get first day of the month and last day of the month to develop a monthly report. I got {"firstDayOfMonth":"2016-11-01T09:45:30.998Z","lastDayOfMonth":"2016-11-30T09:45:30.998Z"}
for temp, is that normal? why it's 9:45 something?
A: You are doing the right thing. You just need to set hour for start and end day:
firstDayOfMonth.setHours(0,0,0,0);
lastDayOfMonth.setHours(23,59,59,999);
A: Just normalize date object with H/M/S set to 12:00:00, like this:
const givenMonth = 6;
const normalizeTime = d => {
d.setHours(12);
d.setMinutes(0);
d.setSeconds(0);
return d;
};
const getISODate = (month, day) => {
const d = new Date();
d.setMonth(month, day);
return normalizeTime(d).toISOString();
};
const temp = {
firstDayOfMonth: getISODate(givenMonth, 1),
lastDayOfMonth: getISODate(givenMonth + 1, 0)
};
temp;
| |
doc_23532334
|
A: well
CCSprite *spr = [CCSprite spriteWithFile:@"theSprite.png"];
actually puts the texture in cache with the file name as key.
so
CCTexture2D * tex = [CCTextureCache sharedTextureCache:textureForKey:@"theSprite.png"];
will actually give you back the sprite's texture.
One last bit : before putting the texture in cache, the CCSprite constructor verifies if the cache already contains a texture with the key. If it does, it skips a whole bunch of steps and returns you the sprite constructed with the cached texture.
A: Try this:
CCTexture2D *pText = [CCTextureCache sharedTextureCache:textureForKey: @"(your picture filename)"];
CCSprite *pSprite = [CCSprite spriteWithTexture: pText];
Read reference here(you can get almost everything you want from the reference):
http://www.cocos2d-iphone.org/api-ref/latest-stable/interface_c_c_sprite.html
| |
doc_23532335
|
I know it says the installation is broken but I'm trying to uninstall it
Here's the part of the log where I found the error message:
| |
doc_23532336
|
Below is the XAML code and XAML.CS
<ListView
x:Name="workList"
Grid.Row="2"
SeparatorColor="{DynamicResource AccentColor}"
ItemsSource="{ Binding WorkItems }"
Margin="5"
CachingStrategy="RecycleElement"
RowHeight="440"
SeparatorVisibility="Default"
SelectionMode="None"
HasUnevenRows="False">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<local:LoadItemPutawayTemplate />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-
compatibility/2006"
mc:Ignorable="d"
x:Class="Sanipex.LoadItemPutawayTemplate">
<Grid
RowSpacing="0"
Padding="0"
Margin="0,10,0,0"
>
<Grid.RowDefinitions>
<RowDefinition
Height="*" />
</Grid.RowDefinitions>
<Entry
x:Name="OverrideLoc"
Grid.Row="0"
TextColor="Black"
WidthRequest="110"
Text="{Binding toLocation}"
grial:EntryProperties.BorderCornerRadius="10"
grial:EntryProperties.BorderStyle="RoundRect"
grial:EntryProperties.BorderColor="Black"
HorizontalOptions="StartAndExpand"
VerticalOptions="Center"
Focused="OverrideLoc_Focused"
TextChanged="OverrideLoc_TextChanged"
grial:EntryProperties.HorizontalPadding="5"
FontAttributes="Bold"
PlaceholderColor="Black"
FontSize="20"/>
</Grid>
public partial class ItemPutAway : ContentPage
{
private static ItemPutAwayViewModel obj;
public ItemPutAway()
{
InitializeComponent();
obj = new ItemPutAwayViewModel();
BindingContext = obj;
}
public static ItemPutAwayViewModel itemPutAwayViewModel
{
get
{
return obj;
}
}
protected override async void OnAppearing()
{
obj.LoadData();
}
}
Below is my first view model code
public class ItemPutAwayViewModel : INotifyPropertyChanged
{
private IList<WorkItem> workItems;
public event PropertyChangedEventHandler PropertyChanged;
public string ltoLocation;
public string toLocation
{
get => ltoLocation;
set
{
ltoLocation = value;
OnPropertyChanged(nameof(toLocation));
}
}
public IList<WorkItem> WorkItems
{
get => workItems;
set
{
workItems = value;
OnPropertyChanged(nameof(WorkItems));
}
}
public void LoadData()
{
WorkItems = App.dataManager.GetItemPutAwayWorks();
}
public void setLocation(string _location)
{
toLocation = _location;
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Below is the code through which I am trying to update the toLocation binding value to different value from another XAML page as below:
public partial class AvailableLocationsPopUp : PopupPage
{
private static AvailableLocationViewModel obj;
public AvailableLocationsPopUp(WorkItem _workItem)
{
InitializeComponent();
obj = new AvailableLocationViewModel(gWorkItem.itemid);
BindingContext = obj;
}
private void OnClose(object sender, EventArgs e)
{
PopupNavigation.Instance.PopAsync();
}
private void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
Location content = e.Item as Location;
ItemPutAway.itemPutAwayViewModel.setLocation("ABC-XYZ");
PopupNavigation.Instance.PopAsync();
}
}
A: As I mentioned in the discussion, you have to also implement the INotifyPropertyChanged interface of the class WorkItem.
Implement INotifyPropertyChanged in ItemPutAwayViewModel will only help for changes in the WorkItems(like add or remove one WorkItem), not the changes inside the WorkItem.
So, the code should be:
public class WorkItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _toLocation;
public string toLocation
{
get => _toLocation;
set
{
_toLocation = value;
NotifyPropertyChanged();
}
}
protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
| |
doc_23532337
|
My Model:
model = Sequential()
model.add(InputLayer(input_shape=[64, 64, 1]))
model.add(Conv2D(filters=32, kernel_size=5, strides=1, padding='same',
activation='relu'))
model.add(MaxPool2D(pool_size=5, padding='same'))
model.add(Conv2D(filters=50, kernel_size=5, strides=1, padding='same',
activation='relu'))
model.add(MaxPool2D(pool_size=5, padding='same'))
model.add(Conv2D(filters=80, kernel_size=5, strides=1, padding='same',
activation='relu'))
model.add(MaxPool2D(pool_size=5, padding='same'))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(rate=0.5))
model.add(Dense(5, activation='softmax'))
optimizer = Adam(lr=1e-3)
model.compile(optimizer=optimizer, loss='categorical_crossentropy',
metrics=['accuracy'])
model.fit(x=tr_img_data, y=tr_lbl_data, epochs=50, batch_size=100)
model.summary()
*
*Save with Model weight:
model_json = model.to_json()
with open("model.json", "w") as json_file:
json_file.write(model_json)
model.save_weights("model.h5")
Load:
def loadModel(jsonStr, weightStr):
json_file = open(jsonStr, 'r')
loaded_nnet = json_file.read()
json_file.close()
serve_model = tf.keras.models.model_from_json(loaded_nnet)
serve_model.load_weights(weightStr)
optimizer = Adam(lr=1e-3)
serve_model.compile(optimizer=optimizer, loss='categorical_crossentropy',
metrics=['accuracy'])
return serve_model
model = loadModel('model.json', 'model.h5')
*Try with save all Model H5
model.save('model.h5')
#load model
load_model = load_model('model.h5')
There all always getting error:
ValueError: You are trying to load a weight file containing 5 layers into a model with 0 layers
| |
doc_23532338
|
One for example is the DisplayFor HTML Helper. The code goes @Html.DisplayFor(model => model.name)
I hope no one thinks this is a stupid question, it is just that whilst I (think I) understand Lambda expressions for the most part, they don't "flow" like regular code and I have to think about it quite hard to understand what is actually happening!
So the question really is,
1) is there any benefit that I am missing to them using Lambda queries for these HTML Helpers?
2) As far as I can tell, the DisplayFor will only ever be hooked up to one item - so, why isn't this just @Html.DisplayFor(model.name) or similar?
And please give any other information that can make a MVC newbie better!
A: You do have the option of using an alternative, similar to what you have above. In this case it would actually be @Html.Display("name") without the 'For' portion, and with the property name of the model passed in as a string. This is an OK alternative. If your property name changes though this will break at runtime.
I like the lambdas because I'm a refactoring junkie who constantly renames things. By turning on view compilation I can then lean on the compiler to help me find the places I need to update my views.
A: Before I answer your 2 bullet points, I think you need to understand what lambda expressions actually are.
In .Net, Lambda expressions used in this way are what is called Expression Trees. From MSDN:
Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.
These are essentially data structures that describe what is being passed in rather than the values of the data being passed in. What this means is that when you call Html.DisplayFor(x => model.Name) it is passing in a data structure that says "I am calling this method for the Name property of the xxxx data structure (where xxxx is the type of data structure that represents your View Model).
The DisplayFor then looks at this data and sees that the property name Name is well Name, it looks at all attributes for the property to find out if you have any data annotations attached to it, and then looks at the value to determine how to represent the display for the value. It's a bit complicated until you get your head wrapped around it, but once you look at the MSDN page and think about it you will have an aha! moment like I did, and it will just suddenly make sense :)
As to your question #1, the advantage of using lambda expressions is you get compile time checking of your properties. For example, if you rename ViewModel.Name to ViewModel.ClientName, all your Html.DisplayFor(x => model.Name) won't compile, thus making sure you change them. If you don't use lambda expressions, all your Html.Display() calls will work, but you will get hidden bugs with model binding that will not be immediately obvious of what's wrong.
To answer #2, the reason is the same as my description of expression trees. Without using lambdas, you are just passing in the value of Model.Name with no information about the property itself, so it doesn't know the name of Model.Name property is Name, all it sees is the string value.
Another good write-up of Expression Trees can be found here. Understanding expression trees opens up a whole lot of power in .Net :)
| |
doc_23532339
|
This works in MS SQL Server, but not in Firebird. (haven't tested it n Oracle yet)
CONVERT(char(8),MAX(p.end_Time)-MIN (p.start_Time),8) as duration
is there a way to acoomplish this same thing for (Firebird, Oracle, and MS Sql Server)?
thanks
A: there is no CONVERT on firebird.
Use CAST:
select cast(MAX(p.end_Time) as varchar(50)) and so on...
A: For Firebird you need to use DATEDIFF to obtain a difference between two timestamps (datetimes). This BTW is similar to the SQL Server DATEDIFF. If you then want to cast it to char, you can use CAST, eg CAST(DATEDIFF(DAY, MAX(p.end_Time), MIN(p.start_Time)) AS CHAR(8)) should do the trick (or you can simply do CAST(MAX(p.end_Time) - MIN (p.start_Time) AS CHAR(8)) as timestamps are subtractable.
I just noticed though that the option you specify in your CONVERT will convert to hh:mi:ss. There is no such option in Firebird. If you need to convert specifically to hh:mi:ss, you might want to look at UDF libraries like FreeAdhocUDF (specifically F_SECONDS2PERIOD) or rFunc UDF. If all else fails, you could write your own UDF.
A: On Oracle (Oracle 8i, Oracle 9i, Oracle 10g, Oracle 11g), you can use to_char function:
select to_char( value, [ format_mask ], [ nls_language ] ) ....
Example:
SELECT TO_CHAR ( SYSDATE - TO_DATE ( '18-10-2012', 'dd-mm-yyyy' ), '9,999.99' ) as duration FROM DUAL;
Here is the link for Oracle/PLSQL: To_Char Function
| |
doc_23532340
|
docker pull alexdobin/star
I got an error despite copying the Docker Pull Command as shown in the screenshot (lower right)
The error was the following:
Error response from daemon: manifest for alexdobin/star:latest not found: manifest unknown: manifest unknown
A: The problem is that when you don't specify the tag as part of the image name in the docker command then it is assumed that you are referring to the latest tag.
Further, as there is no image with tag latest present in the repository, you get the error as expected:
Error response from daemon: manifest for alexdobin/star:latest not found: manifest unknown: manifest unknown
Change the tag to one of the available ones and it will work as expected:
docker pull alexdobin/star:2.6.1d
A: You can open just the tab Tags and copy the pull command as shown in the screenshot (bottom right).
It worked just fine.
| |
doc_23532341
|
select get_foo() from dual;
or
select * from table (get_foo);
returns the same result as
select * from foo;
So, I've got a function that compiles...
create or replace function get_foo return sys_refcursor as
rc_foo sys_refcursor;
begin
open rc_foo for 'select * from foo';
return rc_foo;
end;
but select get_foo() from dual returns 1 row.
((ID=1,NAME=Sarah1),(ID=2,NAME=Sarah2),(ID=3,NAME=Sarah3),)
whilst select * from table( get_foo() ) gives me ORA-22905.
How do I change the function definition and/or the call to get the desired outcome?
A: you use a pipelined function.
for example:
SQL> create table foo(id , name) as select rownum, 'Sarah'||rownum from dual connect by level <= 3;
Table created.
SQL> create or replace package pipeline_test
2 as
3 type foo_tab is table of foo%rowtype;
4 function get_foo
5 return foo_tab PIPELINED;
6 end;
7 /
Package created.
SQL> create or replace package body pipeline_test
2 as
3 function get_foo
4 return foo_tab PIPELINED
5 is
6 v_rc sys_refcursor;
7 t_foo foo_tab;
8
9 begin
10 open v_rc for select * from foo;
11 loop
12 fetch v_rc bulk collect into t_foo limit 100;
13 exit when t_foo.count = 0;
14 for idx in 1..t_foo.count
15 loop
16 pipe row(t_foo(idx));
17 end loop;
18 end loop;
19 end;
20 end;
21 /
Package body created.
SQL> select * from table(pipeline_test.get_foo());
ID NAME
---------- ---------------------------------------------
1 Sarah1
2 Sarah2
3 Sarah3
| |
doc_23532342
|
Also, there's been another project spun up called RxSwift.
I wonder if people could add information about what the differences in design/api/philosophy of the two frameworks are (please, in the spirit of SO, stick to things which are true, rather than opinions about which is "best")
[Note for StackOverflow mods: This question DOES have definitive answers, the answer is the differences between the two frameworks. I think it is also highly on topic for SO]
To get started, my initial impression from reading their ReadMe's is:
*
*As someone who is familiar with the "real" C# Rx from microsoft, RxSwift looks a lot more recognisable.
*ReactiveCococa seems to have gone off into its own space now, introducing new abstractions such as Signals vs SignalProducers and Lifting. On the one hand this seems to clarify some situations (what's a Hot vs Cold signal) but on the other hand this seems to increase the complexity of the framework a LOT
A: This is a very good question. Comparing the two worlds is very hard. Rx is a port of what Reactive Extensions are in other languages like C#, Java or JS.
Reactive Cocoa was inspired by Functional Reactive Programming, but in the last months, has been also pointed as inspired by Reactive Extensions as well. The outcome is a framework that shares some things with Rx, but has names with origins in FRP.
The first thing to say is that neither RAC nor RxSwift are Functional Reactive Programming implementations, according to Conal's definition of the concept. From this point everything can be reduced to how each framework handles side effects and a few other components.
Let's talk about the community and meta-tech stuff:
*
*RAC is a 3 years old project, born in Objective-C later ported to Swift (with bridges) for the 3.0 release, after completely dropping the ongoing work on Objective-C.
*RxSwift is a few months old project and seems to have a momentum in the community right now. One thing that is important for RxSwift is that is under the ReactiveX organization and that all other implementations are working in the same way, learning how to deal with RxSwift will make working with Rx.Net, RxJava or RxJS a simple task and just a matter of language syntax. I could say that is based on the philosophy learn once, apply everywhere.
Now it's time for the tech stuff.
Producing/Observing Entities
RAC 3.0 has 2 main entities, Signal and SignalProducer, the first one publishes events regardless a subscriber is attached or not, the second one requires a start to actually having signals/events produced. This design has been created to separate the tedious concept of hot and cold observables, that has been source of confusion for a lot of developers. This is why the differences can be reduced to how they manage side effects.
In RxSwift, Signal and SignalProducer translates to Observable, it could sound confusing, but these 2 entities are actually the same thing in the Rx world. A design with Observables in RxSwift has to be created considering if they are hot or cold, it could sound as unnecessary complexity, but once you understood how they work (and again hot/cold/warm is just about the side effects while subscribing/observing) they can be tamed.
In both worlds, the concept of subscription is basically the same, there's one little difference that RAC introduced and is the interruption event when a Signal is disposed before the completion event has been sent.
To recap both have the following kind of events:
*
*Next, to compute the new received value
*Error, to compute an error and complete the stream, unsubscribing all the observers
*Complete, to mark the stream as completed unsubscribing all observers
RAC in addition has interrupted that is sent when a Signal is disposed before completing either correctly or with an error.
Manually Writing
In RAC, Signal/SignalProducer are read-only entities, they can't be managed from outside, same thing is for Observable in RxSwift. To turn a Signal/SignalProducer into a write-able entity, you have to use the pipe() function to return a manually controlled item. On the Rx space, this is a different type called Subject.
If the read/write concept sounds unfamiliar, a nice analogy with Future/Promise can be made. A Future is a read-only placeholder, like Signal/SignalProducer and Observable, on the other hand, a Promise can be fulfilled manually, like for pipe() and Subject.
Schedulers
This entity is pretty much similar in both worlds, same concepts, but RAC is serial-only, instead RxSwift features also concurrent schedulers.
Composition
Composition is the key feature of Reactive Programming. Composing streams is the essence of both frameworks, in RxSwift they are also called sequences.
All the observable entities in RxSwift are of type ObservableType, so we compose instances of Subject and Observable with the same operators, without any extra concern.
On RAC space, Signal and SignalProducer are 2 different entities and we have to lift on SignalProducer to be able to compose what is produced with instances of Signal. The two entities have their own operators, so when you need to mix things, you have to make sure a certain operator is available, on the other side you forget about the hot/cold observables.
About this part, Colin Eberhardt summed it nicely:
Looking at the current API the signal operations are mainly focussed on the ‘next’ event, allowing you to transform values, skip, delay, combine and observe on different threads. Whereas the signal producer API is mostly concerned with the signal lifecycle events (completed, error), with operations including then, flatMap, takeUntil and catch.
Extra
RAC has also the concept of Action and Property, the former is a type to compute side effects, mainly relating to user interaction, the latter is interesting when observing a value to perform a task when the value has changed. In RxSwift the Action translates again into an Observable, this is nicely shown in RxCocoa, an integration of Rx primitives for both iOS and Mac. The RAC's Property can be translated into Variable (or BehaviourSubject) in RxSwift.
It's important to understand that Property/Variable is the way we have to bridge the imperative world to the declarative nature of Reactive Programming, so sometimes is a fundamental component when dealing with third party libraries or core functionalities of the iOS/Mac space.
Conclusion
RAC and RxSwift are 2 complete different beasts, the former has a long history in the Cocoa space and a lot of contributors, the latter is fairly young, but relies on concepts that have been proven to be effective in other languages like Java, JS or .NET. The decision on which is better is on preference. RAC states that the separation of hot/cold observable was necessary and that is the core feature of the framework, RxSwift says that the unification of them is better than the separation, again it's just about how side effects are managed/performed.
RAC 3.0 seems to have introduced some unexpected complexity on top of the major goal of separating hot/cold observables, like the concept of interruption, splitting operators between 2 entities and introducing some imperative behaviour like start to begin producing signals. For some people these things can be a nice thing to have or even a killer feature, for some others they can be just unnecessary or even dangerous. Another thing to remember is that RAC is trying to keep up with Cocoa conventions as much as possible, so if you are an experienced Cocoa Dev, you should feel more comfortable to work with it rather than RxSwift.
RxSwift on the other hand lives with all the downsides like hot/cold observables, but also the good things, of Reactive Extensions. Moving from RxJS, RxJava or Rx.Net to RxSwift is a simple thing, all the concepts are the same, so this makes finding material pretty interesting, maybe the same problem you are facing now, has been solved by someone in RxJava and the solution can be reapplied taking in consideration the platform.
Which one has to be picked is definitely a matter of preference, from an objective perspective is impossible to tell which one is better. The only way is to fire Xcode and try both of them and pick the one that feels more comfortable to work with. They are 2 implementations of similar concepts, trying to achieve the same goal: simplifying software development.
| |
doc_23532343
|
Can someone help me to get this working?
Please
Here is my jsfiddle Link
http://jsfiddle.net/chogger/j3xvg
This is what I found:
$(chart.series).each(function(i, serie){
$('<li style="color: '+serie.color+'">'+serie.name+'</li>').click(function(){
serie.visible ? serie.hide() : serie.show();
}).appendTo('#legend')
})
A: What exactly doesn't work for you? Are you using load event handler for this? See: http://jsfiddle.net/j3xvg/1/
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'line',
marginRight: 50,
marginBottom: 175,
events: {
load: function () {
var chart = this;
$(chart.series).each(function (i, serie) {
$('<li style="color: ' + serie.color + '">' + serie.name + '</li>').click(function () {
serie.visible ? serie.hide() : serie.show();
}).appendTo('#legend');
});
}
}
},
});
| |
doc_23532344
|
The file structure for the project is as follows:
package.json // Workspaces file
application
package.json
// Applicaiton files
library
package.json
dist
component-library
package.json
esm2020
// JavaScript files
fesm2015
// JavaScript files
fesm2020
// JavaScript files
confirmation
index.d.ts
sort
index.d.ts
packages
component-library
package.json
sort
index.ts
package.json // contains: { "main": "./index" }
confirmation
index.ts
package.json // contains: { "main": "./index" }
In my workspaces file I have the following setup:
{
"scripts": {
"start": "npm run start -w application"
},
"workspaces": [
"application",
"library",
"library/projects/component-library"
]
}
When I install and run, I get the following error:
ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'ɵcmp')
When I replace projects with dist in "library/projects/component-library", and reinstall and run, the application starts up and works fine.
Why am I having issues when not using the built files?
| |
doc_23532345
|
Ex.:
str = "<div>I am a moron</div>";
code = "<div>" + str + "</div>;
newStr = code.replace(str, "I am not a moron");
//newStr = "I am not a moron"
I want //newStr = "<div>I am not a moron</div>"
Without adding the div tags in the replace method
A: You just need to use a regular expression to match the open and close div, so you can put them back with the matching capture groups, $1, and $2, inside your replace call.
Also, if you're not familiar with regular expressions, go check out this RegExr demo where you can play around.
Solution
var str = "<div>I am a moron</div>";
var regex = /(<div>)I am a moron(<\/div>)/;
newStr = str.replace(regex, "$1I am not a moron$2");
console.log(newStr);
Solution 2
This is a more complicated solution, showing how to match several nested elements to get the correct capture groups
var str = '<div class="foo bar2" data-taco="something"><ul><li>I am a moron</li></ul></div>';
var regex = /((?:<.*>)+)I am a moron((?:<\/.*>)+)/;
newStr = str.replace(regex, "$1I am not a moron$2");
console.log(newStr);
Solution 3
This solution focuses on find replace within the HTML DOM vs a string of html
const container = document.getElementById('container');
container.innerHTML = container.innerHTML.replace(/I am a moron/,"I am not a moron");
<div id="container">
<section>
<div id="something" class="foo bar">
<p>I am a moron</p>
</div>
</section>
</div>
Documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
| |
doc_23532346
|
| A | B |
|-------|
| 1 | 2 |
| 1 | 4 |
| 1 | 6 |
| 1 | 9 |
| 1 | 1 |
| 1 | 6 |
| 1 | 9 |
Now I want to increase column A by the index of the result table, so the result would become like this:
| A | B |
|-------|
| 2 | 2 |
| 3 | 4 |
| 4 | 6 |
| 5 | 9 |
| 6 | 1 |
| 7 | 6 |
| 8 | 9 |
How can I do it?
Thanks!
A: You want row_number()
select (row_number() over (order by a) + 1) as A, b
from table t;
A: Maybe something like that:
SELECT
(row_number() OVER (ORDER BY A) + A) AS columnAIndex,
columnB
FROM ...
I don't have a PostgreSQL client installed here, therefore, i don't tested this query.
| |
doc_23532347
|
*
*Graal VM: graalvm-ce-java11-19.3.2
*Windows SDK : Windows SDK 10.
I can't get it to work with other versions of graal ( graalvm-ce-java11-20.2.0-dev, graalvm-ce-java8-20.2.0-dev..), maybe for peculiarities of the local development environment ( impossibility to use Windows 7 SDK, eg. ..)
My next goals are to generate simple executables but with some more complex dependency, eg. the following vertx example
https://how-to.vertx.io/graal-native-image-howto/
Ideally my intention is to generate it using the maven plugin.
If it is not possible, as an alternative creating a fat jar and then converting it to native
1. Using native-image-maven-plugin
<groupId>org.graalvm.nativeimage</groupId>
<artifactId>native-image-maven-plugin</artifactId>
<version>19.3.2</version>
Error: Failed to execute goal org.graalvm.nativeimage:native-image-maven-plugin:19.3.2:native-image (default) on project demo01GraalTestClasses: Image building on Java 11+ without native-image requires MAVEN_OPTS='--add-exports=java.base/jdk.internal.module=ALL-UNNAMED' -> [Help 1]
[ERROR]
2. By command line after creating a fat jar
openjdk version "11.0.7" 2020-04-14
OpenJDK Runtime Environment GraalVM CE 19.3.2 (build 11.0.7+10-jvmci-19.3-b10)
OpenJDK 64-Bit Server VM GraalVM CE 19.3.2 (build 11.0.7+10-jvmci-19.3-b10, mixed mode, sharing)
[ **Important** ] call vcvars64.bat !
**native-image.cmd --verbose --static --no-fallback -H:+ReportExceptionStackTraces -jar demoGraalTestClasses.jar demo**
**Error**:
[demo:4920] classlist: 3,964.94 ms
[demo:4920] (cap): 38,810.44 ms
[demo:4920] setup: 41,140.72 ms
[demo:4920] analysis: 18,151.19 ms
Fatal error: com.oracle.svm.core.util.VMError$HostedError: class java.net.TwoStacksPlainSocketImpl not found
Any idea ??? Thank u!
A: I was running through the same error with no resolution. It seems that it is more plugin issue than the windows one.
I gave up and prepared ubuntu VM, run native image under exactly the same conditions like in windows(pom.xml, java11, graalvm 20.0.0) and it worked.
So I would either wait for next plugin release or tried to go linux way. Do not expect quick advice here.
| |
doc_23532348
|
[SwiftUI] Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like
receive(on:)) on model updates.
Here is how I perform API requests
func performRequest(with request: some AbstractRequest) {
var link = host + request.endpoint
appendParameters(to: &link, with: request.params)
guard let url = URL(string: link) else {
print("Failed to generate url from \(link)")
return
}
let task = URLSession.shared.dataTask(with: url){ data, response, error in
guard let data = data, error == nil else{
print("\(error?.localizedDescription ?? "")")
return
}
request.completion(data: data)
}
task.resume()
}
Here is an example completion handler (Bonus point if you can tell me why I get this warning
Conditional cast from '[LoginResponse]' to '[LoginResponse]' always succeeds
on the cast line but if I remove the cast it complains.)
func completion(data: Data)
{
do{
guard let response = try JSONDecoder().decode([LoginResponse].self, from: data) as? [LoginResponse] else { return }
delegate.responseReceived(response: response)
}catch let error{
print("\(error.localizedDescription)")
}
}
Here is what my LoginManager looks like
class LoginManager: ObservableObject, ApiRequestDelegate{
static var shared = LoginManager()
var token = ""
@Published var isLoggedIn: Bool = false
func responseReceived(response: Any) {
guard let response = response as? LoginResponse, response.token != -1 else { return }
token = String(response.token)
isLoggedIn = true
}
}
And finally my ContentView
struct ContentView: View {
@ObservedObject var loginManager = LoginManager.shared
var body: some View {
if !loginManager.isLoggedIn {
LoginView()
}else {
OpenLinkButton().ignoresSafeArea()
}
}
}
A: Your completion handler inside URLSession.shared.dataTask is called on a background thread. So everything that follows is on a background thread.
The most simple solution would be to dispatch UI changes to the main Thread. e.g.:
DispatchQueue.main.async{
isLoggedIn = true
}
another solution would be to decorate the function interacting with the UI with @MainActor atribute. e.g.:
@MainActor
func responseReceived(response: Any) {
| |
doc_23532349
|
if let popoverController = activityViewController.popoverPresentationController {
popoverController.sourceView = sender
}
self.presentViewController(activityViewController, animated: true, completion: nil)
So basically I want to share the content only through mail and I do not want to show the option of message.
Could you help me out with that. Also I want to set the subject of the email through the code
A: Just add excludedActivityTypes to remove all the other activity except email
yourActivityViewController.excludedActivityTypes = [ UIActivityTypePostToFacebook, UIActivityTypePostToTwitter, UIActivityTypePostToWeibo, UIActivityTypeMessage, UIActivityTypePrint, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll,UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr, UIActivityTypePostToVimeo,UIActivityTypePostToTencentWeibo,UIActivityTypeAirDrop]
Add subject
yourActivityViewController.setValue("Your email Subject" , forKey: "subject") ;
Suggession :-
You can also use MFMailComposeViewController to send email
var picker = MFMailComposeViewController()
picker.mailComposeDelegate = self
picker.setSubject(subject.text)
picker.setMessageBody(body.text, isHTML: true)
presentViewController(picker, animated: true, completion: nil)
More References :-
How do I use UIActivityItemProvider to send an email with attachment with UIActivityViewController?
iOS 8 - Disable iCloud Photo Sharing Activity
| |
doc_23532350
|
My code like:
return myModel.user.create(userInfo, {
include: [{
model: myModel.userAddresses,
as: 'addresses'
}]
}).then((insertUser) => {
return "insert successfully"
}).catch((err) => {
throw err;
});
Error Like:"SequelizeValidationError: notNull Violation: ADDRESS_ID cannot be null"
A: You have to verify your model class in node js "myModel.userAddresses" whether property allow null is true
type: Sequelize.INTEGER,
allowNull: true
| |
doc_23532351
|
What does it do, how to know it?
A: You can capture a thread dump using jstack or capture a CPU snapshot using YourKit.
| |
doc_23532352
|
I have a regex that has nested brackets (see below). I need to match ALL occurrences of it in a line and then do something with the pieces. However, I cannot figure out how to reference specific groups from my regex.
Specifically, this is my regex:
(([a-zA-Z][a-zA-Z0-9_\+\-\.]*\.)+\s*[a-zA-Z]{2,6})
I actually don't care about preserving the contents of the inner brackets I just want to get all the matches for the outer one.
If I use "match" I get one instance and can reference by using the Match Object. However, when I do findall, it does not return Match Objects, it only returns a list.
A: You're probably looking for re.finditer():
import re
a = 'foo 123 blah 234 xxx 655'
for m in re.finditer(r'(\d+)', a):
print m.group(1)
| |
doc_23532353
|
Thanks!
// The 1st Wed in Jan 2020 falls on New Year's Day
// But we get: "Wed 2020-01-08" (INCORRECT... it should return "Wed 2020-01-01")
echo date("D Y-m-d", strtotime("First Wednesday " . "2020-01"));
// However, asking for the 1st Thu in Jan 2020 returns the correct result: "Thu 2020-01-02"
echo date("D Y-m-d", strtotime("First Thursday " . "2020-01"));
// Even asking for the 1st Mon in Sep 2020, which is Labor Day returns the correct result: "Mon 2020-09-07"
echo date("D Y-m-d", strtotime("First Monday " . "2020-09"));
A: You should use "First Wednesday of 2020-01" instead (note the of).
Per the docs:
Observe the following remarks when the current day-of-week is the same
as the day-of-week used in the date/time string:
[...]
"ordinal dayname" does advance to another day. (Example "first wednesday july 23rd, 2008" means "2008-07-30").
[...]
"ordinal dayname 'of' " does not advance to another day. (Example: "first tuesday of july 2008" means "2008-07-01").
A: You could try this.
echo date("D Y-m-d", strtotime("First Wednesday of January 2020"));
// Wed 2020-01-01
| |
doc_23532354
|
A: The following code will click on the connect button when you are on a page, and the connect button is shown to the right of the profile picture.
driver.find_element_by_xpath('//div[@id="ember1355"]/button').click()
| |
doc_23532355
|
As you can see, heroku can't connect to my mongodb. I using mongodb atlas cluster and im pretty sure that my ip address in whitelist. Because i tried it in my local and it perfectly worked. How can i deal with this problem?
Besides all this, I may not be sure what the real problem is...
A:
heroku still cant connect to my mongodb atlas cluster but console starting to me show that results (i wrote this on my code take a look at the screenshoot)
| |
doc_23532356
|
Name (6)
Gender (6)
Phone Number (12) - Includes a space
Data.txt
DanielMale (07654) 521254
Lisa Female(16545) 654456
Sarah Female(54656) 4896546
I need to extract the name and gender data including any spaces if the data doesn't fit the data width.
The brackets for the phone number need to be ignored. (How do you ignore items in regular expressions?
I currently have the following regular expression, that pulls out the people's names. I thought I could simply add the bit on the white to make it pull out the Genders, but this doesn't work. Where am I going wrong?
/(?<name>.{6}+) (?<gender>.{6}+)/
I need the data to look like this at the end.
^ = space
Daniel
Male^^
07654 521254
Lisa^^
Female
16545 654456
Sarah^
Female
54656 4896546
A: This should catch all four fields:
/^(?<name>.{6})(?<gender>.{6})\((?<prefix>[^\)]+)\)\ (?<number>.+)/
*
*The first ^ means match from the start.
*{6}: match 6 times the pattern (the plus sign is redundant here)
*\( and \): match brackets (without escaping they would mean boundaries of a subpattern)
*[^\)]+ means "everything before the first closing bracket
| |
doc_23532357
|
Here's my function:
QString NWork::send(QVector<QString> &data) const{
//QNetworkAccessManager qnam = new QNetworkAccessManager();
QNetworkAccessManager qnam;
try{
QString json = NWork::to_JSON(data);
QByteArray json_data(json.toUtf8());
QNetworkRequest request;
request.setUrl(QUrl(NWork::connection));
request.setRawHeader("Content-Type", "application/json");
request.setRawHeader("Content-Length", json_data);
reply = qnam.post(request, json_data);
//reply = qnam.get(request);
int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
QString s(reply -> readAll());
qDebug()<<"code "<<status<<"Content "<<s;
//return QString::fromUtf8(response.data(),response.size());
}catch(std::exception x){
std::cout<<x.what()<<std::endl;
}
return "";
}
Making connections of the form suggested by many like
connect(qnam,SIGNAL(destroyed(QNetworkReply*)),this,SLOT(read(QNetworkReply*)));
have no effect on all. The request is reaching the PHP script and I know this by writing the request data in a file. It does so for every request. Echoing anything back even with a text/html header is not working.
Yes, I have tried my PHP script with a HTML AJAX request program and it works. It writes to file, and returns a response to the browser. Same code in both cases.
Here's my PHP code:
header("Access-Control-Allow-Origin: *");
$k = file_get_contents("php://input");
$file = "/file/path/log.k";
//echo $file;
$handle = fopen($file, "a+");
if($handle){
echo $k;
fwrite($handle, $k."\n");
fclose($handle);
}
header("Content-Type: text/html");
echo "line 22 ".$que;
exit(0);
I've checked my apache2 error logs and none are invoked. Why is it not working in my case?
A: I know this is almost a year old question but I just started teaching myself Qt and I recently ran into this issue as well and was bought to this page. So for those who are also stuck on this, here is how I solved it.
First change the connect from:
connect(qnam,SIGNAL(destroyed(QNetworkReply*)),this,SLOT(read(QNetworkReply*)));
to:
connect(reply, SIGNAL(finished()), this, SLOT(onReply()));
Then add it to your code after the post call like so:
reply = qnam.post(request, json_data);
connect(reply, SIGNAL(finished()), this, SLOT(onReply()));
The finished method is part of the QNetworkReply signals and is fired when the reply is finished. The method inside of SLOT is a Q_SLOT that you have to define in your hpp. Then move your code to your onReply method it would look similar to this:
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
QString response = reply->readAll();
if (reply)
{
if (reply->error() == QNetworkReply::NoError)
{
const int available = reply->bytesAvailable();
if (available > 0)
{
const QByteArray buffer = reply->readAll();
response = QString::fromUtf8(buffer);
// success = true;
}
}
else
{
response = tr("Error: %1 status: %2").arg(reply->errorString(), reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString());
}
qDebug()<<"code: "<<reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString()<<" response: "<<response;
reply->deleteLater();
}
sources: QNetworkReply, BlackBerry Sample App Maven source code
| |
doc_23532358
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<tt xmlns="http://www.w3.org/ns/ttml" xmlns:nttm="http://www.netflix.com/ns/ttml#metadata" xmlns:ttp="http://www.w3.org/ns/ttml#parameter" xmlns:tts="http://www.w3.org/ns/ttml#styling" ttp:timeBase="media" ttp:version="2" tts:extent="1280px 720px" xml:lang="zh-Hans">
<head>
<metadata nttm:movieId="81170257" nttm:packageId="1618461" nttm:schemaVersion="0" nttm:textType="SUBS" nttm:uuid="9c50201b-f11e-4665-9944-3bda07268f29"/>
</head>
<body>
<div begin="00:00:06.833" end="00:00:09.958" tts:extent="479px 51px" tts:origin="407px 597px">
<image src="1.png"/>
</div>
<div begin="00:00:26.083" end="00:00:29.250" tts:extent="431px 46px" tts:origin="431px 602px">
<image src="2.png"/>
</div>
<div begin="00:14:27.125" end="00:14:27.958" tts:extent="161px 46px" tts:origin="566px 602px">
<image src="165.png"/>
</div>
</body>
</tt>
Here is the code that I am running:
import lxml.etree as ET
tree = ET.parse("sample_ttml2.xml")
root = tree.getroot()
print(root.tag)
for div in root.iterfind(".//div"):
print(div)
for div in root.iterfind("div"):
print(div)
This outputs:
{http://www.w3.org/ns/ttml}tt
What I was expecting was the tt tag, without this namespace thing. When I attempt to iterate through, I get nothing, even when using an XPath. I think there is some problem with parsing it, but I have no idea why. Will I have to write my own parser?
| |
doc_23532359
|
SELECT SQL_NO_CACHE COUNT(id) FROM t;
1 row in set (29.86 sec)
I made some searches (e.g. "SELECT COUNT(*)" is slow, even with where clause) , and all the answers from the same issue are : my table is fragmented. But when I look at the informations, it does not like to be so fragmented :
> SELECT * FROM information_schema.tables WHERE TABLE_NAME="t" AND table_schema="s"\G;
DATA_LENGTH: 1726447616
INDEX_LENGTH: 3371892736
DATA_FREE: 8388608
This give me (using http://meinit.nl/optimize-only-fragmented-tables-mysql method) a very low fragmentation value:
8388608/(1726447616+3371892736) = 0.16%
The only solutions I have is to:
*
*Run an OPTIMIZE TABLE, but it will lock the table, and this is not acceptable for the moment in production mode (evaluated as 5 hours of lock)
*Run ALTER TABLE t ENGINE=InnoDB (from https://dba.stackexchange.com/questions/16341/how-do-you-remove-fragmentation-from-innodb-tables ), it only lock in read, but not acceptable for same reasons.
Do you have any other solutions before I get the production in maintenance mode ?
| |
doc_23532360
|
My contacts data goes like this:
CompanyX
Office 28 Nulla St. Mankato Mississippi 96522
CompanyX
Headquarters 92 Dictum Av. San Antonio MI 47096
CompanyX
Customer Service 48 Dolor. Av. Muskegon KY 12482
My vcard html goes like this:
<div class="vcard">
<strong class="org">CompanyX <span class="category">Office</span></strong>
<div class="adr">
<div class="street-address">28 Nulla St.</div>
<span class="postal-code">96522</span> <span class="locality">Mankato Mississippi</span>
</div>
| |
doc_23532361
|
I have an account with marketstack.com who provide the API. The URL request works well, but I would really love some help helping me display this on a page.
The URL is: https://api.marketstack.com/v1/tickers/LLOY.XLON/eod/latest?access_key=YOUR_API_KEY
(I've removed my API key).
This returns the following:
{"open":42.4,"high":43.575,"low":42.195,"close":43.395,"volume":139808684.0,"adj_high":null,"adj_low":null,"adj_close":43.395,"adj_open":null,"adj_volume":null,"split_factor":1.0,"dividend":0.0,"symbol":"LLOY.XLON","exchange":"XLON","date":"2022-06-24T00:00:00+0000"}
Marketstack have provided the following example jQuery code as a demo.
<script>
$.ajax({
url: 'https://api.marketstack.com/v1/tickers/aapl/eod',
data: {
access_key: 'YOUR_ACCESS_KEY'
},
dataType: 'json',
success: function(apiResponse) {
if (Array.isArray(apiResponse['data'])) {
apiResponse['data'].forEach(stockData => {
console.log(`Ticker ${stockData['symbol']}`,
`has a day high of ${stockData['high']},
`on ${stockData['date']}`);
});
}
}
});
</script>
How do I make the API call, get the 'close' value and get it as a var object so I can display in on my page?
Thank you for your help - I hope to help others with their code someday!
Updated code below:
<script>
$.ajax({
url: 'https://api.marketstack.com/v1/tickers/NWG.XLON/eod/latest',
data: {
access_key: 'b391c31dfc8a648bd50b9b0befc8bec7'},
dataType: 'json',
success: function(apiResponse)
{if (Array.isArray(apiResponse['data'])) {
apiResponse['data'].forEach(stockData => {
console.log(`Ticker ${stockData.symbol}, has a day high of ${stockData.high}, on ${stockData.date}`);
});
}
}
});
</script>
Removed the {if (Array.isArray block
<script>
$.ajax({
url: 'https://api.marketstack.com/v1/tickers/NWG.XLON/eod/latest',
data: {
access_key: 'b391c31dfc8a648bd50b9b0befc8bec7'},
dataType: 'json',
success: function(apiResponse)
});
</script>
A: Your logic is correct. The issue you have is that your syntax around the template literal is incorrect. You have used too many ` characters. It's clearer to see this if you keep the literal on a single line.
// mock response:
let apiResponse = {"pagination":{"limit":100,"offset":0,"count":1,"total":1},"data":[{"open":42.4,"high":43.575,"low":42.195,"close":43.395,"volume":139808684.0,"adj_high":null,"adj_low":null,"adj_close":43.395,"adj_open":null,"adj_volume":null,"split_factor":1.0,"dividend":0.0,"symbol":"LLOY.XLON","exchange":"XLON","date":"2022-06-24T00:00:00+0000"}]}
// inside AJAX succes handler:
if (Array.isArray(apiResponse['data'])) {
apiResponse['data'].forEach(stockData => {
console.log(`Ticker ${stockData.symbol}, has a day high of ${stockData.high}, on ${stockData.date}`);
});
}
| |
doc_23532362
|
I coudnt find any api for sale order export to magento.
Any help would be appreciated.
Thanks
| |
doc_23532363
|
def feeling():
...
def homesick():
...
def miss():
...
I'd like to put them in a list, shuffle them, and call each of them in succession:
import random
prompts = [feeling, homesick, miss]
My idea was to call each function like this:
random.shuffle(prompts)()
But this throws a
TypeError: 'NoneType' object is not callable
What am I doing wrong, and how can I get this to work?
A: You have a task to choose one of these functions at random. Here's a small demo does what you're doing, but correctly.
>>> f = [sum, max, min]
>>> random.shuffle(f)
>>> f.pop()([1, 2, 3]) # looks like we picked max. Alternatively, `f[0](...)`
3
Or, if it's only one function you want, there's no need to use random.shuffle at all. Use random.choice instead.
>>> random.choice(f)([1, 2, 3])
>>> 3
Why Your Error Occurs
random.shuffle performs an inplace shuffling, as the docs mention.
>>> y = list(range(10))
>>> random.shuffle(y)
>>> y
[6, 3, 4, 1, 5, 8, 9, 0, 7, 2]
So, when you call the function, expect nothing in return. In other words, expect None in return.
Further, calling () on an object invokes its __call__ method. Since NoneType objects do not have such a method, this errors out with TypeError. For an object to be callable, you'd need -
class Foo:
def __init__(self, x):
self.x = x
def __call__(self, y):
return self.x + y
>>> f = Foo(10)
>>> f(20)
30
As an exercise, try removing __call__ and rerunning the code. Calling f(20) should give you the same error.
| |
doc_23532364
|
my js hashmap is following:
self.userList["user1"] = {sms:true,email:false}
self.userList["user2"] = {sms:false,email:false}
self.userList["user3"] = {sms:true,email:true}
self.userList["user4"] = {sms:false,email:false}
and my view is following:
<tr ng-repeat="(user,value) in editRulesCtrl.userList">
<td>
{{user}}
</td>
<td>
<md-checkbox ng-model="{{value.sms}}"></md-checkbox>
</td>
<td >
<md-checkbox ng-model="{{value.email}}"></md-checkbox>
</td>
</tr>
Not sure what I am doing wrong, but table shows up empty.
A: This should work, only problem I can see is, ng-model needs variable name, it does failed if you try to pass {{}}(interpolation) to it.
<tr ng-repeat="(user,value) in editRulesCtrl.userList">
<td>
{{user}}
</td>
<td>
<md-checkbox ng-model="value.sms"></md-checkbox>
</td>
<td>
<md-checkbox ng-model="value.email"></md-checkbox>
</td>
</tr>
Plunker
A: <tr ng-repeat="(user,value) in userList">
| |
doc_23532365
|
when I use
r=requests,get('http//.....')
r.headers
output has
'WWW-Authenticate': 'Negotiate, NTLM', 'Server': 'Microsoft-IIS/7.5'
fields.
Please help
| |
doc_23532366
|
In my exercice, They need to add only images. But apparently they can add others files than images.
I don't see what they want because for me, it's work.
class UploadFileType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('file', FileType::class, [
'attr' => [
'accept' => "image/*"
]
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Upload::class
]);
}
class Upload
{
protected ?\SplFileInfo $file;
public function getFile(): ?\SplFileInfo
{
return $this->file;
}
class UploadController extends AbstractController
{
/**
* @Route("/upload", name="upload")
*/
public function upload(Request $request)
{
$upload = new Upload();
$form = $this->createForm(UploadFileType::class, $upload);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if ($upload->getFile()) {
// sauvegarde du fichier, pas a implementer
}
}
return $this->render('Exercices/upload.html.twig', [
'form' => $form->createView()
]);
}
}
public function setFile(?\SplFileInfo $file): void
{
$this->file = $file;
}
}
A: I think you also have to specify constraints on this
use Symfony\Component\Validator\Constraints\Image;
$builder->add('file', FileType::class, [
'attr' => [
'accept' => "image/*"
],
'constraints' => [
new Image()
]
]);
| |
doc_23532367
|
http://google.com
or
www.google.com
My Regular expression is:
[RegularExpression(@"^http(s?)\:\/\/[0-9a-zA-Z]([.\w][0-9a-zA-Z])(:(0-9))(\/?)([a-zA-Z0-9\\.\?\,\'\/\\\+&%\$#_])?$", ErrorMessage = "*")]
My code is working fine for http://google.com but not for www.google.com.
Does anyone have any suggestions?
A: Try this rule:
'#((https?://|www\.)([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)#'
| |
doc_23532368
|
Taking data class as an example:
register.py:
def register(key, module, module_dict):
"""Register and maintain the data classes
"""
if key in module_dict:
logger.warning(
'Key {} is already pre-defined, overwritten.'.format(key))
module_dict[key] = module
data_dict = {}
def register_data(key, module):
register(key, module, data_dict)
data.py:
from register import register_data
import ABCDEF
class MyData:
"""An alternative data class
"""
pass
def call_my_data(data_type):
if data_type == 'mydata'
return MyData
register_data('mydata', call_my_data)
builder.py:
import register
def get_data(type):
"""Obtain the corresponding data class
"""
for func in register.data_dict.values():
data = func(type)
if data is not None:
return data
main.py:
from data import MyData
from builder import get_data
if __name__ == '__main__':
data_type = 'mydata'
data = get_data(type=data_type)
My problem
In main.py, to register MyData class into register.data_dict before calling the function get_data, I need to import data.py in advance to execute register_data('mydata', call_my_data).
It's okay when the project is small, and all the data-related classes are placed according to some rules (e.g. all data-related class should be placed under the directory data) so that I can import them in advance.
However, this registeration mechanism means that all data-related classes will be imported, and I need to install all packages even if I won't use it actually. For example, when the indicator data_type in main.py is not mydata I still need to install ABCDEF package for the class MyData.
So is there any good idea to avoid importing all the packages?
A: Python's packaging tools come with a solution for this: entry points. There's even a tutorial about how to use entry points for plugins (which seems like what you're doing) (in conjunction with this Setuptools tutorial).
IOW, something like this (nb. untested), if you have a plugin package that has defined
[options.entry_points]
myapp.data_class =
someplugindata = my_plugin.data_classes:SomePluginData
in setup.cfg (or pypackage.toml or setup.py, with their respective syntaxes), you could register all of these plugin classes (here shown with an example with a locally registered class too).
from importlib.metadata import entry_points
data_class_registry = {}
def register(key):
def decorator(func):
data_class_registry[key] = func
return func
return decorator
@register("mydata")
class MyData:
...
def register_from_entrypoints():
for entrypoint in entry_points(group="myapp.data_class"):
register(entrypoint.name)(entrypoint.load())
def get_constructor(type):
return data_class_registry[type]
def main():
register_from_entrypoints()
get_constructor("mydata")(...)
get_constructor("someplugindata")(...)
| |
doc_23532369
|
No relay set (used as window.postMessage targetOrigin), cannot send cross-domain message
bd()cb=gapi.loaded_0 (line 117)
a = 3
c = "No relay set (used as w...nd cross-domain message"
ed()cb=gapi.loaded_0 (line 118)
a = "No relay set (used as w...nd cross-domain message"
xb()cb=gapi.loaded_0 (line 193)
a = ".."
c = "wistia_embed"
d = Object { s="_noop_echo", f="wistia_embed", c=1, more...}
Vb()cb=gapi.loaded_0 (line 210)
a = ".."
c = "_noop_echo"
d = a(a)
e = undefined
xg()
| |
doc_23532370
|
What I can not figure out is the signature to use for the IList. I tryed IList<Item<T>>, but because I do not (in the class where the IList is to be used) have a defination of T (which as I said varys anyhow) I can not use this signature. What is the best way to approach this requirement?
A: You need to add a non-generic interface to your Item<U> and make the collection out of those interfaces.
There is no way you can create a collection of IList<Item<T>> where T is some base type for a lot of different object types you want to place into the same list. This is co(ntra)-variance in place which specifically prohibits this.
So you need to instead add something common, that isn't generic, and make the list out of that. For instance, you might make Item<T> implement IItem, and create IList<IItem> instead.
That's the best you can do.
A: An IList is meant to hold a single type. To decide if something is a "single type" or not, you have to expand all the type parameters. Taking your example of an IList<Item<T>>, the T would have to be one and only one thing for a particular instance.
For example, you can pick Animal for T and then proceed to put Dog, Cat, and Bear instances in the IList. But you can't put arbitrary types there; they have to be able to be converted to the type you specify for T. And if your types are and not related in this way, you don't have any choice except to have a non-generic interface for your list. You could also consider defining an interface type for T that all your eligible items can conform to.
Once you've decided what T will be, you can then make your method generic:
public void PrintItems<T>(IList<Item<T>> list)
{
// ...
}
A: You can make your method generic, like:
public void DoSomethingWithTheList<T>(IList<Item<T>> theList)
{
//Do that something
}
A: Its a bit of a pain in .Net 3, because all the Item for different U are treated as independent types. To make it work you have to manually introduce an interface for this type:
interface IItem{}
class Item<U>:IItem {...}
and now you can:
IList<IItem> list = new IList<IItem>();
list.Add(new Item<string>());
list.Add(new Item<int>());
Alternatively you could stick to the non-generic list.
A: You could try this
class Item<U>
{
...
}
class Item : Item<object> {
...
}
....
IList<Item> itemList;
A: I think you just want an IList<Item<U>>. The key is that the T in the name of the generic type IList<T> is just a placeholder - it doesn't have any special meaning. You want a list of Item<U>s, so just make one.
Now, this will of course mean that the method / class that contains this IList will itself be generic in U, but that seems to be dictated by the terms of your question.
| |
doc_23532371
|
@Injectable()
export class LMSVideoResulful {
getVideos( enrolmentId : number ) :Observable<Array<Video>> {
var x = new Array<Video>();
//https://www.youtube.com/embed/MV0vLcY652c
x.push( new Video( "SQL 1", "https://www.youtube.com/embed/qMvDsarDdK0", "sdsdssdss" ));
x.push( new Video( "SQL 2", "https://www.youtube.com/embed/hVBALRtY8g0", "sdsdssdss" ));
x.push( new Video( "SQL 3", "https://www.youtube.com/embed/qMvDsarDdK0", "sssdssds" ));
x.push( new Video( "SQL 4", "https://www.youtube.com/embed/8Fo_KTDrBSU", "sdsdssdss" ));
return from([x]);
}
}
Here is the video model
export class Video{
constructor(
title : string,
videoUrl: string,
description : string
){}
}
In the component's constructor i call the service as
constructor( private _sanitizer: DomSanitizer, public myVideoService : LMSVideoResulful ){//https://www.youtube.com/watch?v=cm196HOdSzI
this.safeURL = this._sanitizer.bypassSecurityTrustResourceUrl("https://www.youtube.com/embed/MV0vLcY652c");
this.myVideoService.getVideos(1).subscribe( x => {
this.videoList = x;
console.log(JSON.stringify(x));
}, error => error)
}
Even there are four objects sent through the service the console.log() line shows array of four objects but the objects are empty
Why this happens and how do i fix this?
A: This happens because most likely you have not assigned the values in the constructor to the member variables of your class. Due to which you get the object printed out, but with no properties.
Make sure that the class Video is defined as below:
export class Video {
constructor(private seq: string, private url: string, private desc: string) { }
}
You need to declare the variables in the constructor with any access specifier. That then becomes a shorthand notation for assigning the values to them. Without them, as you can see the values will not be assigned.
| |
doc_23532372
|
myComponent1.html
<select id="BisMonat" class="form-control" [(ngModel)]="currentmonatbis">
<option [value]="01">Januar</option>
<option [value]="02">Februar</option>
<option [value]="03">März</option>
<option [value]="04">April</option>
<option [value]="05">Mai</option>
<option [value]="06">Juni</option>
<option [value]="07">Juli</option>
<option [value]="08">August</option>
<option [value]="09">September</option>
<option [value]="10">Oktober</option>
<option [value]="11">November</option>
<option [value]="12">Dezember</option>
</select>
myComponent1.ts:
export class myComponent1 implements OnInit
{
currentmonatbis: number = new Date().getMonth()+1;
but this is not working:
myComponent2.html:
<select id="Weltanschauung" class="form-control" [(ngModel)]="weltanschauung">
<option [value]="westlich">Westlich</option>
<option [value]="koscher">Koscher</option>
<option [value]="halal">Halāl</option>
<option [value]="vegetarisch">Vegetarisch</option>
<option [value]="vegan">Vegan</option>
</select>
myComponent2.ts:
export class myComponent2.ts implements OnInit
{
weltanschauung: string = "koscher";
like its basically the same ??
A: When you use [value]="westlich", The compiler is searching for a variable named "westlich" but there is no variable like this.
Use this:
<select id="Weltanschauung" class="form-control" [(ngModel)]="weltanschauung">
<option value="westlich">Westlich</option>
<option value="koscher">Koscher</option>
<option value="halal">Halāl</option>
<option value="vegetarisch">Vegetarisch</option>
<option value="vegan">Vegan</option>
</select>
I.E Use the values with the [,]
A:
<select id="Weltanschauung" class="form-control" [(ngModel)]="weltanschauung">
<option value="westlich">Westlich</option>
<option value="koscher">Koscher</option>
<option value="halal">Halāl</option>
<option value="vegetarisch">Vegetarisch</option>
<option value="vegan">Vegan</option>
</select>
| |
doc_23532373
|
here is the listview adapter code `
public class SubLessionAdapter extends ArrayAdapter<SubLessionDetail> {
Context context;
int resource, textViewResourceId;
List<SubLessionDetail> items;
List<SubLessionDetail> tempItems;
List<SubLessionDetail> suggestions;
private Dialog pinDialog;
private EditText popup_title, popup_review;
private TextView submit;
private RatingBar rating;
private String flag;
private VideoList videoList;
private CourseListMain myCourseListMain;
SubLessionAdapter.ViewHolder publicholder;
SharedPreferences pref;
SharedPreferences.Editor editor;
int listposition;
String topic_position,course_position,lession_position,item_id;
public SubLessionAdapter(Context dummyTopicList, ArrayList<SubLessionDetail> lessionLIstDetails, String flag,String course_position,String topic_position,String lession_position,String item_id) {
super(dummyTopicList, 0, lessionLIstDetails);
this.context = dummyTopicList;
this.items = lessionLIstDetails;
this.flag=flag;
this.course_position=course_position;
this.topic_position=topic_position;
this.lession_position=lession_position;
this.item_id=item_id;
pref = getContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
editor = pref.edit();
myCourseListMain = PrefUtils.getMyCourse(getContext());
listposition = pref.getInt("sublistpostion",0);
}
private class ViewHolder {
TextView title;
ImageView img_lock,download_green,download_gray,itemcheckded;
LinearLayout topic;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
SubLessionAdapter.ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_topics, parent, false);
holder = new SubLessionAdapter.ViewHolder();
holder.topic =(LinearLayout)convertView.findViewById(R.id.topic);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.img_lock = (ImageView) convertView.findViewById(R.id.img_lock);
holder.download_gray=(ImageView)convertView.findViewById(R.id.downlaod_gray_sublist);
holder.download_green=(ImageView)convertView.findViewById(R.id.download_green_sublist);
holder.itemcheckded =(ImageView)convertView.findViewById(R.id.itemchecked);
convertView.setTag(holder);
}
else
{
holder = (SubLessionAdapter.ViewHolder) convertView.getTag();
}
SubLessionDetail productItems = items.get(position);
holder.title.setText( productItems.getTitle());
if (productItems.getLocked().equals("1")) {holder.img_lock.setVisibility(View.GONE);} else {holder.img_lock.setVisibility(View.VISIBLE);}
if (flag.equals("my_course")){holder.img_lock.setVisibility(View.GONE);}else {holder.img_lock.setVisibility(View.VISIBLE);}
if(listposition==position){
holder.title.setTypeface(null, Typeface.BOLD);
holder.title.setTextColor(Color.parseColor("#4dd289"));
}else{
holder.title.setTypeface(null, Typeface.NORMAL);
holder.title.setTextColor(Color.parseColor("#000000"));
}
final ViewHolder finalHolder = holder;
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finalHolder.title.setTypeface(null, Typeface.BOLD);
finalHolder.title.setTextColor(Color.parseColor("#4dd289"));
// finalHolder.itemcheckded.setVisibility(View.VISIBLE);
switch (flag) {
case "my_course":
Intent intent = new Intent(getContext(), ContentTabActivity.class);
intent.putExtra("titlevalue",myCourseListMain.getCourseArrayList().get(Integer.parseInt(course_position)).getTopicListMain().getTopicDetailsArrayList().get(Integer.parseInt(topic_position)).getLessionArrayList().get(Integer.parseInt(lession_position)).getLessionLIstDetailArrayList().get(position).getTitle());
intent.putExtra("lession_id", myCourseListMain.getCourseArrayList().get(Integer.parseInt(course_position)).getTopicListMain().getTopicDetailsArrayList().get(Integer.parseInt(topic_position)).getLessionArrayList().get(Integer.parseInt(lession_position)).getLessionLIstDetailArrayList().get(position).getLession_id());
intent.putExtra("id", item_id);
intent.putExtra("lession_position", lession_position);
intent.putExtra("postion_current_selected_item",position+"");
intent.putExtra("course_position", course_position);
intent.putExtra("topic_position", topic_position);
editor.putString("sublession_has_1_item","no");
editor.putInt("sublistpostion",position);
editor.commit();
context.startActivity(intent);
break;
case "curriculam":
Toast.makeText(getContext(), "Content is Locked", Toast.LENGTH_SHORT).show();
break;
}
}
});
return convertView;
}
}
`
What happens now is when i click on the item, it changes textstyle and textcolor, but the previous item is still highlighted.
I want to highlight only one item at a time (clear the highlighting from the previous item).
below are some images of what's happening right now.
A: You should have a field in your data source to indicate whether the data is selected or not, and you should just change the field in your onclick listener instead of highlight the view. The specific actions of changing view should happen in getView() method and during this time you should set or restore text color and typeface depends on the field value.
You can do like this:
public class SubLessionAdapter extends ArrayAdapter<SubLessionDetail> {
Context context;
int resource, textViewResourceId;
List<SubLessionDetail> items;
List<SubLessionDetail> tempItems;
List<SubLessionDetail> suggestions;
private Dialog pinDialog;
private EditText popup_title, popup_review;
private TextView submit;
private RatingBar rating;
private String flag;
private VideoList videoList;
private CourseListMain myCourseListMain;
SubLessionAdapter.ViewHolder publicholder;
SharedPreferences pref;
SharedPreferences.Editor editor;
private SubLessionDetail preSelectedItem;
String topic_position,course_position,lession_position,item_id;
public SubLessionAdapter(Context dummyTopicList, ArrayList<SubLessionDetail> lessionLIstDetails, String flag,String course_position,String topic_position,String lession_position,String item_id) {
super(dummyTopicList, 0, lessionLIstDetails);
this.context = dummyTopicList;
this.items = lessionLIstDetails;
this.flag=flag;
this.course_position=course_position;
this.topic_position=topic_position;
this.lession_position=lession_position;
this.item_id=item_id;
pref = getContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
editor = pref.edit();
myCourseListMain = PrefUtils.getMyCourse(getContext());
listposition = pref.getInt("sublistpostion",0);
}
private class ViewHolder {
TextView title;
ImageView img_lock,download_green,download_gray,itemcheckded;
LinearLayout topic;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
SubLessionAdapter.ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_topics, parent, false);
holder = new SubLessionAdapter.ViewHolder();
holder.topic =(LinearLayout)convertView.findViewById(R.id.topic);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.img_lock = (ImageView) convertView.findViewById(R.id.img_lock);
holder.download_gray=(ImageView)convertView.findViewById(R.id.downlaod_gray_sublist);
holder.download_green=(ImageView)convertView.findViewById(R.id.download_green_sublist);
holder.itemcheckded =(ImageView)convertView.findViewById(R.id.itemchecked);
convertView.setTag(holder);
}
else
{
holder = (SubLessionAdapter.ViewHolder) convertView.getTag();
}
final SubLessionDetail productItems = items.get(position);
holder.title.setText( productItems.getTitle());
if (productItems.getLocked().equals("1")) {holder.img_lock.setVisibility(View.GONE);} else {holder.img_lock.setVisibility(View.VISIBLE);}
if (flag.equals("my_course")){holder.img_lock.setVisibility(View.GONE);}else {holder.img_lock.setVisibility(View.VISIBLE);}
if (productItems.isSelected()) {
holder.title.setTypeface(null, Typeface.BOLD);
holder.title.setTextColor(Color.parseColor("#4dd289"));
} else {
holder.title.setTypeface(null, Typeface.NORMAL);
holder.title.setTextColor(Color.parseColor("#000000"));
}
final ViewHolder finalHolder = holder;
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (preSelectedItem != null) {
preSelectedItem.setSelected(false);
}
productItems.setSelected(true);
preSelectedItem = productItems;
notifyDataSetChanged();
switch (flag) {
case "my_course":
Intent intent = new Intent(getContext(), ContentTabActivity.class);
intent.putExtra("titlevalue",myCourseListMain.getCourseArrayList().get(Integer.parseInt(course_position)).getTopicListMain().getTopicDetailsArrayList().get(Integer.parseInt(topic_position)).getLessionArrayList().get(Integer.parseInt(lession_position)).getLessionLIstDetailArrayList().get(position).getTitle());
intent.putExtra("lession_id", myCourseListMain.getCourseArrayList().get(Integer.parseInt(course_position)).getTopicListMain().getTopicDetailsArrayList().get(Integer.parseInt(topic_position)).getLessionArrayList().get(Integer.parseInt(lession_position)).getLessionLIstDetailArrayList().get(position).getLession_id());
intent.putExtra("id", item_id);
intent.putExtra("lession_position", lession_position);
intent.putExtra("postion_current_selected_item",position+"");
intent.putExtra("course_position", course_position);
intent.putExtra("topic_position", topic_position);
editor.putString("sublession_has_1_item","no");
editor.putInt("sublistpostion",position);
editor.commit();
context.startActivity(intent);
break;
case "curriculam":
Toast.makeText(getContext(), "Content is Locked", Toast.LENGTH_SHORT).show();
break;
}
}
});
return convertView;
}
You don't show your SubLessionDetail class, and you also should add a boolean field named selected in it.
A: What you have to do is save the click position of the item then check whether the clicked item's text color is cyan or not. If yes then do what you want if not then clear the list, call notify it and then add the complete list again. After notifying the addition set the text color at the position we have saved earlier.
List<Bean> list;
List<Bean> tempList;
tempList = list;
int pos;
//Clean List
public void cleanList() {
int size = this.list.size();
this.list.clear();
notifyItemRangeRemoved(0, size);
list.addAll(tempList);
notifyDataSetChanged();
}
Now the click listener for the textView
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pos = = getAdapterPosition();
if (textView.getTextColors().equals(<ColorYouDesire>)){
Log.d(TAG,"Item Clicked Again");
}else{
cleanList();
textView.setTextColor(<ColorYouDesire>);
notifyItemChanged(pos);
}
}
});
Try this and let me know what happened.
| |
doc_23532374
|
Everything working fine except loading the images..The images are served in a separate webserver...
Here is the code -
slicedata.forEach(function(e,i,a){
var obj = e;
$("<div id = product" + i + " class = product-cards </div>").appendTo('#product-container')
$("<div id = product" + i + "left class = product-cards-left> <a href={% static 'product-images/" + obj.image_caption + "' %} >Image #1</a> </div>").appendTo('#product' + i)
$("<div id = product" + i + "right class = product-cards-right </div>").appendTo('#product' + i )
$("<label><b> NAME: <b></label> <label>" + obj.name + "</label><br>").appendTo('#product' + i +"right" )
$("<label><b> Price: <b></label> <label>" + '$' + obj.price + "</label><br>").appendTo('#product' + i +"right" )
$("<label><b> Old Price: <b></label> <label>" + '$' + obj.old_price + "</label><br>").appendTo('#product' + i +"right" )
$("<label><b> Author Name: <b></label> <label>" + obj.author_name + "</label>").appendTo('#product' + i +"right" )
})
Problem:-
The images need to be loaded from a separate place and when I use the below code
the final substitution looks like this -
<a href="/online_static/product-images/%22%20%2B%20obj.image_caption%20%2B%20%22">Image #1</a>
$("<div id = product" + i + "left class = product-cards-left> <a href={% static 'product-images/" + obj.image_caption + "' %} >Image #1</a>
How do I fix this issue?
A: If your images are uploaded correct in the other place you can create a global variable on your settings file named "IMAGES_SERVER" and use this variable into your template file.
A: static is a reverence for Django to the local static folder. I would recommend using Lara advice and set a global variable.
| |
doc_23532375
|
I am creating an object but somehow it dosen't give result in console.
here is my code.
var car=new object();
car.name="Mercedes Benz";
car.speed=220;
car.showNameAndSpeed=function(){
console.log("The name of the car is " + car.name + " and the topspeed is " + car.speed());
};
car.showNameAndSpeed();
It says object is not defined. What am i doing wrong??Thanks.
A: Your issue is that object needs to be capitalized - object isn't a thing in JavaScript, but Object is.
You want:
var car=new Object();
As w3schools says, JavaScript identifiers are case sensitive:
All JavaScript identifiers are case sensitive.
The variables lastName and lastname, are two different variables.
So object and Object are two different things, and you want Object - almost everything in JS starts as an Object.
More on Object here.
Also, as ozil pointed out, you should change car.speed() to simply car.speed. You've previously set car.speed to 220, so it's not a function. car.speed() tries to treat it as a function, which will cause issues.
So, in all, this code is what you want:
var car=new Object();
car.name="Mercedes Benz";
car.speed=220;
car.showNameAndSpeed=function(){
console.log("The name of the car is " + car.name + " and the topspeed is " + car.speed);
};
car.showNameAndSpeed();
A: A better way to create an object, in my opinion:
var car = {
name: "Mercedes Benz",
speed: 220,
showNameAndSpeed: function(){
var self = this;
console.log("The name of the car is " + self.name + " and the topspeed is " + self.speed);
}
}
car.showNameAndSpeed(); //Output: The name of the car is Mercedes Benz and the topspeed is 220
Fiddle
A: object needs to be capitalized and car.speed() needs to be car.speed as speed is not a function
| |
doc_23532376
|
Project A : class library for MVC
Project B : MVC website (main)
Project C : MVC website (area only)
C is deployed on B as an Area and that work really well. B has a reference to both A and C. C has a reference to A.
In class library A I defined the following attribute (error checking removed):
[AttributeUsage(AttributeTargets.Method)]
public class MyAttribute : Attribute {
public string Name = "";
public MyAttribute(string s)
{
Name = s;
}
}
Then in project C (same as in project B) I have some classes where SOME methods are decorated with my custom attribute:
public class SomeController : Controller, ISomethingSpecial
{
[MyAttribute("test")]
public ActionResult Index() {
return View();
}
}
The custom attribute is applied to the action methods as indicated by the attribute usage constraint.
For the sake of testing I put this code in one of the action methods of the controller:
IEnumerable<System.Type> all =
System.Web.Compilation.BuildManager.GetReferencedAssemblies().Cast<System.Reflection.Assembly>().SelectMany(a => a.GetTypes()).Where(type => typeof(ISomethingSpecial).IsAssignableFrom(type)).ToList();
foreach (Type t in all) {
if (!t.Equals(typeof(ISomethingSpecial))) {
MyAttribute[] sea = (MyAttribute[])Attribute.GetCustomAttributes(t, typeof(MyAttribute));
}
}
When I debug the code I get to the iteration where the examined type t is SomeController which has some methods decorated with my custom attribute. But I see that the returned list of GetCustomAttributes has zero elements!
Before somebody asks what I basically want to achieve is obtain a list of assemblies of the web application that implement the ISomethingSpecial interface and from that list of candidates I want to extract the names of the methods (MVC action methods) that are decorated with my custom attribute MyAttribute.
A: Your attribute in defined on method not on class. But in your code you request custom attributes from your class. If you need to get attributes from methods you should iterate over each method using
Type.GetMethods
https://msdn.microsoft.com/en-us/library/4d848zkb(v=vs.110).aspx
and for each method request custom attributes like you do now for your classes.
| |
doc_23532377
|
import yum
yb = yum.YumBase()
yb.disablePlugins()
yb.setCacheDir()
repos = yb.repos.listEnabled()
destdir="/tmp/repo"
arch = "x86_64"
repoid="Myrepo"
baseurl="http://mirror.yandex.ru/centos/6.6/os/%s" % (arch)
imgurl="%s/images/install.img" % (baseurl)
repopath="Myrepo"
cachedir = "/tmp" #yum.misc.getCacheDir()
yb.repos.setCacheDir(cachedir)
newrepo = yum.yumRepo.YumRepository(repoid)
newrepo.name = repopath
newrepo.baseurl = baseurl
newrepo.mirrorlist = None
newrepo.basecachedir = cachedir
newrepo.metadata_expire = 0
newrepo.timestamp_check = False
yb.repos.add(newrepo)
yb.repos.enableRepo(newrepo.id)
yb.repos.doSetup()
yb.cleanRpmDB()
XM = yb.selectGroup(grpid='base')
print XM
Output :
[]
Warning: Group base does not have any packages to install.
Process finished with exit code 0
| |
doc_23532378
|
I saw this example with Setup.hs, however on my scaffolded project I don't have it, so my question where is the right place to put the code to run those bash commands.
A: If you're using the default Yesod scaffolding (generated by stack tool), then it indeed doesn't contain Setup.hs (which is a bit weird, as their own guide - https://github.com/commercialhaskell/stack/blob/master/doc/GUIDE.md - recommends having it as a good practice)
Setup.hs should be located in main project directory (same where stack.yml and yourproject.cabal are located) and content should be roughly the same as in your included example (defaultMainWithHooks is the key part).
Details of hooks usage are specified in https://www.haskell.org/cabal/users-guide/developing-packages.html and in cabal spec: https://hackage.haskell.org/package/Cabal-1.24.0.0/docs/Distribution-Simple.html
BTW, for now stack doesn't support pre-build hooks on its own (for details see: https://github.com/commercialhaskell/stack/issues/503), so you have to stick to ones provided by cabal - that's where Setup.hs comes from.
| |
doc_23532379
|
So I have an object of key-value pairs making some options:
<select v-model="myObject.myProperty">
<option v-for="v, k in myOptions" :key="k" :value="k">{{v}}</option>
</select>
{{myObject.myProperty}} //this line prints out the correct value
But the options are not showing as selected. The value is updated for myObject.myProperty and it returns what I expect. I suspect that behind the scenes, it's correctly assigning k to my custom object, but that because it returns a different string value, Vue can't inherently figure out which option to mark 'selected'.
Manually adding :selected does not help:
<option v-for="v, k in myOptions" :key="k" :value="k" :selected="v === myObject.myProperty">{{v}}</option>
I also tried to manually bind the select instead of using the v-model attribute, also no:
<select :value="myObject.myProperty" @input="myObject.myProperty = $event.target.value"
Is there an alternative way to wire up a select/option situation? If not, building a custom component with faux-select functionality is my next step.
For clarity, myOptions is a key-value like this
{
0 : 'Option 1',
1 : 'Option 2',
}
But myObject has special setters that take and remember the key, then also a special getter than returns the value from myOptions.
So then:
myObject.myProperty = 0;
console.log(myObject.myProperty) //logs 'Option 1'
When when I set the value to the key (k) I get back the corresponding value when the option is selected and the value of 'myObject.myProperty' is what I expect. Example: I pick 'Option 1' from the drop-down, which has a value of 0 derived from the key k.
However, although myObject.myProperty has the value I want, I can't get Vue to display the the actual html option as selected, probably because the value returned by myObject.myProperty is 'Option 1' and not 0
A: Alright, the actual answer:
<select @input="myObject.myProperty = $event.target.value">
<option v-for="v, k in myOptions" :selected="myObject.myProperty === v" :key="k" :value="k">{{v}}</option>
</select>
v-model won't work here because it simply doesn't care that you've manually applied selected: it will always try to match the option value to the the v-model property value. As this object takes one value with a setter and returns another with a getter, these will never align.
Instead, manually assign the value to the object with @input and match the value from the getter to the value in the options for selected.
A: Not sure I understand your question properly or not. Hence, adding my input on your requirement below.
As myObject.myProperty returning the value you passed in the select and as per your code you are passing the index as value.
Hence, while comparing in :selected both LHS and RHS should contain index of the item you passed.
Working Demo :
const app = new Vue({
el: '#app',
data() {
return {
myOptions: [{
id: 1,
name: 'alpha'
}, {
id: 2,
name: 'beta'
}, {
id: 3,
name: 'gama'
}],
myObject: {
myProperty: ''
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<select v-model="myObject.myProperty">
<option v-for="(item, index) in myOptions" :selected="myObject.myProperty === item.id" :key="item.id" :value="item.id">{{item.name}}</option>
</select>
{{myObject.myProperty}}
</div>
A: UPDATE Based on the newly provided information.
In Template:
<select v-model="selectedOption">
<option v-for="(v, k) in options" :key="k" :value="k">
{{ v }}
</option>
</select>
In JS
data() {
return {
selectedOption: null,
options: {
0: 'Option 1',
1: 'Option 2',
},
};
}
By setting selectedOption with the key of options will correctly display the selected option.
Here is a link to a working example using your data structure. It contains two selects both using the same object for its data source. One with a default selection. the other without.
https://stackblitz.com/edit/vue-efekym?file=src/App.vue
THIS IS NOW OUTDATED BASED ON THE LATEST INFO
Based on the logic in your further examples I think the problem is within conflating your k & v variables in your loop. Although it is hard to tell because there isn't any sample data or a complete isolated component outlying the behavior.
However in your later examples you have:
<option v-for="v, k in myOptions" :key="k" :value="k" :selected="v === myObject.myProperty">{{v}}</option>
I am inferring that you believe that myObject.myProperty is holding the value from variable v, when in fact you are setting the value as variable k as witnessed in :value="k"
By correcting this I believe your issue will be resolved, you also noted a int to string conversion. depending on how/where this is happening this could also contribute to your headaches because this will never equate to true. '1231' === 1231
| |
doc_23532380
|
these are the links that I want to click
<div id="secondlevel">
<ul>
<li><span><a href="NewReleases.aspx?catalogueCode=cat1">New Releases</a></span></li>
<li><span><a href="BestSellers.aspx">Best Sellers</a></span></li>
</ul>
This is my query which I feel should work but doesn't.
Advice perhaps.
$(document).ready(function () {
$("li").on("click", function () {
$(this).siblings("li").css("fontWeight", "normal");
$(this).css("fontWeight", "bold");
window.alert("The link was clicked");
});
});
A: Use e.preventDefault() to prevent default action:
$("li").on("click", function (e) {
e.preventDefault();
$(this).siblings("li").css("fontWeight", "normal");
$(this).css("fontWeight", "bold");
window.alert("The link was clicked");
});
Demo
A: Try this:
$(document).ready(function () {
$("li").on("click", function () {
$(this).siblings("li").find('a').css("font-weight", "normal");
$(this).find('a').css("font-weight", "bold");
});
});
| |
doc_23532381
|
The class is supposed to plot a graph which I intend to display using the fragment. This is returned in an intent.
Here is my Fragment class:
public class NewFragment extends Fragment {
public static final NewFragment newInstance() {
NewFragment f = new NewFragment();
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.newfragment, container, false);
PerformanceGraph line = new PerformanceGraph();
Intent intent = line.getIntent(getApplicationContext());
startActivity(intent);
return v;
}
}
And here is my PerformanceGraph class:
public class PerformanceGraph {
public Intent getIntent(Context context) {
int x[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
int y[] = { 1, 4, 9, 16, 25, 36, 38, 39, 38, 37, 36, 32, 31, 30, 30 };
int z[] = { 3, 4, 6, 7, 4, 3, 2, 2, 4, 3, 5, 5, 4, 6, 7 };
String xaxis[] = { "jan", "feb", "mar", "apr", "may", "jun", "jul",
"aug", "sept", "oct", "nov", "dec", "jan", "feb", "mar" };
TimeSeries series = new TimeSeries("line1");
TimeSeries series2 = new TimeSeries("line2");
for (int i = 0; i < x.length; i++) {
series.add(x[i], y[i]);
series2.add(x[i], z[i]);
}
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(series);
dataset.addSeries(series2);
XYSeriesRenderer renderer = new XYSeriesRenderer();
renderer.setColor(Color.BLUE);
renderer.setPointStyle(PointStyle.SQUARE);
renderer.setFillPoints(true);
XYSeriesRenderer renderer2 = new XYSeriesRenderer();
renderer2.setColor(Color.DKGRAY);
renderer2.setPointStyle(PointStyle.CIRCLE);
renderer2.setFillPoints(false);
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
mRenderer.addSeriesRenderer(renderer);
mRenderer.addSeriesRenderer(renderer2);
mRenderer.setChartTitle("haha");
mRenderer.setXLabels(0);
mRenderer.setXTitle("Duration");
mRenderer.setYTitle("Price (ksh)");
mRenderer.setApplyBackgroundColor(true);
mRenderer.setAxisTitleTextSize(15);
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(12);
mRenderer.setPointSize(2f);
mRenderer.setAxesColor(Color.BLACK);
mRenderer.setYLabelsAlign(Align.RIGHT);
mRenderer.setYLabelsVerticalPadding(2);
mRenderer.setShowGridY(true);
mRenderer.setGridColor(Color.GRAY);
mRenderer.setLabelsColor(Color.parseColor("#5f5f5f"));
mRenderer.setBackgroundColor(Color.parseColor("#F5F5F5"));
mRenderer.setMarginsColor(Color.parseColor("#F5F5F5"));
mRenderer.setPanEnabled(false, false);
mRenderer.setZoomEnabled(false, false);
for (int i = 0; i < x.length; i++) {
mRenderer.addXTextLabel(x[i], xaxis[i]);
}
Intent intent = ChartFactory.getLineChartIntent(context, dataset,
mRenderer, "Line graph title");
return intent;
}
}
Problem is, in the fragment class am getting errors trying to call getIntent(). The application context has to be supplied in the argument.
How can I achieve this? Trying getIntent(getApplicationContext()) or getIntent(this) doesn't solve the problem.
A: In your xml for fragment place the linear layout where you want and customize.
<LinearLayout
android:layout_width="wrap_content"
android:id="@+id/chart"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginLeft="22dp"
android:layout_marginTop="23dp"
android:orientation="vertical" >
</LinearLayout>
Then
public View displayLineChart()
{
int x[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
int y[] = { 1, 4, 9, 16, 25, 36, 38, 39, 38, 37, 36, 32, 31, 30, 30 };
int z[] = { 3, 4, 6, 7, 4, 3, 2, 2, 4, 3, 5, 5, 4, 6, 7 };
String xaxis[] = { "jan", "feb", "mar", "apr", "may", "jun", "jul",
"aug", "sept", "oct", "nov", "dec", "jan", "feb", "mar" };
TimeSeries series = new TimeSeries("line1");
TimeSeries series2 = new TimeSeries("line2");
for (int i = 0; i < x.length; i++) {
series.add(x[i], y[i]);
series2.add(x[i], z[i]);
}
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(series);
dataset.addSeries(series2);
XYSeriesRenderer renderer = new XYSeriesRenderer();
renderer.setColor(Color.BLUE);
renderer.setPointStyle(PointStyle.SQUARE);
renderer.setFillPoints(true);
XYSeriesRenderer renderer2 = new XYSeriesRenderer();
renderer2.setColor(Color.DKGRAY);
renderer2.setPointStyle(PointStyle.CIRCLE);
renderer2.setFillPoints(false);
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
mRenderer.addSeriesRenderer(renderer);
mRenderer.addSeriesRenderer(renderer2);
mRenderer.setChartTitle("haha");
mRenderer.setXLabels(0);
mRenderer.setXTitle("Duration");
mRenderer.setYTitle("Price (ksh)");
mRenderer.setApplyBackgroundColor(true);
mRenderer.setAxisTitleTextSize(15);
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(12);
mRenderer.setPointSize(2f);
mRenderer.setAxesColor(Color.BLACK);
mRenderer.setYLabelsAlign(Align.RIGHT);
// mRenderer.setYLabelsVerticalPadding(2);
mRenderer.setShowGridY(true);
mRenderer.setGridColor(Color.GRAY);
mRenderer.setLabelsColor(Color.parseColor("#5f5f5f"));
mRenderer.setBackgroundColor(Color.parseColor("#F5F5F5"));
mRenderer.setMarginsColor(Color.parseColor("#F5F5F5"));
mRenderer.setPanEnabled(false, false);
mRenderer.setZoomEnabled(false, false);
for (int i = 0; i < x.length; i++) {
mRenderer.addXTextLabel(x[i], xaxis[i]);
}
mChartView = ChartFactory.getLineChartView(getActivity(), dataset,
mRenderer);
return mChartView;
}
Then in onCreateView
View v = inflater.inflate(R.layout.newfragment, container, false);
LinearLayout layout = (LinearLayout) view.findViewById(R.id.chart);
layout.addView(displayLineChart());
snapshot
| |
doc_23532382
|
@beach-font-color: #3d3d3d;
@ocean-font-color: #d3d3d3;
@theme: "beach";
@symbol: "@";
@currentTheme-font-color: ~"@{symbol}@{theme}-font-color";
In the stylesheet:
body { color: @currentTheme-font-color; }
The generated css produces:
body { color: @beach-font-color; }
instead of:
body { color: #3d3d3d; }
One thing I thought might be required is:
@font: ~"@{symbol}@{theme}-font-color";
@currentTheme-font-color: ~"@{font}";
But this just produces the same results.
Why does the Less compiler use the string literal instead of the variable value?
How would I be able to get the value of the variable, going along these lines?
A: (I cannot skip this to not provide an alt. answer since such "namespace emulation via variable name concatenation" is my most favourite bloody wrong Less pattern (unfortunately it is also the most widely spread one :().
Instead of emulating namespaces via using looong global variable names (doh#1 in most of programming languages and paradigms global variables are considered harmful since 1970's... :) and then assembling those variable names via the ugly concatenation syntax (doh#2, ~"@{@{@foo}}-@{bar}-seriously}?"), one can use normal namespaces with much more clean syntax:
.theme(beach) {
@font-color: #3d3d3d;
// other beach variables
}
.theme(ocean) {
@font-color: #d3d3d3;
// other ocean variables
}
@theme: beach;
.theme(@theme);
body {color: @font-color}
This is just one of possible variations (for more examples see:
*
*Dynamic Variable Names with Less -> gist
*How to thematize in lesscss
*etc.)
| |
doc_23532383
|
However, when I try to sign the logout Request, that is not working.
I notice that If I try to sign the request and then I check signature they create in their site, is different.
So the question is how is the signature for Saml Logout Request signed.
A: *
*First you need to generate your own cert/public key for instance using site https://www.samltool.com/self_signed_certs.php
*If you are not using any libray you need to sign the request by yourself example code below in Java
*To check SAML request/parameters you can use SAML tracer addon on firefox https://addons.mozilla.org/en-US/firefox/addon/saml-tracer/
*To validate request signature you can use online tool https://www.samltool.com/validate_logout_req.php
Example how to sign the request can be checked here: https://github.com/jrowny/java-saml
| |
doc_23532384
|
user_id video_interest
1 [{"category":"a","score":1},{"category":"b","score":2},{"category":"c","score":3},{"category":"d","score":4}]
2 [{"category":"e","score":1},{"category":"f","score":2},{"category":"g","score":-3}]
The output is
user_id video_interest_top3
1 [{"category":"d","score":4},{"category":"c","score":3},{"category":"b","score":2}]
2 [{"category":"f","score":2},{"category":"e","score":1}]
I need to filter score>0, and then select each user_id's top3 video_interest in descending order of score
A: Explode JSON array, extract score, calculate max score per user (if necessary to order final output by score desc) and row_number by score to filter top 3, collect array again and concatenate it to STRING if necessary. See comments in the code. I added sorting arrays and the whole output, because it was initially not clear what exactly should be sorted: arrays or final output, remove max_score sorting if you do not need it.
Demo:
with mytable as (
select stack(2,
1,'[{"category":"a","score":1},{"category":"b","score":2},{"category":"c","score":3},{"category":"d","score":4}]',
2,'[{"category":"e","score":1},{"category":"f","score":2},{"category":"g","score":-3}]'
) as (user_id,video_interest)
)
select --collect array and convert to JSON string
user_id, max_score, concat('[',concat_ws(',',collect_list(category_score)),']') as video_interest
from
(
select user_id, category_score, max_score, score
from
(
select --extract score, filter and sort
user_id, vi.category_score, get_json_object(vi.category_score, '$.score') as score,
row_number() over(partition by user_id order by get_json_object(vi.category_score, '$.score') desc) rn,
max(get_json_object(vi.category_score, '$.score')) over (partition by user_id) max_score
from
(--prepare for exploding array
select user_id, regexp_replace(regexp_replace(video_interest,'\\[|\\]',''), --remove []
'\\},\\{', '},,,{') as video_interest --replace , between array elements with ,,, to split
from mytable
)s
--split and explode
lateral view outer explode(split(video_interest,',,,')) vi as category_score
where get_json_object(vi.category_score, '$.score')>0
)s
where rn<=3 --filter top 3
distribute by user_id sort by score desc --Sort collection, remove if not necessary
)s
group by user_id, max_score
order by max_score desc --Sorting users by max_score desc, remove if not necessary
Result:
user_id max_score video_interest
1 4 [{"category":"d","score":4},{"category":"c","score":3},{"category":"b","score":2}]
2 2 [{"category":"f","score":2},{"category":"e","score":1}]
A: First, I explode video_interest and make its category and score a single field.
Second, I use row_number() function to partition by user_id order by score(descending), then make each line be marked with their order in the group and filter order<=3
In the end, I use collect_list() to simply collect them as a list, because they were ordered when using row_number
select user_id,
collect_list(pos) as first_video_interest_top3
from (
select user_id,
category,
score,
pos,
row_number() over(
partition by
user_id
order by
score desc
) rNum
from (
select user_id,
pos.category,
pos.score,
pos
from myData
lateral view explode(video_interest) e as pos
) t1
where score > 0
) t2
where rNum <= 3
group by
user_id
| |
doc_23532385
|
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT(firstName BEGINSWITH[c] %@)",arrIndex]; //where arrIndex is the array of alphabetical characeters.
NSArray *arrContacts = [arrayTotalContacts filteredArrayUsingPredicate:predicate];
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do a substring operation with something that isn't a string (lhs = iPhone rhs = (
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z
))'
arrayTotalContacts has the below data:
(
{
firstName = iPhone;
lastName = "";
},
{
firstName = Madhu;
lastName = "";
},
{
firstName = "Swa";
lastName = "";
},
{
firstName = TechV;
lastName = "";
},
{
firstName = Vedika;
lastName = Vt;
}
)
A: You can use regular expression with a Core Data predicate:
[NSPredicate predicateWithFormat:@"NOT (firstName MATCHES %@)", @"^[A-Za-z].*"]
where ^[A-Za-z].* is a regex for all strings that do start with A-Z or a-z.
To make it work with letters from foreign languages as well (e.g. "Ä"), use
the Unicode property name:
[NSPredicate predicateWithFormat:@"NOT(firstName MATCHES %@)", @"^\\p{Letter}.*"]
Here ^\\p{Letter}.* is a regex for all strings that start with a letter.
But if this is for a table view, you might better use a fetched results controller
and its sectionNameKeyPath parameter. See for example here:
*
*NSFetchedResultsController with sections created by first letter of a string
for some examples how to group a table view according to the initial letter. It should be
possible to modify the code to group all names that do not start with a letter into
a separate group.
A: Try this out,
NSArray * arrContacts = [arrayTotalContacts valueForKeyPath:@"firstName"];
Hope it helps :)
| |
doc_23532386
|
Appreciate your answers.
| |
doc_23532387
|
After clicking OK the project starts and runs without any issue. However the pop-up keeps nagging me every time I start my solution.
*
*How can I stop showing it?
*What is it trying to tell me anyway?
A: I had some variables in my watch window that was causing this error popup to happen. Just remove them from your watch window and the error popup should no longer display.
A: There seems to be two possible solutions to this, that at least worked for me being on Visual Studio 2019.
Solution
Goto Tools => Options => Debugging => General and then either enable Use Managed Compatibility Mode (thanks to Nan Yu) or disable Enable property evaluation and other implicit function calls.
The second solution faces the drawback that when being in break mode, we have to manually hit refresh on the locals window to see a variables content.
Background
The message is telling us, that our system state may get changed when being in break mode due to implicit property evalution.
By default, we tell Visual Studio debugger to try and evaluate properties implicitly.
This of course requires running code while we are braked, and not only display memory content.
Running code, might potentially change the state of the system, which is not always what we want.
For example, I might be increasing a counter every time the property is accessed,
which means that when the debugger will try to evaluate the property, my code will run,
the counter will be incremented, and my system state is changed, even though I am braked.
https://blogs.msdn.microsoft.com/eliofek/2012/12/12/why-do-we-get-the-function-evaluation-requires-all-threads-to-run/
| |
doc_23532388
|
I have some set of header files residing remotely(not in local_path). But i have included it under includes tree. I am trying to include this header file in a c file present in jni/sample.c Now the problem is that these header files are not recognized. (It shows "unresolved inclusion..etc"). Is this anything related to android.mk file? I did not mention remote header files path anywhere in android.mk file
A: you have to add the path to these header files to LOCAL_C_INCLUDES variable you can set inside Android.mk (as you rightly guessed):
LOCAL_C_INCLUDES += ./path/to/your/includes
| |
doc_23532389
|
TypeError: admin.messaging.send is not a function
at sendNotification (/workspace/index.js:220:8)
at exports.onCreateActivityFeedItem.functions.firestore.document.onCreate (/workspace/index.js:176:5)
at process._tickCallback (internal/process/next_tick.js:68:7)
I already tried npm install firebase-admin@latest but it didn't fix the issue. This is the function I created in index.js
exports.onCreateActivityFeedItem = functions.firestore
.document('/feed/{userId}/feedItems/{activityFeedItem}')
.onCreate(async (snapshot, context) => {
console.log('Activity feed item created', snapshot.data());
// 1) Get user connected to the feed
const userId = context.params.userId;
const userRef = admin.firestore().doc(`users/${userId}`);
const doc = await userRef.get();
// 2) Once we have user, check if they have a notification token;
//send notification if they have token
const androidNotificationToken = doc.data().androidNotificationToken;
const createdActivityFeedItem = snapshot.data();
if (androidNotificationToken) {
sendNotification(androidNotificationToken, createdActivityFeedItem);
} else {
console.log('No token for user, cannot send notification');
}
function sendNotification(androidNotificationToken, activityFeedItem){
let body;
// 3) switch body based on activity feed item type
switch (activityFeedItem.type) {
case 'comment':
body = `${activityFeedItem.username} replied:
${activityFeedItem.commentData}`;
break;
case 'like':
body = `${activityFeedItem.username} liked your post`;
break;
case 'follow':
body = `${activityFeedItem.username} started following you`;
break;
case 'request':
body = `${activityFeedItem.username} needs a tutorial in ${activityFeedItem.postId}`;
break;
case 'accepted':
body = `${activityFeedItem.username} accepted your
${activityFeedItem.postId} request`;
break;
case 'message':
body = `${activityFeedItem.username} sent you a message`;
break;
default:
break;
}
// 4) Create message for push notification
const message = {
notification: {body},
token: androidNotificationToken,
data: {recipient: userId},
}
// 5) Send message with admin.messaging()
admin
.messaging
.send(message)
.then(response => {
// response is a message ID string
console.log('Succesfully sent message', response)
})
.catch(error => {
console.log('Error sending message', error)
});
}
});
A: You need to use admin.messaging() with parenthesis. It's a function call, not a property, just like you are already using with admin.firestore().
| |
doc_23532390
|
In my code, I have my bots programmed to react to specific trigger words, and it works, but not without it's problems.
The Problem I'm having is that my bot is responding to a small word, for example, 'Pen' and reacts to the word, but also reacts to a word like 'happen' because it has pen in it.
bot.on('message', message=>{
if(message.content.toLowerCase().includes('pen'.toLowerCase())) {
if (message.author.id === bot.user.id) return;
message.channel.send(pen[Math.floor(Math.random() * pen.length)]);
}});
This is the code. And I should mention that I am very new to JavaScript
Is there something I can specifically do it to make it ONLY react to the word 'pen'?
A: You need to check if message.content equals to pen
if(message.content.toLowerCase() === 'pen')
A: You can use word boundaries in regular expressions to only match a specific word, and not substrings of other words. Note the i flag at the end allows it to match both uppercase and lowercase "pen".
/\bpen\b/i
The expression above would match "pen" written as a word alone, but wouldn't match it inside "happened", for example. Here's how to use it in JavaScript:
/\bpen\b/i.test('i have a pen') // true
/\bpen\b/i.test('that happened') // false
Finally, your code would look like this:
bot.on('message', message => {
if(/\bpen\b/i.test(message.content)) {
if (message.author.id === bot.user.id) return;
message.channel.send(pen[Math.floor(Math.random() * pen.length)]);
}
}
);
If you want to play around with the expression, I've posted it to RegExr.
| |
doc_23532391
|
,0,0,0,0,0,1,1,
,0,0,0,7,8,6,6,
,3,3,3,3,9,4,5,
,5,6,6,9,5,2,1,
,6,2,8,0,0,3,9,
--------------------------------------------------
Reference,-,C,A,A,G,A,T,
17-F1,.,.,.,.,.,T,C,
37-F2,1A,A,C,T,T,.,.,
And I need to convert this to a XLS file
A: My awnser using Apache poi and Commons IO
Workbook wb = new HSSFWorkbook();
CreationHelper helper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
List<String> lines = IOUtils.readLines(new StringReader(csv));
for (int i = 0; i < lines.size(); i++) {
String str[] = lines.get(i).split(",");
Row row = sheet.createRow((short) i);
for (int j = 0; j < str.length; j++) {
row.createCell(j).setCellValue(helper.createRichTextString(str[j]));
}
}
FileOutputStream fileOut = new FileOutputStream("c:\\someName.xls");
wb.write(fileOut);
fileOut.close();
| |
doc_23532392
|
Problem setup: a user is attempting to create an advertisement campaign constructed of a set of attritubes (i.e. the campaign should target individuals in San Francisco). The user provides two numerical values to describe the constraints of their campaign, and the model generates a sequence of attributes describing a campaign.
Initial approach: the native approach is to convert the numerical inputs into string representations (2.0 -> two point zero). A custom tokenizer is trained on the dataset. After the number to string conversion, the numerical values, along with the target sequence, are used to train a fine-tuned version of the GPT-2 model by OpenAI.
Results: As expected, the model does very well at generating campaigns that make sense; However, the campaigns do not make sense in the context of the numerical inputs. Numerical inputs of 2.0 and 2.1 yield very different campaigns, when in fact, they should yield similar sequences of attributes.
Has there been work done on passing numerical information through a transformer model?
Example data:
Given a budget of 1200, a CPM target of 2.1, we recommend the following targets. Channel: mobile, connected tv, Location: US, ... (and so on).
| |
doc_23532393
|
System.Net.ServicePointManager.ServerCertificateValidationCallback =
((sender, certificate, chain, sslPolicyErrors) => true);
What doesn't make sense is that I have the certificate that is required installed on the remote machine. Before I had the certificate installed, I could navigate to the test Restful service URL for the other application and get certificate error. So I installed this certificate error to the Trusted Root and that error went away. However, my web application must still be getting the error. When I add the above mentioned code everything is working perfectly fine.
Does IIS 7.5 have settings that I can set for Certificates, does my web application have configurations where I can change this behavior? I don't understand the default behavior, my expectation is that since the certificate is installed in the trusted root my web app on that server would be fine.
A: You have to install the certificate in the Machine or Registry store so that the IIS application pool identity can pick it up. If you install it in the User store, your browser will see it and use it but since ASP.NET runs under a different identity, it will not be able to use it.
| |
doc_23532394
|
df <- tibble(x = c(1, 4, 2, 7), y = c(3, 1, 8, 4), group = c(2, 1, 1, 2))
fig <- plot_ly(data = df, type = "scatter", mode = "markers") %>%
add_trace(type = "scatter", mode = "markers", x=~x, y=~y,
transforms = list(
list(
type = "filter",
target = ~group,
operation = 'in',
value = unique(df$group)
)
)
) %>%
layout(
updatemenus = list(
list(
type = 'dropdown',
active = 0,
buttons = list(
list(method = "restyle",
args = list("transforms[0].value", unique(df$group)[2]),
label = "Group 1"),
list(method = "restyle",
args = list("transforms[0].value", unique(df$group)[1]),
label = "Group 2"),
list(method = "restyle",
args = list("transforms[0].value", unique(df$group)),
label = "All groups")
)
)
)
)
fig
| |
doc_23532395
|
My folder structure is:
Pages
-social
--fb
I have a social.vue file in pages which works fine as www.example.com/social but can't get www.example.com/social/fb. Any direction would be much appreciated.
A: Create social folder inside pages, then create fb.vue inside social folder.
This should work
A: I normally load the layout.vue from the router and treat everything else as a child which is passed though as a router-view, this then saves having an index.vue for each parent.
But you would always want to make a directory to contain the social pages. Then would be a case of simply adding to the router.js file.
layouts/template.vue
<template>
<router-view></router-view>
</template>
<script>
export default {
name: 'layout-template'
}
</script>
router.js
...
/*
* Social
*/
{
path: '/social',
component: () => import('./layout/template.vue'),
props: true,
// rendered inside <router-view>
children: [{
path: '/',
component: () => import('./pages/social/index.vue')
}, {
path: 'fb',
component: () => import('./pages/social/fb.vue')
}, {
path: 'twitter',
component: () => import('./pages/social/twitter.vue')
},
// or do something more dynamic
{
path: ':network', // accessible in component though `$route.params.network`
props: true, // makes accessible though `props: ['network']`
component: () => import('./pages/social/network.vue')
}]
},
...
./pages/social/index.vue - could show something /social homepage or change route to import('./pages/not-found.vue') instead.
./pages/social/network.vue
<template>
...
</template>
<script>
export default {
name: "page-social-network",
props: {
network: {
type: String,
default: ''
}
},
created() {
// or through
this.$route.params.network
}
};
</script>
<style lang="scss" scoped></style>
See: https://router.vuejs.org/guide/essentials/passing-props.html#boolean-mode
Otherwise is just standard vue pages
| |
doc_23532396
|
Now i have this code in my jsp page:
<c:forEach var="news" items="${requestScope.listaNews}">
<img src="ShowImage?idI=${news.idImmagine}" >
</c:forEach>
In the servlet ShowImage i make a query using idI and i print the image.
This is not good to me, because i may have 100 items in my loop and ill have to call 100 times the servlet ShowImage; since i call the db inside the servlet ShowImage this would means that ill make 100 connections to the database, in just one page.
What's the right way to print a loop of images taken from a db (from a bliob field) with just on query?
A: you can use the out of the JSTL
Here is a simple example:
The JSP
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Image Overview</title>
</head>
<body>
<c:forEach items="${imageBean.images}" step="1" var="img">
<c:out value="${img.name}"/><br/>
<img src="${img.sourceUri}"><br/>
</c:forEach>
</body>
</html>
And the BackingBean, i initialized the List with the Images on the first Instantiation of the Bean, do this, if the number of your images wont change, otherwise you can query the list of the images fresh from the Database, when you call the getImages() Method or encapsulate this in another method and call this before return images; on the Bean.
So here is the Demo Bean
import de.professional_webworkx.imagegallery.domain.DisplayImage;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
@Named(value = "imageBean")
@SessionScoped
public class ImageBean implements Serializable {
private List<DisplayImage> images = new ArrayList<>();
@PostConstruct
public void init() {
images.add(new DisplayImage("Image1", "http://i.stack.imgur.com/7bI1Y.jpg"));
images.add(new DisplayImage("Image2", "http://i.stack.imgur.com/XZ4V5.jpg"));
images.add(new DisplayImage("Image3", "http://i.stack.imgur.com/7bI1Y.jpg"));
images.add(new DisplayImage("Image4", "http://i.stack.imgur.com/iQFxo.gif"));
}
public List<DisplayImage> getImages() {
return images;
}
public void setImages(List<DisplayImage> images) {
this.images = images;
}
}
And the Domain class
import java.io.Serializable;
public class DisplayImage implements Serializable {
private String name;
private String sourceUri;
public DisplayImage() {
}
public DisplayImage(String name, String sourceUri) {
this.name = name;
this.sourceUri = sourceUri;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSourceUri() {
return sourceUri;
}
public void setSourceUri(String sourceUri) {
this.sourceUri = sourceUri;
}
}
Now you can display all your Images on one JSP Page.
Patrick
A: If you have plenty of memory in your server, and not too much images, simply preload everything in memory, but I must acknowledge it may not be a real option.
But your problem is really a question of caching the accesses to the database. It is easy to use one single query for the whole page, with the option of caching it for the duration of the session, depending on the disponible memory and the expected number of concurrent sessions.
Princips : in this answer, I will not separate the controller, service and database layers for brevity. As you get listaNews form the request attributes, I assume that you allready have a servlet that calculate this list put it in a request attribute and forward to your JSP.
This servlet will load all the images from listaNews from database, and store them in session. Then ShowImage searches the image in session (if it is not there for any reason it should load it from database) and returns it. Optionaly, it removes it from session if saving memory is a concern.
I would implement it that way, using a count to send for evicting cached images from session - if <0, never evict, if >0 number of send before cache evict (1 for normal case) :
CachedImage : keeps image bytes and the number of times it can be sent
public class CachedImage {
private static final int BUFFER_SIZE = 32768; // 32k buf
byte[] data;
int toSend;
public CachedImage(int toSend, InputStream is) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
ByteArrayOutputStream os = new ByteArrayOutputStream();
while (is.read(buffer) != -1) {
os.write(buffer);
}
data = os.toByteArray();
}
}
Modification in the servlet that prepares the page :
@Override
protected void service(HttpServletRequest hsr, HttpServletResponse hsr1) throws ServletException, IOException {
final int TO_SEND = 1; //number of time each image should be downloaded before purge (-1 = no purge)
HashMap<String, CachedImage> images = new HashMap<String, CachedImage>();
...
// calculates listaNews
// loads all the images from database and store them in session
for(...) { // loops for the images key id , InputStream is
images.put(id, new CachedImage(TO_SEND, is));
}
HttpSession session = hsr.getSession();
session.setAttribute("cachedImages", images);
}
ShowImage :
@Override
protected void service(HttpServletRequest hsr, HttpServletResponse hsr1) throws ServletException, IOException {
String id = hsr.getParameter("idI");
HttpSession session = hsr.getSession();
Map<String,CachedImage> images = (Map<String,CachedImage>) session.getAttribute("cachedImages");
if (images != null) { // Ok map is in session
CachedImage cached = images.get(id);
if (cached != null) { // ok image is in cache
if (cached.toSend > 0) { // if relevant, evict image from session cache
if (--cached.toSend == 0) {
images.remove(id);
}
}
}
//send cached image : cached.data
}
// load image from database and send it
}
| |
doc_23532397
|
The problem is with the following code. I keep getting a KeyNotFound exception here after de-serializing and trying to load the dictionary:
foreach (Perk p in perksTier1[skill])
{
string s = p.Name.ToString();
if (!lboxTier1.Items.Contains(s))
lboxTier1.Items.Add(s);
}
However, when I step through the code and examine the dictionary, it looks just as it should, with the Skill key clearly present.
Here's the really weird part:
Using ContainsKey returns null, but using GetKeys GIVES ME THE KEY
Wut. Please help.
A: You mention ContainsKey but you are using Contains. They are not the same. Contains is checking for the value in the dictonary. ContainsKey Method returns true or false. IF you are getting NULL, you are using the incorrect method.
A: Huzzah! Found it. See this post for the long details: GetHashCode and Equals implementation in Dictionary C#
To fix the imported dictionary, I had to override the Equals and GetHashCode() methods in my Skill class:
public override bool Equals(object obj)
{
Skill newskill;
newskill = (Skill)obj;
return (obj.GetHashCode() == newskill.GetHashCode());
}
public override int GetHashCode()
{
int temp = name.GetHashCode();
return temp;
}
(Thank you to Mike and Preston for pointing me in the right direction)
A: Your key is a custom object. By default, the dictionary is going to use an object reference comparison to determine if the given instance of a key is present in the Keys collection of the dictionary. Since it's using a reference comparison, the references are not the same as they will point to different references (even though they may "look" the same because they have the same values).
You need to tell the dictionary how it should test for equality. This is typically done in the object being used as the key, in this case your Skill object, by providing a custom Equals method or by implementing an EqualityComparer<Skill> object that defines the "rules" for determining if two instances are equal.
A: Based on your explanation you are using custom class as your key.
When using reference types as key you need to make sure that you use a reference to the same object that is being referenced by the dictionary key.
For example if you have this type
public class Skill
{
public string SkillName
{
get;
set;
}
}
Then you use it this way
Dictionary<Skill, object> dic = new Dictionary<Skill, object>();
for (int i = 0; i < 5; i++)
{
dic.Add(new Skill() { SkillName = i.ToString() }, new object());
}
Skill lookup = new Skill() { SkillName = "0"};
Console.WriteLine(dic.ContainsKey(lookup));
This will return false because lookup reference is pointing to an object which is different from the object that has been created in the loop, notice that the SkillName has the same value ("0" in this case).
If you change the code to the following
Dictionary<Skill, object> dic = new Dictionary<Skill, object>();
for (int i = 0; i < 5; i++)
{
dic.Add(new Skill() { SkillName = i.ToString() }, new object());
}
Skill lookup = dic.Keys.FirstOrDefault(sk => sk.SkillName == "0");
Console.WriteLine(dic.ContainsKey(lookup));
You will notice that the console line is printing true now. This is because the lookup reference is pointing to the same object that the dictionary has.
How does this related to your question? Its the serialization and de-serialization. If you create an object of type Skill like this
Skill skill1 = new Skill(){SkillName = "C#"};
Then serialize it using a serializer of your choice
Serializer.Serialize(skill1,streem);
Then you de-serialize it like this
Skill skill2 = Serializer.Deserialize(stream);
And print skill1 == skill2 you will find that it will return false, this is because what the serializer did when de-serializing the object is that it created new object and populated it with the same values that the first object had.
The rule is very simple reference equality is based on pointing to the same object, not on two different objects having the same property values.
Wish I have hit the spot given that you didn't provide enough information
| |
doc_23532398
|
iframe {
width: 100%;
height: 100%;
border: 0;
position: fixed;
top: 0;
z-index: -9999999999;
}
img {
position: fixed;
top: 0;
}
https://jsfiddle.net/3ef2onLc/1/
A: Your image is transparent but actually covers the whole map so you will be always clicking the image instead.
One quick solution would be to split the image in two, a left part and an upper part. That way you get a clickable quarter in the bottom right.
The better solution would be to construct the angled parts out of divs with some css. (Helpful: http://apps.eky.hk/css-triangle-generator/)
| |
doc_23532399
|
"created_at":"Mon Oct 29 22:37:25 +0000 2012","utc_offset":10800,"time_zone":"Baghdad"
But when I try to get the timezone information, I get an error saying that says KeyError: 'time_zone'. This is the code I'm using:
tweets_data = []
tweets_file = open(tweets_data_path, "r")
for line in tweets_file:
try:
tweet = json.loads(line)
tweets_data.append(tweet)
except:
continue
tweets = pd.DataFrame()
tweets['timezone'] = list(map(lambda tweet: (tweet['time_zone'] if 'time_zone' != None else None ),tweets_data))
Thanks!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.