text:
Q: How to implement horizontal scroller with ImageViews I would like to displaying set of Images downloaded from web and display it as part of bottom horizontal thumbnail view,in horizontal scroll view mode,whenever i take photos,it needs to be added to list of images in bottom.
What type of native component to be used,I tried recycler view and horizontalGridView(LeanBack V17 APIs,a extension of recycler view),in both of them,I am getting horizontal scrolling issues,which I am not able to fix it out,(scroll issue related to recycle view)
Is there anyother alternative native APIs that can be used for achieving the horizontal listview of Images.

A: Yes, you can use LinearLayout with attribute
 android:orientation="horizontal"
You also need to put this LinearLayout in ScrollLayout to have scroll over it.
When the image is downloaded, you can add it in ImageView inside LinearLayout

A:  <android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:layout_height="match_parent"
    >

    </android.support.v7.widget.RecyclerView>
    Activity:

    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(manager);
    adapter = new EventListAdapter(this, imageList);
        recyclerView.setAdapter(adapter);

    Adapter:
    public class ImageListAdapter extends RecyclerView.Adapter<ImageListAdapter.ViewHolder> {

    private final LayoutInflater inflator;
    private Context context;
    private List<Integer> imageList = new ArrayList<>();

    public ImageListAdapter(Context context, List<Integer> imageList) {

        this.context = context;
        this.imageList = imageList;

        inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = inflator.inflate(R.layout.eventlistadapterdata, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Integer image = imageList.get(position);

holder.view.setImageResource(image);
    }

    @Override
    public int getItemCount() {
        return imageList.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
      ImageView view;

        ViewHolder(ImageView view) {
            super(view);
            this.view = view;
        }
    }

}


text:
Q: Java - Error when serializing/deserializing the date I'm having trouble to figure out what is this date format: 2019-02-28T12:17:46.279+0000. I have tried different date formats to get this result but nothing worked. Closest pattern was: yyyy-MM-dd'T'HH:mm:ss.SSSZ But with this pattern output was like this: 2019-02-28T12:17:46.279-0000 (- is after seconds instead of +)
I get this exception:
Caused by: java.lang.IllegalArgumentException: 2019-02-28T12:17:46.279+0000
    at org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl$Parser.skip(XMLGregorianCalendarImpl.java:2932)
    at org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl$Parser.parse(XMLGregorianCalendarImpl.java:2898)
    at org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl.<init>(XMLGregorianCalendarImpl.java:478)
    at org.apache.xerces.jaxp.datatype.DatatypeFactoryImpl.newXMLGregorianCalendar(DatatypeFactoryImpl.java:230)
    at __redirected.__DatatypeFactory.newXMLGregorianCalendar(__DatatypeFactory.java:132)
    at javax.xml.bind.DatatypeConverterImpl.parseDate(DatatypeConverterImpl.java:519)
    at javax.xml.bind.DatatypeConverter.parseDate(DatatypeConverter.java:431)
    at eu.europa.ec.my.custom.package.model.mapper.XsdDateTimeConverter.unmarshal(XsdDateTimeConverter.java:23)

My XsdDateTimeConverter class looks like this:
public class XsdDateTimeConverter {

    public static Date unmarshal(String dateTime) {
        return DatatypeConverter.parseDate(dateTime).getTime();
    }

    public static String marshalDate(Date date) {
        final Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return DatatypeConverter.printDate(calendar);
    }

    public static String marshalDateTime(Date dateTime) {
        final Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateTime);
        return DatatypeConverter.printDateTime(calendar);
    }
}

And parsed date in my postgres db looks like this:
move_timestamp timestamp(6) with time zone

2019-02-28 12:17:46.279+00

In my rest method I use ObjectMapper like this.
MyCustomResponseDto responseDto = customService.getCustomResponseDto(query);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
String strValue = mapper.writeValueAsString(responseDto);
return Response.ok(strValue).build();

I guess what I really wanted is what is the right pattern for this date. I can go in this page: http://www.sdfonlinetester.info/ and enter my pattern (e.g. yyyy-MM-dd'T'HH:mm:ss.SSSZ) and it gives you an actual date output for that pattern. I need the other way around. I want to enter my date and it will give me the right pattern for it.

A: tl;dr
OffsetDateTime.parse(
    "2019-02-28T12:17:46.279+0000" ,
    DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSX" , Locale.ROOT )
)

java.time
You are using terrible Calendar class that was supplanted years ago by the java.time classes.
ISO 8601
Your input string is in standard ISO 8601 format, designed for human-readable machine-parseable textual representations of date-time values. That is a good thing.
The java.time classes use ISO 8601 formats by default when parsing/generating strings.
OffsetDateTime
You should be able to simply parse with OffsetDateTime.
OffsetDateTime.parse( "2019-02-28T12:17:46.279+0000" )

…but unfortunately the optional COLON character being omitted from the offset (+00:00) is a problem. The OffsetDateTime class has a minor bug where it refuses to parse without that character. The bug is discussed here and here.
The ISO 8601 standard permits the colon's absence, but practically you should always include it. The OffsetDateTime class is not alone; I have seen other libraries that break when the colon or padding zeros are absent. I suggest asking the publisher of your data to use the full ISO 8601 format including the colon.
The workaround for the OffsetDateTime bug is to define a DateTimeFormatter explicitly.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSX" , Locale.ROOT ) ;

Then parse.
String input = "2019-02-28T12:17:46.279+0000" ;
OffsetDateTime odt = OffsetDateTime.parse( input , f ) ;

To generate text in full standard ISO 8601 format, simply call toString.
String output = odt.toString() ;

See this code run live at IdeOne.com.

output: 2019-02-28T12:17:46.279Z

The Z on the end means UTC, that is +0000 or +00:00. Pronounced "Zulu". Very commonly used, more immediately readable than the numeric offset.
If you want same output format as your input, use the same DateTimeFormatter.
String output = odt.format( f ) ;

A: You may try below code
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.ENGLISH);
String lastmod =  format.format(new Date());

A: Save yourself a mountain of trouble and save the epochtime in millis. Only parse and render dates in UIs. Very very few cases of scheduling for humans require a computer to know hours, day, week, month, year... But saving an instant in time is just a 'long'.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can images under other have focus (for hovering over)? I have a page-full of thumbnails, let's call them A,B,C, etc.   They are laid out like:
A,B,C,D,E,
F,G,H,I,J,
K,L,M,N .. etc.
When you hover-over one, it gets z-index:+1 and enlarges to 2.5 times size - hence, if we hover over A, it enlarges & completely obscures B and F and G.
Therefore to next see e.g. B one must move the mouse away from the enlarged version of A (at which point another image with enlarge) and then move the mouse back to B.
Hence lots to screen 'flashing' etc.
Is there a way to display A, but when the mouse moves away from its top-left portion, the underlying next in line (B) has focus and enlarges.
I looked at HTML's <area> and <map> tags but without success.
Currently I have:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>...</title>

DGF 1

DGF 2

DGF 3

DGF 4

DGF 5

DGF 6

DGF 7

DGF 8

DGF 9

DGF10

DGF11

DGF12

DGF13

DGF14

DGF15

...

I can use JavaScript/JQuery if needed.

A: The problem you have is, that the .F1 elements still stays in hover state even when the mouse is "outside" of their area, as long as the child element (.I1) is hovered.
There is a way to circumvent the problem, althoug it is a bit hacky, as it needs an additional div element just for the effect. Add an additional div element to the html like this:

Next you use the following rules for your CSS:
.hoverme { position: absolute; width: 100%; height: 100%; z-index:2; }
.F1 > .hoverme:hover ~ .I1 { width:300px; height:auto; position: absolute; z-index:1; left:0px; top:0;}

The trick is, that we are using an overlay element (with z-index:2) which "senses" the hover, but the CSS rules are applied to the .I1 via the CSS sibling selector (~).

A: You can put fully transparent elements over the original images (with the same floating style) and make a JavaScript that uses these transparent elements to track the mouse and resize the images beneath them.

DGF 1

DGF 2

DGF 3

JSFiddle
You can remove the div's background color style, it just for the clear vision. And don't forget to set the div_hover's opacity to 0.


text:
Q: On deleting C++ pointers OK..so this confuses the hell out of me. I am dealing with some legacy C++ code parts of which I have a feeling are just not safe, but I am not 100% sure. Here's a snippet, for example of the risky stuff.
struct A {
    A() : a_ptr(0) {}
    A(some_type *ptr) : a_ptr(ptr) {}
    const some_type *a_ptr;
};

struct B {
    B() : b_ptr(0) {}
    B(some_type *ptr) : b_ptr(ptr) {}
    const some_type *b_ptr;
};

struct Data {
    Data(...) {//-Stuff that doesn't invole aptr_list or bptr_list;
    }
    ~Data() {
        for(std::vector<A*>::iterator itr = aptr_list.begin(); itr != aptr_list.end() ++itr) {
            delete *itr;
        }
        for(std::vector<B*>::iterator itr = bptr_list.begin(); itr != bptr_list.end() ++itr) {
            delete *itr;
        }
    }
    std::vector<A*> aptr_list;
    std::vector<B*> bptr_list;
private:
    Data(const Data&);
    Data& operator=(const Data&);
};

Then in the implementation, I find:
void some_func(...) {
    //-Inside some function
    Data& d = get_data(...);
    ...
    for(...) {
         some_type *sptr = dynamic_cast<some_type*>(a_source_of_some_type_pointer);
         A* a = new A(sptr);
         B* b = new B(sptr);
         d.aptr_list.push_back(a);
         d.bptr_list.push_back(b);
    }
}

I am a little uneasy about the same pointer sptr being used in the implementation above; would this create problems when the destructor of Data is invoked? On the other hand, it looks like we have two new calls for A* and B* and exactly two deletes, so if the destructor in Data is not deep - and maybe that's where I need clarification, then perhaps this is safe after all and my concern is misplaced? I did notice that the structs A and B for instance don't have any destructors defined, so I hope it is not deep. But I am not sure if this means their pointer data will be freed up or not. Appreciate expert insights as always.
Thanks for your time and interest.

