text:
Q: Hibernate One-To-One DAO I've got two entity classes:

*

*User: user's credentials.

*UserInfo: user's anagraphic infos.

and one DAO:

*

*UserDAO: Dao for class User.

They are linked with a OneToOne relation by primary-key as foreign-key. So User.id is the primary-key both for User and UserInfo.
The data fetching runs well BUT the problem is: when I save a User with userDAO, the UserInfo doen't know the primary-key it must be saved with.
How can I tell UserInfo to wait User to be saved to know its shared primary-key?
I got this Exception
    Request processing failed; nested exception is org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.marciani.sample.entity.user.model.UserInfo.user]

Thank you in advance!
This is the code:
User
    @Entity
    @Table(name = "users")
    public class User implements Serializable {

        private static final long serialVersionUID = -7351729135012380019L;

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "user_id", nullable = false, unique = true)
        private Integer id;

        @Column(name = "username", nullable = false, unique = true, length = 25)
        private String username;

        @Column(name = "password", nullable = false, unique = false, length = 25)
        private String password;

        @ManyToOne(fetch = FetchType.EAGER)
        @JoinColumn(name = "role_id", nullable = false)
        @ForeignKey(name = "fk_user_role")
        private Role role;

        @OneToOne(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
        private UserInfo userInfo;

        public User(String username, String password, Role role, UserInfo userInfo) {
            this.username = username;
            this.password = password;
            this.role = role;
            this.userInfo = userInfo;
        }

        public User() {}

            //Getters/Setters ...
    }

UserInfo
    @Entity
    @Table(name = "users_info")
    public class UserInfo implements Serializable {

        private static final long serialVersionUID = 3977944889257599040L;

        @Id
        @GeneratedValue(generator="gen")
        @GenericGenerator(name="gen", strategy="foreign", parameters={@Parameter(name="property", value="user")})
        private Integer userId;

        @Column(name = "firstname", nullable = false, unique = false, length = 25)
        private String firstname;

        @Column(name = "lastname", nullable = false, unique = false, length = 25)
        private String lastname;

        @Column(name = "email", nullable = false, unique = false, length = 50)
        private String email;

        @OneToOne
        @MapsId
        private User user;

        public UserInfo(String firstname, String lastname, String email) {
            this.firstname = firstname;
            this.lastname = lastname;
            this.email = email;
        }

        public UserInfo() {}

            //Getters/Setters

    }

UserService
    @Service("userService")
    public class UserServiceImpl implements UserService {

        @Autowired
        private UserDAO userDAO;

        @Override
        @Transactional(readOnly = false)
        public void saveUser(User user) {
            userDAO.saveUser(user);
        }

        @Override
        @Transactional(readOnly = false)
        public void deleteUser(String username) {
            User user = findByUsername(username);
            userDAO.deleteUser(user);
        }

        @Override
        @Transactional(readOnly = true)
        public User findByUsername(String username) {
            Criterion criterion = Restrictions.eq("username", username);
            List<User> list = userDAO.find(criterion);
            return list.get(0);
        }

        @Override
        @Transactional(readOnly = true)
        public User getUser(String username, String password) {
            Criterion criterion = Restrictions.conjunction()
            .add(Restrictions.eq("username", username))
            .add(Restrictions.eq("password", password));
            List<User> list = userDAO.find(criterion);
            if (list.size() > 0) {
                return list.get(0);
            } else {
                return null;
            }
        }

        @Override
        @Transactional(readOnly = true)
        public List<User> findAll() {
            return userDAO.findAll();
        }

    }

UserDAO
    @Repository
    public class UserDAOImpl implements UserDAO {

        @Autowired
        public SessionFactory sessionFactory;

        public Session getCurrentSession() {
            return sessionFactory.getCurrentSession();
        }

        @Override
        public void saveUser(User user) {
            getCurrentSession().saveOrUpdate(user);;
        }

        @Override
        public void deleteUser(User user) {
            getCurrentSession().delete(user);
        }

        @Override
        public List<User> find(Criterion criterion) {
            Criteria criteria = getCurrentSession().createCriteria(User.class);
            criteria.add(criterion);
            return criteria.list();
        }

        @Override
        public List<User> findAll() {
            Criteria criteria = getCurrentSession().createCriteria(User.class);
            return criteria.list();
        }

    }

A: where did you initiate this user id (
private Integer id;)
also you didn't mention @column for
userId of UserInfo class


text:
Q: Pixel gap bottom of a div A simple question and probably a simple solution, but I can't seem to find it.
As you can see in the example there is a pixel gap between the bottom of the 2 images and the DIV (home-top or home-bottom).
How do I get rid of that?

.container{
    width:80%;
}

.menu{
    width:100%;
    background:black;
    color:white;
    text-align:center;
}

.home-top{
    background:white;
    overflow:hidden;
}

.home-bottom{
    background:#EEE;
    overflow:hidden;
}

.footer{
    width:100%;
    background:black;
    color:white;
}

.txt-left, .img-left{
    width:50%;
    float:left;
}

.txt-right, .img-right{
    width:50%;
    float:left;
}

    menu

home top

            some text goes here.

home bottom

            some text goes here.

    footer

A: Set "display:block;" on the images.
img{
    display:block;
}

https://jsfiddle.net/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changing boxplot Fonts in R I am trying to change boxplot font to "Times New Roman" through this command in R:
library(extrafont)
loadfonts(device="win")
fonts()
boxplot(sp ~ grp, data = mydata,family="Times New Roman")

But the fonts in the plot does not change. How to I change all the text in boxplot graph?
Thanks in advance
You can see the results here

A: The font family cannot be changed by setting family in boxplot(). Instead, use par(family = "Times New Roman") to modify this graphical parameter before calling boxplot().
A reproducible example follows:
boxplot(count ~ spray, data = InsectSprays)
boxplot(count ~ spray, data = InsectSprays, family = "serif")
# -> 'family' has no effect here

par(family = "serif")
boxplot(count ~ spray, data = InsectSprays)
# -> font has changed

A: Try this:
windowsFonts(
  A=windowsFont("Arial Black"),
  B=windowsFont("Bookman Old Style"),
  C=windowsFont("Comic Sans MS"),
  D=windowsFont("Times New Roman")
)
par(mfrow=c(2,2))
for (f in LETTERS[1:4]) {
  par(family=f)
  boxplot(Sepal.Length ~ Species, data = iris, main = "Title", font=2)
}


text:
Q: Difference between Object and object
Possible Duplicate:
c#: difference between "System.Object" and "object"

Hello,
In C# there are Object and object types. They seem to have the same functionnality, so what is the difference between the two ?

A: I don't believe they are different, its like the difference between System.Int32 and int... they are the same essentially.

A: There is none. C# provides synonyms for the primitives defined by the CLR. System.String -> string, System.Int64 -> long, System.Object -> object, etc.

A: None.

The object type is an alias for System.Object in the .NET Framework. You can assign values of any type to variables of type object.

http://msdn.microsoft.com/en-us/library/9kkx3h3c%28VS.71%29.aspx

A: No difference.
object is a synomym of System.Object
It is there to allow old users to not get totally confused when they moved from an older system to this.


text:
Q: Android button margins when background color added I have problem with button margins (Android Studio) when I change background colors of buttons. All buttons are the same size but those added background color has no space between them. How can I fix this?

This code is for buttons for uncolored buttons
<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btnAdd"
        android:id="@+id/btnAdd"
        android:layout_above="@+id/btnSub"
        android:layout_centerHorizontal="true"/>

And I added this line for get background color on colored buttons.
android:background="@color/red"

If I delete all background attributes from middle buttons then all buttons looks same same and in sync.

These are the same buttons without this line of code:
android:background="@color/red"

What should I do to get exactly same button sizes with same margins with background color? No java code involved. Just xml codes above.


text:
Q: Check that you can see a text with a class in functional testing / Laravel I need to check that my text exists in my page with PHPUnit / Laravel.
  <del class="text-muted">Configure</del>

Right now, I know only how to check that Configure exists with
 $this->visit('/')
        ->see('configure')

Is it posible to check that there is a Configure text with a text-muted class in Laravel 5.2 Built in Tests???

A: Solution is:
 $this->visit('/')
      ->seeInElement("del.text-muted", 'Configure'));

But I didn't find it in official doc :(


text:
Q: How to implement Image Gallery in Gridview in android? I have a requirement in that I want to implement an image gallery with a GridView.
I tried using Hello gallery on the Android developer website. But the GridView doesn't work.

A: See this hello-gridview. For more reference see this also

*

*gallery-into-grid-style-menu

*image-gallery-with-checkbox-in-grid-to-select-multiple/

*add-capture-button-and-update-gallery/
I think the above links are very useful to you. And keep in mind before posting question you first check out android developer. This will provide all most all information about Android. If you're still getting any problem then let me know

A: This tutorial Hello Grid View provide a good basic example on creating Image Gallery with gridview, but the image are from drawable resource, you need to expand it as your requirement need.

A: Use this XML for Layout : gallery.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="@drawable/bg_child">

    <FrameLayout android:id="@+id/FrameLayout01"
        android:layout_width="fill_parent" android:layout_height="fill_parent">
        <FrameLayout android:id="@+id/LinearLayout01"
            android:layout_gravity="top" android:layout_height="50dp" android:layout_width="fill_parent">
            <TextView android:id="@+id/TextView01"
                android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:layout_gravity="center_vertical" android:layout_marginLeft="30dp" android:gravity="center_vertical" android:drawableLeft="@drawable/photo_frame" android:textColor="@color/grey" android:text="@string/photogallery_txt"></TextView>
            <Button android:layout_gravity="right" android:id="@+id/btnMoreInfo" android:layout_marginRight="5dp" android:layout_marginTop="5dp" android:textStyle="bold" android:background="@drawable/my_child_button" android:layout_width="100dp" android:layout_height="40dp" android:text="@string/moreinfo_txt"></Button>
        </FrameLayout>
        <GridView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/gridview" android:layout_width="fill_parent"
            android:layout_height="fill_parent" android:columnWidth="90dp"
            android:numColumns="auto_fit" android:verticalSpacing="10dp"
            android:horizontalSpacing="10dp" android:stretchMode="columnWidth"
            android:gravity="center" android:layout_gravity="bottom"
            android:layout_marginTop="50dp"></GridView>
    </FrameLayout>
</LinearLayout>

Activity File GalleryPage.java
public class GalleryPage extends Activity {

    // private Integer[] mImageIds = {R.drawable.splash, R.drawable.splash,
    // R.drawable.splash, R.drawable.splash, R.drawable.splash,
    // R.drawable.splash, R.drawable.splash};

