text:
Q: I have got two associative arrays of different lengths. I want to know how to compare values and apply to checkboxes? There are two associative arrays of different lengths, how to compare their values and apply to checkboxes? If the values match, I need the checkbox gets the attribute checked.
Now I have this:

*

*Politics

*Video (Checked)

*Policy (Checked)

*Video

I want

*

*Video (Checked)

*Policy (Checked)

My code at the monent:
@foreach($category as $categories)
    <input type="checkbox" aria-label="{{$categories->title}}" value="{{$categories->title}}" name="category[{{$categories->id}}]"> {{$categories->title}}
    @foreach($post->category as $selected)
        @if($selected->title == $categories->title)
            <input type="checkbox" aria-label="{{$categories->title}}" value="{{$categories->title}}" name="category[{{$categories->id}}]" checked> {{$categories->title}}
        @endif
    @endforeach
@endforeach

A: You can apply that condition inside element to apply checked property
@foreach($category as $categories)
    <input type="checkbox" aria-label="{{$categories->title}}" value="{{$categories->title}}" name="category[{{$categories->id}}]"> {{$categories->title}}
    @foreach($post->category as $selected)
        <input type="checkbox" aria-label="{{$categories->title}}" value="{{$categories->title}}" name="category[{{$categories->id}}]" {{$selected->title == $categories->title ? 'checked' : ''}}> {{$categories->title}}
    @endforeach
@endforeach

A: I have resolved this problem
Controller:
    $checkedCategory = [];

    foreach($post->category as $selected) {
        for($i = 0; $i < count($category); $i++) {
            if($selected->title == $category[$i]->title) {
                $checkedCategory[$i] = $category[$i]->title;
            }
        }
    }

    $checkedCategory = array_values(array_unique($checkedCategory, SORT_REGULAR));

Template:
<fieldset>
            <legend>Категории</legend>

            @foreach($category as $categories)
                @if(in_array($categories->title, $checkedCategory))
                    <input type="checkbox" aria-label="{{$categories->title}}" value="{{$categories->title}}" name="category[{{$categories->id}}]" checked> {{$categories->title}}
                @else
                    <input type="checkbox" aria-label="{{$categories->title}}" value="{{$categories->title}}" name="category[{{$categories->id}}]"> {{$categories->title}}
                @endif
            @endforeach

        </fieldset>


text:
Q: Get all published posts in Wordpress, performance issues due to long result set I need to build a array like this:
$arrPosts = array(
    thePostID => "The Post Title"
)

I'm doing as follow:
$posts = get_posts(
    array(
        'numberposts' => -1,
        'post_status' => 'published',
        //'post_type' => get_post_types('post', 'opinion')
    )
);

foreach($posts as $post) {
    $article[] = [
        $post->ID => $post->title
    ];
}

But it takes a long time to process which is not suitable (I had to set define('WP_MAX_MEMORY_LIMIT','1024M') which is a lot of memory). I need to get only posts from that are post and opinion custom post type.
Does any knows a better way to achieve this?

A: You can use wp_query() like this,
$args = array(
              'post_type' => 'post',
              'orderby'   => 'title',
              'order'     => 'ASC',
              'post_status' => 'publish', //here you can retrieve posts that are published
              'posts_per_page' => -1,
            );

