text:
Q: ListFragment with multiple strings per row I am new to Android development and I am trying to create a ListFragment that can create a ListView from 3 ArrayList objects each containing 30 Strings. Each row would contain a string from each array.

In my reading, I have found that a ListView is essentially created from an ArrayAdapter. The only examples I've seen of this however only show 1 String[] array being used (http://goo.gl/Yrkn0k, http://goo.gl/hqkdl).
How can I pass the three arrays to ArrayAdapter to create this ListView?

A: ArrayAdapters can work on lists of any sort. If you need to have an ArrayAdapter operate on three separate lists at once, you will need to do two things:

*

*Create a new object class that is the combination of the three lists, eg. an Item class that has three fields: Title, Description, Price. Once you have a suitable object, turn your three lists into a single list of your object.

*Then you will need to create a custom adapter class that extends ArrayAdapter, overriding the getView method in order to properly display your items.

Edit
Example:
public class Item {
    private String title, desc, price;
    public Item(String title, String desc, String price) {
        this.title = title;
        ...
    }
    *provide standard getters and setters*
}
...
ArrayList<Item> items = new ArrayList<Item>();
for(int i = 0; i < titles.length; i++) {
    items.add(new Item(titles[i], descriptions[i], prices[i]);
}

Then new adapter should take the form of
private class CustomAdapter extends ArrayAdapter<Item> {
    public CustomAdapter(ArrayList<Item> items) {
        super(getActivity(), 0, items);
    }
...

A: The ArrayAdapter<T> class is generic, so you can use it with java Collections.  To do what you're trying to do, you could use an ArrayList<ArrayList<String>> or just build model objects that contain your 3 string fields and use ArrayList<YourModel>.
For Example:
public class MyAdapter extends ArrayAdapter<ArrayList<ArrayList<String>>>{

//Constructor

        @Override
    public View getView(int position, View convertView, ViewGroup parent) {
             ArrayList<String> current = getItem(position);

             //Do Something
        }

}


text:
Q: How to make all files read-only in Android Studio I would like to make all of the files in an Android Studio project read-only, so that if a cat runs across my keyboard it's safe.
In other words, I would like to have the same effect as if I clicked on the padlock icon in the right bottom corner for all of the files in a particular project or a specific folder:

Is this supported by the UI, or is it conveniently achievable somehow?

A: Mokay, this may have been an strange question... but just in case somebody else is trying to do the same thing:
chmod -R a-w app/src

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mermory issue by using a for loop in R of C++ function using Rcpp there is something unclear by using for loop with Rcpp function. here is a simple example that should help:
This is my cpp code in file test_cpp.cpp
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::mat test_Cpp(int n,
                   arma::vec my_vec,
                   Rcpp::List my_list,
                   int mat_size,
                   double lambda,
                   double beta) {
  //  Matrix of mat_size rows & mat_size columns (filled with 0)
  arma::mat matrix_out(mat_size, mat_size) ;
  for (int it = 0 ; it < n ; ++it) {
    arma::mat temp_mat_flux_convol = my_list[it] ;
    if (my_vec[it] != 0) {
      matrix_out += lambda * my_vec[it] * beta * temp_mat_flux_convol ;
    }
  }
  return matrix_out ;
 }

Then from the R code why res1 and res2 are different when used in a 'useless' for loop and the same without for loop? I guess there is a segfault stuff, but I did not get it!
library(Rcpp)
library(RcppArmadillo)
sourceCpp(file = "src/test_cpp.cpp")
set.seed(123)
ls_rand = lapply(1:10, function(x) matrix(rnorm(9), ncol=3))

for(i in 1:1){
  res1 <- test_Cpp(n = 10,
                my_vec = 1:100,
                my_list = ls_rand,
                mat_size = 3,
                lambda =  24,
                beta = 0.4)

  res2 <- test_Cpp(n = 10,
                my_vec = 1:100,
                my_list = ls_rand,
                mat_size =  3,
                lambda = 24,
                beta = 0.4)
}
all.equal(res1, res2)
res1 ; res2 # here res2 is twice res1 !!!

## Without for loop
res1 <- test_Cpp(n = 10,
                my_vec = 1:100,
                my_list = ls_rand,
                mat_size = 3,
                lambda =  24,
                beta = 0.4)
res2 <- test_Cpp(n = 10,
              my_vec = 1:100,
              my_list = ls_rand,
              mat_size =  3,
              lambda = 24,
              beta = 0.4)

all.equal(res1, res2)
res1 ; res2 # here res1 and res2 are the same!

A: The error lies here:
  //  Matrix of mat_size rows & mat_size columns (filled with 0)
  arma::mat matrix_out(mat_size, mat_size) ;

The documentation says:

mat(n_rows, n_cols)       (memory is not initialised)
   mat(n_rows, n_cols, fill_type)     (memory is initialised)

So if you change your code to
  //  Matrix of mat_size rows & mat_size columns (filled with 0)
  arma::mat matrix_out(mat_size, mat_size, arma::fill::zeros) ;

The comment is actually right and the problem goes away.


text:
Q: Can asynchronous fetch still freeze the browser? I'm working on a page that has to download a lot of data on initial page load. I initially tried using an asynchronous XMLHttpRequest, but I found that the browser was being frozen during while the request was in progress (which was about 3 seconds). I then tried to use the browser's fetch API, which is what I am showing below.
async function fetch_stuff() {
    for (let i of [0, 1, 2, 3, 4]) {
        let response = await fetch(`chunk.${i}.json`);
        let data = await response.json();
        Object.assign(combined_data, data);
        refresh_list();
    }
}

In addition, I have an event listener in a textinput that updates DOM elements so that the user can see the result of his query.
filter_input.addEventListener("keyup", function() {
    refresh_list();
});

The problem is that the page largely freezes while all the downloads are happening, which means the user can't really type into the text box. My guess is that the requests are indeed happening asynchronously, but still overloading the browser somehow so that the page is busy just keeping up with the incoming data.
I'd like to have a long-ish download running in the background while giving the user a smooth experience.

*

*Why are asynchronous requests causing a slow user interface?

*Would running synchronous requests in web workers be any smoother?

*Am I doing something wrong here to cause this behavior.


text: Q: How to get place type in Core Location/MapKit? When I use Google Places API to search places, I can get business or establishment type (available types are listed here). But if I try to use Apple's native Core Location or MapKit, there's no such information available via standard classes, despite the fact that Apple Maps shows POIs with various icons, depending on POI type. Is it possible to get the same info from Swift/ObjC?


text:
Q: Find out if password expired or when it expires for user in a specific OU Is there any powershell command that outputs the users that have their passwords expired from a specific organizational unit (OU).
If so can it be combined in a script with another command that outputs the time when it expires for all the users in the specific OU ?
Thank you.

A: Get AD Users Password Expiration Report from Specific OU:
Import-Module ActiveDirectory
Get-ADUser -SearchBase "OU=TestOU,DC=TestDomain,DC=Local" -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} -Properties "SamAccountName","msDS-UserPasswordExpiryTimeComputed" |
  Select-Object -Property "SamAccountName", @{Name="Password Expiry Date"; Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}} |
    Format-Table

You may also take help from this blog which lets you how to email users a active directory password expiration notification and schedule reports,  alerts and be compliant with all password expiration related tasks to save your time: http://www.symantec.com/connect/blogs/how-automate-password-change-notification-through-email

A: Users with expired passwords:
Get-ADUser -SearchBase "ou=MyOU,dc=MyDomain,dc=Local" -filter * -properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet | where {$_.Enabled -eq "True"} | where {$_.PasswordNeverExpires -eq $false} | where {$_.passwordexpired -eq $true}

To get time when password expires you should get PasswordLastSet property and add MaxPasswordAge from domain policy (e.g. $DefaultmaxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge).
Please have a look at Password Expiry Email Notification script on TechNet:
https://gallery.technet.microsoft.com/Password-Expiry-Email-177c3e27
Good sample for the subject.

A: To list enabled users with expired passwords in a specific OU:
Get-ADUser -filter {Enabled -eq $True -and PasswordExpired -eq $True} -SearchBase "OU=Finance,OU=Users,DC=yourdomain,DC=com"

To list enabled users within a specific OU with password expiration dates:
Get-ADUser -filter {Enabled -eq $True} -SearchBase "OU=Finance,OU=Users,DC=yourdomain,DC=com" –Properties "DisplayName", "msDS-UserPasswordExpiryTimeComputed"
|
Select-Object -Property "Displayname",@{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}


text:
Q: type of process dump when its generated from task manager Starting from Windows Vista, now one can generate a process dump right from task manager. Typically I generate a process dump either by using Adplus or right from Windbg. If I use one of these option, I have to provide some switches with my command in order to describe what type of dump is been generated. Given that all these details are hidden when I generate a process dump from task manager, does someone know what type of dump it is and what is contained in it? I remember reading somewhere that process dump generated from task manager does not contains details on the handle table. Any ideas on this as well?

A: The dump is a "User Mini Dump File with Full Memory", so for most tasks you're good.
However, you can't specify that the dump should be created at some specific event. Tools like adplus and procdump allow you to create a dump for various conditions (exception, work load etc). So essentially task manager only supports give me a snapshot of the process (which is usable for a hanging process). For other situations you need to use adplus or procdump.
Also, you should be aware that 64 bit Windows ships with two versions of the task manager. The 64 bit manager will create 64 bit dumps - even for 32 bit processes (i.e. the dump will contain the Wow64 stuff needed to run the 32 bit process). However, if you use the 32 bit version of task manager (located in \Windows\SysWOW64) you'll get a proper 32 bit dump.


text:
Q: Display: block showing all my s inline I am just learning CSS so this is probably something super basic that I am just messing up. I have a page with 2 header divs one main content div and a footer div. I just have an image and a couple of lines of text in the main content div and I want them to display vertically. I have the text broken up like I want with spans and have display:block in the CSS for the div. I thought this would display everything vertically but it is still displaying all in one line.
I appreciate any help you can provide.

#a {
  border: 2px solid #000000;
  float: left;
  margin: 10px 0px;
  width: 30%;
}

#b {
  border: 2px solid #000000;
  float: right;
  margin: 10px 0px;
  width: 60%;
}

#c {
  border: 2px solid #000000;
  margin: 10px 0;
  padding: 50px;
  display: block;
  text-align: center;
}

#d {
  border: 2px solid #000000;
  margin: 10px 0;
  padding: 50px;
}

#e {
  border:2px solid #000000;
  margin: 10px 0;
  width: 100%;
  overflow: hidden;
}

img {
  width: 150px;
  height: 150px
}

Relating to this HTML

  There and Back
  My journey

The image and following spans are all being displayed inline. There is currently no content in the other divs.
Thank you for your help.

A: 's by default are inline.
You should be using divs if you want blocks. But if you want to force the span's in your html to be blocks (you shouldn't - you should change them to divs), just do this:
#c span { display: block; }

A: The easiest way to do this is remove the  tags, replacing them with