A: A and B do not have a user defined destructor, so nothing INSIDE a or b gets destroyed (other than the actual memory it holds being freed up, but since sptr is just held there, it is not being deleted). [Obviously, if A or B contains some other class, say a std::string or a std::vector, that class would be destroyed].
So, in other words, your code is just fine like it is - a and b only holds a copy of sptr, but it's never deleted [in this bit of code, if it needs deleting later, that's a different matter].

A: Data::~Data() will not destroy sptr pointer. It will call A::~A() and B::~B() only.
I'm not sure what you want to do, but if you want a deep destruction you need to make sure you don't free a memory address which was already freed by someone before.
It depends on implementation requirements, but ideally the user who allocated the object should free as well. So since this sptr is allocated been by someone else, if you free it you might get a dangling pointer.

A: sptr is not owned by either A or B, so this is correct.

A: If we shall be really finical then the code can leak.
If d.aptr_list.push_back() needs and fails to reserve more capacity, then the memory pointed to by a and b will leak.
for(...) {
     some_type *sptr = dynamic_cast<some_type*>(a_source_of_some_type_pointer);
     A* a = new A(sptr);          // Allocate memory
     B* b = new B(sptr)           // Allocate memory (and missing semicolon!!)
     d.aptr_list.push_back(a);    // If this fails,
     d.bptr_list.push_back(b);    // or this,
}                                 // then exception is thrown and memory is lost
                                  // (unless you catch the exception and
                                  // perform a delete).

You should use a smart pointer like std::unique_ptr to wrap around the pointers for safety.
Your lists should be of type std::vector<std::unique_ptr<A>> and std::vector<std::unique_ptr<B>>.
In some_func the code could read something like this:
some_type *sptr = dynamic_cast<some_type*>(a_source_of_some_type_pointer);
d.aptr_list.push_back(std::unique_ptr<A>(new A(sptr)));
d.bptr_list.push_back(std::unique_ptr<B>(new B(sptr)));


text:
Q: Symfony3 FormBuilder with associative array In advance, sorry for my english...
I have a problem with my symfony form which seem simple but i don't understand how to do.
I have a user class which has an argument "salaries". This is an array of object "salary" with an id, a label and an amount.
When i add a user, i want to fill my objects "salary". I want for each instance of salary a widget with the label (which is in my object salary) and the input to put the amount.
I tried with collectionType but it doesn't seem to work.
I tried to create a field in my object user per salary but i can't create the setter and getter dynamically.
Just for information, i don't use Doctrine.
If it's not clear, i can explain in French, it will be better...
Here's my userType.php :
$builder
->add('name', TextType::class, array('label'=>'Name : '))
->add('lastname', TextType::class, array('label'=>'Lastname : '))
->add('salaries', CollectionType::class, array('entry_type' => salaryType::class));

My salaryType.php :
public function buildForm(FormBuilderInterface $builder, array $options){

        $builder->add('amount', TextType::class, array('label'=> $builder->getData()->getLabel(), 'required' => false));
        $builder->getForm();
}

And my twig :

Salary

        {% for salary in formUser.salaries %}

{{ form_label(salary.label) }}{{ form_widget(salary.amount) }}

        {% endfor %}

A: in your userType replace this
   ->add('salaries', CollectionType::class, array('entry_type' =>
 salaryType::class));

By
$builder->add('salaries', EntityType::class, [
                    'class' => 'NameBundle:salary',
                    'empty_value' => 'Choise a Salary',
                    'label' => 'Salary',
                    'required' => false,
                    'query_builder' => function (SalaryRepository $er){
                        return $er->findAll();
                    }
                ]);


text:
Q: Почему RecyclerView не правильно обновляет данные? Столкнулся с такой проблемой, что методы notifyItemRmoved() и notifyItemInserted() не правильно обновляют данные после их вызова. Удаляю item из позиции 1, все нормально, удаляю потом из этой же позиции item который сместился из позиции 2 в 1, удаляется item ниже него, и все в таком духе.
Код метода адаптера, для удаления items за ранее:
public void removeItem(final Item item) {
    int position = this.items.indexOf(item);
    this.items.remove(position);
    super.notifyItemRemoved(position);
}

Вызывал notifyItemRangeChange() после notifyItemRemoved(position); все равно не помогает. В общем recycler напрочь отказывается нормально работать с этими методами, проблему решает только notifyDataSetChanged но им не особо хочу пользоваться.
Из-за чего может быть такая проблема, может кто нибудь знает?

A: Проблема может возникать если в адаптере hasStableIds возвращает true, а getItemId возвращает не уникальный id а просто текущую позицию элемента.


text:
Q: Permanent fix for lockfileVersion of npm-shrinkwrap to lockfileVersion@1, it automatically makes lockfileversion@2? I am getting this when I am trying to push my code into github actions or building dockerimage.
 shell: /usr/bin/bash -e {0}
npm WARN read-shrinkwrap This version of npm is compatible with lockfileVersion@1, but package-lock.json was generated for lockfileVersion@2. I'll try to do my best with it!

I tried to implement this Link it works but again after some commit I am getting the same error and I have to repeat the same procedure again and again.
Any fix for that?

A: Look in your .gitignore if you have the lines :
package-lock.json
node_modules/
if not,then add them,
after that look in your Github repository and delete the package-lock.json file and the node_modules directory (if any)
Important Edit :
My bad, Kevin Martin is right the official documentation tell us to add it to the repository for CI/CD.

This file is intended to be committed into source repositories, and
serves various purposes:
Describe a single representation of a dependency tree such that
teammates, deployments, and continuous integration are guaranteed to
install exactly the same dependencies.
Provide a facility for users to "time-travel" to previous states of
node_modules without having to commit the directory itself.
To facilitate greater visibility of tree changes through readable
source control diffs.
And optimize the installation process by allowing npm to skip repeated
metadata resolutions for previously-installed packages.

But for my case (Azure Devops) i had a lot of trouble with it.


text:
Q: Should tags that are essentially pointers to other network sites have a link and an automatic warning? The Data Science site recently emerged from beta. There's a [data-science] tag on Stack Overflow. I've just added a link to that site in the tag description. SO also has a [statistics] tag which would arguably be a red-flag that the question should have gone to Cross Validated.
Keeping SO pure as a programming/coding site will require migration of even more questions and I'm not seeing a lot of support for that function. I can close SO questions but I cannot migrate them with a single vote. It requires 4 or 5 votes to even move a predominantly statistics question to Cross Validated. That seems excessive.
Leaving it this way seems a burden on the moderators (and to experienced SO users). In the case of the new site that has no migrate-to option in the close panels, I could flag all the "data-sciency" questions (with little programming meat), but I also want to limit the moderator workload.

*

*Shouldn't there be better support for warning users of off-topic questions for one site, but the possibility of on-topic-ness on another? This seems especially important for forums where there is a potential overlap of conceptual content

*Shouldn't the number of votes to migrate be more in line with the number of votes to close?

A: Conventional wisdom on Stack Exchange is that if Topic X becomes on-topic on a site - whether because the site was created or its scope was expanded - then there's no reason for Topic X to be made off-topic on another network site where it was already on-topic. I've seen this firsthand in a couple of cases - notable, Astronomy Stack Exchange, whose questions are by and large on-topic on Physics Stack Exchange. Astronomy SE being created didn't lead to astronomy being removed from Physics's scope, and users who ask on Physics aren't discouraged from posting there. The same principle applies here: If people on Stack Overflow are asking and answering data science questions that are on-topic for SO, there's no reason to move them elsewhere.
It's not a bad idea to point people to Data Science Stack Exchange in the tag wiki, but be careful when you do. Keep a couple things in mind:

*