// The Query
$the_query = new WP_Query( $args );
$posts = array();
// The Loop
if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        $posts['thePostID '] =  get_the_title() ; //change appropiately
    }

} else {
    // no posts found
}
print_r($posts);
/* Restore original Post Data */
wp_reset_postdata();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rendering an active menu element in a menu partial in rails 3 I have a dynamic submenu that is rendered according to which page the user is on. I placed the following code in a _sub_menu.html.erb partial:
Index
Account
Payments`

From my my main view, I call <%= render 'sub_menu' %>, which works.
However, I want to change the class="current" part according to which page the user is on. I was hoping to do this from the render by passing in a local parameter and rendering according to that, but it seems hacky:
<%= render 'sub_menu' , :locals => {:active_item => 'payments'}  %>
Plus the logic becomes really ugly. Is there a better way of doing this?

A: I think you can make use of the block parameter to link_to_unless_current, which provides the content to render when the link is the current page:
<%= link_to_unless_current("Index", :action => 'index') { link_to("Index", {:action => 'index'}, {:class => 'current' }) %>
<%= link_to_unless_current("Account", :action => 'account') { link_to("Account", {:action => 'account'}, {:class => 'current' }) %>
<%= link_to_unless_current("Payments", :action => 'payments') { link_to("Payments", {:action => 'payments'}, {:class => 'current' }) %>

Does that work?

A: You can define an additional helper method, that would be calling link_to_unless_current:
def link_to_current_with_class(name, current_class, options = {}, html_options = {}, &block)
  link_to_unless_current(name, options, html_options) do
    options[:class] = current_class + " " + options[:class]
    link_to(name, options, html_options)
  end
end

and then call it from you navigation partial:
<%= link_to_current_with_class "Index", "current", "/dashboard/index" %>


text:
Q: How to show cell values of raster in ArcGIS I would like to know if it is possible to display a raster cell value in the center of a cell with ArcGIS in the same way that SAGA-GIS does when you zoom in.

A: You could use the Pixel Inspector tool for dynamic viewing
http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//009t00000097000000
Or, could convert the raster to points and label by the values

A: Here is a work around that accomplishes what you want by creating a shapefile of points in the center of each cell:
RasterToPoint_conversion (in_raster, out_point_features, raster_field)

Set display fill to "None"
Label points as values, no offset.


text:
Q: Laravel 5.5 PHPUnit does not display descriptions When I run phpunit its show the test is not passed. But It does not tell me why the test is not passing. I have attached two images to describe this.
Here is the result I get:

I want something I like this, to help me guide in Test Driven Development:

A: You're seeing different results because you're running into two different categories of failures here:
1. The code executed, but your assertion failed.
This happens when PHPUnit gets some assertion that isn't truthy, such as:
$this->assertEquals(1, 0);

When this happens, PHPUnit only sees that you tried to compare 1 and 0 and that's everything PHPUnit knows about this. It can't tell you why the code failed, because you have a business logic error that isn't detectable by PHP.
2. Some code you executed raised an error or exception that wasn't caught.
If you attempt to do something that isn't allowed in PHP (such as referencing a class that doesn't exist), you have a runtime error. In these situations, PHP will offer up more information about the error or provide a call-stack with where an exception occurred, resulting in the more detailed message you're seeing.


text:
Q: Google Calendar API Color Coding Based On Sender I'm looking to create a code that will automatically color code events based on the sender. This would color code events ideally based on the sender, so internal meetings will be differentiated from external meetings.
Thanks in advance!


text: Q: Read single standard UTF-8 string from InputStream in Java There is a stream of serialized C# objects (String fields use standard UTF-8). I'm reading the stream and deserializing it in Java (one object at a time). Java uses MUTF-8 format for the string. DataInputStream.readUTF assumes that format. Is there a way to read just one single "standard" UTF-8 string from input stream?


text:
Q: put list in textbox in c# windowsform So this is my code:
MySqlDataReader msdr = mysqlquery.Reader("SELECT * FROM amount WHERE id=@id", "@id", i);
List<decimal> decimallist = new List<decimal>();

while (msdr.Read())
{
   decimallist.Add(msdr.GetDecimal(1));
   TbAmount.Text = string.Join(" ", decimallist.ToString());
}

so TbAMount is suppossed to get 2 values, but it only gets one. What am I doing wrong?

A: You should assign the string after the loop when the list is filled completely. However, that gives the same result as if you always overwrite it in the loop, so isn't the reason for this issue.
But you use decimallist.ToString() in String.Join which just returns the type name of the list. Since the string implements IEnumerable<char> it compiles but is certainly not what you want.
You should use:
while (msdr.Read())
{
   decimallist.Add(msdr.GetDecimal(1));
}

TbAmount.Text = string.Join(" ", decimallist);

A: Every iteration replaces the value so move below line out of loop.
TbAmount.Text = string.Join(" ", decimallist);


text:
Q: Firebase Deploy: Error: Could not detect language for functions at I'm trying to deploy my firebase project, but Im getting the following error:

=== Deploying to 'my-proj'...
deploying firestore, functions, hosting
cloud.firestore: checking firestore.rules for compilation errors...
[W] undefined:undefined - Ruleset uses old version (version [1]). Please update to the latest version (version [2]).
cloud.firestore: rules file firestore.rules compiled successfully
Error: Could not detect language for functions at

any thoughts?

A: In my case, I missed functions init:
firebase init functions

documentation

A: In my case I use firebase deploy --only hosting command

A: I can't tell what else is perhaps going wrong with your code, but I also had an error that looked like this part:
[W] undefined:undefined - Ruleset uses old version (version [1]). Please update to the latest version (version [2]).

Some of your firebase rules are written using version 1. You may need to go in and add
rules_version = '2';

to the top of your firebase rule set, specifically for Firebase Firestore. You can do this in the firebase console, or in the firestore.rules in your project - which may be a newly generated file in your project.

A: For anyone else who ends up here.   I had setup firebase static hosting 1yr+ ago, and at that point in time hosting was a "function".  Since then, hosting is now a distinct offering separate of functions.
You need to convert the previous "default" function (which 'was' hosting) to hosting offering.

*

*Delete (or edit) firebase.json in the root directory of your firebase project.

*Firebase init hosting -> This will create a new "public" folder.

*Copy your previous functions/public folder to overwrite the new one.

*Delete the previous functions folder altogether.

Now hosting is fixed and you can deploy again.

*Firebase init functions -> This will create a new functions folder, and all of the boilerplate json and .js files.

The problem I was having is the functions folder had both hosting and functions stepping on each other within the functions directory.  The "today" process puts hosting in a separate folder altogether.

A: Please update your rule to version 2 as the error message says.


text:
Q: How to call onCreate of application class while running activity tests using Espresso In my Android app, I have an Application class which extends MultiDexApplication. Let's call it MyApplicationClass In the onCreate() of MyApplicationClass.java, I set some static variables. Then in the onCreate() method of all the activities I get those variables using static methods.
public class MyApplicationClass extends MultiDexApplication {

  private static String value;

  public static void setValue(String value) {
    MyApplicationClass.value = value;
  }

  public static String getValue() {
    return MyApplicationClass.value;
  }
}

Now using Espresso framework, I am writing UI tests for an activity using the following code
public class MyActivityTest{

  @Rule
  public ActivityTestRule activityTestRule =
      new ActivityTestRule(MyActivity.class);

  @Test
  public void testButtonIsVisible() {
     //Some Test code.
  }
}

After running the test from Android Studio, onCreate() method of MyActivity gets called and its tries to get the static variables. But the value of those variables is null. The reason is fairly simple. onCreate() of MyApplicationClass.java doesn't get called in the process.
So how do I call the onCreate() method of an Application class before launching the activity in Espresso?
P.S. Please don't advice regarding the setting and getting of static variables. That the requirement of the code.

A: I had the same problem and spent a lot of time until I realized that we use a custom TestRunner and ovveride the newApplication method. Because of this during tests we used another class for the Application with an empry onCreate method.
Once I switched to the default TestRunner the onCreate from the application was executed as expected.
@Override
@NonNull
public Application newApplication(@NonNull ClassLoader cl,
                                  @NonNull String className,
                                  @NonNull Context context)
        throws InstantiationException,
        IllegalAccessException,
        ClassNotFoundException {

    return super.newApplication(cl,TestPLayerApplication.class.getName(), context);
}


text:
Q: Scala mapping Json and case class now I'm trying to parse json to case class, and I have a problem.
This is my json string:
{"book_id":"1", "book_name":"Skype", "author_name":"bla bla", "author_country":"Poland"}

And I have 2 case classes:
case class Book(bookId: String, bookName: String){}
case class Author(authorNam: String, authorCountry: String){}

So how can I parse the Json into 2 classes?
The output will be:
Book(1, Skype)
Author(bla bla, Poland)

Thank you so much for your help.

A: There are a few solutions for you, the most obvious of them:

*

*Json4s (it supports jackson)

*Spray-Json is a lightweight, clean and efficient JSON implementation in Scala.
UPD Let's consider usage of Json4s:
  object JsonExample extends App {

  import org.json4s._
  import org.json4s.JsonDSL._
  import org.json4s.jackson.JsonMethods._

  case class Winner(id: Long, numbers: List[Int])
  case class Lotto(id: Long, winningNumbers: List[Int], winners: List[Winner], drawDate: Option[java.util.Date])

  val winners = List(Winner(23, List(2, 45, 34, 23, 3, 5)), Winner(54, List(52, 3, 12, 11, 18, 22)))
  val lotto = Lotto(5, List(2, 45, 34, 23, 7, 5, 3), winners, None)

  val json =
    ("lotto" ->
      ("lotto-id" -> lotto.id) ~
      ("winning-numbers" -> lotto.winningNumbers) ~
      ("draw-date" -> lotto.drawDate.map(_.toString)) ~
      ("winners" ->
        lotto.winners.map { w =>
          (("winner-id" -> w.id) ~
           ("numbers" -> w.numbers))}))

  println(compact(render(json)))
}

A: And this is the answer:
object JsonExample extends App {

  import org.json4s._
  import org.json4s.JsonDSL._
  import org.json4s.jackson.JsonMethods._

  implicit val formats = DefaultFormats // Brings in default date formats etc.

  case class Book(bookId: String, bookName: String) {}
  case class Author(authorName: String, authorCountry: String) {}

  val jsonString = """{"book_id":"1", "book_name":"Skype", "author_name":"bla bla", "author_country":"Poland"}"""
  val json = parse(jsonString)
  println(json.camelizeKeys.extract[Book])
  println(json.camelizeKeys.extract[Author])
}

Thank @rukavitsya for this.

A: Well, you could create another class to get the full Json, as a response class:
case class Response(bookId: String, bookName: String, authorNam: String, authorCountry: String){}

You map your response, that i am assuming comes from a server or other service, and then from this you separate into your two other classes, mapping them.
The better you can do in these cases is getting the whole response that you'll use in your use case, or in your code in general, and then treating the data in your code, before displaying or using the received data.
EDIT: to map the response, using your example, you'll have
Response(1, Skype, bla bla, Poland)

then you would do something like
Book(Response.bookID, Response.bookName)
Author(Response.authorName, Response.authorCountry)

Other approach is having your Response being a case class of the other classes, nesting the case classes, so you'll have both classes inside your Response.
Hope it helps. Cheers!


text:
Q: javascript not properly running on my website on IE browser I created a website and it works perfectly fine on chrome but on IE the js doesn't seem to be working. I'm not sure what's going on because I added a < noscript > tag to check if JS wasn't loading but it doesn't show up (which means JS is running fine), and I went to some of those "check if JS is enabled on your browser" sites and they all said it was working.
Then I checked the settings and it had it enabled as well. So JavaScript seems to be working but the JS on my website (such as smoothly scrolling down when I click a link in the navbar) isn't working.
Anyone have any reasons as to why? Am I forgetting to put an extra tag or something. Any help is appreciated

A: document.querySelectorAll returns a NodeList NOT an array. forEach on a NodeList is not supported in IE. See https://developer.mozilla.org/en-US/docs/Web/API/NodeList#Browser_compatibility
It should work if you replace the forEach with a For loop or use the Array.prototype.forEach (which is also documented on the page in the link above)


text:
Q: How can apply a function using data-table? Question
How can one apply a function on one or more variable per unique values of another variable? Something like
dt[,DoStuff(x) ,y]

Example
Consider the mpg data set from ggplot2
require(data.table)
require(ggplot2)
as.data.table(mpg)
     manufacturer  model displ year cyl      trans drv cty hwy fl   class
  1:         audi     a4   1.8 1999   4   auto(l5)   f  18  29  p compact
  2:         audi     a4   1.8 1999   4 manual(m5)   f  21  29  p compact
  3:         audi     a4   2.0 2008   4 manual(m6)   f  20  31  p compact
  4:         audi     a4   2.0 2008   4   auto(av)   f  21  30  p compact
  5:         audi     a4   2.8 1999   6   auto(l5)   f  16  26  p compact
 ---
230:   volkswagen passat   2.0 2008   4   auto(s6)   f  19  28  p midsize
231:   volkswagen passat   2.0 2008   4 manual(m6)   f  21  29  p midsize
232:   volkswagen passat   2.8 1999   6   auto(l5)   f  16  26  p midsize
233:   volkswagen passat   2.8 1999   6 manual(m5)   f  18  26  p midsize
234:   volkswagen passat   3.6 2008   6   auto(s6)   f  17  26  p midsize

I would like to paste together the unique manufacturer names (separated by underscore) for each unique value of fl. I tried
as.data.table(mpg)[,list(x = function(manufacturer) {paste(unique(manufacturer), collapse="_")} ),fl]

Error in `[.data.table`(as.data.table(mpg), , list(x = function(manufacturer) { :
All items in j=list(...) should be atomic vectors or lists. If you are trying something like j=list(.SD,newcol=mean(colA)) then use := by group instead (much quicker), or cbind or merge afterwards.

An alternative solution is
sapply(unique(mpg$fl), FUN=function(x){paste(unique(mpg$manufacturer[mpg$fl==x]),collapse="_")})

A: You could try this:
as.data.table(mpg)[,paste(unique(manufacturer),collapse="_"),by=fl]

Or, if your function is more elaborate you could write it separately:
myfun <- function(x){
  u_x <- unique(x)
  return(paste(u_x,collapse="_"))
}

res <- as.data.table(mpg)[,myfun(manufacturer),by=fl]


text:
Q: Working on 2 mixed data frames I have two dataframes:
> # Create dataframe1
> ID <- c('ID1','ID2','ID3','ID4','ID5','ID6','ID7')
> hr <- c(56,32,38,NA,42,23,35)
> cr <- c(1,4,5,2,2,5,4)
> data1 <- data.frame(ID,hr,cr)
> data1
   ID hr cr
1 ID1 56  1
2 ID2 32  4
3 ID3 38  5
4 ID4 NA  2
5 ID5 42  2
6 ID6 23  5
7 ID7 35  4
>
> # Create dataframe2
> ID <- c('ID1','ID2','ID5','ID7','ID9','ID6','ID7')
> hr <- c(23,13,15,49,22,24,23)
> cr <- c(1,4,5,2,2,5,4)
> data2 <- data.frame(ID,hr,cr)
> data2
  ID hr cr
1 ID1  23   1
2 ID2  13   4
3 ID5  15   5
4 ID7  49   2
5 ID9  22   2
6 ID6  24   5
7 ID7  23   4

If the values in columns ID and cr match in both dataframes, I want to paste dataframe2$hr column onto dataframe 1 (otherwise paste NA), ie. if dataframe1$ID == dataframe2$ID & dataframe1$cr == dataframe2$cr, then paste the value of dataframe2$hr into a new column in dataframe1 and if they don't match, paste NA.
What is the best way of doing this?  I tried this way:
data1$newhr=ifelse(data1$ID%in%data2$ID2 & data1$cr%in%data2$cr2,data2$hr2,"NA")

which works for this small example, however for my larger dataframes (which vary in dimensions) this does not work.  I get the following error message:

Error in $<-.data.frame(*tmp*, "newP", value = c(NA, NA, NA, NA,
  NA,  :
        replacement has 563 rows, data has 48

In addition, a warning message in gwascat_highlight$V2 %in% testfull3$gcSNP & gwascat_highlight$V3 %in%  :

longer object length is not a multiple of shorter object length

I cannot recreate my larger data frames, however is there an alternative method of carrying out this task that I could try?

A: I am assuming that the rows in the dataframes must be in the same order. Else you must perform the check line by line or reorder using merge as suggested by M.D., e.g., t2 <- merge(data1, data2, by = c("ID", "cr"), all.x = TRUE) then comparing the merge against data1).
Split your problem in two:
if (compare_dfs(data1,data2)){
  data1$newhr <- data2$hr
} else {
  data1$newhr <-NA
}

then you need to define the comparison method:
 all(data1[,c("ID","cr")] == data2[,c("ID","cr")])

will work for dfs with the same dimension. You can also use
identical(data1[,c("ID","cr")],data2[,c("ID","cr")])

which will work regardless of dimensions.

A: With library dplyr, you can use the inner_join as  follows:
library(dplyr)
inner_join(data1, data2, by = c('ID', 'cr'))

Output is:
   ID hr.x cr hr.y
1 ID1   56  1   23
2 ID2   32  4   13
3 ID6   23  5   24
4 ID7   35  4   23

A: Is the following what you want?
merge(data1, data2, by = c("ID", "cr"), all.x = TRUE)

Result:
   ID cr hr.x hr.y
1 ID1  1   56   23
2 ID2  4   32   13
3 ID3  5   38   NA
4 ID4  2   NA   NA
5 ID5  2   42   NA
6 ID6  5   23   24
7 ID7  4   35   23

Same can be achieved with dplyr, data.table and so on.


text: Q: Визуально выделить элемент на странице CSS/JS Есть необходимость фокуса на определенных элементах UI (цепляю скрин, что бы было понятно о чем речь). Кто-то делал? Есть-ли готовые решения? И куда копать, что бы такое выделение работало независимо от разрешения? (responsive)


text:
Q: Populating textarea in a modal window Here's my code:
// Open modal window with links
$('.links').colorbox({speed:100, opacity:0.75, html:'

Download links
<textarea name="links"></textarea>
'});

// Populate textarea with links
for(i in linkList) {
    $('#links-colorbox textarea').append('http://site.com/' + linkList[i][0] + '/' + linkList[i][1] + '\n');
}

The problem is the textarea in the modal window doesn't get populated, probably because it's inserted into the DOM on the fly with the modal window plugin I'm using.
Is there a way I can make this work? Thanks.

A: Use oncomplete callback:
$('.links').colorbox({
    speed:100,
    opacity:0.75,
    html:'

Download links
<textarea name="links"></textarea>
',
    onComplete: function() {
        for(i in linkList) {
            $('#links-colorbox textarea').append('http://site.com/' + linkList[i][0] + '/' + linkList[i][1] + '\n');
        }
    }
});


text:
Q: c++ conditional expression assign reference using namespace std;
class A {
    public:
        virtual int r();
};

class B : public A {
    public:
        int r() { return 1; }
};

class C : public A {
    public:
        int r() { return 2;}
};

int main(int argc, char ** argv) {
    B b;
    C c;
    A &a = argc > 1 ? b : c;
    return a.r();
}

with errors:
#g++ a.cc
a.cc: In function 'int main(int, char**)':
a.cc:20:18: error: operands to '?:' have different types 'B' and 'C'
   20 |  A &a = argc > 1 ? b : c;
      |         ~~~~~~~~~^~~~~~~

How can I fix it to bind the reference to either of the two objects?

A: It's just the way the language works, that's all. Note that you can't static_cast from a B to a C either (or vice-versa) which, informally speaking, is required for the branch types of the ternary conditional operator.
You need to write something like
A &a = argc > 1 ? static_cast<A&>(b) : static_cast<A&>(c);


text:
Q: UITextView increase hight like iOS Mail App I have a question , I would  multiple UITextField in my iOS application, but since it's not possible i use editable UITextView, where i set my "placeholder" and my property, this is the code:
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    NSString *presentText = self.textFieldObject.text;

    if (![presentText isEqualToString:@"Message..."] && presentText != nil)
    {
        self.textFieldObject.textColor = [UIColor blackColor];
    }
    else
    {
       self.textFieldObject.text = @"";
       self.textFieldObject.textColor = [UIColor blackColor];
    }
    return YES;
}

-(void)textViewDidChange:(UITextView *)textView
{

    if(self.textFieldObject.text.length == 0)
    {
        self.textFieldObject.textColor = [UIColor colorWithRed:215.0/255.0 green:215.0/255.0 blue:215.0/255.0 alpha:1.0];
        self.textFieldObject.text = @"Message...";
        [self.textFieldObject resignFirstResponder];
    }
}

I would that UITextView increase its hight when I write more text like iOS mail app or Facebook post.
Under and over the UITextView there are any object so they will should move when hight increase. How can I solve the problem?
Thanks a lot.

A: First, disable UITextView's scrollable.
Two options:

*

*uncheck Scrolling Enabled in .xib.

*[TextView setScrollEnabled:NO];
Create a UITextView and connect it with IBOutlet (TextView).
Add a dummy UITextView height constraint with default height, connect it with IBOutlet (TextViewHeightConstraint).
When you set your UITextView's text asynchronously you should calculate the height of UITextView and set UITextView's height constraint to it.
sample code snippet:
 [TextView setText:song.lyrics];

 CGSize sizeThatFitsTextView = [TextView     sizeThatFits:CGSizeMake(TextView.frame.size.width, MAXFLOAT)];

 TextViewHeightConstraint.constant = sizeThatFitsTextView.height;


text:
Q: GNUplot script that works with tab seperated .txt but not with .csv even when the datafile separater is changed I have a GNUplot script that works perfectly with tab separated data, but my data comes in .csv files and it would be really handy to read them direct, any ideas?
Here is a sample of data in comma seprated.csv format, the other is exactly the same but in a .txt and obviously tab by a comma rather than a tab
HEADER
HEADER

Timestamp,Date,Time,Value,Units
1413867843,21/10/2014,05:04:03,0.053,µA
1413867243,21/10/2014,04:54:03,0.091,µA
1413866643,21/10/2014,04:44:03,0.084,µA
1413866043,21/10/2014,04:34:03,20.000,µA
1413846241,20/10/2014,23:04:01,0.041,µA
1413845641,20/10/2014,22:54:01,0.056,µA
1413845041,20/10/2014,22:44:01,0.123,µA
1413844441,20/10/2014,22:34:01,20.000,µA
1413824638,20/10/2014,17:03:58,0.075,µA
1413824038,20/10/2014,16:53:58,0.073,µA
1413823438,20/10/2014,16:43:58,0.103,µA
1413822838,20/10/2014,16:33:58,20.000,µA

Here is the problematic GNUPlot script I use
CSV MIN
#!/gnuplot
set terminal pdf enhanced font "sans,6"

#Filename
set output "BIOSENSE GRAPH TEMPLATE.pdf"
set size ratio 0.71
set pointsize 0.1

set datafile separator ","

#DATA FILES
plot 'ACT.csv'  using 1:4 every::6 title 'Active'  with points pt 5 lc rgb 'red'  axes x1y1

And finally this is the error message I get from GNUplot
line 15: x range is invalid
Any help appreciated!
Thanks


text:
Q: List of Registered Taxonomies of Current Post I am trying to get list of registred taxonomies of current post,
I mean:
register_taxonomy('color',array('thing'),$args) ;
register_taxonomy('shape',array('thing'),$args) ;
register_taxonomy('material',array('thing'),$args) ;
// etc..

So how can I get the list of taxonomies that registred to 'thing' posttype?
Must be something like:
$taxonomies = get_registred_taxonomies_of('thing') ;
print_r($taxonomies) // Show "color,shape,material"...

Any idea? Thank you!

A: You are looking for get_object_taxonomies ex:
$taxonomies = get_object_taxonomies('thing') ;
print_r($taxonomies) // Show "color,shape,material"..


text:
Q: Cordova is not recognized as an internal or extenal command, operable program or batch file When I ran the command line,
cordova platform add android

I got this error message,

cordova is not recognized as an internal or external command, operable program or batch file

However, I could install the ios, not this android. Is there a way to work around this?

A: Given the details you have provided, I would guess that you do not have the android tools on your path.
both the platform_tools and tools directories in the android sdk must be placed on the system path.
if you need additional help, please post more details:

*

*your exact error message

*your operating system

*your system path

You can find complete platform installation guides in the Cordova projects documentation


text:
Q: How to convert decimal values to time values in oracle? I have a table that is formatted like this:
date     | flag    |dec_time
04-MAY-21   2       0.54
04-MAY-21   5       2.18
12-MAY-20   9       6.1
12-MAY-20   10      8
12-MAY-20   42      4
12-MAY-20   11      4.75

I want the output to be like this:
date     | flag    |new_dec_time
04-MAY-21   2       00:54
04-MAY-21   5       02:18
12-MAY-20   9       06:10
12-MAY-20   10      08:00
12-MAY-20   42      04:00
12-MAY-20   11      04.75

Basically transform the values in the dec_time field into time values like the example above in new_dec_time.
This is my SQL so far:
select to_number(replace(dec_time,'.',':')) as new_dec_time

This simply changes replaces the decimal point with the semicolon but doesnt add the 0s where needed. Is there a simple way to go about doing this? Any ideas or suggestions would help.

A: Never rely on default NLS settings if you need exact format. Always specify NLS parameters explicitly (for example, decimal separator in Russian is comma, not period).
So this is the query, if your numbers are restricted to valid time. If not, you'll get nonsense that looks like time. Also Oracle have no time datatype alone, that's why you need to implement operations with strings by yourself.

with a as (
  select 2.18 as h from dual union
  select 0.54 from dual union
  select 6.1 from dual
)
select
  to_char(h, '00D00',
  'NLS_NUMERIC_CHARACTERS='': ''') as tm
from a

| TM     |
| :----- |
|  00:54 |
|  02:18 |
|  06:10 |

db<>fiddle here

A: You want a string result, so don't use to_number()!
You want lpad():
select lpad(replace(dec_time, '.', ':'), 5, '0')


text:
Q: How do I integrate Asp.Net Identity in to a custom MVC/EF application? I want to understand and use ASP.Net Identity and all the tutorials I have done from the official site start with the same template and you add your models to the default context.
This seems to work in their examples, however, when I try to scaffold views off this, I seem to get errors that are not present when trying to scaffold off of a custom/smaller dbcontext (as I used to do in MVC3 EF4.1).
I am having trouble locating best practices and actual real world examples of using identity. I was wondering what should I be doing long term and if anyone knows of actual larger scale tutorials/best practices for using ASP.Net Identity?
In particular, I was wondering:
1) Should I be using two DbContexts per app: one for identity, one for my app?
2) Should I be extending my DbContext for identity?
3) Should I be extending the ASP.Net Identity DBContext for my app?

A: The easiest is if you start a fresh application with authentication and then move your existing code over - that way everything works, and you can then customize the templates. Regarding your questions,
1) As of EF6, you can use several DbContexts with the same Db, so I would generally use the given one for the Identity stuff and define my own context for my own data
2) Would not do that, rather do 3) if I only use one DbContext.


text:
Q: Filtering through / Summarizing a list of numbers in an object Looking for some help in javascript.  Heres the problem
Heres my input:
[
{channel: 471, unit: 1},
{channel: 472, unit: 2},
{channel: 473, unit: 3},
{channel: 474, unit: 5},
{channel: 479, unit: 6}
]

And here is what I am looking for as an output:
Ch: 471-474, 479 #1-3,5-6

So essentially looping through an array of objects to summarize numeric values in a sorted manner. I was originally using a math.max() and math.min() method to find max and min numbers to display like this:
Ch: 471-479

But that is not accounting for the fact that there is no 475,476,477, or 478.
I was also using an Object.keys() method to turn the objects into arrays to then filter through using math.max and min
Any idea how I would do something like this? Is it even possible? Any help is appreciated!
for the sake of being thorough, here is my entire code so far where I am stuck
const regex = /Ch (?<channel>\d+): (?<position>(?:\w|\s)+) #(?<units>\d+)/g;

const inputString = "Ch 471: PRO BM R #5,Ch 472: PRO BM R #4,Ch 473: PRO BM R #3,Ch 481: PRO BM L #5,Ch 482: PRO BM L #4,Ch 484: PRO BM L #3";

const groups = {};

[...inputString.matchAll(regex)].forEach(a => (groups[a.groups.position] ||= []).push({ channel: +a.groups.channel, units: +a.groups.units }));

console.log(groups);

const keys = Object.keys(groups);
console.log(keys)
keys.forEach((key,index)=>{
  let maxChannelNum = Math.max.apply(Math, groups[key].map(function(x) {return x.channel;}))
  let minChannelNum = Math.min.apply(Math, groups[key].map(function(x) {return x.channel;}))
  let maxUnitNum = Math.max.apply(Math, groups[key].map(function(x) {return x.units;}))
  let minUnitNum = Math.min.apply(Math, groups[key].map(function(x) {return x.units;}))
  console.log(`Ch: ${minChannelNum}-${maxChannelNum} ${key} #${minUnitNum}-${maxUnitNum}`)
})

