Programs & Examples On #Textchanged

An event that occurs when the text/content of a UI element has changed.

React Native TextInput that only accepts numeric characters

Using a RegExp to replace any non digit. Take care the next code will give you the first digit he found, so if user paste a paragraph with more than one number (xx.xx) the code will give you the first number. This will help if you want something like price, not a mobile phone.

Use this for your onTextChange handler:

onChanged (text) {
    this.setState({
        number: text.replace(/[^(((\d)+(\.)\d)|((\d)+))]/g,'_').split("_"))[0],
    });
}

Custom Listview Adapter with filter Android

If you want to achieve filtering with custom model class in kotlin then you can implement below code.

Step 1: Add SearchView in your xml file and then in your activity or fragment implement SearchView.OnQueryTextListener

class SearchActivity : AppCompatActivity(),SearchView.OnQueryTextListener {


    lateinit var sectionModelArrayList: ArrayList<CategorySectionModel>
    lateinit var filteredArrayList: ArrayList<CategorySectionModel>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_category_updated)
        searchView.setOnQueryTextListener(this)
    }


    //Called this method with you own data to populate the recycler view.
    private fun parseJson() {
        rv_category_list.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        adapter = CategoryLabelAdapter(sectionModelArrayList, this)
        rv_category_list.adapter = adapter
    }

    override fun onQueryTextSubmit(query: String?): Boolean {
        return false
    }

    override fun onQueryTextChange(newText: String?): Boolean {
        adapter.filter!!.filter(newText.toString())
        return false
    }

My model class CategorySectionModel looks like

class CategorySectionModel(val categoryLabel: String, val categoryItemList: ArrayList<CategoryItem>)

Now we have to work on adapter class and there you need to implement Filterable interface and override getFilter() method like below

class CategoryLabelAdapter(internal var data: ArrayList<CategorySectionModel>?, internal var activity: Context) : RecyclerView.Adapter<CategoryLabelAdapter.ViewHolder>(), Filterable {
    val originalList = data
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.item_category_name, parent, false)
        return ViewHolder(v)
    }

    override fun getItemCount(): Int {
        return data!!.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        data?.get(position)?.let { holder.bindItem(it) }
    }


    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        @SuppressLint("SetTextI18n")
        fun bindItem(data: CategorySectionModel) {
            itemView.tv_category_name.text = data.categoryLabel
        }
    }

    override fun getFilter(): Filter? {
        return object : Filter() {
            override fun performFiltering(constraint: CharSequence): FilterResults {
                val results = FilterResults()
                if (constraint.isEmpty()) {
                    //no filter implemented we return full list
                    results.values = data
                    results.count = data!!.size
                } else {
                    //Here we perform filtering operation
                    val list: ArrayList<CategorySectionModel> = ArrayList()
                    for (p in data!!) {
                        if (p.categoryLabel.toUpperCase().startsWith(constraint.toString().toUpperCase())) list.add(p)
                    }
                    results.values = list
                    results.count = list.size
                }
                return results
            }

            override fun publishResults(constraint: CharSequence, results: FilterResults) {
                // Now we have to inform the adapter about the new list filtered
                if (results.count == 0 || constraint == "") {
                    data = originalList
                    notifyDataSetChanged()
                } else {
                    data = results.values as ArrayList<CategorySectionModel>?
                    notifyDataSetChanged()
                }
            }
        }
    }
}

Convert Text to Uppercase while typing in Text box

if you can use LinqToObjects in your Project

private YourTextBox_TextChanged ( object sender, EventArgs e)
{
   return YourTextBox.Text.Where(c=> c.ToUpper());
}

An if you can't use LINQ (e.g. your project's target FW is .NET Framework 2.0) then

private YourTextBox_TextChanged ( object sender, EventArgs e)
{
   YourTextBox.Text = YourTextBox.Text.ToUpper();
}

Why Text_Changed Event ?

There are few user input events in framework..

1-) OnKeyPressed fires (starts to work) when user presses to a key from keyboard after the key pressed and released

2-) OnKeyDown fires when user presses to a key from keyboard during key presses

3-) OnKeyUp fires when user presses to a key from keyboard and key start to release (user take up his finger from key)

As you see, All three are about keyboard event..So what about if the user copy and paste some data to the textbox?

if you use one of these keyboard events then your code work when and only user uses keyboard..in example if user uses a screen keyboard with mouse click or copy paste the data your code which implemented in keyboard events never fires (never start to work)

so, and Fortunately there is another option to work around : The Text Changed event..

Text Changed event don't care where the data comes from..Even can be a copy-paste, a touchscreen tap (like phones or tablets), a virtual keyboard, a screen keyboard with mouse-clicks (some bank operations use this to much more security, or may be your user would be a disabled person who can't press to a standard keyboard) or a code-injection ;) ..

No Matter !

Text Changed event just care about is there any changes with it's responsibility component area ( here, Your TextBox's Text area) or not..

If there is any change occurs, then your code which implemented under Text changed event works..

android on Text Change Listener

We can remove the TextWatcher for a field just before editing its text then add it back after editing the text.

Declare Text Watchers for both field1 and field2 as separate variables to give them a name: e.g. for field1

private TextWatcher Field_1_Watcher = new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void afterTextChanged(Editable s) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

};

then add the watcher using its name: field1.addTextChangedListener(Field_1_Watcher) for field1, and field2.addTextChangedListener(Field_2_Watcher) for field2

Before changing the field2 text remove the TextWatcher: field2.removeTextChangedListener(Field_2_Watcher) change the text: field2.setText("")

then add the TextWatcher back: field2.addTextChangedListener(Field_2_Watcher)

Do the same for the other field

Android sqlite how to check if a record exists

you can also see this:

if (cursor.moveToFirst()) {
// record exists
} else {
// record not found
}

OR

You just check Cursor not null after that why you check count not 0.

So, that you try this...

DBHelper.getReadableDatabase();

Cursor mCursor = db.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE    yourKey=? AND yourKey1=?", new String[]{keyValue,keyvalue1});

if (mCursor != null)
{
            return true;
/* record exist */
 }
else
{
        return false;
/* record not exist */
}

Regex that accepts only numbers (0-9) and NO characters

Your regex ^[0-9] matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $ to the end:

^[0-9]*$

This accepts any number of digits, including none. To accept one or more digits, change the * to +. To accept exactly one digit, just remove the *.

UPDATE: You mixed up the arguments to IsMatch. The pattern should be the second argument, not the first:

if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))

CAUTION: In JavaScript, \d is equivalent to [0-9], but in .NET, \d by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9] (or supply the RegexOptions.ECMAScript flag).

runOnUiThread in fragment

Try this: getActivity().runOnUiThread(new Runnable...

It's because:

1) the implicit this in your call to runOnUiThread is referring to AsyncTask, not your fragment.

2) Fragment doesn't have runOnUiThread.

However, Activity does.

Note that Activity just executes the Runnable if you're already on the main thread, otherwise it uses a Handler. You can implement a Handler in your fragment if you don't want to worry about the context of this, it's actually very easy:

// A class instance
private Handler mHandler = new Handler(Looper.getMainLooper());

// anywhere else in your code
mHandler.post(<your runnable>);
// ^ this will always be run on the next run loop on the main thread.

EDIT: @rciovati is right, you are in onPostExecute, that's already on the main thread.

C# winforms combobox dynamic autocomplete

I've found Max Lambertini's answer very helpful, but have modified his HandleTextChanged method as such:

    //I like min length set to 3, to not give too many options 
    //after the first character or two the user types
    public Int32 AutoCompleteMinLength {get; set;}

    private void HandleTextChanged() {
        var txt = comboBox.Text;
        if (txt.Length < AutoCompleteMinLength)
            return;

        //The GetMatches method can be whatever you need to filter 
        //table rows or some other data source based on the typed text.
        var matches = GetMatches(comboBox.Text.ToUpper());

        if (matches.Count() > 0) {
            //The inside of this if block has been changed to allow
            //users to continue typing after the auto-complete results
            //are found.
            comboBox.Items.Clear();
            comboBox.Items.AddRange(matches);
            comboBox.DroppedDown = true;
            Cursor.Current = Cursors.Default;
            comboBox.Select(txt.Length, 0);
            return;
        }
        else {
            comboBox.DroppedDown = false;
            comboBox.SelectionStart = txt.Length;
        }
    }

How to filter data in dataview

Eg:

Datatable newTable =  new DataTable();

            foreach(string s1 in list)
            {
                if (s1 != string.Empty) {
                    dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
                    foreach(DataRow dr in dvProducts.ToTable().Rows)
                    {
                       newTable.ImportRow(dr);
                    }
                }
            }
ListView1.DataSource = newTable;
ListView1.DataBind();

java.lang.RuntimeException: Unable to start activity ComponentInfo

It was my own stupidity:

java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());

Putting this inside onCreate() method fixed my problem.

how to get html content from a webview?

One touch point I found that needs to be put in place is "hidden" away in the Proguard configuration. While the HTML reader invokes through the javascript interface just fine when debugging the app, this works no longer as soon as the app was run through Proguard, unless the HTML reader function is declared in the Proguard config file, like so:

-keepclassmembers class <your.fully.qualified.HTML.reader.classname.here> {
    public *; 
}

Tested and confirmed on Android 2.3.6, 4.1.1 and 4.2.1.

How to use EditText onTextChanged event when I press the number?

In Kotlin Android EditText listener is set using,

   val searchTo : EditText = findViewById(R.id.searchTo)
   searchTo.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(s: Editable) {

        // you can call or do what you want with your EditText here

        // yourEditText...
    }

    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
})

UITextField text change event

As stated here: UITextField text change event, it seems that as of iOS 6 (iOS 6.0 and 6.1 checked) it is not possible to fully detect changes in UITextField objects just by observing the UITextFieldTextDidChangeNotification.

It seems that only those changes made directly by the built-in iOS keyboard are tracked now. This means that if you change your UITextField object just by invoking something like this: myUITextField.text = @"any_text", you won't be notified about any changes at all.

I don't know if this is a bug or it is intended. Seems like a bug since I haven't found any reasonable explanation in documentation. This is also stated here: UITextField text change event.

My "solution" to this is to actually post a notification by myself for every change I make to my UITextField (if that change is done without using the built-in iOS keyboard). Something like this:

myUITextField.text = @"I'm_updating_my_UITextField_directly_in_code";

NSNotification *myTextFieldUpdateNotification  = 
  [NSNotification notificationWithName:UITextFieldTextDidChangeNotification
                  object:myUITextField];

[NSNotificationCenter.defaultCenter 
  postNotification:myTextFieldUpdateNotification];

This way you are 100% confident that you'll receive the same notification when you change the .text property of your UITextField object, either when you update it "manually" in your code or through the built-in iOS keyboard.

It is important to consider that, since this is not a documented behavior, this approach may lead to 2 notifications received for the same change in your UITextField object. Depending on your needs (what you actually do when your UITextField.text changes) this could be an inconvenience for you.

A slightly different approach would be to post a custom notification (this is, with a custom name other than UITextFieldTextDidChangeNotification) if you actually need to know whether the notification was yours or "iOS-made".

EDIT:

I've just found a different approach which I think could be better:

This involves the Key-Value Observing (KVO) feature of Objective-C (http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/KeyValueObserving/KeyValueObserving.html#//apple_ref/doc/uid/10000177-BCICJDHA).

Basically, you register yourself as an observer of a property and if this property changes you get notified about it. The "principle" is quite similar to how NSNotificationCenter works, being the main advantage that this approach works automatically also as of iOS 6 (without any special tweak like having to manually post notifications).

For our UITextField-scenario this works just fine if you add this code to, for example, your UIViewController that contains the text field:

static void *myContext = &myContext;

- (void)viewDidLoad {
  [super viewDidLoad];

  //Observing changes to myUITextField.text:
  [myUITextField addObserver:self forKeyPath:@"text"
    options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld 
    context:myContext];

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object 
change:(NSDictionary *)change context:(void *)context {

  if(context == myContext) {
    //Here you get notified every time myUITextField's "text" property is updated
    NSLog(@"New value: %@ - Old value: %@",
      [change objectForKey:NSKeyValueChangeNewKey],
      [change objectForKey:NSKeyValueChangeOldKey]);
  }
  else 
    [super observeValueForKeyPath:keyPath ofObject:object 
      change:change context:context];

}

Credit to this answer regarding "context" management: https://stackoverflow.com/a/12097161/2078512

Note: Seems like while you are in the process of editing a UITextField with the built-in iOS keyboard, the "text" property of the text field is not updated with every new letter typed/removed. Instead, the text field object gets updated "as a whole" after you resign the first responder status of the text field.

Filtering DataGridView without changing datasource

I found a simple way to fix that problem. At binding datagridview you've just done: datagridview.DataSource = dataSetName.Tables["TableName"];

If you code like:

datagridview.DataSource = dataSetName;
datagridview.DataMember = "TableName";

the datagridview will never load data again when filtering.

Better way to Format Currency Input editText?

Here is my custom CurrencyEditText

import android.content.Context;import android.graphics.Rect;import android.text.Editable;import android.text.InputFilter;import android.text.InputType;import android.text.TextWatcher;
import android.util.AttributeSet;import android.widget.EditText;import java.math.BigDecimal;import java.math.RoundingMode;
import java.text.DecimalFormat;import java.text.DecimalFormatSymbols;
import java.util.Locale;

/**
 * Some note <br/>
 * <li>Always use locale US instead of default to make DecimalFormat work well in all language</li>
 */
public class CurrencyEditText extends android.support.v7.widget.AppCompatEditText {
    private static String prefix = "VND ";
    private static final int MAX_LENGTH = 20;
    private static final int MAX_DECIMAL = 3;
    private CurrencyTextWatcher currencyTextWatcher = new CurrencyTextWatcher(this, prefix);

    public CurrencyEditText(Context context) {
        this(context, null);
    }

    public CurrencyEditText(Context context, AttributeSet attrs) {
        this(context, attrs, android.support.v7.appcompat.R.attr.editTextStyle);
    }

    public CurrencyEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        this.setHint(prefix);
        this.setFilters(new InputFilter[] { new InputFilter.LengthFilter(MAX_LENGTH) });
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        if (focused) {
            this.addTextChangedListener(currencyTextWatcher);
        } else {
            this.removeTextChangedListener(currencyTextWatcher);
        }
        handleCaseCurrencyEmpty(focused);
    }

    /**
     * When currency empty <br/>
     * + When focus EditText, set the default text = prefix (ex: VND) <br/>
     * + When EditText lose focus, set the default text = "", EditText will display hint (ex:VND)
     */
    private void handleCaseCurrencyEmpty(boolean focused) {
        if (focused) {
            if (getText().toString().isEmpty()) {
                setText(prefix);
            }
        } else {
            if (getText().toString().equals(prefix)) {
                setText("");
            }
        }
    }

    private static class CurrencyTextWatcher implements TextWatcher {
        private final EditText editText;
        private String previousCleanString;
        private String prefix;

        CurrencyTextWatcher(EditText editText, String prefix) {
            this.editText = editText;
            this.prefix = prefix;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // do nothing
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // do nothing
        }

        @Override
        public void afterTextChanged(Editable editable) {
            String str = editable.toString();
            if (str.length() < prefix.length()) {
                editText.setText(prefix);
                editText.setSelection(prefix.length());
                return;
            }
            if (str.equals(prefix)) {
                return;
            }
            // cleanString this the string which not contain prefix and ,
            String cleanString = str.replace(prefix, "").replaceAll("[,]", "");
            // for prevent afterTextChanged recursive call
            if (cleanString.equals(previousCleanString) || cleanString.isEmpty()) {
                return;
            }
            previousCleanString = cleanString;

            String formattedString;
            if (cleanString.contains(".")) {
                formattedString = formatDecimal(cleanString);
            } else {
                formattedString = formatInteger(cleanString);
            }
            editText.removeTextChangedListener(this); // Remove listener
            editText.setText(formattedString);
            handleSelection();
            editText.addTextChangedListener(this); // Add back the listener
        }

        private String formatInteger(String str) {
            BigDecimal parsed = new BigDecimal(str);
            DecimalFormat formatter =
                    new DecimalFormat(prefix + "#,###", new DecimalFormatSymbols(Locale.US));
            return formatter.format(parsed);
        }

        private String formatDecimal(String str) {
            if (str.equals(".")) {
                return prefix + ".";
            }
            BigDecimal parsed = new BigDecimal(str);
            // example pattern VND #,###.00
            DecimalFormat formatter = new DecimalFormat(prefix + "#,###." + getDecimalPattern(str),
                    new DecimalFormatSymbols(Locale.US));
            formatter.setRoundingMode(RoundingMode.DOWN);
            return formatter.format(parsed);
        }

        /**
         * It will return suitable pattern for format decimal
         * For example: 10.2 -> return 0 | 10.23 -> return 00, | 10.235 -> return 000
         */
        private String getDecimalPattern(String str) {
            int decimalCount = str.length() - str.indexOf(".") - 1;
            StringBuilder decimalPattern = new StringBuilder();
            for (int i = 0; i < decimalCount && i < MAX_DECIMAL; i++) {
                decimalPattern.append("0");
            }
            return decimalPattern.toString();
        }

        private void handleSelection() {
            if (editText.getText().length() <= MAX_LENGTH) {
                editText.setSelection(editText.getText().length());
            } else {
                editText.setSelection(MAX_LENGTH);
            }
        }
    }
}

Use it in XML like

 <...CurrencyEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

You should edit 2 constant below for suitable for your project

private static String prefix = "VND ";
private static final int MAX_DECIMAL = 3;

enter image description here

Demo on github

How to stop BackgroundWorker correctly

If you add a loop between the CancelAsync() and the RunWorkerAsync() like so it will solve your problem

 private void combobox2_TextChanged(object sender, EventArgs e)
 {
     if (cmbDataSourceExtractor.IsBusy)
        cmbDataSourceExtractor.CancelAsync();

     while(cmbDataSourceExtractor.IsBusy)
        Application.DoEvents();

     var filledComboboxValues = new FilledComboboxValues{ V1 = combobox1.Text,
        V2 = combobox2.Text};
     cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues );
  }