*Don't point them there if you don't know the scope of the site. This irks me a lot about migrations: people not properly knowing the scope of the site they migrate a question to. That's one reason why you can't migrate stuff single-handedly (unless you're a mod); it reduces human error in that regard.

*If you do mention the site, phrase things so that you note that it's an option to ask there - and users shouldn't feel obligated to do so.

*Additionally, talk briefly about the scope of the site in the full tag wiki (not just the excerpt). I know that most people don't read tag wikis, but if someone does, and sees that Data Science Stack Exchange is a possibility for them, the least you can do is provide them with some basic information about its scope and the sort of questions they take (and see my first bullet!).

It might be worth asking someone who knows the site for their input on your tag wiki edit, just to make sure you've got it right. It can't hurt.

A: Considering that there are over 1300 open questions with the data science tag on Stack Overflow, I'm not sure that it's fair to say that no data science questions are on topic there. Remember, sites can have overlapping topics. That said, there's a request on Meta Stack Overflow to get rid of the tag entirely:
Burninate the [data-science] tag?
With so many questions using it, though, that takes a lot of teamwork to clear it from existing questions or retag questions that need a better tag to prep for it being removed.
I'm not personally a fan of this but my understanding is that, in some cases, Stack Overflow does do this, such as the history tag, which currently reads:

DO NOT USE THIS TAG. Questions about the history of programming are off-topic. For questions about browser history, use [browser-history] instead. For questions about the JavaScript library, use [history.js]. For questions about the HTML5 API, use [html5-history]. For questions about version control, use [revision-history]. For questions about recalling inputs in an entry box, use [input-history].

That said, there are very good reasons that migrations are limited the way they are. For a migration to go through several things are required, as mentioned in the FAQ for migrations:

*

*Don't migrate crap.
A subject being generally on topic elsewhere doesn't mean that all questions should be move there - only good questions.

*Question must be less than 60 days old (even for moderators).

*Questions may only be migrated to sites that have migration paths and each site can only have up to five paths leading away from them. Explanation is here.

*No migration paths are established to or from Beta sites.
This is because beta sites are expected to find their own community. A huge influx of questions from an established site will overwhelm a new community and they will be unlikely to manage it. As such, only moderators can migrate to beta sites.

*Questions must receive at least four votes to migrate (out of five total close votes) in order to be migrated (non-SO sites it's only three).

I'm not quite sure why you think more votes are needed to migrate than to close. Close votes (for any reason other than gold badge duplicate votes) require five close votes. Migrations are a type of close vote. Also, as I said, out of the five close vote slots, only four (on SO) need to be migration votes.
So, please, don't flag stuff that's older than 60 days for migration and avoid flagging huge numbers of things for migration to new beta sites. In the case of Cross Validated, it's possible that many of the questions were already asked there, so migrating large numbers of questions makes more work for them to figure that out. Bulk migrations are extremely rare as the CMs have to do them.
So, if it's one or two new questions and there's a migration target, judge the quality of the question. If it's good, vote to close and migrate to that site. If it's bad, just close the question.
If there's no migration target, and a good question, you can flag for migration. It helps if you know the target site and are able to attest to whether the question would be on topic there or not.
Old questions (older than 60 days) that are off topic on Stack Overflow should just be closed. Trying to migrate them is a waste of everyone's time.


text:
Q: Is there a word to describe words that can be spelled different ways? Is there a word in English to describe words that can be spelled more than one way?
For example:

*

*colour and color

*favourite and favorite

However, this shouldn't be limited to words spelled differently in different dialects, though I'm not sure what other case there would be.

A: The word you are looking for is variant:

a different spelling, pronunciation, or form of the same word
Dictionary.com

Wikipedia uses the term "spelling variant", which indicates more clearly that it is a difference in spelling, not pronunciation or form.

A: *

*Synonym

A word or phrase that means exactly or nearly the same as another word or phrase in the same language
  https://en.oxforddictionaries.com/definition/synonym

*Homologue

A word shared by two languages or dialects.
  https://en.wiktionary.org/wiki/homologue

There are homonyms, homographs and homophones but none of these describes words which mean the same and are spelled differently.
'Color' and 'favorite' are the American English spellings; 'colour' and favourite' are the British English method. They are pronounced the same in that persons on either side of the Atlantic would pronounce both pairs of words the same.
Thus the pairs of words sound the same, mean the same, but are spelled differently.
This was dealt with, previously, in Stack Exchange :

What term means "words that look alike and mean alike, across two languages"?

The conclusion was either 'cognate' or that there was no technical definition.
'Spelled' and 'spelt' both mean the same, but are pronounced differently and have different spellings. They are both, currently, in use in English.
There are words within British English that sound the same, mean the same and can be spelled differently, but, usually, it is because one spelling is older, such as 'intreat' and 'entreat', the second being considered either dated or archaic. Thus one effectively drops out of use and is no longer considered the 'proper' way to spell the word.
Within English there are many words of similar, or even identical, meaning which come from different sources - Latin, Greek, French and so forth. These are called synonyms and since your example is one of different countries but with the same language, then 'synonym' would be technically correct.
Homophones sound the same, but have different meanings.
Homographs are written the same but sound differently.
There is debate, apparently, whether a homonym must be both a homophone and a homograph :

https://www.vocabulary.com/articles/chooseyourwords/homonym-homophone-homograph/

'Flower' and 'flour' are homophones; sounding the same, but with different meanings.
'Sow' to plant seeds, and 'sow', a female pig, are homographs, written the same but sounding differently and with different meanings.
'Well' meaning a waterhole and 'well' meaning healthy are spelled the same, sound the same, but have different meanings and are usually considered to be homonyms.


text:
Q: google drive cache taking too much space I recently found that google drive is taking too much space (50GB) although I only made 3GB available offline.
On my Mac and PC I had too go and delete the cache folder.
Is there a way to avoid it? I don't have such issues with dropbox


text:
Q: Requesting help for mysql division query I am trying to write a mysql query on following table. However, not really getting the expected result. Any suggestion would be very helpful.
"Find employee SSno for those employees who work for at least all those departments that the employee with SSno 444505555 works for".

A: Not tested:
SELECT
    DISTINCT empSSNO
FROM
    <YourTableName>
WHERE
    dno in (
        SELECT
            dno
        FROM
            <YourTableName>
        WHERE
            empSSNO = '444505555'
    );

A: Try and check if this works:
select empSSno, GROUP_CONCAT(dno) as dnos from your_table where dnos like CONCAT('%',
(select GROUP_CONCAT(dno) as dnos from your_table where empSSno == '444505555' GROUP BY empSSno)), '%') GROUP by empSSno

One assumption which I am taking here is that the dno for employees are entered in the sorted order in the table. For example for every employee, dno 1 would come before dno 2.


text:
Q: Scoring difference between seemingly equivalent Solr queries As I understand Solr's scoring function, the following two queries should be equivalent.
Namely, score(q1, d) = score(q2, d) for each docuement d in the corpus.
Query 1: evolution OR selection OR germline OR dna OR rna OR mitochondria
Query 2: (evolution OR selection OR germline) OR (dna OR rna OR mitochondria)
The queries are obviously logically equivalent (they both return the same set of documents). Also, both queries consist of the same 6 terms, and each term has a boost of 1 in both queries. Hence each term is supposed to have the same contribution to the total score (same TF, same IDF, same boost).
In spite of that, the queries don't give the same scores.
In general, a conjunction of terms (a OR b OR c OR d) is not the same as a conjunction of queries ((a OR b) OR (c OR d)). What is the semantic difference between the two types of queries? What is causing them to result in different scorings?
The reason I'm asking is that I'm building a custom request handler in which I construct the second type of query (conjunction of queries) while I might actually need to construct the first type of query (conjunction of terms). In other words, this is what I'm doing:
Query q1 = ... //conjunction of terms evolution, selection, germline
Query q2 = ... //conjunction of terms dna, rna, mitochondria
Query conjunctionOfQueries = new BooleanQuery();
conjunctionOfQueries.add(q1, BooleanClause.Occure.SHOULD);
conjunctionOfQueries.add(q2, BooleanClause.Occure.SHOULD);

while maybe I should actually do:
List<String> terms = ... //extract all 6 terms from q1 and q2
List<TermQuery> termQueries = ... //create a new TermQuery from each term in terms
Query conjunctionOfTerms = new BooleanQuery();
for (TermQuery t : termQueries) {
    conjunctionOfTerms.add(t, BooleanClause.Occure.SHOULD);
}

A: I've followed femtoRgon's advice to check the debug element of the score calculation. What I've found is that the calculations are indeed mathematically equivalent. The only difference is that in the conjunction-of-queries calculation we store intermediate results. More precisely, we store the contribution to the sum of each sub-query in a variable. Apparently, stopping in order to store intermediate results has an effect of accumulating a numerical error: Each time we store the intermediate result we're losing some accuracy. Since the actual queries in the application are quite big (not like the trivial example query), there's plenty of accuracy to be lost, and the accumulated error sometimes even changes the ranking order of the returned documents.
So the conjunction-of-terms query is expected to give a slightly better ranking than the conjunction-of-queries query, because the conjunction-of-queries query accumulates a greater numerical error.


text:
Q: onClick(), I want to add table row I want to add row on every click, but my code is replacing the same row.
Also tried to keep if outside addTable function but this did not work for me.
I tried many solutions but failed. Could anyone please help me here?
I have added my code below, Please check and let me know.

import { useState } from "react";
import "./App.css";
const App = (props) => {
  const [count, setCount] = useState(0);
  var [items, setItems] = useState([]);
  function addTable() {
    setCount(count + 1);
    if (count <= 10) {
      setItems(

          5 x {count}
          {5 * count}

      );
    }
  }
  console.log(count);
  return (
    <>

        <button onClick={addTable}>
          Click to generate Multiplication tables of 5{" "}
        </button>

            Multiplication
            Results

{items}

    </>
  );
};

export default App;

A: Well you're overwriting items in your onChange, you need to append to it:
setItems([
    ...items,

      5 x {count}
      {5 * count}

]);

But I would probably do instead is:
import { useState } from "react";
import "./App.css";
const App = (props) => {
  const [count, setCount] = useState(0);
  var [counts, setCounts] = useState([]);
  function addTable() {
    setCount(count + 1);
    if (count <= 10) setCounts([...counts, count]);
  }
  console.log(count);
  return (
    <>

        <button onClick={addTable}>
          Click to generate Multiplication tables of 5{" "}
        </button>

            Multiplication
            Results

{counts.map((c) => (

            5 x {c}
            {5 * c}

        )}

    </>
  );
};

export default App;

A: When you call setItems you're replacing the current state with the new row.
I've removed the section that adds JSX to state (and removed that state altogether) and replaced it with two values: the current times table value, and an upper limit.
The new function getRows then has a simple loop that adds JSX to an array and returns that instead.
(Additionally I've disabled the button when the count exceeds the limit so you can't add any more rows.)

const { useState } = React;

const App = () => {

  // New constants
  const timesTable = 5;
  const limit = 10;

  // One state
  const [count, setCount] = useState(0);

  // The button updates the count
  function updateCount() {
    setCount(count + 1);
  }

  // And we have a simple loop to push the right
  // number of rows into an array which is
  // then returned
  function getRows(count) {
    const rows = [];
    for (let i = 0; i < count; i++) {
      rows.push(

          {timesTable} x {i}
          {timesTable * i}

      );
    }
    return rows;
  }

  return (

        <button
          disabled={count > limit}
          onClick={updateCount}
        >Add row to {timesTable}x table
        </button>

            Multiplication
            Result

        {getRows(count)}

  );
}

ReactDOM.render(
  <App />,
  document.getElementById('react')
);
.button { margin-bottom: 1em; }
table { border-collapse: collapse; }
th { text-transform: uppercase; }
tr:nth-child(odd) { background-color: #efefef; }
td, th { padding: 4px 8px; }
td { border: 1px solid #dfdfdf; }


text:
Q: How can I set up a dedicated screen area for an application in Python? A good example is MS OneNote. It has the option to be fixed to one side of the screen and pushes all other windows to the side. When maximizing or resizing other windows, they can only expand up to the edge of OneNote. Does Python have this capability using Tkinter or another module? Thank you for any assistance.

A: The win32 feature you're looking for is called Application Desktop Toolbars - it allows your application to cooperate with the shell and reserve space along the side, similar to the taskbar.
If you want to implement this yourself, you'll likely need to use Win32 somehow.
It looks like there's a python wrapper for this, however: searching for python and appbar turned up wxAppBar which seems to be a python wrapper for it.

A: See the Microsoft documentation on "Windows" and "Window Features". This being windows-specific stuff, the only way to set these properties is using the Win32 API or similar.
The pywin32 module exposes the Win32 API to Python. There's even a pywin32 tag!

A: Tkinter has very little control over the behavior of the rest of the windows on the OS. There's no built-in cross-platform function for this.


text:
Q: Alloy Language Example I started to learn alloy and for this question I don't know how to complete my code.
Description:
There are three lines shown:

*

*the Jubilee line running north to south from
Stanmore ; and

*the Central Line running west to east to Epping; and

*the Circle line running
clockwise through Baker Street.

Question
There is no station in 3 line.
Line Circle forms a circle.
Line Jubilee forms a straight line that start from Stanmore
There is a station between Stanmore and Baker Street
we can travel from Baker Street to Epping


text:
Q: Unable to connect to azure SQL through Point-to-Site VPN connection We setup a Point-to-Site azure VPN gateway to allow us to connect to our Virtual Machines and azure SQL instance. The gateway is linked to the Virtual Network where our VM's live, and the Azure SQL has a firewall rule to allow connections from That virtual network. We are able to connect to the VM's but not to the Azure SQL.
I tried linking the Virtual network to the Azure SQL through the firewall settings, it didn't help.

A: I assume you are using Azure SQL database. It's public and does not deploy in a VNet. Also, VNet Service Endpoints don't extend to on-premises. So It did not help to connect to Azure SQL database over VPN connection. If you want it to work, you need whitelist your on-premise client public IP address in the firewall of Azure SQL database.
Otherwise, you need to deploy your SQL instance in a VNet, so you need to use Azure SQL Database managed instance. You could follow this quickstart: Configure a point-to-site connection to an Azure SQL Database Managed Instance from on-premises


text:
Q: Using Except on Dictionaries with Object as Value until now i had 2 dictionaries of type Dictionary<string, int> and needed to get everything which is in dict1 but not in dict2 using except. Example:
Dictionary<string, int> dict1 = new Dictionary<string, int>
{
    { "aaa", 1 },
    { "bbb", 2 }
};

Dictionary<string, int> dict2 = new Dictionary<string, int>
{
    { "aaa", 2 },
    { "bbb", 2 }
};

var newDict = dict1.Except(dict2);

newDict now contains { "aaa", 1 } which is what i expect, because the value is different.
My problem is, that we needed an additional value in the dictionary so we changed Dictionary<string, int> to Dictionary<string, MyObject>. When i use except now, i don't get the result i'd like to. Example:
public class MyObject
{
    public MyObject(string name, int someNumber)
    {
        myString = name;
        myInt = someNumber;
    }

    public string myString { get; set; }
    public int myInt { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, MyObject> dict1 = new Dictionary<string, MyObject>
        {
            { "aaa", new MyObject("abc", 1) },
            { "bbb", new MyObject("def", 2) }
        };

        Dictionary<string, MyObject> dict2 = new Dictionary<string, MyObject>
        {
            { "aaa", new MyObject("abc", 2) },
            { "bbb", new MyObject("def", 2) }
        };

        var newDict = dict1.Except(dict2);
    }
}

newDict now contains all kvp from dict1, but i actually only want to have the first entry from dict1. I think that is because values of MyObject are not being compared. What can i do to solve this? Is there maybe an easy way via Linq?
Thanks in advance!

A: You need to either implement GetHashCode() and Equals for your MyObject class or use a custom equality comparer for KeyValuePair<string,MyObject>:
public class MyObjectComparer : IEqualityComparer<KeyValuePair<string,MyObject>>
{
   public bool Equals(KeyValuePair<string, MyObject> obj1, KeyValuePair<string, MyObject> obj2)
   {
        if (obj1 == null) return obj2 == null;
        if (obj2 == null) return false;

        if (obj1.Key != obj2.Key) return false;

        if (obj1.Value == null) return obj2.Value == null;
        if (obj2.Value == null) return false;

        return obj1.Value.myInt == obj2.Value.myInt &&
               obj1.Value.myString == obj2.Value.myString;
   }
   public int GetHashCode(MyObject obj)
   {
       if (obj == null) return 0;
       int hash = obj.Key.GetHashCode();
       if (obj.Value == null) return hash;
       return hash ^ obj.Value.myInt.GetHashCode() ^ obj.Value.myString.GetHashCode();
   }
}

And now pass this comparer to Except():
var newDict = dict1.Except(dict2, new MyObjectComparer());

A: You need to implement object.Equals(object other) in your MyObject.
Depending on how you define equality between your objects, it could look like this:
public override bool Equals(object other)
{
    if(!(other is MyObject))
    {
        return false;
    }
    var o = other as MyObject;
    return myString.Equals(o.myString) && myInt == o.myInt;
}

As René says in the comment, it usually is a good idea to also implement GetHashCode when you implement Equals.

A: Dictionary<string, string> result = dObject.Where(x=> x.key != "ex").ToDictionary(k => k.Key, k => k.Value.ToString());


text:
Q: SSH Private Key doesn't automatically load on startup Whenever i start up my "Ubuntu 16.04" PC i always need to manually run ssh-add to add the default private key path ~/.ssh/id_rsa,
I added it to .ssh/config file:
IdentityFile /home/me/.ssh/id_rsa

Still didn't work, when i try to ssh it gives the following and asks for password:
$ ssh root@xx.xx.xx.xx -vvv
OpenSSH_7.2p2 Ubuntu-4ubuntu2.4, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /home/me/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "xx.xx.xx.xx" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to xx.xx.xx.xx [xx.xx.xx.xx] port 22.
debug1: Connection established.
debug1: identity file /home/me/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/me/.ssh/id_rsa-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.4
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.9p1 Debian-5ubuntu1.10
debug1: match: OpenSSH_5.9p1 Debian-5ubuntu1.10 pat OpenSSH_5* compat 0x0c000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to xx.xx.xx.xx:22 as 'root'
debug3: hostkeys_foreach: reading file "/home/me/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/me/.ssh/known_hosts:10
debug3: load_hostkeys: loaded 1 keys from xx.xx.xx.xx
debug3: order_hostkeyalgs: prefer hostkeyalgs: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519-cert-v01@openssh.com,ssh-rsa-cert-v01@openssh.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: ciphers stoc: chacha20-poly1305@openssh.com,aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,aes128-cbc,aes192-cbc,aes256-cbc,3des-cbc
debug2: MACs ctos: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,zlib@openssh.com,zlib
debug2: compression stoc: none,zlib@openssh.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: host key algorithms: ssh-rsa,ssh-dss,ecdsa-sha2-nistp256
debug2: ciphers ctos: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: ciphers stoc: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
debug2: MACs ctos: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: MACs stoc: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
debug2: compression ctos: none,zlib@openssh.com
debug2: compression stoc: none,zlib@openssh.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: ecdh-sha2-nistp256
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: aes128-ctr MAC: umac-64@openssh.com compression: none
debug1: kex: client->server cipher: aes128-ctr MAC: umac-64@openssh.com compression: none
debug3: send packet: type 30
debug1: sending SSH2_MSG_KEX_ECDH_INIT
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:m4LxapdqnUrO1cpFpX6YpxXR8bPTsfvW73fhgpb0+8Y
debug3: hostkeys_foreach: reading file "/home/me/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/me/.ssh/known_hosts:10
debug3: load_hostkeys: loaded 1 keys from xx.xx.xx.xx
debug1: Host 'xx.xx.xx.xx' is known and matches the ECDSA host key.
debug1: Found key in /home/me/.ssh/known_hosts:10
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey after 4294967296 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug2: set_newkeys: mode 0
debug1: rekey after 4294967296 blocks
debug1: SSH2_MSG_NEWKEYS received
debug2: key: /home/me/.ssh/id_rsa (0x56130221f5c0), explicit, agent
debug3: send packet: type 5
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,password
debug3: start over, passed a different list publickey,password
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/me/.ssh/id_rsa
debug3: send_pubkey_test
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey,password
debug2: we did not send a packet, disable method
debug3: authmethod_lookup password
debug3: remaining preferred: ,password
debug3: authmethod_is_enabled password
debug1: Next authentication method: password
root@xx.xx.xx.xx's password:

A: I figured out the issue, I used ssh-add -L to list the used public keys i found out that it was different than the one in id_rsa.pub, i guess sometime ago i accidentally replaced the original public key file with another one, so now it is working normally


text:
Q: C# WPF Show Image from Mysql i'm a student and i am bad at programing.
I saved the images in my mysql database for each player. I created a program where I can list some soccer players from my database. When i click on a listed player in datagrid, a new window appears with the information about the player. Everything works, but now i want a picture of the selected player to be displayed on the information window from the database. Can anybody help me? My english is not the best (i'm 17) so i hope you can understand what i mean.
This is what i tried to do but i don't know how to continue. PS. It's in WPF.
 MySqlCommand cmd = new MySqlCommand("SELECT Bilder FROM spieler WHERE Bilder='{8}'");
        MySqlDataReader rdr1 = cmd.ExecuteReader();

        try
        {
            conn.Open();
            while (rdr1.Read())
            {
                // image1... I don't know what to write here
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show("Fehler: " + ex);
        }

        rdr1.Close()

A: Just get it using a byte[] casting beforehand:
while (rdr1.Read())
{
   byte[] data = (byte[])reader[0]; // 0 is okay if you only selecting one column
   //And use:
   using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
   {
      Image image = new Bitmap(ms);
   }
}

UPDATE:
In WPF, use the BitmapImage:
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
{
    var imageSource = new BitmapImage();
    imageSource.BeginInit();
    imageSource.StreamSource = ms;
    imageSource.CacheOption = BitmapCacheOption.OnLoad;
    imageSource.EndInit();

    // Assign the Source property of your image
    yourImage.Source = imageSource;
}

A: What is column's type where you hold the image?
You could try somehing like this
Image tmp = ImageConverter.ConvertFrom(rdr1.GetStream("photo"));

where photo is name of your column


text:
Q: Merging in github I'm working on a collaborative HTML website with a friend.  He has made a suggestion to modify two of the links on my page.  I only want to use one of his two suggestion.  How do I, on Github, only choose part of what he wants to change, to be merged into the rest?

A: There is more than one way to handle this situation. All commits are on a given collection of files (blob), so this could work out in a few different ways:

*

*The pull request includes two separate commits, one of which you do not wish to include. You (a) merge the pull request (b) back out of the commit you don't wish to include using something like git rebase -i HEAD~3 to include the last three commits (your merge and the two edits by your friend). This blog post is helpful to understand interactive rebasing

*The pull request includes a single commit of both of these lines. You can choose to:

*

*Merge the commits noting that you will manually edit the file after in a subsequent commit

*Ask your friend to add another commit that includes the removal of that line (you can do that on the PR branch and wait for that update before merger -- Pull Requests are updated as the fork is updated)

All three of these cases end up in the same conclusion, but they have different workflows that may be preferred to trigger certain builds (in Travis CI, for example) or to document certain actions in your commit history. No matter what, don't over think it and pick whatever works for you and your collaborators.


text:
Q: Migrating cruisecontrol to jenkins I want to migrate My jobs from cruisecontrol to Jenkins.
What are the steps that I need to do to achieve this ?

A: 1) Install Jenkins
2) Use the Jenkins docs to create some simple jobs (in other words, learn how Jenkins works but using it for some simple demo projects)
3) Examine your existing cruise control jobs and break them up into groups whose builds are similar.
4) Migrate one group at a time by first creating a Jenkins job form one of the Cruise Control projects, then create the other jobs based on the first (Jenkins lets you create new jobs based on an existing job).

A: If you don't have specific needs, the migration is easy as CruiseControl.NET simply execute task and build reports, as all other continuous integration tools.

*

*Simply create new tasks in Jenkins

*Fill it with the executable tasks you had in CC.NET

*(eventually) need to improve the dashboard if you
want specific information

A: You did not specify your Build/Test/Deploy Steps or of any special needs ,
But as a Vanilla CI would be
1) Build using MSBuild
2) Test Using MSTest
3) Deploy using MSBuild/NANt/ANT/Powershell or even Batch scripts .
All Those steps can be easily replicated to Jenkins Because there are dedicated plugins for all of them .
I would suggest for you to select a simple Build>Test>Deploy Flow from CC.NET and recreate it in Jenkins, after that copying it for other projects,