A: First off, you need to clearly define how exactly you want to display your number ranges and what the minimum interval between each number is - for example, if you're expecting the possibility of floating point numbers (say, 471, 472, 472.5, 473...), you'd have to re-define what counts as part of an interval (for example 471-473) and what breaks an interval (in the aforementioned case that would be a 475).
As long as you can define what counts as part of a range and at what point you need to begin a new one, I don't think there is anything stopping you from the naive approach of simply sorting all of your datasets according to their numerical value; in this case giving you the two sets
471, 472, 473, 474, 479

and
1, 2, 3, 5, 6

and then simply looping through them, selecting the first entry of each data set as the beginning of the range and defining the end of a range once it breaks the condition of your range - in this case, being larger than the preceding number by more than one.
I'm sure there are more optimal ways of achieving this, but does anything speak against this approach outright?

A: You could take all numbbers, combine continuous numbers and join them to strings.

const
    update = (array, value) => {
        const
            last = array[array.length - 1],
            lastValue = last?.[1] || last?.[0];

        if (lastValue + 1 === value) last[1] = value;
        else array.push([value]);
    },
    input = "Ch 471: PRO BM R #5,Ch 472: PRO BM R #4,Ch 473: PRO BM R #3,Ch 481: PRO BM L #5,Ch 482: PRO BM L #4,Ch 484: PRO BM L #3",
    temp = input
        .split(',')
        .map(s => s.match(/\d+/g))
        .reduce((r, [a, b]) => {
            update(r[0], +a);
            update(r[1], +b);
            return r;
        }, [[], []])
        .map(a => a.map(b => b.join('-')).join()),
    result = `Ch: ${temp[0]} #${temp[1]}`