    private static Uri[] mUrls = null;
    private static String[] strUrls = null;
    private String[] mNames = null;
    private GridView gridview = null;
    private Cursor cc = null;
    private Button btnMoreInfo = null;
    private ProgressDialog myProgressDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        CommonFunctions.setLanguage(getBaseContext());

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.gallery);
        btnMoreInfo = (Button) findViewById(R.id.btnMoreInfo);
        // It have to be matched with the directory in SDCard
        cc = this.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null,
                null);

        // File[] files=f.listFiles();
        if (cc != null) {

            myProgressDialog = new ProgressDialog(GalleryPage.this);
            myProgressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            myProgressDialog.setMessage(getResources().getString(R.string.pls_wait_txt));
            //myProgressDialog.setIcon(R.drawable.blind);
            myProgressDialog.show();

            new Thread() {
                public void run() {
                    try {
                        cc.moveToFirst();
                        mUrls = new Uri[cc.getCount()];
                        strUrls = new String[cc.getCount()];
                        mNames = new String[cc.getCount()];
                        for (int i = 0; i < cc.getCount(); i++) {
                            cc.moveToPosition(i);
                            mUrls[i] = Uri.parse(cc.getString(1));
                            strUrls[i] = cc.getString(1);
                            mNames[i] = cc.getString(3);
                            //Log.e("mNames[i]",mNames[i]+":"+cc.getColumnCount()+ " : " +cc.getString(3));
                        }

                    } catch (Exception e) {
                    }
                    myProgressDialog.dismiss();
                }
            }.start();
         gridview = (GridView) findViewById(R.id.gridview);
         gridview.setAdapter(new ImageAdapter(this));

         gridview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                  int position, long id) {
               Intent i = new Intent(GalleryPage.this, BigImage.class);
               Log.e("intent : ", ""+position);
               i.putExtra("imgUrls", strUrls);
               i.putExtra("position", position);
               startActivity(i);
            }
         });

        }

        btnMoreInfo.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(GalleryPage.this, ChildLogin.class);
                startActivity(i);
            }
        });
    }

    /**
     * This class loads the image gallery in grid view.
     *
     */
    public class ImageAdapter extends BaseAdapter {
        private Context mContext;

        public ImageAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            return cc.getCount();
        }

        public Object getItem(int position) {
            return null;
        }

        public long getItemId(int position) {
            return 0;
        }

        // create a new ImageView for each item referenced by the Adapter
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.galchild, null);

            try {

                ImageView imageView = (ImageView) v.findViewById(R.id.ImageView01);
                //imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                // imageView.setPadding(8, 8, 8, 8);
                Bitmap bmp = decodeURI(mUrls[position].getPath());
                //BitmapFactory.decodeFile(mUrls[position].getPath());
                imageView.setImageBitmap(bmp);
                //bmp.
                TextView txtName = (TextView) v.findViewById(R.id.TextView01);
                txtName.setText(mNames[position]);
            } catch (Exception e) {

            }
            return v;
        }
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        FlurryAgent.onStartSession(this, "***");
    }
    // @Override
    // protected void onStop() {
    // TODO Auto-generated method stub
    // super.onStop();
    // FlurryAgent.onEndSession(this);

    // }

    /**
     * This method is to scale down the image
     */
    public Bitmap decodeURI(String filePath){

        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Only scale if we need to
        // (16384 buffer for img processing)
        Boolean scaleByHeight = Math.abs(options.outHeight - 100) >= Math.abs(options.outWidth - 100);
        if(options.outHeight * options.outWidth * 2 >= 16384){
            // Load, scaling to smallest power of 2 that'll get it <= desired dimensions
            double sampleSize = scaleByHeight
                ? options.outHeight / 100
                : options.outWidth / 100;
            options.inSampleSize =
                (int)Math.pow(2d, Math.floor(
                Math.log(sampleSize)/Math.log(2d)));
        }

        // Do the actual decoding
        options.inJustDecodeBounds = false;
        options.inTempStorage = new byte[512];
        Bitmap output = BitmapFactory.decodeFile(filePath, options);

        return output;
    }
}

A: Looks like you want custom gallery, it will take much time for you,
I suggest you get Custom Camera Gallery library for your working.
You will get Photos/Videos in Grid View as you want.

A: private static final int SELECT_PHOTO = 100;
ImageView image;

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

    image = (ImageView) findViewById(R.id.imageView2);
}

public void pickAImage(View view) {
    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    switch (requestCode) {
        case SELECT_PHOTO:
            if (resultCode == RESULT_OK) {
                Uri selectedImage = imageReturnedIntent.getData();
                InputStream imageStream = null;

                try {
                    imageStream = getContentResolver().openInputStream(selectedImage);
                }
                catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
                image.setImageURI(selectedImage);// To display selected image in image view
            }
        }
    }
}


text:
Q: How to use systemd-nspawn with pptp? I would like to set a container use the vpn for only network interface.
I have used the pptpsetup and pon make a pptp connection works, and got a ppp0 interface.
Now, I want all internet connection in the systemd-nspawn container go through the ppp0 .
How can I make it work?

A: systemd-nspawn --network-interface=ppp0

ppp0 will disappear from the host namespace.  You can't share one IP address with a container and not your other IP addresses.  (Apart from doing NAT).
It looks like this might require a very recent kernel though.  http://www.spinics.net/lists/netdev/msg339236.html
OR (machine is created after ppp0):
systemd-nspawn --private-network

ip link set dev ppp0 netns $PID

where $PID is the pid in the host namespace of a process in container, obtained using
P=$(machinectl $MACHINE_NAME show --property=Leader)
PID=${P#Leader=}

and $MACHINE_NAME is the value passed to the -M option of systemd-nspawn


text:
Q: Configuring Syslog to accept remote log submissions By default syslog daemons don't accept remote log submissions. I need mine to, but don't really have a clue how to configure that. Can anyone help me out, send me a good tutorial, etc. I have been googling for awhile, but can seem to find what I'm looking for. Any help would be appreciated

A: Read the man-page for your operating system (man syslogd). On FreeBSD, you need to pass -a and the addresses of white-listed senders to the syslogd invocation.

A: man syslogd
     -r     This option will enable the facility to receive message from the
              network using an internet domain socket with the syslog  service
              (see  services(5)).   The default is to not receive any messages
              from the network.
on centos, should be like this
$  cat /etc/sysconfig/syslog |grep OPT
SYSLOGD_OPTIONS="-m 0 -r"


text:
Q: How to initialize stuff that depends on the view's attributes Say I have this class MyView:
public class MyView extends GLSurfaceView {
    private MyRenderer mRenderer;

    public MyView(Context ctx, AttributeSet attrs) {
        super(ctx, attrs);
        init(ctx);
    }

    private void init(Context ctx) {
        mRenderer = new MyRenderer(ctx);
        setRenderer(mRenderer);
    }

    @Override
    public void setBackground(Drawable background) {
        mRenderer.setBackground(background);
    }
}

That is inflated by MyActivity like this:
public class MyActivity extends Activity {
    private MyView mView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    protected void init() {
        setContentView(R.layout.my_layout);
        mView = (MyView) findViewById(R.id.my_view);
    }
}

To my knowledge setBackground is called by the inflater in setContentView, before init is called in MyView, so mRenderer has not been initialized yet.
It seems like a catch 22, because the view's attributes can't be set without the view's initialization, which happens after the attributes are set.
This is the layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/my_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/background" >

    <com.developer.app.MyView
        android:id="@+id/my_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/background"
        />

    <TextView
        android:id="@+id/left_arrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:background="@drawable/left_arrow"
        />

    <TextView
        android:id="@+id/right_arrow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:background="@drawable/right_arrow"
        />

    <TextView
        android:id="@+id/home_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/home"
        />
</RelativeLayout>

A: What i understood from your question. You need attributes of views in oncreate(). But unable to do so. the reason is at that point UI is not initialized yet. there is work around.
this link might help.
getWidth() and getHeight() of View returns 0

A: You are right. setBackground() is called from View's constructor if android:background attribute was parsed. In your case it called here:
super(ctx, attrs);

If you want to set background to mRenderer, you can do it in init:
private void init(Context ctx) {
    mRenderer = new MyRenderer(ctx);
    setRenderer(mRenderer);
    final Drawable background = getBackground();
    if (background != null) {
        mRenderer.setBackground(background);
    }
}

and add a null-check in setBackground, because this method can be called from superclass' constructor before you set some value to mRenderer
@Override
public void setBackground(Drawable background) {
    if (mRenderer != null) {
        mRenderer.setBackground(background);
    }
}

A: You have initialize its three functions for example and xml and java is as you are doing it.
public class MyEditText extends EditText {
    public MyEditText(Context context) {
        super(context);
        this.setTextColor(Color.parseColor("#4789da"));
        this.setBackgroundResource(R.drawable.edittext_back);
        this.setTextSize(18);
        this.setPadding(5,5,5,5);
    }

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setTextColor(Color.parseColor("#4789da"));
        this.setBackgroundResource(R.drawable.edittext_back);
        this.setTextSize(18);
        this.setPadding(5,5,5,5);
    }

    public MyEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.setTextColor(Color.parseColor("#4789da"));
        this.setBackgroundResource(R.drawable.edittext_back);
        this.setTextSize(18);
        this.setPadding(5,5,5,5);
    }
}


text:
Q: Rails: How to Test an Array's Order with RSpec I'm new to RSpec so I'm looking for a little help on a simple test:
# controller method
def show
  @group = Group.find(params[:id])
  @group_members = @group.group_members.order("posts ASC")
end

# in my rspec
it "should show order correctly" do
  @group = FactoryGirl.create(:group)
  @user_1 = FactoryGirl.create(:user, user_name: "Gary")
  @user_2 = FactoryGirl.create(:user, user_name: "Shawn")
  @user_3 = FactoryGirl.create(:user, user_name: "Gus")
  @user_4 = FactoryGirl.create(:user, user_name: "Jack")
  @group_member_1 = FactoryGirl.create(:group_member, group_id: @group.id, user_id: @user_1.id, posts: 30)
  @group_member_2 = FactoryGirl.create(:group_member, group_id: @group.id, user_id: @user_2.id, posts: 20)
  @group_member_3 = FactoryGirl.create(:group_member, group_id: @group.id, user_id: @user_3.id, posts: 10)
  @group_member_4 = FactoryGirl.create(:group_member, group_id: @group.id, user_id: @user_4.id, posts: 15)
  visit group_path(@group)

  # how do i assert the order of the array?
end

Can someone please help me with a statement to check that the array sorted correctly?

A: my_array.should eq expected_array

