text:
Q: Oracle: Index organised table with null values I have a table which is basically a tree structure with a column parent_id and id.
parent_id is null for root nodes.
There is also a self referential foreign key, so that every parent_id has a corresponding id.
This table is mainly read-only with mostly infrequent batch updates.
One of the most common queries from the application which accesses this table is select ... where parent_id = X. I thought this might be faster if this table was index organised on parent_id.
However, I'm not sure how to index organise this table if parent_id can be null. I'd rather not fudge things so that parent_id=0 is some special id, as I'd have to add dummy values to the table to ensure the foreign key constraints are satisfied, and it also changes the application logic.
Is there any way to index organise a table by possible null value columns?

A: Solution from question asker:
I found I could get the same benefits from index organisation just by adding the queried columns to the end of the parent_id index, i.e. instead of:
create index foo_idx on foo_tab(parent_id);

I do:
create index foo_idx on foo_tab(parent_id, col1, col2, col3);

Where col1, col2, col3 etc are frequently accessed columns.
I've only done this with indexes which are used to return multiple rows which benefit from the ordering and hence disk locality provided by the index, instead of having to jump around the table. Indexes which are generally used to return single rows I've left to reference the table, as there is only one row to read anyway so locality matters much less.
Like I mentioned, this is a mainly read table, and also space is not a huge concern, so I don't think the overhead to writes caused by these indexes is a big concern.
(I realise this won't index null parent_ids, but instead I've made another index on decode(parent_id, null, 1, null) which indexes nulls and only nulls).

A: I would try adding the index on the single column parent_id.
If all of the columns in your index are non-null, then this row does not appear in your index.
So for the parent_id = X you cite above, this should use the index. However, if you're doing parent_id is null, then it won't use the index, and you'll be getting the same performance as you have now. This sounds like behaviour that would suit you.
I have used this in the past to improve the performance of queries. It works particulalry well if the number of items in the index is small compared to the number of rows in the database. We had about 3% of our rows in this particular index, and it flew :-)
But, as always, you need to try it and measure the difference in performance. Your mileage may vary.


text:
Q: Using an asynchronous warning source for CodeMirror's lint feature The examples only show how to implement the JSON and Javascript lint addons with CodeMirror (syntax-highlighting Javascript-based editor), which are synchronous.
Unfortunately, there aren't Javascript-based parsers/lint'ers readily available for most languages. I'd like to implement my own linter for Python. Unfortunately, it seems as if the existing lint addon depends on the linter (which the lint plugin invokes) being synchronous.
angelozerr says that there is a "CodeMirror.remotingValidator" plugin located in remoting-lint.js, but Github show that this file was removed. marijnh says that it was removed because it was "not generally useful", but doesn't clarify any alternatives.
Is there a strategy for, somehow, calling the linter asynchronously, so that I can do an Ajax call in order to parse the code remotely?

A: Sure there is. A quick look through the contents of the last version of remoting-lint.js (https://github.com/marijnh/CodeMirror/commit/27f097ed75561e846bdb955f13f8dd2bcf0b589e) shows that it was little more than a jQuery AJAX request, which invokes a callback provided to the function as a parameter. This callback will only be passed if the "async" option is given to the lint plugin. Note that I have some options being passed-into CodeMirror that may not be relevant to you. The lint-related options are "gutters" and "lintWith".
Note that Python only presents one error at a time, but that the lint addon accepts a list of errors. Because of the former, the latter will only ever have one item, at most.
function python_validator(cm, updateLinting, options) {
    var text = cm.getValue() + "\n";

    if(text.trim() == "")
    {
        updateLinting(cm, []);
        return;
    }

    function result_cb(error)
    {
        var found = [];

        if(error != null) {
            var start_line = error.line_no;
            var start_char = error.column_no;
            var end_line = error.line_no;
            var end_char = error.column_no;
            var message = error.message;

            found.push({
                from: CodeMirror.Pos(start_line - 1, start_char),
                to: CodeMirror.Pos(end_line - 1, end_char),
                message: message
            });
        }

        updateLinting(cm, found);
    }

    check_python_syntax(text, result_cb)
};

var text_obj = $discriminator_text.get()[0];
var editor = CodeMirror.fromTextArea(text_obj, {
    mode: { name: "python",
            version: 2,
            singleLineStringErrors: false },
    lineNumbers: true,
    indentUnit: 4,
    tabMode: "shift",
    matchBrackets: true,
    styleActiveLine: true,
    lineWrapping: false,
    gutters: ["CodeMirror-lint-markers"],
    lintWith: {
        "getAnnotations": python_validator,
        "async" : true,
    },
});

I've posted a very simple project to make this a little more straightforward: https://github.com/dsoprea/CodeMirrorRemoteValidator

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pip Package: installs properly but cannot use any of its classes or methods even though it imports I am implementing a package that is to be installed via pip. It properly installs, and the library imports without errors, but I cannot seem to access any of the helper methods or classes in it.
I do not know how to go about debugging this. Here is the file structure:
data commons
-requirements.txt
-setup.py
-CHANGELOG
-dist
-MANIFEST
-README
--data_commons
---__init__.py
---postgres_conn.py
---redshift_conn.py
---url_helpers.py
---jobs
----__init__.py
----some_job.py
My current setup.py reads:
from distutils.core import setup

setup(
    name='data_commons',
    version='0.1.0',
    author='me',
    author_email='me@me.com',
    packages=['data_commons'],
    scripts=[],
    url='url',
    license='LICENSE.txt',
    description='Useful Helpers',
    long_description=open('README.md').read(),
    install_requires=[
        'boto==2.32.1',
        'psycopg2==2.5.3',
        'wsgiref==0.1.2',
    ],
)


text:
Q: Flash Actionscript 3.0: 1010 Error...not sure what I have not defined, not external classes Program objective:
To create slideshow that imports images and audio via xml, using Timer class to automatically advance both images and audio after 1sec.
What works:
The images work perfectly, traversing the xml tree.
What is broken:
After third call, program throws this error?
TypeError: Error #1010: A term is undefined and has no properties.
    at Chronic_fla::MainTimeline/playSong()
    at Chronic_fla::MainTimeline/timerListener()
    at flash.utils::Timer/_timerDispatch()
    at flash.utils::Timer/tick()
My question:
What is not defined? Do I have to explicitly declare something regarding my playSong function?
Or have I not imported a needed class?
Please help. I would greatly appreciated some insight.
Thanks!
Code:
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
import flash.text.TextField;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.utils.Timer;

var my_songs:XMLList;
var my_total:Number;
var my_sound:Sound;
var my_channel:SoundChannel;
var current_song:Number = 0;

var speed:Number;
var total:Number;
var images:XMLList;

var loaders_array:Array=[];
var labels_array:Array=[];
var success_counter:Number=0;
var playback_counter:Number=0;

var slideshow:Sprite = new Sprite();
var image_slides:Sprite = new Sprite();
var label_slides:Sprite = new Sprite();
var preloader:TextField;

var timer:Timer;
var prev_tween:Tween;
var tweens_array:Array=[];

var xml_loader:URLLoader = new URLLoader();
xml_loader.load(new URLRequest("slideshow2.xml"));
xml_loader.addEventListener(Event.COMPLETE, processXML);

function processXML(event:Event):void
{
var xml:XML=new XML(event.target.data);
speed=xml.@SPEED;
images=xml.IMAGE;
//my_songs=xml.@URL;

total=images.length();

loadImages();

xml_loader.removeEventListener(Event.COMPLETE, processXML);
xml_loader = null;
trace(xml);
//trace(xml.children()[0].attribute("URL"));
//trace(xml.children()[0].attribute("TITLE"));
}

function loadImages():void {
for (var i:Number = 0; i < total; i++) {
    var url:String=images[i].@URL;
    var loader:Loader = new Loader();
    loader.load(new URLRequest(url));
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
    loaders_array.push(loader);

    var label:TextField = new TextField();
    label.text=images[i].@TITLE;
    label.autoSize=TextFieldAutoSize.LEFT;
    labels_array.push(label);

    }

preloader = new TextField();
preloader.text="Loading";
preloader.autoSize=TextFieldAutoSize.CENTER;
    preloader.x = (stage.stageWidth - preloader.width)/2;
preloader.y = (stage.stageHeight - preloader.height)/2;
addChild(preloader);

}

function onComplete(event:Event):void {

success_counter++;
if (success_counter==total) {
    startShow();
    }

    var mloaderInfo:LoaderInfo=LoaderInfo(event.target);
mloaderInfo.removeEventListener(Event.COMPLETE, onComplete);

    }

function startShow():void {

removeChild(preloader);
preloader=null;

addChild(slideshow);
slideshow.addChild(image_slides);
slideshow.addChild(label_slides);

nextImage();

timer=new Timer(speed*1000);
timer.addEventListener(TimerEvent.TIMER, timerListener);
timer.start();

}

function nextImage():void {

var image:Loader=Loader(loaders_array[playback_counter]);
image_slides.addChild(image);
image.x = (stage.stageWidth - image.width)/2;
image.y = (stage.stageHeight - image.height)/2;
tweens_array[0]=new Tween(image,"alpha",Strong.easeOut,0,1,1,true);

var label:TextField=TextField(labels_array[playback_counter]);
label_slides.addChild(label);
label.x=image.x + 50;
label.y=image.y+image.height - 50;
label.border=true;
label.borderColor = 0x000000;
label.background=true;
label.backgroundColor = 0xFFFFFF;
label.textColor= 0xFF0000;
tweens_array[1]=new Tween(label,"alpha",Strong.easeOut,0,1,1,true);

}

function timerListener(event:TimerEvent):void {

hidePrev();

playback_counter++;
if (playback_counter==total) {
    playback_counter=0;
}
nextImage();

current_song++;

if (current_song==my_songs.length) {
    current_song=0;
}
else if (current_song!= 0) {
    playSong(current_song++);
}
}

function hidePrev():void {

var image:Loader=Loader(image_slides.getChildAt(0));
prev_tween=new Tween(image,"alpha",Strong.easeOut,1,0,1,true);
prev_tween.addEventListener(TweenEvent.MOTION_FINISH, onFadeOut);

var label:TextField=TextField(label_slides.getChildAt(0));
tweens_array[2]=new Tween(label,"alpha",Strong.easeOut,1,0,1,true);

}

function onFadeOut(event:TweenEvent):void {
image_slides.removeChildAt(0);
label_slides.removeChildAt(0);
}

var myXMLLoader:URLLoader = new URLLoader();
myXMLLoader.load(new URLRequest("playlist.xml"));
myXMLLoader.addEventListener(Event.COMPLETE, processMXML);

function processMXML(e:Event):void {
var myXML:XML = new XML(e.target.data);

my_songs = myXML.SONG;
my_total = my_songs.length();

playSong(my_songs.length);

myXMLLoader.removeEventListener(Event.COMPLETE, processMXML);
myXMLLoader = null;
trace(myXML);
}

function playSong(mySong:Number):void {
//var myTitle = my_songs[mySong].@TITLE;
//var myArtist = my_songs[mySong].@ARTIST;
var myURL = my_songs[mySong].@URL;

//title_txt.text = myTitle;
//artist_txt.text = myArtist;

if (my_channel) {
    my_channel.stop();
    //my_channel.removeEventListener(Event.SOUND_COMPLETE, onNext);
}

my_sound = new Sound();
my_sound.load(new URLRequest(myURL));
my_channel = my_sound.play();
//my_channel.addEventListener(Event.SOUND_COMPLETE, onNext);
}

A: In the timerListener() method, you're incrementing the current_song variable 2 times, so you're probably getting an index out of bounds error in playSong().
 function timerListener(event:TimerEvent):void {

    hidePrev();

    playback_counter++;
    if (playback_counter==total) {
       playback_counter=0;
    }
    nextImage();

    current_song++;

    if (current_song==my_songs.length) {
         current_song=0;
    }
    else if (current_song!= 0) {
         playSong(current_song); // that's where you incremented current_song again
    }
 }

A: Quite easy really, typed variable would throw a null error, untyped variables throw an undefined error. Look for the untyped variables in that function:
var myURL

Only one I see that can be undefined.
Turn it into:
var myURL:String

And you should get a null error instead.
How come all your other variables are typed and not this one? What's so special about this one that you decide to not type it?


text:
Q: sqlalchemy - double polymorphic inheritance problem I've got a class mapping with two polymorphic inheritance :
#test classes

class AbstractA(Base):

    __tablename__ = "abstract_a"

    id = Column(Integer, primary_key=True)
    class_name = Column('class_name', String(50))

    __mapper_args__ = {
      'polymorphic_on': class_name,
    }

#some stuff here

class AbstractB(AbstractA):

    __tablename__ = "abstract_b"

    id = Column(Integer, ForeignKey('abstract_a.id'), primary_key=True)
    class_name = Column('class_name', String(50))

    __mapper_args__ = {
      'polymorphic_on': class_name,
      'polymorphic_identity': __tablename__,
    }

#some stuff here

class ClassA(AbstractB):

    __tablename__ = "table_a"
    __mapper_args__ = {
      'polymorphic_identity': __tablename__,
    }

    id = Column(Integer, ForeignKey('abstract_b.id'), primary_key=True)
    label = Column('label', String(50))

    def __init__(self, label):
        self.label = label

I persist a ClassA object :
object = ClassA('toto')
db_session.add(object)
db_session.commit()

When I try to reload the object like this :
reloaded_object = AbstractB.query.first()

I get back a ClassA object (just fine)
but when I try to reload like this :
reloaded_object = AbstractA.query.first()

I get back a AbstractA object because abstract_a.class_name has not been set to polymorphic_identity.
Is this an issue or expected work?

A: Why do you need another discriminator for AbstractB subclasses instead of using single AbstractA.class_name for the whole inheritance tree? Just remove 2 lines from AbstractB definition and your test will work:
class AbstractB(AbstractA):

    __tablename__ = "abstract_b"

    id = Column(ForeignKey('abstract_a.id'), primary_key=True)

    __mapper_args__ = {
        'polymorphic_identity': __tablename__,
    }


text:
Q: RecyclerView messes up when scrolling I never asked any question before but hope you'll get my point.
I am making a chat app in which I am using a RecyclerView to show messages. The problem is when I scroll the RecyclerView some of the items disappear from the top and the whole items messes up when I try to add a message it doesn't even scroll to bottom nor added in the ListView.
Here is my RecyclerView:
<android.support.v7.widget.RecyclerView
    android:id="@+id/conversation_recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:layout_above="@id/typingConversationLayout"
    android:layout_below="@id/topLayout_conversation_activity"
    android:layout_marginBottom="-5dp"
    android:paddingBottom="7dp" />

Initializing and setting the RecycerView:
linearLayoutManager = new LinearLayoutManager(this);
    adapter = new ConversationRecyclerViewAdapter();
    conversationRecyclerView.setAdapter(adapter);
    conversationRecyclerView.setLayoutManager(linearLayoutManager);
    linearLayoutManager.setStackFromEnd(true);
    conversationRecyclerView.setHasFixedSize(true);
    conversationRecyclerView.setNestedScrollingEnabled(false);

Here is my Adapter class:
private class ConversationRecyclerViewAdapter
        extends RecyclerView.Adapter<ConversationRecyclerViewAdapter.ConversationViewHolder> {

    @NonNull
    @Override
    public ConversationViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {

        Log.d(TAG, "onCreateViewHolder: Users Find started");

        View conversationsView = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.layout_message_received, parent, false);

        return new ConversationViewHolder(conversationsView);
    }

    @Override
    public void onBindViewHolder(@NonNull final ConversationViewHolder holderConversation, int i) {
        Log.d(TAG, "onBindViewHolder: Users Find started at position is " + i);

        final int position = holderConversation.getAdapterPosition();

        if (mOwnUser_1.get(position)) {
            holderConversation.receivedMsgLayout.setVisibility(View.GONE);

            holderConversation.sentProfileImg.setImageResource(mUserProfileImg_2.get(position));
            holderConversation.sentMsg.setText(mUserText_3.get(position));

        } else {

            holderConversation.sentMsgLayout.setVisibility(View.GONE);

            holderConversation.receivedProfileImg.setImageResource(mUserProfileImg_2.get(position));
            holderConversation.receivedMsg.setText(mUserText_3.get(position));

        }

        Log.d(TAG, "onBindViewHolder: completed at " + position);

    }

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

    public class ConversationViewHolder extends RecyclerView.ViewHolder {

        RelativeLayout receivedMsgLayout, sentMsgLayout;
        EmojiTextView receivedMsg, sentMsg;
        CircleImageView receivedProfileImg, sentProfileImg;

        public ConversationViewHolder(@NonNull View v) {
            super(v);

            receivedMsgLayout = v.findViewById(R.id.received_message_layout);
            sentMsgLayout = v.findViewById(R.id.sent_message_layout);
            receivedMsg = v.findViewById(R.id.received_message_text);
            sentMsg = v.findViewById(R.id.sent_message_text);
            receivedProfileImg = v.findViewById(R.id.received_message_user__profile_image);
            sentProfileImg = v.findViewById(R.id.sent_message_user__profile_image);

        }
    }
}