The while loop with the call to Application.DoEvents() will hault the execution of your new worker thread until the current one has properly cancelled, keep in mind you still need to handle the cancellation of your worker thread. With something like:

 private void cmbDataSourceExtractor_DoWork(object sender, DoWorkEventArgs e)
 {
      if (this.cmbDataSourceExtractor.CancellationPending)
      {
          e.Cancel = true;
          return;
      }
      // do stuff...
 }

The Application.DoEvents() in the first code snippet will continue to process your GUI threads message queue so the even to cancel and update the cmbDataSourceExtractor.IsBusy property will still be processed (if you simply added a continue instead of Application.DoEvents() the loop would lock the GUI thread into a busy state and would not process the event to update the cmbDataSourceExtractor.IsBusy)

Counting Chars in EditText Changed Listener

Use

s.length()

The following was once suggested in one of the answers, but its very inefficient

textMessage.getText().toString().length()

Getting the .Text value from a TextBox

Did you try using t.Text?

Among $_REQUEST, $_GET and $_POST which one is the fastest?

$_REQUEST, by default, contains the contents of $_GET, $_POST and $_COOKIE.

But it's only a default, which depends on variables_order ; and not sure you want to work with cookies.

If I had to choose, I would probably not use $_REQUEST, and I would choose $_GET or $_POST -- depending on what my application should do (i.e. one or the other, but not both) : generally speaking :

  • You should use $_GET when someone is requesting data from your application.
  • And you should use $_POST when someone is pushing (inserting or updating ; or deleting) data to your application.

Either way, there will not be much of a difference about performances : the difference will be negligible, compared to what the rest of your script will do.

OpenCV with Network Cameras

#include <stdio.h>
#include "opencv.hpp"


int main(){

    CvCapture *camera=cvCaptureFromFile("http://username:pass@cam_address/axis-cgi/mjpg/video.cgi?resolution=640x480&req_fps=30&.mjpg");
    if (camera==NULL)
        printf("camera is null\n");
    else
        printf("camera is not null");

    cvNamedWindow("img");
    while (cvWaitKey(10)!=atoi("q")){
        double t1=(double)cvGetTickCount();
        IplImage *img=cvQueryFrame(camera);
        double t2=(double)cvGetTickCount();
        printf("time: %gms  fps: %.2g\n",(t2-t1)/(cvGetTickFrequency()*1000.), 1000./((t2-t1)/(cvGetTickFrequency()*1000.)));
        cvShowImage("img",img);
    }
    cvReleaseCapture(&camera);
}

Spring Boot Rest Controller how to return different HTTP status codes?

In case you want to return a custom defined status code, you can use the ResponseEntity as here:

@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)
public ResponseEntity<?> create(@RequestBody String data) {
    int customHttpStatusValue = 499;
    Foo foo = bar();
    return ResponseEntity.status(customHttpStatusValue).body(foo);
}

The CustomHttpStatusValue could be any integer within or outside of standard HTTP Status Codes.

php: Get html source code with cURL

I found a tool in Github that could possibly be a solution to this question. https://incarnate.github.io/curl-to-php/ I hope that will be useful

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

From the experiment branch

git rebase master
git push -f origin <experiment-branch>

This creates a common commit history to be able to compare both branches.

Go / golang time.Now().UnixNano() convert to milliseconds?

I think it's better to round the time to milliseconds before the division.

func makeTimestamp() int64 {
    return time.Now().Round(time.Millisecond).UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}

Here is an example program:

package main

import (
        "fmt"
        "time"
)

func main() {
        fmt.Println(unixMilli(time.Unix(0, 123400000)))
        fmt.Println(unixMilli(time.Unix(0, 123500000)))
        m := makeTimestampMilli()
        fmt.Println(m)
        fmt.Println(time.Unix(m/1e3, (m%1e3)*int64(time.Millisecond)/int64(time.Nanosecond)))
}

func unixMilli(t time.Time) int64 {
        return t.Round(time.Millisecond).UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}

func makeTimestampMilli() int64 {
        return unixMilli(time.Now())
}

The above program printed the result below on my machine:

123
124
1472313624305
2016-08-28 01:00:24.305 +0900 JST

Running Facebook application on localhost

None of the answers above worked for me. I am running on FB API 2.5. Mine was a combination of issues that lead to success once resolved

  1. Create a test app to ensure that it is maintained and managed as such and can be disabled when going live
  2. Read the error message properly :) - I had to enable "Web OAuth Login" WITH "Client OAuth Login"
  3. Use https://www.whatismyip.com/ to find out what my current IP is
  4. Create an A record on my Domain i.e. http://localhost.mydomain.com that points to my current IP

It's probably not ideal as Dynamic IP's change and one could probably use DynDNS or something similar to make the IP more "static" but it worked for me

How to set root password to null

The answer by user64141

use mysql;
update user set password=null where User='root';
flush privileges;
quit;

didn't work for me in MariaDB 10.1.5 (supposed to be a drop in replacement for MySQL). While didn't tested it in MySQL 5.6 to see if is an upstream change, the error I got was:

ERROR 1048 (23000): Column 'Password' cannot be null

But replacing the null with empty single or double quotes worked fine.

update user set password='' where User='root';

or

update user set password="" where User='root';

Python spacing and aligning strings

@IronMensan's format method answer is the way to go. But in the interest of answering your question about ljust:

>>> def printit():
...     print 'Location: 10-10-10-10'.ljust(40) + 'Revision: 1'
...     print 'District: Tower'.ljust(40) + 'Date: May 16, 2012'
...     print 'User: LOD'.ljust(40) + 'Time: 10:15'
...
>>> printit()
Location: 10-10-10-10                   Revision: 1
District: Tower                         Date: May 16, 2012
User: LOD                               Time: 10:15

Edit to note this method doesn't require you to know how long your strings are. .format() may also, but I'm not familiar enough with it to say.

>>> uname='LOD'
>>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15'
'User: LOD                               Time: 10:15'
>>> uname='Tiddlywinks'
>>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15'
'User: Tiddlywinks                       Time: 10:15'

C/C++ NaN constant (literal)?

As others have pointed out you are looking for std::numeric_limits<double>::quiet_NaN() although I have to say I prefer the cppreference.com documents. Especially because this statement is a little vague:

Only meaningful if std::numeric_limits::has_quiet_NaN == true.

and it was simple to figure out what this means on this site, if you check their section on std::numeric_limits::has_quiet_NaN it says:

This constant is meaningful for all floating-point types and is guaranteed to be true if std::numeric_limits::is_iec559 == true.

which as explained here if true means your platform supports IEEE 754 standard. This previous thread explains this should be true for most situations.

Determine Whether Integer Is Between Two Other Integers?

if number >= 10000 and number <= 30000:
    print ("you have to pay 5% taxes")

Android Call an method from another class

You should use the following code :

Class2 cls2 = new Class2();
cls2.UpdateEmployee();

In case you don't want to create a new instance to call the method, you can decalre the method as static and then you can just call Class2.UpdateEmployee().

callback to handle completion of pipe

Based nodejs document, http://nodejs.org/api/stream.html#stream_event_finish, it should handle writableStream's finish event.

var writable = getWriteable();
var readable = getReadable();
readable.pipe(writable);
writable.on('finish', function(){ ... });

How to correctly set Http Request Header in Angular 2

This should be easily resolved by importing headers from Angular:

import { Http, Headers } from "@angular/http";

MySQL Insert with While Loop

You cannot use WHILE like that; see: mysql DECLARE WHILE outside stored procedure how?

You have to put your code in a stored procedure. Example:

CREATE PROCEDURE myproc()
BEGIN
    DECLARE i int DEFAULT 237692001;
    WHILE i <= 237692004 DO
        INSERT INTO mytable (code, active, total) VALUES (i, 1, 1);
        SET i = i + 1;
    END WHILE;
END

Fiddle: http://sqlfiddle.com/#!2/a4f92/1

Alternatively, generate a list of INSERT statements using any programming language you like; for a one-time creation, it should be fine. As an example, here's a Bash one-liner:

for i in {2376921001..2376921099}; do echo "INSERT INTO mytable (code, active, total) VALUES ($i, 1, 1);"; done

By the way, you made a typo in your numbers; 2376921001 has 10 digits, 237692200 only 9.

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace

You must give permission to your app for listening http requests. You can use this command in cmd for this purpose (open cmd Run As Administrator mode)

netsh http add urlacl url=http://+:8000/ user=Everyone

If your app is working other port, for example 9095, this command must be like as below:

netsh http add urlacl url=http://+:9095/ user=Everyone

And re-run your app, it should work. This way working for me.

Best practice for instantiating a new Android Fragment

The only benefit in using the newInstance() that I see are the following:

  1. You will have a single place where all the arguments used by the fragment could be bundled up and you don't have to write the code below everytime you instantiate a fragment.

    Bundle args = new Bundle();
    args.putInt("someInt", someInt);
    args.putString("someString", someString);
    // Put any other arguments
    myFragment.setArguments(args);
    
  2. Its a good way to tell other classes what arguments it expects to work faithfully(though you should be able to handle cases if no arguments are bundled in the fragment instance).

So, my take is that using a static newInstance() to instantiate a fragment is a good practice.

Convert integer to string Jinja

The OP needed to cast as string outside the {% set ... %}. But if that not your case you can do:

{% set curYear = 2013 | string() %}

Note that you need the parenthesis on that jinja filter.

If you're concatenating 2 variables, you can also use the ~ custom operator.

How to find the kth largest element in an unsorted array of length n in O(n)?

If you want a true O(n) algorithm, as opposed to O(kn) or something like that, then you should use quickselect (it's basically quicksort where you throw out the partition that you're not interested in). My prof has a great writeup, with the runtime analysis: (reference)

The QuickSelect algorithm quickly finds the k-th smallest element of an unsorted array of n elements. It is a RandomizedAlgorithm, so we compute the worst-case expected running time.

Here is the algorithm.

QuickSelect(A, k)
  let r be chosen uniformly at random in the range 1 to length(A)
  let pivot = A[r]
  let A1, A2 be new arrays
  # split into a pile A1 of small elements and A2 of big elements
  for i = 1 to n
    if A[i] < pivot then
      append A[i] to A1
    else if A[i] > pivot then
      append A[i] to A2
    else
      # do nothing
  end for
  if k <= length(A1):
    # it's in the pile of small elements
    return QuickSelect(A1, k)
  else if k > length(A) - length(A2)
    # it's in the pile of big elements
    return QuickSelect(A2, k - (length(A) - length(A2))
  else
    # it's equal to the pivot
    return pivot

What is the running time of this algorithm? If the adversary flips coins for us, we may find that the pivot is always the largest element and k is always 1, giving a running time of

T(n) = Theta(n) + T(n-1) = Theta(n2)

But if the choices are indeed random, the expected running time is given by

T(n) <= Theta(n) + (1/n) ?i=1 to nT(max(i, n-i-1))

where we are making the not entirely reasonable assumption that the recursion always lands in the larger of A1 or A2.

Let's guess that T(n) <= an for some a. Then we get

T(n) 
 <= cn + (1/n) ?i=1 to nT(max(i-1, n-i))
 = cn + (1/n) ?i=1 to floor(n/2) T(n-i) + (1/n) ?i=floor(n/2)+1 to n T(i)
 <= cn + 2 (1/n) ?i=floor(n/2) to n T(i)
 <= cn + 2 (1/n) ?i=floor(n/2) to n ai

and now somehow we have to get the horrendous sum on the right of the plus sign to absorb the cn on the left. If we just bound it as 2(1/n) ?i=n/2 to n an, we get roughly 2(1/n)(n/2)an = an. But this is too big - there's no room to squeeze in an extra cn. So let's expand the sum using the arithmetic series formula:

?i=floor(n/2) to n i  
 = ?i=1 to n i - ?i=1 to floor(n/2) i  
 = n(n+1)/2 - floor(n/2)(floor(n/2)+1)/2  
 <= n2/2 - (n/4)2/2  
 = (15/32)n2

where we take advantage of n being "sufficiently large" to replace the ugly floor(n/2) factors with the much cleaner (and smaller) n/4. Now we can continue with

cn + 2 (1/n) ?i=floor(n/2) to n ai,
 <= cn + (2a/n) (15/32) n2
 = n (c + (15/16)a)
 <= an

provided a > 16c.

This gives T(n) = O(n). It's clearly Omega(n), so we get T(n) = Theta(n).

Doing HTTP requests FROM Laravel to an external API

Definitively, for any PHP project, you may want to use GuzzleHTTP for sending requests. Guzzle has very nice documentation you can check here. I just want to say that, you probably want to centralize the usage of the Client class of Guzzle in any component of your Laravel project (for example a trait) instead of being creating Client instances on several controllers and components of Laravel (as many articles and replies suggest).

I created a trait you can try to use, which allows you to send requests from any component of your Laravel project, just using it and calling to makeRequest.

namespace App\Traits;
use GuzzleHttp\Client;
trait ConsumesExternalServices
{
    /**
     * Send a request to any service
     * @return string
     */
    public function makeRequest($method, $requestUrl, $queryParams = [], $formParams = [], $headers = [], $hasFile = false)
    {
        $client = new Client([
            'base_uri' => $this->baseUri,
        ]);

        $bodyType = 'form_params';

        if ($hasFile) {
            $bodyType = 'multipart';
            $multipart = [];

            foreach ($formParams as $name => $contents) {
                $multipart[] = [
                    'name' => $name,
                    'contents' => $contents
                ];
            }
        }

        $response = $client->request($method, $requestUrl, [
            'query' => $queryParams,
            $bodyType => $hasFile ? $multipart : $formParams,
            'headers' => $headers,
        ]);

        $response = $response->getBody()->getContents();

        return $response;
    }
}

Notice this trait can even handle files sending.

If you want more details about this trait and some other stuff to integrate this trait to Laravel, check this article. Additionally, if interested in this topic or need major assistance, you can take my course which guides you in the whole process.

I hope it helps all of you.

Best wishes :)