That will make sure that each item is in the exact same spot. If you want to check that an array has the same elements as another array, but the order doesn't matter, do this:
my_array.should =~ expected_array

So in your particular case, you first would need to do a get to the show action, then check the variable. That's done like this:
get :show, :id => @group.id
expected_group_members = [@group_member_3, @group_member_4, @group_member_2, @group_member_1]
assigns(:group_members).should eq expected_group_members

For more information, check out RSpec's GitHub page.


text:
Q: Regex match using awk for a line starting with a non conforming string I have a huge file, I want to only copy from it lines starting with
,H|756|F:BRN\

but when I do
awk  '$1 ~ /^ ,H|756|F:BRN\/' file_1.txt > file_2.txt

I get:

awk: line 1: runaway regular expression /^ ,H|756|F ...

A: The meta-characters in the regex match needs to be properly escaped to achieve what you are trying to do. In Extended Regular Expressions (ERE) supported by awk by default | has a special meaning to do alternate match, so you need to escape it to deprive it of its special meaning and treat it literally and the same applies for \
awk '/^,H\|756\|F:BRN\\/' file

Also you don't need to use the explicit ~ match on $1. For a simpler case like this, a string pattern starting with, the /regex/ approach is easier to do.

A: If the file is "huge", you can consider grep or ack or ag, which may bring you better performance.
grep '^,H|756|F:BRN\\' input > output

grep uses BRE as default, so you don't have to escape the pipe |. But the ending back-slash you should escape.


text:
Q: mysql select statement by group with minimum number of recordsets I'm not sure if this will work with a single mysql statement, but this is what I'm trying to achieve:
We are storing user's answers for a variable number of online quizes in tbl_results. Each online quiz has a variable number of questions. Each question has a variable number of answers, of which only one is correct.
Here is our tbl_results with some sample entries
id | quiz_id | user_id | question_id | answer_id | correct
1    2         3         1             1           0
2    2         3         2             2           1
3    2         3         3             3           1

4    2         4         1             1           1
5    2         4         2             2           1
6    2         4         3             3           1

7    2         5         1             1           1
8    2         5         2             2           1
9    2         5         3             3           1

10   2         6         1             1           1
11   2         6         2             2           1

$number_of_questions tells us how many questions have to be answered correctly in order to win the quiz currently in question.
How do we find out how many users have won quiz number 2 when $number_of_questions = 3 ? In this case, it would be user_ids 4 & 5.
This is what we've got so far:
SELECT * FROM tbl_results WHERE quiz_id = 2 AND CORRECT = 1 GROUP BY user_id

How would we adapt this to take account of $number_of_questions ...?
Many thanks in advance for any help!

A: You can use a HAVING clause:-
SELECT quiz_id, user_id, correct, COUNT(*) AS correct_answers
FROM tbl_results
WHERE quiz_id = 2
AND CORRECT = 1
GROUP BY quiz_id, user_id, correct
HAVING correct_answers = 3

Note that your GROUP BY in the original query is a bit dubious, and which rows values are brought back for the columns not in the GROUP BY clause are undefined.


text:
Q: Matching Password against local filename I know this is bad practice.  It's temporary until I get these passwords into an AD environment.  The point is, I am trying to get the password matching to work and it appears that I'm missing something.
Basically, I have a .secrets file that holds the passwords in the following format:

user1:pass1
user2:pass2
etc, etc

Here is the entire PHP file:
<?php

//If Submit Button Is Clicked Do the Following
if ($_POST['submit']){
  $username = $_POST['username'];
  $secret_word = $_POST['secret_word'];
  $password = $_POST['password'];

  $fh = fopen('.secrets','r');
  $result = explode(":",$fh);
  for($i=0; $i< count($result); $i++){
    if($result[$i] === $username && $result[$i+1] === $secret_word) {
      echo "Matched";
      break;
    } else {
        echo "Secret Word Incorrect - Please try again";
        break;
    }
  }
  fclose($fh);
}

echo "
";
print_r($_POST);
echo "
";

?>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">

User:

<input name="username" required="required" type="text" id="username" />

Password:

<input name="password" required="required" type="password" id="password" />

Confirm Password:

<input name="password_confirm" required="required" type="password" id="password_confirm" oninput="check(this)" />

Secret Word:

<input name="secret_word" type="password" required="required" id="secret_word" />

<input type="submit" name="submit" />

</form>

The only part not working is the matching and the fact that it doesn't say "Matched" or "Does not match".  I feel like I'm so close to getting this, but I've been trying to get this working for the past 30 minutes.  By the way, I'm trying to match the username and the "secret_word", not the password field, by the way.
Output of print_r:
Array
(
    [username] => user1
    [password] => asdf
    [password_confirm] => asdf
    [secret_word] => pass1
    [submit] => Submit
)

A: It appears you opened the file for reading but did not actually proceed to read the file.
I've chosen to use PHP's file_get_contents() instead to make things less verbose.
The next thing I did was to split the lines (\n) first, before splitting on :. If we just sent ahead to split on :, you would have trailing newlines on some of your data - which you could also trim() away. I've just chosen this method because it's clearer.
The updated code looks like this:
if ($_POST['submit']){
  $username = $_POST['username'];
  $secret_word = $_POST['secret_word'];
  $password = $_POST['password'];

  $file = file_get_contents('.secrets');
  $lines = explode("\n", $file);

  $matched = false;

  for ($i = 0; $i < count($lines); $i++) {
    list($stored_user, $stored_pass) = explode(":", $lines[$i]);

    if ($stored_user === $username && $stored_pass === $secret_word) {
      $matched = true;
      break;
    }
  }

  if ($matched) {
    echo "Matched!";
  } else {
    echo "Secret Word Incorrect - Please try again";
  }
}


text:
Q: Convert image to png and then again to original type - Laravel, PHP I am using image intervention in laravel to upload and convert image(jpg, bmp, gif) to PNG type, after upload png image can be sent to another user. User who receives image will then convert that PNG image to original uploaded type back.
For example I am uploading JPG image which have size of 1.5MB, after upload and conversion to PNG it have size of 5MB. When user who received that png image converts it back to original JPG type, after conversion JPG image have size of 850KB (instead of 1.5MB). Problem is that when image is converted back to her original type, sizes are not the same. Is there a way to convert image and to get same size before conversion to png?
1.5MB(JPG) -> PNG -> 850KB??(JPG)
conversion to png:
    $png_image = (string) Img::make($image)->encode('png');
conversion back to original type:
    $originalImage = (string) Img::make($png_image_path)->encode($extension, 100);


text:
Q: Asking facebook for data of multiple users in single request using FB.api I need to get basic user data from Facebook using FB.api('/<some_id>/'). This works well, but is slow, since I need to ask for every id separately and make several calls to facebook. Is there any way to gather all ids and ask for them in single request and get an array?
EDIT
I am not asking for user friends. I am actually trying to gather friends' friends of a user and that's something Facebook doesn't provide, that's why I am using graph.facebook.com/<id>/ rather than graph.facebook.com/me/friends. I don't want friends, I'd like to do something like this: graph.facebook.com/<id1>,<id2>,<id3>,../

A: You can use an fql query to get info on all friends:
SELECT uid, name, pic_small FROM user
WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())

If you prompt the user for more extended permissions you would be able to get access to more fields from the user table.
If you are trying to query a list of arbritary user ids that aren't the users friends, you could try specifiying that list in the FQL query for use Facebooks FQL Multiquery capability, doing multiple select uid, name from user where uid = friendid1 statements.

A: How about using FQL:
From the Facebook examples:
var friends = FB.Data.query(
     "(select uid2 from friend where uid1 = {0})",
     user_id);

var friendsoffriends = FB.Data.query(
     "select uid2 from friend where uid1 in (select uid2 from {0})",
     friends;

 // Now, register a callback
 FB.Data.waitOn([friends, friendsoffriends], function() {
   // now display all the results
   FB.Array.forEach(friendsoffriends.value, function(row) {
       console.log(row.uid);
   });
 });

Then edit for whatever collection of ids you wish to use.
The above approach remains valid (as a reasonable generic example) - however, to clarify:
You would previously have used users.getInfo to do what you are asking, as this allows you to pass a list of UIDS. Unfortunately this is being deprecated. However, all this query actually does is wrap an FQL query.
If you then apply the standard FQL 'in' syntax you can achieve this:
{
myfriends:'select uid2 from friend where uid1=me()',
friendsoffriends:'select uid2 from friend where uid1 in (select uid2 from #myfriends)'
}

However facebook actively prevents you from doing this with the error:
"error_code": 604,
  "error_msg": "Can't lookup all friends of 123456789. Can only lookup for the logged in user (987654321), or friends of the logged in user with the appropriate permission",

Your other option is to get all of the ids and do an FQL query of the form:
select name from user where uid='123456789' OR uid='987654321' OR uid=...

A: FQL is no longer supported but this method does the trick in the new api:
Requesting multiple Facebook fanpage data in a single call
In short use ids param:
FB.api(
    '/',
    {ids : "19292868552,11239244970"},
    function(response) {
        if (!response || response.error) {
            console.log(response.error);
        } else {
            console.log(response);
        }
    }
);


text:
Q: Would Hund's rules still be valid if the electron had spin 3/2? One of my homework assignments in atomic physics was the following:

Given electrons had a Spin of $S = 3/2$, what would be the number of the first 4 noble gasses (complete shells)?

The obvious expected answer is 4, 20, 56 and 120, because now one can put $4(2l+1)$ electrons on each subshell.
My problem with the question is the hypothetical nature. We are modelling physics after nature, so can we really be sure that Hund's rules would still be valid for that case? If so, why?

A: Yes, you can be sure because both $S = 1/2$ and $S = 3/2$ are fermions that must respect the Pauli exclusion principle.


text:
Q: Why is the $W_6$ wheel graph not a line graph? Why is the $W_6$ wheel graph not a line graph? I know a line graph of an undirected graph $G$ represents the adjacencies between edges of $G$.
If I assume that $W_6$ is a line graph, where is the contradiction that it cannot represent the adjacencies between edges of any graph (i.e. such a graph $G$ does not exist such that $W_6$ is its corresponding line graph)?

A: Suppose that there is a graph $G$ such that its line graph $L$ is isomorphic to $W_6$.
Notice $G$ has an edge $e$ that is adjacent to exactly $5$ edges, after we remove this edge from the graph we obtain a graph $G'$ such that its line graph is isomorphic to a cycle. It is easy to show that if the line graph of a graph $H$ is a cycle then $H$ is isomorphic to the same cycle. To see this notice that since the line graph of $H$ contains a cycle then $H$ must also contain a cycle $C$, also $H$ must be connected, now notice that no extra edge can be joined to $C$, as this would force a vertex of the line graph to have degree exceeding $2$, so $H$ is equal to $C$.( this can be generalized, see here)
We conclude that $G$ must be isomorphic to the cycle $C_5$ along with a diagonal, but this clearly does not work.

A: Let $G$ be a graph with $L(G)$ isomorphic to $W_6$. Since $W_6$ has exactly 6 vertices, $G$ has exactly 6 edges. One vertex in $W_6$ is adjacent to all 5 other vertices, so one edge $e$ of $G$ is adjacent to all 5 other edges of $G$. The remaining vertices of $W_6$ have degree 3, thus the remaining edges of $G$ are adjacent to exactly 3 other edges.
By the pigeonhole principle, one endpoint $v$ of $e$ is incident with at least 3 other edges of $G$. Since those edges are adjacent to exactly 3 edges, $v$ must be incident with exactly 3 other edges of $G$, and those edges are adjacent only to each other and to $e$. But then the other endpoint $w$ of $e$ is incident with exactly 2 other edges of $G$, and those edges are adjacent only to each other and to $e$, a contradiction, since those edges must be adjacent to exactly 3 edges.


text:
Q: Running PDFTron under non-interactive windows service PDFTron is a 3rd party library used to convert files from one extension to a pdf document.
We're using it in our application successfully on multiple scenarios and operation systems.
Now, as we moved forward to automated build system such as TFS we are trying to run pdf conversion as part of the testing stage
We tried both ways, using standard UnitTest and we tried .Exe file which called by PowerShell script. None of the following ever succeeded running and throws the following error:
Unhandled Exception: pdftron.Common.PDFNetException: Exception:
 ○ Message: An error occurred while converting the file.
 Detailed error:
 ○Document failed to open
 ○ Conditional expression: false
 ○ Filename   : Convert.cpp
 ○ Function   : trn::PDF::Convert::ToPdf
 ○ Linenumber : 1825

 at pdftron.PDF.Convert.ToPdf(PDFDoc in_pdfdoc, String in_filename)
 at ImageComapareTool.Program.Main(String[] args)
 Exception Message: MSBuild error 1 has ended this build. You can find more specific information about the cause of this error in above messages. (type BuildProcessTerminateException)
Exception Stack Trace:    at System.Activities.Statements.Throw.Execute(CodeActivityContext context)
   at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
   at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)