console.log(result);


text:
Q: Is it possible to prevent a Case from being forwarded to a S2S connection by looking at a specific field on the Case? We would like to set up a S2S connection to publish Cases to another org.  But we only want cases with the custom field, Client Type = 'TypeA' to be sent.  How can we prevent a user forwarding cases with a different Client Type?  Thanks.

A: I can not give you a direct solution, but there is an indirect way if you are willing to automate s2s sending.
2 steps are required:

*

*remove the button from the page layout (Case list view) - this will
prevent users from manually sending Cases to another org.

*create a trigger to automate sending. Example below.

trigger CaseShareWithConsultingOrg on Case (after insert, after update) {
List<PartnerNetworkConnection> connection = [select Id, ConnectionStatus, ConnectionName from PartnerNetworkConnection
                                                where ConnectionStatus = 'Accepted'];
    if(connection.size() > 0){
        List<PartnerNetworkRecordConnection> recordToShareToInsert = new  List<PartnerNetworkRecordConnection>();
            for(Case myCase: Trigger.new){
                PartnerNetworkRecordConnection recordToShare = new PartnerNetworkRecordConnection();
                recordToShare.ConnectionId = connection[0].Id;
                recordToShare.LocalRecordId = myCase.id;
                recordToShare.SendClosedTasks = false;
                recordToShare.SendOpenTasks = false;
                recordToShare.SendEmails = false;
                if(myCase.Clint_Type__c = 'TypeA') {
                    recordToShareToInsert.add(recordToShare);
                }
            }
            try{
                insert recordToShareToInsert;
            }
            catch (Exception  e){
                System.debug('CUSTOM ERROR === ' + e);
            }
    }
}


text:
Q: Empty List is returning using selenium 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

from selenium.webdriver.common.keys import Keys

from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException

import pandas as pd

from bs4 import BeautifulSoup

import requests as r

import time

from selenium.webdriver.support.ui import Select

PATH="chromedriver.exe"

driver=webdriver.Chrome(PATH)

_list=[]

url=f"https://420love.ca/976-main-st-e/?dtche%5Bsearch%5D=&dtche%5Bcategory%5D=all"

driver.get(url)

driver.maximize_window()

WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "age-gate-m")))

month=driver.find_element_by_id("age-gate-m")

month.send_keys("08")

day=driver.find_element_by_id('age-gate-d')

day.send_keys("19")

year=driver.find_element_by_id('age-gate-y')

year.send_keys("1996")

link=driver.find_element_by_xpath('/html/body/div[1]/div[3]/form/input[1]')

link.click()

time.sleep(4)

main_2=driver.find_elements_by_xpath('//*[@id="main-content"]/div[2]/div[1]/div[1]/a/div/div[1]')

_list.append(main_2)

print(_list)


text:
Q: sqlalchemy: How can I associate object of other table with primary key? I have a Transaction table as
class Transaction(Base):
    __tablename__ = 'transaction'
    id = Column('id', Integer, primary_key=True)
    name = Column('name', String)
    amount = Column('amount', Float)
    category_id = Column('category_id', Integer, ForeignKey('category.id'))
    date_created = Column('date_created', Date, default=datetime.now())
    date_modified = Column('date_modifed', Date, onupdate=datetime.now())

and Category table as
class Category(Base):
    __tablename__ = 'category'
    id = Column('id', Integer, primary_key=True)
    name = Column('name', String)
    subtype = Column('subtype', String)

I add the transaction dataset as
name, amount, category_id
Costo,59.0,5
Costo,20,5
Safeway,6.75,1
Safeway,11,1
Safeway,19,1

and I can see them as well when I query them
for transaction in session.query(Transaction):
    logging.info(transaction)

and I see the data as well
INFO:root:<Transaction(22, Medical Insurance, 110.0, 62, 2013-03-09, None)>
INFO:root:<Transaction(23, AllState Renter Insurance, 100.0, 77, 2013-03-09, None)>

But I do see the categoty_id as 62 and 77.
All I need the their values as objects like
INFO:root:<Transaction(22, Medical Insurance, 110.0, **Medical**, 2013-03-09, None)>
INFO:root:<Transaction(23, AllState Renter Insurance, 100.0, **Insurance**, 2013-03-09, None)>

How can I attach the objects of different table?
I am sure just using primary_key will not suffice, but what else I need to do?
Please advice
I have just started learning about SQLAlchemy

A: You probably need to create a relationship(): http://docs.sqlalchemy.org/en/latest/orm/relationships.html
from sqlalchemy.orm import relationship, backref

