id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23532200
|
Stations Bike
I try to take the positions of all stations available in the city using the website above
and then get Latitude & Longitude to show them into a map activity .
After having analyzed the web page I have not found a way to do that such as an RSS feed or a file in JSON format
My Question is how to get data from the map in the website using Android.
Thank you.
A: Trying to find json usage in the Stations Bike, I found an interesting json data using the following link:
https://yelo.agglo-larochelle.fr/stations?p_p_id=yeloStationsResult_WAR_cdalarochelleportlets&p_p_lifecycle=0&p_p_state=exclusive&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_yeloStationsResult_WAR_cdalarochelleportlets_action=nextBus&busStationId=2
It give us json data about a specific station with its longitude and latitude. This could be their api. But I can't make sure that.
Remember to adhere to their website tos.
| |
doc_23532201
|
A: ASP.NET MVC supports PUT requests by putting the HttpPut attribute on the action.
(In earlier versions you might need to use the AcceptVerbs attribute...)
A: Are you sure it doesn't support HTTP Put? I see that it is listed within the HttpVerbs Enumeration: http://msdn.microsoft.com/en-us/library/system.web.mvc.httpverbs.aspx
All you should have to do is ensure that you have decorated your action appropriately.
A: This does not appear to be possible. I've just used the Request.InputStream to read in a bitmap directly.
| |
doc_23532202
|
Now I need to go on each php file inside new folder and change the word "empty" by some word passed through $_POST["variable"].
Maybe by str_replace but I'm stuck in the logic.
Thanks in advance!
if (!file_exists("/home//public_html/new_conf_folder/"))
{
mkdir("/home//public_html/new_conf_folder/", 0755, true);
$source = "/home/public_html/conf_folder/";
$destination = "/home/public_html/new_conf_folder";
$directory = opendir($source);
while(($file = readdir($directory)) != false)
{
copy($source.'/' .$file, $destination.'/'.$file);
}
}
A: Try this code its working for me:
// file_process.php
$destination="./"; // Current Directory
if (file_exists($destination))
{
$directory = opendir($destination);
while(($file = readdir($directory)) != false)
{
//echo $file."<br/>";
$contents=file_get_contents($file);
$contents=str_replace("\"empty\"",$_POST['variable'],$contents);
//$contents=str_replace("\"empty\"",$_POST['variable'],$contents); // use this if the word with qouts
//echo $contents;
$bytes_written=file_put_contents($file,$contents);
if($bytes_written>0)echo "File [$file] has been successfully processed.";
else echo "Process Failed.";
}
}
| |
doc_23532203
|
I have tried to use this:
individuals = list(filter(lambda x: x.waterstore > 0, individuals))
but it gives me "UnboundLocalError: local variable 'individuals' referenced before assignment".
Here is the code where the problem occurs.
def day(numberOfDays):
days = 0
while days < numberOfDays:
print(str(days) + " days")
child = randint(1,100)
if child > 95:
IndividualGenerator(randint(1,2))
SeekWaterHole(individuals, lakes)
rain(lakes)
DrinkWater(individuals, lakes)
for r in range(len(individuals)):
individuals[r].waterstore -= 1
individuals = list(filter(lambda x: x.waterstore > 0,individuals))
individualTotalWater = []
for i in individuals:
individualTotalWater.append(i.waterstore)
AmountWater = lakes[0].water
Logg = [AmountWater, sum(individualTotalWater), len(individuals)]
with open("NewCSVTestFile.csv", "a") as f:
openfile = csv.writer(f, delimiter=",")
openfile.writerow(Logg)
print("logg " + str(Logg))
print()
days += 1
Any suggestion?
A:
"UnboundLocalError: local variable 'individuals' referenced before assignment".
Your first reference to individuals occurs here:
SeekWaterHole(individuals, lakes)
but it is not yet defined in your function, nor given as input to the function. Hence python does not know to what it references.
A: you can add individuals[] as an empty list just before the line of error or u can initialize individuals as an global.
from random import randint
def day(numberOfDays):
individuals=''
days = 0
while days < numberOfDays:
print(str(days) + " days")
child = randint(1,100)
#if child > 95:
#IndividualGenerator(randint(1,2))
individuals=[]//initialize the list before using it
#SeekWaterHole(individuals, lakes)
#rain(lakes)
#DrinkWater(individuals, lakes)
for r in range(len(individuals)):
individuals[r].waterstore -= 1
individuals = list(filter(lambda x: x.waterstore > 0,individuals))
individualTotalWater = []
for i in individuals:
individualTotalWater.append(i.waterstore)
#AmountWater = lakes[0].water
#Logg = [AmountWater, sum(individualTotalWater), len(individuals)]
#with open("NewCSVTestFile.csv", "a") as f:
# openfile = csv.writer(f, delimiter=",")
# openfile.writerow(Logg)
#print("logg " + str(Logg))
print()
days += 1
day(10)
| |
doc_23532204
|
It work almost perfectly, all the images changing with fade out/in.
The issue is: after the last image the first image appear without fade effect.
HTML Code:
<div id="gallery-holder">
<img src="images/main-galery1.jpg" class="active" >
<img src="images/main-galery2.jpg" >
<img src="images/main-galery3.jpg" >
</div>
CSS code:
#gallery-holder{
position:relative;
top:0px;
width:980px;
height:300px;
margin-left:auto;
margin-right:auto;
overflow:hidden;
}
#gallery-holder img{
position:absolute;
top:0;
left:0;
z-index:8;
}
#gallery-holder .active{
z-index:10;
}
#slideshow IMG.last-active {
z-index:9;
}
Java Script
$(document).ready(function(){
slideSwitch();
});
function slideSwitch() {
var $active = $('#gallery-holder IMG.active');
if ( $active.length == 0 ) $active = $('#gallery-holder IMG:last');
var $next = $active.next().length ? $active.next()
: $('#gallery-holder IMG:first');
$active.addClass('last-active');
$next.css({opacity: 0.0})
.addClass('active')
.animate({opacity: 1.0}, 1000, function() {
$active.removeClass('active last-active');
});
}
$(function() {
setInterval( "slideSwitch()", 5000 );
});
any advice?
I tried to replace:
$active.removeClass('active last-active');
with this:
$('#gallery-holder IMG.active').removeClass('active last-active');
No luck
A: Let's simplify things. No opacity/css, no active classes, just simple jQuery fades:
(function slideSwitch() {
var $gallery = $('#gallery-holder'),
$active = $gallery.find('img:visible'),
$next = $active.next().length ? $active.next() : $gallery.find('img').first();
setTimeout(function() {
$active.fadeOut('fast');
$next.fadeIn('fast', slideSwitch);
}, 2000);
}());
Demo: http://jsfiddle.net/AlienWebguy/npTD9/
| |
doc_23532205
|
packagehandler.obj:-1: error: LNK2019: unresolved external symbol "public: void __thiscall boost::iostreams::detail::gzip_header::reset(void)" (?reset@gzip_header@detail@iostreams@boost@@QAEXXZ) referenced in function "public: __thiscall boost::iostreams::detail::gzip_header::gzip_header(void)" (??0gzip_header@detail@iostreams@boost@@QAE@XZ)
packagehandler.obj:-1: error: LNK2019: unresolved external symbol "public: void __thiscall boost::iostreams::detail::gzip_footer::reset(void)" (?reset@gzip_footer@detail@iostreams@boost@@QAEXXZ) referenced in function "public: __thiscall boost::iostreams::detail::gzip_footer::gzip_footer(void)" (??0gzip_footer@detail@iostreams@boost@@QAE@XZ)
packagehandler.obj:-1: error: LNK2001: unresolved external symbol "int const boost::iostreams::zlib::default_compression" (?default_compression@zlib@iostreams@boost@@3HB)
packagehandler.obj:-1: error: LNK2001: unresolved external symbol "int const boost::iostreams::zlib::deflated" (?deflated@zlib@iostreams@boost@@3HB)
packagehandler.obj:-1: error: LNK2001: unresolved external symbol "int const boost::iostreams::zlib::default_strategy" (?default_strategy@zlib@iostreams@boost@@3HB)
packagehandler.obj:-1: error: LNK2019: unresolved external symbol "protected: __thiscall boost::iostreams::detail::zlib_base::~zlib_base(void)" (??1zlib_base@detail@iostreams@boost@@IAE@XZ) referenced in function __unwindfunclet$??0?$zlib_decompressor_impl@V?$allocator@D@std@@@detail@iostreams@boost@@QAE@ABUzlib_params@23@@Z$0
packagehandler.obj:-1: error: LNK2019: unresolved external symbol "protected: __thiscall boost::iostreams::detail::zlib_base::zlib_base(void)" (??0zlib_base@detail@iostreams@boost@@IAE@XZ) referenced in function "public: __thiscall boost::iostreams::detail::zlib_decompressor_impl<class std::allocator<char> >::zlib_decompressor_impl<class std::allocator<char> >(struct boost::iostreams::zlib_params const &)" (??0?$zlib_decompressor_impl@V?$allocator@D@std@@@detail@iostreams@boost@@QAE@ABUzlib_params@23@@Z)
packagehandler.obj:-1: error: LNK2019: unresolved external symbol "protected: void __thiscall boost::iostreams::detail::zlib_base::reset(bool,bool)" (?reset@zlib_base@detail@iostreams@boost@@IAEX_N0@Z) referenced in function "public: __thiscall boost::iostreams::detail::zlib_decompressor_impl<class std::allocator<char> >::~zlib_decompressor_impl<class std::allocator<char> >(void)" (??1?$zlib_decompressor_impl@V?$allocator@D@std@@@detail@iostreams@boost@@QAE@XZ)
packagehandler.obj:-1: error: LNK2019: unresolved external symbol "private: void __thiscall boost::iostreams::detail::zlib_base::do_init(struct boost::iostreams::zlib_params const &,bool,void * (__cdecl*)(void *,unsigned int,unsigned int),void (__cdecl*)(void *,void *),void *)" (?do_init@zlib_base@detail@iostreams@boost@@AAEXABUzlib_params@34@_NP6APAXPAXII@ZP6AX22@Z2@Z) referenced in function "protected: void __thiscall boost::iostreams::detail::zlib_base::init<class std::allocator<char> >(struct boost::iostreams::zlib_params const &,bool,struct boost::iostreams::detail::zlib_allocator<class std::allocator<char>,class std::allocator<char> > &)" (??$init@V?$allocator@D@std@@@zlib_base@detail@iostreams@boost@@IAEXABUzlib_params@23@_NAAU?$zlib_allocator@V?$allocator@D@std@@V12@@123@@Z)
packagehandler.obj:-1: error: LNK2019: unresolved external symbol "public: void __thiscall boost::iostreams::detail::gzip_footer::process(char)" (?process@gzip_footer@detail@iostreams@boost@@QAEXD@Z) referenced in function __catch$??$read@V?$linked_streambuf@DU?$char_traits@D@std@@@detail@iostreams@boost@@@?$basic_gzip_decompressor@V?$allocator@D@std@@@iostreams@boost@@QAE_JAAV?$linked_streambuf@DU?$char_traits@D@std@@@detail@12@PAD_J@Z$0
packagehandler.obj:-1: error: LNK2019: unresolved external symbol "public: void __thiscall boost::iostreams::detail::gzip_header::process(char)" (?process@gzip_header@detail@iostreams@boost@@QAEXD@Z) referenced in function "public: __int64 __thiscall boost::iostreams::basic_gzip_decompressor<class std::allocator<char> >::read<class boost::iostreams::detail::linked_streambuf<char,struct std::char_traits<char> > >(class boost::iostreams::detail::linked_streambuf<char,struct std::char_traits<char> > &,char *,__int64)" (??$read@V?$linked_streambuf@DU?$char_traits@D@std@@@detail@iostreams@boost@@@?$basic_gzip_decompressor@V?$allocator@D@std@@@iostreams@boost@@QAE_JAAV?$linked_streambuf@DU?$char_traits@D@std@@@detail@12@PAD_J@Z)
packagehandler.obj:-1: error: LNK2001: unresolved external symbol "int const boost::iostreams::zlib::okay" (?okay@zlib@iostreams@boost@@3HB)
packagehandler.obj:-1: error: LNK2001: unresolved external symbol "int const boost::iostreams::zlib::stream_end" (?stream_end@zlib@iostreams@boost@@3HB)
packagehandler.obj:-1: error: LNK2019: unresolved external symbol "public: static void __cdecl boost::iostreams::zlib_error::check(int)" (?check@zlib_error@iostreams@boost@@SAXH@Z) referenced in function "public: bool __thiscall boost::iostreams::detail::zlib_decompressor_impl<class std::allocator<char> >::filter(char const * &,char const *,char * &,char *,bool)" (?filter@?$zlib_decompressor_impl@V?$allocator@D@std@@@detail@iostreams@boost@@QAE_NAAPBDPBDAAPADPAD_N@Z)
packagehandler.obj:-1: error: LNK2019: unresolved external symbol "protected: void __thiscall boost::iostreams::detail::zlib_base::after(char const * &,char * &,bool)" (?after@zlib_base@detail@iostreams@boost@@IAEXAAPBDAAPAD_N@Z) referenced in function "public: bool __thiscall boost::iostreams::detail::zlib_decompressor_impl<class std::allocator<char> >::filter(char const * &,char const *,char * &,char *,bool)" (?filter@?$zlib_decompressor_impl@V?$allocator@D@std@@@detail@iostreams@boost@@QAE_NAAPBDPBDAAPADPAD_N@Z)
packagehandler.obj:-1: error: LNK2019: unresolved external symbol "protected: int __thiscall boost::iostreams::detail::zlib_base::xinflate(int)" (?xinflate@zlib_base@detail@iostreams@boost@@IAEHH@Z) referenced in function "public: bool __thiscall boost::iostreams::detail::zlib_decompressor_impl<class std::allocator<char> >::filter(char const * &,char const *,char * &,char *,bool)" (?filter@?$zlib_decompressor_impl@V?$allocator@D@std@@@detail@iostreams@boost@@QAE_NAAPBDPBDAAPADPAD_N@Z)
packagehandler.obj:-1: error: LNK2001: unresolved external symbol "int const boost::iostreams::zlib::sync_flush" (?sync_flush@zlib@iostreams@boost@@3HB)
packagehandler.obj:-1: error: LNK2019: unresolved external symbol "protected: void __thiscall boost::iostreams::detail::zlib_base::before(char const * &,char const *,char * &,char *)" (?before@zlib_base@detail@iostreams@boost@@IAEXAAPBDPBDAAPADPAD@Z) referenced in function "public: bool __thiscall boost::iostreams::detail::zlib_decompressor_impl<class std::allocator<char> >::filter(char const * &,char const *,char * &,char *,bool)" (?filter@?$zlib_decompressor_impl@V?$allocator@D@std@@@detail@iostreams@boost@@QAE_NAAPBDPBDAAPADPAD_N@Z)
debug\EmbeddedBoardTestScriptUtility.exe:-1: error: LNK1120: 18 unresolved externals
A: You should check if libboost_iostreams .lib library is available in your Boost libraries directory and if if is correctly linked in linking directories and linked libraries in linker project settings.
If you have compiled boost and have doubts on boost compilation (it can be compiled with many options excluding some projects) you can use precompiled binaries available on sourceforge [1].
[1] https://sourceforge.net/projects/boost/files/boost-binaries/1.60.0/
A: You need to build boost with zlib enabeled. During the configuration phase boost will try to locate zlib and if succesfull you should see something like this when running the b2 command.
On most *nix platforms you need to install the zlib dev package. On Windows you need find/build zlib binaries and set these 3 environment variables before compiling boost.
ZLIB_BINARY
ZLIB_INCLUDE
ZLIB_LIBPATH
See this boost documentation:
https://www.boost.org/doc/libs/1_54_0/libs/iostreams/doc/installation.html
| |
doc_23532206
|
Many-to-Many (Many Person Many Group) and a table between - Event, witch ralate these two tables.
public class Person
{
public int PersonID { get; set; }
public string No { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Event> Events { get; set; }
}
public class Event
{
public int EventID { get; set; }
public string EventData { get; set; }
public int PersonID { get; set; }
public int GroupID { get; set; }
public virtual Person Person { get; set; }
public virtual Group Group { get; set; }
}
public class Group
{
public int GroupID { get; set; }
public string GroupName { get; set; }
public virtual ICollection<Event> PersonGroup { get; set; }
}
I ddescribed relations using Fluent API.
First I declared PK's
modelBuilder.Entity<Person>()
.HasKey(k => k.PersonID });
modelBuilder.Entity<Event>()
.HasKey(k => k.EventID);
modelBuilder.Entity<Group>()
.HasKey(k => k.GroupID });
Now foreign keys:
Person has many Events
modelBuilder.Entity<Person>()
.HasKey(k => k.PersonID })
.HasMany(k => k.Events)
.WithRequired()
.HasForeignKey(f => f.PersonID);
In Event class I have Person (and all its parameters)
modelBuilder.Entity<Event>()
.HasRequired(s => s.Person)
.WithMany()
.HasForeignKey(fk => fk.PersonID);
Also I need a Group with all data:
modelBuilder.Entity<Event>()
.HasOptional(s => s.Group)
.WithMany()
.HasForeignKey(fk => fk.GroupID });
At least I need a Person group participating in an Event
modelBuilder.Entity<Group>()
.HasKey(k =>k.GroupID })
.HasMany(k => k.PersonGroup)
.WithOptional()
.HasForeignKey(fk => fk.GroupID);
It seems I have everything I need, but I need one mo collection (Group of persons with their names)
What I get through PersonGroup relation I have all events but also need to get Persons. Could You help?
A: Edit
I just realize it's not a typical many-to-many, since your Event-Group relation is optional. Is this intended?
Maybe your model should be changed to reflect a more natural event structure:
Group-Person: many-to-many
Event-Group: many-to-many
Event-Person: no direct relation, only via groups; alternative many-to-many
The way your model is currently designed, a single event entry can't be related to more than one group and one person and a person can't be part of a group unless they are associated in the context of an event entry.
Basically, the thing you ask for is not directly available, because you decided to explicitely create the many-to-many table with additional properties.
However, in queries you can always write a select to get the persons collection
db.Groups.Select(g => new {Group = g, PeopleInGroup = g.PersonGroup.Select(ev => ev.Person)})
Few side-notes regarding your model:
*
*Consider removing EventID and instead use modelBuilder.Entity<Event>().HasKey(k => new { k.PersonID, k.GroupID }), like a typical many-to-many table would be designed.
*Mention reverse properties in fluent api:
.
modelBuilder.Entity<Person>()
.HasKey(k => k.PersonID })
.HasMany(k => k.Events)
.WithRequired(e => e.Person)
.HasForeignKey(f => f.PersonID);
// redundant with the previous configuration
modelBuilder.Entity<Event>()
.HasRequired(s => s.Person)
.WithMany(p => p.Events)
.HasForeignKey(fk => fk.PersonID);
// same to be done for groups
In order to have a convenient access to the associated people of a group, you could create a not-mapped property getter which wraps the necessary query:
public class Group
{
public int GroupID { get; set; }
public string GroupName { get; set; }
public virtual ICollection<Event> PersonGroup { get; set; }
[NotMapped]
public IEnumerable<Person> PersonsInGroupEvents
{
return PersonGroup.Select(ev => ev.Person);
}
}
// or fluent api way of NotMapped:
modelBuilder.Entity<Group>()
.Ignore(x => x.PersonsInGroupEvents);
| |
doc_23532207
|
ut cntr src Item section Year Period css fct ytd_1 ytd_1*fct aproach1 aproach2
49 52 179 f 84 2019 1 63 0.616580311 5578.092 3439.341699 0 0
e4 52 179 f 84 2019 1 31 0.248704663 5578.092 1387.297492 0 0
49 52 179 f 84 2019 1 31 0.248704663 5578.092 1387.297492 0 0
a5 52 179 f 84 2019 1 31 0.248704663 5578.092 1387.297492 0 0
49 52 179 f 84 2019 2 63 0.080405405 18506.982 1488.061391 3439.341 5578.092
49 52 179 f 84 2019 2 31 0.072297297 18506.982 1338.00478 1387.29 5578.092
e4 52 187 f 84 2019 2 31 0.072297297 18506.982 1338.00478 1387.29 5578.092
e4 52 179 f 84 2019 2 31 0.072297297 18506.982 1338.00478 1387.29 5578.092
code:
w_lag = Window.partitionBy(['Item','section','section','css','Year']).orderBy(spark_func.asc('Period'))
df_lag = df_unit.withColumn('approach', spark_func.lead(df_unit['ytd_1']).over(w_lag))
can I get the help to get the values of the previous month which I mentioned in approach2 column(expected results)
A: Check if below works for you.
First creating your Dataframe(Added Period 3 for validation of result, not caring about other columns)
l1 = [('49',52,179,'f',84,2019,1,63,0.616580311,5578.092,3439.341699),
('e4',52,179,'f',84,2019,1,31,0.248704663,5578.092,1387.297492),
('49',52,179,'f',84,2019,1,31,0.248704663,5578.092,1387.297492),
('a5',52,179,'f',84,2019,1,31,0.248704663,5578.092,1387.297492),
('49',52,179,'f',84,2019,2,63,0.080405405,18506.982,1488.061391),
('49',52,179,'f',84,2019,2,31,0.072297297,18506.982,1338.00478),
('e4',52,187,'f',84,2019,2,31,0.072297297,18506.982,1338.00478),
('e4',52,179,'f',84,2019,2,31,0.072297297,18506.982,1338.00478),
('e4',52,179,'f',84,2019,3,31,0.072297297,10006.982,1338.00478),
('e4',52,179,'f',84,2019,3,31,0.072297297,10006.982,1338.00478)]
Create Dataframe
dfl1 = spark.createDataFrame(l1).toDF('ut','cntr','src','Item','section','Year','Period','css','fct','ytd_1','ytd_1*fct')
dfl1.show()
+---+----+---+----+-------+----+------+---+-----------+---------+-----------+
| ut|cntr|src|Item|section|Year|Period|css| fct| ytd_1| ytd_1*fct|
+---+----+---+----+-------+----+------+---+-----------+---------+-----------+
| 49| 52|179| f| 84|2019| 1| 63|0.616580311| 5578.092|3439.341699|
| e4| 52|179| f| 84|2019| 1| 31|0.248704663| 5578.092|1387.297492|
| 49| 52|179| f| 84|2019| 1| 31|0.248704663| 5578.092|1387.297492|
| a5| 52|179| f| 84|2019| 1| 31|0.248704663| 5578.092|1387.297492|
| 49| 52|179| f| 84|2019| 2| 63|0.080405405|18506.982|1488.061391|
| 49| 52|179| f| 84|2019| 2| 31|0.072297297|18506.982| 1338.00478|
| e4| 52|187| f| 84|2019| 2| 31|0.072297297|18506.982| 1338.00478|
| e4| 52|179| f| 84|2019| 2| 31|0.072297297|18506.982| 1338.00478|
| e4| 52|179| f| 84|2019| 3| 31|0.072297297|10006.982| 1338.00478|
| e4| 52|179| f| 84|2019| 3| 31|0.072297297|10006.982| 1338.00478|
+---+----+---+----+-------+----+------+---+-----------+---------+-----------+
Define Window. Here is the trick, we are giving range of -1 to 0 so it will always check one range above and then take the first value of previous range.
Range description from official document
A range-based boundary is based on the actual value of the ORDER BY expression(s)
wl1 = Window.partitionBy(['Item','section','Year','css']).orderBy('Period').rangeBetween( -1, 0)
Now First value will be same for Period 1 so adding when function and marking as 0
dfl2 = dfl1.withColumn('Result', func.when(func.first(dfl1['ytd_1']).over(wl1) == dfl1['ytd_1'], func.lit(0)).otherwise(func.first(dfl1['ytd_1']).over(wl1)))
dfl2.orderBy('Period').show()
+---+----+---+----+-------+----+------+---+-----------+---------+-----------+---------+
| ut|cntr|src|Item|section|Year|Period|css| fct| ytd_1| ytd_1*fct| Result|
+---+----+---+----+-------+----+------+---+-----------+---------+-----------+---------+
| e4| 52|179| f| 84|2019| 1| 31|0.248704663| 5578.092|1387.297492| 0.0|
| a5| 52|179| f| 84|2019| 1| 31|0.248704663| 5578.092|1387.297492| 0.0|
| 49| 52|179| f| 84|2019| 1| 63|0.616580311| 5578.092|3439.341699| 0.0|
| 49| 52|179| f| 84|2019| 1| 31|0.248704663| 5578.092|1387.297492| 0.0|
| 49| 52|179| f| 84|2019| 2| 63|0.080405405|18506.982|1488.061391| 5578.092|
| e4| 52|179| f| 84|2019| 2| 31|0.072297297|18506.982| 1338.00478| 5578.092|
| 49| 52|179| f| 84|2019| 2| 31|0.072297297|18506.982| 1338.00478| 5578.092|
| e4| 52|187| f| 84|2019| 2| 31|0.072297297|18506.982| 1338.00478| 5578.092|
| e4| 52|179| f| 84|2019| 3| 31|0.072297297|10006.982| 1338.00478|18506.982|
| e4| 52|179| f| 84|2019| 3| 31|0.072297297|10006.982| 1338.00478|18506.982|
+---+----+---+----+-------+----+------+---+-----------+---------+-----------+---------+
| |
doc_23532208
|
img = new ImageView(this);
img.setBackgroundResource(R.drawable.starred);
img.setLayoutParams(new TableRow.LayoutParams(28,28));
i want to change image when user click on image
img.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try
{
AlertDialog.Builder builder = new AlertDialog.Builder(Job_Description.this);
builder.setTitle("Save this Job ?");
// builder.setMessage("whould You like to save job");
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
img.setImageResource(R.drawable.starapplied);
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
dialog.cancel();
}
});
builder.show();
}catch(Exception e)
{
Log.d("Image clicked", e.toString());
}
}
});
am i doing something wrong here?
A: You are not setting any image onClick of your image. You are just pushing the dialog. If you want to change image after onClick of the ImageView
then add this line in your onClick method
imageView.setImageResource(resId);
A: ImageView imageView=(ImageView) findViewById(R.id.parking_map);
imageView.setImageResource(R.drawable.ic_launcher);
| |
doc_23532209
|
someCharactersHere andSomeMore 192.168.1.55 11211 typ someMorechars andYetMore
I know the IP address to be replaced but not the port number. I only know that it is an integer followed by "typ."
I am looking for JS to replace any such string by
someCharactersHere andSomeMore 192.168.3.34 20121 typ someMorechars andYetMore
So, for example, a function to do so will be:
function newString(oldString, oldIp, newIp, newPort) {
return oldString.replace(/regEx/, newIp + " " + newPort);
}
Can someone help me with the regEx. The IP address appears only once in the string. The integer port number may appear elsewhere but the one I want to replace will always be surrounded by a single space on the left and space followed by "typ" on the right. In other words the target to be replaced is:
.... oldIp oldPortNo typ ...
by
.... newIp newPortNo typ ....
A: You may try:
(?:\d{1,3}\.){3}\d{1,3} \d+(?= typ)
Explanation of the above regex:
*
*(?:\d{1,3}\.){3} - Represents a non-capturing group matching digits 1 to 3 times followed by a .. The whole group repeats exactly three times.
*\d{1,3} - Matches digit 1 to 3 times.(for the last part of IP)
*\d+(?= typ) - Matches digits which are followed by typ.
You can find the demo of the above regex in here.
const regex = /(?:\d{1,3}\.){3}\d{1,3} \d+(?= typ)/g;
const str = `someCharactersHere andSomeMore 192.168.1.55 11211 typ someMorechars andYetMore
`;
const subst = `192.168.3.34 20121`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log(result);
A: How about this regex?
/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s(\d+)\styp/gum
You can have a look at the regex101 fiddle here: https://regex101.com/r/Xk0gLR/1. Group 1 is the IP address, and Group 2 would be the port number
A: You can use the RegExp constructor to use a variable inside a regular expression:
function newString(oldString, oldIp, newIp, newPort) {
const regex = new RegExp(oldIp + "\\s+\\d+ typ");
return oldString.replace(regex, newIp + " " + newPort + " typ");
}
const oldString = "someCharacters andSomeMore 192.168.1.55 11211 typ someMorechars",
oldIp = "192.168.1.55",
newIp = "192.168.3.34",
newPort = "20121";
console.log( newString(oldString, oldIp, newIp, newPort) );
This will look for the provided oldIp, followed by one or more space (\s+) and one or more digit \d+. And since \ is an escape character in Strings, they need to be escaped themselves (\\).
A: \d+(.\d+)+\s+\d+
s="someCharactersHere andSomeMore 123.123.123.123 123123 typ someMorechars andYetMore"
result=s.replace(/\d+(\.\d+)+\s+\d+/,'456.456.456.456 987987')
console.log(result)
| |
doc_23532210
|
I have written the Choice component in for-each loop and trying to attach the files and trying to use text to log currently and in future will use it to print in email body.
Problem is with the current code Text is also getting attached as a text file in email. How to avoid text getting attached to email? also in case of multiple jpg files attachments extension is getting lost. while for single file it is working properly.
I tried to add choice component in foreach loop and tried to attach only file part of the received form-data and tried to log the text. text is getting logged in loop but after loop both the parts (file and text) are getting attached to SMTP connector.
<foreach collection="#[message.inboundAttachments]" doc:name="Foreach">
<logger message="File name:- #[payload.dataSource.part.fileName] Key name:- #[payload.dataSource.part.name] Content type:- #[payload.dataSource.part.contentType] contents:- #[payload.dataSource.content]."
level="INFO" doc:name="Logger"/>
<choice doc:name="Choice">
<when expression="#[payload.dataSource.part.fileName == null]">
<set-variable variableName="notificationData" value="#[payload.dataSource.content]" doc:name="Variable"/>
<flow-ref name="testNotificationsSub_Flow" doc:name="testNotificationsSub_Flow"/>
</when>
<when expression="#[payload.dataSource.part.fileName != null]">
<set-attachment attachmentName="#[payload.dataSource.part.fileName]" value="#[payload.dataSource.content]" contentType="image/jpeg" doc:name="Attachment"/>
</when>
<otherwise>
<logger message="neither NotificationData nor file #[payload.dataSource.part.name]" level="INFO" doc:name="Logger"/>
</otherwise>
</choice>
</foreach>
expected output is : file should get attached and for Text part, subflow only should get excuted.Text is not attachment, so it is not supposed to get attached to email. postman may look like below
| |
doc_23532211
|
I maked rlib file in bin crate.
And I would like to link this rlib file in bin crate without exporting source code.
Just like linking object file in C/C++.
By adding dependencies in cargo.toml, I think it is necessary to rebuild from.source.
How can I write Cargo.toml?
My rust edition is 2018. Please :)
| |
doc_23532212
|
A: It would take you two tables. Structure is as easy as the following.
Note table:
NotePK | tableFK | note
And a table that lists all your tables.
Either you create one (then you have full control but need to maintain it) or you take the
sys.tables t
You read it out by SELECT * FROM sys.tables t
the column object_id would be your tableFK in the first table
You can store as many comments as you like. If you want to get the note simply query the note table and filter for your tableFK.
A: Well, here's one way:
CREATE TABLE NoteTables
(
TableID INT NOT NULL Identity(1,1),
TableName SysName NOT NULL,
CONSTRAINT PK_NoteTables PRIMARY KEY CLUSTERED(TableID)
)
GO
CREATE TABLE TableNotes
(
TableID INT NOT NULL,
RowID INT NOT NULL,
NoteID INT NOT NULL,
CONSTRAINT PK_NoteAttachments PRIMARY KEY CLUSTERED(TableID, RowID, NoteID)
)
GO
CREATE TABLE Notes
(
NoteID INT NOT NULL Identity(1,1),
Note NVARCHAR(MAX),
CONSTRAINT PK_Notes PRIMARY KEY CLUSTERED(NoteID)
)
Note that I am assuming SQL Server and the use of IDENTITY columns here (if Oracle, you can use Sequences instead).
The Notes table contains all of the notes and gives them an ID to use as both a referemce and a primary key.
The NoteTables just list all of the tables that can have note attached to their rows.
TableNotes links the notes to the tables and rows that they are attached to. Note that this design assumes that all of these tables have INT ID columns that can be used for unique referencing.
| |
doc_23532213
|
Example:
@using (Html.BeginForm())
{
<asp:calander>...
etc
A: Actually Razor does not support WebForm controls, but you need to see Scott Hanselman's example if you really want to mix n match
http://www.hanselman.com/blog/PlugInHybridsASPNETWebFormsAndASPMVCAndASPNETDynamicDataSideBySide.aspx
| |
doc_23532214
|
I coded so every time I clicked a button the wheel spun for testing purposes. But it was not good enough, because the round result is generated in the backend and the amount the wheel translates is retrieved from the server, so the translateX() needs to have dynamic values. I created another post asking how I could dynamically set the value of the translateX() function so it could land in the right number. Turns out it's more complex than that. Take https://csgoempire.com as an example. I was taking a look at the code and in the roulette HTML code, I realized that the change the background-position with element.style.setProperty()
In this website the wheel spin is smooth. Since I'm a considerably new to web programming and using NodeJs, CSS, HTML, and ReactJs I'm not sure how they did this. I'm using sockets on my project to establish a connection between the server and the clients, in a way that everyone can see the same thing at the same time. So I assume I need to make this spin function server-side and pass the background-position to the client every tick, but I don't know if this can cause lag or not. I've been also trying to create a function that does that, but it's quite difficult since I haven't learned this type of math yet. (I'm in the 9th grade)
That's the function I thought that would work. At first, the speed of the roulette spin is constant and at a certain point, it starts to decrease creating a smooth effect. The speed represents the amount of pixels the background-image moves per time. The problem is that I don't know to create this function and I don't know if this is the right solution. What should I do? Thanks in advance! PS: Sorry for any spelling mistake or any trouble understanding what I said in this post. English is not my native language.
A: I think your function is incorrect, it should slow down fast at the beginning then slowly at the end until it stops. An easy function for that is: f(x+1) = f(x)*k where k is smaller than 1 (for example 0.96).
The smaller the value of k, the faster it will stop. Since this simple function is infinite, you should add a test in the loop to detect when it's not moving anymore and then exit the loop and give the result.
| |
doc_23532215
|
But it is not working, seems that fetch-mock does not mock the request.
I tried to set up the polyfill codes, but the result is the same.
Is there something we have to set up before the testing?
| |
doc_23532216
|
I recalled that in Linux you can do:
~/bin/initdb -B 100 -D ~/dir/data
or
~/bin/postgres -B 100 -D ~/dir/data
to start up the server or init the db with 100 buffers, but in my MacOS it shows
initdb: invalid option -- B
I am using PostgreSQL 10.5, did they changed it in MacOS or just me having the wrong cmd for Mac?
| |
doc_23532217
|
Since the text with sarcasm_tag == Yes are very less, it hides many points on the graph. Separate plot for both tags are as follows:
Is there any better way to visualize the scores so that both classes are visible?
A: In addition to the win solution (plot second no points) you can play with the alpha of the points, to give more color to the no.
# Sample data
blue_data = np.random.normal(size=(3000, 2))
red_data = np.random.normal(size=(10, 2))
for blue_point in blue_data:
plt.plot(blue_point[0], blue_point[1], 'ob')
for red_point in red_data:
plt.plot(red_point[0], red_point[1], 'or')
With 0.3 alpha for the blues, and 0.8 alpha for the reds
for blue_point in blue_data:
plt.plot(blue_point[0], blue_point[1], 'ob', alpha=0.3)
for red_point in red_data:
plt.plot(red_point[0], red_point[1], 'or', alpha=0.8)
Best! You can play with the alpha until you find what you are looking for.
| |
doc_23532218
|
Not sure how to parse it but this is what I have (unsuccessfully tried)
df = DataFrame(test)
df.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']
df.set_index('Date')
df.index = pd.to_datetime(df.index, unit = 'd')
where the variable test is a list of the underlying data. this incorrectly parses the data as year being 1970.
The result of the parse:
1970-01-01 00:00:00.000000000
Any ideas?
********************** EDIT ************************************
Python version: 3
Pandas version. 0.23.0
Here is a working example for reproducibility. But first, here are the facts I have discovered.
DATE FORMAT: 64-bit Unix Timestamp in milliseconds since Epoch 1 Jan 1970
TIMEZONE: UTC
MY TIMEZONE: UTC + 4 (the desired datetime index)
The code:
import bitmex
import pandas as pd
from pandas import DataFrame
import datetime
import ccxt
api_connector = ccxt.bitmex({
'enableRateLimit': True
})
#get OHLCV Data
testdata = api_connector.fetch_ohlcv('XBTZ18', '1h')
df2 = DataFrame(testdata)
df2.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']
#df2.set_index('Date')
df2.index = pd.to_datetime(df2.Date, unit='ms')
df3 = df2.drop(['Date'],
axis =1)
df3.tail()
This returns:
Open High Low Close Volume
Date
2018-07-06 00:00:00 6538.5 6555.0 6532.5 6537.0 176836
2018-07-06 01:00:00 6537.0 6535.5 6520.5 6524.5 139735
2018-07-06 02:00:00 6524.5 6542.5 6525.5 6542.5 59759
2018-07-06 03:00:00 6542.5 6545.0 6538.0 6538.0 121410
2018-07-06 04:00:00 6538.0 6538.5 6477.5 6525.0 764125
Close! but no cigar. Today's date is 8/31/2018 so I would at least expect it to be in the correct month.
What am I doing wrong, folks?
A: This is almost certainly a variation on "Unix time": instead of seconds since the 1 Jan 1970 epoch, it's milliseconds since the 1 Jan 1970 epoch:
>>> datetime.datetime.utcfromtimestamp(int('1522454400000') / 1000)
datetime.datetime(2018, 3, 31, 0, 0)
That certainly looks like a reasonable date. And it even looks like it probably is UTC, not local time (unless you happen to be in England, or weren't expecting it to be exactly at midnight).
I don't think any of Pandas' built-in formats (which are actually just wrappers around formats from datetime and/or dateutil) exactly matches this, so you'll probably need to either do what I did about (convert to int and treat it as a number) or do the stringy equivalent (chop off the last 3 characters and then treat as a string of a UNIX timestamp).
The first one seems simpler:
>>> pd.to_datetime(int('1522454400000'), unit='ms')
Timestamp('2018-03-31 00:00:00')
In fact, it'll even work directly on strings, doing the conversion implicitly:
>>> pd.to_datetime('1522454400000', unit='ms')
Timestamp('2018-03-31 00:00:00')
| |
doc_23532219
|
I am trying to put the current date inside a date type input so that I get the current date un angular, I use php inside the input but it gives me an error. how to solve this error?
why?????...
What can i do in angular to get the current date in a input ?
A: There is no syntax problem, I think your file type is html, if it is html you need to change it to php.
Because you used PHP code in the value section, you should convert your file extension to PHP.
agregar-empleado-component.html covert to agregar-empleado-component.php
| |
doc_23532220
|
@app.route('/get_dir/<path>')
def get_dir(path):
return path
A: Use the path converter to capture arbitrary length paths: <path:path> will capture a path and pass it to the path argument. The default converter captures a single string but stops at slashes, which is why your first url matched but the second didn't.
If you also want to match the root directory (a leading slash and empty path), you can add another rule that sets a default value for the path argument.
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def get_dir(path):
return path
There are other built-in converters such as int and float, and it's possible to write your own as well for more complex cases.
| |
doc_23532221
|
All the three screens will be having three different layouts with a set of its own keys.
I would like to implement this inside a ViewPager so that i can swipe my screens, and interact with each screen as if i am interacting to an activity.
How can i do this?
One of my colleagues told me i need to get the id of all the buttons and views used and should interact to it separately. I dint understand that. Could somebody explain the logic to implement this application to me.
I would like to implement something like the launcher in tablet or phone. Does the touch listener be able to make a click on the view or widget lying on the screen below my touch point?
Please find the figures of my app.
All the screens has some buttons and widgets which need to respond to the user touch/click when each is highlighted.
Please shed some light into this.
A: I managed to create a dashboard, similar to some devices' default launchers, by implementing ViewPager and creating my own PagerAdpter. See the code below:
public class DashboardPagerAdapter extends PagerAdapter {
private static final int ROWS = 4;
private static final int COLS = 4;
private Context mContext;
private List<AppEntry> mData;
public DashboardPagerAdapter(Context context, List<AppEntry> data) {
mContext = context;
mData = data;
}
@Override
public int getCount() {
double ratio = (double) mData.size() / (ROWS * COLS);
return (int) Math.ceil(ratio);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((TableLayout) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
int cols = COLS, rows = ROWS;
switch (mContext.getResources().getConfiguration().orientation) {
case Configuration.ORIENTATION_PORTRAIT:
rows++;
break;
default:
cols++;
}
TableLayout table = new TableLayout(mContext);
table.setStretchAllColumns(true);
table.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
table.setBackgroundColor(Color.DKGRAY);
int start = position * rows * cols;
int end = Math.min(start + rows * cols, mData.size());
LayoutInflater inflater = LayoutInflater.from(mContext);
for (int i = 0; i < rows; i++) {
TableRow row = new TableRow(mContext);
row.setLayoutParams(new TableLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
row.setGravity(Gravity.CENTER);
for (int j = 0; j < cols; j++) {
int pos = start + i * cols + j;
if (pos < end) {
AppEntry item = mData.get(pos);
View vItem = inflater.inflate(R.layout.grid_item, null,
false);
ImageView image = (ImageView) vItem.findViewById(R.id.icon);
image.setImageDrawable(item.getIcon());
row.addView(vItem);
} else {
TextView vPlaceHolder = new TextView(mContext);
vPlaceHolder.setText(" ");
row.addView(vPlaceHolder);
}
}
table.addView(row);
}
container.addView(table);
return table;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
The instantiateItem method, in this case, returns a TableLayout which I use to display the app icons. I calculate the number of pages (getCount()) by dividing the size of the collection of data by the number of items per page (rows * cols).
You could add an onClickListener to vItem inside the for loop in case you want to handle that event. I would recommend to share the listener between the views and ask for the tag or ID before taking any action.
If your content is static, you would probably want to use FragmentPagerAdapter instead, and create one Fragment for each page.
A: This is fairly ambitious -- otherwise everyone would have already released their own launcher-style application -- but doable. Sounds like you need a ViewPager with GridView as the hosted view. The GridView can easily do the things you're talking about with a onItemClickListener() attached to it to capture clicks on each item. There are a lot of tutorials out there for ViewPager (see here for a decent one) and GridView (see here for a decent one of those), now all you need to do is get them working together which should be too tough given a little work.
| |
doc_23532222
|
I found one method in one class, where I have a very long switch-case-statement. Of course this is a horrible scenario for unit-testing, since I need to create a test for every statement.
Now I thought about applying the Strategypattern. But the problem is, I have 30 different cases. That would mean I would have to create 30 classes. Is this advised, or should I consider some other way of refactoring? Morover the switch case is inside two for-loop, since it's an Excel-table.
Here is an excerpt of my method:
switch (column) {
case CASE1:
excelUtil.setCell(row, col++, item.getSomething(), styles[0]);
break;
case CASE2:
excelUtil.setCell(row, col++, order.getSomething(), styles[0]);
break;
case CASE3:
excelUtil.setCell(row, col++, order.getSomethingElse(), styles[0]);
break;
case CASE4:
if (!StringUtils.isEmpty(order.getSomething())) {
try {
//do something before setting cell
excelUtil.setCell(row, col++, soldToName, styles[0]);
}
catch (final Exception e) {
excelUtil.setCell(row, col++, "", styles[0]);
}
}
else {
excelUtil.setCell(row, col++, "", styles[0]);
}
break; //.. and so on
A: Yes, the strategy pattern is the right choice in this situation. Ensure that the state tracking logic (e.g. col++) is not leaked into the strategies.
With strategies in place, the strategy selection can then be moved to a dictionary: Create a dictionary that maps from column to a strategy, and use the dictionary in place of the switch-case. This works because the strategies all implement the same interface.
| |
doc_23532223
|
name "0jDPVkL"
cluster_name "elasticsearch"
cluster_uuid "9PfIve-HSP-v7kU__DbGmQ"
version
number "6.4.1"
build_flavor "default"
build_type "zip"
build_hash "e36acdb"
build_date "2018-09-13T22:18:07.696808Z"
build_snapshot false
lucene_version "7.4.0"
minimum_wire_compatibility_version "5.6.0"
minimum_index_compatibility_version "5.0.0"
tagline "You Know, for Search"
The Python Code
import logging
def connect_elasticsearch():
_es = None
_es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
if _es.ping():
print('Yay Connect')
else:
print('Awww it could not connect!')
return _es
if __name__ == '__main__':
logging.basicConfig(level=logging.ERROR)
I am trying to execute from the URL http://blog.adnansiddiqi.me/getting-started-with-elasticsearch-in-python/
A: I have tested your code from the blog. Its working fine. I uploaded in the github also
https://github.com/mak705/Python_ELK/blob/master/recipie.ipynb
Courtesy : Adnan who wrote the blog http://blog.adnansiddiqi.me/getting-started-with-elasticsearch-in-python/
NB: In latest version of ES(6,x) we don't need to mention mapping tags that is starting from the mapping { . Its automatically detects and give the schema. In earlier version(5.x) we have to mention the schema
| |
doc_23532224
|
The iOS App code to subscribe is as follows:
- (void)loginAndConnectToChatQBUserWithLoginName:(NSString *)loginName password:(NSString *)password{
isConnecting = YES;
QBUUser *user = [[QBUUser alloc] init];
user.login = loginName;
user.password = password;
__weak typeof(self) weakSelf = self;
//Authenticate user
[QBRequest logInWithUserLogin:user.login password:user.password successBlock:^(QBResponse * _Nonnull response, QBUUser * _Nullable user) {
NSLog(@"Logged in");
[weakSelf registerForRemoteNotifications];
[AppDelegate appDelegate].currentUser = user;
user.password = password;
[QBChat.instance connectWithUser:user completion:^(NSError * _Nullable error) {
if (QBChat.instance.isConnected) {
NSLog(@"chat is connected");
}
else{
NSLog(@"chat not connected");
}
isConnecting = NO;
}];
} errorBlock:^(QBResponse * _Nonnull response) {
// Handle error here
NSLog(@"Unable to connect");
isConnecting = NO;
}];
}
- (void)registerForRemoteNotifications{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
else{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
}
#else
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
#endif
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
NSString *deviceIdentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
QBMSubscription *subscription = [QBMSubscription subscription];
subscription.notificationChannel = QBMNotificationChannelAPNS;
subscription.deviceUDID = deviceIdentifier;
subscription.deviceToken = deviceToken;
[QBRequest createSubscription:subscription successBlock:^(QBResponse *response, NSArray *objects) {
//Subscription Successfull
NSLog(@"Subscription Successfull.");
} errorBlock:^(QBResponse *response) {
//Subscription Failure
}];
}
Create Subscription success response is as follow:
[QBResponse], status: 201
Code to send push notification from JavaScript is as follows:
var pushCustomParams = {
message: 'Message received from Bob',
ios_badge: 1,
ios_sound: 'mysound.wav', //Sound File name
user_id: '234', //Caller User ID
}
var params = {
notification_type: 'push',
user: {ids: [110678]}, // recipients.
environment: 'development', // environment, can be 'production' as well.
message: QB.pushnotifications.base64Encode(JSON.stringify(pushCustomParams))
};
QB.pushnotifications.events.create(params, function(err, response) {
if (err) {
console.log(err);
} else {
// success
}
});
On creation on event I get an error all the time:
[EventsProxy] create Object { notification_type:"push", user:Object,environment:"development",message:"ey....."}
[ServiceProxy] Request: POST Object {data:"{"url":"https://api.quickblox.com/e.."}
[ServiceProxy] ajax error 401 Unauthorized {"errors" : ["Token is required"]}
Object {code:401, status:"error", message:"Unauthorized", detail:"{errors"["Token is required"]}"}
Please suggest me what I am doing wrong in the code.
A: In order to send a push you have to act as a user
To do this you have to create a session with user
so your code should be like that:
var params = {login: 'garry', password: 'garry5santos'};
QB.createSession(params, function(err, result) {
if(!err){
// send a push code
}
});
| |
doc_23532225
|
Is there a way to adjust the following code so that I don't have to have those empty lines?
def bfield(self):
self.n=0
for i in self.whole:
for j in i:
print("{:>4}".format(j), end='')
self.n=self.n+1
if self.n==len(i):
print('\n')
self.n=0
A: I'll agree with Rahul Chowdhury, remove the \n. Pythons print command, by default, will always start a new line after each print call. Hence your addition of '\n' will always result in an empty line.
If you wanted to look into how to get around the whole newline thing python does (every call in its own line), I found this link for you. It is fairly simple to do!
EDIT: It just occurred to me I should maybe list a few of the options just in case the link goes down. Here is one example:
print("Hello ", end = '')
print("World!")
With this, you overwrite the usual python lineend with your end = '' argument.
Another option would be to use the sys library
import sys
and then call the stdout.write() function, like so:
sys.stdout.write("Hello ")
sys.stdout.write("World!")
| |
doc_23532226
|
I am able to git clone --recursive [HTTP]. But when I try to access the cloned directory through Mobaxterm's SSH Browser (I can access it with 'cd', but not by clicking on it in the SSH Browser), it returns 'SFTP error #3: Permission denied'.
I tried copying the specific file I want to download into an accessible directory, but when I try to download it I get 'Error #3: Permission denied' and 'Error #2: No such file'.
Can someone help me be able to download from the cloned repo? Thank you!
| |
doc_23532227
|
I am trying to pass a Value for a graph in jQuery.
The value that I have to pass is something like
var hours = [
["Jan", 1],
["Feb", 2],
["Mar", 3]
];
In graph this hours is passed to data
var plot_statistics = jQuery.plot($("#site_stat"), [{
data: hours,
label: "Hours Lost"
}]);
I tried to do this using HashMap , but i didn't got the desired output.
final HashMap<String, Number> columnMap = new HashMap<String, Number>();
columnMap.put("jan", num);
Gson gson = new Gson();
gson.toJson(columnMap);
Please Help me to resolve this
A: [] is a list in JSON, so your prototype has a list of lists. From that description, what you want is List<List<Object>>.
List<List<Object>> outer = new ArrayList<>();
List<Object> inner = new ArrayList<>();
inner.add("Jan");
inner.add(1);
outer.add(inner);
inner = new ArrayList<>();
inner.add("Feb");
inner.add(2);
outer.add(inner);
inner = new ArrayList<>();
inner.add("Mar");
inner.add(3);
outer.add(inner);
Gson gson = new Gson();
gson.toJson(outer);
| |
doc_23532228
|
aws cloudformation create-stack --stack-name iam-stack --template-body file://./iam.yml --capabilities CAPABILITY_IAM --profile dev
An error occurred (InsufficientCapabilitiesException) when calling the CreateStack operation: Requires capabilities : [CAPABILITY_NAMED_IAM]
A: Change --capabilities to CAPABILITY_NAMED_IAM
If you have IAM resources with custom names, you must specify
CAPABILITY_NAMED_IAM. If you don't specify this parameter, this action
returns an InsufficientCapabilities error.
https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStack.html
A: As per AWS docs,
If you specify a Role name in cloud formation, you must specify the CAPABILITY_NAMED_IAM value to acknowledge your template's capabilities Link
So your command should be
aws cloudformation create-stack --stack-name iam-stack --template-body file://./iam.yml --capabilities CAPABILITY_NAMED_IAM --profile dev
A: In my case I needed both CAPABILITY_IAM and CAPABILITY_NAMED_IAM capabilities for a resource of type "AWS::IAM::Role".
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudFormation.html#createStack-property
A: If you are using AWS CodePipeline to deploy an EC2 using a CloudFormation stack, there is an option called "Capabilities" from which you can select CAPABILITY_NAMED_IAM.
A: You must pass capability as below if you're not letting CloudFormation name your IAM resources.
Change from --capabilities CAPABILITY_IAM to --capabilities CAPABILITY_NAMED_IAM.
| |
doc_23532229
|
And its say's to change to android:screenOrientation="fullSensor"
Can anyone have any idea what is the reason behind it?
A: In Android studio 3.6.0 i guess they want the user to handle the orientation and encourage developer to use ViewModel stuff. Let me explain screenOrientation in detail
android:screenOrientation="portrait"
will give you error you have to either specify
android:screenOrientation="fullSensor" or android:screenOrientation="unspecified"
fullSensor Means either you have ON the "Rotate off" or not it will change the orientation based on you move the phone
unspecified Means if you have ON the Rotate off then it will stay only in that orientation and if not then it will change the orientation based on you move the phone.
A: To build on Deep Sheth's answer, this is a warning not an error.
As it suggests you set the fullSensor or unspecified in your activity so that the user can use the application in any orientation and provide a great experience in Chrome OS devices.
You can make that warning go away by adding the following to your activity declaration in the manifest: tools:ignore="LockedOrientationActivity"
A: I have used bellow ..
*
*Add manifest file bellow lines ..
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="LockedOrientationActivity">
*manifest file will look like..
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yourpackage"
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="LockedOrientationActivity">
.....
<activity
android:name=".MainActivity"
android:theme="@style/AppTheme.NoActionBar"
android:screenOrientation="portrait"
android:configChanges="orientation|keyboardHidden"/>
</manifest>
| |
doc_23532230
|
Temp Table
Reviewer | Status
---------------------------
Reviewer1 | Under Review
Reviewer2 | Approved
Reviewer3 | Denied
Reviewer4 | Under Review
Desired Result
Reviewer1 | Reviewer2 | Reviewer3 | Reviewer4
------------------------------------------------------------
Under Review | Approved | Denied | Under Review
I've followed this example: Setting column values as column names in the SQL query result
and can get it to work with a pre-defined numbers of rows/values in the temp table, but I will have an undefined number of Reviewers and I can't get the dynamic select version to work because SQL does not have a Group_Contact function.
I've been stuck on this awhile and would appreciate any advice.
A: Perhaps this script will help. As I mentioned above it's using PIVOT with dynamic SQL.
CREATE TABLE Review (Reviewer VARCHAR(100), Status VARCHAR(100))
INSERT INTO Review
VALUES ('Reviewer1','Under Review'),
('Reviewer2','Approved'),
('Reviewer3','Denied'),
('Reviewer4','Under Review'),
('Reviewer5','Denied'),
('Reviewer6','Under Review');
DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N', p.' + QUOTENAME(Name)
FROM (SELECT p.Reviewer AS Name
FROM Review AS p
GROUP BY p.Reviewer) AS x;
SET @sql = N'
SELECT ' + STUFF(@columns, 1, 2, '') + '
FROM
(
SELECT p.Reviewer AS Name, p.Status
FROM Review AS p
) AS j
PIVOT
(
MAX(Status) FOR Name IN ('
+ STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '')
+ ')
) AS p;';
PRINT @sql;
EXEC sp_executesql @sql;
| |
doc_23532231
|
Thanks
A: You want to set the scroll page size, so it calculates the proportional size of the bar given the range and page size. Look at SetScrollInfo and related functions.
| |
doc_23532232
|
Ember-CLI uses tests/index.html and not the usual testem.json config for testing.
Is there any way I can exclude certain files from being built into app.js?
Usecase : I have some js files where I inject some dependencies. These dependencies are different during the testing environment. I would like to ignore these files and inject the dependencies from my test-injectors.
A: I'm answering in the context of an ember application using ember-cli 1.13.8 and ember 2.1.
ember-cli does use testem.json unless you pass another test configuration file via ember test -c path/to/testem.json. Though, not all options from testem.json are integrated into ember-cli's test process.
To exclude trees, checkout:
ember-cli exclude a directory beneath "tests" from being watched by "ember serve"
For ignoring specific files in tests, you can rename files so that they do not match the pattern embedded into ember-cli-test-loader:
https://github.com/ember-cli/ember-cli-test-loader/blob/master/test-loader.js#L38-L40
| |
doc_23532233
|
Object {message: "sqlite3_step failure: NOT NULL constraint failed: items.barcode", code: 6}
Here's my code snippet:
if ($scope.item.itemname && $scope.item.soldby && $scope.item.price) {
var query = "INSERT into items (itemname,category,soldby,price,sku,barcode) VALUES(?,?,?,?,?,?)";
$cordovaSQLite.execute(db, query, [$scope.item.itemname, $scope.item.category, $scope.item.soldby, $scope.item.price, $scope.item.sku, $scope.item.barcode,])
.then(function (result) {
console.log($scope.item.itemname);
console.log($scope.item.category);
console.log($scope.item.soldby);
console.log($scope.item.price);
console.log($scope.item.sku);
console.log("Printing barcode");
console.log($scope.item.barcode);
console.log($scope.item.total);
//ITEM ADDED SUCCESS POPUP STARTS
//ITEM ADDED SUCCESS POPUP ENDS
}, function (error) {
console.log(error);
});
// $scope.item = {
// itemname: $scope.item.itemname,
// };
$state.go('menu.allItems');
}
And here is the code where I created the table:
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS items (id integer primary key AUTOINCREMENT,itemname text ,category text ,soldby text ,price REAL ,quantity REAL ,sku integer ,barcode text,timestamp DATE DEFAULT (datetime('now','localtime')),cashier text,total REAL,receitnumber integer,grandtotal REAL)");
A: CREATE TABLE IF NOT EXISTS does not change anything if a table with the same name already exists, even if it has a different structure.
To ensure that you always get rid of the old table, use:
DROP TABLE IF EXISTS items;
CREATE TABLE items ( [...] );
This also deletes all old data. If you want to update the table definition but keep the old data, you have to use a temporary table to do the conversion.
| |
doc_23532234
|
Let our code be:
func Spinner(delay time.Duration) {
for !StopSpinner{
for _, r := range `-\|/` {
fmt.Printf("\r%c", r)
time.Sleep(delay)
}
}
}
The problem is - how to remove animation, when there is no need in it from the console screen.
I tried escape sequences like fmt.Print("\b") or fmt.Printf("\r%s", "") but no result. I can not remove last symbol from screen and it concatenates with next text. How do you erase characters already printed to the console?
A: All you need to do is print a space (0x20) when you are done and that will overwrite the spinner.
ie: fmt.Fprint(os.Stdout, "\r \r") to put the cursor back to beginning of line after the space.
A:
All you need to do is print a space (0x20) when you are done and that
will overwrite the spinner.
ie: fmt.Fprint("\r \r") to put the cursor back to beginning of line
after the space.
This answer is helpful, thank you!
But, there is an important detail!
Because the spinner function has a delay, it cannot stop exactly when StopSpinner boolean flag is set to true. So, I have added a channel for synchronization.
func Spinner(delay time.Duration) {
for !StopSpinner {
for _, r := range `-\|/` {
fmt.Printf("\r%c", r)
time.Sleep(delay)
}
}
fmt.Fprint("\r \r")
c <- struct{}{}
}
Now, calling function waits, while my spinner stop.
var c chan struct{} = make(chan struct{}) // event marker
func callingFunc(){
StopSpinner = false
go Spinner(100 * time.Millisecond)
// do something...
StopSpinner = true
<-c // wait spinner stop
//do something else
}
In my opinion, this is the complete solution!
A: fmt.Print("\033[H\033[2J")
This will put the cursor in the top left then clear the console as per this document of useful terminal commands:
https://www.student.cs.uwaterloo.ca/~cs452/terminal.html
| |
doc_23532235
|
( I use nvidia's drivers 470.141.03 )
This is how i setup the virtuals monitors
xrandr --setmonitor DP-0-1 1920/300x1080/170+0+0 DP-0
xrandr --setmonitor DP-0-2 1920/300x1080/170+1920+0 none
xrandr --setmonitor DP-0-3 1920/300x1080/170+0+1080 none
xrandr --setmonitor DP-0-4 1920/300x1080/170+1920+1080 none
And after i can see that the monitors have been created successfully
xrandr --listactivemonitors
Monitors: 4
0: DP-0-1 1920/300x1080/170+0+0 DP-0
1: DP-0-2 1920/300x1080/170+1920+0
2: DP-0-3 1920/300x1080/170+0+1080
3: DP-0-4 1920/300x1080/170+1920+1080
But when i want to maximaze one window, she's take the whole 4k monitor, that is not supposed to happen, she should maximize to one of the 4 virtual screen.
I would be very please if someone that have the same problem could answered me.
| |
doc_23532236
|
pip install tensorflow-gpu
Requirement already satisfied: tensorflow-gpu in /usr/local/lib/python3.5/dist-packages
Requirement already satisfied: wheel>=0.26 in /usr/lib/python3/dist-packages (from tensorflow-gpu)
Requirement already satisfied: six>=1.10.0 in /usr/lib/python3/dist-packages (from tensorflow-gpu)
Requirement already satisfied: numpy>=1.11.0 in /usr/local/lib/python3.5/dist-packages (from tensorflow-gpu)
Requirement already satisfied: protobuf>=3.1.0 in /usr/local/lib/python3.5/dist-packages (from tensorflow-gpu)
Requirement already satisfied: setuptools in /usr/local/lib/python3.5/dist-packages (from protobuf>=3.1.0->tensorflow-gpu)
When I ftry to import tensorflow It says ImportError: No module named tensorflow I am guessing since it is looking in the python 2.7 packages.
Shouldn't it be looking in python 2.7 dist-packges?
A: I would suggest you to use anaconda and run the following command
conda install -c anaconda tensorflow-gpu
*
*Anaconda will make your life easier... hope this helps
This will also install the cuda toolkit and cudnn for you and you are good to go
| |
doc_23532237
|
curl -i http://172.10.2.200
i can get it :
HTTP/1.1 200 OK
Server: nginx/1.20.1
Date: Wed, 10 Aug 2022 03:12:53 GMT
Content-Type: text/html
Content-Length: 4018
Last-Modified: Wed, 10 Aug 2022 00:22:50 GMT
Connection: keep-alive
ETag: "62f2fa5a-fb2"
Accept-Ranges: bytes
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="icon" href="/favicon.ico"><title>title</title><link href="/js/chunk-0429ffa3.c3835ff0.js" rel="prefetch">
.... some elements
</body></html>
but when i visit it in chrome or other browsers, i get 503 error:
and i tried postman, get same result:
my nginx config like this:
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 60000;
gzip on;
gzip_min_length 10k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 5;
gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php application/javascript application/json;
gzip_disable "MSIE [1-6]\.";
gzip_vary on;
server {
listen 80;
proxy_ssl_server_name on;
client_max_body_size 1024M;
location / {
root D:\Path_To_Web\Web;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
}
}
A: i solved it, the culprit is my proxy software,it intercepts my traffic, but doesn't know where this LAN address is
| |
doc_23532238
|
What I did so far : I followed the upgraade instructions on the capacitor page.
https://capacitorjs.com/docs/updating/3-0
The Ionic-Build succeeds, however, when I try to build the solution for my Android device in
the Android Studio (latest version) I got the following error:
(Sorry, I'm not allowed to add pictures right now)
Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
Could not find org.apache.cordova:framework:7.0.0.
Searched in the following locations:
- https://dl.google.com/dl/android/maven2/org/apache/cordova/framework/7.0.0/framework-7.0.0.pom
- https://repo.maven.apache.org/maven2/org/apache/cordova/framework/7.0.0/framework-7.0.0.pom
-file [MY_PATH]/android/capacitor-cordova-android-plugins/src/main/libs/framework-7.0.0.jar
-file:[MY_PATH]/android/capacitor-cordova-android-plugins/src/main/libs/framework.jar
-file:[MY_PATH]/ScannerApp/android/app/libs/framework-7.0.0.jar
-file[MY_PATH]/ScannerApp/android/app/libs/framework.jar
Required by:
project :app > project :capacitor-android
project :app > project :capacitor-cordova-android-plugins
Any help is welcome.
A: Found the solution : in the build.gradle I had to change following section :
(Comment out mawenCentral() and use jcenter() )
allprojects {
repositories {
google()
jcenter()
//mavenCentral()
}
}
| |
doc_23532239
|
In Kate's Tools/Mode/sources menu I select either C++ or ISO C++.
I've coded up a small program the object of which was to fix a deliberate memory leak presented in the previous exercise. Here is my code.
/* Fix the program from Exercise 6. */
#include <iostream>
int myFunction(int * pInt);
int main()
{
int myVar;
int * pInt = new int;
pInt = &myVar;
*pInt = myFunction(&myVar);
std::cout << "The value of myVar is " << *pInt << std::endl;
delete pInt; // Free up pointer.
pInt = 0; // Make pointer safe.
return 0;
}
int myFunction(int * pInt)
{
*pInt = 2;
return *pInt;
}
When I pass this code through g++ the following output is generated.
The value of myVar is 2
munmap_chunk(): invalid pointer
Aborted (core dumped)
However, when the delete instruction is commented out, the following output is generated.
The value of myVar is 2
Given that delete is a standard keyword in C++, why should its use in this code cause a core dump ?
I am at a loss to understand this and would really appreciate any help that can be given.
Best regards,
Stuart
A: In this statement
pInt = &myVar;
you have overwritten the previous value returned by new int and replaced it with a pointer to a local variable. That's why delete crashes (technically, it's undefined behaviour) because operator delete can't free local variables and can only free what's allocated with respective new operator.
When you have reassigned the pointer, you lost access to the one returned by new. This is a memory leak.
| |
doc_23532240
|
Please reply ...
| |
doc_23532241
|
Mark001.xls Mark_001_initial.xls
Mark001_improvement.xls
Mark002.xls
Mark002_initial.
Marc002_Improvement.xls
Pol001.xls
...
Sub Macro1()
Dim FilesToOpen
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="EXLS Files(*.xls), *.xls," & "Mark??? Files (Mark???.xls), Mark???.xls", MultiSelect:=True, Title:="EXLS Files To Open")
End Sub
This opens a window to select files, however there are no files to select,it doesn't identify them
There are also identical files in .txt format, but I only need to open the ones that are of type Mark001.xls, the larger names are irrelevant.
Also I need to copy them to a different folder. I tried to use OpenFile, SerchFile, and selectFile applications but had no success.
Thank you very much!
A: For Application.GetOpenFilename wildcards work only for the file extension as in
FileFilter:="Excel files (*.xl*)," & "*.xl*"
That will return all *.xls and *.xlsx files
Other Options:
Application.FileDialog (msoFileDialogOpen Or msoFileDialogFilePicker)
.
Sub openWildFile() 'use params to make it generic: "ByVal partialName As String"
Const partialName As String = "*Mark_"
Const partialExt As String = "*.xl*"
Dim selectedFile As String, dlg As Object 'A 3rd option is to use APIs
Set dlg = Application.FileDialog(msoFileDialogOpen) 'Or (msoFileDialogFilePicker)
With dlg
.Title = "Select " & partialName & " File"
With .Filters
.Clear
.Add partialName & " Files", partialExt
End With
.AllowMultiSelect = True
.InitialFileName = partialName & partialExt
If (.Show <> 0) Then selectedFile = Trim(.SelectedItems.Item(1))
End With
End Sub
.
To copy files use this:
FileCopy SourceFile, DestinationFile ' Copy source file to target
| |
doc_23532242
|
As you can see in the code i have tried to connect it with the code.
<script src="Login.js"></script>
Here is the html code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>kjedelig AF</title>
<link rel="stylesheet" href="Login.css">
</head>
<body oncontextmenu="return false;">
<form class="box" action="Login.html" method="post" name="login">
<div class="login">
<h1>Kjedelig AF</h1>
<input type="text" name="usrname" placeholder="Username">
<input type="password" name="pswrd" placeholder="Password">
<input type="submit" onclick="return check(this.form)" value="Login">
</div>
</form>
<script src="Login.js"></script>
</body>
</html>
And here is my javascript code witch i have problems connecting to the html code:
<script language="javascript">
function check(form){
if(form.usrname.value == "dd" && form.pswrd.value == "dd") {
window.location.href= "Main.html";
return false;
}
else
{
alert("Iks dette er kjedelig AF :)")
}
return true;
}
</script>
A: First of all, include your JS file at the <head>. there is no good reason not to.
To fix your issue remove <script language="javascript"></script> from your .js file
you should use <script language="javascript"></script> when inside .html file not .js
A: Two reasons:
*
*The script link to the JS file should be anywhere within the
<head></head> tags
*The JS file shouldn't have the <script language="javascript"></script>, all that the JS file needs to have is:
function check(form){
if(form.usrname.value == "dd" && form.pswrd.value == "dd") {
window.location.href= "Main.html";
return false;
}
else
{
alert("Iks dette er kjedelig AF :)")
}
return true;
}
Hope this helps.
| |
doc_23532243
|
Price column / Alias C1 / data [100000, 600000, 800000, 200000 ...]
example ==> (C1>700000?0.5:2)*20 > 20 AND C1 <80000"
I input example text equation at textarea control.
When entering a example and clicking a button, I want to extract only a specific line.
I want to show only the results that correspond to the expression.
so, How can I convert a textual representation of a search expression to something that can be executed in Java?
| |
doc_23532244
|
{"102":{"customerName":"asfd","address":"","orderList":{"3":{"8":1,"6":1}}},"103":{"customerName":"hose","address":"Road Jamica Queens","orderList":{"4":{"15":1}}}}
However when access the same webservice from android I am getting a Java exception.
Unexpected token (position:TEXT {"102":{"custome...@1:194 in java.io.InputStreamReader@29041cbd)
Also the responsedump is adding XML to the end and thus causing the issue.
responseDump:{"102":{"customerName":"asfd","address":"","orderList":{"3":{"8":1,"6":1}}},"103":{"customerName":"hose","address":"Road Jamica Queens","orderList":{"4":{"15":1}}}}<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><getInvoicesResponse xmlns="http://tempuri.org/" /></soap:Body></soap:Envelope>
public class webServiecHandler extends AsyncTask<String, Void, String> {
/**
* Variable Decleration................
*
*/
String namespace = "http://tempuri.org/";
private String url = "http://sample/WebService1.asmx";
String SOAP_ACTION;
SoapObject request = null, objMessages = null;
SoapSerializationEnvelope envelope;
/**
* Set Envelope
*/
protected void SetEnvelope() {
try {
// Creating SOAP envelope
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//You can comment that line if your web service is not .NET one.
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
} catch (Exception e) {
System.out.println("Soap Exception---->>>" + e.toString());
}
}
public String doInBackground(String ... params)
{
try {
SOAP_ACTION = namespace + "getInvoices";
//Adding values to request object
request = new SoapObject(namespace, "getInvoices");
HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
SetEnvelope();
try {
//SOAP calling webservice
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
String result = "";
return result;
} catch (Exception e) {
Log.d("returnedClass", e.getMessage());
return e.toString();
}
} catch (Exception e) {
// TODO: handle exception
return e.toString();
}
}
/************************************/
}
| |
doc_23532245
|
I just want to include different repos into my repo like this
website/
libs/
js/
fs-slides [external]
fs-dialog [external]
and have to possibility to update those repos easily. As far as I understand there is no easy possibility of including just one file from a repo, right? (But that's okay.)
Should I use submodules for this?
Or are there any problems with it? Or is subtree much easier?
A: Submodule is well-suited to your case, especially since you don't mind included those subrepos in their own subdirectory.
The main serious issue you could have using submodules is when updating them while having updates in progress, as described in "how exactly does git submodule work":
If you forget to set a branch when making commits in a submodules, said commits will be made on a detached HEAD, and those changes in progress will be lost at the next git submodule update (you can get them back through the reflog, if activated for your submodule repo).
Then, as Michael comments, and as I detail in the link above, you need to push the submodule to its own upstream before commit and pushing the parent repo (to avoid pushing unpublish submodule commits)
| |
doc_23532246
|
A: This is currently not possible. However, to pass project-specific sbt command line parameters to sbt you may place a .sbtopts in your project directory, and likewise a .jvmopts for VM parameters.
| |
doc_23532247
|
For some reason with these settings the grey border around test in div extends all the way to the left of the parent div when I need it to just go around the text like it does in FF or Chrome. By the way, I hate IE7 for this crap. The markup is totaly logical and should work but IE7 just has to be a jerk.
<div style="width: 200px;">
<div style=" height: 400px; border: 1px solid #000000;">
</div>
<div style="border: 1px solid #c0c0c0; position: relative; height:15px; bottom: 19px; left: -2px; float:right;">
<div style="height: 15px; float: right;">
Text in div</div>
</div>
</div>
A: IE7 is kind of dumb. You may need to give the DIV an explicit width, so that IE7 doesn't get lost without it.
A: You could switch to using position: relative/position: absolute:
http://jsfiddle.net/5fdcV/
<div style="width: 200px; position: relative">
<div style=" height: 400px; border: 1px solid #000000;">
</div>
<div style="border: 1px solid #c0c0c0; position: absolute; height:15px; bottom: 2px; right: 2px;">
<div style="height: 15px;">
Text in div</div>
</div>
</div>
| |
doc_23532248
|
n=0
while [ $n -le 12 ]
do
ssh compute-0-$n
#evaluate the f(x) for the x values that I want
exit
n=$(($n+1))
done
But this did not work because whenever I used the ssh compute-0-$n command to jump to a node the connection to the original shell script seemed to cease, when I would exit the node, the shell script seemed to continue along its merry way... I suppose there is a better way to accomplish this, but I am relatively new to this, can anyone help?
A: The first thing to understand is that when you run ssh (without the &), ssh itself runs until completion. It opens up a new shell on the remote host, and reads commands -- but not the commands from the script that launched it. The ssh session has no knowledge of the script that launched it; it's waiting for commands from stdin.
You need to do three things:
*
*Take all the code from inside your loop after the ssh line, and put
it into its own script (call it docompute.sh).
*Put that script on
each compute node, in a directory in the $PATH variable of the
executing user, and
*in the parent script, replace everything in the
loop with ssh compute-0-$n docompute.sh &. The & will get you
the parallelism you want, by running the ssh process in the
background.
See running same script over many machines for discussion of something quite similar. The use of & to run the command in the background is key there.
A: GNU Parallel is made for exactly this kind of tasks.
evaluate_f() {
x="$1"
# do some crazy computation
}
seq 48 | env_parallel --env evaluate_f -Snode{1..12} evaluate_f {}
If the machines are not really called node1 .. node12, then is becomes a bit longer:
seq 48 | env_parallel --env evaluate_f -Snode1,nodeb,nodeIII,node0100,node0x5,node6,nodeg,nodeVIII,node01001,node0xa,node11,nodel evaluate_f {}
If you have the nodes in a file:
seq 48 | env_parallel --env evaluate_f --slf my_nodefile evaluate_f {}
What this does is to copy the function evaluate_f to the remote servers and run it there with one argument from seq 48. By default it will run one job per cpu-core in the servers. This makes sense if your computation is not multithreaded and does not have a lot of disk I/O. This can be changed with --jobs.
env_parallel was introduced in version 20160322, so make sure your version is newer than that.
GNU Parallel is a general parallelizer and makes is easy to run jobs in parallel on the same machine or on multiple machines you have ssh access to.
If you have 32 different jobs you want to run on 4 CPUs, a straight forward way to parallelize is to run 8 jobs on each CPU:
GNU Parallel instead spawns a new process when one finishes - keeping the CPUs active and thus saving time:
Installation
You should install GNU Parallel with your package manager, but if GNU Parallel is not packaged for your distribution, you can do a personal installation, which does not require root access. It can be done in 10 seconds by doing this:
(wget -O - pi.dk/3 || curl pi.dk/3/ || fetch -o - http://pi.dk/3) | bash
For other installation options see http://git.savannah.gnu.org/cgit/parallel.git/tree/README
Learn more
See more examples: http://www.gnu.org/software/parallel/man.html
Watch the intro videos: https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1
Walk through the tutorial: http://www.gnu.org/software/parallel/parallel_tutorial.html
Sign up for the email list to get support: https://lists.gnu.org/mailman/listinfo/parallel
A: If in ubuntu, you could use odp program.
this program utilize the parallel ssh to run command simultaneously.
user only needed to write their data center configuration and scripts into a config file, then use this program to parallel execute.
here is url:
http://sourceforge.net/projects/odp/
| |
doc_23532249
|
<< User1,User2 >
< rate1,rate2 >>
(the movie Id has been dropped, but there are several records for each couple of users).
I want to see if there is a correlation between two users. Is it possible to apply some sort of correlation by key?
Thanks in advance.
| |
doc_23532250
|
My problem is that the exception (SQLiteDatabaseCorruptException) appears inside the DAO autogenerated java code:
at com.cormorant.fishingtracker.database.DBDao_Impl$234.compute(DBDao_Impl.java:10024)
So I can't try-catch it! It occurs inside AsyncTask but the exception was not captured! I have tried:
protected void openDatabase(OnOpenDatabaseResult onOpenDatabaseResult) {
dataRepository.openDatabase(getApplication());
try {
dataRepository.getRecordsCount(null, new DataRepository.AsyncResponse<Long>() {
@Override
public void processFinish(Long output) {
onOpenDatabaseResult.onResult(output!=null);
}
});
} catch (Exception exception) {
exception.printStackTrace();
onOpenDatabaseResult.onResult(false);
}
}
And also inside the AsyncTask:
public class getRecordsCountAsyncTask extends executeOutAsyncTask<Long> {
getRecordsCountAsyncTask(DBDao dao, Class<? extends Base> klass, AsyncResponse<Long> delegate) {
super(dao, klass, delegate);
}
@Override
protected Long newDoInBackground() {
if (mClass== null) {
Long ret;
try {
ret = mAsyncTaskDao.countTables();
} catch (Exception exception) {
ret =null;
exception.printStackTrace();
}
return ret;
}
...
How to detect the corrupted file when opening the database (code below)?
public static DBRoom getDatabase(final Context context) {
context_ = context;
if (INSTANCE == null) {
synchronized (DBRoom.class) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
DBRoom.class, dbFileName)
.addMigrations(MIGRATION_1_2,MIGRATION_2_3,MIGRATION_3_4,MIGRATION_4_5)
.fallbackToDestructiveMigration() // Wipes and rebuilds instead of migrating if no Migration object.
.addCallback(sRoomDatabaseCallback)
.build();
}
}
return INSTANCE;
}
The entire log:
04-28 11:20:44.218 12854-12879/com.cormorant.fishingtracker E/SQLiteLog: (26) file is encrypted or is not a database
04-28 11:20:44.219 12854-12879/com.cormorant.fishingtracker E/SQLiteLog: (26) file is encrypted or is not a database
04-28 11:20:44.219 12854-12879/com.cormorant.fishingtracker E/SQLiteDatabase: Failed to open database '/data/user/0/com.cormorant.fishingtracker/databases/fishingtracker'.
android.database.sqlite.SQLiteDatabaseCorruptException: file is encrypted or is not a database (code 26): , while compiling: PRAGMA journal_mode
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.executeForString(SQLiteConnection.java:632)
at android.database.sqlite.SQLiteConnection.setJournalMode(SQLiteConnection.java:318)
at android.database.sqlite.SQLiteConnection.setWalModeFromConfiguration(SQLiteConnection.java:289)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:213)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:191)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:794)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:571)
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:269)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:96)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:54)
at androidx.room.RoomDatabase.query(RoomDatabase.java:238)
at com.cormorant.fishingtracker.database.DBDao_Impl$209.compute(DBDao_Impl.java:8046)
at com.cormorant.fishingtracker.database.DBDao_Impl$209.compute(DBDao_Impl.java:8032)
at androidx.lifecycle.ComputableLiveData$2.run(ComputableLiveData.java:101)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
04-28 11:20:44.222 12854-12881/com.cormorant.fishingtracker E/SQLiteLog: (26) file is encrypted or is not a database
04-28 11:20:44.223 12854-12881/com.cormorant.fishingtracker E/SQLiteLog: (26) file is encrypted or is not a database
--------- beginning of crash
04-28 11:20:44.224 12854-12879/com.cormorant.fishingtracker E/AndroidRuntime: FATAL EXCEPTION: arch_disk_io_0
Process: com.cormorant.fishingtracker, PID: 12854
android.database.sqlite.SQLiteDatabaseCorruptException: file is encrypted or is not a database (code 26): , while compiling: PRAGMA journal_mode
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.executeForString(SQLiteConnection.java:632)
at android.database.sqlite.SQLiteConnection.setJournalMode(SQLiteConnection.java:318)
at android.database.sqlite.SQLiteConnection.setWalModeFromConfiguration(SQLiteConnection.java:289)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:213)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:191)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:794)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:571)
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:269)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:96)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:54)
at androidx.room.RoomDatabase.query(RoomDatabase.java:238)
at com.cormorant.fishingtracker.database.DBDao_Impl$209.compute(DBDao_Impl.java:8046)
at com.cormorant.fishingtracker.database.DBDao_Impl$209.compute(DBDao_Impl.java:8032)
at androidx.lifecycle.ComputableLiveData$2.run(ComputableLiveData.java:101)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
04-28 11:20:44.228 12854-12881/? E/SQLiteDatabase: Failed to open database '/data/user/0/com.cormorant.fishingtracker/databases/fishingtracker'.
android.database.sqlite.SQLiteDatabaseCorruptException: file is encrypted or is not a database (code 26): , while compiling: PRAGMA journal_mode
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.executeForString(SQLiteConnection.java:632)
at android.database.sqlite.SQLiteConnection.setJournalMode(SQLiteConnection.java:318)
at android.database.sqlite.SQLiteConnection.setWalModeFromConfiguration(SQLiteConnection.java:289)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:213)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:191)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:794)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:571)
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:269)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:96)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:54)
at androidx.room.RoomDatabase.query(RoomDatabase.java:238)
at com.cormorant.fishingtracker.database.DBDao_Impl$217.compute(DBDao_Impl.java:8772)
at com.cormorant.fishingtracker.database.DBDao_Impl$217.compute(DBDao_Impl.java:8758)
at androidx.lifecycle.ComputableLiveData$2.run(ComputableLiveData.java:101)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
04-28 11:20:44.229 12854-12880/? E/SQLiteLog: (26) file is encrypted or is not a database
04-28 11:20:44.229 12854-12880/? E/SQLiteLog: (26) file is encrypted or is not a database
04-28 11:20:44.235 12854-12881/? I/Process: Sending signal. PID: 12854 SIG: 9
| |
doc_23532251
|
Hello guys.
I want to design an arc similar first rectangle (red one).
As you see result in green rectangle. I try to use border-radius in CSS and I did not get a good result.
border-bottom-right-radius: 5em;
border-top-right-radius: 5em;
I desire a arc like first rectangle.
thanks.
A: As Quentin alluded to, you can get whatever exact shape you want with an SVG. But depending on your case, that might be overcomplicating things a bit.
You can get a shape pretty similar to your screenshot just by using a double border radius.
div {
width: 100px;
height: 200px;
background-color: red;
border-top-right-radius: 30px 50%;
border-bottom-right-radius: 30px 50%;
}
<div></div>
As Envision mentioned, you can also use clip-path to achieve something like this, but browser support for that is poor right now.
| |
doc_23532252
|
$ git remote -v
origin git@bitbucket.org:***/***.git (fetch)
origin git@bitbucket.org:***/***.git (push)
vsts ssh://***@vs-ssh.visualstudio.com:***/DefaultCollection/***/_ssh/*** (fetch)
vsts ssh://***@vs-ssh.visualstudio.com:***/DefaultCollection/***/_ssh/*** (push)
I'm trying to check out a new branch from vsts. It's called release/1.4.1. I'm on Git 2.16.x, so I should be able to use git checkout, but this is what happens:
$ git checkout release/1.4.1
error: pathspec 'release/1.4.1' did not match any file(s) known to git.
I think maybe it's assuming I meant origin. So I try this:
$ git checkout vsts/release/1.4.1
error: pathspec 'vsts/release/1.4.1' did not match any file(s) known to git.
I should make sure git can find the branch. So I use git ls-remote to get a list of remote branches:
$ git ls-remote vsts
...
abcde*** refs/heads/release/1.4.1
...
I get a list of branches and commit hashes, and release/1.4.1 is definitely one of them.
I try a few more things:
$ git checkout -b release/1.4.1 vsts/release/1.4.1
fatal: 'vsts/release/1.4.1' is not a commit and a branch 'release/1.4.1' cannot be created from it
$ git fetch vsts release/1.4.1
From ssh://vs-ssh.visualstudio.com:***/DefaultCollection/***/_ssh/***
* branch release/1.4.1 -> FETCH_HEAD
(After this command, I try all the previous ones again. The results are unchanged.)
$ git checkout -b release/1.4.1 remotes/vsts/release/1.4.1
fatal: 'remotes/vsts/release/1.4.1' is not a commit and a branch 'release/1.4.1' cannot be created from it
$ git checkout -b release/1.4.1 remotes/vsts/refs/heads/release/1.4.1
fatal: 'remotes/vsts/refs/heads/release/1.4.1' is not a commit and a branch 'release/1.4.1' cannot be created from it
If I try git pull vsts/release/1.4.1 it successfully merges the remote branch release/1.4.1 into the current branch, but that's not a useful workaround here.
What else can I try? I don't understand why I can't check out the remote branch.
A: The problem was that my local git config was messed up. I used git config --local -e to open it in vim and found this section:
[remote "vsts"]
url = ssh://***@vs-ssh.visualstudio.com:***/DefaultCollection/***/_ssh/***
fetch = +refs/heads/dev:refs/remotes/vsts/dev
Which looks like it's only set up to fetch dev. I don't know how it got that way, but I changed it to the following:
[remote "vsts"]
url = ssh://***@vs-ssh.visualstudio.com:***/DefaultCollection/***/_ssh/***
fetch = +refs/heads/*:refs/remotes/vsts/*
After which I'm able to do this:
$ git checkout release/1.4.1
Switched to a new branch 'release/1.4.1'
Branch 'release/1.4.1' set up to track remote branch 'release/1.4.1' from 'vsts'.
| |
doc_23532253
|
A: You have to put in the env file (/.env) the variable regarding the application name named DB_APPLICATION_NAME = ;
And you have to specify the following:
Form Laravel version 5.5 you can add this row to the file /config/database.php at the bottom of the postgresql connection.
'application_name' => env('DB_APPLICATION_NAME', 'Laravel')
If you don't specify the app name in the .env file the application name will be taken from /config/database.php file.
| |
doc_23532254
|
DELIMITER $$
CREATE ` PROCEDURE `vaars_test_latest`.`geterpdata`(IN applicant_id VARCHAR(255))
BEGIN
SELECT
t2.start_date AS date_from_ad,
t2.end_date AS date_to_ad,
t1.job_id,
t1.org_id,
t1.seniority_date_bs AS seniority_date_bs,
t1.seniority_Date AS seniority_date_ad,
t5.name_en AS working_office,
t5.id AS working_office_id,
t7.name_en AS designation,
t7.id AS designation_id,
t8.name_en AS service_group,
t8.id AS service_group_id,
t9.name_en AS work_level,
t9.id AS work_level_id,
CASE
WHEN t1.incharge = 1 THEN 'YES'
ELSE 'NO'
END AS is_office_incharge,
CASE
WHEN t1.incharge = 1 THEN t1.start_date
ELSE NULL
END AS incharge_date_from_ad,
CASE
WHEN t1.incharge = 1 THEN t1.end_date
ELSE NULL
END AS incharge_date_to_ad
FROM
erp_service_history t1
LEFT JOIN
temp1 t2
ON t1.emp_no = t2.emp_no
AND t1.job_id = t2.job_id
AND t1.org_id = t2.org_id
INNER JOIN
applicant_profile t4
ON t4.nt_staff_code = t1.emp_no
LEFT JOIN
erp_organization t3
ON t3.id = t1.org_id
LEFT JOIN
mst_working_office t5
ON t5.id = t3.working_office_id
LEFT JOIN
erp_jobs t6
ON t6.id = t1.job_id
LEFT JOIN
mst_designation t7
ON t7.id = t6.designation_id
LEFT JOIN
mst_work_service_group t8
ON t8.id = t6.service_group_id
LEFT JOIN
mst_work_level t9
ON t9.name_en = t1.grade
WHERE
t1.seniority_Date = t2.seniority_Date AND t4.id = applicant_id
ORDER BY
t2.start_date DESC ;
END$$
DELIMITER ;
and it throws following exception:
Query execution failed
Reason:
SQL Error [1064] [42000]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 61
On the line 61 is the ordery by line, please help.
| |
doc_23532255
|
<script type="text/javascript">
//var minutes2 = currentTime.setMinutes(currentTime.getMinutes() + 30);
function addMinutes(date, minutes) {
return new Date(date.getTime() + minutes*60000);
}
var dat = new Date();
//var tim = addMinutes(dat, 15);
//console.log(tim);
function fixIntegers(integer)
{
if (integer < 0)
integer = 0;
if (integer < 10)
return "0" + integer;
return "" + integer;
}
$(function () {
$('.btn-start-timer').click(function(){
var i = window.setInterval(function(){
var future = addMinutes(dat, 60);
//var future = new Date("Dec 12 2013 22:10:00 GMT-0800 (Pacific Standard Time) ");
var now = new Date();
//console.log(tim);
var difference = Math.floor((future.getTime() - now.getTime()) / 1000);
var seconds = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var minutes = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var hours = fixIntegers(difference % 24);
difference = Math.floor(difference / 24);
var days = difference;
/* $(this).parent().parent().find('.timer #seconds').text(seconds + "s");
$(this).parent().parent().find('.timer #minutes').text(minutes + "m");
$(this).parent().parent().find('.timer #hours').text(hours + "h");
$(this).parent().parent().find('.timer #days').text(days + "d");*/
$(".timer #seconds").text(seconds + "s");
$(".timer #minutes").text(minutes + "m");
$(".timer #hours").text(hours + "h");
$(".timer #days").text(days + "d");
if(hours == 0 && minutes == 0 && seconds == 0){
window.clearInterval( i );
alert('times up');
}
}, 1000);
});
});
</script>
And here is my the html:
<table cellpadding="10">
<tr>
<th>Timer</th>
<th> </th>
</tr>
<tr>
<td class="timer">
<span id="days"></span>
<span id="hours"></span>
<span id="minutes"></span>
<span id="seconds"></span>
</td>
<td><button type="button" class="btn-start-timer">Start Now</button></td>
</tr>
<tr>
<td class="timer">
<span id="days"></span>
<span id="hours"></span>
<span id="minutes"></span>
<span id="seconds"></span>
</td>
<td><button type="button" class="btn-start-timer">Start Now</button></td>
</tr>
</table>
How can I make the time not to reset once it is started?
A: Use the event :
onbeforeunload
To detect when your user leave your page. Then, send an ajax request. To handle your request, you simply want to save whatever information in a $_SESSION variable in posted.php.
// posted.php
session_start();
if ( isset ( $_POST['hours'] && isset ( $_POST['minutes'] && isset ( $_POST['seconds'] && )
{
$_SESSION['hours'] = $_POST['hours'];
$_SESSION['minutes'] = $_POST['minutes'];
$_SESSION['seconds'] = $_POST['seconds'];
}
Then when your new page load / refresh you should have in your javascript your variable that are initialized.
var hours = <?php if ( isset($_SESSION['hours']) ) echo $_SESSION['hours'] else 0; ?>;
var minutes = <?php if ( isset($_SESSION['minutes']) ) echo $_SESSION['minutes'] else 0; ?>;
var seconds = <?php if ( isset($_SESSION['seconds ']) ) echo $_SESSION['seconds '] else 0; ?>;
Now understand that this is a shot in the dark since I have 0 idea about the way your application is built. If you're using some kind of framework it might not be that easy but if you're programming something small or procedural, then this will fit your needs.
EDIT:
I understand that you have multiple timer, instead of using
$_SESSION['hours']
use
$_SESSION['idOfTimer']['hours']
Each timer will have his own timer.
A: Save the hour, minute, sec in $_SESSION or $_COOKIE['time'] or localStorage
and then retrieve the value from that.
| |
doc_23532256
|
As I just want to obtain a simple command-line tool with no UI graphics, I'm trying to keep minimum dependence on Apple's high-level interface frameworks.
My Python code looks a bit like that:
from PIL import Image
import numpy
# Load a 16bit grayscale image and convert it to raw data array
img = Image.open("mylocaldir/Gray16.png")
(sizex,sizey) = img.size
inputpix = numpy.array(img.getdata()).astype(numpy.uint16).reshape((sizey,sizex))
# Here, do whatever processing to fill a RGB raw data array.
outputpix = numpy.zeros((sizey,sizex,3),numpy.uint8)
# ...
# ...
# ...
# Write the array back as a jpg file
img = Image.frombytes("RGB",(sizex,sizey),outputpix.reshape(sizex*sizey*3),"raw")
img.save("mylocaldir/OutputRGB.jpg")
Not so familiar with Apple's frameworks, I am struggling to figure out how to implement that in a way as simple as possible. Should a CGImage be used? Or is there any simpler object allowing image file I/O?
Could anybody help me getting the most streamlined Swift version of the Python code written above?
A: Here is what I came up for loading or saving png images from a UInt16 array of predefined size, only using CoreGraphics.
Sorry, as a Swift beginner with a C++ background, I might not organise my code in the best way!
func LoadPNG(pixels: inout [UInt16], sizx: Int, sizy: Int, name: String) -> Bool {
if FileManager.default.fileExists(atPath: name) {
let data : Data? = try? Data(contentsOf: URL(fileURLWithPath: name, isDirectory: false))
if data != nil {
if let cgprovider = CGDataProvider(data: data! as CFData) {
if let cgimg = CGImage(pngDataProviderSource: cgprovider, decode: nil, shouldInterpolate: false, intent: .defaultIntent) {
if (cgimg.width, cgimg.height, cgimg.bitsPerComponent, cgimg.bitsPerComponent) == (sizx, sizy, 16, 16) {
let cgspace = CGColorSpaceCreateDeviceGray()
let cgcontext = CGContext(data: &pixels, width: sizx, height: sizy, bitsPerComponent: cgimg.bitsPerComponent, bytesPerRow: cgimg.bytesPerRow, space: cgspace, bitmapInfo: cgimg.bitmapInfo.rawValue)
cgcontext?.draw(cgimg, in: CGRect(x: 0.0, y: 0.0, width: CGFloat(sizx), height: CGFloat(sizy)))
return true
}
}
}
}
}
return false
}
func SavePNG(pixels: inout [UInt16], sizx: Int, sizy: Int, name: String) -> Bool {
if let cgprovider = CGDataProvider(data: NSData(bytes:&pixels, length: MemoryLayout<UInt16>.size*pixels.count)) {
let cgspace = CGColorSpaceCreateDeviceGray()
let cginfo = CGBitmapInfo(rawValue:CGImageAlphaInfo.none.rawValue)
if let cgimg = CGImage(width: sizx, height: sizy, bitsPerComponent: 16, bitsPerPixel: 16, bytesPerRow: MemoryLayout<UInt16>.size*sizx, space: cgspace, bitmapInfo:cginfo, provider: cgprovider, decode: nil, shouldInterpolate: false, intent: .defaultIntent) {
let cfdata: CFMutableData = CFDataCreateMutable(nil, 0)
if let destination = CGImageDestinationCreateWithData(cfdata, kUTTypePNG as CFString, 1, nil) {
CGImageDestinationAddImage(destination, cgimg, nil)
if CGImageDestinationFinalize(destination) {
let data = cfdata as Data
try? data.write(to:URL(fileURLWithPath: name, isDirectory: false))
return true
}
}
}
}
return false
}
Unfortunately, there is a problem with this code: Repeated use will fill up the memory! Is there any resource that should have been manually released?
| |
doc_23532257
|
Each video (or episode) in the site has a unique page and URL. When you load an episode, you have to wait 30 seconds for the episode to "load", and only then the <video> tag appears in the HTML source file.
The problem is that the request for the video is encrypted or secured in one way or another (I don't really understand how it works)! When I try to simply wait for the video tag to appear and then download the video with the urllib library (see code below), I get the following error: urllib.error.HTTPError: HTTP Error 401: Unauthorized
I should note that when I try to open the link of the download video in the selenium driver, it opens completely fine and I can download it manually.
How can I download the videos automatically? Thanks in advance!
Code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import urllib.request
def load(driver, url):
driver.get(url) # open the page in the browser
try:
# wait for the episode to "load"
# if something is wrong and the episode doesn't load after 45 seconds,
# the function will call itself again and try to load again.
continue_btn = WebDriverWait(driver, 45).until(
EC.element_to_be_clickable((By.ID, "proceed"))
)
except:
load(url)
def save_video(driver, filename):
video_element = driver.find_element_by_tag_name(
"video") # get the video element
video_url = video_element.get_property('src') # get the video url
# trying to download the video
urllib.request.urlretrieve(video_url, filename)
# ERROR: "urllib.error.HTTPError: HTTP Error 401: Unauthorized"
def main():
URL = r'https://www.sdarot.dev/watch/339-%D7%94%D7%A4%D7%99%D7%92-%D7%9E%D7%95%D7%AA-ha-pijamot/season/1/episode/23'
DRIVER = webdriver.Chrome()
load(DRIVER, URL)
video_url = save_video(DRIVER, "video.mp4")
if __name__ == "__main__":
main()
A: You are getting unauthorised error because they are using cookies to store some information related to your session. Specifically cookie named Sdarot. I have used requests library to download and save the video.
Main point is when you open the url using selenium it works fine because selenium is using the same http client (the browser) which already has cookie details available, but when you call using urllib basically its different http client so its a new request for the server. To overcome this you will have to behave like the browser by providing enough session information, in this case maintained by cookies.
Check how I have extracted value of Sdarot cookie and applied it in requests.get method. You can do this using urllib also.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import requests
def load(driver, url):
driver.get(url) # open the page in the browser
try:
# wait for the episode to "load"
# if something is wrong and the episode doesn't load after 45 seconds,
# the function will call itself again and try to load again.
continue_btn = WebDriverWait(driver, 45).until(
EC.element_to_be_clickable((By.ID, "proceed"))
)
continue_btn.click()
except:
load(driver,url) #corrected parameter error
def save_video(driver, filename):
video_element = driver.find_element_by_tag_name(
"video") # get the video element
video_url = video_element.get_property('src') # get the video url
cookies = driver.get_cookies()
#iterate all the cookies and extract cookie value named Sdarot
for entry in cookies:
if(entry["name"] == 'Sdarot'):
cookies = dict({entry["name"]:entry["value"]})
#set request with proper cookies
r = requests.get(video_url, cookies=cookies,stream = True)
# start download
with open(filename, 'wb') as f:
for chunk in r.iter_content(chunk_size = 1024*1024):
if chunk:
f.write(chunk)
def main():
URL = r'https://www.sdarot.dev/watch/339-%D7%94%D7%A4%D7%99%D7%92-%D7%9E%D7%95%D7%AA-ha-pijamot/season/1/episode/23'
DRIVER = webdriver.Chrome()
load(DRIVER, URL)
video_url = save_video(DRIVER, "video.mp4")
if __name__ == "__main__":
main()
| |
doc_23532258
|
Host gitlab.com
User git
ProxyCommand nc -x 127.0.0.1:1080 %h %p
and it works but the same config in centos doesn't work. and this is the result:
git pull
Ncat: Connection timed out.
ssh_exchange_identification: Connection closed by remote host
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
Anyway, when I run curl --socks5-hostname 127.0.0.1:1080 icanhazip.com the result is an IPv6.
ssh -xvvv git@gitlab.com
OpenSSH_7.4p1, OpenSSL 1.0.2k-fips 26 Jan 2017
debug1: Reading configuration data /root/.ssh/config
debug1: /root/.ssh/config line 1: Applying options for gitlab.com
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 58: Applying options for *
debug1: Executing proxy command: exec nc -x 127.0.0.1:1080 gitlab.com 22
debug1: permanently_set_uid: 0/0
debug1: permanently_drop_suid: 0
debug1: identity file /root/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.4
Ncat: Connection timed out.
ssh_exchange_identification: Connection closed by remote host
cat /etc/ssh/ssh_config
Host *
GSSAPIAuthentication yes
ForwardX11Trusted yes
SendEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
SendEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
SendEnv LC_IDENTIFICATION LC_ALL LANGUAGE
SendEnv XMODIFIERS
Also I tried proxychains4 -q git pull and it works fine
| |
doc_23532259
|
HTML
<body>
<header>
<div class="logo"></div>
<nav>
<a href="#" title="User"><%= image_tag("new-user-icon.png", class: "user-icon") %></a>
<a href="#" title="About"><%= image_tag("about-icon.png", class: "about-icon") %></a>
<a href="#" title="Contact"><%= image_tag("contact-icon.png", class: "contact-icon") %></a>
<a href="#" title="Main Menu" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<div class="dropdown" >
<%=image_tag("new-menu-icon.png", class: "menu-icon") %>
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuLink">
<a class="dropdown-item" href="#">Assets</a>
<a class="dropdown-item" href="#">Debts</a>
<a class="dropdown-item" href="#">Incomes</a>
<a class="dropdown-item" href="#">Expenses</a>
<a class="dropdown-item" href="#">Transfers</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Account</a>
<a class="dropdown-item" href="#">Log Out</a>
</div>
</div>
</nav>
</header>
...
</body>
CSS (Sass)
header{
display:inline-block;
background: rgb(125,185,232);
background: -moz-linear-gradient(left, rgba(125,185,232,1) 0%,
rgba(32,124,202,1) 0%, rgba(32,124,202,1) 0%, rgba(98,189,234,1) 0%,
rgba(129,202,237,1) 50%, rgba(98,189,234,1) 100%);
background: -webkit-linear-gradient(left, rgba(125,185,232,1) 0%,rgba(32,124,202,1) 0%,rgba(32,124,202,1) 0%,rgba(98,189,234,1) 0%,rgba(129,202,237,1) 50%,rgba(98,189,234,1) 100%);
background: linear-gradient(to right, rgba(125,185,232,1) 0%,rgba(32,124,202,1) 0%,rgba(32,124,202,1) 0%,rgba(98,189,234,1) 0%,rgba(129,202,237,1) 50%,rgba(98,189,234,1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(
startColorstr='#7db9e8', endColorstr='#62bdea',GradientType=1 );
border-bottom: 1px solid $universal-background;
height: 55px;
width: 100%;
float: right;
margin-bottom: 0;
padding: 0;
div.logo{
float: left;
height: 55px;
width: 100px;
background-color: transparent;
background-image: url('https://image.ibb.co/nw64yw/logo_white.png');
}
}
A: Add this CSS
div.logo {
float: left;
height: 55px;
width: 140px;
background-color: transparent;
background-image: url(https://image.ibb.co/nw64yw/logo_white.png);
background-size: 100%;
background-repeat: no-repeat;
background-position: 0px 13px;
}
A: The problem
Your basic problem is that the background-image ignores the dimensions of the container. Since your image file is very big, you can not see anything of it because it is only showing the transparent upper-left corner. Also there are some styles missing which you need to apply to show the background-image appropriate.
What do you need to do?
*
*background-position: center This makes sure that the background-image will be placed centered inside the container.
*background-size: contain This specifies the size of the background images. This property arrived with CSS3 and solved a lot of problems with background images. Your are able to add pixel values or contain / cover. Contain scales the image to the largest size to fit inside the container. Cover scales the image to the largest size to cover the whole container. W3C reference
*background-repeat: no-repeat We only wont to show the image once (obvious).
Code snippet separate properties:
.logo {
background-size: contain;
background-color: transparent;
background-repeat: no-repeat;
background-position: center;
background-image: url('https://image.ibb.co/nw64yw/logo_white.png');
}
Code snippet with shorthand: (W3C reference)
.logo {
background-size: contain;
background-image: transparent url('path_to_image.png') center no-repeat;
}
Live jsFiddle example can be found here
I hope that helps you to understand what went wrong. If you have any additional questions, feel free to ask.
| |
doc_23532260
|
<'.if (get_post_meta($post->ID,"_as_roomtype",true) == 'DE').'>
<a href="'.get_permalink().'" class="readnow" >"---NAME---"</a>
I have values on "meta_value" like "DE", "UK", "SP"
I need to make something like that.
if the value on "meta_value" = "DE" show Germany on "---NAME---"
if the value on "meta_value" = "UK" show United Kingdom on "---NAME---"
if the value on "meta_value" = "SP" show Spain on "---NAME---"
How can I make this?
A: Try something like this:
<?php
$meta_values = array('DE' => 'Germany', 'UK' => 'United Kingdom', 'SP' => 'Spain');
if ($meta_key = get_post_meta($post->ID,"_as_roomtype",true)):
?>
<a href="<?php echo get_permalink() ?>" class="readnow" ><?php echo $meta_values[$meta_key]; ?></a>
| |
doc_23532261
|
http://codepen.io/ssanders/pen/KmJgwK
Important -
You need to have these -
*Safari- Version 10.1.1
*mac os - sierra
.list {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-flow: column wrap;
flex-flow: column wrap;
height: 600px;
}
.item {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
width: 48%;
margin-top: 25px;
min-width: 340px;
}
A: After posting a bug and reaching out to the safari support team, it appears this was a bug specific to version 10.1.1 of safari. It has been fixed in subsequent releases.
| |
doc_23532262
|
I've been looking into OS development a lot lately, and I've found that most, if not all, don't have fully Object Oriented window-application interfaces, Windows included. This is, of course, with the notable exception of bytecode interpreted languages such as C# (or CLI in general) and Java. (To clarify, I mean that they tend to create a window through a function, rather than through the creation of a class).
I can understand the smaller managers made for simplicity, such as tinywm, but even larger window managers like MetaCity, Fluxbox, and Openbox tend to be still not come from objects, but rather functions -- despite some being written in C++ as opposed to pure C (at least, as far as I understand).
This may be a naive question, but why is it done this way?
I understand that it is important to implement a non-object-oriented ABI for languages that do not support object orientation, but why can't it also provide higher-level hooks for languages that DO support object orientation?
Would it not arguably be easier for the programmer in the end to have such hooks, because it would allow easier development of software? Given advances in hardware, would the performance loss not be minimal in comparison to the benefits of how much easier it'd be to develop?
This has just been something that's bugged me for a bit, and I'm hoping that someone will have an answer.
PS: If my understanding is fundamentally wrong somewhere, feel free to correct me.
A: It's not just windowing. There aren't operating systems that have object-oriented APIs in terms of methods called via objects as in myObject->method() or myObject.method(). Most of the ones we're using now have windowing APIs designed in the early 1980s (Windows for example, The X Window System, etc). There are language and ABI issues to consider. The only exception I can think of is OS/2's language-independent OO thing called System Object Model.
Formally speaking there is no difference between method(object, ...) and object.method(...) or object->method(...), just a syntactic difference.
A: I think you may be fundamentally wrong somewhere, but it's an awkward way to say that. :)
Window managers typically are object oriented, but they're not designed around classes and objects as you might find in C++. What you tend to have is something along the lines of:
struct Object {
...
};
void DoSomething(Object* obj, ...);
All of the functions provided by the window manager manipulate the internals of Object, whether that's a button, a window, or some other widget. Most of the time, the programmer is expected to treat those objects opaquely and let the API manage their contents. As a programmer, you're still operating with objects, and methods on those objects. It's just that much of the coupling is broken and it doesn't look like what people expect object oriented programming to look like because the objects are parameters to the functions instead of the functions being properties of the objects.
| |
doc_23532263
|
app state:
class AppState {
final List menuList;
final int currentIndex;
AppState({this.menuList, this.currentIndex});
}
the reducers:
AppState appReducer(AppState state, Object action) {
return AppState(
menuList: menuListReducer(state.menuList, action),
currentIndex: currentIndexReducer(state.currentIndex, action));
}
final menuListReducer = combineReducers<List>(
[TypedReducer<List, SetMenuListAction>(_setMenuList)]);
List _setMenuList(List menuList, SetMenuListAction action) {
menuList = action.menuList;
return menuList;
}
final currentIndexReducer = combineReducers<int>(
[TypedReducer<int, SetCurrentIndexAction>(_setCurrentIndex)]);
int _setCurrentIndex(int currentIndex, SetCurrentIndexAction action) {
currentIndex = action.index;
return currentIndex;
}
the action:
class SetMenuListAction {
List menuList;
SetMenuListAction(this.menuList);
}
class SetCurrentIndexAction {
int index;
SetCurrentIndexAction(this.index);
}
the main logic:
void main() {
final store = Store<AppState>(
appReducer,
initialState: AppState(menuList: [
{
'picUrl': 'http://pic3.16pic.com/00/55/42/16pic_5542988_b.jpg',
'description': 'this is the first image'
},
{
'picUrl': 'http://photo.16pic.com/00/38/88/16pic_3888084_b.jpg',
'description': 'this is the second image'
},
{
'picUrl':
'http://img4.imgtn.bdimg.com/it/u=3434394339,2114652299&fm=214&gp=0.jpg',
'description': 'this is the third image'
},
{
'picUrl': 'http://pic1.win4000.com/pic/2/07/8c57e143b1.jpg',
'description': 'this is the fourth image'
},
], currentIndex: 0),
);
runApp(App(
store: store,
));
}
// App
class App extends StatelessWidget {
final Store<AppState> store;
const App({Key key, this.store}) : super(key: key);
@override
Widget build(BuildContext context) {
return StoreProvider(
store: store,
child: MaterialApp(title: 'Flutter redux example', home: MyDetail()),
);
}
}
class MyDetail extends StatefulWidget {
@override
_MyDetailState createState() => _MyDetailState();
}
class _MyDetailState extends State<MyDetail> with TickerProviderStateMixin {
PageController _controller;
@override
void initState() {
_controller = PageController(initialPage: 0);
super.initState();
}
@override
Widget build(BuildContext context) {
return StoreConnector<AppState, int>(
converter: (store) => store.state.currentIndex,
onDidChange: (newIdx) {
//this won't work because the _controller hasn't been attached to PageView
_controller.jumpToPage(newIdx);
},
builder: (BuildContext context, int idx) {
return StoreConnector<AppState, List>(
converter: (store) => store.state.menuList,
onDidChange: (newList) {
//maybe do something further
},
builder: (BuildContext context, List menus) {
return Container(
color: Colors.white,
child: Column(
children: <Widget>[
//pageview
Expanded(
child: PageView(
children: menus.map((item) {
return Column(
children: <Widget>[
Image.network(item['picUrl']),
Text(
item['description'],
style: TextStyle(fontSize: 24.0),
)
],
);
}).toList(),
onPageChanged: (int index) {
StoreProvider.of<AppState>(context)
.dispatch(SetCurrentIndexAction(index));
},
physics: BouncingScrollPhysics(),
),
),
//indicators
Container(
margin: EdgeInsets.only(bottom: 50.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: menus
.asMap()
.map((i, item) => MapEntry(
i,
GestureDetector(
onTap: () {
//this won't work either maybe because the widgets is rebuilding
_controller.jumpToPage(i);
StoreProvider.of<AppState>(context)
.dispatch(SetCurrentIndexAction(i));
},
child: Container(
width: 10.0,
height: 10.0,
color: i == idx
? Colors.purpleAccent
: Colors.blue,
margin: EdgeInsets.only(right: 10.0),
),
)))
.values
.toList(),
),
)
],
),
);
},
);
},
);
}
}
Sorry for the long code, but I think maybe this can help to understand my problem:
*
*When I tap the indicator, I want to synchronise the PageView, that is _controller.jumpToPage(i), but it will show Errors. So how to make this work?
*I can change the currentIndex in another screen, how to synchronise the PageView?
*Is there any method to watch the state changes(separately, not the whole state) and do something?
A: After debugging your code I found that you are missing controller: _controller in PageView, this should fix it:
Expanded(
child: PageView(
controller: _controller,
children: menus.map((item) {
return Column(
children: <Widget>[
Image.network(item['picUrl']),
Text(
item['description'],
style: TextStyle(fontSize: 24.0),
)
],
);
}).toList(),
onPageChanged: (int index) {
StoreProvider.of<AppState>(context)
.dispatch(SetCurrentIndexAction(index));
},
physics: BouncingScrollPhysics(),
),
),
| |
doc_23532264
|
the source file is different from when the module was built
or the debugger does not go to the line that is faulty.
So I searched stack overflow's Website and found this but none of the suggestions offered worked for me.
I removed Visual Studio and All my extensions then Removed them from regedit.exe(hkcu and hklm) and %Appdata% (local and Roaming). Then I reinstalled everything(new Versions)
*
*Visual studio 2013 update 4
*Resharper(12.0.31101.0)
*Visual Assist 10.9 (2052)
*DevExpress-20140923
Then I noticed This:
As seen on the GIF as soon as I run (F5) the code it looks like something edits the lines. I think that's why I get:
the source file is different from when the module was built
If I look At the Undo List their is two misery Items called "Smart delete"
and when I remove Resharper the bug disappears. I also found this unanswered Question on Resharper
For those three reasons think it's Resharper, but I'm not sure...
I Have found that selecting a entire line, or going to design view stops this behavior,
But that is annoying to do every time i run the project.
What can I do to stop this annoying behavior?
A: Goto:
Tools -> Options -> Text Editor -> C# -> General -> Uncheck Apply Cut or Copy commands to blank lines when there is no selection
| |
doc_23532265
|
Item Name - P2_CHANGE_ENTRY
Created 3 dynamic actions as below -
1. SetValue
JavaScript Expression => this.triggeringElement.value
Affected Elements =>P2_CHANGE_ENTRY
2. Execute PL/SQL Code
PL/SQL Code => null
Items to Submit => P2_CHANGE_ENTRY
Items to Return => null
3. Execute PL/SQL Code
**PL/SQL Code =>**
begin
apex_collection.update_member_attribute (
p_collection_name =>'NEW_COLLECTION',
p_seq =>1,
p_attr_number =>3,
p_attr_value =>:P2_CHANGE_ENTRY);
end;
Items to Submit => P2_CHANGE_ENTRY
Items to Return => null
And in the process am inserting above attribute value in to Database but its inserting value as 'null'. Can you please help me on this.
A: apex_collection.update_member_attribute (
p_collection_name => 'NEW_COLLECTION',
p_seq => '1',
p_attr_number => '3',
p_attr_value => :P2_CHANGE_ENTRY
);
Remember to use single quotes
| |
doc_23532266
|
Is there something I can add to my PWA so it only opens one instance no matter how many link clicks?
Version 76.0.3809.87
| |
doc_23532267
|
gene n
<chr> <int>
CBLB 434
UBAC2;NA;TM9SF2;GPR18;GPR183 434
ATP6V1G3;PTPRC 379
NA;BCAS1 372
I want to split the lines where multiple genes are separated with a ";". So :
gene n
<chr> <int>
CBLB 434
UBAC2 434
NA 434
TM9SF2 434
GPR18 434
GPR183 434
ATP6V1G3 379
PTPRC 379
NA 372
BCAS1 372
I tried this :
hs %>% rowwise() %>% mutate(gene=unlist(strsplit(gene,";")),n=n)
But it gives me :
Error in mutate_impl(.data, dots) :
Column `gene` must be length 1 (the group size), not 3
Any idea ?
here's a reproducible example :
structure(list(gene = c("CBLB", "UBAC2;NA;TM9SF2;GPR18;GPR183",
"ATP6V1G3;PTPRC", "NA;BCAS1", "HINT3;NCOA7", "RALGPS2"), IS = c(434L,
434L, 379L, 372L, 372L, 349L)), .Names = c("gene", "n"), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))
| |
doc_23532268
|
A: You have to specify exactly which columns you wan't displayed.
There is no simple solution where mysql will display only columns that have data in them while using SELECT * FROM TABLE;
| |
doc_23532269
|
Object (... is equal to different values I don't need):
id: '45678',
attributes: {
title: 'This is a title!'
...
},
resources: [
{url: 'www.facebook.com', type: 'social media', ...},
{url: 'www.instagram.com', type: 'social media', ...},
],
...
Let's say I have a component I need to display the value stated above and ignore the rest (...). What's the best practice here?
Do I create a new array, map the old one and solely push a manipulated object with only the data I need? What about typing and creating interfaces in Angular, do I need to cover all objects?
EDIT:
return this.http.get(this.url)
.pipe(
map((a: any) => {
const products = [];
a.items.map(obj => {
products.push({id: obj.id, resources: obj.resources, attributes: obj.attributes});
})
return products;
})
);
A: If you're using the Angular HttpClient you've probably will get an Observable<YOUR_OBJ_TYPE[]>
You can just use the rxjs map operator and then map the array objects, should look something like that:
httpClient.get<YOUR_OBJ_TYPE[]>('URL')
.pipe(map((res:YOUR_OBJ_TYPE[])=> res.map(
(obj: YOUR_OBJ_TYPE) => {
id: obj.id,
attributes: obj.attributes,
resources: obj.resources,
...
})))
| |
doc_23532270
|
shift_group schedule_date
------------------------------
Shift 1 2014-11-22
Shift 1 2014-11-23
Shift 1 2014-11-24
Shift 1 2014-11-25
Shift 1 2014-11-26
Shift 1 2014-11-27
Shift 1 2014-11-28
Shift 1 2014-11-29
Shift 1 2014-11-30
Shift 2 2014-11-25
Shift 2 2014-11-26
Shift 2 2014-11-27
Shift 2 2014-11-28
Shift 2 2014-11-29
Shift 2 2014-11-30
Shift 1 2014-12-01
Shift 1 2014-12-02
Shift 1 2014-12-03
Shift 1 2014-12-04
Shift 1 2014-12-05
Shift 1 2014-12-06
Shift 1 2014-12-07
All I found is DATEDIFF between two date columns. Is there any method to calculate the number of days for every shift? For example:
shift_group month number of days
------------------------------------
Shift 1 11 9
Shift 1 12 7
Shift 2 11 6
A: I think you are trying to get the number of shifts per month.
select shift_group , datepart(month, schedule_date), count(1) from table
group by shift_group , datepart(month, schedule_date)
order by shift_group
| |
doc_23532271
|
X.IncMSE IncNodePurity feature
14 17.047198 16538.30890 RMFSL
16 11.098980 8696.06086 BORROW
2 8.088110 4995.53967 BAA10YM
24 5.847918 1883.49994 DTTHFM
25 5.487581 1277.76421 DTRTM
27 5.171936 1190.90316 IPCONGD
3 4.864875 2822.91257 AAA10YM
11 4.783012 333.98030 TWEXBMTH
34 4.617952 1285.28342 HOUST
10 4.562884 319.38383 MPRIME
My exepcted result will like: "TERMCBAUTO48NS, BAA10YM, AAA10YM, TB3SMFFM, T5YFFM".
Thank you in advance.
A: This will give you the expected output:
paste(df$feature[1:5], collapse = ", ")
EDIT
The paste function concatenates objects after converting them to character class. If a vector is composed by more than one element, the argument collapse concatenates the elements using the passed string as separator.
Example:
v <- LETTERS[1:5]
v
# [1] "A" "B" "C" "D" "E"
paste(v, collapse = ", ")
# [1] "A, B, C, D, E"
The object v is a character vector of five elements. The output given after using paste with the argument collapse is a vector of one element.
For more information I suggest you to read the documentation with ?paste
| |
doc_23532272
|
data = sns.distplot(frame,hist=False).get_lines()[0].get_data()
The range of Xs of the frame variable is (0,24), but the range of Xs of the data variable is (0,ca. 115?)
How do I create a distplot that has the same range of Xs as the frame? I a univariate distribution of observations with the same X range as the original function.
When I do the following (below), the maxima of the distributions are the maxima of the (0,ca. 115) function, not the original one.
x = data[0]
y = data[1]
plt.plot(y)
xt_y = argrelextrema(y,np.greater)
print(ext_y)
| |
doc_23532273
|
So I dont want to do things like described in How do I dump an arbitrary struct in C?, coz thats just a hexdump
and I also dont want to invent some kind of introspection (java/modern c++ like), but just want to use the knowledge gcc has/generates for gdb, and add some knowledge I have (like how to select the right variant of a union)
like proposed in Linux C: Easy & 'pretty' dump/printout of structs (like in gdb) - from source code?.
So my plan is: Take all that nice c-code I have, let gcc work on it and produce some meta-info, which in a second turn gets parsed/analyzed by something, which then is able to interpret/print a piece of memory according to that information.
There is a utility in Linux called pstruct/c2ph, whicht does something similar and seems to be at some level of knowledge which could be modified to do what I want..
So, basically Im looking for a tool which takes a file containing
struct X {
int a;
char *b;
}
and produces a function lile printX (void *p); which then prints something like
{a:1, b:"lala"}, if p points to the according X
So is there something out there which can already do that? I have the feeling that pstruct is very close...
A: The best and most precise approach is to rely on compiler plugin interface, like those provided by clang and gcc. Basically, the compiler will call callbacks supplied by your plugin on each interesting event (such as encountering declarations), giving you the chance to produce the necessary wrappers/metadata.
Alternative approaches include tools like gcc-xml (which will produce an xml representation of your program), swig and whatever tools capable of parsing DWARF debugging output (that's what gdb uses).
| |
doc_23532274
|
here is my code:
private byte[] transformImageToJpg(byte[] receivedImage, int width, int height) {
if (receivedImage == null)
return null;
InputStream is = null;
BufferedImage bufferedImage = null;
byte[] imageInByte = null;
try {
is = new ByteArrayInputStream(receivedImage);
bufferedImage = ImageIO.read(is);
if(bufferedImage == null) {
receivedImage = null;
is.close();
showError("Invalid File", "The selected file is not a valid image file.");
return null;
}
int w = bufferedImage.getWidth();
int h = bufferedImage.getHeight();
BufferedImage newBufferedImage = new BufferedImage(width,
height, BufferedImage.TYPE_INT_RGB);
newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, width, height, 0, 0, w, h, Color.WHITE, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(newBufferedImage, "jpg", baos);
baos.flush();
imageInByte = baos.toByteArray();
newBufferedImage.flush();
bufferedImage.flush();
baos.close();
is.close();
receivedImage = null;
} catch (IOException e) {
e.printStackTrace();
}
return imageInByte;
}
| |
doc_23532275
|
isql -h
**********************************************
* unixODBC - isql *
**********************************************
* Syntax *
* *
* isql DSN [UID [PWD]] [options] *
* *
* Options *
* *
* -b batch.(no prompting etc) *
* -dx delimit columns with x *
* -x0xXX delimit columns with XX, where *
* x is in hex, ie 0x09 is tab *
* -w wrap results in an HTML table *
* -c column names on first row. *
* (only used when -d) *
* -mn limit column display width to n *
* -v verbose. *
* -lx set locale to x *
* -q wrap char fields in dquotes *
* -3 Use ODBC 3 calls *
* -n Use new line processing *
* -e Use SQLExecDirect not Prepare *
* -k Use SQLDriverConnect *
* -L Length of col display (def:300) *
* --version version *
* *
* Commands *
* *
* help - list tables *
* help table - list columns in table *
* help help - list all help options *
* *
* Examples *
* *
* isql WebDB MyID MyPWD -w < My.sql *
* *
* Each line in My.sql must contain *
* exactly 1 SQL command except for the *
* last line which must be blank (unless *
* -n option specified). *
* *
**********************************************
I experimented with the -d flag, e.g: no -d flag in a dummy query:
cat bla.sql
select 1 as bla, 2 as ha
isql -v -c -b BQ < bla.sql
+---------------------+---------------------+
| bla | ha |
+---------------------+---------------------+
| 1 | 2 |
+---------------------+---------------------+
SQLRowCount returns -1
1 rows fetched
I can make csv using -d, like so:
isql -v -c -b -d, BQ < bla.sql
bla,ha
1,2
But my real query will contain json structure data. What is the appropriate deliminator to use with the -d flag here?
| |
doc_23532276
|
def extract_recieve_addr_info(recieve_addr_info):
recieve_addr_info['all_null'] = recieve_addr_info[['addr_id', 'region', 'phone', 'fix_phone', 'receiver_md5']].apply(lambda x: 1 if (x.addr_id is np.nan) and (x.region is np.nan) and (x.phone is np.nan) and (x.fix_phone is np.nan) | (x.receiver_md5 is np.nan) else 0, axis=1)
feature = recieve_addr_info.drop_duplicates(['id'])[['id']]
recieve_addr_info['index'] = recieve_addr_info.index
all_is_null = pd.pivot_table(recieve_addr_info, index='id', values='all_null', aggfunc='min').reset_index()
addr_id = pd.pivot_table(recieve_addr_info, index='id', values='index', aggfunc='count').reset_index().rename(columns={'index': 'record_count'})
feature = feature.merge(all_is_null, on='id', how='left')
feature = feature.merge(addr_id, on='id', how='left')
province = {'Gansu', 'Yunnan', 'Guizhou', 'null'}
train_recieve_addr_info['province'] = train_recieve_addr_info[['region']].apply(lambda x: 'null' if x.region is np.nan else x.region[0:2], axis=1)
city_set = pd.pivot_table(train_recieve_addr_info, index='id', values='province', aggfunc=return_set).reset_index()
for string in list(province):
city_set[string] = [1 if string in index else 0 for index in city_set['province']]
city_set['province'] = city_set[['province']].apply(lambda x: x.province.clear() if 'null' in x.province else x.province, axis=1)
city_set['province_len'] = [0 if index is None else len(index) for index in city_set['province']]
feature = feature.merge(city_set.drop(['province'], axis=1), on='id', how='left')
return feature
An error occurred in the second last line of code feature = feature.merge(city_set.drop(['province'], axis=1), on='id', how='left')
ValueError: You are trying to merge on int64 and object columns. If you wish to proceed you should use pd.concat
I’ve tried the solution provided by ValueError: You are trying to merge on object and int64 columns when use pandas merge, added city_set['province'] = city_set['province'].astype(str) but not work.
How to fix it?
| |
doc_23532277
|
any way that I can simultaneously add an action bar and an opencv webcam in Kivy GUI framework? Thanks. Also if you do
def build:
pass
in the python script instead of the build function in camApp you can see the actionbar. It is just that I don't know how to combine them together.
Python file:
from kivy.app import App
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.graphics.texture import Texture
import cv2
class KivyCamera(Image):
def __init__(self, capture, fps, **kwargs):
super(KivyCamera, self).__init__(**kwargs)
self.capture = capture
Clock.schedule_interval(self.update, 1.0 / fps)
def update(self, dt):
ret, frame = self.capture.read()
if ret:
# convert it to texture
buf1 = cv2.flip(frame, 0)
buf = buf1.tostring()
image_texture = Texture.create(
size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')
image_texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')
# display image from the texture
self.texture = image_texture
class CamApp(App):
def build(self):
self.capture = cv2.VideoCapture(1)
self.my_camera = KivyCamera(capture=self.capture, fps=30)
return self.my_camera
def on_stop(self):
#without this, app will not exit even if the window is closed
self.capture.release()
if __name__ == '__main__':
CamApp().run()
kv file :
#:kivy 1.8.0
#:import KivyLexer kivy.extras.highlight.KivyLexer
#:import Factory kivy.factory.Factory
<ActionSpinnerOptions@SpinnerOption>
background_color: .4, .4, .4, 1
<ActionSpinner@Spinner+ActionItem>
canvas.before:
Color:
rgba: 0.128, 0.128, 0.128, 1
Rectangle:
size: self.size
pos: self.pos
border: 27, 20, 12, 12
background_normal: 'atlas://data/images/defaulttheme/action_group'
option_cls: Factory.ActionSpinnerOptions
<ActionDropdown>:
on_size: self.width = '220dp'
<ShowcaseScreen>:
ScrollView:
do_scroll_x: False
do_scroll_y: False if root.fullscreen else (content.height > root.height - dp(16))
AnchorLayout:
size_hint_y: None
height: root.height if root.fullscreen else max(root.height, content.height)
GridLayout:
id: content
cols: 1
spacing: '8dp'
padding: '8dp'
size_hint: (1, 1) if root.fullscreen else (.8, None)
height: self.height if root.fullscreen else self.minimum_height
BoxLayout:
orientation: 'vertical'
canvas.before:
Color:
rgb: .6, .6, .6
Rectangle:
size: self.size
source: 'data/background.png'
ActionBar:
ActionView:
id: av
ActionPrevious:
with_previous: (False if sm.current_screen.name == 'button' else True) if sm.current_screen else False
title: 'Showcase' + ('' if not app.current_title else ' - {}'.format(app.current_title))
on_release: app.go_hierarchy_previous()
ActionSpinner:
id: spnr
important: True
text: 'Jump to Screen'
values: app.screen_names
on_text:
if sm.current != args[1]:\
idx = app.screen_names.index(args[1]);\
app.go_screen(idx)
ActionToggleButton:
text: 'Toggle sourcecode'
icon: 'data/icons/sourcecode.png'
on_release: app.toggle_source_code()
ActionButton:
text: 'Previous screen'
icon: 'data/icons/prev.png'
on_release: app.go_previous_screen()
ActionButton:
text: 'Next screen'
icon: 'data/icons/next.png'
on_release: app.go_next_screen()
important: True
ScrollView:
id: sv
size_hint_y: None
height: 0
CodeInput:
id: sourcecode
lexer: KivyLexer()
text: app.sourcecode
readonly: True
size_hint_y: None
font_size: '12sp'
height: self.minimum_height
ScreenManager:
id: sm
on_current_screen:
spnr.text = args[1].name
idx = app.screen_names.index(args[1].name)
if idx > -1: app.hierarchy.append(idx)
A: (Note: I haven't worked with opencv yet and I can't find it on pypi)
I see that your class KivyCamera is just a casual widget used in Kivy. What happens when you do def build(self): pass is, that it opens the kv file and finds something that can be used as a root widget - in your case probably the BoxLayout: under <ShowcaseScreen>:.
What you can do with this is: try to put <KivyCamera>: into your kv file. Just that, nothing else under that. then put KivyCamera: somewhere into that BoxLayout: (the best would be into that ScreenManager as a separate Screen) and it should display it. Sizing shouldn't be an issue here as it's BoxLayout, which should prohibit overlaping of ActionBar and KivyCamera by default.
| |
doc_23532278
|
+-----------------+------------+------------+-----------+
| exhibition_name | start_date | end_date | Paintings |
+-----------------+------------+------------+-----------+
| E1 | 12-18-2015 | 12-18-2015 | 7 |
| E2 | 11-10-2015 | 11-13-2015 | 2 |
| Scupture show | 10-20-2015 | 10-25-2015 | 4 |
+-----------------+------------+------------+-----------+
These tables below are what i am using and values I have already inserted values into them
CREATE TABLE Exhibition(
name VARCHAR(15) NOT NULL,
start_date VARCHAR(11),
end_date VARCHAR(11),
PRIMARY KEY (name)
);
CREATE TABLE Shown_at(
art INT NOT NULL,
exhibition_name VARCHAR(15) NOT NULL,
PRIMARY KEY (art, exhibition_name),
FOREIGN KEY (art) REFERENCES Art_object(id_no),
FOREIGN KEY (exhibition_name) REFERENCES Exhibition(name)
);
This is my attempt to complete the function.
CREATE FUNCTION No_of_painting_exhibited(exhb_name VARCHAR(15), startd VARCHAR(11), enddVARCHAR(11), num_paint INT)
RETURNS VARCHAR(15), VARCHAR(11), VARCHAR(11), INT
DETERMINISTIC
SELECT exhibition_name, start_date, end_date, COUNT(*) as Paintings
FROM Shown_at, Exhibition
WHERE name = exhibition_name
Group by exhibition_name;
END
A: There are a couple of issues
*
*You need to change to a Procedure, not a function in order to return a table
*Number of paintings is an output, so you can remove the num_paint parameter
*Since Exhibition name is a primary key, this isn't desirable as an input if you intend showing a grouped list of many exhibitions
*Seemingly you would want to use the start and end date as parameters
*You should use strong date types for dates, not VARCHAR
*Please use ANSI JOINS to join tables, rather than joining on the where clause
*You might consider using a surrogate key (e.g. another id, guid, etc) for Exhibition - names can be a problematic choice.
How about (with DELIMITER other than ;, e.g. //):
CREATE PROCEDURE No_of_painting_exhibited(
startd DATE,
endd DATE)
BEGIN
SELECT exhibition_name, start_date, end_date, COUNT(*) as Paintings
FROM Exhibition
INNER JOIN Shown_at
ON name = exhibition_name
WHERE end_date >= startd and start_date <= endd
GROUP BY exhibition_name, start_date, end_date;
END;
Executed like so:
CALL No_of_painting_exhibited('2015/11/01','2016/01/01');
SqlFiddle here
| |
doc_23532279
|
Here's the sample data
studentGroup <- list(
Group1 = c("Samuel", "Reed", "Lucas"),
Group2 = c("Ami", "Vincent", "Dina", "George"),
Group3 = c("Connor", "Steven", "Lois", "Moran", "Zane", "Molina")
)
I have followed this post, but since my vector is a string, neither dist() nor outer() worked. So the remaining option is just combn(). The desired output is like this
> studentGroupTest
[[1]]
[1] "Samuel & Reed" "Samuel & Lucas" "Reed & Lucas"
[[2]]
[1] "Ami & Vincent" "Ami & Dina" "Ami & George" "Vincent & Dina" "Vincent & George"
[6] "Dina & George"
[[3]]
[1] "Connor & Steven" "Connor & Lois" "Connor & Moran" "Connor & Zane" "Connor & Molina" "Steven & Lois"
[7] "Steven & Moran" "Steven & Zane" "Steven & Molina" "Lois & Moran" "Lois & Zane" "Lois & Molina"
[13] "Moran & Zane" "Moran & Molina" "Zane & Molina"
My code
studentGroupTest <- vector(mode = "list", length = length(studentGroup))
for (i in 1:length(studentGroup)) {
combined_group <- as.data.frame(combn(studentGroup[[i]], 2))
combined_student <- NULL
for (j in 1:ncol(combined_group)) {
combined_student <- append(combined_student, paste(combined_group[1,j], "&", combined_group[2,j]))
}
studentGroupTest[[i]] <- combined_student
}
As you can see, my code is a little "bulky" and isn't straightforward. I wonder if I can get an lapply solution to my problem?
Thanks in advance!
A: We can loop over the list, use combn to get pairwise combinations selecting 2 at a time and paste them
lapply(studentGroup, function(x) combn(x, m = 2,
FUN = function(y) paste(y, collapse = ' & ')))
-output
$Group1
[1] "Samuel & Reed" "Samuel & Lucas" "Reed & Lucas"
$Group2
[1] "Ami & Vincent" "Ami & Dina" "Ami & George" "Vincent & Dina" "Vincent & George" "Dina & George"
$Group3
[1] "Connor & Steven" "Connor & Lois" "Connor & Moran" "Connor & Zane" "Connor & Molina" "Steven & Lois" "Steven & Moran" "Steven & Zane"
[9] "Steven & Molina" "Lois & Moran" "Lois & Zane" "Lois & Molina" "Moran & Zane" "Moran & Molina" "Zane & Molina"
| |
doc_23532280
|
A: Let this graph have n vertices.
Suppose we reverse all the edges, then we are trying to prove there is a vertex with an out-degree of zero.
If not, then simply start anywhere and travel along n edges (always possible as every vertex as non-zero out-degree). Therefore we have visited n+1 vertices - so at least 2 of them must be the same (pigeon hole principle), and therefore we have found a cycle in your acyclic graph.
| |
doc_23532281
|
So I have a column RID:
RID
111
111
111
222
222
222
333
333
333
Now I have to make use of t-sql ROW_NUMBER with BY GROUP or BY_PARTITION to make the following result:
RID | No
111 | 1
111 | 1
111 | 1
222 | 2
222 | 2
222 | 2
333 | 3
333 | 3
333 | 3
Thank you very much. Have a nice day :D
A: DENSE_RANK Function will allow you to rank each row based on the value in RID.
See the mockup below:
DECLARE @TestTable table (RID INT)
INSERT INTO @TestTable
SELECT 111 UNION ALL
SELECT 111 UNION ALL
SELECT 111 UNION ALL
SELECT 222 UNION ALL
SELECT 222 UNION ALL
SELECT 222 UNION ALL
SELECT 333 UNION ALL
SELECT 333 UNION ALL
SELECT 333 UNION ALL
SELECT 333
SELECT
RID,
[No]=DENSE_RANK() over (order by RID)
FROM
@TestTable
A: You can use dense_rank():
select rid, dense_rank() over (order by rid) as num
from t;
A: you have use to dense_rank
select * ,dense_rank over (order by rid ) as No from t
| |
doc_23532282
|
when navigating to it I get the correct information:
"this field is required {label} combobox 1 of 4" (seemingly telling me the default selected one which is in place 1 of 4)
However when I arrow through the options it does not read off what they are. After selecting the option I want it then announces it for example:
"Apple 3 of 4"
I am in need of it announcing as the user keyboards through the options.
The code is as follows for the entire component:
import { GenericControlProps } from "..";
import "./HighgearDropdown.scss";
export interface Option {
label: string;
value: string;
}
export interface OptionGroup {
title: string;
options: Option[];
}
export type HighgearDropdownProps = GenericControlProps<string> & {
options: (Option | OptionGroup)[];
};
export const HighgearDropdown: React.FC<HighgearDropdownProps> = (props) => {
// This is state so that we continue showing the empty option after the initial render.
const [showEmptyOption] = React.useState(!props.value);
const { id, value = "", focusRef, disabled, onChange, options } = props;
return (
<select
ref={focusRef as React.Ref<HTMLSelectElement>}
className="hg-control-dropdown"
onChange={(ev) => onChange(ev.currentTarget.value)}
{...{ id, value, disabled }}
>
{showEmptyOption && <option value="" />}
{options.map((it, i) => {
return "title" in it ? (
<optgroup key={i} label={it.title}>
{it.options.map((jt, j) => (
<option key={j} value={jt.value}>
{jt.label}
</option>
))}
</optgroup>
) : (
<option key={i} value={it.value}>
{it.label}
</option>
);
})}
</select>
);
};
| |
doc_23532283
|
NoMethodError in UserController#register
undefined method `save' for nil:NilClass
here is the code from the user_controller.rb file:
class UserController < ApplicationController
def index
@title = "RailsSpace User Hub"
end
def register
@title = "Register"
if request.post? and params[:user]
@user = User.new(user_params)
end
if @user.save
flash[:notice] = "User #{@user.screen_name} created!"
redirect_to :action => "index"
end
end
private
def user_params
# Add the user attributes that you sent with post (form) to the permit
method.
params.require(:user).permit(:name, :screen_name)
end
end
It's complaining about line 11 where it says: if @user.save I'm just following the tutorial I don't know what's going on.
A: Try to understand what the error message is saying. You're trying to call .save on @user but where you are calling it, @user may not be defined. The problem is you can't call .save on a nil object so it throws NoMethodError.
You're logic is incorrect so you must first make sure @user is instantiating a new User instance. It should be more like this:
def register
@title = "Register"
if request.post? && params[:user]
@user = User.new(user_params)
if @user.save
flash[:notice] = "User #{@user.screen_name} created!"
redirect_to :action => "index"
else
# handle erorrs here
flash[:alert] = "Please fix errors: #{@user.errors.full_messages.inspect}"
redirect_to :back #this may need to change depending, just an example.
end
end
end
A: NoMethodError in UserController#register undefined method 'save' for nil:NilClass
The error is thrown because you are calling save on a nil; and it is because nil object does not have this method. the save is a instance method belonging to ActiveRecord::Base class.
The reason @user is nil is because @user is an instance variable in the UserController class which you have not given it any value. Any variable starting with @ inside a class is an instance variable in Ruby.
To solve this problem, you should set a value to @user, and in this case it should be a User instance. You can either create a new user object by doing @user = User.new(user_params) or you fetch a record from the Database by doing @user = User.find(<some_id>)
| |
doc_23532284
|
Also I write a program for this communication. This code is composed of the following components:
*
*RCC configuration
*GPIO configuration
*USART configuration
*Send and receive of a string
*Comparison between the sent string and the received string
*Test if the communication succeeded => LED4 turn on else the LED3 turn on
The problem is in all cases the LED3 turns on. It means that the data transmission failed.
With my IDE (IAR's Embedded Workbench) I compile this program code:
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
#include "stm32_eval.h"
/* Private typedef -----------------------------------------------------------*/
typedef enum { FAILED = 0, PASSED = !FAILED} TestStatus;
/* Private define ------------------------------------------------------------*/
#define USARTy USART1
#define USARTy_GPIO GPIOA /* PORT name*/
#define USARTy_CLK RCC_APB2Periph_USART1
#define USARTy_GPIO_CLK RCC_APB2Periph_GPIOA
#define USARTy_RxPin GPIO_Pin_10/* pin Rx name*/
#define USARTy_TxPin GPIO_Pin_9 /* pin Tx name*/
#define USARTz USART2
#define USARTz_GPIO GPIOA/* PORT name*/
#define USARTz_CLK RCC_APB1Periph_USART2
#define USARTz_GPIO_CLK RCC_APB2Periph_GPIOA
#define USARTz_RxPin GPIO_Pin_3/* pin Rx name*/
#define USARTz_TxPin GPIO_Pin_2/* pin Tx name*/
#define TxBufferSize (countof(TxBuffer))
/* Private macro -------------------------------------------------------------*/
#define countof(a) (sizeof(a) / sizeof(*(a)))
/* Private variables ---------------------------------------------------------*/
USART_InitTypeDef USART_InitStructure;
uint8_t TxBuffer[] = "Bufferrr";
uint8_t RxBuffer[8];
__IO uint8_t TxConteur = 0, RxConteur = 0;
volatile TestStatus TransferStatus = FAILED;
/* Private function prototypes -----------------------------------------------*/
void RCC_Configuration(void);
void GPIO_Configuration(void);
TestStatus Buffercmp(uint8_t* pBuffer1, uint8_t* pBuffer2, uint16_t BufferLength);
__IO uint8_t index = 0;
GPIO_InitTypeDef GPIO_InitStructure;
int main(void)
{
STM_EVAL_LEDInit(LED1);
STM_EVAL_LEDInit(LED2);
STM_EVAL_LEDInit(LED3);
STM_EVAL_LEDInit(LED4);
/* System Clocks Configuration */
RCC_Configuration();
/* Configure the GPIO ports */
GPIO_Configuration();
USART_InitStructure.USART_BaudRate = 230400 /*115200*/;
USART_InitStructure.USART_WordLength =USART_WordLength_8b ;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
/* Configure USARTy */
USART_Init(USART1,&USART_InitStructure);
/* Enable the USARTy */
USART_Cmd(USART1,ENABLE);
while(TxConteur < TxBufferSize)
{
/* Send one byte from USARTy to USARTz */
USART_SendData(USARTy, TxBuffer[TxConteur++]);
/* Loop until USARTy DR register is empty */
while(USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET)
{
}
/* Store the received byte in RxBuffer */
RxBuffer[RxConteur++] = USART_ReceiveData(USARTy) & 0xFF;
}
/* Check the received data with the send ones */
TransferStatus = Buffercmp(TxBuffer, RxBuffer, TxBufferSize);
/* TransferStatus = FAILED, if the data transmitted from USARTy and
received by USARTz are different */
if (TransferStatus == FAILED)
{
STM_EVAL_LEDOn(LED3);
}
else
{
STM_EVAL_LEDOn(LED4);
}
while (1)
{
}
}
void RCC_Configuration(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA , ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 , ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC , ENABLE);
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure1,GPIO_InitStructure2;
/* Configure USARTy Rx as input floating */
GPIO_InitStructure1.GPIO_Pin =GPIO_Pin_10;
GPIO_InitStructure1.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure1.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure1);
/* Configure USARTy Tx as alternate function push-pull */
GPIO_InitStructure2.GPIO_Pin =GPIO_Pin_9;
GPIO_InitStructure2.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure2.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure2);
/* Configure USARTz Tx as alternate function push-pull */
}
TestStatus Buffercmp(uint8_t* pBuffer1, uint8_t* pBuffer2, uint16_t BufferLength)
{
while(BufferLength--)
{
if(*pBuffer1 != *pBuffer2)
{
return FAILED;
}
pBuffer1++;
pBuffer2++;
}
return PASSED;
}
A: Like explained in a comment by Hans Passant, the OP was testing the flag USART_FLAG_TC (Transmission Completed) instead of the flag USART_FLAG_RXNE (RX buffer Not Empty).
| |
doc_23532285
|
list1.addAll(list2);
I want to now sort this arraylist on the order of the date time object that the arraylist consists of. Can anyone guide me how to sort this arraylist.
A: ArrayList<Date> myDates = new ArrayList<>();
// populate the List...
Collections.sort(myDates);
If you are using Joda Time Date time, this is done the same way, since those classes usually implement Comparable.
A: If you meant they have Java Date object. You can just do Collections#sort()
A: You can define your comparator for the objects of the arraylist, like if I am using objects having structure
and then you can use, sort method directly.
| |
doc_23532286
|
using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
namespace Nop.Web.Themes.MyTheme.Extensions
{
public static class FormLineHelper
{
public static MvcHtmlString FormLine<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty[]>> expression,
object htmlAttributes = null)
{
TagBuilder tag = new TagBuilder("tr");
tag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);
var member = (MemberExpression)expression.Body;
string propertyName = member.Member.Name;
tag.InnerHtml += String.Format("<td class='label'>{0}</label></td><td class='field'>{1}</td><td class='padding'>{2}</td>",
htmlHelper.LabelFor(expression), htmlHelper.EditorFor(expression), htmlHelper.ValidationMessageFor(expression));
return MvcHtmlString.Create(tag.ToString());
}
}
}
This compiles just fine. However when i do
@model Nop.Plugin.MyPlugin.Models.ViewModel
@{
Layout = "../Shared/_Root.cshtml";
}
<div class="form">
<div class="form-top"></div>
<div class="form-center">
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
@Html.FormLine(model => model.FirstName)
</table>
}
</div>
<div class="form-bottom"></div>
</div>
I made sure the web.config contains
<compilation debug="true" targetFramework="4.0">
I get the "The type arguments cannot be inferred from the usage" error. Another helper that works similair, but doesn't use the standard helpers works fine. I have also tried this:
@{ Html.FormLine<ViewModel, string>(model => model.FirstName); }
Which gives the error "Cannot implicitly convert type 'string' to 'string[]'".
I have seen similair questions but I haven't been able to find an answer. So what am i doing wrong?
A: Why you get the array of properties?
How change this line:
Expression<Func<TModel, TProperty[]>> expression,
With
Expression<Func<TModel, TProperty>> expression,
| |
doc_23532287
|
What could be the reason for this?
A: There are many possibilities that can explain this that have little to do with PostgreSQL itself. Because you say that the pause happens with DDL operations, it sounds to me like one of these may be the problem.
What client are you using? Does the client have an auto-reconnection capability? If so, then your connection may be being closed while idle by a firewall between you and your server, and your client has to detect that the connection was closed and then establish a new one. If this is the case, then check to see if your client supports keepalive.
Does your remote Ubuntu server have enough memory? Is it busy with other tasks? If so, then an idle period may cause postmaster to be deprioritized or swapped out by the OS, and it takes a while for it to be "awakened" to serve your next request.
Is your remote Ubuntu server virtual? Is the host for that VM busy or overcommitted? If so, then your entire Ubuntu VM may be swapped out by the hypervisor on idle.
| |
doc_23532288
|
inside one of the activity, I have a ViewPager:
<android.support.v4.view.ViewPager
android:id="@+id/image_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
I load multiple images view in the pager from the adapter to scroll between them.
However I am facing a conflict in scrolling.
When I swipe to the left everything works fine, the next image gets displayed.
But when I swipe to the right, the sliding menu will open, since its his behavior.
Can I make it in a way that swiping on the View Pager does not propagate to the sliding menu?
I tried to return true in the OnTouchListener of the pager, but the sliding menu is still opening, and now the slider doesn't work anymore.
viewPager.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return true;
}
});
Thanks for any help
A: check accepted answer here
The feinstein slidingmenu can be configured so it only reacts to gestures that begin at the edge of the screen. That should allow your other handler to be the sole delegate of swipes that originate anywhere NOT on the extreme edge of the screen.
I believe that you can set these in "class BaseActivity extends SlidingFragmentActivity"
A: I have a better solution:
Set an OnTouchListener for you ViewPager and disable the SlidingMenu on ACTION_DOWN, enable the SlidingMenu on ACTION_UP and ACTION_CANCEL.
Here is the code:
ViewPager mPager;
// Find your SlidingMenu here.
SlidingMenu mSlidingMenu;
mPager.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mSlidingMenu.setSlidingEnabled(false);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mSlidingMenu.setSlidingEnabled(true);
break;
}
return false;
}
}
| |
doc_23532289
|
I need to convert my Func<string, bool> value to an Expression to be used in the Moq framework but I cannot get passed an error when trying to convert the Func to an Expression.
This is the error:
Static method requires null instance, non-static method requires
non-null instance.
This is my sample code:
using System;
using System.Linq.Expressions;
namespace ConsoleApp1
{
class Program
{
public class MyObject
{
public void Add<T>(Func<T, bool> value)
{
// Line below causes error: Static method requires null instance,
// non-static method requires non-null instance.
Expression<Func<T, bool>> expression =
Expression.Lambda<Func<T, bool>>(Expression.Call(value.Method));
// I need to use the expression for the line below that is commented out
// (for context reasons I have included this)
//_myMock.Setup(m => m.MyMethod(key, It.Is(expression))).Returns("test");
}
}
public static void Main(string[] args)
{
// Call it using:
var myObject = new MyObject();
myObject.Add(new Func<string, bool>(x => x.StartsWith("test")));
}
}
}
Not sure if my function is a static or non-static, but I would have thought it was static. I inspected the Func object using the debugger and there is a field called "IsStatic" set to false (value.Method.IsStatic). A bit confused what else to try.
Thank you.
Stack Trace:
System.ArgumentException
HResult=0x80070057
Message=Static method requires null instance, non-static method requires non-null instance.
Parameter name: method
Source=System.Core
StackTrace:
at System.Linq.Expressions.Expression.ValidateStaticOrInstanceMethod(Expression instance, MethodInfo method)
at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, IEnumerable`1 arguments)
at System.Linq.Expressions.Expression.Call(MethodInfo method, Expression[] arguments)
at ConsoleApp1.Program.MyObject.Add[T](Func`2 value) in C:\Users\userName\source\repos\ConsoleApp1\ConsoleApp1\Program.cs:line 14
at ConsoleApp1.Program.Main(String[] args) in C:\Users\userName\source\repos\ConsoleApp1\ConsoleApp1\Program.cs:line 28
A: Your method that you are wrapping in expression call is not static.
To call not static method you would need valid instance to pass as this, and this can get tricky if you actually use some variable from outside of the func. You can inspect the method further and see its declaring type. Instance of it would be required to make the Expression.Call work.
To just do the mock setup, as it is your goal, you could modify your Add method and just get the expression directly
Add<T>(Expression<Func<T, bool>> expression)
{
_myMock.Setup(m => m.MyMethod(key, It.Is(expression))).Returns("test");
}
and this will just work when called like this:
myObject.Add((string x) => x.StartsWith("test"));
| |
doc_23532290
|
No route matches [DELETE] "/articles"
I have the resources :articles command in my routes.rb
ArticlesController
def destroy
@article = Article.find(params[:id])
respond_to do |format|
format.html { redirect_to articles_url notice: 'Article was successfully deleted.' }
format.json { head :no_content }
end
Show page link:
<%= link_to 'Delete', article_path(@article), method: :delete, data: {confirm: "Are you sure"} %>
A: Look, I think you have missed the object like if your delete link into the each loop then definitely it has an object like @articles.each do |article| that means the object name is article so on the delete link you need to pass the object like this
<%= link_to 'Delete', article_path(article), method: :delete, data: {confirm: "Are you sure"} %>
@article to article, please refactor the code.
and update the destroy method like this
def destroy
@article = Article.find(params[:id])
@article.destroy
respond_to do |format|
format.html { redirect_to articles_url notice: 'Article was successfully deleted.' }
format.json { head :no_content }
end
end
If it is not helpful to you, then please copy & paste your error logs here from the log file.
Hope it will help.
A: Run rails routes.
Your destroy route might be like this:
DELETE /articles/:id(.:format)
*You have to specify the id you want to be destroyed!
A: A Tour of Rails’ jQuery UJS
Make sure Jquery files are loaded properly in your rails project. Read the above link for more information.
A: try this
def destroy
@article = Article.find(params[:id]
@article.destroy
respond_to do |format|
format.html { redirect_to articles_url}
format.json { head :no_content }
end
end
| |
doc_23532291
|
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoView videoView = (VideoView) findViewById(R.id.videoView);
videoView.setVideoPath("android.resource://" + getPackageName() + "/" + R.raw.gotem);
videoView.start();
}
}
A: Add the following code before calling video.start()
videoView.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.setLooping(true);
}
});
This waits for the MediaPlayer to be prepared and then loops the content of the MediaPlayer since VideoView uses MediaPlayer internally.
| |
doc_23532292
|
I have a dropDownList with selectable items from a model class and a button ("GAStatisticsReport-Submit"). I just need t check if item "Visitors" is selected in the DropDownList, if that's the case i can click run and the Charts will display the data with visitors. How could i archive this?
The controller has a method called CreateGAStatisticsReport wich returns data to the view for the charts to display. This method has an ActionResult. However when the function draws the charts it draws them from GetData ActionResult and not GAStatistics.
Here is the view:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.load("visualization", "1", { packages: ["treemap"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.get('/GAStatistics/GetData', {}, <--- here's GetData ActionResult in the Controller
function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('date', 'Datum');
tdata.addColumn('number', 'Besökare');
for (var i = 0; i < data.length; i++) {
var dateStr = data[i].Date.substr(0, 4) + "-" + data[i].Date.substr(4, 2) + "-" + data[i].Date.substr(6, 2);
tdata.addRow([new Date(dateStr), parseInt(data[i].Visitors)]);
}
var options = {
title: "Number of unique visitors"
};
var chart1 = new google.visualization.AreaChart(document.getElementById('chart_div1'));
var chart2 = new google.visualization.LineChart(document.getElementById('chart_div2'));
var chart4 = new google.visualization.ColumnChart(document.getElementById('chart_div4'));
chart1.draw(tdata, options);
chart2.draw(tdata, options);
chart4.draw(tdata, options);
});
}
</script>
<table class="adminContent">
<tr>
<td class="adminTitle">
@Html.NopLabelFor(model => model.StartDate):
</td>
<td class="adminData">
@Html.EditorFor(model => model.StartDate)
</td>
</tr>
<tr>
<td class="adminTitle">
@Html.NopLabelFor(model => model.EndDate):
</td>
<td class="adminData">
@Html.EditorFor(model => model.EndDate)
</td>
</tr>
<tr>
<td class="adminTitle">
@Html.NopLabelFor(model => model.GAStatisticsId ):
</td>
<td class="adminData">
@Html.DropDownList("GAStatisticsId", Model.AvailableGAStatistics)
<input type="button" id="GAStatisticsReport-Submit" class="t-button" value="@T("Run")" />
</tr>
</table>
My ViewModel (note: When SelectListItem "Visitors is selected and the user has clicked the "Run" button it should execute and draw the charts):
public class GAStatisticsListModel : BaseNopModel
{
public GAStatisticsListModel()
{
AvailableGAStatistics = new List<SelectListItem>();
SelectListItem Visitors = new SelectListItem() { Text = "Besökare", Value = "1", Selected = false };
SelectListItem PercentNewVisitors = new SelectListItem() { Text = "Nya Besökare (Procent)", Value = "2", Selected = false };
SelectListItem ConversionRate = new SelectListItem() { Text = "Konverteringsgrad", Value = "3", Selected = false };
AvailableGAStatistics.Add(Visitors);
AvailableGAStatistics.Add(PercentNewVisitors);
AvailableGAStatistics.Add(ConversionRate);
}
[NopResourceDisplayName("Admin.ShopStatistics.List.StartDate")]
[UIHint("DateNullable")]
public DateTime? StartDate { get; set; }
[NopResourceDisplayName("Admin.ShopStatistics.List.EndDate")]
[UIHint("DateNullable")]
public DateTime? EndDate { get; set; }
[NopResourceDisplayName("Admin.GAStatistics.GAStatistics.GAStatisticsList")]
public int GAStatisticsId { get; set; }
public List<SelectListItem> AvailableGAStatistics { get; set; }
}
}
The Controller (GetData passes data to the JQuery code in the view from CreateGAStatisticsReport for the charts to display):
public class GAStatisticsController : Controller
{
//GET: /ShopStatistics/
[HttpPost]
public ActionResult GetData()
{
return Json(CreateGAStatisticsReport(), JsonRequestBehavior.AllowGet);
}
public ActionResult GAStatistics()
{
return View(new GAStatisticsListModel());
}
private List<GAStatistics> CreateGAStatisticsReport()
{
var serviceAccountEmail = "xxxxxxxxx@developer.gserviceaccount.com";
var certificate = new X509Certificate2(@"C:\Users\Desktop\NopCommerce\Presentation\Nop.Web\key.p12", "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { AnalyticsService.Scope.Analytics }
}.FromCertificate(certificate));
// Create the service.
//Twistandtango
var GoogleAnalyticsService = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "MyApp",
});
var request = GoogleAnalyticsService.Data.Ga.Get("ga:xxxxxxxx", "2014-01-24", "2014-01-30", "ga:visitors");
//Specify some addition query parameters
request.Dimensions = "ga:date";
request.Sort = "-ga:date";
request.MaxResults = 10000;
//Execute and fetch the results of our query
Google.Apis.Analytics.v3.Data.GaData d = request.Execute();
List<GAStatistics> ListGaVisitors = new List<GAStatistics>();
foreach (var row in d.Rows)
{
GAStatistics GaVisits = new GAStatistics(row[0], row[1]);
ListGaVisitors.Add(GaVisits);
}
return ListGaVisitors;
}
}
A: For what you want you can't use google.setOnLoadCallback(drawChart) (see this link too understand why). If I understand what you want to do, you must set a event on your button and that event will execute the drawChart() function.
Like this:
$("#GAStatisticsReport-Submit").click(function(){ drawChart() })
So, when you click on that button the chart will be draw.
To draw the chart only if the 'Visitors' is selected you must do something like this:
$("#GAStatisticsReport-Submit").click(function(){
if($("select[name='GAStatisticsId'] option:selected").text()=="Visitors")
drawChart()
})
| |
doc_23532293
|
For example if user enter this to a text field. "2*sin(2*M_PI*t)" which the "t" inside the equation is a variable inside the code and Xcode would able understand the equation like
double answer = 2*sin(2*M_PI*t);
Many Thanks
Kin
A: You can do it with just the standard cocoa classes, but the syntax gets somewhat ridiculous, and the amount of set-up is staggering too.
@interface MyExprTest : NSObject
-(void)run;
@end
@implementation MyExprTest
-(void)run {
NSExpression *e = [(NSComparisonPredicate *)[NSPredicate
predicateWithFormat:@"2*FUNCTION(2*PI*$t,'sin')==0"]
leftExpression];
NSMutableDictionary *vars = [NSMutableDictionary
dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:0.04], @"t",
nil];
NSLog(@"%@", [e expressionValueWithObject:self context:vars]);
}
-(double)PI {
return M_PI;
}
@end
@interface NSNumber (Trigonometry)
- (NSNumber*)sin;
@end
@implementation NSNumber (Trigonometry)
- (NSNumber*) sin {
double result = sin([self doubleValue]);
return [NSNumber numberWithDouble:result];
}
@end
int main (int argc, const char * argv[]) {
MyExprTest *t = [[MyExprTest alloc] init];
[t run];
return 0;
}
A few pointers to note:
*
*The t in your expression became $t so that you could reference it from the vars dictionary
*The M_PI became simply PI; note the added method to support it
*There are no built-in trigonometric functions; see how FUNCTION and a category is used to get around it.
A: Your best bet is to use a math parser like DDMathParser.
It allows variable substitution and has built-in constants.
| |
doc_23532294
|
Filling the text fields is easy, but I don't know where to start when trying to figure out how to dynamically filling those text fields with dates such as "first day of the month through today" or "from the first of the year through today".
This is what I've got so far:
javascript
<script>
$(document).ready(function() {
$("#datetype option").filter(function() {
return $(this).val() == $("#datepickstart").val();
return $(this).val() == $("#datepickend").val();
}).attr('selected', true);
$("#datetype").live("change", function() {
$("#datepickstart").val($(this).find("option:selected").attr("value"));
$("#datepickend").val($(this).find("option:selected").attr("value"));
});
});
</script>
html
<select id="datetype" name="datetype">
<option value="">Please select...</option>
<option value="LBD">LBD</option>
<option value="MtD">MtD</option>
<option value="YtD">YtD</option>
</select>
<input type="text" id="datepickstart" name="datepickstart" value="">
<input type="text" id="datepickend" name="datepickend" value="">
A: To achieve expected result use below option
$(document).ready(function() {
$("#datetype option").filter(function() {
return $(this).val() == $("#datepickstart").val();
return $(this).val() == $("#datepickend").val();
}).attr('selected', true);
var d = new Date();
var today = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
var fdm = (d.getMonth() + 1) + '/01/' + d.getFullYear();
var fdy = '01/01/' + new Date().getFullYear();
$("#datetype").on("change", function() {
var selectedVal = $(this).find("option:selected").attr("value");
if (selectedVal == 'LBD') {
$("#datepickstart").val(today);
$("#datepickend").val(today);
}
if (selectedVal == 'MtD') {
$("#datepickstart").val(fdm);
$("#datepickend").val(today);
}
if (selectedVal == 'YtD') {
$("#datepickstart").val(fdy);
$("#datepickend").val(today);
}
});
});
http://codepen.io/nagasai/pen/begRax
LBD will fill today's date in both fields
MtD will fill Month's first date and second field will have today's date
YtD will fill Year's first date and second field will have today's date
| |
doc_23532295
|
Please provide me some idea how to achieve this .
A: I ve had same problem developing an app where I had to download large images whose URLs where stored in a XML feed. What I did is upload the images to Imgur. It has an API where you can simply add a suffix to the image url (in your code) an the image will be scaled by the server. Apple the desired suffix depending on the device dpi and image size. The best way is to measure the total width/height in pixels and request the image resized according to it. More info about the API here https://api.imgur.com/models/image
| |
doc_23532296
|
def get_episodes(driver):
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//a[contains(@title,'Episode')]")))
episodes = driver.find_elements_by_xpath("//a[contains(@title,'Episode')]")
del episodes[-1]
episodes = list(reversed(episodes))
return episodes
However recently i've found out that not every episode contains the word 'episode' in its link text. As such, i am trying to figure out another way to get every link to an episode. The basic structure of the page contains a table, and each link is located inside a <td> element.
I've thought of gathering all the td elements, and then getting their children (or should i say child) by using css selectors. Nevertheless, this won't work either because there are more <td> elements than those that meet the eye.
Here's an example page for reference. I am a noob as far as selenium is concerned, and thus not very familiar with its api, so i don't know exactly what i am looking for. Any suggestion is appreciated.
A: Try to make your XPath more specific:
//tr/td/a[starts-with(@href,'/Anime/')]
A: You're on the right track, but you may be over-thinking this a bit. Why not just target the table that we know has the episodes, then use a list comprehension to grab all the episode links?
def get_episodes():
episode_table = driver.find_element_by_class_name('listing')
episode_links = [i.get_attribute('href') for i in episode_table.find_elements_by_tag_name('a')]
print(episode_links)
>>>['http://kissanime.to/Anime/Death-Note-Dub/Episode-037?id=97557', 'http://kissanime.to/Anime/Death-Note-Dub/Episode-036?id=97556', 'http://kissanime.to/Anime/Death-Note-Dub/Episode-035?id=97555', 'http://kissanime.to/Anime/Death-Note-Dub/Episode-034?id=97554',etc..]
| |
doc_23532297
|
It is important to note that all the bytes need to be positive, i.e. the negative range cannot be used.
Can this be done in Java, and if yes, how?
I need to be able to multiply the contents of a file by a constant. I was assuming that I can read the bytes into a BigInteger and then multiply, however since some of the bytes are negative I am ending up with 12 13 15 -12 etc and get stuck.
A: With the unsigned API in Java 8 you have Byte.toUnsignedInt. That'll be a lot cleaner than manually casting and masking out.
To convert the int back to byte after messing with it of course you just need a cast (byte)value
A: Well, Java doesn't have the concept of unsigned bytes... the byte type is always signed, with values from -128 to 127 inclusive. However, this will interoperate just fine with other systems which have worked with unsigned values for example, C# code writing a byte of "255" will produce a file where the same value is read as "-1" in Java. Just be careful, and you'll be okay.
EDIT: You can convert the signed byte to an int with the unsigned value very easily using a bitmask. For example:
byte b = -1; // Imagine this was read from the file
int i = b & 0xff;
System.out.println(i); // 255
Do all your arithmetic using int, and then cast back to byte when you need to write it out again.
You generally read binary data from from files using FileInputStream or possibly FileChannel.
It's hard to know what else you're looking for at the moment... if you can give more details in your question, we may be able to help you more.
A: If using a larger integer type internally is not a problem, just go with the easy solution, and add 128 to all integers before multiplying them. Instead of -128 to 127, you get 0 to 255. Addition is not difficult ;)
Also, remember that the arithmetic and bitwise operators in Java only returns integers, so:
byte a = 0;
byte b = 1;
byte c = a | b;
would give a compile time error since a | b returns an integer. You would have to to
byte c = (byte) a | b;
So I would suggest just adding 128 to all your numbers before you multiply them.
A: You wrote in a comment (please put such informations in the question - there is an edit link for this):
I need to be able to multiply the contents of a file by a constant.
I was assuming that I can read the bytes into a BigInteger and then
multiply, however since some of the bytes are negative I am ending
up with 12 13 15 -12 etc and gets stuck.
If you want to use the whole file as a BigInteger, read it in a byte[], and give this array (as a whole) to the BigInteger-constructor.
/**
* reads a file and converts the content to a BigInteger.
* @param f the file name. The content is interpreted as
* big-endian base-256 number.
* @param signed if true, interpret the file's content as two's complement
* representation of a signed number.
* if false, interpret the file's content as a unsigned
* (nonnegative) number.
*/
public static BigInteger fileToBigInteger(File f, boolean signed)
throws IOException
{
byte[] array = new byte[file.length()];
InputStream in = new FileInputStream(file);
int i = 0; int r;
while((r = in.read(array, i, array.length - i) > 0) {
i = i + r;
}
in.close();
if(signed) {
return new BigInteger(array);
}
else {
return new BigInteger(1, array);
}
}
Then you can multiply your BigInteger and save the result in a new file (using the toByteArray() method).
Of course, this very depends on the format of your file - my method assumes the file contains the result of the toByteArray() method, not some other format. If you have some other format, please add information about this to your question.
"I need to be able to multiply the contents of a file by a constant." seems quite a dubious goal - what do you really want to do?
A: Some testing revealed that this returns the unsigned byte values in [0…255] range one by one from the file:
Reader bytestream = new BufferedReader(new InputStreamReader(
new FileInputStream(inputFileName), "ISO-8859-1"));
int unsignedByte;
while((unsignedByte = bytestream.read()) != -1){
// do work
}
It seems to be work for all bytes in the range, including those that no characters are defined for in ISO 8859-1.
| |
doc_23532298
|
how can I do that in my react native app
import React, { useContext, useState } from 'react';
import { View, Button, Text, StyleSheet, Switch} from 'react-native';
const Testing = ({ navigation }) => {
return (
<View>
<Text> My mother has blue eyes and my father has dark green eyes.</Text>
</View>
);
}
export default Testing;
A: Text elements have to be nested:
const Testing = ({ navigation }) => {
return (
<View>
<Text> My mother has <Text style={{color: '#0000fff'}}>blue<Text> eyes and my father has dark green eyes.</Text>
</View>
);
}
Example: https://reactnative.dev/docs/text#nested-text
A: You can add a <Text> inside another <Text> and add a style for each text. Like the code bellow:
<Text style={styles.text}> text text text text text
<Text onPress={() => goToScreen('Premiações')} style={styles.blue_text}>
differently styled text
</Text>
text text.
</Text>
Perceive my inner <Text> has a style different from the outter <Text>, and also perceive my inner <Text> has even a onPress, which will be applied only to this inner <Text> when pressed (it's a link inside the body of a text).
A: I put a simple js code and you can convert to react:
document.getElementById('mother').style.color = document.getElementById('mother').innerHTML;
document.getElementById('father').style.color = document.getElementById('father').innerHTML;
<View>
<Text> My mother has <span id="mother">blue</span> eyes and my father has <span id="father">darkgreen</span> eyes.</Text>
</View>
| |
doc_23532299
|
This is what I have in main
import java.util.ArrayList;
public class LocationTest {
public static void main(String[] args) {
ArrayList<Location> locationList = new ArrayList<>();
locationList.add(new Location(new Address(1, "Abubakr rd Almorsalat", "Riyadh", "Saudi Arabia"), new Geolocation(24.7136, 46.6753, 612), 1, "Prince Sultan University"));
locationList.add(new Location(new Address(1, "Nassria st", "Sfax", "Tunisia"), new Geolocation(34.7478, 10.7662, 20), 2, "Second Location"));
locationList.get(1).getGeolocation().setAltitude(20);
locationList.get(0).getAddress().setStreetNumber(15);
for(Location i : locationList) {
System.out.println(i.getGeolocation());
}
}
}
and I have getters and setters for the two classes I'm using inside of Location this is their set method
public void setAddress(Address address) {
this.address.setStreetNumber(address.getStreetNumber());
this.address.setStreetName(address.getStreetName());
this.address.setCity(address.getCity());
this.address.setCountry(address.getCountry());
}
public void setGeolocation(Geolocation geolocation) {
this.geolocation.setLatitude(geolocation.getLatitude());
this.geolocation.setLongitude(geolocation.getLongitude());
this.geolocation.setAltitude(geolocation.getAltitude());
}
I have a feeling that the problem is here, I'm not sure
The error is
Exception in thread "main" java.lang.NullPointerException
at quiz01.fall2016.Location.setAddress(Location.java:59)
at quiz01.fall2016.Location.<init>(Location.java:20)
at quiz01.fall2016.LocationTest.main(LocationTest.java:13)
The constructor
public Location(Address address, Geolocation geolocation, int id, String name) {
setAddress(address);
setGeolocation(geolocation);
setId(id);
setName(name);
}
A: Before setAddress calls setters on this.address, make sure you are initializing this.address.
By default, all the objects will be initialized with null, so you are hitting NullPointerException.
Your constructor should be as follows
public Location(Address address, Geolocation geolocation, int id, String name) {
// Initialize objects.
this.address = new Address();
this.geolocation = new Geolocation();
setAddress(address);
setGeolocation(geolocation);
setId(id);
setName(name);
}
A: You should create Location class as follows:
public class Location {
private Address address;
private Geolocation geolocation;
private int id;
private String name;
public Location() {
super();
}
public Location(Address address, Geolocation geolocation, int id, String name) {
super();
this.address = address;
this.geolocation = geolocation;
this.id = id;
this.name = name;
}
// ... other methods ...
}
A: In your constructor you are assuming that this.address is initialized automatically, whereas, it is not. You haven't intiailized it, that's the reason you are facing NullPointerException.
Change you method setAddress like this :
public void setAddress(Address address) {
this.address = new Addess();
this.address.setStreetNumber(address.getStreetNumber());
this.address.setStreetName(address.getStreetName());
this.address.setCity(address.getCity());
this.address.setCountry(address.getCountry());
}
You will have to make similar change for GeoLocation as well.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.