Running the executable\powershell script manually from the build server works just fine. which led us to think this is an issue when running under windows service
We ran into this document, but it failed to give us any good assumptions since we're running the service under local user.
Any lead regarding an optional solution\pointing in the right direction will be helpful

A: Eventually, after trying multiple directions such as experimental builds from Pdftron or psexec runs, we ran the TFS service in interactive mode which means an actual user has to be logged on to the TFS Build server.... So it's not the most convenient solution since it's very fragile but at least it works.


text:
Q: Python Typing Annotation inside __init__ How to annotate the type of an instance variable that is only avaiable after __init__? I'd like to list all instance attributes inside __init__ as per POLS.
MWE:
class MyClass(object):
   def __init__(self):
      self.foo :Union[CustomClass, None] = None

   def set_foo(self):
      self.foo = CustomClass()

   def use_foo(self):
      self.foo.do_something()

Inside __init__, if I just annotate foo as self.foo: CustomClass = None, Pylint will complain:

T484: Incompatible types in assignment (expression has type None, variable has type "CustomClass").

However, if I annotate foo as self.foo: Union[CustomClass, None] = None (as in above MWE), PyLint will then complain inside use_foo function:

T484: "None" has no attribute "do_something".

How do I make PyLint happy? (w/o disabling T484)

A: The easiest way I can think of is to simply initialise self.foo to "" instead of None.
This means that self.foo.upper() will be available, so pylint will have no cause to complain.
If you don't want use_foo to be useable until get_foo (which probably would be better called set_foo) is called, you could check to make sure that self.foo is populated, or keep a boolean field stating whether it has ever been run.

If your class is a little more complicated than a string, you'll have to do a quick check before using self.foo.
def use_foo(self):
    if self.foo is None:
        raise EnvironmentError("You haven't called get_foo!")
    self.foo.upper()

This is not a very clean solution - I think we can do better.
Lets try outsourcing this check to a decorator;
def ensure_foo(func):
    def inner_func(self, *args, **kwargs):
        if self.foo is None:
            raise EnvironmentError("You haven't called get_foo!")
        func(self, *args, **kwargs)
    return inner_func

I haven't personally tried this with pylint - but if pylint is clever enough to work out what's going on, slapping @ensure_foo on top of your class methods is going to be a lot cleaner than putting None checks everywhere...


text:
Q: Making a passenger top in rails 4 from a belongs_to table I have 2 classes that have associations with each other
class Trip < ActiveRecord::Base
  has_many :passengers
end

and a class
class Passenger < ActiveRecord::Base
    belongs_to :trip
end

And my Idea is to make a top of X passengers that have been to most trips.
I have found out that you can count entries of each passenger using something like
def count_passenger_trips
  pas_names = Passenger.pluck(:name)

  pas_names.each do |p|
    puts p
    puts Passenger.where(:name => p).count
    pas_names.delete(p)
  end
end

But it does not really return the right result(always keeping the last entry in the array and not counting it in/deleting it from the array)
I guess I could make a new array with key-value pairs and then order them by counts. Wanted to know what might be the problem for not counting in the last passenger and also maybe there is a simpler way to do this(because I want to add a block of Top passengers to my webpage).

A: If name is the unique identifier for these Passenger entities, you could do something like this:
Passenger.group(:name).count

This should give you back results like:
{
  'Jane Doe' => 25,
  'Bob Smith' => 35,
  'Heywood Johnson' => 1,
}

These can be pricey queries if you don't have indexes set up for them, so beware.
If you wanted to, say, only find people with at least 10 trips, you could do this:
Passenger.group(:name).having('count(*) >= 10').count


text:
Q: How to switch to a TableView from a first View? I'm working on my first app and I've issues on how to layout some of its logics.
Basically, what the app is supposed to do is to show a first screen when launched where user can fill in some values and press a button that opens a tableview which shows results. The first screen (view), outlets and connections are all working fine. The issue I'm having is how to leave this "home" search view and show the results to the end user on a table view. Right now, I've only 1 view with its related View Controler and this controller handles the tasks of taking user inputs and get results throughout a HTTP post request.
I need your guidance...Thx in advance
Stephane

A: Is there a reason that this all has to happen on one screen? iOS is set up to allow for this to happen very easily and (I think) attractively by using a UINavigationController and pushing in a new view controller (could be a UITableViewController or simply a UIViewController that contains a UITableView).
If you MUST have all of this take place in one view, Swastik is correct that it will require some view acrobatics. One way to do it attractively is to use the UIView animations introduced with iOS 4.
Here's Apple's UIView documentation: UIView Class Reference
Specifically, check out the CLASS methods of:

1. animateWithDuration:animations: (with or without completion:)

2. transitionWithView:duration:options:animations:completion:

Note that these methods will require you to learn a little bit about blocks, but it's worth it and I think blocks give tremendous power!
With the methods mentioned above, you could fade out your form and fade in your tableview, or maybe just move the form off-screen while the table view flies in. The possibilities are limited only by your imagination.

A: u can add a table in ur xib.Initially make it hidden, & when u need to show it unhide it & also if u want to update table's data , you can reload the data of the table.


text:
Q: MongoDB - changing data directory name changes data I am witnessing a very bizzare behaviour of MongoDB.
I launch MongoD on a test system (Windows 10, 64bit) like this:
"C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe" --dbpath "C:\MongoData"

I then shut down the server and replace the MongoData directory with a data set from a production server. I start mongod again, but I get a collection with 4 documents, which is what I used to have before I replaced my test data set with a real one.
That's not right, because I would expect to see loads of documents in a real data set. I then try dozens of things, including pointing MongoD to the data folder in its original location, which gives me all the documents from the real collection. Phew, the data is safe. But what is happening in my test system?
I have noticed that if I rename the folder in my test system to MongoData2 and lanuch mongod pointing at it then I get my proper production data set. but if I rename it back to MongoData and launch mongod pointing at this folder I get 4 documents again.
What is causing this?

A: As per MongoDB documentation here To use an alternate dbpath, specify the path in the configuration file (e.g. C:\mongodb\mongod.cfg) or on the command line with the --dbpath option.

Default: /data/db on Linux and macOS, \data\db on Windows

The directory where the mongod instance stores its data.
Changed in version 3.0: The files in --dbpath must correspond to the storage engine specified in --storageEngine. If the data files do not correspond to --storageEngine, mongod will refuse to start.
--directoryperdb
Uses a separate directory to store data for each database. The directories are under the --dbpath directory, and each subdirectory name corresponds to the database name.
Changed in version 3.0: To change the --directoryperdb option for existing deployments, you must restart the mongod instances with the new --directoryperdb  value and a new data directory (--dbpath ), and then repopulate the data.

*

*For standalone instances, you can use mongodump
on the existing instance, stop the instance, restart with the new --directoryperdb
value and a new data directory, and use
mongorestore to populate the new data directory.

*For replica sets, you can update in a rolling manner by stopping a
secondary member, restart with the new --directoryperdb
value and a new data directory, and use initial
sync to populate the new data directory. To update all members,
start with the secondary members first. Then step down the primary,
and update the stepped-down member.

A: Looks like the local COMODO firewall was partially blocking the application with its HIPS feature.
I have used command-line arguments to control the DB path, so I'm not totally surprised that it may have affected what MongoD was seeing.
The latest symptom was the database 'forgetting' the newly created users. After allowing the app through the firewall all works well.


text:
Q: NodeJS EJS engine showing undefined I'm trying to figure out what is the issue with the undefined type in my table.
I have an array of objects with strings, I'm rendering it to HTML template  like this:
message.find({ }, function (err, docs) {
  res.render('table', {
    emails: docs
  });
});

First, I just wanted to show the "_id" of the object and it worked but when I have added more keys to my table it started to show undefined state.
Like shown here:

Here is the code inside the HTML template:

    <% emails.forEach(function(item) { %>

        <%= item._id %>
        <%= item.email %>
        <%= item.price %>
        <%= item.ShippingPrice %>
        <%= item.ItemName %>
        <%= item.content %>

    <% }); %>

Here is the console log output from the find query:
{ _id: 57de4c3ef3a4b2c820336c97,
userId: '57de41efaa75cc6933218e57',
email: 'Netta Tzin',
price: '$30.0',
ItemName: 'Airplay Campaign - 1200',
messageId: '13f2339358995daa',
content: '...' }