The span tag is becoming redundant, I never use it any more as a DIV behave much better in all situations. Span doesn't like to be stylised.
Keep your CSS the same.
Your new HTML:

There and Back

My journey


text:
Q: Unable to get product attribute value store wise, I have a magento1.x product attribute (its scope is store, and admin site defines default and store wise attribute value different)
I am trying to get its value but every time i got default store value
My collection query
$productCollections = $productCollection->joinAttribute('visibility','catalog_product/visibility','entity_id',null,'inner',$store->getId())->joinAttribute('status','catalog_product/status','entity_id',null,'inner',$store->getId());

Want get store wise value for a product attribute


text:
Q: MySQL select duplicates I have a table containing group_id, user_id, and role_id.
Because the unique key was set wrong, there are users who are in a group twice, with different roles. Like this:
group_id   |   user_id   |   role_id
    1      |      1      |      1
    1      |      1      |      2
    2      |      1      |      1
    1      |      2      |      1
    2      |      2      |      3

How can i find the user id's of the user where this is the case? So, in this example only user id 1?
Edit:
Because neither the answer from @Manil Liyanage nor the one from @TX Turner give me the right results, maybe i have to explain it some more;
Users can be in multiple groups, but they shouldn't be in the some group more than once. Unfortunately, because of the wrong unique key, some users now are in the same group more than once, but only with another role. How can I find the users who are in a group more than once?

A: the following would show you which userids are duplicated per group, and the count.
SELECT user_id, group_id, COUNT(group_id) cnt
FROM tablename
GROUP BY user_id, group_id
HAVING COUNT(group_id) > 1

A: Following should work just fine for you. It shows the ida of the duplicated records
EDIT: Use the keys inside the having-count statement concatenated.

SELECT concat(concat('Group is: ',group_id) ,
concat(' user id : ' , user_id)) Places
FROM table
HAVING count(concat(group_id,concat (':',user_id))) > 1


text:
Q: How to close all stages when the primary stage is closed? I have an application where I call the following code when an exception occurs- that is, it is located within the "catch" of a "try/catch". It merely creates a "popup"-like window which tells the user to enter an int instead.
Stage dialogStage = new Stage();
dialogStage.initModality(Modality.WINDOW_MODAL);
dialogStage.setScene(new Scene(VBoxBuilder.create().
children(new Text("Please enter an integer."), new Button("Ok.")).
alignment(Pos.CENTER).padding(new Insets(5)).build()));
dialogStage.show();

The only problem is that the stage lingers even if the primary stage (that is the parameter in the public void start(Stage primaryStage)) is closed.
What have I tried?:
I made the dialogstage visible in the whole class by defining it as a class variable. Then I implemented the following code:
primaryStage.setOnCloseRequest((new EventHandler<WindowEvent>(){

        @Override
        public void handle(WindowEvent arg0) {
                            arg0.consume();
            try
            {
             dialogStage.close();

                            }
            catch(Exception ex)
            {
                System.out.print(ex.getMessage()+"\r\n");
            }

        }
    }));
}

This "works" in that the dialogstage is closed when a user tries to exit the main application, however, it does not actually do what I intended: when you try to close the primary stage only the dialogstage is closed.
It is also an aesthetically displeasing solution as I don't want the whole class to know about the stupid dialog box which is only located in one try/catch and might never be used.
I'd like to know if there is a simple solution that tells the dialogstage to close when the primary stage does and where I don't have to write much code outside of my try/catch.

A: On the event OnCloseRequest on your main stage, perform Platform.exit (docs.oracle.com/javafx/2/api/javafx/application/Platform.html)


text:
Q: Is it possible to fake Internet traffic? I'm looking for a way to fake my Internet traffic so that any connections made to other websites on the Internet will look like a static connection. (i.e when i'm downloading files or visiting pages from website X or Y, the ISP will see that I'm interacting with website Z. my mobile 4G provider gives free Internet access to certain mobile apps and any connection made to those apps are free of charge. I want to do this on Windows 8.1. I couldn't find any useful information, all I found was about bots for website traffic etc. Thanks in advance.

A: All your Internet traffic is passing through your ISP, so unless it's encrypted he knows its destination. To use website X you must specify that you want to use website X because your ISP has to know where to pass your traffic.
A web proxy is an option if it supports HTTPS, otherwise it's not encrypted and can be viewed by ISP. VPN and proxies aren't websites, but services and they could work.
The problem is: probably none of these is offered by the apps that you can use for free. All in all, what you want to achieve is not possible.


text:
Q: c# Entity Framework sqlite (spatialite) spatial date Is it possible to use the Entity Framework to preform a sqlite intersect query on a geom datatype?
I have had success with the below SQLiteConnection (after loading the 'libspatialite-4.dll')
string query = @"SELECT * FROM Spatial_Table WHERE intersects(Geom, GeomFromText('LINESTRING (-69.929201602936 23.577301964831, -20.358889102936 37.730080532218, 4.6020483970643 55.586555530742)', 4326)) = 1"

I have had success using the EF to query non spatial data from my SQLite database.
Is this type of query possible?
Can I load the dll?
Thanks very much

A: Bit late to the party I know (I only just spotted this) but the accepted answer is not strictly true.
What is true is that there are no Geometry and/or Geography types in EF to support this, but there is a way you can get around it.
First off...
You can load the extension DLL's using the ExecuteSqlCommand on your database context as follows:
_ctx.Database.ExecuteSqlCommand(@"SELECT load_extension('libspatialite-4.dll')");

Secondly, if you return your Geometry as binary rather than text, you can bring the data back from your DB as a regular
byte[]

data type.  This may seem a little counter productive until you have a nose around on NuGet and install the ".NET Topology Suite" (NTS for short)
You can feed these binary arrays into NTS and it will construct and return to you a first class .NET object representing your geometry.  NTS basically has everything in it that Spatialite has but in a C# assembly.  In fact, I would go so far as to say, with NTS you actually don't need spatialite, you can just save and retrieve binary arrays to / from your database and operate on them purely in your own code.
The only thing you lose doing things that way is the ability to do SQL like select statements to search geometry out of your DB.
Fear not however....
For that, you can return your results to your code as regular gegraphic text objects such as
POINT(1 2)

or
LINE(1 2,3 4,5 6,7 8)

All you need to do is make sure the result of any SQL querys you perform create thier output by passing the result through Spatialites "AsText" function.
So to use your example
string query = @"SELECT col1,col2,col3,AsText(GeometryColumn) FROM Spatial_Table WHERE intersects(Geom, GeomFromText('LINESTRING (-69.929201602936 23.577301964831, -20.358889102936 37.730080532218, 4.6020483970643 55.586555530742)', 4326)) = 1"

Which will produce something like:
1,2,3,POINT(1 2)
4,5,6,POINT(3 4)
1,2,3,POINT(1 2)
4,5,6,POINT(3 4)

Which you can feed into a normal .NET object as follows:
public class myclass
{
  public int col1 { get; set; }
  public int col2 { get; set; }
  public int col3 { get; set; }
  public string GeometryColumn { get; set; }
}

and once again, if you then employ NTS, NTS can parse and turn into a graphic object anything passed from Spatialite in the text string.
My Company uses these techniques very reliably in one of our flagship products and we have done since EF 4.3.
The ExecuteSqlCommand has just appeared in EF5, but there are other similar ways of executing arbitrary SQL statements in previous versions.
You'll also find that on your entity tables there is a new function (I believe added in EF5) called SqlQuery which allows you to run data reader style querys on a given table and make use of your strongly typed models, to get the data back.

A: Unfortunately no.
Neither System.Data.SQLite provider nor devArt's dotConnect for SQLite provider support spatial (Geometry, Geography) types at this time.


text:
Q: Async functions on expressJS I have a doubt related to async function on Express. I'm fetching some JSON from database and I'm getting the following error: Error: Can't set headers after they are sent.
I've read a little bit about it and it seems that it's related to the function having a Finished state or something like that.
I had the following code and it was crashing my application:
 router.get('/home', isAuthenticated, function(req, res){

    atendimentos.find({}, function(err, atendimentos) {
        if(!err){
            console.log(atendimentos);
            return res.json(atendimentos);
        }
    })

    res.render('home', {user: req.user});
})

But then I changed to this code:
 router.get('/home', isAuthenticated, function(req, res){

    //Added async to the function
    atendimentos.find({}, async function(err, atendimentos) {
        if(!err){
            console.log(atendimentos);
            return res.json(atendimentos);
        }
    })

    res.render('home', {user: req.user});
})

The application stopped crashing but the error continues. I don't know why. Maybe I could get some help handling this?
Thanks

A: res.json() sends the response (formatted as JSON).
res.render() sends the response (using other formatting methods).
You can't send two responses to the same request.
Pick one.

A: From the Docs:
res.render

Renders a view and sends the rendered HTML string to the client.

res.json

Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().

So, as mentioned, you are sending two responses. If what you want is to have the atendimentos data in your view, you could pass it as a property of the object to res.render, something like:
 router.get('/home', isAuthenticated, function(req, res){

    //Added async to the function
    atendimentos.find({}, async function(err, atendimentos) {
        if(!err){
            console.log(atendimentos);

            res.render('home', {user: req.user, atendimentos});
        }
    });

});

Or you could just make a separate API call with fetch, XMLHttpRequest or any other way.
P.S. async has nothing to do with your issue, the reason it stopped crashing is that unhandled rejections do not make Node crash, this will change in a future release.


text:
Q: How to copy and paste a file through the command-line? I want to copy and paste a file to /usr folder but I guess I need root access to do so so I need to learn how to copy and paste a file from one location to another through the terminal.

A: This should do it:
For a file: sudo cp /path/to/file /path/to/destination-folder/
For a folder: sudo cp -R /path/to/folder /path to destination-folder


text:
Q: Proguard - any way to ignore incompatible (due to Java bytecode version) packages in external library? I have a desktop Java project (compiled with an older JRE as target). The simplified structure of my .pro file is:
-injars qtt.jar
-outjars qtt_obf.jar
-libraryjars \Libraries\wsp.jar

wsp.jar is offered by a 3rd-party that includes Java 9-specific packages, e.g. META-INF\versions\9\com.xyz.prod\<various_other_folders>. At this time, Java 9 support is not available, hence Proguard complains about the presence of classes with version 53.0.
Is there any way to make Proguard "skip" these external dependencies (and, fo course, not break the application at runtime)?