class Category(Base):
    __tablename__ = 'category'
    id = Column('id', Integer, primary_key=True)
    name = Column('name', String)
    subtype = Column('subtype', String)
    # This line is new
    transactions = relationship("Transaction", backref="category")

I'm not sure if I entirely understood your question, but this should attach a transactions attribute to each category containing a collection of associated items. Or alternatively:
class Transaction(Base):
    __tablename__ = 'transaction'
    id = Column('id', Integer, primary_key=True)
    name = Column('name', String)
    amount = Column('amount', Float)
    category_id = Column('category_id', Integer, ForeignKey('category.id'))
    date_created = Column('date_created', Date, default=datetime.now())
    date_modified = Column('date_modifed', Date, onupdate=datetime.now())
    category = relationship("category")

to attach objects many-to-one in the opposite direction (as @daydreamer already figured out).

A: After adding the following line in my Transaction, I was able to refer to the Category associated with the transaction
category = relationship('Category')

My class Transaction finally looks like
class Transaction(Base):
    __tablename__ = 'transaction'
    id = Column('id', Integer, primary_key=True)
    name = Column('name', String)
    amount = Column('amount', Float)
    category_id = Column('category_id', Integer, ForeignKey('category.id'))
    date_created = Column('date_created', Date, default=datetime.now())
    date_modified = Column('date_modifed', Date, onupdate=datetime.now())
    category = relationship('Category')

and I can see the output as
INFO:root:<Transaction(28, ATT, 89.0, <Category(148, Utilities, Phone)>, 2013-03-09, None)>
INFO:root:<Transaction(27, Car Gas, 47.0, <Category(146, Utilities, Gas & Fuel)>, 2013-03-09, None)>

Thanks to @David Marx for pointing to the right documentation


text:
Q: little confuse about optionals in swift Maybe I'm very confused idk yet. I thought i understood the basic concept but when playing around in xcode I'm not getting what I thought I should be
Take the following code
var title: String? = "hello world"
println("\(title)")

I thought that this would give me an error because I thought that title should have to be unwrapped since I;m accessing it, but it seems to compile just fine. Can someone shed some light on this.

A: Optionals are Printables, meaning you can print them to an output stream (here the console). You should see something like Optional("hello world") in your console and not hello world

A: All an optional is is that if it is nil, the app won't crash. If you put the elimination mark, and did not assign a value, it would crash.
In an if statement, you can check if the variable is nil:
if (title == nil) {

//this works

}

A: var title: String? = "hello world"
println("\(title)") // This would print out Optional(Title)
var title2: String! = "hello world"
println("\(title2)") // This would print in Title

Optional do not cause your program to crash when they are executed without a value but !(variable) will cause your code to crash if they have no value.
Swift documentation:

As described above, optionals indicate that a constant or variable is allowed to have "no value". Optionals can be checked with an if statement to see if a value exists, and can be conditionally unwrapped with optional binding to access the optional's value if it does exist.

A: As per documentation, your statement will be converted to
var title: Optional<String> = Some("hello world").

From Apple documentation, Optional is
enum Optional<A> {
case Nil
case Some(A)
}

So when you are passing a value to an optional, at the time of declaration, compiler understands, it has got a value and that's why it is not showing error.
But if you do the below code you may get different result.
var title: String? = "hello world"
title = nil
println("\(title)")

It will print "nil" in playground.

A: Based on apple doc

The concept of optionals doesn't exist in C or Objective-C. The
  nearest thing in Objective-C is the ability to return nil from a
  method that would otherwise return an object, with nil meaning "the
  absence of a valid object." However, this only works for objects—it
  doesn't work for structures, basic C types, or enumeration values. For
  these types, Objective-C methods typically return a special value
  (such as NSNotFound) to indicate the absence of a value. This approach
  assumes that the method's caller knows there is a special value to
  test against and remembers to check for it. Swift's optionals let you
  indicate the absence of a value for any type at all, without the need
  for special constants.

Example
let possibleString: String? = "An optional string."
let forcedString: String = possibleString! // requires an exclamation mark

let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString // no need for an exclamation mark

Reference: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html


text:
Q: How should I declare attributes in JS class? I am currently working on an API and I want to create classes, one class Object that retrieves data from tables and a class associated with a table. I'm trying to create a attribute in the Object class which is set while calling the static method get() from a class associated with a table. How should I use the attributes ?
My API is running with express, I'm on Ubuntu 19.04, I'm using ObjectionJS as my ORM, I also use Knex. I have a loader.js file which requires all my model files.
Object.js:
'use strict';

const dbTables = require('../../src/database/Models/loader');

module.exports = class Object {

    constructor () {
        console.log('Test');
    }

    //Get queries

    static get() {
        console.log(`ModelName = ${this.modelName}`);
        const req = 'dbTables.' + this.modelName + '.query()';
        return eval(req);
    }
}

UserClass.js:
'use strict';

const Object = require('./Object');

module.exports = class UserClass extends Object {

    constructor() {
        super('Employee');
        this.modelName = 'Employee';
    }
};

Here is the error I'm getting :
ModelName = undefined
TypeError: Cannot read property 'query' of undefined
    at eval (eval at get (/home/usersio/SafiAPI/src/Classes/Object.js:17:16), <anonymous>:1:20)
    at Function.get (/home/usersio/SafiAPI/src/Classes/Object.js:17:16)
    at app.get (/home/usersio/SafiAPI/index.js:54:28)
    at Layer.handle [as handle_request] (/home/usersio/SafiAPI/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/usersio/SafiAPI/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/usersio/SafiAPI/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/usersio/SafiAPI/node_modules/express/lib/router/layer.js:95:5)
    at /home/usersio/SafiAPI/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/home/usersio/SafiAPI/node_modules/express/lib/router/index.js:335:12)
    at next (/home/usersio/SafiAPI/node_modules/express/lib/router/index.js:275:10)
    at methodOverride (/home/usersio/SafiAPI/node_modules/method-override/index.js:65:14)
    at Layer.handle [as handle_request] (/home/usersio/SafiAPI/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/home/usersio/SafiAPI/node_modules/express/lib/router/index.js:317:13)
    at /home/usersio/SafiAPI/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/home/usersio/SafiAPI/node_modules/express/lib/router/index.js:335:12)
    at next (/home/usersio/SafiAPI/node_modules/express/lib/router/index.js:275:10)

A: Your problem is because your function get() is static and you're trying to get this.modelName on it.
But static functions do not ref to a particular instance of it.
Let's look at some examples:

const dbTables = {
  Employee: {query : () => ['1', '2', '3']},
  Car: {query : () => ['A', 'B', 'C']},
}

class AbstractTable {
    //Get queries
    static get() {
        console.log(`get():`, {this:this, model: this.modelName});
        return dbTables[this.modelName]
            && dbTables[this.modelName].query()
            || null;
    }

    // Same but non static
    getNonStatic() {
        console.log(`getNonStatic():`, {this:this, model: this.modelName});
        return dbTables[this.modelName]
            && dbTables[this.modelName].query()
            || null;
    }

    // Static with args
    static getWithArg(table) {

        console.log(`getWithArg(table):`, {this:this, model: table.modelName, table:table});
        return dbTables[table.modelName]
            && dbTables[table.modelName].query()
            || null;
    }
}
class UserTable extends AbstractTable {

    constructor() {
        super('Employee');
        this.modelName = 'Employee';
    }
};

console.log("--- Test 1 ---");
console.log(UserTable.get()); // get() is static so NO instance (this is undefined)

console.log("--- Test 2 ---");
// Create an instance of UserTable:
const userTable = new UserTable();
console.log("Function:", userTable.get); // This is not defined because get() is static

console.log("--- Test 3 ---");
console.log("Function:", userTable.getNonStatic);
console.log("Result:", userTable.getNonStatic()); // This is not defined because get() is static

console.log("--- Test 4 ---");
// you can also use static and inject the UserTable
console.log("Function:", AbstractTable.getWithArg(userTable));

You can also redefined an abstract static function and use it using super()

const dbTables = {
  Employee: {query : () => ['1', '2', '3']},
  Car: {query : () => ['A', 'B', 'C']},
}

class AbstractTable {
    //Get queries
    static get(modelName) {
        return dbTables[modelName]
            && dbTables[modelName].query()
            || null;
    }
}

class UserTable extends AbstractTable {
  static get() {
    return super.get("Employee");
  }
}

console.log(UserTable.get());

A: Constructors are called when you create an instance of a class.
class Test {
  constructor() {
    console.log('ctor called');
  }
}

const instance = new Test();
// will log 'ctor called'

When you call a static method, you do not create an instance and your constructor is not called. That's the first reason why this.modelName in your get() function is undefined and so you are trying to call query() on something that does not exist.
Try console.log(req) in your get() function.
Second reason is that this in your constructor refers to the instance while this in a static method refers to the class.
One option would be to add a static property to your extending class and set the model name there.

const dbTables = {
  Employee: {query : () => ['1', '2', '3']},
}

/*module.exports =*/ class Object {
    //Get queries
    static get() {
        return dbTables[this.modelName].query();
    }
}

/*module.exports =*/ class UserClass extends Object {
    static modelName = 'Employee';
};

const queryResult = UserClass.get();
console.log("Users: ", queryResult);


text:
Q: running a set of unit tests for each 'implementation' My unit tests (MSTest, using Resharper to run manually) has a number of tests against a particular implementation of an FtpClient. I started off with an implementation of AlexFTP and then switched over to WinSCP when I needed to support SFTP (not just FTP and FTPS). I have a common interface, IFtpClient that all my test cases are based off of.
My question, which has nothing to do with Ftp, is how can I run my suite of test cases for each implementation of an interface?
My code structure looks something like this, and I currently uncomment/comment out the the implementation I want to test
    public IFtpClient GetFtpClient()
    {
            return new AlexPilottiFtpClient();
            // return new WinScpFtpClient();
    }