text:
Q: Using Flask with Google App Engine Dev Server, swagger ui not found? I am developing a website using Flask and Flask Restplus. I tried to use Google App Engine to deploy the app, however when I run dev_appserver.py on my computer, all the swagger-ui files cannot be found. I have no ideas why this happens? Can anyone tell me how to solve this?
Here is the example logs 404 for the resource:
INFO     2017-06-14 04:21:52,859 module.py:809] default: "GET /api/ HTTP/1.1" 200 3710
INFO     2017-06-14 04:21:53,113 module.py:809] default: "GET /swaggerui/bower/swagger-ui/dist/css/screen.css HTTP/1.1" 404 233
INFO     2017-06-14 04:21:53,113 module.py:809] default: "GET /swaggerui/bower/swagger-ui/dist/lib/jquery.slideto.min.js HTTP/1.1" 404 233
INFO     2017-06-14 04:21:53,115 module.py:809] default: "GET /swaggerui/bower/swagger-ui/dist/lib/object-assign-pollyfill.js HTTP/1.1" 404 233
INFO     2017-06-14 04:21:53,121 module.py:809] default: "GET /swaggerui/bower/swagger-ui/dist/css/typography.css HTTP/1.1" 404 233

A: You need to put swaggerui inside your project.  I suggest making a libs directory at the root of your project (same level as app.yaml).
Then, use GAE's vendoring method.  To use vendoring, create (or modify) appengine_config.py in the root of your project, as follows:
from google.appengine.ext import vendor

# Add 3rd party libraries in the "libs" folder.
vendor.add('libs')


text:
Q: Variable output stream delay attempt not working The module I'm trying to get working takes in a pulse data stream with pulses occurring between 500 and 12500 clk cycles, and it needs to delay the stream by a specified number of clk cycles between 500 and 12500 clk cycles. But without using a 12500 bit shift register.
I wrote some code that works in the behavioral simulation, but doesn't post-synthesis. I know my solution is probably terrible form from a Verilog coders perspective. This is my jumping off point I'm just trying to get something working just using what my brain comes up with. My specific problem I think shows up in the schematic view pretty clearly, before synthesis the schematic looks like this:
Before Synthesis Schematic
Which already doesn't make sense to me cause zooming in on the output s_OUT, I see this:
Before Synthesis Schematic Zoomed In
The output seems to just be ground connected to a buffer, but in behavioral simulation it works. After synthesis however the schematic gets rid of all the other stuff not connected to the output and just leaves that buffer and output pin and it no longer works in simulation:
Post Synthesis Schematic
I'd like to know if there's a rule I'm breaking in my Verilog code that's causing this or if its something else:
module data_delay_counter(
    input clk,
    input en,
    input [13:0] ShiftNum,
    input s_IN,
    output reg s_OUT
    );

    // counting phase
    reg [13:0] cyclesToInputPulse = 0; // counted clk cycles before a pulse
    // storage phase
    reg [4:0] memoryIndxWrite = 0; // index to write pulse information to
    reg [13:0] storage [0:24]; // memory for pulse information
    // delay phase
    reg [13:0] delayCounter = 0; // output delay counter
    // output phase
    reg [4:0] memoryIndxRead = 0; // index to read out pulse information from
    reg [13:0] cyclesToOutputPulse = 0; // counted clk cycles up to number read out from storage
    reg [24:0] unusedStorage = 0; // specifies if storage pulse info has been used or not, 1 for unused 0 for used

    always @(posedge clk) begin
        if (en == 1) begin
            // counting phase
            if (s_IN != 1)
                cyclesToInputPulse = cyclesToInputPulse + 14'd1;
            else begin
            // storage phase
                cyclesToInputPulse = cyclesToInputPulse + 14'd1;
                storage[memoryIndxWrite] = cyclesToInputPulse;

                unusedStorage[memoryIndxWrite] = 1;
                cyclesToInputPulse = 14'd0;
                memoryIndxWrite = memoryIndxWrite + 14'd1;
                if (memoryIndxWrite == 25)
                    memoryIndxWrite = 14'd0;

            end
            // delay phase
            if (delayCounter != ShiftNum)
                delayCounter = delayCounter + 1;
            // output phase
            else begin
                cyclesToOutputPulse = cyclesToOutputPulse + 14'd1;
                if (cyclesToOutputPulse == storage[memoryIndxRead] && unusedStorage[memoryIndxRead] == 1) begin
                    s_OUT = 1;
                    unusedStorage[memoryIndxRead] = 0;
                    cyclesToOutputPulse = 14'd0;
                    memoryIndxRead = memoryIndxRead + 14'd1;
                    if (memoryIndxRead == 25)
                        memoryIndxRead = 0;
                end
                else begin
                    s_OUT = 0;
                end
            end
        end
        else begin
            cyclesToInputPulse = 0;
            memoryIndxWrite = 0;
            delayCounter = 0;
            cyclesToOutputPulse = 0;
            memoryIndxRead = 0;
            unusedStorage = 0;
            s_OUT = 0;
        end
    end

    always @(ShiftNum) begin
        cyclesToInputPulse = 0;
        memoryIndxWrite = 0;
        delayCounter = 0;
        cyclesToOutputPulse = 0;
        memoryIndxRead = 0;
        unusedStorage = 0;
        s_OUT = 0;
    end

The process I was thinking to use was have 25, 14 bit registers as memory to handle the worst case of a pulse every 500 cycles and max delay of 12500 cycles, count the cycles to each pulse store them in memory, wait for the delay and output the pulses according to what's stored in memory. And I needed to add that unusedStorage parameter in order to ensure it always used each stored memory delay only once.

A: The first problem I see is that you are making assignments to signals from multiple always blocks.  For example, s_OUT is assigned in both of your always blocks.  While this is legal for simulations, it is likely causing problems for synthesis.
Another issue with the 2nd block is that the signal in the sensitivity list (ShiftNum) is not used within the block; typically, all signals in the list would also be "read" (i.e., appear on the RHS of an assignment).  This block does not map to a conventional synthesis construct.
I recommend incorporating all the assignments from the 2nd always block into the 1st somehow.
If you have log files for your synthesis run, take a look in them.  I'd be surprised if you didn't get warning messages for any of this.

It is also good practice to use nonblocking assignments (<=) in clocked always blocks.


text:
Q: Why is my ANTLR 4 parser rule not returning the desired value? I am trying to use ANTLR 4.3 with the antlr4-maven-plugin of the same version to achieve two goals:

*

*Validate a user provided expression against a fairly simple grammar to prevent injection of invalid or potentially dangerous code.

*Rewrite identifiers in the expression such that they are fully qualified using dot notation, e.g. context.identifier.

I am having problems with item 2. Because I only need to make very minor modifications to the input expression, using a parser rule with a return value seems like the appropriate solution. However, the parser returns the original identifier rather than the rewritten one that I would expect to see.
Here's simplified version of the grammar to illustrate the behavior:
grammar Sample;

expr
 : ( field_name ) EOF
 ;

field_name returns [String fqn]
 : any_name { $fqn = "prefix." + $text; }
 ;

any_name
 : IDENTIFIER
 | STRING_LITERAL
 | '(' any_name ')'
 ;

IDENTIFIER
 : '"' (~'"' | '""')* '"'
 | '`' (~'`' | '``')* '`'
 | '[' ~']'* ']'
 | [a-zA-Z_] [a-zA-Z_0-9]*
 ;

STRING_LITERAL
 : '\'' ( ~'\'' | '\'\'' )* '\''
 ;

The field_name rule is intended to prepend a qualifier to any name it encounters and return the fully qualified name. However, in my test this never seems to work:
package sample;

import static org.junit.Assert.assertEquals;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.BailErrorStrategy;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.TokenStream;
import org.junit.Test;

public class SampleParserTest {

    @Test
    public void testSampleParser() {
        CharStream input = new ANTLRInputStream("field1");
        SampleLexer lexer = new SampleLexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        SampleParser parser = new SampleParser(tokens);
        BailErrorStrategy errorHandler = new BailErrorStrategy();
        parser.setErrorHandler(errorHandler);
        ParserRuleContext tree = parser.expr();
        TokenStream tokenStream = parser.getTokenStream();
        String fqn = tokenStream.getText(tree);
        assertEquals("prefix.field1", fqn);
        // org.junit.ComparisonFailure: expected:<[prefix.]field1> but
        // was:<[]field1>
    }

}

What's wrong with my grammar or the unit test that prevents the field_name rule from returning the expected fully-qualified name? Are there other (better) ways to achieve the same goals?
Thanks in advance for your time and expertise.


text:
Q: TestInputFileBuilder 'missing' while updating sonar-java-plugin So, i have a sonar java custom rules plugin, running on the 4.2.1.6971 version and SonarQube platform at 5.6.3.
Recently i tried to update the java plugin dependency to the latest 4.9.0.9858 version, and after trying to 'clean install' the project i get the same error on all unit tests:
[INFO] Running checks.security.SystemExitCallsCheckTest
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed:
0.001 s <<< FAILURE! - in checks.security.SystemExitCallsCheckTest
[ERROR] detected(checks.security.SystemExitCallsCheckTest)  Time elapsed: 0s << ERROR!
java.lang.NoClassDefFoundError:
org/sonar/api/batch/fs/internal/TestInputFileBuilder
at checks.security.SystemExitCallsCheckTest.detected(SystemExitCallsCheckTest.java:19)

It seems like the class
TestInputFileBuilder is not found, but i get no dependency error on Eclipse.
Here's a part of my pom.xml:
    <properties>
    <sonar.version>6.0</sonar.version>
    <java.plugin.version>4.9.0.9858</java.plugin.version>
    <sslr.version>1.21</sslr.version>
    <gson.version>2.6.2</gson.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.sonarsource.sonarqube</groupId>
        <artifactId>sonar-plugin-api</artifactId>
        <version>${sonar.version}</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.sonarsource.java</groupId>
        <artifactId>sonar-java-plugin</artifactId>
        <type>sonar-plugin</type>
        <version>${java.plugin.version}</version>
        <scope>provided</scope>
    </dependency>

What should i do to get ride of this error? I get the same error when i try to run any unit test separately too.
Thanks in advance!

A: You need to upgrade the sonar version to API 6.3. This is because internally the SonarJava plugin relies on this API for tests because of this file : TestInputFileBuilder : https://github.com/SonarSource/sonarqube/blob/master/sonar-plugin-api/src/main/java/org/sonar/api/batch/fs/internal/TestInputFileBuilder.java which was introduced in 6.3.
Note that while it is required to rely on this API for your plugin tests, as long as you don't use an API that is not available in 5.6 (LTS) you can perfectly run your custom rules on LTS.