text:
Q: RecyclerView scroll to desired position without animation Previously, when I want to scroll a ListView to a desired position, I will use
listView.setSelection(row);

The ListView will be scrolled without any animation - Android List View set default position without animation
Now, I want to achieve the same effect on RecyclerView. I try to perform
((LinearLayoutManager)recyclerView.getLayoutManager()).scrollToPositionWithOffset(row, 0);

However, there is scrolling animation, which I would like to avoid.
Is there any way I can perform programmatically scrolling, without animation?
This is the animation I meant - https://youtu.be/OKsUKwBLoks
Note, I had already tried the following ways. All of them do generate animation.

*

*scrollToPositionWithOffset

*smoothScrollToPosition

*scrollToPosition

A: Add this line in your layout.xml
android:overScrollMode="never"

EDIT:
Another way to scroll recycleview
recyclerView.smoothScrollToPosition(position);

A: You can scroll without animation with:
recyclerView.scrollToPosition(position)

A: I know I'm a little late with this answer but it may help someone else.
Try following (at least I could not see any animation when using it):
Kotlin:
    //-- Immediately jump to the position in RecyclerView without delay or animation.
    mRecyclerView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            mRecyclerView.scrollToPosition(position)
            mRecyclerView.viewTreeObserver.removeOnGlobalLayoutListener(this)
        }
    })