A: It turns out that filters are a lifesaver here: changing your example so it reads
-injars qtt.jar
-outjars qtt_obf.jar
-libraryjars \Libraries\wsp.jar(!META-INF/**)

will filter out all the stuff in META-INF -- including the version 9 classfiles you are trying to get rid of. See more details in the page below.
https://www.guardsquare.com/proguard/manual/usage#filefilters


text:
Q: How to allow flex container to not shrink items with more content? I have a flex container that has items set in a row and when it reaches the end of the viewport width I want it to overflow-x: scroll. Instead it shrinks all items with more items added to fit the screen.
How can I allow it to overflow and still scroll in the x direction while keeping the items from shrinking?

.footer-container {
  width: 100%;
  height: 12rem;
  background-color: #fff;
  position: fixed;
  bottom: 0;
  display: flex;
  overflow-x: scroll;
  padding: 1rem;
  animation: slide-up;
  animation-duration: 1s;
  visibility: hidden;
  opacity: 0;
}

.footer-items {
  background-color: rgb(214, 218, 219);
  width: 17rem;
  list-style-type: none;
  border-radius: 4px;
  margin-right: 1.5rem;
  padding: 1rem;
  font-size: 1.5rem;
  position: relative;
  animation: fade-in;
  animation-duration: 2s;
  display: flex;
}

.side-col {
  display: flex;
  flex-direction: column;
}

.cart-image {
  min-width: 10rem;
  height: 6rem;
}

.cart-price {
  position: absolute;
  top: 50%;
  right: 1rem;
  transform: translateY(-50%);
  font-weight: 600;
}

Bike

    $2345

Here is how it looks without overflowing items https://i.stack.imgur.com/ZUrZS.png
and with overflowing items
https://i.stack.imgur.com/18obq.png

A: If I got you right, Just add flex-shrink: 0; to the item you don't want to shrink.
If something else needed, pls let me know.
You can have a look at flex-shrink here.

.footer-container {
  width: 100%;
  height: 12rem;
  background-color: #fff;
  position: fixed;
  bottom: 0;
  display: flex;
  overflow-x: scroll;
  padding: 1rem;
  animation: slide-up;
  animation-duration: 1s;
}

.footer-items {
  background-color: rgb(214, 218, 219);
  width: 17rem;
  flex-shrink: 0; /*add this property only*/
  list-style-type: none;
  border-radius: 4px;
  margin-right: 1.5rem;
  padding: 1rem;
  font-size: 1.5rem;
  position: relative;
  animation: fade-in;
  animation-duration: 2s;
  display: flex;
}

.side-col {
  display: flex;
  flex-direction: column;
}

.cart-image {
  min-width: 10rem;
  height: 6rem;
}

.cart-price {
  position: absolute;
  top: 50%;
  right: 1rem;
  transform: translateY(-50%);
  font-weight: 600;
}

Bike

    $2345

Bike

    $2345

Bike

    $2345

Bike

    $2345

Bike

    $2345


text:
Q: "TripleDES.CreateEncryptor() "Reference to a non-shared member requires an object reference I Import the Imports System.Security.Cryptography to encrypt my password but using this and adding this code.
Public Function EncryptData(ByVal plaintext As String) As String
    Dim plainttextBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(plaintext)
    Dim ms As New System.IO.MemoryStream
    Dim encStream As New CryptoStream(ms, TripleDES.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)

    encStream.Write(plainttextBytes, 0, plainttextBytes.Length)
    encStream.FlushFinalBlock()

    Return Convert.ToBase64String(ms.ToArray)

End Function

I'm having a error Reference to a non-shared member requires an object reference. Can someone help me. Thanks

A: CreateEncryptor is an instance method, not Shared, so you need to call it on an instance of the TripleDES class, not on the class itself. What you're doing would be akin to this:
Return Convert.ToBase64String(MemoryStream.ToArray)

You are obviously calling ToArray on an instance of the MemoryStream class rather than on the class itself. You need to do the same for the TripleDES.CreateEncryptor method, i.e. create an instance of the class first and then call the method on that.


text:
Q: Making a duplicate Foreign Key in schema bad practice? Here's a summary of my tables:
---------
user_info
---------
id

---------
post
---------
id
user_id(Foreign Key)

---------
review
---------
id
post_id(Foreign Key)

I have cases where I need fetch reviews by the user_id.
Right now, I find posts with user_id(FK) then find reviews with post_id(FK) that match post.id
I wanted to ask if it's a bad practice to make another user_id(FK) in review
table because it is redundant

A: In your example data, you don't have a user_id in the reviews table.
However, if you did, it would probably be the user of the reviewer, not the post author.
Hence, it is something entirely different, you probably should have the column, and it should have a proper foreign key reference.


text:
Q: CFDocument error: an exception occurred when document processing <cffunction name="print" output="no" access="private">
    <cfset filenameb = "mysite.com\print\test.pdf">
    <cfdocument filename="#filenameb#" overwrite="yes" format="PDF" pagetype="A4" orientation="portrait">
        <cfdocumentitem type="header">
            Print
        </cfdocumentitem>
        <cfdocumentitem type="footer">
            blah
        </cfdocumentitem>

        <cfoutput>
            aaaaaaaaa
        </cfoutput>
    </cfdocument>
</cffunction>

Does anyone have any ideas what is causing this error?
"an exception occurred when document processing"

A: Try specifying font for all the text elements (in header, footer and body).
For eg: replace
<cfoutput>
    aaaaaaaaa
</cfoutput>

with
<cfoutput>
    <div style="font-family: monospace"> aaaaaaaaa </div>
</cfoutput>


text:
Q: Pset2 Need help encrypting words Vigenere is encrypting the message incorrectly for example if the key is "hello" and the message is hello, the encrypted text is now "eipsv" when it should be "hello".
I would really appreciate any tips on fixing this bug.
    string message = GetString();
    int m = strlen(message);
    int i = 0;

      if(isalpha(message[i]))
      {
     for(int j = 0; j < n; i++)
    {
     key[j] = tolower(key[j]) - 97;
     j++;

      for (i = 0; i < m; i++)
       {
            char c = message[i];

              if (islower(c))
                {
                    c = (((c - 'a' + key[j%n])%26) +'a');
                    j++;
                    printf("%c", c);
                }
              if (isupper (c))
                    {
                        c = (((c - 'A' + key[j%n])%26) +'A');
                        j++;
                        printf("%c", c);
                        }
              else if (!isupper(c) && !islower(c))
                    {
                     printf("%c", c);
                     j++;
                    }
      }
      }
    }
   printf("\n");
    }

A: Using the keyword "hello" would encode your message "hello" as follows:
h -> (shift 7) -> o
e -> (shift 4) -> i
l -> (shift 11) -> w
l -> (shift 11) -> w
0 -> (shift 14) -> c

So, the result should be "oiwwc".

A: Ok, a handful of changes:
Your first loop to convert the key to values of 0 - 25 should be in a separate loop from the encoding loop.  Convert the key, and then move on to the encoding loop.
In the encoding loop, you will need two incrementers, "i" and "j", both of which need to be reinitialized to 0 in your FOR ( ...;...;... ) line.  You can't reuse "j" from your key conversion loop because it is out of scope.
Remove j++ after your printf() line from your ELSE IF statement in encoding loop.  You do not increment "j" if a letter isn't encoded.
By the way, once you update your program and run it through check50, you will find several error-check errors because you have some error conditions to check that I don't see in your current code.  But, it should encode correctly with the above changes.


text:
Q: Possible extensions to the default diagnostic plots for lm (in R and in general)? I started digging a bit into the plot.lm function, this function gives six plots for lm, they are:

*

*a plot of residuals against fitted values

*a Scale-Location plot of sqrt(| residuals |) against fitted values

*a Normal Q-Q plot, a plot of Cook's distances versus row labels

*a plot of residuals against leverages

*a plot of Cook's distances against leverage/(1-leverage)

And I am wondering what other common/useful extensions of current plots exists for linear models, and how can they be done in R? (links to articles of packages are also welcomed)
So the boxcox function (from {MASS}) is an example of another useful diagnostic plot (and such an answer would be great), however, I am more curious about variations/extensions on existing default diagnostic plots for lm in R (although general other remarks on the topic are always welcomed).
Here are some simple examples of what I mean:
#Some example code for all of us to refer to
set.seed(2542)
x1 <- rnorm(100)
x2 <- runif(100, -2,2)
eps <- rnorm(100,0,2)
y <- 1 + 2*x1 + 3*x2 + eps
y[1:4] <- 14 # adding some contaminated points
fit <- lm(y~x1+x2)

#plot(y~x1+x2)
#summary(fit)

To plot the residuals vs each of the potential x
plot(resid(fit)~x1); abline (h = 0)
plot(resid(fit)~x2); abline (h = 0)
# plot(resid(fit)~x1+x2) # you can also use this, but then you wouldn't be able to use the abline on any plot but the last one

To add the the 0-1 line (how is this line called in English?!) to the qqplot so to see how much the qqline deviates from it
plot(fit, which = 2); abline(0,1, col = "green")

To plot the qq-plot using externally studentized residuals
# plot(fit, which = 2); abline(0,1, col = "green") # The next command is just like this one
qqnorm(rstandard(fit), ylim = c(-2.2,4.2)); qqline(rstudent(fit), lty = 2) ;abline(0,1, col = "green")
qqnorm(rstudent(fit), ylim = c(-2.2,4.2)); qqline(rstudent(fit), lty = 2) ;abline(0,1, col = "green")
# We can note how the "bad" points are more extreme when using the rstudent

A: This answer focus on what's available in base R, rather than external packages, although I agree that Fox's package is worth to adopt.
The function influence() (or its wrapper, influence.measures()) returns most of what we need for model diagnostic, including jacknifed statistics. As stated in Chambers and Hastie's Statistical Models in S (Wadsworth & Brooks, 1992), it can be used in combination to summary.lm(). One of the example provided in the so-called "white book" (pp. 130-131) allows to compute standardized (residuals with equal variance) and studentized (the same with a different estimate for SE) residuals, DFBETAS (change in the coefficients scaled by the SE for the regression coefficients), DFFIT (change in the fitted value when observation is dropped), and DFFITS (the same, with unit variance) measures without much difficulty.
Based on your example, and defining the following objects:
lms <- summary(fit)
lmi <- influence(fit)
e <- residuals(fit)
s <- lms$sigma
xxi <- diag(lms$cov.unscaled)
si <- lmi$sigma
h <- lmi$hat
bi <- coef(fit) - coef(lmi)