text:
Q: How to grep or awk string in non fixed position I didn't find similar solution, apart from parsing multiple arguments which is a whole script by it self.
I need to get handle # from nftables for the script, and having problems because it is not always located on the same position.  With Iptables it was line number which was always listed on the first field so was very easy to capture insert position.
when I do:
nft -n -a list chain inet fw4 forward
output would be something like this:
table inet fw4 {
    chain forward { # handle 2
        type filter hook forward priority 0; policy drop;
        ip saddr 192.168.0.0/16 ip daddr 192.168.0.0/16 accept # handle 223
        ct state 0x2,0x4 accept comment "!fw4: Allow forwarded established and related flows" # handle 179
        iifname "br-lan" jump forward_lan comment "!fw4: Handle lan IPv4/IPv6 forward traffic" # handle 180
        iifname "eth0.2" jump forward_wan comment "!fw4: Handle wan IPv4/IPv6 forward traffic" # handle 181
        jump handle_reject # handle 182
    }
}

I need to capture "handle #", which in this case is 223 without any spaces before or after
normally I would do:
InsNo=$(nft -n -a list chain inet fw4 forward|grep -m 1 "192.168.0.0"|awk '{print $10}')

which works only when fixed number of fields are present.  I tried also
InsNo=$(nft -n -a list chain inet fw4 forward|grep -m 1 "192.168.0.0"|awk -F'handle ' '{print $2}')

which works if no more arguments are present after handle number.  But I'd like to know if there is any more reliable method, in getting this number, also without spaces before or after.

A: You could check if the line contains 192.168.0.0 and then get a match if the handle part can be anywhere in the line.
After the first match remove the leading handle  using substr and exit the program.
For example, if the example data is in file
awk '
/192\.168\.0\.0/ && match($0, /handle [0-9]+/) {
    print substr($0, RSTART+7)
    exit
}' file

Output
223

If for exampe the handle part always comes after the ip, you might also use gnu awk with a capture group:
awk '
match($0, /192\.168\.0\.0.*handle ([0-9]+)/, a) {
    print a[1]
    exit
}' file

A: awk solutions are your easiest option here (and what you asked about), but a potentially "safer" version can be written with sed by matching both handle and the consecutive numbers. Just an additional option because... why not.
nft -n -a list chain inet fw4 forward |
    sed -En '/192\.168\.0\.0/s/.*# +handle +([0-9]+).*/\1/p'

Final solution was "only first match" and ended up like this:
nft -n -a list chain inet fw4 forward |
    sed -En '/192\.168\.0\.0/{s/.*# +handle +([0-9]+).*/\1/p; q}

The () parathesis is a capture group, recovered by \1 later on, i.e. returning the match within. [0-9] matches any digit and the following + matches "one or more" of that = any number of consecutive digit(s). Th p prints line to stdout. It's needed as we suppress all lines otherwise with the -n flag. To only print one match, simply encapsulate the substitute in {} curly brackets and add q for quit.

A: The piece of information you're apparently missing is that awk has a variable named NF for the number of fields. And also that you should use the -F grep option to interpret the 192.168.0.0 pattern as fixed string, not regular expression.
InsNo=$(nft -n -a list chain inet fw4 forward | grep -F -m 1 "192.168.0.0" |
  awk '{print $NF}')

But piping grep in awk is usually a waste:
InsNo=$(nft -n -a list chain inet fw4 forward |
  awk '/192\.168\.0\.0/ {print $NF}')

If the field you are interested in is not always the last of the line, but always follows fields # and handle, and is always a decimal number, we can be a bit more accurate:
InsNo=$(nft -n -a list chain inet fw4 forward |
  awk '/192\.168\.0\.0/ {
         for(i=1; i<=NF-2; i++)
           if($i=="#" && $(i+1)=="handle" && $(i+2)~/^[0-9]+$/)
             print $(i+2)
       }')

And finally, if you want only the first match, just add an exit statement after print:
InsNo=$(nft -n -a list chain inet fw4 forward |
  awk '/192\.168\.0\.0/ {
         for(i=1; i<=NF-2; i++)
           if($i=="#" && $(i+1)=="handle" && $(i+2)~/^[0-9]+$/) {
             print $(i+2); exit
           }
       }')


text:
Q: Overriding a function in Emacs Lisp I would like to temporarily override the kill-new function.  I have a way I want to reimplement kill-new that works in only in certain contexts, but I don't want to reimplement a special version of kill-region on top of that.  (kill-new is called from kill-region)
Since Emacs Lisp uses dynamic scoping, this should be possible, right?  (On the other hand, it seems that this would be an unsafe thing to support, and it might make me a bit nervous knowing that it is possible...)
I have experimented with using let and fset, but so far have found no way to get it to work as expected.  So, hopefully someone can fill in the blank in the following pseudocode:
(defun my-kill-new (string &optional replace yank-handler)
   (message "in my-kill-new!"))

(defun foo ()
   (some-form-that-binds-a-function (kill-new my-kill-new)
   (kill-region (point) (mark))))

What should some-form-that-binds-a-function be?  Or am I barking up the wrong tree?

A: Look at the advice package, which is very good at doing all of this.

A: Your some-form-that-binds-a-function is called flet, so you were close.

A: Here is a solution:
(defadvice kill-new (around my-kill-new (string &optional replace yank-handler))
   (message "my-kill-new!"))