Here I am adding data to ListView and displaying to the RecyclerView:
sendBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String msg = editText.getText().toString().trim();

            if (TextUtils.isEmpty(msg)) {

                editText.setError("Please add a message");
                editText.requestFocus();

            } else {
                Log.d(TAG, "onClick: send Btn ADDED TEXT.. ");

                mOwnUser_1.add(user);
                mUserProfileImg_2.add(image);
                mUserText_3.add(message);

                editText.setText("");
                editText.requestFocus();

                adapter.notifyItemInserted(mOwnUser_1.size());
                conversationRecyclerView.scrollToPosition(mOwnUser_1.size() - 1);

            }

        }
    });

I don't know what i am doing wrong but it does not seem to work as i wanted.
Update Code:
The three listviews:
private ArrayList<Boolean> mOwnUser_1 = new ArrayList<>();
private ArrayList<Integer> mUserProfileImg_2 = new ArrayList<>();
private ArrayList<String> mUserText_3 = new ArrayList<>();

And the way of adding data to adapter:
mOwnUser_1.add(true);
mUserProfileImg_2.add(R.drawable.boy);
mUserText_3.add(edittext.getText().toString().trim());
adapter.notifyItemInserted(mOwnUser_1.size());
conversationRecyclerView.scrollToPosition(mOwnUser_1.size() - 1);

My Whole Conversation Activity Class:
public class ConversationActivity extends AppCompatActivity {
private static final String TAG = "ConversationActivity";

private EditText editText;
private LinearLayout linearLayout;
private LinearLayoutManager linearLayoutManager;

private ImageView sendBtn;
private ImageView emojiImage;
private View rootView;
private Boolean popUpShown = false;
private Boolean micShown = false;
private ImageView micBtn;
private RelativeLayout micLayout;
private RecyclerView conversationRecyclerView;

// Array Lists for Find USERS
private ArrayList<Boolean> mOwnUser_1 = new ArrayList<>();
private ArrayList<Integer> mUserProfileImg_2 = new ArrayList<>();
private ArrayList<String> mUserText_3 = new ArrayList<>();

private ConversationRecyclerViewAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.d(TAG, "onCreate: started");
    super.onCreate(savedInstanceState);
    EmojiManager.install(new TwitterEmojiProvider());
    setContentView(R.layout.activity_conversation);

    editText = findViewById(R.id.conversationEditText);
    linearLayout = findViewById(R.id.optionsOther);
    emojiImage = findViewById(R.id.emojiIconOther);
    rootView = findViewById(R.id.root_view_conversation);
    micBtn = findViewById(R.id.microphoneBtn);
    micLayout = findViewById(R.id.microphoneLayout);
    conversationRecyclerView = findViewById(R.id.conversation_recyclerView);
    sendBtn = findViewById(R.id.sendBtnConversation);

    if (!(Build.VERSION.SDK_INT >= 21))
        findViewById(R.id.typingConversationLayout).setBackgroundResource(R.drawable.edit_text_conversation_background_below_api);

    sendBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String msg = editText.getText().toString().trim();

            if (TextUtils.isEmpty(msg)) {

                editText.setError("Please add a message");
                editText.requestFocus();

            } else {
                Log.d(TAG, "onClick: send Btn ADDED TEXT.. ");

                addData(true, R.drawable.boy0, msg);
            }

        }
    });

    initConversationArrayList();

}

private void addData(Boolean user, int image, String message) {

    mOwnUser_1.add(user);
    mUserProfileImg_2.add(image);
    mUserText_3.add(message);

    editText.setText("");
    editText.requestFocus();

    adapter.notifyItemInserted(mOwnUser_1.size());
    conversationRecyclerView.scrollToPosition(mOwnUser_1.size() - 1);

}

private void initConversationArrayList() {
    Log.d(TAG, "initConversationArrayList: created");

    mOwnUser_1.add(true);
    mUserProfileImg_2.add(R.drawable.boy0);
    mUserText_3.add("Hello How are you?");

    Log.d(TAG, "initConversationArrayList: completed");

    initConversationRecyclerView();

}