we can compute the above quantities as follows:
std. residuals    e / (s * (1-h)^.5
stud. residuals   e / (si * (1-h)^.5
dfbetas           bi / (si %o% xxi^.5
dffit             h * e / (1-h)
dffits            h^.5 * e / (si * (1-h))

(This is Table 4.1, p. 131.)
Chambers and Hastie give the following S/R code for computing DFBETAS:
dfbetas <- function(fit, lms = summary(fit), lmi = lm.influence(fit)) {
  xxi <- diag(lms$cov.unscaled)
  si <- lmi$sigma
  bi <- coef(fit) - coef(lmi)
  bi / (si %o% xxi^0.5)
}

Why do I mention that approach? Because, first, I find this is interesting from a pedagogical perspective (that's what I am using when teaching introductory statistics courses) as it allows to illustrate what can be computed from the output of a fitted linear model fitted in R (but the same would apply with any other statistical package). Second, as the above quantities will be returned as simple vectors or matrices in R, that also means that we can choose the graphics device we want---lattice or ggplot--- to display those statistics, or use them to enhance an existing plot (e.g., highlight DFFITS values in a scatterplot by varying point size cex).

A: Package car has quite a lot of useful functions for diagnostic plots of linear and generalized linear models. Compared to vanilla R plots, they are often enhanced with additional information. I recommend you try example("<function>") on the following functions to see what the plots look like. All plots are described in detail in chapter 6 of Fox & Weisberg. 2011. An R Companion to Applied Regression. 2nd ed.

*

*residualPlots() plots Pearson residuals against each predictor (scatterplots for numeric variables including a Lowess fit, boxplots for factors)

*marginalModelPlots() displays scatterplots of the response variable against each numeric predictor, inluding a Lowess fit

*avPlots() displays partial-regression plots: for each predictor, this is a scatterplot of a) the residuals from the regression of the response variable on all other predictors against b) the residuals from the regression of the predictor against all other predictors

*qqPlot() for a quantile-quantile plot which includes a confidence envelope

*influenceIndexPlot() displays each value for Cook's distance, hat-value, p-value for outlier test, and studentized residual in a spike-plot against the observation index

*influencePlot() gives a bubble-plot of studentized residuals against hat-values, with the size of the bubble corresponding to Cook's distance, also see dfbetaPlots() and leveragePlots()

*boxCox() displays a profile of the log-likelihood for the transformation parameter $\lambda$ in a Box-Cox power-transform

*crPlots() is for component + residual plots, a variant of which are CERES plots (Combining conditional Expectations and RESiduals), provided by ceresPlots()

*spreadLevelPlot() is for assessing non-constant error variance and displays absolute studentized residuals against fitted values

*scatterplot() provides much-enhanced scatterplots inluding boxplots along the axes, confidence ellipses for the bivariate distribution, and prediction lines with confidence bands

*scatter3d() is based on package rgl and displays interactive 3D-scatterplots including wire-mesh confidence ellipsoids and prediction planes, make sure to run example("scatter3d")
In addition, have a look at bplot() from package rms for another approach to illustrating the common distribution of three variables.


text:
Q: Para que serve o método setRequestHeader no AJAX puro em modo POST? Para que serve e qual a importância deste tradicional método setRequestHeader do AJAX puro quando são feitas requisições do tipo POST pelo cliente para uma aplicação PHP no servidor? Sempre sou obrigada a usa-lo com o valor "Content-Type","application/x-www-form-urlencoded" sem saber ao certo sua real função. Também gostaria de saber as falhas de segurança já conhecidas pela comunidade que podem ser causadas no servidor caso o PHP eventualmente receba um cabeçalho com valor diferente deste que, para mim que sou leiga, é um valor padrão. Sua utilização é obrigatória?

A: XHR().setRequestHeader serve para definir um cabeçalho na lista de cabeçalhos da requisição. Quando você chama ele dessa maneira:
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")

você está definindo o tipo de conteúdo que vai atribuir na requisição do método "post" ou "put", lá no primeiro parâmetro de XHR().send. O tipo de conteúdo "application/x-www-form-urlencoded" só indica que o conteúdo está no formato de parâmetros de URL, por exemplo: "?param=1&etc=2"
Cabeçalhos sempre são usados em requisições, nunca há risco de segurança para o servidor.
Verifique essa página, ela lista cabeçalhos que podem ser definidos em uma requisição. Observação: nem todos cabeçalhos podemos definir programaticamente com o método XHR().setRequestHeader.
Não há risco de segurança em relação à cabeçalhos. Não existe essa coisa de não enviar cabeçalhos, e além disso eles não podem afetar o servidor.
Para obter mais informações ainda, há uma especificação sobre o XMLHttpRequest aqui.
O que pode afetar o servidor depende de suas ações.


text:
Q: Devexpress column header color (each column different color), winform c# I have a GridView and GridControl in winform app (c#) and I have several columns in GridView and I want to set background of header columns. I can do it but it changes all columns in same color. I used that code:
gridcntrActic.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Flat;
gridcntrActic.LookAndFeel.UseDefaultLookAndFeel = false;
gridviewActiv.Appearance.HeaderPanel.Options.UseBackColor = true;
gridviewActiv.Appearance.HeaderPanel.BackColor = System.Drawing.Color.White;

This code changes all column headers to white. But I want to change first column to white and second to red and so. How can I do it?

A: If you want to change first column to white and second to red, so change it.
Here is example:
gridcntrActic.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Flat;
gridcntrActic.LookAndFeel.UseDefaultLookAndFeel = false;

gridviewActiv.Columns[0].AppearanceHeader.Options.UseBackColor = true;
gridviewActiv.Columns[0].AppearanceHeader.BackColor = System.Drawing.Color.White;

gridviewActiv.Columns[1].AppearanceHeader.Options.UseBackColor = true;
gridviewActiv.Columns[1].AppearanceHeader.BackColor = System.Drawing.Color.Red;

//And so on.

A: Reference documentation: Customizing the Appearances of Individual Column and Band Headers

Custom appearances can also be assigned to individual column and band
headers. This technique is similar to the one described above. To
specify the appearance settings used to paint an individual column
header, use the column's GridColumn.AppearanceHeader property.
The analogue for bands is the GridBand.AppearanceHeader property.

The appearance settings of all the column headers within the View are specified by the GridViewAppearances.HeaderPanel property. The AppearanceHeader property provides appearance settings for individual column headers.
Column headers can also be custom painted using the GridView.CustomDrawColumnHeader event.
Method 1:
  gridControl1.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Flat;
  gridControl1.LookAndFeel.UseDefaultLookAndFeel = false; // <<<<<<<<
  gridviewActiv.Columns[0].Appearance.HeaderPanel.Options.UseBackColor = true;
  gridviewActiv.Columns[0].Appearance.HeaderPanel.BackColor = System.Drawing.Color.White;

Method 2:
void gridView1_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e) {
    if (e.Column == null) return;
    if (e.Column == colGrowth) //condition to paint specific column
    {
        e.Appearance.BackColor = Color.Red;
        e.Handled = true; // must set flag to true to tell grid that it has been customized.
    }
}

Source:Applying Styles to Group Rows
Example:
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.Utils;

private void Form1_Load(object sender, System.EventArgs e) {
   // ...
   InitStyles();
}

private void InitStyles() {
   GridView View = gridControl1.MainView as GridView;
   // Customize the column headers' appearances.
   AppearanceObject appCountry = View.Columns["Country"].AppearanceHeader;
   appCountry.BackColor = Color.AntiqueWhite;
   appCountry.BackColor2 = Color.Snow;
   View.Columns["City"].AppearanceHeader.BackColor = Color.LightSalmon;
   // Set the View's painting syle.
   View.PaintStyleName = "UltraFlat";
}

Note:
Using the Appearance settings, you can change the background color of a column header when GridControls's LookAndFeel property is set to Flat, UltraFlat or Style3D value. If you wish to change a color for a skinned column header, you should create your own Skin. One more solution is to paint the column header manually within the CustomDrawColumnHeader event handler. This event allows you to paint the column header just as you need and thus do not rely on the grid's painting.

A: Subscribe to event CustomDrawColumnHeader and set color to column you need:
gridView1.CustomDrawColumnHeader +=
    new ColumnHeaderCustomDrawEventHandler(gridView1_CustomDrawColumnHeader);

void gridView1_CustomDrawColumnHeader(object sender, ColumnHeaderCustomDrawEventArgs e)
{
    if (e.Column == _yourColumn)
    {
        e.Appearance.BackColor = Color.Red;
        e.Handled = true;
    }
}


text:
Q: Canvas draw text () not show text on secreen i am trying to drawtext on screen.
but nothing show on the secreen.help me plz.
my code is here .
Main.java class
   public class MainActivity extends Activity

 {

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

    int w = 30, h = 30;

    Bitmap.Config conf = Bitmap.Config.ARGB_8888;
    Bitmap bmp = Bitmap.createBitmap(w, h, conf);
    Canvas canvas = new Canvas(bmp);

    Paint paint = new Paint();
 Typeface face=Typeface.createFromAsset(getAssets(),"RECOGNITION.ttf");
    paint.setColor(Color.BLACK);
    paint.setTypeface(face) ;
    paint.setTextSize(20);
    canvas.drawText("Some Text", 30, 30, paint);

  }

but nothing show on the screen.
my xml is here..
mystyle.xml
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

  </RelativeLayout>

A: Try this
-Main.java--
public class MAIN extends Activity {
    CustomDrawableView mCustomDrawableView;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mCustomDrawableView = new CustomDrawableView(this);
        setContentView(mCustomDrawableView);

    }
}

--CustomDrawableView.java--
public class CustomDrawableView extends View {
//private ShapeDrawable mDrawable;
int x=0;
int y=0;

public CustomDrawableView(Context context) {
    super(context);

}

protected void onDraw(Canvas canvas) {
    Paint mPaint = new Paint();
    mPaint.setColor(0xffff0000);
    canvas.drawCircle(x, y, 5, mPaint);
}

}


text:
Q: How to create ActiveTabChanged for Ajax tabContainer? How to create ActiveTabChanged for Ajax tabContainer? If it was a Button, just double click to create the code below. I double clicked the tabContainer but nothing happened.
I also have a related question, please click this link:
[Ajax tabContainer using GridView inside panel, one button outside of the tabContainer
My .aspx code: notice I've changed to AutoPostBack="True"

                         Splash

A: 1) first you select your tab container
2) after press f4 then
3) go to event
4) double click on ActiveTabChanged


text:
Q: Validating radiobuttons in android I know that you cant uncheck a radiobutton in android by pressing it again. But you can uncheck all the other radioButtons if one radiobutton is checked.
The question is how can I know that one radiobutton was clicked in a radiobutton group..?
could someone also give me a link to a short snippet of how to to reset all the radiobuttons in a group while one radio button was selected?!?!

A: radioButtonGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(RadioGroup radioGroup,
            int radioButtonID) {
        switch(radioButtonID) {
            case R.id.radioButton1:
                //radio 1 clicked
                break;
            case R.id.radioButton2:
                //radio 2 clicked
                break;
            case R.id.radioButton3:
                //radio 3 clicked
                break;
        }
    }
});

I hope it wil help u..

A: Take a look at the official guide (scroll down to Radio Buttons).
It reads: It's important that the RadioButtons are grouped together by the RadioGroup element so that no more than one can be selected at a time. This logic is automatically handled by the Android system. When one RadioButton within a group is selected, all others are automatically deselected.
It also provides some code snippets for listening to and handling click events.


text:
Q: Как на ovh поменять главный ipv4 на один из failover адресов? У меня ovh хост game1, система debian 9, на нем есть основной адрес и 10 адресов failover.
Я хочу сменить главный адрес на один из failover адресов.
Мне это необходимо, чтобы исходящие соединения не использовали главный адрес.
Допустим главный адрес это 43.144.13.127, а failover - 32.114.67.212
Текущий конфиг /etc/systemd/network/50-default.network у меня такой:
# This file sets the IP configuration of the primary (public) network device.
# You can also see this as "OSI Layer 3" config.
# It was created by the OVH installer, please be careful with modifications.
# Documentation: man systemd.network or https://www.freedesktop.org/software/systemd/man/systemd.network.html