(defun foo ()
  (progn (ad-enable-advice 'kill-new 'around 'my-kill-new)
     (ad-activate 'kill-new)
     (kill-region (point) (mark))
     (ad-disable-advice 'kill-new 'around 'my-kill-new)
     (ad-activate 'kill-new)))


text:
Q: Как увеличить область отображаемого числа? Только начал учить Python, и сделать калькулятор но тут он выдает ошибку которую я не могу никак найти
x = float(input())
y = float(input())
operation = str(input())

if operation == "+":
    print (x + y)
elif operation == "-":
    print (x - y)
elif operation == "/" and y != 0.0:
    print (x / y)
elif operation == "*":
    print (x * y)
elif operation == "mod" and y != 0.0:
    print (x // y and x % y)
elif operation == "pow":
    print (x ** y)
elif operation == "div" and y != 0.0:
    print (x % y)
if y == 0.0 and (operation in ('/', 'mod', 'div')):
    print('Деление на 0!')

Данные которые ввожу:
7
399
pow

Ошибка которую он выдает:
Traceback (most recent call last):
  File "jailed_code", line 16, in <module>
    print (x ** y)
OverflowError: (34, 'Numerical result out of range')

Как я понял, что данная ошибка указывает на то что максимум знаков которая она может показать это 34, но как увеличить этот максимум, я не понимаю

A: from decimal import Decimal
x = 7
y = 399

try:
    result = x ** y
except OverflowError:
    result = Decimal('{:.2E}'.format(Decimal(x) ** Decimal(y)))
print(result)
# 1.56E+337

from decimal import Decimal
x = 7
y = 20000

result = Decimal('{:.2E}'.format(Decimal(x) ** Decimal(y)))

print(result)
print(result / 50000000)
print(float(result))
# 9.14E+16901
# 1.828E+16894
# inf


text:
Q: Inner product given by its orthonormal basis Say we have an inner product such that $\{(1,0,0),(1,1,0),(1,1,1)\}$ is an orthonormal basis. I'm asked to find

*

*$||(1,2,3)||$

*An orthonormal basis for $U=$span$\{(0,1,0),(0,0,2)\}$

*The orthonormal projection of $v=(3,2,1)$ on $U$.

Now approaching this problem, I calculated 1 using the following method:
We can write $(1,2,3)$ as $-1(1,0,0)-1(1,1,0)+3(1,1,1)$.
We also know that for orthonormal basis, we can also write:
$(1,2,3)=\langle(1,2,3),(1,0,0)\rangle(1,0,0)+\langle(1,2,3),(1,1,0)\rangle(1,1,0)+\langle(1,2,3),(1,1,1)\rangle(1,1,1)$
So we can infer the inner product of $\langle(1,2,3),(1,0,0)\rangle=1, \langle(1,2,3),(1,1,0)\rangle=1, \langle(1,2,3),(1,1,1)\rangle=3$
Using linearity of inner product we can then infer:
$||(1,2,3)||^2=\langle(1,2,3),(1,2,3)\rangle=-1\langle(1,2,3),(1,0,0)\rangle-1\langle(1,2,3),(1,1,0)\rangle+3\langle(1,2,3),(1,1,1)\rangle=11$
Using the same approach I found that the orthonormal basis of $U$ is $B=\{\frac{1}{\sqrt2}(0,1,0),\frac{1}{\sqrt8}(0,1,2)\}$.
First of all - is my approach right? And secondly I'm having trouble with finding the projection, for some reason it always comes out $(0,0,0)$ which feels pretty weird to me.


text:
Q: python dynamic class names Trying to instantiate a class based on a string value and... failing. The parser object below is a dict, in the example let's say we have one called foo and here parser['name'] is 'foo':
obj = parser['name']()

Fails, yielding TypeError: 'str' object is not callable. But, since I have:
class foo:
    def __init__(self():
        print 'Hello'

And if I do obj = foo() it works fine and creates the correct object. Also, calling obj = type(parser['name'])() doesn't work.
How to resolve this? Update: I don't really want to use a mapping system: the names of these classes are defined INI files, and parsed that way, so they will be strings..

A: Don't use strings:
parser = {}

class foo:
    pass

parser['foo'] = foo

obj = parser['foo']()

A: You can use a metaclass that stores a dict of known classes:
# a metaclass
class Registry(type):
    # store all the types we know
    registered = {}
    def __new__(cls, name, bases, attrs):
        # create the new type
        newtype = super(Registry, cls).__new__(cls, name, bases, attrs)
        # store it
        cls.registered[name] = newtype
        return newtype

    @classmethod
    def class_by_name(cls, name):
        # get a class from the registerd classes
        return cls.registered[name]

# arbitrary base class for every class that should be in the Register
class Registered(object):
    __metaclass__ = Registry

# some classes
class Foo(Registered):
    pass

class Bar(Foo):
    pass

 # get the class object:
print Registry.class_by_name('Foo') # <class '__main__.Foo'>
# it can be instanciated too ofc:
print Registry.class_by_name('Bar')() # <__main__.Bar object at 0x01F0F9F0>

But not everyone understands metaclasses, so you might want to avoid them to prevent any confusion. They can be useful for stuff like this, but as you can see from the other answers, there are plenty other ways to do it.

A: The type(name, bases, dict) built-in function is the correct way to dynamically construct classes--especially when given strings for class names. See the documentation here: http://docs.python.org/library/functions.html#type
In you particular example, it might look like this:
>>> def init(self):
...     print 'Hello'
...
>>> Foo = type('Foo', (object,), {'__init__': init})
>>> foo = Foo()
Hello

A: You could use inspect to create the class map:
def get_classes():
    classes = {}
    for name, obj in inspect.getmembers(sys.modules[__name__]):
        if inspect.isclass(obj):
            classes[name] = obj
    return classes

Then instantiate a class
>>> classes = get_classes()
>>> c = classes['ClassName']
>>> c
<class ClassName...>

Mostly nicked from How can I get a list of all classes within current module in Python?

A: classmap = {
  'foo': foo
}

obj = classmap[parser['name']]()

A: As answered in:
Python dynamic class names
There is an easier way to do this if you know which module the classes are defined in, for example:
getattr(my_module, my_class_name)()

A: I would use a map of class name to class object like everyone else is saying.  You can initialize it using statements like parser[foo.__name__] = foo.  If you do not want to use a mapping object, then you will have to fall back to using the eval function like the following:
>>> class foo:
...   pass
...
>>> klass_name = 'foo'
>>> klass_inst = eval(klass_name)
>>> klass_inst
<class __main__.foo at 0x1004b2b90>
>>> inst = klass_inst()
>>> inst
<__main__.foo instance at 0x1004d2680>
>>>

Of course if you want to use classes that are embedded within a package, then the package will have to be imported before you do the eval.  You really should build a mapping object so that you can limit the classes that can be accessed using this code.

A: In response to your update: The only way to do this is with a mapping system. If you don't want to use an explicit mapping system, then you can use one of Python's built-in mapping systems, though it's much less nice and explicit in my opinion.
obj = globals()[parser['name']]()

will access the global object of with name parser['name'] == 'foo'. If this happens to be a class (or a class that you actually want instantiated based on user input), then you should be good to go. Otherwise, you will have to build logic around it to whitelist the classes that you actually want.
If the classes are coming from a module, then you can use that module's __dict__ attribute to the same effect.
obj = somemodule.__dict__[parser['name']]()

The same caveats apply to this situation as the previous one. It's really better to just use an explicit mapping


text:
Q: Pseudoselectors in jQuery I have something like this in my JavaScript:
var id = "\#mode";
if (visible){
    $("a[href^=\/\""+id+"\"]").addClass('w--current');
} else {
    $("a[href^=\/\""+id+"\"]").removeClass('w--current');
}                               }

I know that you can do something like this in CSS as well, so for instance
a[class^=myClass] {
    display: none;
}

should trigger on every a-tag, which has a class starting with myClass.
However, does this apply to the href attribute?
This here is the error printed in the console:

Error: Syntax error, unrecognized expression: a[href^=/"#mode"]

A: I think your escape sequence is the problem, you have an extra \/ in your script
$('a[href^="' + id + '"]').addClass('w--current');


text:
Q: Where is the data store for the python generator? I refer to Python : Using the map function  It says "map returns a specific type of generator in Python 3 that is not a list (but rather a 'map object', as you can see). "  That is my understanding too.  Generator object do not contain the values but is able to give you the values when you call it (next()).  So my question is where are those values store ?
I tried the following experiment.

*

*create 2 tuple and check their size

*create 2 map objects from the tuple

*do a next() on the map objects to use up some of the values

*delete one of the tuple

*continue to do next()

I would assume that when I delete the tuple, there would be no more values to do a next() but that's not the case.  So my question is where are those values coming from ?  Where are they stored after I delete the tuple ?
Code:
t1 = tuple(range(1000))
t2 = tuple(range(10000))
print(f'{t1[:10]} len = {len(t1):5d} size = {getsizeof(t1):5d}')
print(f'{t2[:10]} len = {len(t2):5d} size = {getsizeof(t2):5d}')

Output:
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) len =  1000 size =  8040
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) len = 10000 size = 80040

Code:
m1 = map(lambda y: print(y), t1)
m2 = map(lambda y: print(y), t2)
print(f'size of m1 = {getsizeof(m1)}')
print(f'size of m2 = {getsizeof(m2)}')

Output:
size of m1 = 48
size of m2 = 48

Do the following a number of  times:
next(m1)
next(m2)

Output:
23
23

Delete the tuple:
import gc
del t1
gc.collect()
t1

Output:
168
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-336-df561a5cc277> in <module>
      2 del t1
      3 gc.collect()
----> 4 t1

NameError: name 't1' is not defined

Continue next()
next(m1)
next(m2)

Output:
31
31

I'm still able to get values from map after deleting the tuple.

A: With del t1 you delete the variable, not the object it references.
Before del t1:

After del t1:

So that's still all alive and well and functional. You just don't have the separate t1 variable referencing the tuple anymore.

A: del doesn't remove the tuple from memory, it just removes the variable.
The map object has its own reference to the tuple -- it's a class instance variable variable.
Garbage collection doesn't remove a the tuple from memory until all references to it are destroyed. This will happen when the generator reaches the end (it should delete its own reference to avoid a memory leak) or if you delete the reference to the generator.


text:
Q: Afraid to tell the truth about someone Simple one word to describe a feeling of uncertainty or anxiety about telling someone something very important but possibly damaging to either oneself or the person in question.

A: You might consider  'reticent'
It applies more directly to communication than some of the other words of concern, although the idea of "concern" is more a matter of "reservation" .

reticent at Dictionary.com

*

*taciturn, quiet, uncommunicative.

  1.
  not open or communicative; not saying all that one knows; taciturn; reserved
The New York Times, usually so reticent on sex-scandal stories, has named her and run the picture.
Leno asked why he has been so reticent to publicize his opinions about President Obama and his policies.

While one definition can me "quiet" of nature the context of most sentences you would use it in for your stated purpose would strongly suggest a ~reluctance~ to say something for some reason beyond a being a quiet type.

A: I'd use "apprehension", although one could argue that it's not strong enough.


text:
Q: Number of ways to fill 3xN tiles with 2 x 1 dominoes (SPOJ: M3TILE) I've been trying to solve this programming problem, but since I can't figure it out, I found a solution online. but I can't really understand why that solution works either ..
the task is to calculate in how many ways can a 3*n (n >= 0, n is the only input) rectangle be completely filled with 2*1 dominos.
e.g. (red lines represent dominos):

This was what I first drew on a sheet of paper when I read the text, and I saw that there were three possible combinations that a 3*2 rectangle can have, and that if n is odd the solution is 0 because there is no way to fill up the entire rectangle then (one piece will always stay uncovered by a domino).
So I thought the solution was simply 3^n, if n was even, and 0, if n was odd. turns out, I was wrong.
I found a relatively simple solution here:
#include <iostream>

using namespace std;

int main()
{
    int arr[31];

    arr[0]=1;
    arr[1]=0;
    arr[2]=3;
    arr[3]=0;

    for(int i = 4; i < 31; i++) {
        arr[i] = arr[i-2] * 4 - arr[i-4]; //this is the only line i don't get
    }

    int n;

    while(1) {
        cin >> n;

        if(n == -1) {
            break;
        }

        cout << arr[n] << endl;
    }

    return 0;
}

Why does this work?!

A: Let T(n) be the number of ways one can tile a 3×n board with 2×1 tiles. Also, let P(n) be the number of ways one can tile a 3×n board with one corner removed with 2×1 tiles. Assume n sufficiently large (>= 4).
Then consider how you can start the tiling from the left (or right, doesn't matter).
You can place the tile covering the top left corner in two ways, vertical or horizontal. If you place it vertical, the tile covering the bottom left corner must be placed horizontally, giving a configuration
|
==

That leaves P(n-1) ways to tile the remaining part. If you place it horizontally, you can place the tile covering the bottom left corner either horizontally or vertically. If you place it vertically, you are in the same situation as before, just reflected, and if you place it horizontally, you must place a tile horizontally between them,
==
==
==

leaving you with a 3×(n-2) board to tile. Thus
T(n) = T(n-2) + 2*P(n-1)              (1)

Now, considering the 3×(n-1) board with one removed (already covered) corner (let's assume top left), you can either place a tile vertically below it, giving
=
|

and leaving you with a 3×(n-2) board to tile, or you can place two tiles horizontally below it, giving
=
==
==

and then you have no choice but to place another tile horizontally at the top, leaving you
===
==
==

with a 3×(n-3) board minus a corner,
P(n-1) = T(n-2) + P(n-3)

Adding up,
T(n) = T(n-2) + 2*(T(n-2) + P(n-3))
     = 3*T(n-2) + 2*P(n-3)                            (2)

But, using (1) with n-2 in place of n, we see that
T(n-2) = T(n-4) + 2*P(n-3)

or
2*P(n-3) = T(n-2) - T(n-4)

Inserting that into (2) yields the recurrence
T(n) = 4*T(n-2) - T(n-4)

q.e.d.

A: Sharing  my image tut.Hope it helps .


text:
Q: Utilizar el ciclo for correctamente en Angular Muy buenas compañeros, el problema que tengo es que no se como hacer un ciclo for.

OBJETIVO: Cambiarle a un JSON el formato de fecha de timestamp a dd/mm/yyyy

He intentado esto
  this.dataTable.dataRows = response.data;
  for (let date of this.dataTable.dataRows){
    let date = moment(this.dataTable.dataRows.fecha.timestamp*1000).utc();
   this.dataTable.dataRows.fecha=date.format('YYYY-MM-DD');
}
 console.log(this.dataTable.dataRows);

El JSONes:
{
    "status": "success",
    "code": "200",
    "mensaje": "Todos los datos se han cargado correctamente",
    "data": [
        {
            "idCorrDoc": 1,
            "noResolucion": "15041-RES-CR-03925-2015",
            "serie": "15DS000F",
            "desde": 1,
            "hasta": 7000,
            "fecha": {
                "timezone": {
                    "name": "UTC",
                    "transitions": [
                        {
                            "ts": -9223372036854775808,
                            "time": "-292277022657-01-27T08:29:52+0000",
                            "offset": 0,
                            "isdst": false,
                            "abbr": "UTC"
                        }
                    ],
                    "location": {
                        "country_code": "??",
                        "latitude": 0,
                        "longitude": 0,
                        "comments": ""
                    }
                },
                "offset": 0,
                "timestamp": 1422835200
            },
            "status": true,
            "nomimprenta": "CREATIVA, S.A. DE C.V.",
            "nitimprenta": "0614-231092-107-7",
            "nrcimprenta": "72018-6",
        }
    ]
}

A: El problema es que no estas asignando la fecha a ninguna variable.
  this.dataTable.dataRows = response.data;
      for (let i=0; i < this.dataTable.dataRows.length; i++){
        let date = moment(this.dataTable.dataRows[i].fecha.timestamp*1000).utc();
       this.dataTable.dataRows[i].fecha=date.format('YYYY-MM-DD');
    }

*

*La forma como declaras el ciclo, se pierde el contexto del arreglo por que lo resignas.


text:
Q: Xcode 10 Build failed - React Native Error Message Screenshot I've been trying to get my react-native app to build in Xcode 10. However, the build fails with an error message of header files not found, viz, 'React/UIView+React.h' file not found'
I've added React in the target dependencies and in the schemes, as suggested on a lot of Stack Overflow questions.
But the error still persists, and build fails.
My react-native version is 0.43.
Any help is appreciated.


text:
Q: SQL Statement to Join Users and Last Login Date,Location I have two tables, a list of Users, and a UserLoginHistory table that has their history of login dates, IP Addresses, and Geolocations.
I want to create one SQL statement that will return one each User + their last LoginDate and Geolocation.
  Users.UserId, Users.Name
     100        Bill
     101        Steve

  UserLoginHx.UserId, UserLoginHx.LoginDate, UserLoginLocation
    100               1/1/2018               New York
    101               1/1/2018               Los Angeles
    100               1/4/2018               Chicago
    101               1/5/2018               Denver
    ....

Result desired in this example should return two rows as:
    100  Bill  1/4/2018   Chicago
    101  Steve 1/5/2018   Denver

Thanks. (so far nobody got close)

A: Try below query:
select UserLoginHx.UserId,users.name,a.logindate,a.location from UserLoginHx
inner join
(select UserLoginHx.UserId,max(UserLoginHx.LoginDate) as logindate
from UserLoginHx
group by UserLoginHx.UserId)a on a.UserId=UserLoginHx.UserId and a.logindate=UserLoginHx.LoginDate
inner join Users on Users.UserId=UserLoginHx.UserId

A: SELECT u.UserId, u. Name, ulh.LoginDate, ulh.UserLoginLocation
FROM Users u
JOIN UserLoginHistory ulh ON u.UserId = ulh.UserId

A: A JOIN clause is used to combine rows from two or more tables, based on a related column between them.
so for you  need join two tables
SELECT u.*, uh.LoginDate, uh.UserLoginLocation
FROM Users u
JOIN UserLoginHistory uh ON u.UserId = uh.UserId

A: Try the following query-:
with cte as
(
select a.*,LoginDate,UserLoginLocation,
ROW_NUMBER() over (partition by a.UserId order by Login desc) rn
from Users a
join UserLoginHistory  b
on a.UserId=b.UserId
)select * from cte where rn=1

SQL Server


text:
Q: How to execute programs from geany using the GUI? well i recently installed geany .. the ide is great and worked great for python programs ,
but when i try executing c/c++ programs from the executed button i get an error saying ./geany_run_script.sh: 5: ./rsa2: not found    ( rsa is the name of my program )
well i did try googling out but could find a case like mine.

A: If you want to run a program, you need to compile it.
By default, the compile key in geany is F8.
Then, you can run the program. (F5)
You can define flags in project>properties (click on the "construct" tab).

A: I tried doing F8 and F5 and the problem was same as yours. But then i did build, compile and run and it worked.(This post may help someone !!)


text:
Q: Changing HashMap keys during iteration is it possible to change keys of a the same HashMap instance during iteration ? Because map entry set don't have a method entry.setKey(). Now what I can think off is create another HashMap...
MultipartParsingResult parsingResult = parseRequest(request);

Map<String, String[]> mpParams = parsingResult.getMultipartParameters();
Map<String, String[]> mpParams2 = new HashMap<String, String[]>();

Iterator<Entry<String,String[]>> it = mpParams.entrySet().iterator();

while (it.hasNext()) {
    Entry<String,String[]> entry = it.next();
    String name = entry.getKey();

    if (name.startsWith(portletNamespace)) {
        mpParams2.put(name.substring(portletNamespace.length(), name.length()), entry.getValue());
    }
    else {
        mpParams2.put(name, entry.getValue());
    }
}

A: There are four common types of modification you might want to do to the keys or values in a HashMap.

*

*To change a HashMap key, you look up the value object with get, then remove the old key and put it with the new key.

*To change the fields in a value object, look the value object up by key with get, then use its setter methods.

*To replace the value object in its entirely, just put a new value object at the old key.

*To replace the value object with one based on the old, look the value object up with get, create a new object, copy data over from the old one, then put the new object under the same key.

Something like this example.
static class Food
    {
    // ------------------------------ FIELDS ------------------------------

    String colour;

    String name;

    float caloriesPerGram;
    // -------------------------- PUBLIC INSTANCE  METHODS --------------------------

    public float getCaloriesPerGram()
        {
        return caloriesPerGram;
        }

    public void setCaloriesPerGram( final float caloriesPerGram )
        {
        this.caloriesPerGram = caloriesPerGram;
        }

    public String getColour()
        {
        return colour;
        }

    public void setColour( final String colour )
        {
        this.colour = colour;
        }

    public String getName()
        {
        return name;
        }

    public void setName( final String name )
        {
        this.name = name;
        }

    public String toString()
        {
        return name + " : " + colour + " : " + caloriesPerGram;
        }

    // --------------------------- CONSTRUCTORS ---------------------------

    Food( final String name, final String colour, final float caloriesPerGram )
        {
        this.name = name;
        this.colour = colour;
        this.caloriesPerGram = caloriesPerGram;
        }
    }

// --------------------------- main() method ---------------------------

/**
 * Sample code to TEST HashMap Modifying
 *
 * @param args not used
 */
public static void main( String[] args )
    {
    // create a new HashMap
    HashMap<String, Food> h = new HashMap<String, Food>( 149
            /* capacity */,
            0.75f
            /* loadfactor */ );

    // add some Food objecs to the HashMap
    // see http://www.calorie-charts.net  for calories/gram
    h.put( "sugar", new Food( "sugar", "white", 4.5f ) );
    h.put( "alchol", new Food( "alcohol", "clear", 7.0f ) );
    h.put( "cheddar", new Food( "cheddar", "orange", 4.03f ) );
    h.put( "peas", new Food( "peas", "green", .81f ) );
    h.put( "salmon", new Food( "salmon", "pink", 2.16f ) );

    // (1) modify the alcohol key to fix the spelling error in the key.
    Food alc = h.get( "alchol" );
    h.put( "alcohol", alc );
    h.remove( "alchol" );

    // (2) modify the value object for sugar key.
    Food sug = h.get( "sugar" );
    sug.setColour( "brown" );
    // do not need to put.

    // (3) replace the value object for the cheddar key
    // don't need to get the old value first.
    h.put( "cheddar", new Food( "cheddar", "white", 4.02f ) );

    // (4) replace the value object for the peas key with object based on previous
    Food peas = h.get( "peas" );
    h.put( "peas", new Food( peas.getName(), peas.getColour(), peas.getCaloriesPerGram() * 1.05f ) );

    // enumerate all the keys in the HashMap in random order
    for ( String key : h.keySet() )
        {
        out.println( key + " = " + h.get( key ).toString() );
        }
    }// end main
}

I hope this helps

A: Maybe this helps:
map.put(newkey,map.remove(oldkey));

A: You should keep information in other collection to modify it after iteration. You can only remove entry using iterator.remove() during iterator. HashMap contract forbids mutating it during iteration.

A: i got to this thread when i needed to change the keys of the map entries.
in my case i have a JSON representation in a Map , meaning it can hold map or list of maps, here is the code:
private Map<String,Object> changeKeyMap(Map<String, Object> jsonAsMap) throws InterruptedException {

    Map<String,Object> mapClone = new LinkedHashMap<>();
    for (Map.Entry<String, Object> entry : jsonAsMap.entrySet()) {
        if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
        Object value = entry.getValue();
        if (entry.getValue() instanceof Map) {
            value = changeKeyMap((Map) entry.getValue());
        } else if (isListOfMaps(entry.getValue())) {
            value = changeKeyListOfMaps((List<Map<String, Object>>) entry.getValue());
        }
        String changedKey = changeSingleKey(entry.getKey());
        mapClone.put(changedKey, value);
    }
    return mapClone;
}

private List<Map<String,Object>> changeKeyListOfMaps(List<Map<String,Object>> listOfMaps) throws InterruptedException {
    List<Map<String,Object>> newInnerMapList = new ArrayList<>();
    for(Object singleMapFromArray :listOfMaps){
        Map<String,Object> changeKeyedMap = changeKeyMap((Map<String, Object>) singleMapFromArray);
        newInnerMapList.add(changeKeyedMap);
    }
    return newInnerMapList;
}
private boolean isListOfMaps(Object object) {
    return object instanceof List && !((List) object).isEmpty() && ((List) object).get(0) instanceof Map;
}

private String changeSingleKey(String originalKey) {
    return originalKey + "SomeChange"
}

A: The best thing to do is to copy the map into a new one with the modifications you want, then return this new maps and destroy the old one.
I wonder what's the performance impact of this solution however.


text:
Q: Go lang sort a 2D Array of variable size I would like to sort a 2D array in golang, for e.g:
        {40, 100, 20},
        {30, 100},
        {40, 10},
        {30, 100, 80},
        {30, 60},
        {30, 80},
        {100, 20},
        {10, 80},
        {50, 30},

I referred to this go playground example. It works fine in the case above but if I change the order of the array as below:
        {40, 100, 20},
        {40, 10},
        {30, 100},
        {30, 100, 80},
        {30, 60},
        {30, 80},
        {100, 20},
        {10, 80},
        {50, 30},

it sometimes gives error like so:
panic: runtime error: index out of range [2] with length 2
Any suggestions on what might be wrong, why it works in some cases and not in others?
Thanks!

A: The code you've provided is only suitable for fixed length arrays. The error comes from where the program needs to compare a 3 element array with a 2 element one, since it can't access the second array's third element. This works for the first case because of the comparing order, there wouldn't be any case where there is a 3 to 2 comparison, only a 2 to 3, which can be done, but in this case the second array's third element will not be take into account.
You have to modify your code to loop as many times only as minimum element count of the two arrays:
    for x := 0; x < int(math.Min(float64(len(matrix[i])), float64(len(matrix[j])))); x++ {
        if matrix[i][x] == matrix[j][x] {
            continue
        }
        return matrix[i][x] < matrix[j][x]
    }

But in this case it's not handled when there is more elements in any of the comparable arrays.


text:
Q: How to mask/change format of data in a view? Is there a inbuilt function that masks output data in a view?
For instance, if I gave the following string in a database
119902

and I want the output in a view to be something like
01.19-9/02

Is there a inbuilt function I could use to make the mask as ##.##-#/##?