private void initConversationRecyclerView() {
    Log.d(TAG, "initConversationRecyclerView: started");

    linearLayoutManager = new LinearLayoutManager(this);
    adapter = new ConversationRecyclerViewAdapter();
    conversationRecyclerView.setAdapter(adapter);
    conversationRecyclerView.setLayoutManager(linearLayoutManager);
    linearLayoutManager.setStackFromEnd(true);
    conversationRecyclerView.setHasFixedSize(true);
    conversationRecyclerView.setNestedScrollingEnabled(false);

    Log.d(TAG, "initConversationRecyclerView: completed");
}

A: Currently I am also working on chat module, let me show you how am I doing this. I am going to show you in steps.
Step 1: make two separate layout for recyclerview items, one for message that has been sent from your side and one for message received from another side.
Step 2 : make two view holders to populate different layout according to your scenario, made in above step, like this:
public class ChatNewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Chat> chats;

public ChatNewAdapter(List<Chat> chats) {
    this.chats = chats;
}

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

    if (viewType == 0) {
        View viewSend = (View) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message_send, parent, false);
        return new ViewHolderSend(viewSend);
    } else {
        View viewReceive = (View) LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message_received, parent, false);
        return new ViewHolderReceive(viewReceive);
    }
}

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
    switch (holder.getItemViewType()) {
        case 0:
            ViewHolderSend viewHolderSend = (ViewHolderSend) holder;
            viewHolderSend.messageSend.setText(chats.get(position).getMessage());
            break;

        case 1:
            ViewHolderReceive viewHolderReceive = (ViewHolderReceive) holder;
            viewHolderReceive.messageReceived.setText(chats.get(position).getMessage());
            break;
    }
}

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

@Override
public int getItemViewType(int position) {
    if (chats != null && !chats.get(position).fromAdmin) {
        return 0;
    } else
        return 1;
}

class ViewHolderSend extends RecyclerView.ViewHolder {
    TextView messageSend;

    public ViewHolderSend(View itemView) {
        super(itemView);
        messageSend = (TextView) itemView.findViewById(R.id.messageSend);
    }
}

class ViewHolderReceive extends RecyclerView.ViewHolder {
    TextView messageReceived;

    public ViewHolderReceive(View itemView) {
        super(itemView);
        messageReceived = (TextView) itemView.findViewById(R.id.messageReceived);
    }
}

public int addMessages(Chat chat) {
    chats.add(chat);
    notifyDataSetChanged();
    return chats.size();
}

Step 3 : now in your activity:
public class Test extends AppCompatActivity {

RecyclerView chatList;
RecyclerView.LayoutManager mLayoutManager;
ChatNewAdapter adapter;
ImageView sendButton;
EditText messageEditText;
boolean keyboardUp = false;
boolean isRunning = false;
ArrayList<Chat> chats;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
    isRunning = true;
    setUpComponents();
}

public void setUpComponents() {
    chatList = (RecyclerView) findViewById(R.id.chat_list);
    chatList.setHasFixedSize(true);
    mLayoutManager = new LinearLayoutManager(this);
    chatList.setLayoutManager(mLayoutManager);
    messageEditText = (EditText) findViewById(R.id.messageText);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    sendButton = (ImageView) findViewById(R.id.send);

    adapter = new ChatNewAdapter(chats);
    chatList.setAdapter(adapter);
    chatList.scrollToPosition(chatList.getAdapter().getItemCount() - 1);

    messageEditText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (keyboardShown(messageEditText.getRootView())) {
                Log.d("keyboard", "keyboard UP");

                if (keyboardUp == false) {
                    if (chats.size() > 0)
                        chatList.smoothScrollToPosition(chats.size() + 1);
                    keyboardUp = true;
                }

            } else {
                Log.d("keyboard", "keyboard Down");
                keyboardUp = false;
            }
        }
    });

    sendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            final String message = messageEditText.getText().toString().trim();
            if (!message.equals("")) {
                Chat chat = new Chat();
                String name = message;
                chat.setMessage(name);
                messageEditText.setText("");
                adapter.addMessages(chat);
                chatList.scrollToPosition(chatList.getAdapter().getItemCount() - 1);

            } else {
                Log.d("sending message Error", "error fetching dates");
            }
        }
    });
}

private boolean keyboardShown(View rootView) {

    final int softKeyboardHeight = 100;
    Rect r = new Rect();
    rootView.getWindowVisibleDisplayFrame(r);
    DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
    int heightDiff = rootView.getBottom() - r.bottom;
    return heightDiff > softKeyboardHeight * dm.density;
}

And this is my model class, ignore @PrimaryKey and @Required annotation it just because I am using Realm for local DB. In your case you wont required these annotation.
public class Chat extends RealmObject {

@PrimaryKey
@Required
public Long id;
public boolean fromAdmin;
@Required
public String message;
public int type;
public boolean isRead;
public boolean isSent;
public Date date;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public boolean isFromAdmin() {
    return fromAdmin;
}

public void setFromAdmin(boolean fromAdmin) {
    this.fromAdmin = fromAdmin;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

public int getType() {
    return type;
}

public void setType(int type) {
    this.type = type;
}

public boolean isRead() {
    return isRead;
}

public void setRead(boolean read) {
    isRead = read;
}

public boolean isSent() {
    return isSent;
}

public void setSent(boolean sent) {
    isSent = sent;
}

public Date getDate() {
    return date;
}

public void setDate(Date date) {
    this.date = date;
}

I hope it will be helpful for you, you can ask further if you want to know anything else related to code.

A: RecyclerView as the name stands recycles the views. When binding data to a view, you need to ensure you set or reset all views that are touched in the adapter. Messups typically occur when there's data that is set only conditionally for some but not all items.
In particular:
if (mOwnUser_1.get(position)) {
    holderConversation.receivedMsgLayout.setVisibility(View.GONE);

    holderConversation.sentProfileImg.setImageResource(mUserProfileImg_2.get(position));
    holderConversation.sentMsg.setText(mUserText_3.get(position));

} else {

    holderConversation.sentMsgLayout.setVisibility(View.GONE);

    holderConversation.receivedProfileImg.setImageResource(mUserProfileImg_2.get(position));
    holderConversation.receivedMsg.setText(mUserText_3.get(position));

}

Both of these branches will need to reset the other layout back to visible.
Anyway with this kind of two-layout approach you are likely better off by having them as separate view types in your adapter. See How to create RecyclerView with multiple view type?


text:
Q: How to let the soft keyboard output from the Edittext which gets focus I make a soft keyboard in application. There are two edittext, click can get focus, but the soft keyboard can just output in the second edittext. Is there any way to l let the soft keyboard output from the Edittext which gets focus?

A: Remove android:focusable attribute, android:foucsableInTouchMode attribute and  tag in the XML file, Do it now, then
public class YOURMAINActivity extends Activity implements OnClickListener {

   private EditText editTxt1;
   private EditText editTxt2;

   @Override
   public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_id);
        editTxt1 = (EditText)findViewById(R.id.edit_text_one_id);
        editTxt2 = (EditText)findViewById(R.id.edit_text_two_id);
        editTxt1.setOnClickListener(this);
        editTxt2.setOnClickListener(this);

   @Override
   public void onClick(View view) {

       switch(v.getId()) {

           case R.id.R.id.edit_text_one_id :
                    editTxt1.requestFocus();
                    editTxt1.setFocusable(true);
                    editTxt2.setFocusable(false);
                    break;
           case R.id.R.id.edit_text_two_id :
                    editTxt2.requestFocus();
                    editTxt2.setFocusable(true);
                    editTxt1.setFocusable(false);
                    break;
       }
        // Add Code for Showing Keyboard Here
    }
}


text:
Q: Bootstrap/ASP.NET Core 3.1: Submit button does not update page immediately, but only every other time it is clicked I am very new to ASP.Net Core and web-app development, this is my first project.
I am trying to use a dropdown button that posts back onlick what button is pressed. Whatever is pressed is the action user want to do and I will update the displayed messages and labels in the webapp. Particularly I want to display a message with the action user chose using TempData, when the submit button is clicked. But the the message only shows up every other time.
Meaning it only shows up the 2nd, 4th, 6th.. time I press the submit button.
Here is the C# part of the code:
public class AdminModel : PageModel
    {

        [TempData]
        public string Action { get; set; } = "";
        [TempData]
        public string DisplayMessage { get; set; } = "";
        public string DropDownMessage = "Actions";
        public string ChangeValueLabel = "Set Point to";
        public string CurrentPoint = "No User Selected";
        public void OnGet()
        {

        }
        public IActionResult OnPost()
        {
            // Call ProcessSwipe here with student id from card reader
            return Page();
        }
        public IActionResult OnPostSubmit()
        {
            // Call ProcessSwipe here with student id from card reader

            DisplayMessage = $"Action done with {Action}";
            return Page();
        }
        public IActionResult OnPostCheckBalance()
        {
            DropDownMessage = "Check Point Balances";

            ChangeValueLabel = "No Input Needed";

            CurrentPoint = "99";

            Action = "CheckBalance";

            return Page();
        }
        public IActionResult OnPostIncreasePoint()
        {
            DropDownMessage = "Increase/Award Points";

            ChangeValueLabel = "Increase Point By";

            Action = "IncreasePoint";

            return Page();
        }
        public IActionResult OnPostDecreasePoint()
        {
            DropDownMessage = "Decrease/Redeem Points";

            ChangeValueLabel = "Decrease Point by";

            Action = "DecreasePoint";

            return Page();
        }
        public IActionResult OnPostSetPoint()
        {
            DropDownMessage = "Set Point Balances";

            ChangeValueLabel = "Set Point to";

            Action = "SetPoint";

            return Page();
        }
        public IActionResult OnPostDeleteAccount()
        {
            DropDownMessage = "Delete Account";

            ChangeValueLabel = "No Input Needed";

            Action = "DeleteAccount";

            return Page();
        }
    }

The HTML/Bootstrap part

Welcome to Learning Factory Admin Page

        @{
            if (TempData.Peek("DisplayMessage") != null)
            {

Message: @TempData.Peek("DisplayMessage")

            }
        }

                    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownActionMenu"
                            data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        @Model.DropDownMessage

                    </button>

                            <form asp-page-handler="CheckBalance" method="post">
                                <button class="btn btn-secondary" style="width:200px;" id="1" value="Check Point Balances">Check Point Balances</button>
                            </form>

                            <form asp-page-handler="IncreasePoint" method="post">
                                <button class="btn btn-secondary" style="width:200px;" id="2" value="Increase/Award Points">Increase/Award Points</button>
                            </form>

                            <form asp-page-handler="DecreasePoint" method="post">
                                <button class="btn btn-secondary" style="width:200px;" id="3" value="Decrease/Redeem Points">Decrease/Redeem Points</button>
                            </form>