[Match]
MACAddress=s8:a1:22:5b:43:32

[Network]
Description=network interface on public network, with default route
DHCP=no
Address=43.144.13.127/24
Gateway=43.144.13.254
IPv6AcceptRA=no
NTP=ntp.ovh.net
DNS=127.0.0.1
DNS=213.186.33.99
DNS=1032:23d2:3:163::1
Gateway=1032:23d2:0222:42ff:ff:ff:ff:ff

[Address]
Address=1032:23d2:0222:427f::/64

[Route]
Destination=1032:23d2:0222:42ff:ff:ff:ff:ff
Scope=link

[Address]
Address=32.114.67.212/32
Label=failover

# ... и остальные failover адреса

Как сделать так, чтобы адрес 32.114.67.212 стал главным? То есть использовался для исходящих соединений?
Моя логика заключается в том, что раз я могу сделать исходящий запрос, вручную указав интерфейс, например так:
root@host:~# curl --interface failover ifconfig.me
32.114.67.212

Тогда должен быть способ указать этот интерфейс по умолчанию, но как?

A: С помощью команды ip r это сделать можно так:
/bin/ip r change default via 43.144.13.254 dev enp1s0f0 proto static src 32.114.67.212

Но это правило не сохранится после ребута хоста. Чтобы оно сохранилось, нужно изменить конфигурацию /etc/systemd/network/50-default.network вот так:
# This file sets the IP configuration of the primary (public) network device.
# You can also see this as "OSI Layer 3" config.
# It was created by the OVH installer, please be careful with modifications.
# Documentation: man systemd.network or https://www.freedesktop.org/software/systemd/man/systemd.network.html

[Match]
MACAddress=s8:a1:22:5b:43:32

[Network]
Description=network interface on public network, with default route
DHCP=no
Address=43.144.13.127/24
Gateway=43.144.13.254
IPv6AcceptRA=no
NTP=ntp.ovh.net
DNS=127.0.0.1
DNS=213.186.33.99
DNS=1032:23d2:3:163::1
Gateway=1032:23d2:0222:42ff:ff:ff:ff:ff

[Address]
Address=1032:23d2:0222:427f::/64

[Route]
Destination=1032:23d2:0222:42ff:ff:ff:ff:ff
Scope=link

[Route]
Gateway=43.144.13.254
PreferredSource=51.195.48.249

[Address]
Address=32.114.67.212/32
Label=failover

# ... и остальные failover адреса

Изменения:

*

*Была добавлена новая секция [Route], в которой добавлено два параметра:

*

*PreferredSource - в этом параметре указан адрес, который мы хотим сделать
адресом для исходящих соединений (в моем случае 32.114.67.212).

*Gateway - значение этого параметра берем из одноименного параметра из секции [Network].

После изменения конфига, нужно перезагрузить сеть командой:
systemctl restart systemd-networkd

Готово.


text:
Q: To show a certain ideal is maximal. I was asked the following question in my exam :
$R$ is a commutative ring with identity and $M$ is a maximal ideal of $R$. I needed to show that the ideal of $R[x]$ generated by $M$ and $x$, denoted as $(M,x)$ is maximal in $R[x]$.
My attempt : I kept trying to somehow have a homomorphism from $R$ to the quotient ring $R[x]/(M,x)$ whose kernel is $M$. If I would have succeeded, I could apply the 1st Isomorphism theorem which would imply that $R[x]/(M,x)$ is a field which in turn implies that $(M,x)$ is maximal. But, I kept struggling and couldn't come up with something constructive. Any help is appreciated. Thanks for your time.

A: Consider the homomorphism
$$
R[x]\to R/M,\qquad f(x)\mapsto f(0)+M
$$
and compute its kernel and image.

A: Consider the morphism $f:R[x]\to R[x]/(M,x)$ and the inclusion $g:R\to R[x]$. Then,
$$
\ker(f\circ g) = g^{-1}(\ker(f))= \ker(f)\cap R=(M,x)\cap R=M
$$
and as you explained, this gives you $R/M\cong R[x]/(M,x)$.

A: First we show $(M,x)$ is a proper ideal of $R[x]$.

Suppose instead that $(M,x) = (1)$.

Then $1 \in (M,x)$ implies $1 = m + xg(x)\;$for some $m \in M$, some $g \in R[x]$.

Since $M$ is maximal in $R,\, M$ is a proper ideal of $R$, hence $m \ne 1$.

Then
\begin{align*}&1 = m + xg(x)\\[4pt]
\implies\;&1-m = xg(x)
\end{align*}
contradiction, since $xg(x)$ can't be a nonzero constant.
It follows that $(M,x)$ is a proper ideal of $R[x]$, as claimed.
Let $f \in R[x]\setminus(M,x)$.

Then to show $(M,x)$ is maximal in $R[x]$, it suffices to show $(M,x,f) = (1)$.

Letting $f(x) = r + xg(x)$, for some $r \in R$, some $g \in R[x]$, we can't have $r \in M$, else $f \in (M,x)$.

Since $M$ is maximal in $R$, it follows that as an ideal of $R,\,(M,r) =(1),],$ hence also $(M,r) = (1)$ as an ideal of $R[x]$.

Then
\begin{align*}
&f(x) = r + xg(x)\\[4pt]
\implies\;&r \in (x,f)\\[4pt]
\implies\;&r \in (M,x,f)\\[4pt]
\implies\;&(M,r) \subseteq (M,x,f)\\[4pt]
\implies\;&(M,x,f) = (1)
\end{align*}
It follows that $(M,x)$ is maximal in $R[x]$, as was to be shown.


text:
Q: Python Send known bytes I want to send a stream of known bytes over the network, such as 0020ff00, but I want to use other method beside concatenation of char symbols.
Can you provide me with another, more elegant method?
Thanks
def send_connect_request(sock):
    print('Sending connect request...')
    sock.send('' + chr(2) + chr(0) + chr(0) + chr(0) + chr(255) + chr(0))
    # sock.shutdown(1)

change to
def send_connect_request(sock):
    print('Sending connect request...')
    sock.send(0x0002ff00)
    # sock.shutdown(1)

A: If you know the bytes, use a bytes literal:
sock.send(b'\x02\x00\x00\x00\xff\x00')

If you really don't want to type out all the escape-sequences, use the bytes constructor with a list of ints:
sock.send(bytes([2,0,0,0,255,0]))


text:
Q: Align multi-columns inside Select Dropdown box Hey all I have been trying to find an example of a 3-column dropdown box but have been unsussesful in doing so. Though I have found 2-column ones but they do not seem to work as I need them to.
In the dropdown I'd like it to look like this:
Heading1 | Heading 2     | Heading 3
something| something here| Something here again
blah blah| bleblah       | blahblahlbha
hello    | hi            | goodbye

I have found a somewhat nice jquery code that tries to add spaces where its needed in order to align the columns with each other.
$.each(responce["TrainingSite"], function (key, value) {
   //Loops to populate the dropdown options
   $('#TrainingSite_1').append($('<option>', {
      value: value.RoomN,
      text: value.RoomN + ' +' + value.RoomC + ' +' + value.RoomCo
   }));
});

$("#TrainingSite_1 option").each(function () {
   var len = $(this).text().length;

   if (len > biggestLength) {
       biggestLength = len;
   }
});

var padLength = biggestLength + spacesToAdd;

$("#TrainingSite_1 option").each(function () {
   var parts = $(this).text().split('+');
   var strLength = parts[0].length;

   for (var x = 0; x < (padLength - strLength) ; x++) {
      parts[0] = parts[0] + ' ';
   }

   $(this).text(parts[0].replace(/ /g, '\u00a0') + parts[1] + parts[2]).text;
});

Which produces this result:

Anyone have code for either side (MS SQL / Jquery) that will do the alignment that I need?
Working JSFIDDLE example
https://jsfiddle.net/e17Lt1mL/

A: I'm a little late to the party here, but you're on the right track with spacing out the column data.  Just add a fixed width font to your select and option elements and it will work.  I use:
select.fw, option.fw {font-family: 'courier new'}


text:
Q: How to make the Save option on menu strip in Paint using C# WinForms? I'm trying to make a save option on my menu strip that should save whats drawn on the picture Box, currently I'm making in with SaveFileDialog but in the end I am saving a file which I cannot open with any photo viewer.
Here's the code:
    private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (saveFileDialog1.ShowDialog() == DialogResult.OK)
        {
            using (Stream s = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
                using(StreamWriter swr=new StreamWriter(s))
            {
                swr.Write(pbCanvas.Image);
            }
        }
    }

https://pastebin.com/mU8TXPgW

A: Maybe this would work:
pictureBox.Image.Save(@"FilePath",ImageFormat.Jpeg);


text:
Q: Computer won't execute multi-thread program simultaneously I wrote a simple c program using pthreads. On my laptop the multithreaded program runs as expected. When running on desktop the execution of the program is unusual. Unusual that the program gets executed one thread at a time despite threads running simultaneously.  The output is the same when running on my virtual machine. Any possible reasons as to why this is happening?
Code:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <unistd.h>
#include <pthread.h>

//shared variable
int SharedValue = 0;

//mutex lock
pthread_mutex_t lock;

//barrier
pthread_barrier_t barrier;

//which is an integer pointer to where each thread number is stored
void * SimpleThread(void * which) {
    int num, val;
    int thread_num = *(int *) which;

    for(num = 0; num < 20; num++) {
        #ifdef PTHREAD_SYNC
        pthread_mutex_lock(&lock);
        #endif
        val = SharedValue;

        printf("*** thread %d sees value %d\n", thread_num, val);
        SharedValue = val + 1;
        #ifdef PTHREAD_SYNC
        pthread_mutex_unlock(&lock);
        #endif
    }
    //barrier here
    #ifdef PTHREAD_SYNC
    pthread_barrier_wait(&barrier);
    #endif

    val = SharedValue;
    printf("Thread %d sees final value %d\n", thread_num, val);

}
/*** main thread ***/

//given two arguments program_name, threads to make
int main(int argc, char* argv[]) {
    int i, threadsToMake, error;

    //verify the user has given number of arguments required to run
    if(argc != 2) {
        printf("Please provide a number of threads to create.\n");
        return 0;
    }

    //Verify arguments are within range - integer
    int argumentLength = strlen(argv[1]);
    for(i = 0; i < argumentLength; i++) {
        if(!isdigit(argv[1][i])) {
            printf("Argument is not a number.\n");
            return 0;
        }
    }
    //convert argument to integer
    threadsToMake = atoi(argv[1]);

    //Making an array of pthreads
    pthread_t thread_array[threadsToMake];
    //makingan array of thread_nums to pass to function
    int thread_nums[threadsToMake];
    //initialize barrier to the number of threads for program
    pthread_barrier_init(&barrier, NULL, threadsToMake);

    for(i = 0; i < threadsToMake; i++){
        //store the thread numbers
        thread_nums[i] = i;

        //Generate that many threads
        //Send threads to SimpleThread
        error = pthread_create(&thread_array[i], NULL, SimpleThread, (void *) &thread_nums[i]);
        if(error != 0){
            printf("Problem creating thread %d", i);
            return 0;
        }
    }

    //join all threads
    for(i = 0; i < threadsToMake; i++){
        pthread_join(thread_array[i], NULL);
    }

    return 0;
}