Java:
mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            mRecyclerView.scrollToPosition(position);
            mRecyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
});

A: This can be re-produced easily when you calling notifyItemInserted() with scrollToPosition() at same time.
Animation is caused by DefaultItemAnimator in RecyclerView default item animator class.
I found Youtube video that re-produced problem by other person.
And I has solution too:

*

*First, scroll to last position with scrollToPosition().

*Second, wait a little bit to let layout manager to finish scrolling.

*Third, add item into your adapter data set.

*Fourth, calling notifyItemInserted() and scrollToPosition() now.

I have code example but written in c# , but it does same to kotlin with lambda expression. If you need accessing RecyclerView inside Adapter, you might want to look into Adapter.onAttachedToRecyclerView().
if (Adapter.ListData.Count > 2) Adapter.RecyclerView.ScrollToPosition(Adapter.ListData.Count - 1);
Adapter.RecyclerView.PostDelayed(() =>
{
    Adapter.ListData.Add(new ItemSimplyfiedAdapter.Standard
    {
       //Some new item inserting into data set.
    });
    Adapter.NotifyItemInserted(Adapter.ListData.Count - 1);
    Adapter.RecyclerView?.ScrollToPosition(Adapter.ListData.Count - 1);
}, 100);


text:
Q: Can someone explain me how to use the cookie example from the redux-effects page? I'm not sure how to get a cookie, actually I'm not sure how to access its value. As I understand, there is a middleware that returns a resolved Promise with the value of the cookie:
import cookie from 'component-cookie'

export default function ({dispatch, getState}) {
  return next => action => {
    if (action.type !== 'COOKIE') {
      return next(action)
    }

    switch (action.verb) {
      case 'set':
        return Promise.resolve(cookie(action.name, action.value))
      case 'get':
        return Promise.resolve(cookie(action.name))
    }
  }
}

What is not clear, how to read its value from a reducer for example?
See more on their github.


text:
Q: Exploiting SUID files with LD_PRELOAD and IFS I've been reading about IFS exploitation and LD_PRELOAD Privilege escalation by overriding functions. Although these are two completely different questions, I've decided to post them together and hope that isn't a problem. Though both of these are very old, I've been told that they can both still be used for privilege escalation and I would love to look into that. However, I've ran into some problems.
So, let's begin by making the SUID file, /tmp/suid.
#include <unistd.h>

int main() {
  system("/bin/date");
}

This calls /bin/date. The idea is that we can change the internal field separator and deceive the file into running something else with the privileges that it currently holds. This can be done (or can it?) by making a new file called bin contain the malicious code that the attacker put in a custom location. Then we change the $PATH variable and make it so  that locations are first searched inside our custom path, where our malicious fake binary is located. Then by changing the internal field separator to '/', instead of running /bin/date the program will run /tmp/fakepath/bin with argument date, which can potentially trigger privilege escalation.
When I attempt the method described dankalia.com, it fails. /bin/date gets executed instead. If I just type bin date into the console the malicious binary does get started, but it doesn't when it's being invoked through /tmp/suid.
I thought that the vulnerability is patched and that it simply ignores the IFS variable, but then a post on stackoverflow got me interested. (C: IFS System() Vulnerability). Can anyone confirm to me if this works or not, and what I am doing wrong? Thanks.
As for the LD_PRELOAD, I'll keep it rather simple.
define _GNU_SOURCE
#include <stdio.h>

int puts(const char *str) {
  printf("lel");
}

Use the following command line to compile:
gcc –Wall –fPIC –shared –o puts.so puts.c –ldl

Then, override the function puts with preload tricks:
LD_PRELOAD=./puts.so ./vuln_program_that_uses_puts

This works quite well. However, when dealing with a SUID file and when we're talking about privilege escalation, this ain't happening. LD_PRELOAD doesn't work well with SUID files and for a good reason. I've been told that "you can get it to work but that it's hard". Ideas?
Thanks in advance, and sorry for the long questions.

A:
I've been told that "you can get it to work but that it's hard". Ideas?

The operating system is wise to these sorts of tricks, and most are remediated now. Te general idea is setuid, sudo and friends don't use an unprivileged user's environment.
The following offers more reading:

*

*suid-binary vulnerabilities

*Breaking the links: Exploiting the linker
If all you want is a setuid binary to break into the system:

*

*shutdown the computer

*mount the hard drive

*rename ls (or other program like date)

*copy sudo to ls (or other program like date)

*unmount and reboot


text:
Q: Angular: how to send data from child component to parent component? I'm learning Angular. I've read the documentation and five blog posts and it's as clear as mud. I have two templates in my view. The child template has a button. When the user clicks the button I want an element (an instructions card) to show in the parent template. When the user clicks the button again I want the element to not show. I.e., the child button toggles the parent element on and off.
<button (click)="toggleInstructions()">Instructions</button>

In my header (child) component I made an output event emitter sendData, a boolean variable showInstructions, and a function that toggles the showInstructions between true and false.  After logging showInstructions (works great!) it calls sendData to emit the data. I created a new variable myData because I'm confused about the use of this.
import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent {
  @Output() sendData = new EventEmitter<boolean>();

  showInstructions: boolean = false;

  toggleInstructions(myData: boolean) {
    console.log("Clicked!");
    switch (true) {
      case (this.showInstructions === true):
      this.showInstructions = false;
      break;

      case (this.showInstructions === false):
      this.showInstructions = true;
      break;

      default:
      console.log("Error in switch-case.");
    }
    console.log(this.showInstructions);
    myData = this.showInstructions;
    console.log(myData);
    this.sendData.emit(myData);
  }
}

In the parent component I imported the child component (HeaderComponent) and made a function toggledInstructions to receive the data. When I clicked the button nothing is logged.
import { Component } from '@angular/core';
import { HeaderComponent } from './header/header.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  toggledInstructions(myData: boolean) {
    console.log("Data coming in!");
    console.log(myData);
  }
}

I'm baffled how this is supposed to work. I see nothing in the documentation that connects the transmitting and receiving functions except that data variable name (myData).
Thanks for your help!

A: I found this ZeroesAndOnes blog post that explained this well. To work through my answer, start with the blog post and spin up its code.
Change child.component.html to:

Child Component

    <button (click)="clickButton()">Show Element in Parent</button>

Nothing special in the child template. Just a button that triggers a function in the controller.
Change child.component.ts to:
import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
})
export class ChildComponent {
  showElement: boolean = false;
  @Output() buttonClicked: EventEmitter<boolean> = new EventEmitter<boolean>();

  clickButton() {
    console.log("(Child) Value before toggle: " + this.showElement);
    console.log("(Child) Button clicked!");
    switch (true) {
      case (this.showElement === true):
      this.showElement = false;
      break;

      case (this.showElement === false):
      this.showElement = true;
      break;

      default:
      console.log("Error in switch-case.");
    }
    console.log("(Child) Value after toggle: " + this.showElement);
    this.buttonClicked.emit(this.showElement);
  }

}

The list of variables starts with showElement which is a boolean and is initialized false, i.e., the parent element is hidden.
Next is another variable that is the first bit of Angular magic. The variable is buttonClicked and it has the decorator @Output(). This decorator means that the variable will be available outside the controller. The variable is type EventEmitter<boolean> and it is assigned a new event emitter. The type can be left off if you prefer a shorter line:
@Output() buttonClicked = new EventEmitter<boolean>();