                            <form asp-page-handler="SetPoint" method="post">
                                <button class="btn btn-secondary" style="width:200px;" id="4" value="Set Point Balance">Set Point Balance</button>
                            </form>

                            <form asp-page-handler="DeleteAccount" method="post">
                                <button class="btn btn-secondary" style="width:200px;" id="5" value="Delete Account">Delete Account</button>
                            </form>

                <form asp-page-handler="Submit" method="post">

                        Choose User Account to work on:
                        <input id="UIDSelect" name="UIDSelect" type="text" placeholder="934191061" />
                        Current Point total: @Model.CurrentPoint

                        @Model.ChangeValueLabel:
                        <input id="ChangeValue" name="ChangeValue" type="text" placeholder="Enter Value" />

                        <button class="btn btn-primary" ID ="6" type="submit">Submit</button>
                        <button class="btn btn-primary" type="reset">Reset</button>

                </form>

In the part of the code where I set DisplayMessage = $"Action done with {Action}";, the {Action} part of the message only appears every other click of the submit button, starting the second click. No message is shown on the first click.
The Action done with part of the message appears every time, except the first click.
Any help is appreciated.

A: Don't need to use TempData.Peek to get it, just use Model to get and display it.
And I advice you do not add form tags to each button in dropdown-menu, you just need to add the asp-page-handler attribute to the button, then place the submit's form tag outside all buttons.
Change page code like this:

Welcome to Learning Factory Admin Page

        @{
            if (Model.DisplayMessage != null)
            {

Message: @Model.DisplayMessage

            }
            @*if (TempData.Peek("DisplayMessage") != null)
            {

Message: @TempData.Peek("DisplayMessage")

            }*@
        }
    <form asp-page-handler="Submit" method="post">

                    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownActionMenu"
                            data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        @Model.DropDownMessage

                    </button>

                            <button class="btn btn-secondary" style="width:200px;" id="1" value="Check Point Balances" asp-page-handler="CheckBalance">Check Point Balances</button>

                            <button class="btn btn-secondary" style="width:200px;" id="2" value="Increase/Award Points" asp-page-handler="IncreasePoint">Increase/Award Points</button>

                            <button class="btn btn-secondary" style="width:200px;" id="3" value="Decrease/Redeem Points" asp-page-handler="DecreasePoint">Decrease/Redeem Points</button>

                            <button class="btn btn-secondary" style="width:200px;" id="4" value="Set Point Balance" asp-page-handler="SetPoint">Set Point Balance</button>

                            <button class="btn btn-secondary" style="width:200px;" id="5" value="Delete Account" asp-page-handler="DeleteAccount">Delete Account</button>

                    Choose User Account to work on:
                    <input id="UIDSelect" name="UIDSelect" type="text" placeholder="934191061" />
                    Current Point total: @Model.CurrentPoint

                    @Model.ChangeValueLabel:
                    <input id="ChangeValue" name="ChangeValue" type="text" placeholder="Enter Value" />

                    <button class="btn btn-primary" ID="6" type="submit">Submit</button>
                    <button class="btn btn-primary" type="reset">Reset</button>

    </form>

Here is the result:


text:
Q: Formatting Sum of negative value I am creating a report in SSRS. I want to sum a column and  change the color to red if value goes to negative. But my expression is not working. Here is my expression.
=IIF(SUM(Fields!Column.Value) < 0, "Red", "Black")

A: You need to put the expression in the font color and not the cell value.
To do this : right click on the cell you want the font color to change - text box properties - Font - click on the Fx next to the color and then place the expression
=IIF(SUM(Fields!Column.Value) < 0, "Red", "Black")

This will change the font color based on it's value


text:
Q: How to give an app access to Accounts that was previously denied? I've been playing with Accounts framework and during my tests I've denied the app access to Accounts. Now the following code returns Denied each time I run it.
[[self accountStore] requestAccessToAccountsWithType:twitterType options:nil completion:^(BOOL granted, NSError *error) {
    if (granted) {
        accounts = [[self accountStore] accountsWithAccountType:twitterType];
    } else if (error != nil) {
        NSLog(@"Failed to list Twitter accounts %@", error);
    } else {
        NSLog(@"Access denied");
    }
}];

What sucks is I have no clue where to reset it and googling doesn't help. I've seen how to fix it on iOS but I'm running a Mac app and the solution doesn't apply.
The Account Framework API documentation is not helpful at all.
Palm face.

A: Figured it out, I've found a file with my app id called "~/Library//Application Support/com.apple.TCC/TCC.db"
It's a sqlite3 file, so run sqlite3 "~/Library//Application Support/com.apple.TCC/TCC.db" then search for your app in "access" table, delete the row and should you have access again.
If that doesn't help there's also a file called ~/Library/Accounts/Accounts3.sqlite, there ZAUTHORIZATION table which includes your app.

A: The proposed solution no longer works, because of high-profile hacks made by big companies and others. This solution has never been supported and is an invitation to hackers. The right way to do this is using the tool provided by Apple: tccutil.
Thus, do the following:

*

*Open Terminal.

*Run tccutil reset <service> [bundle_id], in which <service> can be AddressBook or Calendar or All with the optional ID of the bundle you want to reset.

Example:
tccutil reset All com.apple.Terminal


text:
Q: Symfony2 validation doesn't work when Entity Relationships/Associations controller
public function indexAction(Request $request)
{
    $user = $this->container->get('security.context')->getToken()->getUser();
    $owner = $user->getId();

    $first = new First();
    $first->setOwner($owner);

    $second = new Second();
    $second->setOwner($owner);
    $second->setFirst($first);

    $form = $this->createForm(new SecondType(), $second);

    if ($request->getMethod() == 'POST') {
        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->get('doctrine')->getEntityManager();
            $em->persist($first);
            $em->persist($second);
            $em->flush();
        }
    }

    return $this->render('MySampleBundle:Home:index.html.twig', array(
        'form' => $form->createView(),
    ));

}

ORM Yaml
My\SampleBundle\Entity\First:
    type: entity
    table: first
    id:
        id:
            type: integer
            generator: { strategy: AUTO }
    fields:
        title:
            type: string
        date_created:
            type: datetime
        date_edited:
            type: datetime
        owner:
            type: integer
    lifecycleCallbacks:
        prePersist: [ prePersist ]
        preUpdate: [ preUpdate ]
    oneToMany:
        reviews:
            targetEntity: Second
            mappedBy: review

My\SampleBundle\Entity\Second:
    type: entity
    table: second
    id:
        id:
            type: integer
            generator: { strategy: AUTO }
    fields:
        review:
            type: string
        date_created:
            type: datetime
        date_edited:
            type: datetime
        owner:
            type: integer
    lifecycleCallbacks:
        prePersist: [ prePersist ]
        preUpdate: [ preUpdate ]
    manyToOne:
        first:
            targetEntity: First
            inversedBy: reviews
            joinColumn:
                name: first_id
                referencedColumnName: id

Form/Type
class FirstType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title', 'text');
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'My\SampleBundle\Entity\First',
        );
    }

    public function getName()
    {
        return 'first';
    }
}

class SecondType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('first', new FirstType());
        $builder->add('review', 'textarea');
    }

    public function getName()
    {
        return 'second';
    }
}

Validation.yml
My\SampleBundle\Entity\First:
    properties:
        title:
            - NotBlank: ~
            - MinLength: 2

My\SampleBundle\Entity\Second:
    properties:
        review:
            - NotBlank: ~
            - MinLength: 14

The created form works normally.
However, only the validation does not work normally.
If it performs individually, validation will work normally.
$form = $this->createForm(new FirstType(), $first);

However, if it is in a Entity Relationships/Associations state, the first validation will not work.The First's title property in one character will be registered.
How can I manage to achieve that?

A: Symfony 2.1+ doesn't automatically validate all the embedded objects. You need to put the Valid constraint on the first field to make it validate as well:
My\SampleBundle\Entity\Second:
    properties:
        first:
            - Valid: ~


text:
Q: Jquery compare 4000 values with 4000 checkbox values and check matches I've inherited some shoddy code. The main problem I'm having is that the browser (I'm using Chrome) may have to iterate through potentially thousands of values (it's unlikely but it could happen), compare these values to potentially thousands of checkbox values and check the ones that match (I know this is poor design). I've created a fiddle to illustrate with about 4000 values and checkboxes: http://jsfiddle.net/zargarf/LG83j/3/
function checkAppropriateCheckBoxes(divId, inputName) {
    var start = new Date().getTime();
        var val = $('#' + divId).prop('value');
    var boxes = $("input[name='" + inputName + "']");
        if (val != '') {
            var boxes=$("input[name='" + inputName + "']");
                $.each(val.split(",").slice(0, -1),
                    function(index, item) {
                        boxes.each(function() {

                            if ($(this).prop("value") == $.trim(item)) {
                                $(this).prop("checked", true);
                                return false;
                            }
                        });
                    });

        }
    alert((new Date().getTime() - start));
    }

  $('.selectAll').click(function(){
       $('#courses input:checkbox').prop('checked', true);
        return false;
    });
   $('.selectNone').click(function(){

       $('#courses input:checkbox').prop('checked', false);
   });

checkAppropriateCheckBoxes('sessionCourse', 'course');

The html structure is similar to below:

<input id="sessionCourse" type="hidden" value="2SFASSA08R/131401,6CDCNHA01R/131501,loads more comma separated values"/>

<input type="checkbox" name="course" id="cbcol-6EDEIPB01R/121401" value="6EDEIPB01R/121401">(AWE) BTEC L3 Diploma in Electrical/Electronic Engineering (6EDEIPB01R/121401)

repeated for a tonne of lines

Basically, it's taking over 20 seconds for the page to render and for the appropriate checkboxes to be checked. Basically when used in the proper application it is freezing an ajax waiting image while it's processing (not shown in the fiddle).
Do any of you have any ideas how to speed it up the iteration and to stop the browser from stopping a rotating image from spinning?
Thanks in advance for your help