and then I have my test code
[TestMethod]
public void Should_connect_with_valid_credentials()
{
    IFtpClient client = base.GetFtpClient();
    client.Connect(....)
    Assert(....)
}
[TestMethod]
public void Another_Test2()
{
    IFtpClient client = base.GetFtpClient();
    ...
}
[TestMethod]
public void Another_Test3()
{
    IFtpClient client = base.GetFtpClient();
    ...
}

Anyone have ideas how I can run both (or multiple) implementations as part of my run? Some ideas I can think of include:
1) for loop of each implementation, inside each TestMethod
e.g.
[TestMethod]
public void Another_Test4()
{
    foreach (IFtpClient client in _clientList)
    {
          ...
    }
}

2) duplicate the test methods - one for each implementation and maybe a base method common to all
e.g.
[TestMethod]
public void Another_Test5_AlexFtp()
{
        _client = new AlexPilottiFtpClient();
        this.Another_Test5_Base();
}
[TestMethod]
public void Another_Test5_WinScp()
{
        _client = new WinScpFtpClient();
        this.Another_Test5_Base();
}

private void Another_Test5_Base()
{
        _client.Conect(...);
        Assert(...);
}

3) reside myself that I can't do it (manually) and rely on automated builds to run through all implementations, e.g. via configuration / dependency injection
??? Suggestions would be greatly appreciated. Thanks.

A: I would most likely make an abstract base class defining all the tests, with a single abstract method that returns the implementation of IFtpClient to test.
Then make concrete test classes for each implementation you need to test.
So you would have:
public abstract class FtpBaseTest
{
    public abstract IFtpClient GetClient();

    [TestMethod]
    public void TestOne()
    {
        IFtpClient client = GetClient();

        // do test on client ...
    }

    [TestMethod]
    public void TestTwo()
    {
        IFtpClient client = GetClient();

        // another test on client ...
    }
}

[TestClass]
public class AlexFtpTest
{
    public override IFtpClient GetClient() { return new AlexFtpClient(..); }
}

[TestClass]
public class AnotherFtpTest
{
    public override IFtpClient GetClient() { return new AnotherFtpClient(..); }
}

This would make the tests appear in the runner as separate test cases in different test classes, even though you only have the implementation once.


text:
Q: Is there a cost for a Service Principal that is only to be used with Azure DevOps? I have searched for, but have been able to find anything related to costs when it comes to service principals. I want to set up builds, tests and deployments in Azure DevOps, but the I want to be able to calculate the potential costs.
Maybe its only the actions inside Azure DevOps that adds any costs and not the service principal itself?

A: Service principals don't cost anything. Certain tiers of Azure AD (which service principals are created in) do cost money. The resources you deploy within Azure will definitely cost something


text:
Q: How to make a service (or the system process) impersonate the *elevated* variant of a user account? In my network, there is a Windows 2008 R2 server with network name Dax. On that server, I have (among others, of course):

*

*a hard disk drive, mounted as E:\

*a folder E:\odo

*an SMB  share \\Dax\odo which provides the folder E:\odo to the network

*a user account Dax\Backup
The user Dax\Backup is member of the Dax\Backup Operators group and additionally has full permissions on the share \\Dax\odo as well as on the folder E:\odo.
I also have some client PCs running Windows 10 x64 Enterprise (version 1809). Each client PC has

*

*multiple user accounts which are different from the user accounts on the server (i.e. there is no AD, the client PCs are not joined to a domain)

*a complex and deeply nested data folder with carefully crafted permissions, i.e. every user on a client has access to different parts (subfolders) of the data folder

*a user account Client\Backup which has the same password as the server's account Dax\Backup, and which also is member of the respective client's Client\Backup Operators group.

On the client PCs, I have a software which is able to copy the whole data folder mentioned above, including all permissions, owner info, alternate streams, junctions and so on onto the share \\Dax\odo. I let this software run under user account Client\Backup so that it can read the data folder regardless of the ACLs which are in effect there.
Indeed, folders, files, junctions and so on (i.e. the actual contents of the data folder) are copied without any problem, but adjusting the metadata (e.g. ACLs, ownership) on the destination fails.
I would like to understand why, and of course what I can do about it.
My thoughts and tests so far are:

*

*My client software is copying those files and folders onto the server's share while running as user Backup. Since that user (on the server) is in the Backup Operators group, there should be no problem with changing the metadata while copying or even after having copied a file or folder, because that's exactly the purpose the Backup Operators group should serve.

*If (on the server) I make the user Backup a member of the Administrators group, the problem persists.

*If (on the server) I give the user Dax\Administrator full permission for the share \\Dax\odo as well as for the respective folder E:\odo, and if I run my client software under the account Client\Administrator (that account also has the same password on the clients and the server), the problem does not persist, and the process works as intended.
Furthermore, I have tracked down what I believe is the cause of the problem on the server: Using Sysinternals' process monitor, I have seen that obviously the user Backup on the server, or more precisely, its impersonation by the network service / system process, does not have sufficient privileges. At least, this is what I would make out of the event properties shown below:
High Resolution Date & Time:    04.05.2019 09:27:37,2077520
Event Class:    File System
Operation:  IRP_MJ_CREATE
Result: PRIVILEGE NOT HELD
Path:   E:\Odo\d-LSE\d\temp\test - 2019-05-04 09-27-40\bla.txt
TID:    2812
Duration:   0.0000581
Desired Access: Generic Write, Read Attributes, Write DAC, Write Owner, Access System Security
Disposition:    OpenIf
Options:    Complete If Oplocked
Attributes: n/a
ShareMode:  Read
AllocationSize: 0
Impersonating:  DAX\Backup

In the past few days, I also have learned that for members of certain groups (among them Administrator and Backup Operators) there are two tokens: a normal one and an elevated one, where only the latter enables the special privileges of such groups.
So (please note that this is just naive guessing and that I am not an expert in this field): Could the network service / system process on the server impersonate the non-elevated version of the user account Backup when handling the network traffic on behalf of that user, and could this be the reason for the problem? Could I solve the problem by somehow making the network service / system process impersonate the elevated version of the user account Backup when handling the network traffic on behalf of that user? If yes, how?
P.S. If my above theory is silly, the title of this post will be misleading, so feel free to correct it ...

A: Your theory is correct.  This behaviour can be changed via a registry setting.
In
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

find or create the DWORD value LocalAccountTokenFilterPolicy and set it to 1.  You may then need to reboot.
This will allow remote connections to have unrestricted administrator access.


text:
Q: How to convert to String^ type I am newbie to programming for windows phone, so I have a question. How can i convert type String to its pointer type(String^)? here's fragment from sample of windows phone 8.1 program
Uri^ uri;
String^ ready;
TryGetUri(L"http://abotstars.16mb.com/images", &uri);
filter->CacheControl->ReadBehavior = HttpCacheReadBehavior::Default;
filter->CacheControl->WriteBehavior = HttpCacheWriteBehavior::Default;

create_task(httpClient->GetAsync(uri), cancellationTokenSource.get_token()).then([=](HttpResponseMessage^ response)
{

}, task_continuation_context::use_current()).then([=](task<HttpResponseMessage^> previousTask)
{

    // Check if any previous task threw an exception.
    HttpResponseMessage^ response = previousTask.get();

    ready = response->Source.ToString();

});
// Create a notification for the Square310x310 tile using one of the available templates for the size.
auto tileContent = TileContentFactory::CreateTileSquare310x310Text09();
tileContent->TextHeadingWrap->Text = "Hello World! My very own tile notification";

I want to put response that come from server to Tile. But IntelliSense(VS2013) said, that the left value can't be changed. It says something about lambda value. I don't really know what it wants, but I tried different ways to have this value and always get different errors. What I do wrong?
Sorry for Russian language of SDK :D. So here's an error which show that it can't convert String^
http://i.stack.imgur.com/fztz8.png

A: If someone have similar question - problem was here:
create_task(httpClient->GetAsync(uri), cancellationTokenSource.get_token()).then([=](HttpResponseMessage^ response)
{

}

There were empty brackets.


text:
Q: What causes a Tekton step to fail? Steps succeed or fail based on the output of the command or script they run, but I'm not clear on how exactly this works. Does any output to stderr cause the step to fail? If not, how exactly does Tekton determine if a step has failed or succeeded?

A: It's about the exit code of each steps in your Task.
If one of your steps exits with a non-0 code, then your Task failed. Otherwise it succeeded.


text:
Q: My application crashes before asking for permissions when running the application for the first time it crashes (nothing on logcat). then you can see the requests for permissions and after you give the permission you can open the application and it works fine.
public class MainActivity extends AppCompatActivity {

    String [] PERMISSIONS = {Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    int PERMISSION_ALL  = 1;

    Button record;
    Button play;
    Button stop;

    MediaPlayer mediaPlayer;
    MediaRecorder mediaRecorder;

    String outPutFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //---------------------
        //asking for permission
        //---------------------

        if(!hasPermissions(this, PERMISSIONS)){
            ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
        }
        record = (Button) findViewById(R.id.recordbutton);
        play = (Button) findViewById(R.id.playbutton);
        stop = (Button) findViewById(R.id.stopbutton);

        if (outPutFile==null){
            play.setEnabled(false);
        }

        stop.setEnabled(false);

        outPutFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";

        mediaRecorder = new MediaRecorder();
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mediaRecorder.setOutputFile(outPutFile);

        //---------------------
        //recording
        //---------------------

        record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    mediaRecorder.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                    //Toast.makeText(getApplicationContext(),"error", Toast.LENGTH_LONG).show();

                }
                mediaRecorder.start();
                record.setEnabled(false);
                stop.setEnabled(true);

                Toast.makeText(getApplicationContext(),"recording", Toast.LENGTH_LONG).show();
            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mediaRecorder.stop();
                mediaRecorder.release();
                mediaRecorder = null;
                stop.setEnabled(false);
                play.setEnabled(true);

                Toast.makeText(getApplicationContext(), "Audio recorded", Toast.LENGTH_LONG).show();
            }
        });
        //---------------------
        //playing the record
        //---------------------

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mediaPlayer = new MediaPlayer();

                try {
                    mediaPlayer.setDataSource(outPutFile);
                    mediaPlayer.prepare();

                    Toast.makeText(getApplicationContext(), "Audio Playing", Toast.LENGTH_LONG).show();

                } catch (Exception e) {

                }
                mediaPlayer.start();

                record.setEnabled(true);
            }
        });

    }

    public static boolean hasPermissions(Context context, String... permissions) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }
}