Unusual output for 2 threads:
*** thread 0 sees value 0
*** thread 0 sees value 1
*** thread 0 sees value 2
*** thread 0 sees value 3
*** thread 0 sees value 4
*** thread 0 sees value 5
*** thread 0 sees value 6
*** thread 0 sees value 7
*** thread 0 sees value 8
*** thread 0 sees value 9
*** thread 0 sees value 10
*** thread 0 sees value 11
*** thread 0 sees value 12
*** thread 0 sees value 13
*** thread 0 sees value 14
*** thread 0 sees value 15
*** thread 0 sees value 16
*** thread 0 sees value 17
*** thread 0 sees value 18
*** thread 0 sees value 19
*** thread 1 sees value 20
*** thread 1 sees value 21
*** thread 1 sees value 22
*** thread 1 sees value 23
*** thread 1 sees value 24
*** thread 1 sees value 25
*** thread 1 sees value 26
*** thread 1 sees value 27
*** thread 1 sees value 28
*** thread 1 sees value 29
*** thread 1 sees value 30
*** thread 1 sees value 31
*** thread 1 sees value 32
*** thread 1 sees value 33
*** thread 1 sees value 34
*** thread 1 sees value 35
*** thread 1 sees value 36
*** thread 1 sees value 37
*** thread 1 sees value 38
*** thread 1 sees value 39
Thread 1 sees final value 40
Thread 0 sees final value 40

A: How do you know its not multi threading?
It probably is multi threaded, but for some possible reasons it may not look like it.
First, because the task is very small and thread creation requires some time
the first thread may finish even before the second init is finished.
Second, its up to the thread scheduler to decide which thread should run in every moment, and here it may be possible that he decided to run one to finish and then the other.
If you really want to see it multi threading, use a bigger task, like computing all primes in certain range or count divisors of a large number.
Those are functions that require more computing, and there will be a noticeable difference between runtime for single thread apps to multi thread apps (if you divide the work between them).

A: In addition to the general considerations expressed by @Uriel.Gi,
pthreads mutexes do not, in general, impose a fairness policy.  That is, when multiple threads contend to acquire a mutex, it does not necessarily go to the one that has been waiting longest, nor do threads that have recently held the mutex get de-prioritized.
As a result, a tight loop where a mutex is acquired at the very top and relinquished at the very bottom is an anti-pattern.  A thread running such a loop attempts to re-acquire the mutex immediately after releasing it, and there is a very good chance that it succeeds because it's already running when it releases the mutex, any other threads waiting on it are not, and the attempt to re-acquire comes so quickly that other threads don't have much chance to cut in.  This commonly produces a situation where the threads each hog the mutex for an extended time, with switches between them being rare.
Generally speaking, such a problem is a symptom of poor design.  There cannot be concurrent execution of a critical region, so if substantially all of several threads' executions are inside critical regions guarded by the same mutex, then what's the point of the threads?

A: Your threads spend almost all their time printing to the same output stream. Since only one thread can access that stream at a time, there is no way they can run with any significant concurrence.
There is no point to trying to use more than one core. Only one core could be running code to access the output stream and the others would be waiting for their turn. That's terribly inefficient, so this code is going to, more or less, run on only one core.
Given that, it makes sense to let one thread keep using the core for as long as possible. Context switches take time and make the caches cold. So this code is going to let the one core run one thread until the thread's timeslice is exhausted.
So you got exactly the behavior I would expect.


text:
Q: Python: how to split a string based on space but keep '\n'? I want to split a string based on space
a = ' girl\n    is'
a.split()
['girl', 'is']

I found that after split, the '\n' will also disappear. My desired result is
['girl\n', 'is']

Then if I used .splitlines method, the result returned is also not what I want.
a.splitlines(True)
[' girl\n', '    is']

Do you have any suggestions? Thank you!

A: Try this one
[s for s in a.split(' ') if s]
['girl\n', 'is']

A: You can use regular expressions in order to split on any sequences of horizontal whitespace (including e.g. tabs), but not vertical:
>>> import re
>>> re.split(r'[^\S\n\r]+', a.strip())
['girl\n', 'is']

# [^...]: not any of ...
# \S:     non whitespace
# \n, \r: line breaking white space
# [^\S\n\r]+: one or more non-space or non-line-breaking space