Next is the function that toggles showElement between true and false. At the bottom of this function is the second bit of Angular magic. The output event is called and showElement variable is sent to be emitted by the event emitter.
Now change the parent template app.component.html to:

  <app-child (buttonClicked)="parentEventHandlerFunction($event)">
  </app-child>

Parent Component

  Value emitted from child component is:
  {{ valueEmittedFromChildComponent }}

My awesome element!

The big Angular magic is in the parent template, specifically in this line:
  <app-child (buttonClicked)="parentEventHandlerFunction($event)">
  </app-child>

The directive app-child embeds the child template into the parent template. buttonClicked is the event emitter in the child controller. parentEventHandlerFunction is a function in the parent controller. $event is the object sent from the child to the parent. This single line combines parts of the child controller and the parent controller, with an equal sign to connect them. That's the big Angular magic.
Now set up the parent controller app.component.ts:
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent {
  valueEmittedFromChildComponent: boolean;

  parentEventHandlerFunction(valueEmitted){
    this.valueEmittedFromChildComponent = valueEmitted;
    console.log("(Parent) Value emitted: " + valueEmitted);
  }
}

We have one variable named valueEmittedFromChildComponent which is a boolean. Then we have one function parentEventHandlerFunction with one parameter valueEmitted. The $event object comes in from the magic line in the parent template and is assigned to the local variable valueEmittedFromChildComponent.
Going back to the parent template, we display the the local variable valueEmittedFromChildComponent and use it in an *ngIf to make an element show and hide.
ZeroesAndOne concluded their blog post, "In conclusion, angular makes it extremely easy to create child components that emit data to its parent component using the @Output() decorator." Hah! This is not what I call "extremely easy." In AngularJS, in comparison, the two templates would share one controller. The button in one template binds to a function in the controller, which toggles a variable, which binds to an element in the second template to show and hide an element. The data goes from the first template to a single variable in the controller to the second template. That's "extremely easy."
In Angular, the button in the child template triggers a function in the child controller, the same as AngularJS. But then you need to make an @Output() decorator with an event emitter, and call the event emitter from the toggle function. The data is then emitted to the magic line in the parent template, which combines stuff from the child controller and parent controller. Then the data goes to the parent controller, and then back to the parent template to show or hide the target element.
Let's repeat that. When the user clicks the button in the child template, the data goes to the child controller, where a function toggles the value, and then sends the data from the function to an event emitter. The event emitter sends the data to the parent template, which sends the data to the parent controller, which sends the data back to the parent template to show or hide the element. That's not what I call easy.
How would you do this in React? Is React more like AngularJS or Angular?

A: It looks like you need $event variable to get emitted value:
<button (click)="toggleInstructions($event)">Instructions</button>

and
toggledInstructions(event: boolean) {
    console.log("Data coming in!", myData);
}

The event binding (fooevent) allows to bind to DOM events and to EventEmitter events
UPDATE:
An example of work code:
ChildComponent.ts:
@Output() public onFooClicked = new EventEmitter<boolean>();

showMenu() {
  this.onFooClicked .emit(true);
}

app.component.ts:
<foo (onFooClicked)="onClicked($event)">
</foo>

onClicked(event: boolean) {
    console.log(`Somebody clicked`, event);
}

In addition, there is a great article how to pass data.


text:
Q: No module named 'cog' discordpy I'm getting this error message when trying to load cogs:

parent = import(parent_name, fromlist=['path'])
ModuleNotFoundError: No module named 'cog'

Code:
COGS = [path.split("\\")[-1][:-3] for path in glob("./cogs/*.py")]

client = commands.Bot(command_prefix="!", case_insensitive=True)

for cog in COGS:
    print(f"loading cog... {cog}")
    client.load_extension(f"cogs.{cog}")

Any ideas why? Thanks!

A: Alright, I figured it out so hopefully this will help someone with this issue.
For Windows, the directory separator is 2 back slashes. But for Linux, 1 forward slash.
So, I change this line from this:
COGS = [path.split("\\")[-1][:-3] for path in glob("./cogs/*.py")]

To this:
COGS = [path.split("/")[-1][:-3] for path in glob("./cogs/*.py")]

A: I'm glad you figured it out, but if you want your code to work on any platform, and save yourself the hassle of specifying separators and slices, you could use Python's pathlib module, which makes a lot of things cleaner and more convenient.
from pathlib import Path

cogs = [path.stem for path in Path('cogs').glob('*.py')]

*

*Path('cogs') (or, equivalently, Path('./cogs') ), creates a Path object representing your cogs folder.

*This Path object has a glob method that returns Path objects representing each matching file. (Note: you don't need to import the glob module for this; it's part of the Path object.)

*Path objects have handy attributes like name ('cog.py'), extension ('.py'), and stem ('cog').

pathlib is several years old at this point (2014), and included in the standard Python distribution, but a lot of tutorials and recipes out there haven't yet caught up. It can make your code remarkably cleaner, more portable, and easier to modify.
(In particular, you always specify paths to Path() with forward slashes, and it automatically handles the necessary separator conversion for different platforms.)


text:
Q: Program for finding min, max, average, median and mode Background
Write a C++ program that takes a user input of a set of numbers, and outputs the maximum value, minimum value, average, median, and mode. We know that the mode can be more than one number so write your code so it outputs multiple modes if necessary.
Sample Input
Enter integers and enter a letter when done.
-2 3 3 5 6 4 4 8 9 9 9 1 -2 10 10 10

Sample Output
Your numbers are: -2 -2 1 3 3 4 4 5 6 8 9 9 9 10 10 10
Max: 10
Min: -2
Average: 5.4375
Median: 5.5
Mode: 9 10 (3)

My Code
#include <iostream>
using namespace std;

void main()
{
    double value, sum;
    double average, minimum, maximum;
    int count;
    // initialise
    sum = 0.0;
    count = 0;
    cout << "Enter a value: ";
    cin >> value;
    minimum = value;
    maximum = value;
    while (value >= 0.0)
    {
        // process value
        sum += value;
        count++;
        if (value > maximum)
            maximum = value;
        else if (value < minimum)
            minimum = value;
        // get next value
        cout << "Enter a value: ";
        cin >> value;
    }
    if (count == 0)
        cout << "No data entry" << endl;
    else
    {
        average = sum / count;
        cout << "There were " << count << " numbers" << endl;
        cout << "Average was " << average << endl;
        cout << "Minimum was " << minimum << endl;
        cout << "Maximum was " << maximum << endl;
    }
}

A: If you want to use STL, you can write something like this (use c++11):
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
template<typename A, typename B>
std::pair<B,A> flip_pair(const std::pair<A,B> &p)
{
    return std::pair<B,A>(p.second, p.first);
}
template<typename A, typename B>
std::multimap<B,A> flip_map(const std::map<A,B> &src)
{
    std::multimap<B,A> dst;
    std::transform(src.begin(), src.end(), std::inserter(dst, dst.begin()),
                   flip_pair<A,B>);
    return dst;
}
int main() {
  std::string line;
  std::cout << "Enter numbers: ";
  std::getline(std::cin, line);
  std::istringstream iss(line);
  std::vector<int> elements;
  elements.reserve(1000);
  std::string elem;
  while (std::getline(iss, elem, ' ')) {
    try {
      elements.push_back(std::stoi(elem));
    } catch (...) {  }
  }
  double sum = 0.0;
  std::size_t n = elements.size();
  std::sort(elements.begin(), elements.end());
  std::cout << "max=" << elements.back() << std::endl;
  std::cout << "min=" << elements.front() << std::endl;
  for (auto &x: elements) {
    sum += x;
  }
  if (n == 0) return 1;
  std::cout << "avg=" << sum / n << std::endl;
  if (n == 1) {
    std::cout << "med=" << elements[0] << std::endl;
  }
  else if (n % 2 == 0) {
    std::size_t i = n/2;
    std::cout << "med=" << (double)(elements[i] + elements[i-1]) / 2.0 << std::endl;
  }
  else {
    std::cout << "med=" << elements[n/2] << std::endl;
  }
  std::set<int> elements_set;
  for (auto &x: elements) {
    elements_set.insert(x);
  }
  std::map<int, std::size_t> elements_count;
  for (auto &x: elements_set) {
    elements_count.insert(std::pair<int, std::size_t>(x, std::count(elements.begin(), elements.end(), x)));
  }
  std::multimap<std::size_t, int> count_elements;
  count_elements = flip_map(elements_count);
  std::cout << "mod: ";
  std::size_t count_mod = count_elements.rbegin()->first;
  for (auto &x: count_elements) {
    if (x.first == count_mod) {
      std::cout << x.second << ", ";
    }
    else {  }
  }
  std::cout << "(" << count_mod << ")" << std::endl;
  return 0;
}

A: The following code is an edited version of your code which is fully working:
    #include <iostream>
    #include <map>
    #include <vector>
    #include <algorithm>
    using namespace std;

    int main()
    {
        double value, sum;
        double average, minimum=(double)INFINITY, maximum=-(double)INFINITY, median;
        map<int,int>modes;
        vector<int>data;
        int count,mxmode=0;
        // initialise
        sum = 0.0;
        count = 0;
        cout << "Enter a value (To end, press Ctrl+Z and Enter): ";

        while (cin >> value)
        {
            // process value
            sum += value;
            count++;
            if (value > maximum)
                maximum = value;

            if (value < minimum)
                minimum = value;

            modes[ value ]++;
            mxmode = max(mxmode, modes[value]);
            data.push_back(value);

            // get next value
            cout << "Enter a value (To end, press Ctrl+Z and Enter): ";
        }
        if (count == 0)
            cout << "No data entry" << endl;
        else
        {
            average = sum / count;

            sort(data.begin(), data.end());

            if(data.size()%2==0) median = ( data[ data.size()/2 - 1 ] + data[ data.size()/2 ] )/2.0;
            else median = data[ data.size()/2 ];

            cout << "There were " << count << " numbers" << endl;
            cout << "Average was " << average << endl;
            cout << "Minimum was " << minimum << endl;
            cout << "Maximum was " << maximum << endl;
            cout << "Median was " << median << endl;
            cout << "Mode was";

            for (auto &x: modes)
                if(x.second == mxmode) cout<<" "<<x.first;

            cout<<" ("<<mxmode<<")" << endl;
        }
    }