Why is that?
logcat-
07-30 19:03:03.812 4491-4491/com.example.tsuryohananov.voicerecorder E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.tsuryohananov.voicerecorder, PID: 4491
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tsuryohananov.voicerecorder/com.example.tsuryohananov.voicerecorder.MainActivity}: java.lang.RuntimeException: setAudioSource failed.
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6540)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                                Caused by: java.lang.RuntimeException: setAudioSource failed.
                                                                                at android.media.MediaRecorder.setAudioSource(Native Method)
                                                                                at com.example.tsuryohananov.voicerecorder.MainActivity.onCreate(MainActivity.java:64)
                                                                                at android.app.Activity.performCreate(Activity.java:6980)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6540)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

A: I moved that codes:
    mediaRecorder = new MediaRecorder();
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    mediaRecorder.setOutputFile(outPutFile);

to
    record.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mediaRecorder = new MediaRecorder();
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mediaRecorder.setOutputFile(outPutFile);
            try {
                mediaRecorder.prepare();

            } catch (IOException e) {
                e.printStackTrace();

            }
            record.setEnabled(false);
            stop.setEnabled(true);
            mediaRecorder.start();

            Toast.makeText(getApplicationContext(),"recording", Toast.LENGTH_LONG).show();
        }
    });

problem was that at first running the             mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
were running before the user gave the permissions.
I assume that there is other ways, maybe like:
    if (hasPermissions(this, PERMISSIONS)) {
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile(outPutFile);

    }


text:
Q: How to filter JSON data based on another JSON data in typescript I have 2 JSON Data 1. Payers 2. Rules. I need to filter Payers JSON data based on PayerId from Rules JSON data.
{
"Payers": [
{
  "payerId": "12345",
  "name": "Test Payer1"
},
{
  "payerId": "23456",
  "name": "Test Payer2",

},
{
  "payerId": "34567",
  "name": "Test Payer3"
}}

Rules JSON file
  {
  "Rules": [
 {
  "actions": {
    "canCopyRule": true
  },
  "RuleId": 123,
  "description": "Test Rule",
  "isDisabled": false,
  "Criteria": [
    {
      "autoSecondaryCriteriaId": 8888,
      "criteriaType": { "code": "primaryPayer", "value": "Primary Payer" },
      "payerId": ["12345", "34567"]
    }
  ]
}
}]}