A: Performance wise, you should consider using list comprehensions (as is mentioned in Ursus's answer)  with str.split(' ') as:
>>> a = ' girl\n    is'

>>> [word for word in a.split(' ') if word]
['girl\n', 'is']

However if you are interested in functional approach, you may use filter as:
>>> list(filter(bool, a.split(' ')))
['girl\n', 'is']

Here a.split(' ') will split your string based on space as separator and filter (with bool) will filter out your empty strings from the list.

Issue with your code
As the Python's str.split document says:

*

*if separator is not passed:

or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

*if separator is passed:

consecutive delimiters are not grouped together and are deemed to delimit empty strings. Splitting an empty string with a specified separator returns [''].

A: Easy to understand:
b=a.split()
c=[i for i in b if i]
print(c)

Meaning:
b=a.split()
c=[i for i in b if i!=' ']
print(c)


text:
Q: sqlalchemy некорректно отрабатывает условие фильтра: q.filter(table1.name1 != table2.name2) Есть приложение на flask, используется sqlalchemy. Есть запрос, в который вставляю .filter()
Вопрос следующий: Почему такой код
q.filter(Transaction.transaction_id == ReconciledTransaction.safe_withdraw_id)

отрабатывает корректно, а вот этот
q.filter(Transaction.transaction_id != ReconciledTransaction.safe_withdraw_id)

работает неправильно (фильтр в этом случае тупо игнорируется)?

A: Помогли на enSO
При использовании запроса на подобии этого:
q = db.session.query(Transaction). \
filter(Transaction.transaction_id != ReconciledTransaction.safe_withdraw_id)

Получаем такой SQL:
SELECT Transaction.* FROM Transaction, ReconciledTransaction
WHERE Transaction.transaction_id != ReconciledTransaction.safe_withdraw_id

Соответственно мы в любом случае делаем выборку из второй таблицы, и в таком случае в результат запроса попадают и те и те результаты, получается что фильтр 'как-бы игнорируется'.
Чтобы такого не происходила, нужно сделать выборку из второй таблицы(с которой сравниваем):
r_query = db.session.query(ReconciledTransaction.safe_withdraw_id). \
group_by(ReconciledTransaction.safe_withdraw_id)
r_ids = [x[0] for x in r_query]

А наш фильтр(в моём случае), будет выглядить следующим образом:
q = q.filter(Transaction.transaction_id.notin_(r_ids))

Как вариант, можно сделать вот так(говорят, лучше производительность):
q = q.filter(~session.query(ReconciledTransaction). \
filter(ReconciledTransaction.safe_withdraw_id == Transaction.id).exists())


text:
Q: Adding a TestSettings file to SolutionItems in VisualStudio ((EnvDTE80.Solution2)dte.Solution).GetProjectItemTemplate("Test Settings", "Test");

I need to add a new TestSettings object programmatically to a C# project in Visual Studio. To do this I need to get the path of the template file. The call to GetProjectItemTemplate should do this, but fails for this type of template. Other template types, for example, a CSharp class, work fine. Even custom types that I have registered work fine. But not the TestSettings type.
You can see the template in this zip file:
C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\Test\1033\TestSettings.zip
Any idea why this template type doesn't work?

A: You are not the only person to have issues with "test settings", a chap on the forum
below resorted to unloading, editing the project xml and reloading it in order to update
the settings...
Its a bit of a faff but it could be some solution..
http://social.msdn.microsoft.com/Forums/en-US/vsx/thread/a1160459-23e3-4bd4-a672-d204eb9ffa4c/

A: In VS 2017 it is there under the solution.
Right click on Solution|Add Item...|Test Settings


text:
Q: Does using std::get on std::array give better performance? The Standard Library class template std::array<T, N> has both a member accessor function
constexpr const T& operator[]( size_type n ) const;

as well as a non-member accessor function template
template< size_t I, class T, size_t N >
constexpr const T& get( const array<T,N>& a ) noexcept

In C++17, all the operator[] overloads have been made constexpr, so I wonder what, if any, are the remaining advantages of std::get. E.g. in a program like this:
int main()
{
    auto a = std::array<int, 3> { 1, 2, 3 };
    constexpr auto idx = 0;
    std::cout << a[idx] << '\n';
    std::cout << std::get<idx>(a) << '\n';
}

any decent compiler should be able to propagate the constant index value 0 for both operator[] and get.
Question: what benefits does std::get on std::array give that operator[] doesn't?

A:
Question: what benefits does std::get on std::array give that operator[] doesn't?

In addition to providing a common interface with tuple, which is apparently how we're implicitly generically defining product types in C++, std::get does have one more advantage. Bounds checking at compile time:
std::array<int, 3> arr;
arr[4] = 17;           // bad
std::get<5>(arr) = 42; // bad, but also compile error, so actually good

That's because the tuple interface is explicitly ill-formed if the index is out of bounds (see [array.tuple]), but operator[] is just a runtime problem you have to track down.

A: Get is required for structured bindings.
Other generic tuple code will also use it.


text:
Q: Dynamically lock tr at bottom of table is there some way to lock a tr at the end of a table with VUE or Js?
I have a Vue-Component which adds tablerows dynamically based on an API call, but I need one specific tr to be at the bottom and if a new tr is added, it should be above the last one.
Not in the tfoot because there is some other nformation
Here is the Vue-Component

Template of the Vue-Component

       <input name="deliverynote" :value="delivery.id" :checked="delivery.is_printable_by_default" type="checkbox">

  [[ delivery.dispatched ]] Uhr
  [[ delivery.action ]]

[[ delivery.article_name ]]

[[ delivery.amount ]]

[[delivery.weight]]

  <input type="text" name="delivery" id="id_delivery" :value="delivery.id">[[delivery.id]]
  [[ delivery.price ]]	0.00 €

A: If your components iterated over in a loop you can render this specific  after loop above

    some headers

      your API call items

      your specific item


text:
Q: Android APP with a local database If building an app for android tablet, how big can the local database be ?
Do you this it could handle a database of 5 million registries (Read Only) ?

A: Like Distwo describes, the size in a Sqlite Database depends on what you put into the database not in the number of entries.
Check this document about Sqlite limits http://www.sqlite.org/limits.html


text:
Q: Clone Spring controller instance for testing purpose Is it possible to clone an instance of a Spring @Controller in a JUnit 5 test?
I would like to do so for the following reasons :

*

*Mocking pollutes the context for next tests and DirtiesContext has a huge impact on performance. So I don't want to use Mocks unless the modification sticks to the test class.

*I would like to run tests in parallel so modifying a shared controller instance at runtime (with ReflectionUtils for example) will produce unpredictable behavior.

*I don't want to set a controller as prototype as it is not the case at runtime and Spring is already wiring all dependencies.

I was thinking to inject the controller in the test class with @Autowired as usual and then making a deep copy of it with SerializationUtils like described in this post but I hope there could be a more robust approach than serializing / deserializing in every test class.

What makes tests failing in parallel mode?
The end-to-end tests are using common services. For example, I have a controller used in those two tests.
@RestController
@RequestMapping("/api/public/endpointA/")
public class SomeController {

    @Autowired
    private MyService myService;

    @GetMapping("/{id}")
    public Something getSomethingById(@PathVariable int id) {
        return myService.getSomethingById(id);
    }
}

The first test just check the standard usage.
class SomeControllerTest {

    @Autowired
    @InjectMocks
    private SomeController someController;

    @Test
    void testGetSomethingById() {
        Assertions.assertEquals(
            1,
            // I use some custom wrapper for the HTTP methods calls on
            // the controller like this to ease the mock mvc setup.
            someController.getAndParse(
                HttpStatus.OK,
                Something.class,
                "/{id}",
                1
            ).getId()
        );
    }
}

The second case test what happens when error occurs.
class SomeControllerExceptionTest {

    @Autowired
    private SomeController someController;

    @SpyBean
    private MyService myService;

    @BeforeEach
    public void before() {
        // Mock to test error case
        doThrow(RuntimeException.class).when(myService)
                .getSomethingById(anyInt());
    }

    @Test
    void testGetSomethingById() {
        Assertions.assertThrows(
            someController.getAndParse(
                 HttpStatus.OK,
                 Something.class,
                 "/{id}",
                 1
            )
        );
    }
}

By mocking in the second test, I'm not sure the first test won't use the mocked instance of the second test when tests are running in parallel.

Instantiate the controller in the test method yourself, mock the dependencies inside the method and inject them in the controller.
Same situation described above but I mock on a new instance of the controller.
@RestController
@RequestMapping("/api/public/endpointA/")
public class SomeController {

    @Autowired
    private MyService myService;

    @GetMapping("/{id}")
    public Something getSomethingById(@PathVariable int id) {
        return myService.getSomethingById(id);
    }
}

Test both cases in one test.
class SomeControllerTest {

    @Autowired
    private SomeController someController;

    private SomeController someControllerMocked;

    @BeforeEach
    public void before() {
        someControllerMocked = new SomeController();
        MyService mockedService = mock(MyService.class);
        doThrow(RuntimeException.class).when(mockedService)
                .getSomethingById(anyInt());
        ReflectionTestUtils.setField(
            someControllerMocked,
            "myService",
            mockedService
        );
    }

    @Test
    void testGetSomethingById() {
        Assertions.assertEquals(
            1,
            someController.getAndParse(
                HttpStatus.OK,
                Something.class,
                "/{id}",
                1
            ).getId()
        );
    }

    @Test
    void testGetSomethingByIdException() {
        Assertions.assertThrows(
            someControllerMocked.getAndParse(
                HttpStatus.OK,
                Something.class,
                "/{id}",
                1
            )
        );
    }
}

Yes! It's working and the context is not polluted. Ok let's say I have 10 services injected in my controller actually. I will have to do ReflectionUtils#setField 9 times for the legacy services and 1 time for the mock. Looks a bit ugly.

With AutowireCapableBeanFactory to the rescue. I've managed to clean this a little bit.
Same situation, but SomeController has 10 autowired services.
class SomeControllerTest {

    @Autowired
    private SomeController someController;

    private SomeController someControllerMocked;

    @Autowired
    private AutowireCapableBeanFactory beanFactory;

    @BeforeEach
    public void before() {
        someControllerMocked = new SomeController();

        // Replace the 9 ReflectionUtils#setField calls with this
        beanFactory.autowireBean(someControllerMocked);

        MyService mockedService = mock(MyService.class);
        doThrow(RuntimeException.class).when(mockedService)
                .getSomethingById(anyInt());
        ReflectionTestUtils.setField(
            someControllerMocked,
            "myService",
            mockedService
        );
    }

    @Test
    void testGetSomethingById() {
        Assertions.assertEquals(
            1,
            someController.getAndParse(
                HttpStatus.OK,
                Something.class,
                "/{id}",
                1
            ).getId()
        );
    }

    @Test
    void testGetSomethingByIdException() {
        Assertions.assertThrows(
            someControllerMocked.getAndParse(
                HttpStatus.OK,
                Something.class,
                "/{id}",
                1
            )
        );
    }
}

I think it's the best approach I've found.


text:
Q: What affects projectile speed? What factors have any effect on the traveling speed of a cast projectile?
Is it the same all over, regardless of attack speed or other boni?
Are there any skills or equipments which do affect projectile speed?
(This question covers the mechanics of attack speed but I can't figure out whether it can increase projectile speed (Wizard, Demon Hunter etc.), if it is ever possible.)

A: As far as I'm aware of, no items in the game can increase your projectile travelling speed.
However :

*

*Some skills like Arcane Orb provide a rune (Obliteration) that increase the projectile speed.

*Elites with the affixe "Missile Dampening" can slow them.

From the game guide :

Missile dampening monsters project an aura that slows your incoming
  projectiles, making ranged attacks less effective.


text:
Q: GRPC-GO:Client stub not shown in the generated pb.go file I am trying to learn GRPC from the official doc, Here is the tutorial I have followed grpc-go
Generating the proto  using this command
protoc  --go_out=$PWD  helloworld/helloworld.proto

This above command will generate the file helloworld.pb.go without any problem but the problem is the code for the client stub is missing from the generated file
syntax = "proto3";
package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

The actual error i am  getting from the client connection which is

undefined: helloworld.NewGreeterClient

And this has occurred from the line c := pb.NewGreeterClient(conn) in the greeter_client/main.go file
The reason behind because the client stub not generated in the generated file

A: Issue resolved i have some problems with the command
Here is the actual command
protoc   --go_out=plugins=grpc:$PWD helloworld.proto

A: Add --I to your command. e.g.
protoc -I helloworld --go_out=${PWD} helloworld/*.proto


text:
Q: Unrecognised selector error when adding UIImage to array I am storing a UIImage in a NSDictionary, and then passing the NSDictionary at another place in the app.  gridImages is a NSMutableArray
NSDictionary *pageDict = [pageArray objectAtIndex:0];

UIImage *pageImage = [pageDict objectForKey:@"image"];

[gridImages addObject:pageImage];

pagedict returns
{
    class = is;
    image = "<UIImage: 0x14e20e10>";
    name = kaka;
    page = 64;
}

which presumably I do
UIImage *pageImage = [pageDict objectForKey:@"image"];

However, when I try to add that UIImage to an array, I get this error:
-[UIImage stringByDeletingPathExtension]: unrecognized selector sent to instance 0x14e20e10

Any idea whats going on?
EDIT:
For the NSDictionary, I tried storing the UIImage as NSData:
NSData *imageData = UIImagePNGRepresentation(textbookImage);
    [pageDict setObject:imageData forKey:@"image"];
    [pageDict setObject:textbookName forKey:@"name"];
    [pageDict setObject:page forKey:@"page"];
    [pageDict setObject:nameOfClass forKey:@"class"];

And the parsing it like this:
  NSData *imageData = [pageDict objectForKey:@"image"];
   UIImage *pageImage = [UIImage imageWithData:imageData];

But it still returns the same error

A: You can't set UIImage into NSUserDefaults as UIImage is non-property-list object.
You better store path of image from documents directory.
This code will help.
// SET Image
NSString *strImagePath = //path of image from documents directory

NSMutableDictionary *dictOne = [NSMutableDictionary dictionaryWithCapacity:0];

[dictOne setObject:strImagePath forKey:@"image"];

[[NSUserDefaults standardUserDefaults] setObject:dictOne forKey:@"dict"];

// GET image
 NSMutableDictionary *dict = [[NSUserDefaults standardUserDefaults] objectForKey:@"dict"];

    UIImage *image = [UIImage imageWithContentsOfFile:[dict objectForKey@"image"]];

EDIT:
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0];
 NSString *strImageFileName = [documentsDirectory stringByAppendingPathComponent:@"yourImageFileName"];
 UIImage *image = // Your image;

 NSData *dataImage = UIImageJPEGRepresentation(image, 0.5f);
 /* Good image quality
        NSData *dataImage = UIImagePNGRepresentation(image);
 */

[dataImage writeToFile:strImageFileName atomically:YES];

Happy coding.


text:
Q: Extend angular-cli ng build to ignore git repository? Using angular-cli and a custom express server, I deployed a basic Angular2 application to heroku.  Running ng build is great at compiling all the Angular files, as well as the files I've added to the src and public directories.  However, some files I've had to add manually, and they are removed when running ng build.
The biggest problem is the git repository I'm using in the dist folder for deployment.  It is removed/overwritten every time I run ng build.  So instead of pushing changes to heroku, I have to initialize a new repo and push a new application.
Can ng build be extended to ignore or add files in the dist directory?

A: So it looks like I was going about this the wrong way.  Short answer for my case is to use gulp to pipe files from the dist directory into a different directory for deployment and pipe server files too.  If anyone is interested, here is the full work flow:
In Development
All the server files go into the src directory generated by angular-cli.  I use a server directory for models, routes, etc., and an app.js file for an entry point into the application.  These files are going to be added to the dist directory when ng build is run from the command line.  So the app.js file will point to the index.html.  Here's a simple example:
// app.js

var express = require('express');
var app = express();
var router = express.Router();
var port = process.env.PORT || 3000;

router.get('/*', function (req, res) {
    res.sendfile(path.join(__dirname, "index.html"));
});

app.listen(port, function () {
    console.log('Express server started on port ' + port);
});

module.exports = app;

You can run ng build or ng test from the command line, and this will add the server files to the dist directory.  To run the application, use node dist/app from the command line.
In Production
When building for production using ng build -production, the server files in the src directory are not moved in the dist directory.  So I used gulp to create a new directory, add the files from the dist directory and the server files from the src directory.  I'm not great at task runners, so here's the full code:
From the command line: npm install --save-dev gulp del
Add gulpfile.js to the application root directory.
// gulpfile.js

var gulp = require('gulp');
var del = require('del');

// destination for piped files
var deployment = 'heroku';

// remove old files from the deployment directory
gulp.task('clean', function() {
    del([ (deployment + '/**/*'), '!.git']);
});

//  grab the angular files
gulp.task('angularFiles', function() {
    return gulp.src('dist/**/*')
        .pipe(gulp.dest(deployment));
});

// grab the server files and package.json
gulp.task('packageFile', function() {
    return gulp.src('package.json')
        .pipe(gulp.dest(deployment));
});

gulp.task('serverFiles', function() {
    return gulp.src('src/server/**/*')
        .pipe(gulp.dest(deployment + '/server'));
});

gulp.task('appFile', function() {
    return gulp.src('src/app.js')
        .pipe(gulp.dest(deployment));
});

// make a single task for the npm script
gulp.task('buildProd', ['angularFiles','packageFile','serverFiles','appFile']);

In the package.json file, make a new script: "build:heroku": "gulp clean && ng b -prod && gulp buildProd"
This runs the gulp tasks and uses the angular ng b -prod command, which, builds for production.
Run the script in the application root directory in the command line with npm run build:heroku
The first time you run run the script, it will create the deployment directory (called heroku in my case), clean it, add the angular files, then add the server files and package.json.  One thing I do manually, as I'm not a task runner expert, is remove excess scripts from the heroku directory so it looks like this:
// heroku/package.json
"scripts": {
  "start": "node app.js",
}

Otherwise, heroku may try to run some of the other angular npm scripts during deployment.
Then I cd into the heroku directory and use git for deployment. From the command line:
git init // only for first deployment
git add -A
git commit -m 'ready for deployment'
heroku create // only for first deployment
    -or-
heroku git:remote -a <heroku app name> // only for first deployment
git push heroku master

For subsequent deployments, the npm script build:heroku won't delete the git repository.  Just run the script, adjust the package.json, and use git to push to heroku.
Few other things

*

*Remember to add the deployment directory to the main application's .gitignore file.

*I've found dropbox sometimes causes conflicts with ng build -production.  Pausing dropbox syncing fixes the problem.

*angular-cli ng build or ng build -production rewrites the dist folder every time.  So after deployment, you have to rebuild the development environment.  I personally use ng test and leave it running in the terminal.


text:
Q: Unexpected token user = await User.create(user) when i try to create a new user I'm trying to create a new user using node.js/adonis
I create this two functions:
const User = use("App/Models/User")

async store ({ request, auth }){

    let user = new User()
    user = request.all()

    this.userLogged(auth).then(res => {
        user.user_id = res.id
        console.log(user)
        user = await User.create(user)
        const token = await auth.generate(user)
        Object.assign(user, token)
        return user
    })
}

async userLogged(auth) {
    try {
        return await auth.getUser()
    } catch (error) {
        console.log(error)
    }
}

The function "userLogged()" return the user that i receive the token in the authorization header.
So i try:
create a new instance of User;
put the request data in this instance;
take the user_id of the authorization header and put in the user.user_id;
create the user with the user_id;
take the token of the registred user;
put in the object user the token;
return the user;

but i'm receiving:

Unexpected token user = await User.create(user)

A: You are attempting to await something not in an async function, specifically the callback in your promise resolver .then.

async store ({ request, auth }){

    let user = new User()
    user = request.all()

    this.userLogged(auth).then(async res => {
        user.user_id = res.id
        console.log(user)
        user = await User.create(user)
        const token = await auth.generate(user)
        Object.assign(user, token)
        return user
    })
}

Also, based on the code provided, store does not need to be async since you're not awaiting anything at the top level of its scope.


text:
Q: I have two lists. I would like to make a third from the elements given in one of the lists Sorry for the confusing title!
I have two lists, say:
a = [30,55,76,43,27,28]
b = [0,2,3,5]

I want to make a list c that is both elements of a, i.e.
c = [30,76,43,28]  # -> the 0th, 2nd, 3rd, 5th elements of a

Should I use the zip() function?  Or can you use a simple for loop?
Thanks.

A: You could achieve this through enumerate function.
>>> a = [30,55,76,43,27,28]
>>> b = [0,2,3,5]
>>> l = []
>>> for i,j in enumerate(a):
        for m in b:
            if i == m:
                l.append(j)

>>> l
[30, 76, 43, 28]

Through list_comprehension.
>>> a = [30,55,76,43,27,28]
>>> b = [0,2,3,5]
>>> [j for i,j in enumerate(a) for m in b if i == m ]
[30, 76, 43, 28]


text:
Q: How do I show that $1$ is not an eigenvalue for $A$, by showing that there are no eigenvectors for $\lambda = 1$. Consider the matrix $$A=\begin{pmatrix}-1 &  3&  3& 3\\ 3&  1&  -1& 5\\ 3&  -1&  7& -1\\ 3&5&  -1&1\end{pmatrix}.$$
How do I show that $1$ is not an eigenvalue for $A$, by showing that there are no eigenvectors for $\lambda = 1$?
This what I've done so far:
$$\left ( A - \lambda I \right )\vec{x} = \vec{0},$$
$$A-I =\begin{pmatrix}-2 &  3&  3& 3\\ 3&  0&  -1& 5\\ 3&  -1&  6& -1\\ 3&5&  -1&0\end{pmatrix}.$$
I have do the Gaussian elimination to find the solution.
This is what my augmented matrix looks like in row-reduction form:
$$\begin{pmatrix}-1 &  3&  2& 8\\ 3&  0&  -1& 5\\ 0&  -7&  -5& -0\\ 0&1&  0&-1\end{pmatrix}.$$
What do I do from here?

A: Showing that $1$ is not an eigenvalue of $A$ is the same as showing that the matrix $A - I$ is invertible.
You can do this by checking that its determinant is nonzero.
Alternatively, you can perform row reduction starting with $A - I$. Once you arrive at an upper triangular matrix with no zeros on the diagonal, you can be certain that $A - I$ is not invertible.
The matrix you wrote is not nearly in row-echelon form, because of the nonzero entries in the $(2,1)$-, $(3,2)$- and $(4,2)$-positions.

A: A nice trick to show that $\lambda=1$ is not an eigenvalue of $A$ is to consider that over $\mathbb{F}_2$:
$$\det(A-I) =\det\begin{pmatrix}0 &  1&  1& 1\\ 1&  0&  1& 1\\ 1&  1&  0& 1\\ 1&1&  1&0\end{pmatrix}=1,$$
hence the determinant of $A-I$ is odd, so it is for sure different from zero.
As a curiosity, this is related with the fact the the number of derangements (permutations without fixed points) in $S_{2n}$ is always odd.


text:
Q: Child layout(GridView) is repeating count of images times in ExpandableListView I am facing a problem while implementing an ExpandableListView with a Grid View as a child.
Implementation is done successfully, issue arises with the count of images.
For ex: if there are 4 images in GridView, it show a grid view with more than 4 images, with a slot of 46 images. Means one slot of 4 images shown then another 4 images again shown beneath that then another and then another. Means many times the same layout is repeating in one layout. I am unable to find the source of the problem therefore I failed to resolve that.
Please suggest me any solution regarding the same.
I am not getting any error, only the images get repeated, according to the count of images.

I am getting like this, but i want images to be show only one time..irrespective of image count.

A: I found the solution..i was passing wrong count in getChildrenCountMethod
public int getChildrenCount(int groupPosition) {

        return 1;
    }

Here, i have to pass the number of children for that particular header.And my need is one child per header.


text:
Q: How can I view my Instagram backup data in a friendly way? recently i have downloaded a backup of my Instagram account ...
and the zip file contained a lot of ".json" files and i have no idea how to view
it like... the way that Instagram did

thanks

A: I have no idea how to view it like... the way that Instagram did
Probably the best you can do is convert the JSON files into CSV files and use a spreadsheet to view them. See below for more information.

When you unzip Instagram's data archive, you'll see a folder that's
  full of a bunch of ugly JSON files. You can open these up in a text
  editor to try and parse the raw information yourself, or you can copy
  and paste the contents of any JSON file into a site like this
  one, which converts the data into a CSV that's slightly easier to
  read. (That's all done within your browser, not server-side, so you
  aren't shipping your data off to some unknown entity.)
The JSON files cover a lot of data:

*

*Comments you've made to friends' pictures (or replies to comments they've made on yours)

*When you started following other Instagram users and when other Instagram users started following you

*Who you blocked on Instagram (and when)

*When you liked content from different users (not a list of the specific content you liked)

*When you posted content to Instagram (and what your witty caption was)

*All of the messages you've sent to other users using Instagram's mobile apps

*Your profile information

*Searches you've made

  Within the archive's folders, you can also view much of the content
  you've uploaded to Instagram's service, including:

*

*What images you've sent others via direct messages

*All of the Instagram photos you've uploaded

*Instagram stories you've archived

*Videos you've published to Instagram

Source What's in Your Instagram Data Dump and How to Get It

A: Have a Look At This , I Created For the same purpose
https://github.com/mainigautam/instagram_backup_manager


text:
Q: FluorineFx: Client_onConnect does not exist in current context namespace TinyChat
{
    class Program
    {
        NetConnection Client;

        static void Main(string[] args)
        {
            Program TinyChat_Function = new Program();
            TinyChat_Function.connectTinyChat();
        }
        void connectTinyChat()
        {
            Client = new NetConnection();
            Client.OnConnect += new ConnectHandler(Client_OnConnect);
            Client.NetStatus += new NetStatusHandler(Client_NetStatus);

            Client.Connect("rtmp://209.212.144.77:443/tinyconf", new string[] { "SomeRoom", "none", "show", "tinychat" });
        }
    }

Errors:
1 The name 'Client_OnConnect' does not exist in the current context
2 The name 'Client_netStatus' does not exist in the current context

Using latest version of FluorineFx.
The documentation shows that this is the right way to do this, but this does not work. Any ideas on how i can solve this problem?
The documentation can be found here.

A: Where is the code for the Client_OnConnectevent handler and the Client_NetStatusevent handlers? You are adding the events here in your lines , but you didn't implement the code. Unless you forgot to paste it in the question.
Client.OnConnect += new ConnectHandler(Client_OnConnect);
Client.NetStatus += new NetStatusHandler(Client_NetStatus);

You   if you look at the documentation link this is the code
void netConnection_OnConnect(object sender, EventArgs e)
{
    //The NetConnection object is connected now
    netConnection.Call("serverHelloMsg", new ServerHelloMsgHandler(), "some text");
}

You should replace netConnection_OnConnect to Client_OnConnect and write the code in the method, maybe like this
void Client_OnConnect(object sender, EventArgs e)
{

 //handle connection below and do whatever needs to be done

}


text:
Q: What is the AttributeType property used for in the CodeDOM class CodeAttributeDeclaration? I'm doing code generation, creating a custom attribute to decorate a class using CodeDOM, targetting C# and VB.
To do this, I'm creating an instance of the CodeAttributeDeclaration class.
I'm currently setting the AttributeType property, as well as the Name, but it does not seem to be used. Instead, the Name property is all that is used to produce the attribute declaration.
Am I missing something? What is this property used for?

A: It's an alternative (I believe, haven't done CodeDOM for a while) - you can define the attribute declaration using either a name or a type. If both are set, it will (apparently) use the name. Looking at the overloads for the constructor of this type gives some clues to this.
Looking in reflector, it turns out that setting the Name always forces the AttributeType to be a CodeTypeReference to the same name, and the constructors that take the TypeReference always set the name also - so it's not even that one can be set instead of the other.