Remember:

*

*Don't forget to compile it with the most recent -std=c++11 flag as I used the feature of C++11.

*Input is terminated by EOF or in console you can terminate it by pressing Ctrl + z then Enter (Use corresponding keys if you are in different OS than Windows).

A: Median:
First, you need to sort your numbers. You can store them in an array and then use a sorting algorithm e.g. insertion sort, selection sort etc. Once the array is sorted, the median is the middle number. Below, there is the the code for insertion sort implementation assuming that you have stored your numbers in arr[] and length is the length of your array.
    void insertion_sort(double arr[], int length) {
      int i, j;
      double tmp;
      for (i = 1; i < length; i++) {
        j = i;
        while (j > 0 && arr[j - 1] > arr[j]) {
          tmp = arr[j];
          arr[j] = arr[j - 1];
          arr[j - 1] = tmp;
          j--;
        }//end of while loop
        print_array(arr,5);
      }//end of for loop
    }//end of insertion_sort.

Mode:
You can have a counter to keep track of every number in your array. The most frequent one is the mode.


text:
Q: Why am i Getting correct in bitwise shifting by a negative value?
Possible Duplicate:
Right shifting negative numbers in C

This question i have found on SO, but everywhere i found the result as undefined.
int main()
{
   printf("%d\n",32<<-2); <-------------1
   printf("%d\n",32>>-2); <-------------2
   return 0;
}

I am getting the output as:   http://ideone.com/fIaXo
8
128

It seems that in the statement numbered 1, 32 is shifted 2 times right while in the second, 32 is being shifted 2 times left.
Is it really the case that when a value is shifted left by -p, the compiler treats it as shifting p times right?
Why am i getting the correct output here?


text:
Q: How to determine if iOS device's orientation *actually* changes? I am writing this code to make some changes to how my app is laid out depending on if it is in landscape or portrait mode. I have set up the app to get a notification on the orientation changing like this:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedRotate:) name:UIDeviceOrientationDidChangeNotification object:NULL];

And then defining receivedRotate:
-(void) receivedRotate: (NSNotification*) notification {
    UIDeviceOrientation interfaceOrientation = [[UIDevice currentDevice] orientation];

    // ... do something
}

However, UIDeviceOrientationDidChangeNotification is called whenever the device is moved slightly. E.g., the UIDeviceOrientation can be any of the following:
UIDeviceOrientationPortrait,
UIDeviceOrientationPortraitUpsideDown,
UIDeviceOrientationLandscapeLeft,
UIDeviceOrientationLandscapeRight,
UIDeviceOrientationFaceUp,
UIDeviceOrientationFaceDown

This is great but I just want to know if the device orientation is in portrait or landscape, and I also only want to run this code when the orientation actually changes - from portrait to landscape or vice-versa. If they turn the phone all the way around, it is still in landscape mode - just a different form of landscape mode. What's the ideal way to make sure that my rotation code only runs when it is necessary?

A: DeviceOrientation vs. ScreenSize vs StatusBar.isLandscape?
iOS 11, Swift 4 and Xcode 9.X
Regardless of using AutoLayout or not, there are several ways to get the right device orientation, and they could be used to detect rotation changes while using the app, as well as getting the right orientation at app launch or after resuming from background.
This solutions work fine in iOS 11 and Xcode 9.X
1. UIScreen.main.bounds.size:
If you only want to know if the app is in landscape or portrait mode, the best point to start is in viewDidLoad in the rootViewController at launch time and in viewWillTransition(toSize:) in the rootViewController if you want to detect rotation changes while the app is in background, and should resume the UI in the right orientation.
let size = UIScreen.main.bounds.size
if size.width < size.height {
    print("Portrait: \(size.width) X \(size.height)")
} else {
    print("Landscape: \(size.width) X \(size.height)")
}

This also happens early during the app/viewController life cycles.
2. NotificationCenter
If you need to get the actual device orientation (including faceDown, faceUp, etc). you want to add an observer as follows (even if you do it in the application:didFinishLaunchingWithOptions method in the AppDelegate, the first notifications will likely be triggered after the viewDidLoad is executed
device = UIDevice.current
device?.beginGeneratingDeviceOrientationNotifications()
notificationCenter = Notifi`enter code here`cationCenter.default
notificationCenter?.addObserver(self, selector: #selector(deviceOrientationChanged),
    name: Notification.Name("UIDeviceOrientationDidChangeNotification"),
    object: nil)

And add the selector as follows. I split it in 2 parts to be able to run inspectDeviceOrientation() in viewWillTransition(toSize:)
@objc func deviceOrientationChanged() {
    print("Orientation changed")
    inspectDeviceOrientation()
}

func inspectDeviceOrientation() {
    let orientation = UIDevice.current.orientation
    switch UIDevice.current.orientation {
    case .portrait:
        print("portrait")
    case .landscapeLeft:
        print("landscapeLeft")
    case .landscapeRight:
        print("landscapeRight")
    case .portraitUpsideDown:
        print("portraitUpsideDown")
    case .faceUp:
        print("faceUp")
    case .faceDown:
        print("faceDown")
    default: // .unknown
        print("unknown")
    }
    if orientation.isPortrait { print("isPortrait") }
    if orientation.isLandscape { print("isLandscape") }
    if orientation.isFlat { print("isFlat") }
}

Note that the UIDeviceOrientationDidChangeNotification may be posted several times during launch, and in some cases it may be .unknown. What I have seen is that the first correct orientation notification is received after the viewDidLoad and viewWillAppear methods, and right before viewDidAppear, or even applicationDidBecomeActive
The orientation object will give you all 7 possible scenarios(from the enum UIDeviceOrientation definition):
public enum UIDeviceOrientation : Int {
    case unknown
    case portrait // Device oriented vertically, home button on the bottom
    case portraitUpsideDown // Device oriented vertically, home button on the top
    case landscapeLeft // Device oriented horizontally, home button on the right
    case landscapeRight // Device oriented horizontally, home button on the left
    case faceUp // Device oriented flat, face up
    case faceDown // Device oriented flat, face down
}

Interestingly, the isPortrait read-only Bool variable is defined in an extension to UIDeviceOrientation as follows:
extension UIDeviceOrientation {
    public var isLandscape: Bool { get }
    public var isPortrait: Bool { get }
    public var isFlat: Bool { get }
    public var isValidInterfaceOrientation: Bool { get }
}

3. StatusBarOrientation
UIApplication.shared.statusBarOrientation.isLandscape

This also works fine to determine if orientation is portrait or landscape orientation and gives the same results as point 1. You can evaluate it in viewDidLoad (for App launch) and in viewWillTransition(toSize:) if coming from Background. But it won't give you the details of top/bottom, left/right, up/down you get with the notifications (Point 2)

A: I believe what you're looking for is UIInterfaceOrientation, not UIDeviceOrientation. To use this, just implement the following function in your view controller.
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    UIInterfaceOrientation currentOrientation = self.interfaceOrientation;
    //
}

This enum is declared as the following
typedef enum : NSInteger {
   UIInterfaceOrientationPortrait           = UIDeviceOrientationPortrait,
   UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
   UIInterfaceOrientationLandscapeLeft      = UIDeviceOrientationLandscapeRight,
   UIInterfaceOrientationLandscapeRight     = UIDeviceOrientationLandscapeLeft
} UIInterfaceOrientation;

A: Save the previous orientation in a property and compare it with current one.

A: @0x7ffffff's and @Kunal Balani's answers are down the right path, but I'd recommend you take a look at UIViewController's documentation for rotation handling on iOS 6+ applications vs how it's handled in iOS 5 and older, since you don't mention whether or not you're supporting iOS 5 (which at the time of writing of this answer is still supported). This will help resolve any issues you could run into down the road. I'd recommend specifically taking a look at willRotateToInterfaceOrientation:duration: / willAnimateRotationToInterfaceOrientation:duration: / didRotateFromInterfaceOrientation: and when they are called during the lifecycle of a rotation.
You will definitely want to store the previous orientation as mentioned in the other answers so you don't run your code more than once.
As for your specific question on more "agnostic" as to what version of landscape vs portrait, UIKit's function reference contains a number of pertinent macros, specifically UIInterfaceOrientationIsPortrait() and UIInterfaceOrientationIsLandscape().


text:
Q: Office365 authorization for graph API : AADSTS70001 I must have done those steps 200 times during my last integrations, but today it doesn't work.
I have an app in azure AD with graph authorization set up.
I create a sign in url as follows:
https://login.microsoftonline.com/common/oauth2/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A8101%2Fintegrations%2F&prompt=login&response_type=code&client_id=20xxxxxx-xxx-xxxx..94d3
This code used to work for 2 month for asking office 365 user to log in and get their access and refresh token, for some reason, today it doesn't work anymore, and on office page I got the following error:
Additional technical information:
Correlation ID: 8fc051b1-a2e8-493b-806c-158440c21cf3
Timestamp: 2015-12-04 12:58:49Z
AADSTS70001: Application with identifier '20xxxxxx-xxx-xxxx..94d3' was not found in the directory <mylogin>.onmicrosoft.com

For information, I do generate the secret ID key AFTER having add the application graph and having set the permissions.


text:
Q: Is there a "quick" way to identify the site(s) getting hammered? I have a couple of clients that run multiple, low traffic websites on a given Ubuntu server. When I set these things up, I always configure each Nginx virtual host to write to its own access|error log file.
That approach works great for almost everything, but the one scenario where it bites me from time to time is when one site is getting hammered by some kind of brute force attack or even weird outlier events that aren't malicious, but generate similarly unnecessary and unwanted traffic.
I can see the CPU and Memory spike, but what I don't know how to do is quickly identify which site is getting hammered. Usually I find myself running tail -f on each site access log for a few seconds until I find the log that is being written to more often than expected.
I'm wondering whether there's some kind of one-liner script that could help me quickly identify which of these access log files is growing fastest or getting written to the most or whatever. Just anything that gets me closer to identifying the target faster than I'm currently getting there with my laborious approach.

A: Assuming you keep your log files under /var/log/nginx with names that include access, this can do the trick:
find /var/log/nginx -type f -iname '*access*' -exec wc -l '{}' \+ | sort -n