text:
Q: Passing variable from .js file to google maps api v3 html I'm trying to show markers in google maps, but it's not working yet. I'm using node.js and express.
So here's my code
First the javascript function, which reads a set of locations from a file, and transforms the whole script
var readMonActual = function(){
  var coordsArray=fs.readFileSync("grd2google.txt", "utf8");
  var coordsArray=coordsArray.substring(1,coordsArray.length-1);
  var myCoords=[];
  data=coordsArray.split(',');
  for (var i=0;i<data.length;i+=3){
    myCoords.push([
                    Number(String(data[i]).replace(/\'/g, "")),
                    Number(String(data[i+1]).replace(/\'/g, "")),
                    Number(String(data[i+2]).replace(/\'/g, ""))
                  ]);
  }
  //return {myCoords:myCoords};
  return myCoords;
}

Then the function in the html file
function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(10.191, -68.192),
        zoom: 7,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
    var markers=readMonActual(); //<- this returns as undefined
    var marker = new Array();

    for(i=0; i< markers.length; i++ ) {
        var position = new google.maps.LatLng(parseFloat(markers[i][1]), parseFloat(markers[i][2]));
                new google.maps.Marker({
                position: position,
                map: map,
                title: String(markers[i][0])
                });
    }
}
google.maps.event.addDomListener(window, 'load', initialize);

The map loads, the .js script loads, but it still doesn't show the markers because the variable that contains the array comes back blank (even though a console.log() of the readMonActual function shows me the array with the locations)

A: This is being caused by the synchronous file process. initialize trying to use data that hasn't been returned yet. I've simplified the functions below a little to save some space. In short, pass a callback function into readMonActual that will return the markers once the file process is done.
function initialize() {
  // rest of codecode
  // pass in a callback to readMonActual
  readMonActual(function (markers) {
    for(i=0; i< markers.length; i++ ) {
      // do loop
    }
  });
}

var readMonActual = function (callback) {
  var coordsArray=fs.readFileSync("grd2google.txt", "utf8");
  var coordsArray=coordsArray.substring(1,coordsArray.length-1);
  var myCoords=[];
  // the rest of the code
  // return the markers via the callback
  callback(myCoords);
}


text:
Q: Native Date Picker in Html I used Datepicker plugin for getting Calendar in HTML. But my boss ordered me not to  t use any jquery plugins for date picker. He is saying that I must use native code only for date picker. It should work without Javascript also.
Is it possible to create native calendar in html ?
I know html5 supports native date picker; but that is not supported by all browsers.
Can i get native date picker as following style..?

A: "Native" and "without JavaScript" is where this idea will not work on older browsers. You could always create an HTML5 datepicker, and non-supportive browsers will fallback to a plain textbox. You could instruct the user to enter a date in MM/DD/YYYY format, and have this format applied by the datepicker, or by hand if the datepicker is unavailable.
This page offers some advice on the HTML5 datepicker: http://html5tutorial.info/html5-date.php
Edit: Alternatively, you could just create three dropdown menus and have the user select the month, day, and year. (Of course without JS in this case, you couldn't have the number of days in a month change with the user's choice, but you could always validate their input on the server.)

A:
You could instruct the user to enter a date in MM/DD/YYYY format, spryno724

This, a simple html5 placeholder (you can also style css placeholder) would suffice.
<input type='text' placeholder='dd/mm/yyyy' name='form[datetime]' id='datetime' />

A: why not make the jquery datepicker a fallback?
pseudocode:
if (! input.supports('date'))
    $(input).datepicker();

this way, you get a datepicker if your browser does not support the native one. That is exactly what jQuery's original 'unobtrusive' idea was.

A: Look at this simple Code.
You need to add 2 js files and 1 css file from net.. Don't worry,It is simple
Here it is

<!DOCTYPE html>
<html>
 <head>
  <title>Date</title>
  <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>
 </head>
 <body>
    <input type="text" id="dob" name="date" placeholder="MM/DD/YYYY"/>
   <script>
    $(document).ready(function(){
     var date_input=$('input[name="date"]');
     var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent() : "body";
     date_input.datepicker({
      format: 'dd/mm/yyyy',
      container: container,
      todayHighlight: true,
      autoclose: true,
     })
    })
   </script>
 </body>
</html>


text:
Q: ComboBox formatting I know this is probably a stupidly easy question to answer but I'm going to ask it anyways.
So I have a combobox that when it's got data in it looks like this

I want to know if there is any way to make the data look like this instead while still using only 1 combobox
John, Doe
Nickel, Back
etc...
Any help would be appreciated.

A: Create a class for Person with first name and last name, then override ToString() method to output the string as you need.
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public override string ToString()
    {
        return FirstName + ", " + LastName;
    }
}

Now, you can create a list of people and bind to DataSource of comboBox.
var people = new List<Person>
{
    new Person() { FirstName = "John", LastName = "Doe" },
    new Person() { FirstName = "Nickel", LastName = "Back" }
};
comboBox1.DataSource = people;


text:
Q: Google Chrome Ignoring too frequent calls to print()
Possible Duplicate:
JavaScript print blocked by Chrome, Workaround?

When I make 2 or more print() method calls in Google Chrome, the browser prevents the print() function in the latest version of Chrome.
This is the Error that I get in the console:

Ignoring too frequent calls to print().


text:
Q: generic binary search tree I'm working on a binary search tree console application, specifically, a method to list the shortest path between two target nodes.  My approach is to
1) Create an ArrayList of the values of each target node in the tree from the root node to the target (one ArrayList for each path)
2) Compare the two ArrayLists, removing all duplicates except the last one (which would represent where the two paths branch
3) combine the two remaining ArrayLists into a single array and print to console with a for loop
This is the method I'm working with.  The problem I'm having is that I'm never entering the block that reads "if (list1[n] == list2[n])", even though the ArrayLists are printing out with the values
Contents of _pathArrayList1:  5, 7, 9
Contents of _pathArrayList2:  5, 7, 9, 10, 12, 11
I tried typcasting, but that didn't help.
array<T>^ removeDuplicates(ArrayList^ list1, ArrayList^ list2)
{
    int forLoopCount;
    int i; // for loop iterator for this method
    Console::WriteLine(L"Contents of _pathArrayList1: ");
    for (i = 0; i < list1->Count; i++)
        Console::WriteLine(list1[i]);

    Console::WriteLine(L"Contents of _pathArrayList2");
    for (i = 0; i < list2->Count; i++)
        Console::WriteLine(list2[i]);

    // find out which array is the shortest; we need to use the shorter of the two
    if (list1->Count - list2->Count < 0)
        forLoopCount = list1->Count;
    else
        forLoopCount = list2->Count;
    Console::WriteLine("Value of forLoopCopunt is " + forLoopCount);
    array<T>^ combineArray = gcnew array<T>(forLoopCount);

    for (int n = 0; n < forLoopCount; n++)
    {
        Console::WriteLine(L"List1[n] = " + list1[n]);
        Console::WriteLine(L"list2[n] = " + list2[n]);

        if (list1[n] == list2[n])  // never entering this block of code
        {
            if (list2[n+1] == list1[n+1])
            {
                Console::WriteLine(L"Removing " + list1[n] + " and " + list2[n]);
                list1->RemoveAt(n);
                list2->RemoveAt(n);
                n --;
            }
            else
            {
                Console::WriteLine(L"Deleting " + list1[n]);
                list1->RemoveAt(n);
                //_pathArrayList1->Reverse();
                return combineArray = combineArrays(_pathArrayList1, _pathArrayList2);
            }
        }
    }
    return combineArray = combineArrays(_pathArrayList1, _pathArrayList2);
}

A: Please clarify "I tried typcasting, but that didn't help.".
ArrayList does not use generics, so it deals with everything as Objects. Even if the two objects are ints, when they're typed as Object, == won't compare the integer values as you expect.
Object^ o1 = 1;
Object^ o2 = 1;

bool asObject = (o1 == o2); // false
bool asInt = ((int)o1 == (int)o2); // true

If you switch out your ArrayList for List<int>, then == will work as you expect, with the added benefits of type-safety.
Other Notes:

*

*Use Math.Min when setting forLoopCount. If other people have to stop and think about it to figure out if the code is correct, for something that simple, use the function.

*Before checking if list2[n+1] == list1[n+1], make sure there's an extra item in both lists. In your example data (5-7-9 and 5-7-9-10-12-11), this will give you an exception when list1[n] is the 9.

*You can remove gcnew array<T>(forLoopCount), or even combineArray entirely. That object is getting thrown away when you assign the return value of combineArrays.

Edit
If the objects in the passed lists are the items themselves (not their node addresses, or something else that's always an int), then I'd recommend adding where T : IEquatable<T> to the generic definition. That gives you an Equals(T) method, and you can use that instead of ==, which isn't defined for all types. (If you implement this on your types, just be sure to implement all three methods Equals(T), Equals(object), and GetHashCode(), so that everything's consistent.)
To help with building the search tree in the first place, you may find IComparable<T> useful. Use the CompareTo method instead of the comparison operators (e.g., <).


text:
Q: API started, db killed, db started, peewee.InterfaceError connection already closed Starting app.py, then killing the database and hitting /api/foo gives me:

peewee.OperationalError: could not connect to server: Connection refused

Bringing the database back up gives me and hitting /api/foo gives me:

peewee.OperationalError: terminating connection due to administrator
  command\nSSL connection has been closed unexpectedly\n

And hitting /api/foo again gives me:

peewee.InterfaceError: connection already closed

Test case
test_case/__init__.py
#!/usr/bin/env python

from os import environ

from bottle import Bottle, request, response
from playhouse.db_url import connect

bottle_api = Bottle()
db = connect(environ['RDBMS_URI'])

from test_case.foo.models import Foo

db.connect()  # Not needed, but do want to throw errors ASAP
db.create_tables([Foo], safe=True)  # Create tables (if they don't exist)

from test_case.foo.routes import foo_api

bottle_api.merge(foo_api)

bottle_api.catchall = False

@bottle_api.hook('before_request')
def _connect_db():
    print 'Connecting to db'
    db.connect()

@bottle_api.hook('after_request')
def _close_db():
    print 'Closing db'
    if not db.is_closed():
        db.close()

def error_catcher(environment, start_response):
    try:
        return bottle_api.wsgi(environment, start_response)
    except Exception as e:
        environment['PATH_INFO'] = '/api/error'
        environment['api_error'] = e
        return bottle_api.wsgi(environment, start_response)

@bottle_api.route('/api/error')
def global_error():
    response.status = 500
    return {'error': (lambda res: res[res.find("'") + 1:res.rfind("'")])(
                      str(request.environ['api_error'].__class__)),
            'error_message': request.environ['api_error'].message}

test_case/__main__.py
from __init__ import bottle_api
# Or `from __init__ import bottle_api`; `from bottle import run`;
# Then `run(error_catcher, port=5555)`

bottle_api.run(port=5555)

test_case/foo/__init__.py
test_case/foo/models.py
from peewee import Model, CharField

from test_case import db

class Foo(Model):
    id = CharField(primary_key=True)

    class Meta(object):
        database = db

test_case/foo/routes.py
from bottle import Bottle
from playhouse.shortcuts import model_to_dict

from test_case.foo.models import Foo

foo_api = Bottle()

@foo_api.get('/api/foo')
def retrieve_foos():
    return {'foos': tuple(model_to_dict(foo) for foo in Foo.select())}

Github gist for easy cloning.

A: Update:
I believe the problem lies in how you've structured your imports and the way python loads and caches modules in sys.path.
I think that one of your modules is being imported and loaded twice and different parts of the codebase use different instances of the module.
Thus, the views in foo.routes, are using one instance of the database object, while the connection hooks are using another.
Instead of from __init__, what about trying from test_case import bottle_api? That is the one import statement that jumps out at me as a possible culprit.

I added the following to your code so I could run it from the command-line:
if __name__ == '__main__':
    api.run()

Then I made a request to /api/foo and saw some fake data. I stopped the Postgresql server and got this error:
Traceback (most recent call last):
  File "/usr/lib64/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/home/charles/tmp/scrap/bottlez/lib/python2.7/site-packages/bottle.py", line 979, in __call__
    return self.wsgi(environ, start_response)
  File "/home/charles/tmp/scrap/bottlez/lib/python2.7/site-packages/bottle.py", line 954, in wsgi
    out = self._cast(self._handle(environ))
  File "/home/charles/tmp/scrap/bottlez/lib/python2.7/site-packages/bottle.py", line 857, in _handle
    self.trigger_hook('before_request')
  File "/home/charles/tmp/scrap/bottlez/lib/python2.7/site-packages/bottle.py", line 640, in trigger_hook
    return [hook(*args, **kwargs) for hook in self._hooks[__name][:]]
  File "bt.py", line 31, in _connect_db
    db.connect()
  File "/home/charles/tmp/scrap/bottlez/src/peewee/peewee.py", line 2967, in connect
    self.initialize_connection(self.__local.conn)
  File "/home/charles/tmp/scrap/bottlez/src/peewee/peewee.py", line 2885, in __exit__
    reraise(new_type, new_type(*exc_value.args), traceback)
  File "/home/charles/tmp/scrap/bottlez/src/peewee/peewee.py", line 2965, in connect
    **self.connect_kwargs)
  File "/home/charles/tmp/scrap/bottlez/src/peewee/peewee.py", line 3279, in _connect
    conn = psycopg2.connect(database=database, **kwargs)
  File "/home/charles/tmp/scrap/bottlez/lib/python2.7/site-packages/psycopg2/__init__.py", line 164, in connect
    conn = _connect(dsn, connection_factory=connection_factory, async=async)
OperationalError: could not connect to server: Connection refused
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?
could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?

When I restarted the server and made a subsequent request I got a normal response with my test data.
So, in short, I'm not sure what I may be missing but the code seems to be working correctly to me.
Postgresql 9.4, psycopg2 2.6, python 2.7.9, peewee 2.6.0


text:
Q: Unknown web method When Making AJAX Call to WebMethod with ASP.NET I'm kinda new to using AJAX call to a WebMethod. I feel my Web Method logic is but maybe someone could help out here. I do get an unknown web method error when I log the AJAX response to the console. Below is my Web method and AJAX call code.
$("#btnLogin").click(function () {
    email = $("#txtEmailAddress").val();
    password = $("#txtPassword").val();

    //Create the login info object
    var loginInfo = {};
    //Set the object properties and value
    loginInfo.Email = email;
    loginInfo.Password = password;
    //Make the ajax call
    $.ajax({
         type: "POST",
         dataType: 'json',
         url: '<%=ResolveUrl("identicate.aspx/ValidateUsersToken") %>',
         data: '{loginInfo:' +  JSON.stringify(loginInfo) + '}',
         contentType: "application/json; charset=utf-8",
         success: function (data) {
             if (data.d == null || data.d == undefined)
             {
                 alert("Username or password not correct = " + data.d);
                 console.log(data);
                 console.log(loginInfo);
                 console.log(this.url);
             }
         },
         error: function (data) {
              console.log(data);
              console.log(loginInfo);
              console.log(this.url);
              alert(data.d);
         }
     });
});

And here's my web method
[WebMethod]
public static String ValidateUsersToken(iloginmodel loginInfo)
{
        //Variable to hold the user email address
        String email = string.Empty;
        //Get the connection string from config file
        String connectionString = iDbConfiguration.GetConnectionString();
        //Create the command text
        String commandText = "select Email, Password from VUser where Email = @Email & Password = @Password";
        //Create database connection object and open it
        using(SqlConnection loginConnection = new SqlConnection(connectionString))
        {
            //Set command paramters
            SqlCommand loginCommand = new SqlCommand(commandText, loginConnection);
            //Set command type to text
            loginCommand.CommandType = System.Data.CommandType.Text;
            //Add parameter to command
            loginCommand.Parameters.AddWithValue("Email", loginInfo.Email);
            loginCommand.Parameters.AddWithValue("@Password", loginInfo.Password);

            //Open the database connection
            try
            {
                loginConnection.Open();

                SqlDataReader loginReader = loginCommand.ExecuteReader();
                if(loginReader.HasRows)
                {

                    HttpContext.Current.Response.Write(loginReader.ToString());

                    while (loginReader.Read())
                    {
                        if (loginReader.HasRows)
                        {
                            email = loginReader["Email"].ToString();
                        }
                    }
                }
            }
            catch(SqlException sqlEx)
            {
                HttpContext.Current.Response.Write(sqlEx.Message);
            }
            finally
            {
                loginConnection.Close();
            }

        }
    return email;
}


text:
Q: Custom button not appearing on iOS device So I'm trying to implement a custom button in my iOS app to replace the default rounded rectangle button. Heres a code snippet:
UIImage *normalImage  = [[UIImage imageNamed:@"Images/whitebutton.png"] stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
UIImage *pressedImage = [[UIImage imageNamed:@"Images/bluebutton.png"]  stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];

[self.theButton setBackgroundImage:normalImage  forState:UIControlStateNormal];
[self.theButton setBackgroundImage:pressedImage forState:UIControlStateHighlighted];

When I run it in the simulator everything works fine, my custom button shows up. However, when I run it on my actual device the button just appears as the default one with no customisation at all. Anybody got any idea where I'm going wrong?

A: The iOS file system is case sensitive, unlike the sinulator's. I'd start by checking that "Images" directory.
(Quick test if I'm barking up the wrong tree: does the +imageNamed: call return nil?)

A: You should add whitebutton.png and bluebutton.png to your project. And call imageNamed:@"filename" not imageNamed:@"file path" . Also , when running on the simulator there is no problem with case sensitivity. On the device , you have to type the correct name of the file because it IS case sensitive.
Hope this helps.
Cheers,
George

A: Your resources are going to get flattened in your app bundle. Also, the filesystem on iOS is case sensitive while the filesystem on Mac OS X is case preserving, so make sure the actual filenames of your images are case-correct. If they are, just remove the Images/ prefix and it should work:
[UIImage imageNamed:@"bluebutton"];

Also, if the image is a png type, you don't need to specify the file extension with imageNamed:.

A: Use
[UIImage imageNamed:@"whitebutton.png"]

and
[UIImage imageNamed:@"bluebutton.png"]

Regardless of how you have it visually organized in Xcode, it all gets flattened in the bundle


text:
Q: behavior of C++ ofstream in the event of program crash I am trying to debug a run time error that is causing my program to freeze up in the middle of execution. I have created a logging system that writes a simple log text file during the course of execution.
I write information to the log file simply using an ofstream object's stream insertion (<<) operator with messages of std::string type.
void foo(){
// ... Code block 1 ...
// myLogger.Write (timestamp, "Code block1 successfully executed");
// ... Code block 2 ... PROGRAM FREEZE AND CRASH!
}

My question is this : Suppose my program freezes up, and I need to kill it's process from the Task Manager, can I trust my logging system to have reliably written all messages prior to the point of crash?
Or, in reference to the above mentioned code, if Code block2 causes my program to freeze up, can I trust that the "Code block1 successfully executed" message will in every case indeed show up in my log file?
P.S. I am on Windows, and the reason I feel concerned is I don't fully trust the OS behavior around file permissions in odd cases. My program does have read/write permission to the file, but I don't know what odd things can happen during crash. Maybe I am just paranoid, please tell me if so.
Is there a better way to detect what code block the crash happens in?

A:
"can I trust that the "Code block1 successfully executed" message will in every case indeed show up in my log file?"

No, you can't trust that anything is finally written to your log files, when that statement is executed, and your program actually is in some kind of exceptional state.
With a flush() call implied with the line to write, chances get better, but still won't be guaranteed. It depends on the exceptional condition your program has met.
Consider a case, your program crashes because of undefined behavior, that accidentally messed up something in the buffers or data used by your Logger class instance. Also if you've hit kind of out of memory conditions, no guarantees could be given for subsequently executed code, even if it was caught correctly.

Also note:
Synchronous flushing usually isn't wanted for logging systems in multithreaded application contexts. The synchronous call of flush() might change the actually applied threads' behavior, and hide/obfuscate race conditions, that would appear as soon logging is switched off.

A: If you want to be sure that your text has been written to the log file you need to use std::endl which performs a flush which writes any buffers used to the output device.
Eg:
std::cout << "write me!\n";  // no flush

std::cout << "write me!" << std::endl;  // buffer flushed


text:
Q: Only parameterless constructors and initializers are supported in LINQ to Entities parcelas = (from docuRec in Dados.DOCUREC
                        where docuRec.CODALUNO == codAluno && docuRec.CODESCOLA == codEscola &&
                            (configBoleto.DtVencimentoInicial >= (docuRec.VENCESP != null ?
                            new DateTime(docuRec.DTVENCIMENTO.Year, docuRec.DTVENCIMENTO.Month, docuRec.VENCESP.Value) :
                                docuRec.DTVENCIMENTO))
                        select docuRec);

Only parameterless constructors and initializers are supported in LINQ to Entities

Can anybody help me?

A: In L2E you must have all your entities defining at least one parameterless constructor. That's necessary because the serializer must create an instance of your object and it doesn't know what parameters to pass;
The serializer then sets each property individually.
My guess is that Dados.DOCUREC doesn't define such a constructor.


text:
Q: Java flood fill algorithm with different neighbourhood inside a grid First of all, I wanted to say that I'm not very experienced Java programmer but was forced to learn things very quickly by school assignment. The assignment is to create a grid inside which we have a simple image. When a cell inside an image is clicked, then it's flood filled. The program needs to allow for different type of neighbourhood (4, 6 or 8). I managed to create a program that allows the user to paint the inside the image with different neighbourhoods, however now I'm trying to adjust the program so it would allow the flood fill. My question is - how can I set the boundaries for flood fill? I know that I can set the boundaries based on the color - that's why my image is painted in red, while I was planning to do the filling in black. However, I have no idea how can I put a condition using the color value. I checked different isssues on the net but couldn't quite apply anything to my program.
Here's the code I'm using (just the class for paining):
    class MyCanvas extends JPanel implements MouseListener {

    private int x,y;
    ArrayList<Point> points = new ArrayList<Point>();
    ArrayList<Point> points2 = new ArrayList<Point>();

    @Override
    public void mouseClicked(MouseEvent e) {
    }
    @Override
     public void mouseEntered(MouseEvent e) {
      // TODO Auto-generated method stub

     }

     @Override
     public void mouseExited(MouseEvent e) {
      // TODO Auto-generated method stub

     }

     @Override
        public void mousePressed(MouseEvent e) {
            x = e.getX();
            y = e.getY();

            int xSiatki = x/20;
            int ySiatki = y/20;  //gets the rectangle coordinate of grid
            System.out.println("Siatka x: " + xSiatki + " " + "y: " + ySiatki );

            if(clickEight){
            points.add(new Point(xSiatki,ySiatki));
            }
            if(clickSix){
            points2.add(new Point(xSiatki,ySiatki));

            }
            repaint();

            }

     @Override
     public void mouseReleased(MouseEvent e) {
      // TODO Auto-generated method stub

     }

     @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            Krata(g2d);
            Rysunek(g2d);

            if (clickStart){
                Krata(g2d);
                Rysunek (g2d);
                repaint();
                points.clear();
                points2.clear();}

            if (clickEight){
                Krata(g2d);
                Rysunek (g2d);
                for(Point p: points) {
                    int x,y;
                    x = (int)p.getX();
                    y = (int)p.getY();
                drawEightFlood(g2d, x, y);}

           }
            if (clickSix){
                Krata(g2d);
                Rysunek (g2d);
                for(Point p: points2) {
                    int x,y;
                    x = (int)p.getX();
                    y = (int)p.getY();

                drawSixFlood(g2d, x, y);}

           }
        }

        private void drawEightFlood (Graphics2D g2d, int x, int y){

            g2d.setColor(Color.BLACK);
            g2d.fillRect (20*x, 20*y, 20, 20);
            g2d.fillRect (20*x, 20*(y+1), 20, 20);
            g2d.fillRect (20*(x+1), 20*y, 20, 20);
            g2d.fillRect (20*(x-1), 20*y, 20, 20);
            g2d.fillRect (20*x, 20*(y-1), 20, 20);
            g2d.fillRect (20*(x-1), 20*(y+1), 20, 20);
            g2d.fillRect (20*(x+1), 20*(y-1), 20, 20);
            g2d.fillRect (20*(x-1), 20*(y-1), 20, 20);
            g2d.fillRect (20*(x+1), 20*(y+1), 20, 20);

            drawEightFlood (g2d, 20*x, 20*(y+1));
            drawEightFlood (g2d, 20*(x+1), 20*y);
            drawEightFlood (g2d, 20*(x+1), 20*(y+1));
            drawEightFlood (g2d, 20*(x-1), 20*(y+1));
            drawEightFlood (g2d, 20*x, 20*(y-1));
            drawEightFlood (g2d, 20*(x-1), 20*(y-1));
            drawEightFlood (g2d, 20*(x-1), 20*(y-1));
            drawEightFlood (g2d, 20*(x-1), 20*y);

            }

        private void drawSixFlood (Graphics2D g2d, int x, int y){

            g2d.setColor(Color.BLACK);
            g2d.fillRect (20*x, 20*y, 20, 20);
            g2d.fillRect (20*x, 20*(y-1), 20, 20);
            g2d.fillRect(20*x, 20*(y+1), 20, 20);
            g2d.fillRect(20*(x+1), 20*(y-1), 20, 20);
            g2d.fillRect(20*(x+1), 20*y, 20, 20);
            g2d.fillRect(20*(x-1), 20*y, 20, 20);
            g2d.fillRect(20*(x-1), 20*(y+1), 20, 20);

            drawSixFlood (g2d, 20*x, 20*(y+1));
            drawSixFlood (g2d, 20*(x+1), 20*y);
            drawSixFlood (g2d, 20*(x-1), 20*(y+1));
            drawSixFlood (g2d, 20*x, 20*(y-1));
            drawSixFlood (g2d, 20*(x-1), 20*(y-1));
            drawSixFlood (g2d, 20*(x-1), 20*y);

        }

        public void Krata (Graphics2D g2d) {  //code for grid
        for(int i=0; i<54; i++) {
            for(int j=0; j<34; j++) {
                g2d.setColor(Color.BLACK);
                g2d.drawRect (20*i, 20*j, 20, 20);
            }
        }
        }

        public void Rysunek (Graphics2D g2d){  //code for the image
        for (int i=0; i<54;i++){
            for (int j=0; j<34; j++){
                if ((i == 0 || i == 53) && (j>12 && j<21 )){
                g2d.setColor(Color.RED);
                g2d.fillRect(20*i, 20*j, 20, 20);
        }
                if (((i>0 && i<11) || (i>42 && i<53)) &&(j == 13 || j == 20)){
                    g2d.setColor(Color.RED);
                g2d.fillRect(20*i, 20*j, 20, 20);
        }
                if ((i > 16 && i < 37) && (j == 7 || j == 20)){
                    g2d.setColor(Color.RED);
                    g2d.fillRect(20*i, 20*j, 20, 20);
            }

                if ((i > 10 && i < 17) && (j == (23-i))){
                    g2d.setColor(Color.RED);
                    g2d.fillRect(20*i, 20*j, 20, 20);
            }
                if ((i > 36 && i < 43) && (j == (i-30))){
                    g2d.setColor(Color.RED);
                    g2d.fillRect(20*i, 20*j, 20, 20);
            }
                if (((i > 10 && i < 17) || (i>36 && i<43)) && (j==23 || j==18)){
                    g2d.setColor(Color.RED);
                    g2d.fillRect(20*i, 20*j, 20, 20);
            }
                if ((i == 11 || i == 16 || i == 37 || i == 42) && (j>18 && j<23)){
                    g2d.setColor(Color.RED);
                    g2d.fillRect(20*i, 20*j, 20, 20);
            }

            }

    }
    }

}

A: The code you present is pretty incomprehensible (no comments, method-names in foreign language - i guess polish or sth like that, overall bad code style, etc.).I'd recommend painting to a BufferedImage instead of directly painting to the screen. This way you can easily check the color of single pixels or modify it or paint to the image and keep changes consistent:
int type = BufferedImage.TYPE_4BYTE_ABGR;
BufferedImage image = new BufferedImage(width , height , type);

Graphics g = image.getGraphics();
//draw stuff with g, just like in paintComponent(Graphics)
g.dispose();

//get color of pixel at (px , py)
Color c = new Color(image.getRGB(px , py));

//set color at pixel (px , py) to red
image.setRGB(px , py , Color.red.getRGB());


text:
Q: How i can display the value of suffix e+number in python? i'm trying to display the same original value (inverse of log )after taking the log based 10 as shown in the example, but i'm not able to display the original value, i have follow the answer there but its still not display it, i know its large value . is there away to display it? i'm using python 3.6
import math
a=2172533123329917620172861889109867406049975387320169322608751844460406222231626416365984808960
x=math.log10(a)
print(x) # result there is 93.33696640660276
y=10**x
print(y) #  result there is 2.1725331233299482e+93
print(y*10**93) # result there is 2.1725331233299483e+186

A: When using sympy, you can use arbitrary precision math:
>>> import sympy
>>> a = 2172533123329917620172861889109867406049975387320169322608751844460406222231626416365984808960
>>> x = sympy.log(a, 10)
>>> x
1 + log(217253312332991762017286188910986740604997538732016932260875184446040622223162641636598480896)/log(10)
>>> y = 10**x
>>> y
10**(1 + log(217253312332991762017286188910986740604997538732016932260875184446040622223162641636598480896)/log(10))
>>> y*10**93
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*10**(1 + log(217253312332991762017286188910986740604997538732016932260875184446040622223162641636598480896)/log(10))
>>> result = y*10**93
>>> result
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*10**(1 + log(217253312332991762017286188910986740604997538732016932260875184446040622223162641636598480896)/log(10))
>>> result.simplify()
2172533123329917620172861889109867406049975387320169322608751844460406222231626416365984808960000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

A: You can use string formating - '{:f}'
print('{:f}'.format(y))
print('{:f}'.format(y*10**93))

Result:
2172533123329948244974667712184302503862484572004323002958790801469409104613465879037786193920.000000
2172533123329948250187989505303380345960860577775669342927459052809311382170807040229342819817270425458795653742290299639999303458637786346385752271584468621244918497826695717627392688128.000000

To remove zeros after dot - '{:.0f}'
print('{:.0f}'.format(y))
print('{:.0f}'.format(y*10**93))

Result:
2172533123329948244974667712184302503862484572004323002958790801469409104613465879037786193920
2172533123329948250187989505303380345960860577775669342927459052809311382170807040229342819817270425458795653742290299639999303458637786346385752271584468621244918497826695717627392688128

To display with e - '{:e}'
print('{:e}'.format(x))

Result:
9.333697e+01

More about string formating on pyformat.info

Code:
import math

a = 2172533123329917620172861889109867406049975387320169322608751844460406222231626416365984808960
x = math.log10(a)
y = 10**x

print('{:e}'.format(x))
print('{:.0f}'.format(y))
print('{:.0f}'.format(y*10**93))

A: As furas says, if you want to avoid the "engineering notation" when printing the result specify a precision in the format string.
If, however, you want a higher precision for the calculation you can use the decimal library:
from decimal import Decimal, getcontext

a = Decimal(2172533123329917620172861889109867406049975387320169322608751844460406222231626416365984808960)

# Increase the precision
getcontext().prec = 100

x = a.log10()
y = 10 ** x
print(y)

A: thank you everybody for perfect answers. the final code as shown below
from decimal import Decimal, getcontext

a = Decimal(2172533123329917620172861889109867406049975387320169322608751844460406222231626416365984808960)

# Increase the precision
getcontext().prec = 100

x = a.log10()
y = 10 ** x
print(y)
print('{:.0f}'.format(y))


text:
Q: Why is "Saturday" Romanic? Sunday and Monday are named after the sun and moon (English < Germanic), and Tuesday through Friday are named after Anglo-Saxon/Germanic gods.  This seems consistent enough so far, but then we come to the oddbal;: Saturday.
Ignoring the mandatory -day, this is the only Latin-derived name of the lot.  Why are six of the week-day names Germanic and one Romanic?

A: The names of the week were originally Roman according to the Oxford English Dictionary:

The Latin days of the week in imperial Rome were named after the planets, which in turn were named after gods (see discussion at week n.). In most cases the Germanic names have substituted for the Roman god's name that of a comparable one from the Germanic pantheon, but in the case of Saturday, the Roman name was retained and borrowed.

For example, Tuesday was originally named after Mars, but then switched to Tiw:

Originally cognate with or formed similarly to Old Frisian tīesdei , Old High German ziestag , Middle High German zīstag (German regional (south-eastern) Ziestag , (south-eastern and Swiss) Ziestig ) < the genitive of the Germanic base of the name of (the god) Tiw (see note) + the Germanic base of day n., after post-classical Latin dies Martis day of (the planet) Mars (4th cent. but probably earlier; frequently from c1135 in British sources; compare classical Latin Martis diēs

When the days were renamed, Mars was equivalent to Tiig (Tiw):

eOE    Corpus Gloss. 76/2   Mars, martis, tiig.

The OED also notes that the Germanic people would have originally used the Roman names, but then subsequently changed them (by Old English, Mars didn't factor into Tuesday at all):

The English names, Sunday, Monday, etc., belong to an astrological week which, quite independently of the Jewish–Christian week, arose from the practice of assigning the successive hours to the seven planets in the order of their distance, and then naming each whole day (of 24 hours) from the planet supposed to rule its first hour. The planetary names, Dies Solis, Dies Lunæ, Dies Martis, etc., came into common use in the Roman empire, and were adopted in translated form by the English (before they came to Britain) and other Germanic peoples; the names Mars, Mercurius, etc., being apprehended as names of Roman gods, were rendered by the names of the Teutonic deities supposed to correspond to these

There is no further note on why Saturday was allowed to remain a reference to Saturn, however.

A: Most likely, "Saturn" was retained as a solution for the problems that arose when Germans tried to translate the seven day week.
First, the tradition of a seven-day workweek, with all weekdays being named after planets, was adopted by Northern Europe from the Mediterranean Latin and Greek cultures;   that's a pretty straightforward matchup:  Thor was Saturn, Tyr/Tiu was Mars, Odin was Jupiter, Freyja was the personification of Venus, Sunna was the personification of the Sun, and Mani was the personification of the Moon.
This is all largely the same as in the Latinized week, and you can see it pretty easily in French (or any other Romance language): "Lundi" is "Luna's Day", "Mardi" is "Mars' day", "Mercredi" is "Mercury's day", "Jeudi" is "JUpiter's day", and "Vendredi" is "Venus' day";  today, the remaining words are "Samedi" (a corruption of "Sabbath", "Sabato" in Italian) and "Dimanche" ("Domenica" in It., or "Holy Day"), but these are Christian imports.   The words for these days were originally, in Latin, just as they are in English, today:  "Sunday" was "Dies Solis", or "Day of the Sun", and "Saturday" was "Dies Saturni", or "Day of Saturn".
What should be obvious from the above is that the Norse didn't just transliterate the days of the week in perfect order, but adapted them according both to the characteristics of their gods as well as to the order in which the planets were named in the Latin/Greek tradition.  Largely, the order was preserved, but one important substitution was made:  Mercury, being the planet of the god Loki, the great traitor and progenitor of all evil, dropped out.  Thus, Jupiter shifted forward to take its place as "Wodin's Day", as did Saturn/Thor for the fourth day, making "Thor's Day".
So -- how did the one Latinized form, Saturn, creep its way into English?  Because there were only five planets back then, and Mercury/Loki, the traitor, wasn't something the Norse much wanted to use in their day-to-day time-telling.  So that left four planets (Venus, Mars, Jupiter, Saturn), + Sun & Moon.  One day was left over.  Some word was needed to fill it.
Presumably, Mercury was out regardless of what name it used (i.e. -- the Norse didn't want to use the word in any language, even a foreign one), so which other planet should double up?  "Saturn" was a word that represented time itself (going back to the Greco-Roman tradition of Kronos/Saturn), and was a deity whose characteristics and qualities didn't correspond to any other in the Norse pantheon.  Further, it doubled up on Thor, who was a beloved deity to the Norse and the great hero-leader/tragic figure of the entire pantheon.  Finally, since "Thor" and "Saturn" sounded completely different, there was no reason to even bother with inventing a new word:  "Saturn's Day" could just remain in place, without bothering to change a thing. Thus, Saturday stuck.
Long story short:  we can't really be sure of the exact mechanisms, but this is probably something close to how it happened.

A: Interpretatio germanica is the practice by the Germanic peoples of identifying the Roman gods with the names of Germanic deities. This started to occur around the 1st century CE when both cultures came into closer contact. This is thought to be the mechanism by which the Roman names for the days of the week.
So the problem with this interpretation of the translated days of the week, according to Rudolf Simek, is that while the correspondence between Jupiter and Thor is fairly obvious, (what with the thunder and the lightning and whatnot) for the other figures we must rely on speculation as too little is known about the role the gods played in the then-contemporary beliefs of the Germanic people.
However, Tacitus said that the Rhineland tribes chiefly worshipped Mercury. Jonas of Babbio writing in The Life of Columbanus around 642 CE identified Mercury with Woden. It's unclear whether the Anglo-Saxons regarded Woden as their "chief" deity at the time, or if they picked that up from the invading Danes who held Óðinn as the king of the gods.
So although we don't necessarily know precisely why some particular Germanic gods were identified with other Roman deities, it is fairly evident they were and the days of the week were translated. But the question remains, why did Saturday stick around? Why wasn't a substitution made for that day? Many other languages made substitutions for the Hebrew sabbath, but not Old English.
There's an old Anglo-Saxon poem Solomon and Saturn which is basically a "riddle contest" between the wisest king of the land of Israel and the Roman god, done in the style of Norse poetic eddas. I haven't been able to pin down when it was written, I think in the 9th or 10th centuries. So I take this as some evidence that Saturn wasn't lost to Anglo-Saxon folklore. In the poem, he represented the pagan and eastern tradition, held in contrast to the Christian tradition and faith represented by Solomon. So perhaps this is a case where the name of saturday didn't really change because Saturn wasn't an obscure foreign god, but rather a well-known (although still foreign) entity from folklore.
I don't think anyone knows for sure why Saturday "stuck" while the other days were transformed in Old English. We can only speculate.
EDIT
OK, I've unearthed another interesting tidbit. In Anglo-saxon, Saturday is Sæterdæg or Sæterndæg. The word sætere means "setter", "seducer" or "insidiator". Coincidence? I've seen various sources that say Sætere was worshipped as a "shadowy" Anglo-Saxon deity (not sure about the reliability of these sources), and/or the name was associated with Loki, who was well known as being the trickster.
Of course, this begs the question: was the word sætere coined from Saturn in early germanic history? Was it a coincidence that saturn's day sounded like a nickname for Loki and thus the Latin name for Saturday needed to be only marginally changed to fit the german pantheon? Or did the early anglo-saxons just keep the Roman name for the day virtually unchanged?
And then there's the Norse god Surtr … but let's not muddy the waters any more…
I'm really not enough of a historian or etymologist to know. ;)


text:
Q: How can I see the SQL statements which go to the database when using PDO? How can I see the SQL statements which go to the database when using PDO?

A: I don't know how to do this with bare PDO, but if you wrap PDO in a Zend_Db_Adapter, then you can use Zend_Db_Profiler.
Then you'll be able to see the parameterized queries, together with the parameter values. Also, its profiling, i.e. measuring the query execution times.

A: If you are using MySQL, enable the query log?


text:
Q: ASP.NET User Control : can't initialize a user control property using Eval("...") I designed a user control. It contains a public property "CurrentValue".
When I try to initialize the property using an Eval expression, a null value is assigned.
// In below code, label assignment is OK, RatingNull user control assignment get null
<asp:TemplateField>
    <ItemTemplate>
        <asp:Label ID="Label1" runat="server" Text='<%# Eval("Difficulty") %>'
        <uc1:RatingNull ID="RatingNull1" runat="server" CurrentValue='<%# Eval("Difficulty") %>' />
    </ItemTemplate>

If I directly assigned a value (ie, CurrentValue="5"), user control works fine.
public partial class RatingNull : System.Web.UI.UserControl
{
    private string _CurrentValue;

    public string CurrentValue
    {
        get { return _CurrentValue; }
        set { _CurrentValue = value; }
    }
    (...)
}

A: The following code works for me. When do you use _CurrentValue field?
UserControl
public partial class Test1 : System.Web.UI.UserControl
{

    public string CurrentValue
    {
        get { return (string)ViewState["CurrentValue"] ?? string.Empty; }
        set { ViewState["CurrentValue"] = value; }
    }

    protected override void Render(HtmlTextWriter writer)
    {
        base.Render(writer);

        writer.Write(this.CurrentValue);
    }

}

Page
protected void Page_Load(object sender, EventArgs e)
{
    var ds = new[]
    {
        new { FirstName = "F1", LastName = "L1" },
        new { FirstName = "F2", LastName = "L2" },
    };

    DataList1.DataSource = ds;
    DataList1.DataBind();
}

Html Markup
<asp:DataList ID="DataList1" runat="server">
    <ItemTemplate>
        <uc1:Test ID="Test1" runat="server" CurrentValue='<%# Eval("FirstName") %>' />
    </ItemTemplate>
</asp:DataList>


text:
Q: Как сделать так, чтобы программа последовательно проверяла слова на наличие и удаляла их из строки? Алгоритм примерно такой:
Допустим у нас есть строка:
Строка: "Бутылка Маша Таня пенёк Маша"
удалить слово "бутылка", если оно есть
затем удалить слово "Маша", если оно есть(только то слово, которое попалось первым)
удалить слово "пенёк", если оно есть
удалить слово "Маша", если оно есть
То есть программа должна удалять заданное одно слово, если оно есть, а не все подобные слова сразу(в данном случае не все слова Маша сразу)

A: Метод String.replaceFirst() заменяет только первый найденный результат:
text = text.replaceFirst("Маша", "");


text:
Q: sudo apt update error: No module named JSON Im not sure why i'm getting the following error
Traceback (most recent call last):
  File "/usr/lib/cnf-update-db", line 8, in <module>
    from CommandNotFound.db.creator import DbCreator
  File "/usr/lib/python3/dist-packages/CommandNotFound/db/creator.py", line 4, in <module>
    import json
ModuleNotFoundError: No module named 'json'
Reading package lists... Done
E: Problem executing scripts APT::Update::Post-Invoke-Success 'if /usr/bin/test -w /var/lib/command-not-found/ -a -e /usr/lib/cnf-update-db; then /usr/lib/cnf-update-db > /dev/null; fi'
E: Sub-process returned an error code

when running a simply sudo apt update

A: Looks like a badly built package (assuming that json is installed on the user's system when it is actually outside the standard library).
You can use pip to globally install json: just write pip install json. You may need to install pip separately.