How to round an image with Glide library?

I found one easy and simple solution for add border over imageview in which color want to set or add gradient over image.

STEPS:

  1. Take one frame layout and add two images.You can set size as per your requirement. For imgPlaceHolder , you need one white image or color which you want to set.

        <ImageView
            android:id="@+id/imgPlaceHolder"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:src="@drawable/white_bg"/>

        <ImageView
            android:id="@+id/imgPic"
            android:layout_width="190dp"
            android:layout_height="190dp"
            android:layout_gravity="center"
            android:src="@drawable/image01"/>
    </FrameLayout>
  1. After placing this code on xml file , put below line in java file.

    Glide.with(this).load(R.drawable.image01).asBitmap().centerCrop().into(new BitmapImageViewTarget(imgPic) {
        @Override
        protected void setResource(Bitmap resource) {
            RoundedBitmapDrawable circularBitmapDrawable =
                    RoundedBitmapDrawableFactory.create(getResources(), resource);
            circularBitmapDrawable.setCircular(true);
            imageView.setImageDrawable(circularBitmapDrawable);
        }
    });
    
    Glide.with(this).load(R.drawable.white_bg).asBitmap().centerCrop().into(new BitmapImageViewTarget(imgPlaceHolder) {
        @Override
        protected void setResource(Bitmap resource) {
            RoundedBitmapDrawable circularBitmapDrawable =
                    RoundedBitmapDrawableFactory.create(getResources(), resource);
            circularBitmapDrawable.setCircular(true);
            imgTemp2.setImageDrawable(circularBitmapDrawable);
        }
    });
    

This will make border of imageview simply with out any extra padding and margin.

NOTE : White image is compulsory for border otherwise it will not work.

Happy codding :)

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

I am adding the solution that worked for me for this same error.

I right clicked project > properties > (left panel) Android

Right panel under Library I removed the faulty library and added it again.

For me this error occurred after a corrupt workspace eclipse file where I had to import all projects again.

MySQL Install: ERROR: Failed to build gem native extension

yum -y install gcc mysql-devel ruby-devel rubygems
gem install mysql2

View list of all JavaScript variables in Google Chrome Console

If you want to exclude all the standard properties of the window object and view application-specific globals, this will print them to the Chrome console:

{

    const standardGlobals = new Set(["window", "self", "document", "name", "location", "customElements", "history", "locationbar", "menubar", "personalbar", "scrollbars", "statusbar", "toolbar", "status", "closed", "frames", "length", "top", "opener", "parent", "frameElement", "navigator", "origin", "external", "screen", "innerWidth", "innerHeight", "scrollX", "pageXOffset", "scrollY", "pageYOffset", "visualViewport", "screenX", "screenY", "outerWidth", "outerHeight", "devicePixelRatio", "clientInformation", "screenLeft", "screenTop", "defaultStatus", "defaultstatus", "styleMedia", "onsearch", "isSecureContext", "performance", "onappinstalled", "onbeforeinstallprompt", "crypto", "indexedDB", "webkitStorageInfo", "sessionStorage", "localStorage", "onabort", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "onformdata", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmouseenter", "onmouseleave", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onresize", "onscroll", "onseeked", "onseeking", "onselect", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "ontoggle", "onvolumechange", "onwaiting", "onwebkitanimationend", "onwebkitanimationiteration", "onwebkitanimationstart", "onwebkittransitionend", "onwheel", "onauxclick", "ongotpointercapture", "onlostpointercapture", "onpointerdown", "onpointermove", "onpointerup", "onpointercancel", "onpointerover", "onpointerout", "onpointerenter", "onpointerleave", "onselectstart", "onselectionchange", "onanimationend", "onanimationiteration", "onanimationstart", "ontransitionrun", "ontransitionstart", "ontransitionend", "ontransitioncancel", "onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onmessageerror", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onrejectionhandled", "onstorage", "onunhandledrejection", "onunload", "alert", "atob", "blur", "btoa", "cancelAnimationFrame", "cancelIdleCallback", "captureEvents", "clearInterval", "clearTimeout", "close", "confirm", "createImageBitmap", "fetch", "find", "focus", "getComputedStyle", "getSelection", "matchMedia", "moveBy", "moveTo", "open", "postMessage", "print", "prompt", "queueMicrotask", "releaseEvents", "requestAnimationFrame", "requestIdleCallback", "resizeBy", "resizeTo", "scroll", "scrollBy", "scrollTo", "setInterval", "setTimeout", "stop", "webkitCancelAnimationFrame", "webkitRequestAnimationFrame", "chrome", "caches", "ondevicemotion", "ondeviceorientation", "ondeviceorientationabsolute", "originAgentCluster", "cookieStore", "showDirectoryPicker", "showOpenFilePicker", "showSaveFilePicker", "speechSynthesis", "onpointerrawupdate", "trustedTypes", "crossOriginIsolated", "openDatabase", "webkitRequestFileSystem", "webkitResolveLocalFileSystemURL"]);

    for (const key of Object.keys(window)) {
        if (!standardGlobals.has(key)) {
            console.log(key)
        }
    }
}

The script works well as a bookmarklet. To use the script as a bookmarklet, create a new bookmark and replace the URL with the following:

javascript:(() => {
    const standardGlobals = new Set(["window", "self", "document", "name", "location", "customElements", "history", "locationbar", "menubar", "personalbar", "scrollbars", "statusbar", "toolbar", "status", "closed", "frames", "length", "top", "opener", "parent", "frameElement", "navigator", "origin", "external", "screen", "innerWidth", "innerHeight", "scrollX", "pageXOffset", "scrollY", "pageYOffset", "visualViewport", "screenX", "screenY", "outerWidth", "outerHeight", "devicePixelRatio", "clientInformation", "screenLeft", "screenTop", "defaultStatus", "defaultstatus", "styleMedia", "onsearch", "isSecureContext", "performance", "onappinstalled", "onbeforeinstallprompt", "crypto", "indexedDB", "webkitStorageInfo", "sessionStorage", "localStorage", "onabort", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "onformdata", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmouseenter", "onmouseleave", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onresize", "onscroll", "onseeked", "onseeking", "onselect", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "ontoggle", "onvolumechange", "onwaiting", "onwebkitanimationend", "onwebkitanimationiteration", "onwebkitanimationstart", "onwebkittransitionend", "onwheel", "onauxclick", "ongotpointercapture", "onlostpointercapture", "onpointerdown", "onpointermove", "onpointerup", "onpointercancel", "onpointerover", "onpointerout", "onpointerenter", "onpointerleave", "onselectstart", "onselectionchange", "onanimationend", "onanimationiteration", "onanimationstart", "ontransitionrun", "ontransitionstart", "ontransitionend", "ontransitioncancel", "onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onmessageerror", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onrejectionhandled", "onstorage", "onunhandledrejection", "onunload", "alert", "atob", "blur", "btoa", "cancelAnimationFrame", "cancelIdleCallback", "captureEvents", "clearInterval", "clearTimeout", "close", "confirm", "createImageBitmap", "fetch", "find", "focus", "getComputedStyle", "getSelection", "matchMedia", "moveBy", "moveTo", "open", "postMessage", "print", "prompt", "queueMicrotask", "releaseEvents", "requestAnimationFrame", "requestIdleCallback", "resizeBy", "resizeTo", "scroll", "scrollBy", "scrollTo", "setInterval", "setTimeout", "stop", "webkitCancelAnimationFrame", "webkitRequestAnimationFrame", "chrome", "caches", "ondevicemotion", "ondeviceorientation", "ondeviceorientationabsolute", "originAgentCluster", "cookieStore", "showDirectoryPicker", "showOpenFilePicker", "showSaveFilePicker", "speechSynthesis", "onpointerrawupdate", "trustedTypes", "crossOriginIsolated", "openDatabase", "webkitRequestFileSystem", "webkitResolveLocalFileSystemURL"]);
    for (const key of Object.keys(window)) {
        if (!standardGlobals.has(key)) {
            console.log(key)
        }
    }
})()

Postgresql Select rows where column = array

SELECT  *
FROM    table
WHERE   some_id = ANY(ARRAY[1, 2])

or ANSI-compatible:

SELECT  *
FROM    table
WHERE   some_id IN (1, 2)

The ANY syntax is preferred because the array as a whole can be passed in a bound variable:

SELECT  *
FROM    table
WHERE   some_id = ANY(?::INT[])

You would need to pass a string representation of the array: {1,2}

MongoDB relationships: embed or reference?

Actually, I'm quite curious why nobody spoke about the UML specifications. A rule of thumb is that if you have an aggregation, then you should use references. But if it is a composition, then the coupling is stronger, and you should use embedded documents.

And you will quickly understand why it is logical. If an object can exist independently of the parent, then you will want to access it even if the parent doesn't exist. As you just can't embed it in a non-existing parent, you have to make it live in it's own data structure. And if a parent exist, just link them together by adding a ref of the object in the parent.

Don't really know what is the difference between the two relationships ? Here is a link explaining them: Aggregation vs Composition in UML

One line if/else condition in linux shell scripting

To summarize the other answers, for general use:

Multi-line if...then statement

if [ foo ]; then
    a; b
elif [ bar ]; then
    c; d
else
    e; f
fi

Single-line version

if [ foo ]; then a && b; elif [ bar ]; c && d; else e && f; fi

Using the OR operator

( foo && a && b ) || ( bar && c && d ) || e && f;

Notes

Remember that the AND and OR operators evaluate whether or not the result code of the previous operation was equal to true/success (0). So if a custom function returns something else (or nothing at all), you may run into problems with the AND/OR shorthand. In such cases, you may want to replace something like ( a && b ) with ( [ a == 'EXPECTEDRESULT' ] && b ), etc.

Also note that ( and [ are technically commands, so whitespace is required around them.

Instead of a group of && statements like then a && b; else, you could also run statements in a subshell like then $( a; b ); else, though this is less efficient. The same is true for doing something like result1=$( foo; a; b ); result2=$( bar; c; d ); [ "$result1" -o "$result2" ] instead of ( foo && a && b ) || ( bar && c && d ). Though at that point you'd be getting more into less-compact, multi-line stuff anyway.

Best way to move files between S3 buckets?

For new version aws2.

aws2 s3 sync s3://SOURCE_BUCKET_NAME s3://NEW_BUCKET_NAME

How to run an .ipynb Jupyter Notebook from terminal?

For new version instead of:

ipython nbconvert --to python <YourNotebook>.ipynb

You can use jupyter instend of ipython:

jupyter nbconvert --to python <YourNotebook>.ipynb

Convert a double to a QString

Check out the documentation

Quote:

QString provides many functions for converting numbers into strings and strings into numbers. See the arg() functions, the setNum() functions, the number() static functions, and the toInt(), toDouble(), and similar functions.

Need to install urllib2 for Python 3.5.1

In Python 3, urllib2 was replaced by two in-built modules named urllib.request and urllib.error

Adapted from source


So replace this:

import urllib2

With this:

import urllib.request as urllib2

How to clone an InputStream?

If the data read from the stream is large, I would recommend using a TeeInputStream from Apache Commons IO. That way you can essentially replicate the input and pass a t'd pipe as your clone.

How can I access "static" class variables within class methods in Python?

class Foo(object):
     bar = 1
     def bah(self):
         print Foo.bar

f = Foo() 
f.bah()

Sending XML data using HTTP POST with PHP

Another option would be file_get_contents():

// $xml_str = your xml
// $url = target url

$post_data = array('xml' => $xml_str);
$stream_options = array(
    'http' => array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
        'content' =>  http_build_query($post_data)));

$context  = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);

How can I align the columns of tables in Bash?

Just in case someone wants to do that in PHP I posted a gist on Github

https://gist.github.com/redestructa/2a7691e7f3ae69ec5161220c99e2d1b3

simply call:

$output = $tablePrinter->printLinesIntoArray($items, ['title', 'chilProp2']);

you may need to adapt the code if you are using a php version older than 7.2

after that call echo or writeLine depending on your environment.

Configure active profile in SpringBoot via Maven

There are multiple ways to set profiles for your springboot application.

  1. You can add this in your property file:

    spring.profiles.active=dev
    
  2. Programmatic way:

    SpringApplication.setAdditionalProfiles("dev");
    
  3. Tests make it very easy to specify what profiles are active

    @ActiveProfiles("dev")
    
  4. In a Unix environment

    export spring_profiles_active=dev
    
  5. JVM System Parameter

    -Dspring.profiles.active=dev
    

Example: Running a springboot jar file with profile.

java -jar -Dspring.profiles.active=dev application.jar

When should I use curly braces for ES6 import?

If you think of import as just syntax sugar for Node.js modules, objects, and destructuring, I find it's pretty intuitive.

// bar.js
module = {};

module.exports = {
  functionA: () => {},
  functionB: ()=> {}
};

 // Really all that is is this:
 var module = {
   exports: {
      functionA, functionB
   }
  };

// Then, over in foo.js

// The whole exported object:
var fump = require('./bar.js'); //= { functionA, functionB }
// Or
import fump from './bar' // The same thing - object functionA and functionB properties


// Just one property of the object
var fump = require('./bar.js').functionA;

// Same as this, right?
var fump = { functionA, functionB }.functionA;

// And if we use ES6 destructuring:
var { functionA } =  { functionA, functionB };
// We get same result

// So, in import syntax:
import { functionA } from './bar';

LINQ: "contains" and a Lambda query

Use Any() instead of Contains():

buildingStatus.Any(item => item.GetCharValue() == v.Status)

How to handle authentication popup with Selenium WebDriver using Java

Selenium 4 supports authenticating using Basic and Digest auth . It's using the CDP and currently only supports chromium-derived browsers

Java Example :

Webdriver driver = new ChromeDriver();

((HasAuthentication) driver).register(UsernameAndPassword.of("username", "pass"));

driver.get("http://sitewithauth");

Note : In Alpha-7 there is bug where it send username for both user/password. Need to wait for next release of selenium version as fix is available in trunk https://github.com/SeleniumHQ/selenium/commit/4917444886ba16a033a81a2a9676c9267c472894

Difference between Constructor and ngOnInit

I think the best example would be using services. Let's say that I want to grab data from my server when my component gets 'Activated'. Let's say that I also want to do some additional things to the data after I get it from the server, maybe I get an error and want to log it differently.

It is really easy with ngOnInit over a constructor, it also limits how many callback layers I need to add to my application.

For Example:

export class Users implements OnInit{

    user_list: Array<any>;

    constructor(private _userService: UserService){
    };

    ngOnInit(){
        this.getUsers();
    };

    getUsers(){
        this._userService.getUsersFromService().subscribe(users =>  this.user_list = users);
    };


}

with my constructor I could just call my _userService and populate my user_list, but maybe I want to do some extra things with it. Like make sure everything is upper_case, I am not entirely sure how my data is coming through.

So it makes it much easier to use ngOnInit.

export class Users implements OnInit{

    user_list: Array<any>;

    constructor(private _userService: UserService){
    };

    ngOnInit(){
        this.getUsers();
    };

    getUsers(){
        this._userService.getUsersFromService().subscribe(users =>  this.user_list = users);
        this.user_list.toUpperCase();
    };


}

It makes it much easier to see, and so I just call my function within my component when I initialize instead of having to dig for it somewhere else. Really it's just another tool you can use to make it easier to read and use in the future. Also I find it really bad practice to put function calls within a constructor!

How to replace captured groups only?

A simplier option is to just capture the digits and replace them.

_x000D_
_x000D_
const name = 'preceding_text_0_following_text';_x000D_
const matcher = /(\d+)/;_x000D_
_x000D_
// Replace with whatever you would like_x000D_
const newName = name.replace(matcher, 'NEW_STUFF');_x000D_
console.log("Full replace", newName);_x000D_
_x000D_
// Perform work on the match and replace using a function_x000D_
// In this case increment it using an arrow function_x000D_
const incrementedName = name.replace(matcher, (match) => ++match);_x000D_
console.log("Increment", incrementedName);
_x000D_
_x000D_
_x000D_

Resources

How to control border height?

A border will always be at the full length of the containing box (the height of the element plus its padding), it can't be controlled except for adjusting the height of the element to which it applies. If all you need is a vertical divider, you could use:

<div id="left">
  content
</div>
<span class="divider"></span>
<div id="right">
  content
</div>

With css:

span {
 display: inline-block;
 width: 0;
 height: 1em;
 border-left: 1px solid #ccc;
 border-right: 1px solid #ccc;
}

Demo at JS Fiddle, adjust the height of the span.container to adjust the border 'height'.

Or, to use pseudo-elements (::before or ::after), given the following HTML:

<div id="left">content</div>
<div id="right">content</div>

The following CSS adds a pseudo-element before any div element that's the adjacent sibling of another div element:

div {
    display: inline-block;
    position: relative;
}

div + div {
    padding-left: 0.3em;
}

div + div::before {
    content: '';
    border-left: 2px solid #000;
    position: absolute;
    height: 50%;
    left: 0;
    top: 25%;
}

JS Fiddle demo.

How do I get the max and min values from a set of numbers entered?

//for excluding zero
public class SmallestInt {

    public static void main(String[] args) {

        Scanner input= new Scanner(System.in);

        System.out.println("enter number");
        int val=input.nextInt();
        int min=val;

        //String notNull;

        while(input.hasNextInt()==true)
        {
            val=input.nextInt();
            if(val<min)
                min=val;
        }
        System.out.println("min is: "+min);
    }
}

How to print a string in C++

If you'd like to use printf(), you might want to also:

#include <stdio.h>

Multiple Buttons' OnClickListener() android

I had a similar issue and what I did is: Create a array of Buttons

Button buttons[] = new Button[10];

Then to implement on click listener and reference xml id's I used a loop like this

for (int i = 0; i < 10; i++) {      
String buttonID = "button" + i;
        int resID = getResources().getIdentifier(buttonID, "id",
                "your package name here");
        buttons[i] = (Button) findViewById(resID);
        buttons[i].setOnClickListener(this);
    }

But calling them up remains same as in Prag's answer point 4. PS- If anybody has a better method to call up all the button's onClick, please do comment.

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

Something like gunzip using the -r flag?....

Travel the directory structure recursively. If any of the file names specified on the command line are directories, gzip will descend into the directory and compress all the files it finds there (or decompress them in the case of gunzip ).

http://www.computerhope.com/unix/gzip.htm

HTTPS connections over proxy servers

as far as i can remember, you need to use a HTTP CONNECT query on the proxy. this will convert the request connection to a transparent TCP/IP tunnel.

so you need to know if the proxy server you use support this protocol.

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

I don't know whether this is efficient or not but I would like to suggest this solution.

  1. Compute xor of the 100 elements
  2. Compute xor of the 98 elements (after the 2 elements are removed)
  3. Now (result of 1) XOR (result of 2) gives you the xor of the two missing nos i..e a XOR b if a and b are the missing elements
    4.Get the sum of the missing Nos with your usual approach of the sum formula diff and lets say the diff is d.

Now run a loop to get the possible pairs (p,q) both of which lies in [1 , 100] and sum to d.

When a pair is obtained check whether (result of 3) XOR p = q and if yes we are done.

Please correct me if I am wrong and also comment on time complexity if this is correct

Check existence of directory and create if doesn't exist

I had an issue with R 2.15.3 whereby while trying to create a tree structure recursively on a shared network drive I would get a permission error.

To get around this oddity I manually create the structure;

mkdirs <- function(fp) {
    if(!file.exists(fp)) {
        mkdirs(dirname(fp))
        dir.create(fp)
    }
} 

mkdirs("H:/foo/bar")

Git pushing to remote branch

With modern Git versions, the command to use would be:

git push -u origin <branch_name_test>

This will automatically set the branch name to track from remote and push in one go.

MySQL CREATE FUNCTION Syntax

You have to override your ; delimiter with something like $$ to avoid this kind of error.

After your function definition, you can set the delimiter back to ;.

This should work:

DELIMITER $$
CREATE FUNCTION F_Dist3D (x1 decimal, y1 decimal) 
RETURNS decimal
DETERMINISTIC
BEGIN 
  DECLARE dist decimal;
  SET dist = SQRT(x1 - y1);
  RETURN dist;
END$$
DELIMITER ;

Difference between Method and Function?

well, in some programming languages they are called functions others call it methods, the fact is they are the same thing. It just represents an abstractized form of reffering to a mathematical function:

f -> f(N:N).

meaning its a function with values from natural numbers (just an example). So besides the name Its exactly the same thing, representing a block of code containing instructions in resolving your purpose.

Controller not a function, got undefined, while defining controllers globally

I had this problem when I accidentally redeclared myApp:

var myApp = angular.module('myApp',[...]);
myApp.controller('Controller1', ...);

var myApp = angular.module('myApp',[...]);
myApp.controller('Controller2', ...);

After the redeclare, Controller1 stops working and raises the OP error.

PHP - Session destroy after closing browser

If you want to change the session id on each log in, make sure to use session_regenerate_id(true) during the log in process.

<?php
session_start();
session_regenerate_id(true);
?> 

Display special characters when using print statement

Do you merely want to print the string that way, or do you want that to be the internal representation of the string? If the latter, create it as a raw string by prefixing it with r: r"Hello\tWorld\nHello World".

>>> a = r"Hello\tWorld\nHello World"
>>> a # in the interpreter, this calls repr()
'Hello\\tWorld\\nHello World'
>>> print a
Hello\tWorld\nHello World

Also, \s is not an escape character, except in regular expressions, and then it still has a much different meaning than what you're using it for.

while-else-loop

Assuming you are coming from Python and accept this as the same thing:

def setLinkerAt(value, rowIndex):
    isEnough = lambda i: return i < dataColLinker.count()
    while (not isEnough(rowIndex)):
        dataColLinker.append(value)
    else:
        dataColLinker[rowIndex] = value 

The most similar I could come up with was:

public void setLinkerAt( int value, int rowIndex) {
    isEnough = (i) -> { return i < dataColLine.size; }
    if(isEnough()){
        dataColLinker.set(rowIndex, value);
    }
    else while(!isEnough(rowInex)) {
        dataColLinker.add(value);
    }

Note the need for the logic, and the reverse logic. I'm not sure this is a great solution (duplication of the logic), but the braceless else is the closest syntax I could think of, while maintaining the same act of not executing the logic more than required.

Extracting the last n characters from a string in R

Try this:

x <- "some text in a string"
n <- 5
substr(x, nchar(x)-n, nchar(x))

It shoudl give:

[1] "string"

Checking for multiple conditions using "when" on single task in ansible

Adding to https://stackoverflow.com/users/1638814/nvartolomei answer, which will probably fix your error.

Strictly answering your question, I just want to point out that the when: statement is probably correct, but would look easier to read in multiline and still fulfill your logic:

when: 
  - sshkey_result.rc == 1
  - github_username is undefined or 
    github_username |lower == 'none'

https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#the-when-statement

Permutation of array

Implementation via recursion (dynamic programming), in Java, with test case (TestNG).


Code

PrintPermutation.java

import java.util.Arrays;

/**
 * Print permutation of n elements.
 * 
 * @author eric
 * @date Oct 13, 2018 12:28:10 PM
 */
public class PrintPermutation {
    /**
     * Print permutation of array elements.
     * 
     * @param arr
     * @return count of permutation,
     */
    public static int permutation(int arr[]) {
        return permutation(arr, 0);
    }

    /**
     * Print permutation of part of array elements.
     * 
     * @param arr
     * @param n
     *            start index in array,
     * @return count of permutation,
     */
    private static int permutation(int arr[], int n) {
        int counter = 0;
        for (int i = n; i < arr.length; i++) {
            swapArrEle(arr, i, n);
            counter += permutation(arr, n + 1);
            swapArrEle(arr, n, i);
        }
        if (n == arr.length - 1) {
            counter++;
            System.out.println(Arrays.toString(arr));
        }

        return counter;
    }

    /**
     * swap 2 elements in array,
     * 
     * @param arr
     * @param i
     * @param k
     */
    private static void swapArrEle(int arr[], int i, int k) {
        int tmp = arr[i];
        arr[i] = arr[k];
        arr[k] = tmp;
    }
}

PrintPermutationTest.java (test case via TestNG)

import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * PrintPermutation test.
 * 
 * @author eric
 * @date Oct 14, 2018 3:02:23 AM
 */
public class PrintPermutationTest {
    @Test
    public void test() {
        int arr[] = new int[] { 0, 1, 2, 3 };
        Assert.assertEquals(PrintPermutation.permutation(arr), 24);

        int arrSingle[] = new int[] { 0 };
        Assert.assertEquals(PrintPermutation.permutation(arrSingle), 1);

        int arrEmpty[] = new int[] {};
        Assert.assertEquals(PrintPermutation.permutation(arrEmpty), 0);
    }
}

CSS selector (id contains part of text)

Try this:

a[id*='Some:Same'][id$='name']

This will get you all a elements with id containing

Some:Same

and have the id ending in

name

Count number of iterations in a foreach loop

$Contents = array(
    array('number'=>1), 
    array('number'=>2), 
    array('number'=>4), 
    array('number'=>4), 
    array('number'=>4), 
    array('number'=>5)
);

$counts = array();

foreach ($Contents as $item) {
    if (!isset($counts[$item['number']])) {
        $counts[$item['number']] = 0;
    }
    $counts[$item['number']]++;
}

echo $counts[4]; // output 3

mysql is not recognised as an internal or external command,operable program or batch

Simply type in command prompt :

set path=%PATH%;D:\xampp\mysql\bin;

Here my path started from D so I used D: , you can use C: or E:

enter image description here

jQuery make global variable

Your code looks fine except the possibility that if the variable declaration is inside a dom read handler then it will not be a global variable... it will be a closure variable

jQuery(function(){
    //here it is a closure variable
    var a_href;
    $('sth a').on('click', function(e){
        a_href = $(this).attr('href');

          console.log(a_href);  
         //output is "home"

        e.preventDefault();
    }
})

To make the variable global, one solution is to declare the variable in global scope

var a_href;
jQuery(function(){
    $('sth a').on('click', function(e){
        a_href = $(this).attr('href');

          console.log(a_href);  
         //output is "home"

        e.preventDefault();
    }
})

another is to set the variable as a property of the window object

window.a_href = $(this).attr('href')

Why console printing undefined

You are getting the output as undefined because even though the variable is declared, you have not initialized it with a value, the value of the variable is set only after the a element is clicked till that time the variable will have the value undefined. If you are not declaring the variable it will throw a ReferenceError

Why does one use dependency injection?

The main reason to use DI is that you want to put the responsibility of the knowledge of the implementation where the knowledge is there. The idea of DI is very much inline with encapsulation and design by interface. If the front end asks from the back end for some data, then is it unimportant for the front end how the back end resolves that question. That is up to the requesthandler.

That is already common in OOP for a long time. Many times creating code pieces like:

I_Dosomething x = new Impl_Dosomething();

The drawback is that the implementation class is still hardcoded, hence has the front end the knowledge which implementation is used. DI takes the design by interface one step further, that the only thing the front end needs to know is the knowledge of the interface. In between the DYI and DI is the pattern of a service locator, because the front end has to provide a key (present in the registry of the service locator) to lets its request become resolved. Service locator example:

I_Dosomething x = ServiceLocator.returnDoing(String pKey);

DI example:

I_Dosomething x = DIContainer.returnThat();

One of the requirements of DI is that the container must be able to find out which class is the implementation of which interface. Hence does a DI container require strongly typed design and only one implementation for each interface at the same time. If you need more implementations of an interface at the same time (like a calculator), you need the service locator or factory design pattern.

D(b)I: Dependency Injection and Design by Interface. This restriction is not a very big practical problem though. The benefit of using D(b)I is that it serves communication between the client and the provider. An interface is a perspective on an object or a set of behaviours. The latter is crucial here.

I prefer the administration of service contracts together with D(b)I in coding. They should go together. The use of D(b)I as a technical solution without organizational administration of service contracts is not very beneficial in my point of view, because DI is then just an extra layer of encapsulation. But when you can use it together with organizational administration you can really make use of the organizing principle D(b)I offers. It can help you in the long run to structure communication with the client and other technical departments in topics as testing, versioning and the development of alternatives. When you have an implicit interface as in a hardcoded class, then is it much less communicable over time then when you make it explicit using D(b)I. It all boils down to maintenance, which is over time and not at a time. :-)

Fatal error compiling: invalid target release: 1.8 -> [Help 1]

Do a force Maven Update which will bring the compatible 1.8 Jar Versions and then while building, update the JRE Versions in Execute environment to 1.8 from Run Configurations and hit RUN

Git Pull vs Git Rebase

git-pull - Fetch from and integrate with another repository or a local branch GIT PULL

Basically you are pulling remote branch to your local, example:

git pull origin master

Will pull master branch into your local repository

git-rebase - Forward-port local commits to the updated upstream head GIT REBASE

This one is putting your local changes on top of changes done remotely by other users. For example:

  • You have committed some changes on your local branch for example called SOME-FEATURE
  • Your friend in the meantime was working on other features and he merged his branch into master

Now you want to see his and your changes on your local branch. So then you checkout master branch:

git checkout master

then you can pull:

git pull origin master

and then you go to your branch:

git checkout SOME-FEATURE

and you can do rebase master to get lastest changes from it and put your branch commits on top:

git rebase master

I hope now it's a bit more clear for you.

How to pass a textbox value from view to a controller in MVC 4?

You can use simple form:

@using(Html.BeginForm("Update", "Shopping"))
{
    <input type="text" id="ss" name="qty" value="@item.Quantity"/>
    ...
    <input type="submit" value="Update" />
}

And add here attribute:

[HttpPost]
public ActionResult Update(string id, string productid, int qty, decimal unitrate)

Comparing two strings in C?

if(strcmp(sr1,str2)) // this returns 0 if strings r equal 
    flag=0;
else flag=1; // then last check the variable flag value and print the message 

                         OR

char str1[20],str2[20];
printf("enter first str > ");
gets(str1);
printf("enter second str > ");
gets(str2);

for(int i=0;str1[i]!='\0';i++)
{
    if(str[i]==str2[i])
         flag=0;
    else {flag=1; break;}
}

 //check the value of flag if it is 0 then strings r equal simple :)

How to make the window full screen with Javascript (stretching all over the screen)

Create Function

function toggleFullScreen() {

            if ((document.fullScreenElement && document.fullScreenElement !== null) ||
                    (!document.mozFullScreen && !document.webkitIsFullScreen)) {
             $scope.topMenuData.showSmall = true;
                if (document.documentElement.requestFullScreen) {
                    document.documentElement.requestFullScreen();
                } else if (document.documentElement.mozRequestFullScreen) {
                    document.documentElement.mozRequestFullScreen();
                } else if (document.documentElement.webkitRequestFullScreen) {
                    document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
                }
            } else {

                  $scope.topMenuData.showSmall = false;
                if (document.cancelFullScreen) {
                    document.cancelFullScreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitCancelFullScreen) {
                    document.webkitCancelFullScreen();
                }
            }
        }

In Html Put Code like

<ul class="unstyled-list fg-white">

            <li class="place-right" data-ng-if="!topMenuData.showSmall" data-ng-click="toggleFullScreen()">Full Screen</li>
            <li class="place-right" data-ng-if="topMenuData.showSmall" data-ng-click="toggleFullScreen()">Back</li>
        </ul>

Find if current time falls in a time range

if (new TimeSpan(11,59,0) <= currentTime.TimeOfDay && new TimeSpan(13,01,0) >=  currentTime.TimeOfDay)
{
   //match found
}

if you really want to parse a string into a TimeSpan, then you can use:

    TimeSpan start = TimeSpan.Parse("11:59");
    TimeSpan end = TimeSpan.Parse("13:01");

MetadataException: Unable to load the specified metadata resource

Sometimes i see this error in my project. I solve that by

1 - Right click on EDMX file

2 - Select Run Custom Tool option

3 - Rebuild project

python dataframe pandas drop column using int

Since there can be multiple columns with same name , we should first rename the columns. Here is code for the solution.

df.columns=list(range(0,len(df.columns)))
df.drop(columns=[1,2])#drop second and third columns

Angular 6: saving data to local storage

You should define a key name while storing data to local storage which should be a string and value should be a string

 localStorage.setItem('dataSource', this.dataSource.length);

and to print, you should use getItem

console.log(localStorage.getItem('dataSource'));

List vs tuple, when to use each?

There's a strong culture of tuples being for heterogeneous collections, similar to what you'd use structs for in C, and lists being for homogeneous collections, similar to what you'd use arrays for. But I've never quite squared this with the mutability issue mentioned in the other answers. Mutability has teeth to it (you actually can't change a tuple), while homogeneity is not enforced, and so seems to be a much less interesting distinction.

Convert all first letter to upper case, rest lower for each word

jspcal's answer as a string extension.

Program.cs

class Program
{
    static void Main(string[] args)
    {
        var myText = "MYTEXT";
        Console.WriteLine(myText.ToTitleCase()); //Mytext
    }
}

StringExtensions.cs

using System;
public static class StringExtensions
{

    public static string ToTitleCase(this string str)
    {
        if (str == null)
            return null;

        return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
    }
}

How to remove leading and trailing zeros in a string? Python

You can simply do this with a bool:

if int(number) == float(number):

   number = int(number)

else:

   number = float(number)

Difference between "on-heap" and "off-heap"

The heap is the place in memory where your dynamically allocated objects live. If you used new then it's on the heap. That's as opposed to stack space, which is where the function stack lives. If you have a local variable then that reference is on the stack. Java's heap is subject to garbage collection and the objects are usable directly.

EHCache's off-heap storage takes your regular object off the heap, serializes it, and stores it as bytes in a chunk of memory that EHCache manages. It's like storing it to disk but it's still in RAM. The objects are not directly usable in this state, they have to be deserialized first. Also not subject to garbage collection.

What is the difference between display: inline and display: inline-block?

Block - Element take complete width.All properties height , width, margin , padding work

Inline - element take height and width according to the content. Height , width , margin bottom and margin top do not work .Padding and left and right margin work. Example span and anchor.

Inline block - 1. Element don't take complete width, that is why it has *inline* in its name. All properties including height , width, margin top and margin bottom work on it. Which also work in block level element.That's why it has *block* in its name.

How to scp in Python?

Have a look at fabric.transfer.

from fabric import Connection

with Connection(host="hostname", 
                user="admin", 
                connect_kwargs={"key_filename": "/home/myuser/.ssh/private.key"}
               ) as c:
    c.get('/foo/bar/file.txt', '/tmp/')

Downloading an entire S3 bucket?

It's always better to use awscli for downloading / uploading files to s3. Sync will help you to resume without any hassle.

aws s3 sync s3://bucketname/ .

Vagrant stuck connection timeout retrying

It's a new 'feature' of vagrant. Take a look here: https://github.com/mitchellh/vagrant/issues/3329

They will change the 'Error' to 'Warning'. It's just telling you that the machine isn't booted yet, and it's trying to connect...

Difference between HttpModule and HttpClientModule

Don't want to be repetitive, but just to summarize in other way (features added in new HttpClient):

  • Automatic conversion from JSON to an object
  • Response type definition
  • Event firing
  • Simplified syntax for headers
  • Interceptors

I wrote an article, where I covered the difference between old "http" and new "HttpClient". The goal was to explain it in the easiest way possible.

Simply about new HttpClient in Angular

Add column with number of days between dates in DataFrame pandas

How about this:

times['days_since'] = max(list(df.index.values))  
times['days_since'] = times['days_since'] - times['months']  
times

Difference between AutoPostBack=True and AutoPostBack=False?

hai sir

There is one event which is default associate with any webcontrol. For example, in case of Button click event, in case of Check box CheckChangedEvent is there. So in case of AutoPostBack true these events are called by default and event handle at server sid

How to pass Multiple Parameters from ajax call to MVC Controller

function final_submit1() {
    var city = $("#city").val();
    var airport = $("#airport").val();

    var vehicle = $("#vehicle").val();

    if(city && airport){
    $.ajax({
        type:"POST",
        cache:false,
        data:{"city": city,"airport": airport},
        url:'http://airportLimo/ajax-car-list', 
        success: function (html) {
             console.log(html);
          //$('#add').val('data sent');
          //$('#msg').html(html);
           $('#pprice').html("Price: $"+html);
        }
      });

    }  
}

Mocking a class: Mock() or patch()?

mock.patch is a very very different critter than mock.Mock. patch replaces the class with a mock object and lets you work with the mock instance. Take a look at this snippet:

>>> class MyClass(object):
...   def __init__(self):
...     print 'Created MyClass@{0}'.format(id(self))
... 
>>> def create_instance():
...   return MyClass()
... 
>>> x = create_instance()
Created MyClass@4299548304
>>> 
>>> @mock.patch('__main__.MyClass')
... def create_instance2(MyClass):
...   MyClass.return_value = 'foo'
...   return create_instance()
... 
>>> i = create_instance2()
>>> i
'foo'
>>> def create_instance():
...   print MyClass
...   return MyClass()
...
>>> create_instance2()
<mock.Mock object at 0x100505d90>
'foo'
>>> create_instance()
<class '__main__.MyClass'>
Created MyClass@4300234128
<__main__.MyClass object at 0x100505d90>

patch replaces MyClass in a way that allows you to control the usage of the class in functions that you call. Once you patch a class, references to the class are completely replaced by the mock instance.

mock.patch is usually used when you are testing something that creates a new instance of a class inside of the test. mock.Mock instances are clearer and are preferred. If your self.sut.something method created an instance of MyClass instead of receiving an instance as a parameter, then mock.patch would be appropriate here.

Grouping functions (tapply, by, aggregate) and the *apply family

From slide 21 of http://www.slideshare.net/hadley/plyr-one-data-analytic-strategy:

apply, sapply, lapply, by, aggregate

(Hopefully it's clear that apply corresponds to @Hadley's aaply and aggregate corresponds to @Hadley's ddply etc. Slide 20 of the same slideshare will clarify if you don't get it from this image.)

(on the left is input, on the top is output)

Delete all lines beginning with a # from a file

you can directly edit your file with

sed -i '/^#/ d'

If you want also delete comment lines that start with some whitespace use

sed -i '/^\s*#/ d'

Usually, you want to keep the first line of your script, if it is a sha-bang, so sed should not delete lines starting with #!. also it should delete lines, that just contain only a hash but no text. put it all together:

sed -i '/^\s*\(#[^!].*\|#$\)/d'

To be conform with all sed variants you need to add a backup extension to the -i option:

sed -i.bak '/^\s*#/ d' $file
rm -Rf $file.bak

What is the 'dynamic' type in C# 4.0 used for?

Another use case for dynamic typing is for virtual methods that experience a problem with covariance or contravariance. One such example is the infamous Clone method that returns an object of the same type as the object it is called on. This problem is not completely solved with a dynamic return because it bypasses static type checking, but at least you don't need to use ugly casts all the time as per when using plain object. Otherwise to say, the casts become implicit.

public class A
{
    // attributes and constructor here
    public virtual dynamic Clone()
    {
        var clone = new A();
        // Do more cloning stuff here
        return clone;
    }
}

public class B : A
{
    // more attributes and constructor here
    public override dynamic Clone()
    {
        var clone = new B();    
        // Do more cloning stuff here
        return clone;
    }
}    

public class Program
{
    public static void Main()
    {
        A a = new A().Clone();  // No cast needed here
        B b = new B().Clone();  // and here
        // do more stuff with a and b
    }
}

Python coding standards/best practices

"In python do you generally use PEP 8 -- Style Guide for Python Code as your coding standards/guidelines? Are there any other formalized standards that you prefer?"

As mentioned by you follow PEP 8 for the main text, and PEP 257 for docstring conventions

Along with Python Style Guides, I suggest that you refer the following:

  1. Code Like a Pythonista: Idiomatic Python
  2. Common mistakes and Warts
  3. How not to write Python code
  4. Python gotcha

Not an enclosing class error Android Studio

replace code in onClick() method with this:

Intent myIntent = new Intent(this, Katra_home.class);
startActivity(myIntent);

What's the most efficient way to erase duplicates and sort a vector?

std::unique only removes duplicate elements if they're neighbours: you have to sort the vector first before it will work as you intend.

std::unique is defined to be stable, so the vector will still be sorted after running unique on it.

How can I check if an InputStream is empty without reading from it?

public void run() {
    byte[] buffer = new byte[256];  
    int bytes;                      

    while (true) {
        try {
            bytes = mmInStream.read(buffer);
            mHandler.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();
        } catch (IOException e) {
            break;
        }
    }
}

Invalid application of sizeof to incomplete type with a struct

It means the file containing main doesn't have access to the player structure definition (i.e. doesn't know what it looks like).

Try including it in header.h or make a constructor-like function that allocates it if it's to be an opaque object.

EDIT

If your goal is to hide the implementation of the structure, do this in a C file that has access to the struct:

struct player *
init_player(...)
{
    struct player *p = calloc(1, sizeof *p);

    /* ... */
    return p;
}

However if the implementation shouldn't be hidden - i.e. main should legally say p->canPlay = 1 it would be better to put the definition of the structure in header.h.

How to install SimpleJson Package for Python

If you have Python 2.6 installed then you already have simplejson - just import json; it's the same thing.

Using async/await with a forEach loop

With ES2018, you are able to greatly simplify all of the above answers to:

async function printFiles () {
  const files = await getFilePaths()

  for await (const contents of files.map(file => fs.readFile(file, 'utf8'))) {
    console.log(contents)
  }
}

See spec: proposal-async-iteration


2018-09-10: This answer has been getting a lot attention recently, please see Axel Rauschmayer's blog post for further information about asynchronous iteration: ES2018: asynchronous iteration

Return Bit Value as 1/0 and NOT True/False in SQL Server

just you pass this things in your select query. using CASE

CASE WHEN  gender=0 then 'Female' WHEN  gender=1 then 'Male' END as Genderdisp

tmux set -g mouse-mode on doesn't work

You can still using the devil logic of setting options depending on your current Tmux version: see my previous answer.

But since Tmux v1.7, set-option adds "-q" to silence errors and not print out anything (see changelog). I recommend to use this feature, it's more readable and easily expandable.

Add this to your ~/.tmux.conf:

# from v2.1
set -gq mouse on
# before v2.1
set -gq mode-mouse on
set -gq mouse-resize-pane on
set -gq mouse-select-pane on
set -gq mouse-select-window on

Restar tmux or source-file your new .tmux.conf


Side note: I'm open to remove my old answer if people prefer this one

Invoke JSF managed bean action on page load

@PostConstruct is run ONCE in first when Bean Created. the solution is create a Unused property and Do your Action in Getter method of this property and add this property to your .xhtml file like this :

<h:inputHidden  value="#{loginBean.loginStatus}"/>

and in your bean code:

public void setLoginStatus(String loginStatus) {
    this.loginStatus = loginStatus;
}

public String getLoginStatus()  {
    // Do your stuff here.
    return loginStatus;
}

What is path of JDK on Mac ?

On my Mac:

/System/Library/Frameworks/JavaVM.framework/Home/

btw, did you tried which java?

A reference to the dll could not be added

I just ran into that issue and after all the explanations about fixing it with command prompt I found that if you add it directly to the project you can then simply include the library on each page that it's needed

Good tool to visualise database schema?

Years ago, I used to use Data Architect. I don't know if it's still out there.

You could reverse engineer an existing schema into a relational table diagram.

Or you could go even further, and reverse engineer an Entity-Relationship model with an accompanying diagram. ER diagrams were really useful to me when discussing the data with people who were neither programmers nor database experts.

Sometimes a few manual fixups to the ER model and ER diagram were necessary before it was a useful communication tool with stakeholders.

Error in Python script "Expected 2D array, got 1D array instead:"?

I use the below approach.

reg = linear_model.LinearRegression()
reg.fit(df[['year']],df.income)

reg.predict([[2136]])

Doctrine query builder using inner join with conditions

I'm going to answer my own question.

  1. innerJoin should use the keyword "WITH" instead of "ON" (Doctrine's documentation [13.2.6. Helper methods] is inaccurate; [13.2.5. The Expr class] is correct)
  2. no need to link foreign keys in join condition as they're already specified in the entity mapping.

Therefore, the following works for me

$qb->select('c')
    ->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
    ->where('c.username = :username');

or

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
    ->where('c.username = :username');

Difference between static STATIC_URL and STATIC_ROOT on Django

STATICFILES_DIRS: You can keep the static files for your project here e.g. the ones used by your templates.

STATIC_ROOT: leave this empty, when you do manage.py collectstatic, it will search for all the static files on your system and move them here. Your static file server is supposed to be mapped to this folder wherever it is located. Check it after running collectstatic and you'll find the directory structure django has built.

--------Edit----------------

As pointed out by @DarkCygnus, STATIC_ROOT should point at a directory on your filesystem, the folder should be empty since it will be populated by Django.

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

or

STATIC_ROOT = '/opt/web/project/static_files'

--------End Edit -----------------

STATIC_URL: '/static/' is usually fine, it's just a prefix for static files.

New og:image size for Facebook share?

I'm using the minimum image size (200 x 200) and getting good results. Take a look:

enter image description here https://developers.facebook.com/tools/debug/og/object?q=origgami.com.br

This squared size is better than rectangles because it is the format that appears on facebook comments. The rectangle format gets cropped.

This size is on facebook documentation

XPath: difference between dot and text()

There is a difference between . and text(), but this difference might not surface because of your input document.

If your input document looked like (the simplest document one can imagine given your XPath expressions)

Example 1

<html>
  <a>Ask Question</a>
</html>

Then //a[text()="Ask Question"] and //a[.="Ask Question"] indeed return exactly the same result. But consider a different input document that looks like

Example 2

<html>
  <a>Ask Question<other/>
  </a>
</html>

where the a element also has a child element other that follows immediately after "Ask Question". Given this second input document, //a[text()="Ask Question"] still returns the a element, while //a[.="Ask Question"] does not return anything!


This is because the meaning of the two predicates (everything between [ and ]) is different. [text()="Ask Question"] actually means: return true if any of the text nodes of an element contains exactly the text "Ask Question". On the other hand, [.="Ask Question"] means: return true if the string value of an element is identical to "Ask Question".

In the XPath model, text inside XML elements can be partitioned into a number of text nodes if other elements interfere with the text, as in Example 2 above. There, the other element is between "Ask Question" and a newline character that also counts as text content.

To make an even clearer example, consider as an input document:

Example 3

<a>Ask Question<other/>more text</a>

Here, the a element actually contains two text nodes, "Ask Question" and "more text", since both are direct children of a. You can test this by running //a/text() on this document, which will return (individual results separated by ----):

Ask Question
-----------------------
more text

So, in such a scenario, text() returns a set of individual nodes, while . in a predicate evaluates to the string concatenation of all text nodes. Again, you can test this claim with the path expression //a[.='Ask Questionmore text'] which will successfully return the a element.


Finally, keep in mind that some XPath functions can only take one single string as an input. As LarsH has pointed out in the comments, if such an XPath function (e.g. contains()) is given a sequence of nodes, it will only process the first node and silently ignore the rest.

How to backup MySQL database in PHP?

If you want to backup a database from php script you could use a class for example lets call it MySQL. This class will use PDO (build in php class which will handle the connection to the database). This class could look like this:

<?php /*defined in your exampleconfig.php*/
define('DBUSER','root');
define('DBPASS','');
define('SERVERHOST','localhost');
?>

<?php /*defined in examplemyclass.php*/
    class MySql{
        private $dbc;
        private $user;
        private $pass;
        private $dbname;
        private $host;

        function __construct($host="localhost", $dbname="your_databse_name_here", $user="your_username", $pass="your_password"){
            $this->user = $user;
            $this->pass = $pass;
            $this->dbname = $dbname;
            $this->host = $host;
            $opt = array(
               PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
               PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            );
            try{
                $this->dbc = new PDO('mysql:host='.$this->host.';dbname='.$this->dbname.';charset=utf8', $user, $pass, $opt);
            }
            catch(PDOException $e){
                 echo $e->getMessage();
                 echo "There was a problem with connection to db check credenctials";
            }
        } /*end function*/


        public function backup_tables($tables = '*'){  /* backup the db OR just a table */
            $host=$this->host;
            $user=$this->user;
            $pass=$this->pass;
            $dbname=$this->dbname;
            $data = "";
            //get all of the tables
            if($tables == '*')
            {
                $tables = array();
                $result = $this->dbc->prepare('SHOW TABLES'); 
                $result->execute();                         
                while($row = $result->fetch(PDO::FETCH_NUM)) 
                { 
                    $tables[] = $row[0]; 
                }
            }
            else
            {
                $tables = is_array($tables) ? $tables : explode(',',$tables);
            }
            //cycle through
            foreach($tables as $table)
            {
                $resultcount = $this->dbc->prepare('SELECT count(*) FROM '.$table);
                $resultcount->execute();
                $num_fields = $resultcount->fetch(PDO::FETCH_NUM);
                $num_fields = $num_fields[0];

                $result = $this->dbc->prepare('SELECT * FROM '.$table);
                $result->execute();
                $data.= 'DROP TABLE '.$table.';';

                $result2 = $this->dbc->prepare('SHOW CREATE TABLE '.$table);    
                $result2->execute();                            
                $row2 = $result2->fetch(PDO::FETCH_NUM);
                $data.= "\n\n".$row2[1].";\n\n";

                for ($i = 0; $i < $num_fields; $i++) 
                {
                    while($row = $result->fetch(PDO::FETCH_NUM))
                    { 
                        $data.= 'INSERT INTO '.$table.' VALUES(';
                        for($j=0; $j<$num_fields; $j++) 
                        {
                            $row[$j] = addslashes($row[$j]); 
                            $row[$j] = str_replace("\n","\\n",$row[$j]);
                            if (isset($row[$j])) { $data.= '"'.$row[$j].'"' ; } else { $data.= '""'; }
                            if ($j<($num_fields-1)) { $data.= ','; }
                        }
                        $data.= ");\n";
                    }
                }
                $data.="\n\n\n";
            }
            //save filename
            $filename = 'db-backup-'.time().'-'.(implode(",",$tables)).'.sql';
            $this->writeUTF8filename($filename,$data);
        /*USE EXAMPLE
           $connection = new MySql(SERVERHOST,"your_db_name",DBUSER, DBPASS);
           $connection->backup_tables(); //OR backup_tables("posts");
           $connection->closeConnection();
        */
        } /*end function*/


        private function writeUTF8filename($filenamename,$content){  /* save as utf8 encoding */
            $f=fopen($filenamename,"w+"); 
            # Now UTF-8 - Add byte order mark 
            fwrite($f, pack("CCC",0xef,0xbb,0xbf)); 
            fwrite($f,$content); 
            fclose($f); 
        /*USE EXAMPLE this is only used by public function above...
            $this->writeUTF8filename($filename,$data);
        */
        } /*end function*/


        public function recoverDB($file_to_load){
            echo "write some code to load and proccedd .sql file in here ...";
        /*USE EXAMPLE this is only used by public function above...
            recoverDB("some_buck_up_file.sql");
        */
        } /*end function*/


        public function closeConnection(){
            $this->dbc = null;
        //EXAMPLE OF USE 
        /*$connection->closeConnection();*/
        }/*end function*/


    } /*END OF CLASS*/
    ?>

Now you could simply use this in your backup.php:

include ('config.php');
include ('myclass.php');
    $connection = new MySql(SERVERHOST,"your_databse_name_here",DBUSER, DBPASS);
    $connection->backup_tables(); /*Save all tables and it values in selected database*/
    $connection->backup_tables("post_table"); /*Saves only table name posts_table from selected database*/
    $connection->closeConnection();

Which means that visiting this page will result in backing up your file... of course it doesn't have to be that way :) you can call this method on every post to your database to be up to date all the time, however, I would recommend to write it to one file at all the time instead of creating new files with time()... as it is above.

Hope it helps and good luck ! :>

SQL Server convert string to datetime

UPDATE MyTable SET MyDate = CONVERT(datetime, '2009/07/16 08:28:01', 120)

For a full discussion of CAST and CONVERT, including the different date formatting options, see the MSDN Library Link below:

https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql

MySQL case sensitive query

To improve James' excellent answer:

It's better to put BINARY in front of the constant instead:

SELECT * FROM `table` WHERE `column` = BINARY 'value'

Putting BINARY in front of column will prevent the use of any index on that column.

Getting an element from a Set

The contract of the hash code makes clear that:

"If two objects are equal according to the Object method, then calling the hashCode method on each of the two objects must produce the same integer result."

So your assumption:

"To clarify, the equals method is overridden, but it only checks one of the fields, not all. So two Foo objects that are considered equal can actually have different values, that's why I can't just use foo."

is wrong and you are breaking the contract. If we look at the "contains" method of Set interface, we have that:

boolean contains(Object o);
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element "e" such that o==null ? e==null : o.equals(e)

To accomplish what you want, you can use a Map where you define the key and store your element with the key that defines how objects are different or equal to each other.

Please explain the exec() function and its family

exec is often used in conjunction with fork, which I saw that you also asked about, so I will discuss this with that in mind.

exec turns the current process into another program. If you ever watched Doctor Who, then this is like when he regenerates -- his old body is replaced with a new body.

The way that this happens with your program and exec is that a lot of the resources that the OS kernel checks to see if the file you are passing to exec as the program argument (first argument) is executable by the current user (user id of the process making the exec call) and if so it replaces the virtual memory mapping of the current process with a virtual memory the new process and copies the argv and envp data that were passed in the exec call into an area of this new virtual memory map. Several other things may also happen here, but the files that were open for the program that called exec will still be open for the new program and they will share the same process ID, but the program that called exec will cease (unless exec failed).

The reason that this is done this way is that by separating running a new program into two steps like this you can do some things between the two steps. The most common thing to do is to make sure that the new program has certain files opened as certain file descriptors. (remember here that file descriptors are not the same as FILE *, but are int values that the kernel knows about). Doing this you can:

int X = open("./output_file.txt", O_WRONLY);

pid_t fk = fork();
if (!fk) { /* in child */
    dup2(X, 1); /* fd 1 is standard output,
                   so this makes standard out refer to the same file as X  */
    close(X);

    /* I'm using execl here rather than exec because
       it's easier to type the arguments. */
    execl("/bin/echo", "/bin/echo", "hello world");
    _exit(127); /* should not get here */
} else if (fk == -1) {
    /* An error happened and you should do something about it. */
    perror("fork"); /* print an error message */
}
close(X); /* The parent doesn't need this anymore */

This accomplishes running:

/bin/echo "hello world" > ./output_file.txt

from the command shell.

Sum function in VBA

Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"

won't work because worksheet functions (when actually used on a worksheet) don't understand Range or Cell

Try

Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"

Simple java program of pyramid

You can try in this way.

   for(int a=5;a>0;a--){
        int b=0;
       for(b=0;b<a;b++){
           System.out.print(" ");
       }
        for (int j=b;j<5;j++){
            System.out.print(" $ ");
        }
        System.out.println("");

    }

Out put

      $ 
     $  $ 
    $  $  $ 
   $  $  $  $ 

How do I initialise all entries of a matrix with a specific value?

The ones method is much faster than using repmat:

>> tic; for i = 1:1e6, x=5*ones(10,1); end; toc
Elapsed time is 3.426347 seconds.
>> tic; for i = 1:1e6, y=repmat(5,10,1); end; toc
Elapsed time is 20.603680 seconds. 

And, in my opinion, makes for much more readable code.

How to delete from select in MySQL?

DELETE 
  p1
  FROM posts AS p1 
CROSS JOIN (
  SELECT ID FROM posts GROUP BY id HAVING COUNT(id) > 1
) AS p2
USING (id)

Convert byte slice to io.Reader

r := strings(byteData)

This also works to turn []byte into io.Reader

Efficiently sorting a numpy array in descending order?

Be careful with dimensions.

Let

x  # initial numpy array
I = np.argsort(x) or I = x.argsort() 
y = np.sort(x)    or y = x.sort()
z  # reverse sorted array

Full Reverse

z = x[I[::-1]]
z = -np.sort(-x)
z = np.flip(y)
  • flip changed in 1.15, previous versions 1.14 required axis. Solution: pip install --upgrade numpy.

First Dimension Reversed

z = y[::-1]
z = np.flipud(y)
z = np.flip(y, axis=0)

Second Dimension Reversed

z = y[::-1, :]
z = np.fliplr(y)
z = np.flip(y, axis=1)

Testing

Testing on a 100×10×10 array 1000 times.

Method       | Time (ms)
-------------+----------
y[::-1]      | 0.126659  # only in first dimension
-np.sort(-x) | 0.133152
np.flip(y)   | 0.121711
x[I[::-1]]   | 4.611778

x.sort()     | 0.024961
x.argsort()  | 0.041830
np.flip(x)   | 0.002026

This is mainly due to reindexing rather than argsort.

# Timing code
import time
import numpy as np


def timeit(fun, xs):
    t = time.time()
    for i in range(len(xs)):  # inline and map gave much worse results for x[-I], 5*t
        fun(xs[i])
    t = time.time() - t
    print(np.round(t,6))

I, N = 1000, (100, 10, 10)
xs = np.random.rand(I,*N)
timeit(lambda x: np.sort(x)[::-1], xs)
timeit(lambda x: -np.sort(-x), xs)
timeit(lambda x: np.flip(x.sort()), xs)
timeit(lambda x: x[x.argsort()[::-1]], xs)
timeit(lambda x: x.sort(), xs)
timeit(lambda x: x.argsort(), xs)
timeit(lambda x: np.flip(x), xs)

How can I get the Google cache age of any URL or web page?

you can Use CachedPages website

Cached pages are usually saved and stored by large companies with powerful web servers. Since such servers are usually very fast, a cached page can often be accessed faster than the live page itself:

  • Google usually keeps a recent copy of the page (1 to 15 days old).
  • Coral also keeps a recent copy, although it's usually not as recent as Google.
  • Through Archive.org, you can access several copies of a web page saved throughout the years.

Subtract two dates in Java

Edit 2018-05-28 I have changed the example to use Java 8's Time API:

LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE);
Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());
long diffDays = diff.toDays();

What is the purpose of global.asax in asp.net

The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level and session-level events raised by ASP.NET or by HTTP modules.

http://msdn.microsoft.com/en-us/library/2027ewzw.aspx

SQL Server Output Clause into a scalar variable

You need a table variable and it can be this simple.

declare @ID table (ID int)

insert into MyTable2(ID)
output inserted.ID into @ID
values (1)

Nginx serves .php files as downloads, instead of executing them

I had similar problem which was resolved by emptying the browser cache (also worked fine with different browser).

Print a div using javascript in angularJS single page application

$scope.printDiv = function(divName) {
  var printContents = document.getElementById(divName).innerHTML;
  var popupWin = window.open('', '_blank', 'width=300,height=300');
  popupWin.document.open();
  popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
  popupWin.document.close();
} 

Concatenating Files And Insert New Line In Between Files

You can do:

for f in *.txt; do (cat "${f}"; echo) >> finalfile.txt; done

Make sure the file finalfile.txt does not exist before you run the above command.

If you are allowed to use awk you can do:

awk 'FNR==1{print ""}1' *.txt > finalfile.txt

Twitter bootstrap modal-backdrop doesn't disappear

Recently I had this problem and none of solutions provided here helped me. Or it completely destroyed it so it could not be shown again. On document ready also did not work but what worked is that I wrapped all my listeners with immediately invoked function like this:

$(function () {
    $('#btn-show-modal').click(function () {
        $("#modal-lightbox").modal('show');
    });

    $('#btn-close-modal').click(function () {
        $("#modal-lightbox").modal('hide');
    });
});

How come I can't remove the blue textarea border in Twitter Bootstrap?

For anyone still searching. It's neither border or box-shadow. It's actually "outline". So just set outline: none; to disable it.

How do I add a simple onClick event handler to a canvas element?

Alex Answer is pretty neat but when using context rotate it can be hard to trace x,y coordinates, so I have made a Demo showing how to keep track of that.

Basically I am using this function & giving it the angle & the amount of distance traveled in that angel before drawing object.

function rotCor(angle, length){
    var cos = Math.cos(angle);
    var sin = Math.sin(angle);

    var newx = length*cos;
    var newy = length*sin;

    return {
        x : newx,
        y : newy
    };
}

How to convert image to byte array

This code retrieves first 100 rows from table in SQLSERVER 2012 and saves a picture per row as a file on local disk

 public void SavePicture()
    {
        SqlConnection con = new SqlConnection("Data Source=localhost;Integrated security=true;database=databasename");
        SqlDataAdapter da = new SqlDataAdapter("select top 100 [Name] ,[Picture] From tablename", con);
        SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
        DataSet ds = new DataSet("tablename");
        byte[] MyData = new byte[0];
        da.Fill(ds, "tablename");
        DataTable table = ds.Tables["tablename"];
           for (int i = 0; i < table.Rows.Count;i++ )               
               {
                DataRow myRow;
                myRow = ds.Tables["tablename"].Rows[i];
                MyData = (byte[])myRow["Picture"];
                int ArraySize = new int();
                ArraySize = MyData.GetUpperBound(0);
                FileStream fs = new FileStream(@"C:\NewFolder\" + myRow["Name"].ToString() + ".jpg", FileMode.OpenOrCreate, FileAccess.Write);
                fs.Write(MyData, 0, ArraySize);
                fs.Close();
               }

    }

please note: Directory with NewFolder name should exist in C:\

check if "it's a number" function in Oracle

How is the column defined? If its a varchar field, then its not a number (or stored as one). Oracle may be able to do the conversion for you (eg, select * from someTable where charField = 0), but it will only return rows where the conversion holds true and is possible. This is also far from ideal situation performance wise.

So, if you want to do number comparisons and treat this column as a number, perhaps it should be defined as a number?

That said, here's what you might do:

create or replace function myToNumber(i_val in varchar2) return number is
 v_num number;
begin
 begin
   select to_number(i_val) into v_num from dual;
 exception
   when invalid_number then
   return null;
 end;
 return v_num;
end;

You might also include the other parameters that the regular to_number has. Use as so:

select * from someTable where myToNumber(someCharField) > 0;

It won't return any rows that Oracle sees as an invalid number.

Cheers.

Catch paste input

This proved to be quite illusive. The value of the input is not updated prior to the execution of the code inside the paste event function. I tried calling other events from within the paste event function but the input value is still not updated with the pasted text inside the function of any events. That is all events apart from keyup. If you call keyup from within the paste event function you can sanitize the pasted text from within the keyup event function. like so...

$(':input').live
(
    'input paste',
    function(e)
    {
        $(this).keyup();
    }
);

$(':input').live
(
    'keyup',
    function(e)
    {
        // sanitize pasted text here
    }
);

There is one caveat here. In Firefox, if you reset the input text on every keyup, if the text is longer than the viewable area allowed by the input width, then resetting the value on every keyup breaks the browser functionality that auto scrolls the text to the caret position at the end of the text. Instead the text scrolls back to the beginning leaving the caret out of view.

ng-repeat finish event

Indeed, you should use directives, and there is no event tied to the end of a ng-Repeat loop (as each element is constructed individually, and has it's own event). But a) using directives might be all you need and b) there are a few ng-Repeat specific properties you can use to make your "on ngRepeat finished" event.

Specifically, if all you want is to style/add events to the whole of the table, you can do so using in a directive that encompasses all the ngRepeat elements. On the other hand, if you want to address each element specifically, you can use a directive within the ngRepeat, and it will act on each element, after it is created.

Then, there are the $index, $first, $middle and $last properties you can use to trigger events. So for this HTML:

<div ng-controller="Ctrl" my-main-directive>
  <div ng-repeat="thing in things" my-repeat-directive>
    thing {{thing}}
  </div>
</div>

You can use directives like so:

angular.module('myApp', [])
.directive('myRepeatDirective', function() {
  return function(scope, element, attrs) {
    angular.element(element).css('color','blue');
    if (scope.$last){
      window.alert("im the last!");
    }
  };
})
.directive('myMainDirective', function() {
  return function(scope, element, attrs) {
    angular.element(element).css('border','5px solid red');
  };
});

See it in action in this Plunker. Hope it helps!

What does "export" do in shell programming?

Exported variables such as $HOME and $PATH are available to (inherited by) other programs run by the shell that exports them (and the programs run by those other programs, and so on) as environment variables. Regular (non-exported) variables are not available to other programs.

$ env | grep '^variable='
$                                 # No environment variable called variable
$ variable=Hello                  # Create local (non-exported) variable with value
$ env | grep '^variable='
$                                 # Still no environment variable called variable
$ export variable                 # Mark variable for export to child processes
$ env | grep '^variable='
variable=Hello
$
$ export other_variable=Goodbye   # create and initialize exported variable
$ env | grep '^other_variable='
other_variable=Goodbye
$

For more information, see the entry for the export builtin in the GNU Bash manual, and also the sections on command execution environment and environment.

Note that non-exported variables will be available to subshells run via ( ... ) and similar notations because those subshells are direct clones of the main shell:

$ othervar=present
$ (echo $othervar; echo $variable; variable=elephant; echo $variable)
present
Hello
elephant
$ echo $variable
Hello
$

The subshell can change its own copy of any variable, exported or not, and may affect the values seen by the processes it runs, but the subshell's changes cannot affect the variable in the parent shell, of course.

Some information about subshells can be found under command grouping and command execution environment in the Bash manual.

Browser Caching of CSS files

It's probably worth noting that IE won't cache css files called by other css files using the @import method. So, for example, if your html page links to "master.css" which pulls in "reset.css" via @import, then reset.css will not be cached by IE.

Shortcut for echo "<pre>";print_r($myarray);echo "</pre>";

Nope, you'd just have to create your own function:

function printr($data) {
   echo "<pre>";
      print_r($data);
   echo "</pre>";
}

Apparantly, in 2018, people are still coming back to this question. The above would not be my current answer. I'd say: teach your editor to do it for you. I have a whole bunch of debug shortcuts, but my most used is vardd which expands to: var_dump(__FILE__ . ':' . __LINE__, $VAR$);die();

You can configure this in PHPStorm as a live template.

Truncate all tables in a MySQL database in one command?

No. There is no single command to truncate all mysql tables at once. You will have to create a small script to truncate the tables one by one.

ref: http://dev.mysql.com/doc/refman/5.0/en/truncate-table.html

I have filtered my Excel data and now I want to number the rows. How do I do that?

Step 1: Highlight the entire column (not including the header) of the column you wish to populate

Step 2: (Using Kutools) On the Insert dropdown, click "Fill Custom List"

Step 3: Click Edit

Step 4: Create your list (For Ex: 1, 2)

Step 5: Choose your new custom list and then click "Fill Range"

DONE!!!

How to set an iframe src attribute from a variable in AngularJS

I suspect looking at the excerpt that the function trustSrc from trustSrc(currentProject.url) is not defined in the controller.

You need to inject the $sce service in the controller and trustAsResourceUrl the url there.

In the controller:

function AppCtrl($scope, $sce) {
    // ...
    $scope.setProject = function (id) {
      $scope.currentProject = $scope.projects[id];
      $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
    }
}

In the Template:

<iframe ng-src="{{currentProjectUrl}}"> <!--content--> </iframe>

What's the best way to convert a number to a string in JavaScript?

If you need to format the result to a specific number of decimal places, for example to represent currency, you need something like the toFixed() method.

number.toFixed( [digits] )

digits is the number of digits to display after the decimal place.

How to read a single character at a time from a file in Python?

#reading out the file at once in a list and then printing one-by-one
f=open('file.txt')
for i in list(f.read()):
    print(i)

What does status=canceled for a resource mean in Chrome Developer Tools?

We had this problem having tag <button> in the form, that was supposed to send ajax request from js. But this request was canceled, due to browser, that sends form automatically on any click on button inside the form.

So if you realy want to use button instead of regular div or span on the page, and you want to send form throw js - you should setup a listener with preventDefault function.

e.g.

$('button').on('click', function(e){

    e.preventDefault();

    //do ajax
    $.ajax({

     ...
    });

})

ExpressionChangedAfterItHasBeenCheckedError Explained

A solution that worked for me using rxjs

import { startWith, tap, delay } from 'rxjs/operators';

// Data field used to populate on the html
dataSource: any;

....

ngAfterViewInit() {
  this.yourAsyncData.
      .pipe(
          startWith(null),
          delay(0),
          tap((res) => this.dataSource = res)
      ).subscribe();
}

Python - Module Not Found

After trying to add the path using:

pip show

on command prompt and using

sys.path.insert(0, "/home/myname/pythonfiles")

and didn't work. Also got SSL error when trying to install the module again using conda this time instead of pip.

I simply copied the module that wasn't found from the path "Mine was in

C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages 

so I copied it to 'C:\Users\user\Anaconda3\Lib\site-packages'

Excel VBA: Copying multiple sheets into new workbook

Try do something like this (the problem was that you trying to use MyBook.Worksheets, but MyBook is not a Workbook object, but string, containing workbook name. I've added new varible Set WB = ActiveWorkbook, so you can use WB.Worksheets instead MyBook.Worksheets):

Sub NewWBandPasteSpecialALLSheets()
   MyBook = ActiveWorkbook.Name ' Get name of this book
   Workbooks.Add ' Open a new workbook
   NewBook = ActiveWorkbook.Name ' Save name of new book

   Workbooks(MyBook).Activate ' Back to original book

   Set WB = ActiveWorkbook

   Dim SH As Worksheet

   For Each SH In WB.Worksheets

       SH.Range("WholePrintArea").Copy

       Workbooks(NewBook).Activate

       With SH.Range("A1")
        .PasteSpecial (xlPasteColumnWidths)
        .PasteSpecial (xlFormats)
        .PasteSpecial (xlValues)

       End With

     Next

End Sub

But your code doesn't do what you want: it doesen't copy something to a new WB. So, the code below do it for you:

Sub NewWBandPasteSpecialALLSheets()
   Dim wb As Workbook
   Dim wbNew As Workbook
   Dim sh As Worksheet
   Dim shNew As Worksheet

   Set wb = ThisWorkbook
   Workbooks.Add ' Open a new workbook
   Set wbNew = ActiveWorkbook

   On Error Resume Next

   For Each sh In wb.Worksheets
      sh.Range("WholePrintArea").Copy

      'add new sheet into new workbook with the same name
      With wbNew.Worksheets

          Set shNew = Nothing
          Set shNew = .Item(sh.Name)

          If shNew Is Nothing Then
              .Add After:=.Item(.Count)
              .Item(.Count).Name = sh.Name
              Set shNew = .Item(.Count)
          End If
      End With

      With shNew.Range("A1")
          .PasteSpecial (xlPasteColumnWidths)
          .PasteSpecial (xlFormats)
          .PasteSpecial (xlValues)
      End With
   Next
End Sub

How to remove the underline for anchors(links)?

I've been troubled with this problem in web printing and solved. Verified result.

a {
    text-decoration: none !important;
}

It works!.

What's the difference between @Component, @Repository & @Service annotations in Spring?

@Component, @ Repository, @ Service, @Controller:

@Component is a generic stereotype for the components managed by Spring @Repository, @Service, and @Controller are @Component specializations for more specific uses:

  • @Repository for persistence
  • @Service for services and transactions
  • @Controller for MVC controllers

Why use @Repository, @Service, @Controller over @Component? We can mark our component classes with @Component, but if instead we use the alternative that adapts to the expected functionality. Our classes are better suited to the functionality expected in each particular case.

A class annotated with @Repository has a better translation and readable error handling with org.springframework.dao.DataAccessException. Ideal for implementing components that access data (DataAccessObject or DAO).

An annotated class with @Controller plays a controller role in a Spring Web MVC application

An annotated class with @Service plays a role in business logic services, example Facade pattern for DAO Manager (Facade) and transaction handling

Set Culture in an ASP.Net MVC app

protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            if(Context.Session!= null)
            Thread.CurrentThread.CurrentCulture =
                    Thread.CurrentThread.CurrentUICulture = (Context.Session["culture"] ?? (Context.Session["culture"] = new CultureInfo("pt-BR"))) as CultureInfo;
        }

Python requests - print entire http request (raw)?

Since v1.2.3 Requests added the PreparedRequest object. As per the documentation "it contains the exact bytes that will be sent to the server".

One can use this to pretty print a request, like so:

import requests

req = requests.Request('POST','http://stackoverflow.com',headers={'X-Custom':'Test'},data='a=1&b=2')
prepared = req.prepare()

def pretty_print_POST(req):
    """
    At this point it is completely built and ready
    to be fired; it is "prepared".

    However pay attention at the formatting used in 
    this function because it is programmed to be pretty 
    printed and may differ from the actual request.
    """
    print('{}\n{}\r\n{}\r\n\r\n{}'.format(
        '-----------START-----------',
        req.method + ' ' + req.url,
        '\r\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
        req.body,
    ))

pretty_print_POST(prepared)

which produces:

-----------START-----------
POST http://stackoverflow.com/
Content-Length: 7
X-Custom: Test

a=1&b=2

Then you can send the actual request with this:

s = requests.Session()
s.send(prepared)

These links are to the latest documentation available, so they might change in content: Advanced - Prepared requests and API - Lower level classes

How can I export data to an Excel file

 private void button1_Click(object sender, EventArgs e)
    {
        Excel.Application xlApp ;
        Excel.Workbook xlWorkBook ;
        Excel.Worksheet xlWorkSheet ;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Add(misValue);

        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";

        xlWorkBook.SaveAs("csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();

        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlApp);

        MessageBox.Show("Excel file created , you can find the file c:\\csharp-Excel.xls");
    }

    private void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
        }
        finally
        {
            GC.Collect();
        }
    }

The above code is taken directly off csharp.net please take a look on the site.

How do you create a hidden div that doesn't create a line break or horizontal space?

Use style="display: none;". Also, you probably don't need to have the DIV, just setting the style to display: none on the checkbox would probably be sufficient.

Use '=' or LIKE to compare strings in SQL?

LIKE does matching like wildcards char [*, ?] at the shell
LIKE '%suffix' - give me everything that ends with suffix. You couldn't do that with =
Depends on the case actually.

iterrows pandas get next rows value

a combination of answers gave me a very fast running time. using the shift method to create new column of next row values, then using the row_iterator function as @alisdt did, but here i changed it from iterrows to itertuples which is 100 times faster.

my script is for iterating dataframe of duplications in different length and add one second for each duplication so they all be unique.

# create new column with shifted values from the departure time column
df['next_column_value'] = df['column_value'].shift(1)
# create row iterator that can 'save' the next row without running for loop
row_iterator = df.itertuples()
# jump to the next row using the row iterator
last = next(row_iterator)
# because pandas does not support items alteration i need to save it as an object
t = last[your_column_num]
# run and update the time duplications with one more second each
for row in row_iterator:
    if row.column_value == row.next_column_value:
         t = t + add_sec
         df_result.at[row.Index, 'column_name'] = t
    else:
         # here i resetting the 'last' and 't' values
         last = row
         t = last[your_column_num]

Hope it will help.

Can I draw rectangle in XML?

Create rectangle.xml using Shape Drawable Like this put in to your Drawable Folder...

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
   <solid android:color="@android:color/transparent"/>
   <corners android:radius="12px"/> 
   <stroke  android:width="2dip" android:color="#000000"/>  
</shape>

put it in to an ImageView

<ImageView 
android:id="@+id/rectimage" 
android:layout_height="150dp" 
android:layout_width="150dp" 
android:src="@drawable/rectangle">
</ImageView>

Hope this will help you.

Convert Map to JSON using Jackson

You can convert Map to JSON using Jackson as follows:

Map<String,String> payload = new HashMap<>();
payload.put("key1","value1");
payload.put("key2","value2");

String json = new ObjectMapper().writeValueAsString(payload);
System.out.println(json);

Is there a standardized method to swap two variables in Python?

Does not work for multidimensional arrays, because references are used here.

import numpy as np

# swaps
data = np.random.random(2)
print(data)
data[0], data[1] = data[1], data[0]
print(data)

# does not swap
data = np.random.random((2, 2))
print(data)
data[0], data[1] = data[1], data[0]
print(data)

See also Swap slices of Numpy arrays

How to use FormData in react-native?

I was looking for a long time an answer that solve the problem and this is the way I did it

I take the file with expo-document-picker

const pickDocument = async (tDocument) => {
    let result = await DocumentPicker.getDocumentAsync();
    result.type = mimetype(result.name);
    if (result.type === undefined){
      alert("not allowed extention");
      return null;
    }
    let formDat = new FormData();
    formDat.append("file", result);
    uploadDoc(formDat);
  };

  const mimetype = (name) => {
    let allow =  {"png":"image/png","pdf":"application/json","jpeg":"image/jpeg", "jpg":"image/jpg"};
    let extention = name.split(".")[1];
    if (allow[extention] !== undefined){
      return allow[extention]
    }
    else {
      return undefined
    }
  }

const uploadDoc = (data) =>  {
    fetch("MyApi", {
      method: "POST",
      body: data
    }).then(res => res.json())
    .then(response =>{
      if (response.result === 1) {
        //somecode
      } else {
        //somecode
      }
    });
  }

this is because android doesn't manage the mime-type of your file so if you put away the header "Content-type" and instead you put the mime-type on the file it gonna send the correct header

works on IOS an Android

Converting String array to java.util.List

First Step you need to create a list instance through Arrays.asList();

String[] args = new String[]{"one","two","three"};
List<String> list = Arrays.asList(args);//it converts to immutable list

Then you need to pass 'list' instance to new ArrayList();

List<String> newList=new ArrayList<>(list);

Sending HTTP POST Request In Java

A simple way using Apache HTTP Components is

Request.Post("http://www.example.com/page.php")
            .bodyForm(Form.form().add("id", "10").build())
            .execute()
            .returnContent();

Take a look at the Fluent API

Gets byte array from a ByteBuffer in java

This is a simple way to get a byte[], but part of the point of using a ByteBuffer is avoiding having to create a byte[]. Perhaps you can get whatever you wanted to get from the byte[] directly from the ByteBuffer.

How to set timeout in Retrofit library?

public class ApiModule {
    public WebService apiService(Context context) {
        String mBaseUrl = context.getString(BuildConfig.DEBUG ? R.string.local_url : R.string.live_url);

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(120, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .connectTimeout(120, TimeUnit.SECONDS)
                .addInterceptor(loggingInterceptor)
                //.addNetworkInterceptor(networkInterceptor)
                .build();

        return new Retrofit.Builder().baseUrl(mBaseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build().create(WebService.class);

    }
}

Setting graph figure size

Write it as a one-liner:

figure('position', [0, 0, 200, 500])  % create new figure with specified size  

enter image description here

How to use Scanner to accept only valid int as input

  1. the condition num2 < num1 should be num2 <= num1 if num2 has to be greater than num1
  2. not knowing what the kb object is, I'd read a String and then trying Integer.parseInt() and if you don't catch an exception then it's a number, if you do, read a new one, maybe by setting num2 to Integer.MIN_VALUE and using the same type of logic in your example.

Install Visual Studio 2013 on Windows 7

The minimum requirements are based on the Express edition you're attempting to install:

Express for Web (Web sites and HTML5 applications) - Windows 7 SP1 (With IE 10)
Express for Windows (Windows 8 Apps) - Windows 8.1
Express for Windows Desktop (Windows Programs) - Windows 7 SP1 (With IE 10)
Express for Windows Phone (Windows Phone Apps) - Windows 8

It sounds like you're trying to install the "Express 2013 for Windows" edition, which is for developing Windows 8 "Modern UI" apps, or the Windows Phone edition.

The similarly named version that is compatible with Windows 7 SP1 is "Express 2013 for Windows Desktop"

Source

Avoid synchronized(this) in Java?

I'll cover each point separately.

  1. Some evil code may steal your lock (very popular this one, also has an "accidentally" variant)

    I'm more worried about accidentally. What it amounts to is that this use of this is part of your class' exposed interface, and should be documented. Sometimes the ability of other code to use your lock is desired. This is true of things like Collections.synchronizedMap (see the javadoc).

  2. All synchronized methods within the same class use the exact same lock, which reduces throughput

    This is overly simplistic thinking; just getting rid of synchronized(this) won't solve the problem. Proper synchronization for throughput will take more thought.

  3. You are (unnecessarily) exposing too much information

    This is a variant of #1. Use of synchronized(this) is part of your interface. If you don't want/need this exposed, don't do it.

A hex viewer / editor plugin for Notepad++?

Is a completely different (but still free) application an option? I use HxD, and it serves me better than the Notepad++ plugin. It can calculate hashes, open memory of a process, it is fast at opening files of any size, and it works exceptionally well with the clipboard.

I used to use the Notepad++ plugin, but not anymore.

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.

A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t

... which yields:

t  a  avg
----------
1  1  3.00
2  5  3.00
3  3  4.33
4  5  4.00
5  4  6.67
6 11  7.50

As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding) and the subsequent row (1 following).

When you write ROWS UNBOUNDED PRECEDING, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t

yielding...

t  a  sum
---------
1  1    1
2  5    6
3  3    9
4  5   14
5  4   18
6 11   29

Here's another very good explanations of SQL window functions.

Best way to write to the console in PowerShell

The middle one writes to the pipeline. Write-Host and Out-Host writes to the console. 'echo' is an alias for Write-Output which writes to the pipeline as well. The best way to write to the console would be using the Write-Host cmdlet.

When an object is written to the pipeline it can be consumed by other commands in the chain. For example:

"hello world" | Do-Something

but this won't work since Write-Host writes to the console, not to the pipeline (Do-Something will not get the string):

Write-Host "hello world" | Do-Something

CSS display:table-row does not expand when width is set to 100%

If you're using display:table-row etc., then you need proper markup, which includes a containing table. Without it your original question basically provides the equivalent bad markup of:

<tr style="width:100%">
    <td>Type</td>
    <td style="float:right">Name</td>
</tr>

Where's the table in the above? You can't just have a row out of nowhere (tr must be contained in either table, thead, tbody, etc.)

Instead, add an outer element with display:table, put the 100% width on the containing element. The two inside cells will automatically go 50/50 and align the text right on the second cell. Forget floats with table elements. It'll cause so many headaches.

markup:

<div class="view-table">
    <div class="view-row">
        <div class="view-type">Type</div>
        <div class="view-name">Name</div>                
    </div>
</div>

CSS:

.view-table
{
    display:table;
    width:100%;
}
.view-row,
{
    display:table-row;
}
.view-row > div
{
    display: table-cell;
}
.view-name 
{
    text-align:right;
}

How to center a button within a div?

Easiest thing is input it as a "div" give it a "margin:0 auto " but if you want it to be centered u need to give it a width

  Div{
   Margin: 0 auto ;
   Width: 100px ;
  }

Print ArrayList

This helped to me:

System.out.println(Arrays.toString(codeLangArray.toArray()));

How do I create an array of strings in C?

Or you can declare a struct type, that contains a character arry(1 string), them create an array of the structs and thus a multi-element array

typedef struct name
{
   char name[100]; // 100 character array
}name;

main()
{
   name yourString[10]; // 10 strings
   printf("Enter something\n:);
   scanf("%s",yourString[0].name);
   scanf("%s",yourString[1].name);
   // maybe put a for loop and a few print ststements to simplify code
   // this is just for example 
 }

One of the advantages of this over any other method is that this allows you to scan directly into the string without having to use strcpy;

Array of arrays (Python/NumPy)

If the file is only numerical values separated by tabs, try using the csv library: http://docs.python.org/library/csv.html (you can set the delimiter to '\t')

If you have a textual file in which every line represents a row in a matrix and has integers separated by spaces\tabs, wrapped by a 'arrayname = [...]' syntax, you should do something like:

import re
f = open("your-filename", 'rb')
result_matrix = []
for line in f.readlines():
    match = re.match(r'\s*\w+\s+\=\s+\[(.*?)\]\s*', line)
    if match is None:
        pass # line syntax is wrong - ignore the line
    values_as_strings = match.group(1).split()
    result_matrix.append(map(int, values_as_strings))

Transport endpoint is not connected

I have exactly the same problem. I haven't found a solution anywhere, but I have been able to fix it without rebooting by simply unmounting and remounting the mountpoint.

For your system the commands would be:

fusermount -uz /data
mount /data

The -z forces the unmount, which solved the need to reboot for me. You may need to do this as sudo depending on your setup. You may encounter the below error if the command does not have the required elevated permissions:

fusermount: entry for /data not found in /etc/mtab

I'm using Ubuntu 14.04 LTS, with the current version of mhddfs.

is there a function in lodash to replace matched item

You can do it without using lodash.

let arr = [{id: 1, name: "Person 1"}, {id: 2, name: "Person 2"}];
let newObj = {id: 1, name: "new Person"}

/*Add new prototype function on Array class*/
Array.prototype._replaceObj = function(newObj, key) {
  return this.map(obj => (obj[key] === newObj[key] ? newObj : obj));
};

/*return [{id: 1, name: "new Person"}, {id: 2, name: "Person 2"}]*/
arr._replaceObj(newObj, "id") 

Check if pull needed in Git

There are many very feature rich and ingenious answers already. To provide some contrast, I could make do with a very simple line.

# Check return value to see if there are incoming updates.
if ! git diff --quiet remotes/origin/HEAD; then
 # pull or whatever you want to do
fi

Large Numbers in Java

Depending on what you're doing you might like to take a look at GMP (gmplib.org) which is a high-performance multi-precision library. To use it in Java you need JNI wrappers around the binary library.

See some of the Alioth Shootout code for an example of using it instead of BigInteger to calculate Pi to an arbitrary number of digits.

https://benchmarksgame-team.pages.debian.net/benchmarksgame/program/pidigits-java-2.html

CSS hexadecimal RGBA?

I'm afraid that's not possible. the rgba format you know is the only one.

SOAP or REST for Web Services?

1.From my experience. I would say REST gives you option to access the URL which is already built. eg-> a word search in google. That URL could be used as webservice for REST. In SOAP, you can create your own web service and access it through SOAP client.

  1. REST supports text,JSON,XML format. Hence more versatile for communicating between two applications. While SOAP supports only XML format for message communication.

How does MySQL process ORDER BY and LIMIT in a query?

LIMIT is usually applied as the last operation, so the result will first be sorted and then limited to 20. In fact, sorting will stop as soon as first 20 sorted results are found.

How do I get some variable from another class in Java?

I am trying to get int x equal to 5 (as seen in the setNum() method) but when it prints it gives me 0.

To run the code in setNum you have to call it. If you don't call it, the default value is 0.

Alternate output format for psql

you can use the zenity to displays the query output as html table.

  • first implement bash script with following code:

    cat > '/tmp/sql.op'; zenity --text-info --html --filename='/tmp/sql.op';

    save it like mypager.sh

  • Then export the environment variable PAGER by set full path of the script as value.

    for example:- export PAGER='/path/mypager.sh'

  • Then login to the psql program then execute the command \H

  • And finally execute any query,the tabled output will displayed in the zenity in html table format.

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

    <sonar.language>java</sonar.language>
    <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
    <sonar.jacoco.reportPath>${user.dir}/target/jacoco.exec</sonar.jacoco.reportPath>
    <sonar.jacoco.itReportPath>${user.dir}/target/jacoco-it.exec</sonar.jacoco.itReportPath>
    <sonar.exclusions>
        file:**/target/generated-sources/**,
        file:**/target/generated-test-sources/**,
        file:**/target/test-classes/**,
        file:**/model/*.java,
        file:**/*Config.java,
        file:**/*App.java
    </sonar.exclusions>

            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.7.9</version>
                <executions>
                    <execution>
                        <id>default-prepare-agent</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <destFile>${sonar.jacoco.reportPath}</destFile>
                            <append>true</append>
                            <propertyName>surefire.argLine</propertyName>
                        </configuration>
                    </execution>
                    <execution>
                        <id>default-prepare-agent-integration</id>
                        <goals>
                            <goal>prepare-agent-integration</goal>
                        </goals>
                        <configuration>
                            <destFile>${sonar.jacoco.itReportPath}</destFile>
                            <append>true</append>
                            <propertyName>failsafe.argLine</propertyName>
                        </configuration>
                    </execution>
                    <execution>
                        <id>default-report</id>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>default-report-integration</id>
                        <goals>
                            <goal>report-integration</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>             

Is the practice of returning a C++ reference variable evil?

About horrible code:

int& getTheValue()
{
   return *new int;
}

So, indeed, memory pointer lost after return. But if you use shared_ptr like that:

int& getTheValue()
{
   std::shared_ptr<int> p(new int);
   return *p->get();
}

Memory not lost after return and will be freed after assignment.

How to find foreign key dependencies in SQL Server?

The following query will help to get you started. It lists all Foreign Key Relationships within the current database.

SELECT
    FK_Table = FK.TABLE_NAME,
    FK_Column = CU.COLUMN_NAME,
    PK_Table = PK.TABLE_NAME,
    PK_Column = PT.COLUMN_NAME,
    Constraint_Name = C.CONSTRAINT_NAME
FROM
    INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
    ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
    ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
    ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
            SELECT
                i1.TABLE_NAME,
                i2.COLUMN_NAME
            FROM
                INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
            INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2
                ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
            WHERE
                i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
           ) PT
    ON PT.TABLE_NAME = PK.TABLE_NAME

You can also view relationships graphically within SQL Server Management studio within Database Diagrams.

Example of Mockito's argumentCaptor

I agree with what @fge said, more over. Lets look at example. Consider you have a method:

class A {
    public void foo(OtherClass other) {
        SomeData data = new SomeData("Some inner data");
        other.doSomething(data);
    }
}

Now if you want to check the inner data you can use the captor:

// Create a mock of the OtherClass
OtherClass other = mock(OtherClass.class);

// Run the foo method with the mock
new A().foo(other);

// Capture the argument of the doSomething function
ArgumentCaptor<SomeData> captor = ArgumentCaptor.forClass(SomeData.class);
verify(other, times(1)).doSomething(captor.capture());

// Assert the argument
SomeData actual = captor.getValue();
assertEquals("Some inner data", actual.innerData);

Remove carriage return in Unix

I'm going to assume you mean carriage returns (CR, "\r", 0x0d) at the ends of lines rather than just blindly within a file (you may have them in the middle of strings for all I know). Using this test file with a CR at the end of the first line only:

$ cat infile
hello
goodbye

$ cat infile | od -c
0000000   h   e   l   l   o  \r  \n   g   o   o   d   b   y   e  \n
0000017

dos2unix is the way to go if it's installed on your system:

$ cat infile | dos2unix -U | od -c
0000000   h   e   l   l   o  \n   g   o   o   d   b   y   e  \n
0000016

If for some reason dos2unix is not available to you, then sed will do it:

$ cat infile | sed 's/\r$//' | od -c
0000000   h   e   l   l   o  \n   g   o   o   d   b   y   e  \n
0000016

If for some reason sed is not available to you, then ed will do it, in a complicated way:

$ echo ',s/\r\n/\n/
> w !cat
> Q' | ed infile 2>/dev/null | od -c
0000000   h   e   l   l   o  \n   g   o   o   d   b   y   e  \n
0000016

If you don't have any of those tools installed on your box, you've got bigger problems than trying to convert files :-)

Angular JS update input field after change

You can add ng-change directive to input fields. Have a look at the docs example.

What does [STAThread] do?

The STAThreadAttribute marks a thread to use the Single-Threaded COM Apartment if COM is needed. By default, .NET won't initialize COM at all. It's only when COM is needed, like when a COM object or COM Control is created or when drag 'n' drop is needed, that COM is initialized. When that happens, .NET calls the underlying CoInitializeEx function, which takes a flag indicating whether to join the thread to a multi-threaded or single-threaded apartment.

Read more info here (Archived, June 2009)

and

Why is STAThread required?

How to connect SQLite with Java?

If you are using Netbeans using Maven to add library is easier. I have tried using above solutions but it didn't work.

<dependencies>
    <dependency>
      <groupId>org.xerial</groupId>
      <artifactId>sqlite-jdbc</artifactId>
      <version>3.7.2</version>
    </dependency>
</dependencies>

I have added Maven dependency and java.lang.ClassNotFoundException: org.sqlite.JDBC error gone.

Callback when DOM is loaded in react.js

What I have found is that simply wrapping code in the componentDidMount or componentDidUpdate with a setTimeout with a time of 0 milliseconds ensures that the browser DOM has been updated with the React changes before executing the setTimeout function.

Like this:

componentDidMount() {
    setTimeout(() => {
        $("myclass") //  $ is available here
    }, 0)
}

This puts the anonymous function on the JS Event Queue to run immediately after the currently running React stack frame has completed.

BitBucket - download source as ZIP

For the latest version of Bitbucket (2016+), the download link can be found in the Download menu item.

enter image description here


Pre-2016

First method

In the Overview page of the repo, there is a link to download the project.

Direct download of a repo


Second method

Go to Downloads -> Branches -> Download the branch that you want (as .zip, .gz or .bz2). There you'll find download links for all tags. The links will be in the format:

https://bitbucket.org/owner/repository/get/v0.1.2.tar.gz

By tweaking it a little bit, you can also have access to any revision by changing the tag to the commit hash:

https://bitbucket.org/owner/repository/get/A0B1C2D.tar.gz

Is there an effective tool to convert C# code to Java code?

I'm not sure what you are trying to do by wishing to convert C# to java, but if it is .net interoperability that you need, you might want to check out Mono