I need to filter Payers JSON data based on Rules JSON data if PayerID matches
I need output like below
 {
 "Payers": [
 {
  "payerId": "12345",
  "name": "Test Payer1"
},
{
  "payerId": "34567",
  "name": "Test Payer3"
}
}

How to filter?

A: You can use Array.filter like that (based on your data structure):
const filteredPayers = payersObj.Payers.filter((p) => rulesObj.Rules[0].Criteria[0].payerId.includes(p.payerId));

I can't figure out why your Rules json looks like this, I guess you have multiple rules. If so, you will need to iterate over each rule and invoke includes. Same for Criteria.

A: Code will check each rule and each critirias
and will return payers if payerId found in any of the given rules of any criteria

const payers = {
"Payers": [
{
  "payerId": "12345",
  "name": "Test Payer1"
},
{
  "payerId": "23456",
  "name": "Test Payer2",

},
{
  "payerId": "34567",
  "name": "Test Payer3"
}]}
const rules = {
  "Rules": [
    {
      "actions": {
        "canCopyRule": true
      },
    "RuleId": 123,
    "description": "Test Rule",
    "isDisabled": false,
    "Criteria": [
      {
        "autoSecondaryCriteriaId": 8888,
        "criteriaType": { "code": "primaryPayer", "value": "Primary Payer" },
        "payerId": ["12345", "34567"]
      }
    ]
  }
]
}

const data = payers.Payers.filter(payer => rules.Rules.findIndex(rule => rule.Criteria.findIndex(criteria => criteria.payerId.includes(payer.payerId)) != -1) !== -1)

console.log(data)


text:
Q: "UnboundLocalError: local variable referenced before assignment" after an if statement When I try this code:
tfile = open("/home/path/to/file",'r')

def temp_sky(lreq, breq):
    for line in tfile:
        data = line.split()
        if (    abs(float(data[0]) - lreq) <= 0.1
            and abs(float(data[1]) - breq) <= 0.1):
            T = data[2]
    return T
print(temp_sky(60, 60))
print(temp_sky(10, -10))

I get an error that says
Traceback (most recent call last):
  File "tsky.py", line 25, in <module>
    print(temp_sky(10, -10))
  File "tsky.py", line 22, in temp_sky
    return T
UnboundLocalError: local variable 'T' referenced before assignment

The first print works correctly but the second causes an exception. I tried making T a global variable but then both answers are the same.
What is going wrong, and how can I fix it?

A: FWIW: I got the same error for a different reason.  I post the answer here not for the benefit of the OP, but for the benefit of those who may end up on this page due to its title... who might have made the same mistake I did.
I was confused why I was getting "local variable referenced before assignment" because I was calling a FUNCTION that I knew was already defined:
def job_fn(job):
  return job + ".job"

def do_something():
  a = 1
  b = 2
  job_fn = job_fn("foo")

do_something()

This was giving:
UnboundLocalError: local variable 'job_fn' referenced before assignment

Took me a while to see my obvious problem: I used a local variable named job_fn which masked the ability to see the prior function definition for job_fn.

A: The other answers are correct: You don't have a default value. However, you have another problem in your logic:
You read the same file twice. After reading it once, the cursor is at the end of the file, so trying to read it again returns nothing and the loop is never entered. To solve this, you can do two things: Either open/close the file upon each function call:
def temp_sky(lreq, breq):
    with open("/home/path/to/file",'r') as tfile:
        # do your stuff

This has the disadvantage of having to open the file each time. The better way would be:
tfile.seek(0)

You do this after your for line in tfile: loop. It resets the cursor to the beginning so the next call will start from there again.
Related questions:

*

*Iterating on a file doesn't work the second time

*Why a file is empty after reading it?

A: Your if statement is always false and T gets initialized only if a condition is met, so the code doesn't reach the point where T gets a value (and by that, gets defined/bound). You should introduce the variable in a place that always gets executed.
Try:
def temp_sky(lreq, breq):
    T = <some_default_value> # None is often a good pick
    for line in tfile:
        data = line.split()
        if abs(float(data[0])-lreq) <= 0.1 and abs(float(data[1])-breq) <= 0.1:
            T = data[2]
    return T

A: Before I start, I'd like to note that I can't actually test this since your script reads data from a file that I don't have.
'T' is defined in a local scope for the declared function. In the first instance 'T' is assigned the value of 'data[2]' because the conditional statement above apparently evaluates to True. Since the second call to the function causes the 'UnboundLocalError' exception to occur, the local variable 'T' is getting set and the conditional assignment is never getting triggered.
Since you appear to want to return the first bit of data in the file that matches your conditonal statement, you might want to modify you function to look like this:
def temp_sky(lreq, breq):
    for line in tfile:
        data = line.split()
        if ( abs(float(data[0]) - lreq) <= 0.1 and abs(float(data[1]) - breq) <= 0.1):
            return data[2]
    return None

That way the desired value gets returned when it is found, and 'None' is returned when no matching data is found.

A: I was facing same issue in my exercise. Although not related, yet might give some reference. I didn't get any error once I placed addition_result = 0 inside function. Hope it helps! Apologize if this answer is not in context.
user_input = input("Enter multiple values separated by comma > ")

def add_numbers(num_list):
    addition_result = 0
    for i in num_list:
        addition_result = addition_result + i
    print(addition_result)

add_numbers(user_input)

A: Contributing to ferrix example,
class Battery():

    def __init__(self, battery_size = 60):
        self.battery_size = battery_size
    def get_range(self):
        if self.battery_size == 70:
            range = 240
        elif self.battery_size == 85:
        range = 270

        message = "This car can go approx " + str(range)
        message += "Fully charge"
        print(message)

My message will not execute, because none of my conditions  are fulfill therefore receiving " UnboundLocalError: local variable 'range' referenced before assignment"
def get_range(self):
    if self.battery_size <= 70:
        range = 240
    elif self.battery_size >= 85:
        range = 270

A: To Solve this Error just initialize that variable above that loop or statement. For Example var a =""


text:
Q: get opened chrome tabs from outside the browser I need to check what tabs are opened in chrome, but I can't use the browser to do so. I need to do it from the cmd or from a python\c++ or any language that runs on the host computer, does anyone know how can I do it?
Thank you very much.


text:
Q: Login redirect after blocked content I have some articles that are not accessible to non-registered users. When they press the link it prompts them to login, but after a successful login they are sent to their profile. Instead I want them to be sent to the target article after login. Is that possible?

A: You need to override the default login specified in your Administration back end from your custom code you can do so with the following:
Take the url that you would like to redirect the user to after they have successfully logged in and apply the 'base64_encode' function to it. For example,
$redirectUrl = urlencode(base64_encode($redirectUrl));
// a base64_encode of index.php?option=com_pizzapie' yeilds: 'aW5kZXgucGhwP29wdGlvbj1jb21fcGl6emFwaWU='

Prepend the '&return=' query string to your newly encoded $redirectUrl. For example,
$redirectUrl = '&return='.$redirectUrl;

Append that $redirectUrl to the Joomla Login Url. For example,
$joomlaLoginUrl = 'index.php?option=com_users&view=login';
$finalUrl = $joomlaLoginUrl . $redirectUrl;

When you display that $finalUrl, it should look something like this: 'index.php?option=com_users&view=login&return=aW5kZXgucGhwP29wdGlvbj1jb21fcGl6emFwaWU='
The controller.php file in the com_users checks the contents of the 'return' in the JRequest object (the Joomla query access object). If it is set and in the base64 format, it base64_decode(s) it and applies that redirection.


text:
Q: how to implement Queue in javaBeans I have an instance of NotificationEvent. i have added this instance in a queue whenever this instance is created.Name of the queue should be NotificationQueue.
structure of NotificationEvent is like this :
public class NotificationEvent {

    private String sender;
    private String receiver;
    private String message;

    /**
     * @return the sender
     */
    public String getSender() {
        return sender;
    }

    /**
     * @param sender the sender to set
     */
    public void setSender(String sender) {
        this.sender = sender;
    }

    /**
     * @return the receiver
     */
    public String getReceiver() {
        return receiver;
    }

    /**
     * @param receiver the receiver to set
     */
    public void setReceiver(String receiver) {
        this.receiver = receiver;
    }

    /**
     * @return the message
     */
    public String getMessage() {
        return message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(String message) {
        this.message = message;
    }

What should be the required structure of NotificationQueue?

A: I suggest to not reinvent the wheel again. The interface Queue, already in the Java run-time library, defines operations which a queue should have. Here a brief tutorial for the Queue interface and the Queue JavaDoc. Well, here also a example of using Queue implementations.
You can create a Notification queue object like this:
Queue<NotificationEvent> eventQueue = new LinkedList<NotificationEvent>;

or, if you insist on having your own type for the queue:
public class extends LinkedList<NotificationEvent> {
    /**
     * Constructs an empty list.
     */
    public NotificationQueue() {
    }

    /**
     * Constructs a list containing the elements of the specified collection,
     * in the order they are returned by the
     * collection's iterator.
     * @param c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public NotificationQueue(Collection<? extends NotificationEvent> c) {
        super(c);
    }
}

...

NotificationQueue eventQueue == new NotificationQueue();

Note:
LinkedList is not the only available implementation of the Queue interface, see the Queue JavaDoc for other implementations already available in the Java run-time libs. Of course, you could also write your own implementation of the Queue interface.


text:
Q: Algorithm Downheap For the downheap function, we normally compare the two children values at first, determine which one is smaller, and compare the parent value with the smaller child's value, and at last switch.
But what if I just compare the parent value to the left child, if bigger, switch. And compare the right child, if bigger, switch.
Will this work?

A: As long as each parent is smaller than its children - it will work. Note that in your case you may be making two switches. Each switch requires you to compare the new parent to its children (the grandchildren of the original parent). So you'd better make one switch and not two.


text:
Q: macro MOCK_METHOD passed 3 arguments, but takes just 2 error with std::pair I'm using Google Mock 1.6.0. When using the MOCK_METHODN macros, it seems to think I'm passing 3 arguments for methods that return a std::pair:
#include <gmock/gmock.h>
#include <utility>
class IFoo {
public:
    virtual std::pair<int, int> bar() = 0;
};
class MockFoo {
public:
    MOCK_METHOD0(bar, std::pair<int, int>());
};
int main() {
    MockFoo f;
    return 0;
}

Compiler output (GCC 4.6.3):
main.cpp:9:44: error: macro "MOCK_METHOD0" passed 3 arguments, but takes just 2
main.cpp:9:5: error: 'MOCK_METHOD0' does not name a type

This error doesn't appear if I:

*

*Replace std::pair<int, int> with a simple type like int or void

*Use on a method that has a std::pair argument, instead of returning it

A: In FAQ GoogleMock:

You still need a typedef if the return type contains an unprotected comma, but that's much rarer.

Use typedef

A: This appears to be a bug with version 1.6.0. The same code works with version 1.7.0, so the best solution would be to upgrade to that.
Alternately, compiling with Clang also runs into the same error, but provides a strong clue where the error is:
main.cpp:9:38: error: too many arguments provided to function-like macro invocation
    MOCK_METHOD0(bar, std::pair<int, int>());
                                     ^
main.cpp:9:5: error: C++ requires a type specifier for all declarations
    MOCK_METHOD0(bar, std::pair<int, int>());
    ^~~~~~~~~~~~
2 errors generated.

Looks like a buggy macro expansion is interpreting the , inside std::pair<int, int> as another argument. Therefore, you can also work around the issue by avoiding the ,, for instance using a typedef:
typedef std::pair<int, int> MyType;
class MockFoo {
public:
    MOCK_METHOD0(bar, MyType());
};


text:
Q: can't install atom editor on arch linux package re2-20170101-1 is not installing.
i have also marked extra as siglevel never because before it was giving signature error
error: re2: signature from "Anatol Pomozov <anatol.pomozov@gmail.com>" is invalid
:: File /var/cache/pacman/pkg/re2-20170101-1-x86_64.pkg.tar.xz is corrupted (invalid or corrupted package (PGP signature)).
Do you want to delete it? [Y/n] n

then i marked extra as siglevel never
[extra]
SigLevel = Never
Include = /etc/pacman.d/mirrorlist

so i get this error.(404 error was also before adding signlevel = Never)
[pi@vision pacman.d]$ sudo pacman -S atom
resolving dependencies...
looking for conflicting packages...

Packages (5) apm-1.18.1-1  electron-1.4.16-2  minizip-1:1.2.11-1
             re2-20170101-1  atom-1.16.0-1

Total Download Size:     0.15 MiB
Total Installed Size:  217.06 MiB

:: Proceed with installation? [Y/n]
:: Retrieving packages...
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.f4st.host : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirrors.cicku.me : Failed to connect to mirrors.cicku.me port 80: Connection refused
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from ftp.nluug.nl : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from ftp.myrveln.se : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.hactar.xyz : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from archlinux.dynamict.se : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from archlinux.mirror.ba : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.tyborek.pl : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirrors.uni-plovdiv.net : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.neuf.no : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.archlinux.no : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.js-webcoding.de : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirrors.n-ix.net : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.de.leaseweb.net : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.gnomus.de : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirrors.dotsrc.org : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from archlinux.mirrors.uk2.net : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.aur.rocks : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from ftp.acc.umu.se : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.23media.de : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror5.bastelfreak.org : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from gluttony.sin.cvut.cz : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.datacenter.by : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from ftp.rnl.tecnico.ulisboa.pt : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.kaminski.io : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from ftp.snt.utwente.nl : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirrors.manchester.m247.com : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.cinosure.com : The requested URL returned error: 403
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirrors.niyawe.de : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from ftp.byfly.by : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirrors.lug.mtu.edu : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from archlinux.mirror.kangaroot.net : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.nl.leaseweb.net : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirrors.rit.edu : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.fluxent.de : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.netcologne.de : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.united-gameserver.de : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from ftp.wa.co.za : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from arch.midov.pl : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.is.co.za : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from archlinux.surlyjake.com : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from archlinux.mirror.wearetriple.com : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from archlinux.vi-di.fr : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from foss.aueb.gr : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from ftp.swin.edu.au : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from archlinux.openlabto.org : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.metalgamer.eu : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.vfn-nrw.de : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from archimonde.ts.si : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from archlinux.mirrors.linux.ro : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirrors.kernel.org : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from fooo.biz : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.es.its.nyu.edu : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from www.gtlib.gatech.edu : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.pseudoform.org : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from ftp.halifax.rwth-aachen.de : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from mirror.vpsfree.cz : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from ftp.lysator.liu.se : The requested URL returned error: 404
error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from archlinux.polymorf.fr : The requested URL returned error: 404
 re2-20170101-1-x86_64   1190.0   B  0.00B/s 00:00 [######################] 100%
(5/5) checking keys in keyring                     [######################] 100%
(5/5) checking package integrity                   [######################] 100%
:: File /var/cache/pacman/pkg/re2-20170101-1-x86_64.pkg.tar.xz is corrupted (invalid or corrupted package (checksum)).
Do you want to delete it? [Y/n]

A: *

*Pacman said, the key is corrupted:

error: re2: signature from "Anatol Pomozov "
  is invalid :: File
  /var/cache/pacman/pkg/re2-20170101-1-x86_64.pkg.tar.xz is corrupted
  (invalid or corrupted package (PGP signature)). Do you want to delete
  it? [Y/n] n

note: SigLevel = Never you should not avoid the check to staying safe.
Instead of that, You must refresh your keys list:
pacman-key --refresh-keys

If you never imported the whole archlinux keyring before, you should get it (before refresh):
pacman-key --populate archlinux

*Finally, can see that pacman cannot find the archive.
This occur often when the pkg revision has changed and outdated.
(you could not see it before, cause of the PGP error)

error: failed retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from
  mirror.f4st.host : The requested URL returned error: 404 error: failed
  retrieving file 're2-20170101-1-x86_64.pkg.tar.xz' from
  mirrors.cicku.me : Failed to connect to mirrors.cicku.me port 80:
  Connection refused

Let's refresh your repositories database :
sudo pacman -Sy
pacman -S atom