You'll find the log files ordered by the number of hits, with the most busy one printed last.
Notice that this is a "more or less" indication, if you're under a Syn flood attack or such you should check other stuff.


text:
Q: Ask the set of bivariate transformation $X,Y$ are between $0$ and $1$, $0<X,Y<1$. Then the transformation is $U=XY, V=X/Y$
How to get the boundary of $U$ and $V$?
When I do this, my attempted answer is $0<U<1$, and $V>0$
But the answer is  $\{0 < u < v < 1/u, 0 < u < 1\}$. I can verify it is correct. But how to get the answer without knowing the answer before?


text:
Q: How do I force to not use impersonation in IIS 7+? I am trying to force my web application to run completely as the AppPool User (Domain\UserForApp) and I correctly set the setting in IIS and everything runs fine and "System.Security.Principal.WindowsIdentity.GetCurrent().Name" returns the correct "Domain\UserForApp".
However, when I tried to restrict the permissions of my web app directory to the bare bones needed:

*

*SYSTEM (full Access)

*Me (Full Access)

*Admininstrators (Full Access)

*UserForApp (Read)

I could no longer load any static files.  So I downloaded Process Monitor to find out why and whenever it tries to access a static file, I get the following error:
ACCESS DENIED:
Desired Access:     Generic Read
Disposition:        Open
Options:            Sequential Access, No Buffering
Attributes:         RE
ShareMode:          Read, Write, Delete
AllocationSize:     n/a
Impersonating:      NT AUTHORITY\IUSR

And as you see from the above IUSR doesn't have permissions so that is correct, but I just don't understand why its trying to impersonate anyway.  In my web.config file I have:
<location path="" overrideMode="Deny">
    <system.web>
        <identity impersonate="false" />
    </system.web>
</location>

just to ensure that no one turns on impersonation, but it had no effect.
It doesn't work in both Classic and Pipelined mode, but the error is slightly different.  In classic when viewing the images it just shows a HTTP Error 401.3 - Unauthorized page, and when using Pipelined it redirects to the login site.

A: If you wan't the site to run as the app pool's identity then you need:
<location path="my_site">
     <system.webServer>
         <security>
             <authentication>
                 <anonymousAuthentication userName="" />
             </authentication>
         </security>
    </system.webServer>
</location>

You can set this in your applicationHost.config file (probably the best place) by doing:
APPCMD.exe set config "my_site" -section:system.webServer/security/authentication/anonymousAuthentication /username:"" /commit:apphost


text:
Q: Bootstrap datepicker should always show current month page $('#datetimepicker1').datepicker({
    autoclose: true,
    todayHighlight: true,
}).on('changeDate', function(ev){
    $('#datetimepicker1').val("");
    $('#sDate1').text($('#datetimepicker1').data('date'));
    $('#datetimepicker1').datepicker('hide');
});

I am using the above code. If I click the datepicker, it shows the current month(nov) and if we select a date from next month(dec), when I click for the second time it is showing the next month page.
The requirement is it should show current month (i.e November now) whenever I click on datepicker. I have tried many things and I'm fed up with this. Can anyone please help me?

A: Here is a Working Fiddle
As I told there is no straight forward approach as per my knowledge, Also I went through the complete plugin documentation.
This is a work around that does what you need.
Make these changes to your existing scripts
$('#datetimepicker1').datepicker({
  autoclose: true,
  todayHighlight: true,
  todayBtn: true,   // add this option.
});

The todayBtn is used to render a button on the bottom of the calendar which on click will take you to the current Date view.
So lets take advantage of this feature. Lets add this button and trigger it to click programatically when ever we open the calendar. To do so add this code.
$('#datetimepicker1').on('click',function(){
 $(this).siblings('.datepicker').find('.datepicker-days tfoot .today').trigger('click');
});

This will make sure the current date view is shown every time you open the calendar.
Now this will leave us with the button on the calendar named "Today". If you dont want this button simply hide it using css.
.datepicker-days tfoot .today {
  display: none !important; // !important required to override the plugin inline style
}

A: Depending on the exact widget you're using this might vary, but using defaultViewDate (or defaultDate) looks like it will fit your needs (although the initially kind of makes me think it won't work...):

Date to view when initially opening the calendar. The internal value of the date remains today as default, but when the datepicker is first opened the calendar will open to defaultViewDate rather than today. If this option is not used, "today" remains the default view date

A: This may help..

$('#sandbox-container input').on('click', function(e){
 var setDate = new Date();
 $(this).datepicker('setDate', setDate);
})

A: Need to use below concept to open the datepicker with selected date
var selectedDate = new Date();
$('#txtWQApprovalDate').datepicker('setDate',selectedDate).datepicker('fill');


text:
Q: 2D Plotting of triplet data set with third axis as variation of thickness of curve I have similar question like mentioned at representing triplet data set with color on 2d plot but this time instead of color I need to represent variation of third axis with the thickness of the curve

A: Here Filling can be a big help.
Some sample data:
data = {#, Sin[#], #^2} & /@ Range[0, 10, 1/4];

A function to help create the variable "thickness".  The parameter f is like a scaling factor:
addThickness[data_, f_] :=
 Transpose[
  data /. {x_, y_, z_} :> {{x, y}, {x, y - f z}, {x, y + f z}}]

and now make the FillingStyle match the PlotStyle:
ListLinePlot[addThickness[data, 0.01],
 Filling -> {2 -> {1}, 3 -> {1}}, PlotStyle -> Blue,
 FillingStyle -> Opacity[1]]


text:
Q: Google map with bootstrap 3 carousel bug? I am trying to add a google map as an item in a bootstrap carousel.
For some reason when I include a map inside a carousel the tiles of the map load in wrong.
If you're lucky it loads in correctly to start for a seconds but then it appears to stream in a set of tiles at different zoom levels.
If you move the same logic outside of a carousel it displays fine.
I've tried to simplify a sample page down using bootply below to demonstrate the issue as I find it difficult to explain.
http://www.bootply.com/YcaTxtftSW
can anyone offer a suggestion as to what I'm missing please?

A: It's  forced by  CSS, the setting min-height: 400px; for .carousel img will also affect the images used for the map(especially the tiles, which have a natural size of 256x256)
Add this CSS:
#map-canvas img {
  min-height: 0;
}


text:
Q: Java WordCounter Hello I have a project for school where I must create a program in java that counts the words in one or more files. It should start a new thread for each new file. Its also supposed to have locks to protect the combined word counter and a counter for active threads. Ive tried researching locks, but im having trouble grasping the concept.
Here is what I was able to come up with so far.
public class Main {

    public static void main(String[] args)throws InterruptedException {

        WordCount[] counters = new WordCount[args.length];
        for (int index = 0; index < args.length; ++index)
            {
                counters[index] = new WordCount(args[index]);
                counters[index].start();
            }
        int total = 0;
        for (WordCount counter : counters)
        {
            counter.join();
            total += counter.count;
        }

        System.out.println("Total:" + total);

    }

}

public class WordCount extends Thread {

    int count;

    @Override
    public void run()
    {
        count = 0; //it will count the words
        ++count;

    }
}

A: 'Protecting' the word counter really just means preventing two threads from attempting to update the word counter at the same time. The simplest way to achieve that in Java is with the synchronized keyword:
class WordCounter {
    private int count = 0;

    public synchronized void incrementCount() {
        count++;
    }
}

Now if two threads call that method the JVM will force one to wait until the other completes.
Next you need a method that will count words in a file. That should be relatively simple. Something like:
private void countWords(Path path) {
    for (String line : Files.readAllLines(path)) {
        for (String word : line.split("\\s+")) {
            counter.incrementCount();
        }
    }
}

You'll need to cope with IO exceptions here.
Finally you need to create a thread for each file. At the moment you are subclassing the Thread class but a simpler solution is just to create a thread with the Runnable you need the thread to run:
for (Path path: myFiles) {
    Thread thread = new Thread(() -> counter.countWords(path));
    thread.run();
}

That's about it. I haven't added the code to keep a running thread count but it really just follows the same pattern.


text:
Q: C++ namespace.... anonymous namespace is legal?
namespace  {     int Foo (int a) ;  }

Like this. Is this code snippet legal?
Is this legal? and, can I reference Foo in anywhere? or only certain domain?
Thank you.

A: It is legal, You can use Foo anywhere in the same Translation Unit.
Anonymous namespace is the standard prescribed way of saying static on variables to limit their scope to the same Translation unit.
C++03 Standard section 7.3.1.1 Unnamed namespaces
para 2:

The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative.

Update:
As @Matthieu M. correctly points out in the comments, and his answer The C++11 Standard removed the above quote from C++03 Standard, which implies that the static keyword is not deprecated when declaring objects in a namespace scope, Anonymous or Unnamed namespaces are still valid nevertheless.

A: This is legal. You can reference Foo anywhere inside the translation-unit.
From the C++03-standard, Section 7.3.1.1:

An unnamed-namespace-definition behaves as if it were replaced by
namespace unique { /* empty body */ } using namespace unique;
namespace unique { namespace-body }

where all occurrences of unique in
  a translation unit are replaced by the same identifier and this
  identifier differs from all other identifiers in the entire program.
The use of the static keyword is deprecated when declaring objects in
  a namespace scope; the unnamed-namespace provides a superior
  alternative.

A: The definition changed slightly in the C++11 Standard:

7.3.1.1 Unnamed namespaces [namespace.unnamed]
1/ An unnamed-namespace-definition behaves as if it were replaced by

inlineoptnamespace unique { /* empty body */ }
using namespace unique ;
namespace unique { namespace-body }

where inline appears if and only if it appears in the unnamed-namespace-definition, all occurrences of unique in a translation unit are replaced by the same identifier, and this identifier differs from all other identifiers in the entire program.94 [ Example:

namespace { int i; } // unique ::i
void f() { i++; } // unique ::i++

namespace A {
  namespace {
    int i; // A:: unique ::i
    int j; // A:: unique ::j
  }
  void g() { i++; } // A:: unique ::i++
}

using namespace A;

void h() {
  i++; // error: unique ::i or A:: unique ::i
  A::i++; // A:: unique ::i
  j++; // A:: unique ::j
}

—end example ]