Programs & Examples On #Extreme programming

Extreme programming is an Agile Software Development Methodology created by Kent Beck. Extreme Programming values communication, simplicity, feedback, respect, and courage. XP prescribes a number of engineering practices including, test-driven development, a focus on automated testing, pair programming, simple design and refactoring.

How do I do word Stemming or Lemmatization?

Based on various answers on Stack Overflow and blogs I've come across, this is the method I'm using, and it seems to return real words quite well. The idea is to split the incoming text into an array of words (use whichever method you'd like), and then find the parts of speech (POS) for those words and use that to help stem and lemmatize the words.

You're sample above doesn't work too well, because the POS can't be determined. However, if we use a real sentence, things work much better.

import nltk
from nltk.corpus import wordnet

lmtzr = nltk.WordNetLemmatizer().lemmatize


def get_wordnet_pos(treebank_tag):
    if treebank_tag.startswith('J'):
        return wordnet.ADJ
    elif treebank_tag.startswith('V'):
        return wordnet.VERB
    elif treebank_tag.startswith('N'):
        return wordnet.NOUN
    elif treebank_tag.startswith('R'):
        return wordnet.ADV
    else:
        return wordnet.NOUN


def normalize_text(text):
    word_pos = nltk.pos_tag(nltk.word_tokenize(text))
    lemm_words = [lmtzr(sw[0], get_wordnet_pos(sw[1])) for sw in word_pos]

    return [x.lower() for x in lemm_words]

print(normalize_text('cats running ran cactus cactuses cacti community communities'))
# ['cat', 'run', 'ran', 'cactus', 'cactuses', 'cacti', 'community', 'community']

print(normalize_text('The cactus ran to the community to see the cats running around cacti between communities.'))
# ['the', 'cactus', 'run', 'to', 'the', 'community', 'to', 'see', 'the', 'cat', 'run', 'around', 'cactus', 'between', 'community', '.']

Is it possible to declare a public variable in vba and assign a default value?

.NET has spoiled us :) Your declaration is not valid for VBA.

Only constants can be given a value upon application load. You declare them like so:

Public Const APOSTROPHE_KEYCODE = 222

Here's a sample declaration from one of my vba projects:

VBA Constant Image

If you're looking for something where you declare a public variable and then want to initialize its value, you need to create a Workbook_Open sub and do your initialization there. Example:

Private Sub Workbook_Open()
  Dim iAnswer As Integer

  InitializeListSheetDataColumns_S
  HideAllMonths_S

  If sheetSetupInfo.Range("D6").Value = "Enter Facility Name" Then
    iAnswer = MsgBox("It appears you have not yet set up this workbook.  Would you like to do so now?", vbYesNo)
    If iAnswer = vbYes Then
      sheetSetupInfo.Activate
      sheetSetupInfo.Range("D6").Select
      Exit Sub
    End If
  End If

  Application.Calculation = xlCalculationAutomatic
  sheetGeneralInfo.Activate
  Load frmInfoSheet
  frmInfoSheet.Show


End Sub

Make sure you declare the sub in the Workbook Object itself: enter image description here

Return HTML content as a string, given URL. Javascript Function

In some websites, XMLHttpRequest may send you something like <script src="#"></srcipt>. In that case, try using a HTML document like the script under:

<html>
  <body>
    <iframe src="website.com"></iframe>
    <script src="your_JS"></script>
  </body>
</html>

Now you can use JS to get some text out of the HTML, such as getElementbyId.

But this may not work for some websites with cross-domain blocking.

How to call a JavaScript function from PHP?

If you want to echo it out for later execution it's ok

If you want to execute the JS and use the results in PHP use V8JS

V8Js::registerExtension('say_hi', 'print("hey from extension! "); var said_hi=true;', array(), true);
$v8 = new V8Js();
$v8->executeString('print("hello from regular code!")', 'test.php');
$v8->executeString('if (said_hi) { print(" extension already said hi"); }');

You can refer here for further reference: What are Extensions in php v8js?

If you want to execute HTML&JS and use the output in PHP http://htmlunit.sourceforge.net/ is your solution

Node.js https pem error: routines:PEM_read_bio:no start line

You are probably using the wrong certificate file, what you need to do is generate a self signed certificate which can be done as follows

openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem
openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out server.crt

then use the server.crt

   var options = {
      key: fs.readFileSync('./key.pem', 'utf8'),
      cert: fs.readFileSync('./server.crt', 'utf8')
   };

How to parseInt in Angular.js

You cannot (at least at the moment) use parseInt inside angular expressions, as they're not evaluated directly. Quoting the doc:

Angular does not use JavaScript's eval() to evaluate expressions. Instead Angular's $parse service processes these expressions.

Angular expressions do not have access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs.

So you can define a total() method in your controller, then use it in the expression:

// ... somewhere in controller
$scope.total = function() { 
  return parseInt($scope.num1) + parseInt($scope.num2) 
}

// ... in HTML
Total: {{ total() }}

Still, that seems to be rather bulky for a such a simple operation as adding the numbers. The alternative is converting the results with -0 op:

Total: {{num1-0 + (num2-0)|number}}

... but that'll obviously won't parseInt values, only cast them to Numbers (|number filter prevents showing null if this cast results in NaN). So choose the approach that suits your particular case.

see if two files have the same content in python

Yes, I think hashing the file would be the best way if you have to compare several files and store hashes for later comparison. As hash can clash, a byte-by-byte comparison may be done depending on the use case.

Generally byte-by-byte comparison would be sufficient and efficient, which filecmp module already does + other things too.

See http://docs.python.org/library/filecmp.html e.g.

>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False

Speed consideration: Usually if only two files have to be compared, hashing them and comparing them would be slower instead of simple byte-by-byte comparison if done efficiently. e.g. code below tries to time hash vs byte-by-byte

Disclaimer: this is not the best way of timing or comparing two algo. and there is need for improvements but it does give rough idea. If you think it should be improved do tell me I will change it.

import random
import string
import hashlib
import time

def getRandText(N):
    return  "".join([random.choice(string.printable) for i in xrange(N)])

N=1000000
randText1 = getRandText(N)
randText2 = getRandText(N)

def cmpHash(text1, text2):
    hash1 = hashlib.md5()
    hash1.update(text1)
    hash1 = hash1.hexdigest()

    hash2 = hashlib.md5()
    hash2.update(text2)
    hash2 = hash2.hexdigest()

    return  hash1 == hash2

def cmpByteByByte(text1, text2):
    return text1 == text2

for cmpFunc in (cmpHash, cmpByteByByte):
    st = time.time()
    for i in range(10):
        cmpFunc(randText1, randText2)
    print cmpFunc.func_name,time.time()-st

and the output is

cmpHash 0.234999895096
cmpByteByByte 0.0

Giving a border to an HTML table row, <tr>

You can set border properties on a tr element, but according to the CSS 2.1 specification, such properties have no effect in the separated borders model, which tends to be the default in browsers. Ref.: 17.6.1 The separated borders model. (The initial value of border-collapse is separate according to CSS 2.1, and some browsers also set it as default value for table. The net effect anyway is that you get separated border on almost all browsers unless you explicitly specifi collapse.)

Thus, you need to use collapsing borders. Example:

<style>
table { border-collapse: collapse; }
tr:nth-child(3) { border: solid thin; }
</style>

SQL Server SELECT INTO @variable?

you can do this:

SELECT 
    CustomerId, 
    FirstName, 
    LastName, 
    Email
INTO #tempCustomer 
FROM 
    Customer
WHERE 
    CustomerId = @CustomerId

then later

SELECT CustomerId FROM #tempCustomer

you doesn't need to declare the structure of #tempCustomer

Arrays in unix shell?

The Bourne shell and C shell don't have arrays, IIRC.

In addition to what others have said, in Bash you can get the number of elements in an array as follows:

elements=${#arrayname[@]}

and do slice-style operations:

arrayname=(apple banana cherry)
echo ${arrayname[@]:1}                   # yields "banana cherry"
echo ${arrayname[@]: -1}                 # yields "cherry"
echo ${arrayname[${#arrayname[@]}-1]}    # yields "cherry"
echo ${arrayname[@]:0:2}                 # yields "apple banana"
echo ${arrayname[@]:1:1}                 # yields "banana"

What is the most robust way to force a UIView to redraw?

The guaranteed, rock solid way to force a UIView to re-render is [myView setNeedsDisplay]. If you're having trouble with that, you're likely running into one of these issues:

  • You're calling it before you actually have the data, or your -drawRect: is over-caching something.

  • You're expecting the view to draw at the moment you call this method. There is intentionally no way to demand "draw right now this very second" using the Cocoa drawing system. That would disrupt the entire view compositing system, trash performance and likely create all kinds of artifacting. There are only ways to say "this needs to be drawn in the next draw cycle."

If what you need is "some logic, draw, some more logic," then you need to put the "some more logic" in a separate method and invoke it using -performSelector:withObject:afterDelay: with a delay of 0. That will put "some more logic" after the next draw cycle. See this question for an example of that kind of code, and a case where it might be needed (though it's usually best to look for other solutions if possible since it complicates the code).

If you don't think things are getting drawn, put a breakpoint in -drawRect: and see when you're getting called. If you're calling -setNeedsDisplay, but -drawRect: isn't getting called in the next event loop, then dig into your view hierarchy and make sure you're not trying to outsmart is somewhere. Over-cleverness is the #1 cause of bad drawing in my experience. When you think you know best how to trick the system into doing what you want, you usually get it doing exactly what you don't want.

jQuery Set Select Index

you can set selectoption variable value dynamically as well as option will be selected.You can try following code

code:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

      $(function(){
            $('#allcheck').click(function(){
             // $('#select_option').val([1,2,5]);also can use multi selectbox
              // $('#select_option').val(1);
               var selectoption=3;
           $("#selectBox>option[value="+selectoption+"]").attr('selected', 'selected');
    });

});

HTML CODE:

   <select id="selectBox">
       <option value="0">Number 0</option>
       <option value="1">Number 1</option>
       <option value="2">Number 2</option>
       <option value="3">Number 3</option>
       <option value="4">Number 4</option>
       <option value="5">Number 5</option>
       <option value="6">Number 6</option>
       <option value="7">Number 7</option>
 </select> <br>
<strong>Select&nbsp;&nbsp; <a style="cursor:pointer;" id="allcheck">click for select option</a></strong>

How can I install Python's pip3 on my Mac?

If you're using Python 3, just execute python3 get-pip.py . It is just a simple command.

subtract time from date - moment js

Moment.subtract does not support an argument of type Moment - documentation:

moment().subtract(String, Number);
moment().subtract(Number, String); // 2.0.0
moment().subtract(String, String); // 2.7.0
moment().subtract(Duration); // 1.6.0
moment().subtract(Object);

The simplest solution is to specify the time delta as an object:

// Assumes string is hh:mm:ss
var myString = "03:15:00",
    myStringParts = myString.split(':'),
    hourDelta: +myStringParts[0],
    minuteDelta: +myStringParts[1];


date.subtract({ hours: hourDelta, minutes: minuteDelta});
date.toString()
// -> "Sat Jun 07 2014 06:07:06 GMT+0100"

How to print last two columns using awk

@jim mcnamara: try using parentheses for around NF, i. e. $(NF-1) and $(NF) instead of $NF-1 and $NF (works on Mac OS X 10.6.8 for FreeBSD awkand gawk).

echo '
1 2
2 3
one
one two three
' | gawk '{if (NF >= 2) print $(NF-1), $(NF);}'

# output:
# 1 2
# 2 3
# two three

Why can't I find SQL Server Management Studio after installation?

It appears that SQL Server 2008 R2 can be downloaded with or without the management tools. I honestly have NO IDEA why someone would not want the management tools. But either way, the options are here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

and the one for 64 bit WITH the management tools (management studio) is here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

From the first link I presented, the 3rd and 4th include the management studio for 32 and 64 bit respectively.

Java JTable setting Column Width

With JTable.AUTO_RESIZE_OFF, the table will not change the size of any of the columns for you, so it will take your preferred setting. If it is your goal to have the columns default to your preferred size, except to have the last column fill the rest of the pane, You have the option of using the JTable.AUTO_RESIZE_LAST_COLUMN autoResizeMode, but it might be most effective when used with TableColumn.setMaxWidth() instead of TableColumn.setPreferredWidth() for all but the last column.

Once you are satisfied that AUTO_RESIZE_LAST_COLUMN does in fact work, you can experiment with a combination of TableColumn.setMaxWidth() and TableColumn.setMinWidth()

how to return a char array from a function in C

Daniel is right: http://ideone.com/kgbo1C#view_edit_box

Change

test=substring(i,j,*s);

to

test=substring(i,j,s);  

Also, you need to forward declare substring:

char *substring(int i,int j,char *ch);

int main // ...

Write Array to Excel Range

The kind of array definition seems the key: In my case it is a one dimension array of 17 items which have to convert to a two dimension array

Defintion for columns: object[,] Array = new object[17, 1];

Defintion for rows object[,] Array= new object[1,17];

The code for value2 is in both cases the same Excel.Range cell = activeWorksheet.get_Range(Range); cell.Value2 = Array;

LG Georg

Is it safe to expose Firebase apiKey to the public?

I believe once database rules are written accurately, it will be enough to protect your data. Moreover, there are guidelines that one can follow to structure your database accordingly. For example, making a UID node under users, and putting all under information under it. After that, you will need to implement a simple database rule as below

  "rules": {
    "users": {
      "$uid": {
        ".read": "auth != null && auth.uid == $uid",
        ".write": "auth != null && auth.uid == $uid"
      }
    }
  }
}

No other user will be able to read other users' data, moreover, domain policy will restrict requests coming from other domains. One can read more about it on Firebase Security rules

Remove items from one list in another

In my case I had two different lists, with a common identifier, kind of like a foreign key. The second solution cited by "nzrytmn":

var result =  list1.Where(p => !list2.Any(x => x.ID == p.ID && x.property1 == p.property1)).ToList();

Was the one that best fit in my situation. I needed to load a DropDownList without the records that had already been registered.

Thank you !!!

This is my code:

t1 = new T1();
t2 = new T2();

List<T1> list1 = t1.getList();
List<T2> list2 = t2.getList();

ddlT3.DataSource= list2.Where(s => !list1.Any(p => p.Id == s.ID)).ToList();
ddlT3.DataTextField = "AnyThing";
ddlT3.DataValueField = "IdAnyThing";
ddlT3.DataBind();

How to use LDFLAGS in makefile

Your linker (ld) obviously doesn't like the order in which make arranges the GCC arguments so you'll have to change your Makefile a bit:

CC=gcc
CFLAGS=-Wall
LDFLAGS=-lm

.PHONY: all
all: client

.PHONY: clean
clean:
    $(RM) *~ *.o client

OBJECTS=client.o
client: $(OBJECTS)
    $(CC) $(CFLAGS) $(OBJECTS) -o client $(LDFLAGS)

In the line defining the client target change the order of $(LDFLAGS) as needed.

Get top n records for each group of grouped results

There is a really nice answer to this problem at MySQL - How To Get Top N Rows per Each Group

Based on the solution in the referenced link, your query would be like:

SELECT Person, Group, Age
   FROM
     (SELECT Person, Group, Age, 
                  @group_rank := IF(@group = Group, @group_rank + 1, 1) AS group_rank,
                  @current_group := Group 
       FROM `your_table`
       ORDER BY Group, Age DESC
     ) ranked
   WHERE group_rank <= `n`
   ORDER BY Group, Age DESC;

where n is the top n and your_table is the name of your table.

I think the explanation in the reference is really clear. For quick reference I will copy and paste it here:

Currently MySQL does not support ROW_NUMBER() function that can assign a sequence number within a group, but as a workaround we can use MySQL session variables.

These variables do not require declaration, and can be used in a query to do calculations and to store intermediate results.

@current_country := country This code is executed for each row and stores the value of country column to @current_country variable.

@country_rank := IF(@current_country = country, @country_rank + 1, 1) In this code, if @current_country is the same we increment rank, otherwise set it to 1. For the first row @current_country is NULL, so rank is also set to 1.

For correct ranking, we need to have ORDER BY country, population DESC

Finding Number of Cores in Java

int cores = Runtime.getRuntime().availableProcessors();

If cores is less than one, either your processor is about to die, or your JVM has a serious bug in it, or the universe is about to blow up.

Hook up Raspberry Pi via Ethernet to laptop without router?

Configure static ip for your laptop and raspberry pi. On the rapberryPI configure it as following.

pi@rpi>sudo nano /etc/network/interfaces

Then configure following as required to connect to your laptop.

iface eth0 inet static

address 192.168.1.81

netmask 255.255.255.0

broadcast 192.168.1.255

Primitive type 'short' - casting in Java

I'd like to add something that hasn't been pointed out. Java doesn't take into account the values you have given the variables (2 and 3) in...

short a = 2; short b = 3; short c = a + b;

So as far as Java knows, you could done this...

short a = 32767; short b = 32767; short c = a + b;

Which would be outside the range of short, it autoboxes the result to an int becuase it's "possible" that the result will be more than a short but not more than an int. Int was chosen as a "default" because basically most people wont be hard coding values above 2,147,483,647 or below -2,147,483,648

How do you move a file?

Subversion has native support for moving files.

svn move SOURCE DESTINATION

See the online help (svn help move) for more information.

Server cannot set status after HTTP headers have been sent IIS7.5

Just to add to the responses above. I had this same issue when i first started using ASP.Net MVC and i was doing a Response.Redirect during a controller action:

Response.Redirect("/blah", true);

Instead of returning a Response.Redirect action i should have been returning a RedirectAction:

return Redirect("/blah");

CSS: how to add white space before element's content?

You can use the unicode of a non breaking space :

p:before { content: "\00a0 "; }

See JSfiddle demo

[style improved by @Jason Sperske]

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

Short answer:

const base64Canvas = canvas.toDataURL("image/jpeg").split(';base64,')[1];

Javascript swap array elements

Using ES6 it's possible to do it like this...

Imagine you have these 2 arrays...

const a = ["a", "b", "c", "d", "e"];
const b = [5, 4, 3, 2, 1];

and you want to swap the first values:

const [a0] = a;
a[0] = b[0];
b[0] = a0;

and value:

a; //[5, "b", "c", "d", "e"]
b; //["a", 4, 3, 2, 1]

How to change the font color of a disabled TextBox?

If you want to display text that cannot be edited or selected you can simply use a label

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

I just experienced a similar message [ mine was "Permission denied (publickey)"] after connecting to a compute engine VM which I just created. After reading this post, I decided to try it again.

That time it worked. So i see 3 possible reasons for it working the second time,

  • connecting the second time resolves the problem (after the ssh key was created the first time), or
  • perhaps trying to connect to a compute engine immediately after it was created could also cause a problem which resolves itself after a while, or
  • merely reading this post resolves the problem

I suspect the last is unlikely :)

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

Please make sure that your applicationContext.xml file is loaded by specifying it in your web.xml file:

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

For..In loops in JavaScript - key value pairs

ES6 will provide Map.prototype.forEach(callback) which can be used like this

myMap.forEach(function(value, key, myMap) {
                        // Do something
                    });

Can I use if (pointer) instead of if (pointer != NULL)?

Yes, you can. The ability to compare values to zeros implicitly has been inherited from C, and is there in all versions of C++. You can also use if (!pointer) to check pointers for NULL.

Getting rid of all the rounded corners in Twitter Bootstrap

The code posted above by @BrunoS did not work for me,

* {
  .border-radius(0) !important;
}

what i used was

* {
  border-radius: 0 !important;
}

I hope this helps someone

Excel - match data from one range to another and get the value from the cell to the right of the matched data

Put this formula in cell d31 and copy down to d39

 =iferror(vlookup(b31,$f$3:$g$12,2,0),"")

Here's what is going on. VLOOKUP:

  • Takes a value (here the contents of b31),
  • Looks for it in the first column of a range (f3:f12 in the range f3:g12), and
  • Returns the value for the corresponding row in a column in that range (in this case, the 2nd column or g3:g12 of the range f3:g12).

As you know, the last argument of VLOOKUP sets the match type, with FALSE or 0 indicating an exact match.

Finally, IFERROR handles the #N/A when VLOOKUP does not find a match.

What is "overhead"?

You could use a dictionary. The definition is the same. But to save you time, Overhead is work required to do the productive work. For instance, an algorithm runs and does useful work, but requires memory to do its work. This memory allocation takes time, and is not directly related to the work being done, therefore is overhead.

Convert DataSet to List

Here's extension method to convert DataTable to object list:

    public static class Extensions
    {
        public static List<T> ToList<T>(this DataTable table) where T : new()
        {
            IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
            List<T> result = new List<T>();

            foreach (var row in table.Rows)
            {
                var item = CreateItemFromRow<T>((DataRow)row, properties);
                result.Add(item);
            }

            return result;
        }

        private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
        {
            T item = new T();
            foreach (var property in properties)
            {
                if (property.PropertyType == typeof(System.DayOfWeek))
                {
                    DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString());
                    property.SetValue(item,day,null);
                }
                else
                {
                    if(row[property.Name] == DBNull.Value)
                        property.SetValue(item, null, null);
                    else 
                        property.SetValue(item, row[property.Name], null); 
                }
            }
            return item;
        }
    }

usage:

List<Employee> lst = ds.Tables[0].ToList<Employee>();

@itay.b CODE EXPLAINED: We first read all the property names from the class T using reflection
then we iterate through all the rows in datatable and create new object of T,
then we set the properties of the newly created object using reflection.

The property values are picked from the row's matching column cell.

PS: class property name and table column names must be same

How to use nan and inf in C?

double a_nan = strtod("NaN", NULL);
double a_inf = strtod("Inf", NULL);

Android Fragment onAttach() deprecated

This worked for me when i have userdefined Interface 'TopSectionListener', its object activitycommander:

  //This method gets called whenever we attach fragment to the activity
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    Activity a=getActivity();
    try {
        if(context instanceof Activity)
           this.activitycommander=(TopSectionListener)a;
    }catch (ClassCastException e){
        throw new ClassCastException(a.toString());}

}

Why doesn't RecyclerView have onItemClickListener()?

Here you can handle multiple onclick see below code and it is very efficient

    public class RVNewsAdapter extends RecyclerView.Adapter<RVNewsAdapter.FeedHolder> {

    private Context context;
    List<News> newsList;
    // Allows to remember the last item shown on screen
    private int lastPosition = -1;

    public RVNewsAdapter(List<News> newsList, Context context) {
        this.newsList = newsList;
        this.context = context;
    }

    public static class FeedHolder extends RecyclerView.ViewHolder implements OnClickListener {

        ImageView img_main;
        TextView tv_title;
        Button bt_facebook, bt_twitter, bt_share, bt_comment;


        public FeedHolder(View itemView) {
            super(itemView);

            img_main = (ImageView) itemView.findViewById(R.id.img_main);
            tv_title = (TextView) itemView.findViewById(R.id.tv_title);
            bt_facebook = (Button) itemView.findViewById(R.id.bt_facebook);
            bt_twitter = (Button) itemView.findViewById(R.id.bt_twitter);
            bt_share = (Button) itemView.findViewById(R.id.bt_share);
            bt_comment = (Button) itemView.findViewById(R.id.bt_comment);

            img_main.setOnClickListener(this);
            bt_facebook.setOnClickListener(this);
            bt_twitter.setOnClickListener(this);
            bt_comment.setOnClickListener(this);
            bt_share.setOnClickListener(this);

        }


        @Override
        public void onClick(View v) {

            if (v.getId() == bt_comment.getId()) {

                Toast.makeText(v.getContext(), "Comment  " , Toast.LENGTH_SHORT).show();

            } else if (v.getId() == bt_facebook.getId()) {

                Toast.makeText(v.getContext(), "Facebook  " , Toast.LENGTH_SHORT).show();

            } else if (v.getId() == bt_twitter.getId()) {

                Toast.makeText(v.getContext(), "Twitter  " , Toast.LENGTH_SHORT).show();

            } else if (v.getId() == bt_share.getId()) {

                Toast.makeText(v.getContext(), "share  " , Toast.LENGTH_SHORT).show();

            }
            else {
                Toast.makeText(v.getContext(), "ROW PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    @Override
    public FeedHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_row, parent, false);
        FeedHolder feedHolder = new FeedHolder(view);

        return feedHolder;
    }

    @Override
    public void onBindViewHolder(FeedHolder holder, int position) {

        holder.tv_title.setText(newsList.get(position).getTitle());


        // Here you apply the animation when the view is bound
        setAnimation(holder.img_main, position);
    }

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


    /**
     * Here is the key method to apply the animation
     */
    private void setAnimation(View viewToAnimate, int position) {
        // If the bound view wasn't previously displayed on screen, it's animated
        if (position > lastPosition) {
            Animation animation = AnimationUtils.loadAnimation(context, android.R.anim.slide_in_left);
            viewToAnimate.startAnimation(animation);
            lastPosition = position;
        }
    }


}

Namespace not recognized (even though it is there)

In my case removing/adding that assembly worked.

getElementsByClassName not working

If you want to do it by ClassName you could do:

<script type="text/javascript">
function hideTd(className){
    var elements;

    if (document.getElementsByClassName)
    {
        elements = document.getElementsByClassName(className);
    }
    else
    {
        var elArray = [];
        var tmp = document.getElementsByTagName(elements);  
        var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
        for ( var i = 0; i < tmp.length; i++ ) {

            if ( regex.test(tmp[i].className) ) {
                elArray.push(tmp[i]);
            }
        }

        elements = elArray;
    }

    for(var i = 0, i < elements.length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>

ASP.NET MVC Razor render without encoding

HTML RAW :

@Html.Raw(yourString)

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

If you downloaded the file from the internet, either separately or inside a .zip file or similar, it may have been "locked" because it is flagged as coming from the internet zone. Many programs will use this as a sign that the content should not be trusted.

The simplest solution is to right-click the file in Windows Explorer, select Properties, and along the bottom of this dialog, you should have an "Unblock" option. Remember to click OK to accept the change.

If you got the file from an archive, it is usually better to unblock the archive first, if the file is flagged as coming from the internet zone, and you unzip it, that flag might propagate to many of the files you just unarchived. If you unblock first, the unarchived files should be fine.

There's also a Powershell command for this, Unblock-File:

> Unblock-File *

Additionally, there are ways to write code that will remove the lock as well.

From the comments by @Defcon1: You can also combine Unblock-File with Get-ChildItem to create a pipeline that unblocks file recursively. Since Unblock-File has no way to find files recursively by itself, you have to use Get-ChildItem to do that part.

> Get-ChildItem -Path '<YOUR-SOLUTION-PATH>' -Recurse | Unblock-File

How to select Python version in PyCharm?

Quick Answer:

  • File --> Setting
  • In left side in project section --> Project interpreter
  • Select desired Project interpreter
  • Apply + OK

[NOTE]:

Tested on Pycharm 2018 and 2017.


Hive Alter table change Column Name

Change Column Name/Type/Position/Comment:

ALTER TABLE table_name CHANGE [COLUMN] col_old_name col_new_name column_type [COMMENT col_comment] [FIRST|AFTER column_name]

Example:

CREATE TABLE test_change (a int, b int, c int);

// will change column a's name to a1
ALTER TABLE test_change CHANGE a a1 INT;

How do I uninstall a Windows service if the files do not exist anymore?

The easiest way is to use Sys Internals Autoruns

enter image description here

Start it in admin mode and then you can remove obsolete services by delete key

convert htaccess to nginx

You can easily make a Php script to parse your old htaccess, I am using this one for PRestashop rules :

$content = $_POST['content'];

    $lines   = explode(PHP_EOL, $content);
    $results = '';

    foreach($lines as $line)
    {
        $items = explode(' ', $line);

        $q = str_replace("^", "^/", $items[1]);

        if (substr($q, strlen($q) - 1) !== '$') $q .= '$';

        $buffer = 'rewrite "'.$q.'" "'.$items[2].'" last;';

        $results .= $buffer.PHP_EOL;
    }

    die($results);

Is it possible to hide the cursor in a webpage using CSS or Javascript?

Pointer Lock API

While the cursor: none CSS solution is definitely a solid and easy workaround, if your actual goal is to remove the default cursor while your web application is being used, or implement your own interpretation of raw mouse movement (for FPS games, for example), you might want to consider using the Pointer Lock API instead.

You can use requestPointerLock on an element to remove the cursor, and redirect all mousemove events to that element (which you may or may not handle):

document.body.requestPointerLock();

To release the lock, you can use exitPointerLock:

document.exitPointerLock();

Additional notes

No cursor, for real

This is a very powerful API call. It not only renders your cursor invisible, but it actually removes your operating system's native cursor. You won't be able to select text, or do anything with your mouse (except listening to some mouse events in your code) until the pointer lock is released (either by using exitPointerLock or pressing ESC in some browsers).

That is, you cannot leave the window with your cursor for it to show again, as there is no cursor.

Restrictions

As mentioned above, this is a very powerful API call, and is thus only allowed to be made in response to some direct user-interaction on the web, such as a click; for example:

document.addEventListener("click", function () {
    document.body.requestPointerLock();
});

Also, requestPointerLock won't work from a sandboxed iframe unless the allow-pointer-lock permission is set.

User-notifications

Some browsers will prompt the user for a confirmation before the lock is engaged, some will simply display a message. This means pointer lock might not activate right away after the call. However, the actual activation of pointer locking can be listened to by listening to the pointerchange event on the element on which requestPointerLock was called:

document.body.addEventListener("pointerlockchange", function () {
    if (document.pointerLockElement === document.body) {
        // Pointer is now locked to <body>.
    }
});

Most browsers will only display the message once, but Firefox will occasionally spam the message on every single call. AFAIK, this can only be worked around by user-settings, see Disable pointer-lock notification in Firefox.

Listening to raw mouse movement

The Pointer Lock API not only removes the mouse, but instead redirects raw mouse movement data to the element requestPointerLock was called on. This can be listened to simply by using the mousemove event, then accessing the movementX and movementY properties on the event object:

document.body.addEventListener("mousemove", function (e) {
    console.log("Moved by " + e.movementX + ", " + e.movementY);
});

A warning - comparison between signed and unsigned integer expressions

It is usually a good idea to declare variables as unsigned or size_t if they will be compared to sizes, to avoid this issue. Whenever possible, use the exact type you will be comparing against (for example, use std::string::size_type when comparing with a std::string's length).

Compilers give warnings about comparing signed and unsigned types because the ranges of signed and unsigned ints are different, and when they are compared to one another, the results can be surprising. If you have to make such a comparison, you should explicitly convert one of the values to a type compatible with the other, perhaps after checking to ensure that the conversion is valid. For example:

unsigned u = GetSomeUnsignedValue();
int i = GetSomeSignedValue();

if (i >= 0)
{
    // i is nonnegative, so it is safe to cast to unsigned value
    if ((unsigned)i >= u)
        iIsGreaterThanOrEqualToU();
    else
        iIsLessThanU();
}
else
{
    iIsNegative();
}

System.loadLibrary(...) couldn't find native library in my case

actually, you can't just put a .so file in the /libs/armeabi/ and load it with System.loadLibrary. You need to create an Android.mk file and declare a prebuilt module where you specify your .so file as a source.

To do so, put your .so file and the Android.mk file in the jni folder. Your Android.mk should look something like that:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE    := libcalculate
LOCAL_SRC_FILES := libcalculate.so
include $(PREBUILT_SHARED_LIBRARY)

Source : Android NDK documentation about prebuilt

Awaiting multiple Tasks with different results

Forward Warning

Just a quick headsup to those visiting this and other similar threads looking for a way to parallelize EntityFramework using async+await+task tool-set: The pattern shown here is sound, however, when it comes to the special snowflake of EF you will not achieve parallel execution unless and until you use a separate (new) db-context-instance inside each and every *Async() call involved.

This sort of thing is necessary due to inherent design limitations of ef-db-contexts which forbid running multiple queries in parallel in the same ef-db-context instance.


Capitalizing on the answers already given, this is the way to make sure that you collect all values even in the case that one or more of the tasks results in an exception:

  public async Task<string> Foobar() {
    async Task<string> Awaited(Task<Cat> a, Task<House> b, Task<Tesla> c) {
        return DoSomething(await a, await b, await c);
    }

    using (var carTask = BuyCarAsync())
    using (var catTask = FeedCatAsync())
    using (var houseTask = SellHouseAsync())
    {
        if (carTask.Status == TaskStatus.RanToCompletion //triple
            && catTask.Status == TaskStatus.RanToCompletion //cache
            && houseTask.Status == TaskStatus.RanToCompletion) { //hits
            return Task.FromResult(DoSomething(catTask.Result, carTask.Result, houseTask.Result)); //fast-track
        }

        cat = await catTask;
        car = await carTask;
        house = await houseTask;
        //or Task.AwaitAll(carTask, catTask, houseTask);
        //or await Task.WhenAll(carTask, catTask, houseTask);
        //it depends on how you like exception handling better

        return Awaited(catTask, carTask, houseTask);
   }
 }

An alternative implementation that has more or less the same performance characteristics could be:

 public async Task<string> Foobar() {
    using (var carTask = BuyCarAsync())
    using (var catTask = FeedCatAsync())
    using (var houseTask = SellHouseAsync())
    {
        cat = catTask.Status == TaskStatus.RanToCompletion ? catTask.Result : (await catTask);
        car = carTask.Status == TaskStatus.RanToCompletion ? carTask.Result : (await carTask);
        house = houseTask.Status == TaskStatus.RanToCompletion ? houseTask.Result : (await houseTask);

        return DoSomething(cat, car, house);
     }
 }

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

I use the following for VB.Net:

<%# If(Eval("item").ToString() Is DBNull.Value, "0 value", Eval("item")) %>

jquery validate check at least one checkbox

Mmm first your id attributes must be unique, your code is likely to be

<form>
<input class='roles' name='roles' type='checkbox' value='1' />
<input class='roles' name='roles' type='checkbox' value='2' />
<input class='roles' name='roles' type='checkbox' value='3' />
<input class='roles' name='roles' type='checkbox' value='4' />
<input class='roles' name='roles' type='checkbox' value='5' />
<input type='submit' value='submit' />
</form>

For your problem :

if($('.roles:checkbox:checked').length == 0)
  // no checkbox checked, do something...
else
  // at least one checkbox checked...

BUT, remember that a JavaScript form validation is only indicative, all validations MUST be done server-side.

How to set recurring schedule for xlsm file using Windows Task Scheduler

Three important steps - How to Task Schedule an excel.xls(m) file

simply:

  1. make sure the .vbs file is correct
  2. set the Action tab correctly in Task Scheduler
  3. don't turn on "Run whether user is logged on or not"

IN MORE DETAIL...

  1. Here is an example .vbs file:

`

'   a .vbs file is just a text file containing visual basic code that has the extension renamed from .txt  to .vbs

'Write Excel.xls  Sheet's full path here
strPath = "C:\RodsData.xlsm" 

'Write the macro name - could try including module name
strMacro = "Update" '    "Sheet1.Macro2" 

'Create an Excel instance and set visibility of the instance
Set objApp = CreateObject("Excel.Application") 
objApp.Visible = True   '   or False 

'Open workbook; Run Macro; Save Workbook with changes; Close; Quit Excel
Set wbToRun = objApp.Workbooks.Open(strPath) 
objApp.Run strMacro     '   wbToRun.Name & "!" & strMacro 
wbToRun.Save 
wbToRun.Close 
objApp.Quit 

'Leaves an onscreen message!
MsgBox strPath & " " & strMacro & " macro and .vbs successfully completed!",         vbInformation 
'

`

  1. In the Action tab (Task Scheduler):

set Program/script: = C:\Windows\System32\cscript.exe

set Add arguments (optional): = C:\MyVbsFile.vbs

  1. Finally, don't turn on "Run whether user is logged on or not".

That should work.

Let me know!

Rod Bowen

How to check for an undefined or null variable in JavaScript?

In order to understand, Let's analyze what will be the value return by the Javascript Engine when converting undefined , null and ''(An empty string also). You can directly check the same on your developer console.

enter image description here

You can see all are converting to false , means All these three are assuming ‘lack of existence’ by javascript. So you no need to explicitly check all the three in your code like below.

if (a === undefined || a === null || a==='') {
    console.log("Nothing");
} else {
    console.log("Something");
}

Also I want to point out one more thing.

What will be the result of Boolean(0)?

Of course false. This will create a bug in your code when 0 is a valid value in your expected result. So please make sure you check for this when you write the code.

jQuery Data vs Attr?

You can use data-* attribute to embed custom data. The data-* attributes gives us the ability to embed custom data attributes on all HTML elements.

jQuery .data() method allows you to get/set data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

jQuery .attr() method get/set attribute value for only the first element in the matched set.

Example:

<span id="test" title="foo" data-kind="primary">foo</span>

$("#test").attr("title");
$("#test").attr("data-kind");
$("#test").data("kind");
$("#test").data("value", "bar");

What is LDAP used for?

  • LDAP main usage is to provider faster retrieval of data . It acts as a central repository for storing user details that can be accessed by various application at same time .

  • The data that is read various time but we rarely update the data then LDAP is better option as it is faster to read in it because of its structure but updating(add/updatee or delete) is bit tedious job in case of LDAP

  • Security provided by LDAP : LDAP can work with SSL & TLS and thus can be used for sensitive information .

  • LDAP also can work with number of database providing greater flexibility to choose database best suited for our environment

  • Can be a better option for synchronising information between master and its replicase
  • LDAP apart from supporting the data recovery capability .Also , allows us to export data into LDIF file that can be read by various software available in the market

How can I add a class to a DOM element in JavaScript?

Use the .classList.add() method:

_x000D_
_x000D_
const element = document.querySelector('div.foo');_x000D_
element.classList.add('bar');_x000D_
console.log(element.className);
_x000D_
<div class="foo"></div>
_x000D_
_x000D_
_x000D_

This method is better than overwriting the className property, because it doesn't remove other classes and doesn't add the class if the element already has it.

You can also toggle or remove classes using element.classList (see the MDN documentation).

Angular - Use pipes in services and components

As usual in Angular, you can rely on dependency injection:

import { DatePipe } from '@angular/common';

class MyService {

  constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    return this.datePipe.transform(date, 'yyyy-MM-dd');
  }
}

Add DatePipe to your providers list in your module; if you forget to do this you'll get an error no provider for DatePipe:

providers: [DatePipe,...]

Update Angular 6: Angular 6 now offers pretty much every formatting functions used by the pipes publicly. For example, you can now use the formatDate function directly.

import { formatDate } from '@angular/common';

class MyService {

  constructor(@Inject(LOCALE_ID) private locale: string) {}

  transformDate(date) {
    return formatDate(date, 'yyyy-MM-dd', this.locale);
  }
}

Before Angular 5: Be warned though that the DatePipe was relying on the Intl API until version 5, which is not supported by all browsers (check the compatibility table).

If you're using older Angular versions, you should add the Intl polyfill to your project to avoid any problem. See this related question for a more detailed answer.

ffprobe or avprobe not found. Please install one

Compiling the last answers into one:

If you're on Windows, use chocolatey:

choco install ffmpeg

If you are on Mac, use Brew:

brew install ffmpeg

If you are on a Debian Linux distribution, use apt:

sudo apt-get install ffmpeg

And make sure Youtube-dl is updated:

youtube-dl -U

Paste text on Android Emulator

(converting comment discussion to answer)

only solution on windows: https://github.com/gcb/AdbPaste

wrote it in a couple hours to work around this problem. I am now back on 100% linux, so feel free to join it as a contributor or maintainer!

What is a 'workspace' in Visual Studio Code?

They call it a multi-root workspace, and with that you can do debugging easily because:

"With multi-root workspaces, Visual Studio Code searches across all folders for launch.json debug configuration files and displays them with the folder name as a suffix."

Say you have a server and a client folder inside your application folder. If you want to debug them together, without a workspace you have to start two Visual Studio Code instances, one for server, one for client and you need to switch back and forth.

But right now (1.24) you can't add a single file to a workspace, only folders, which is a little bit inconvenient.

Change background color for selected ListBox item

You need to use ListBox.ItemContainerStyle.

ListBox.ItemTemplate specifies how the content of an item should be displayed. But WPF still wraps each item in a ListBoxItem control, which by default gets its Background set to the system highlight colour if it is selected. You can't stop WPF creating the ListBoxItem controls, but you can style them -- in your case, to set the Background to always be Transparent or Black or whatever -- and to do so, you use ItemContainerStyle.

juFo's answer shows one possible implementation, by "hijacking" the system background brush resource within the context of the item style; another, perhaps more idiomatic technique is to use a Setter for the Background property.

How to iterate using ngFor loop Map containing key as string and values as map iteration

As people have mentioned in the comments keyvalue pipe does not retain the order of insertion (which is the primary purpose of Map).

Anyhow, looks like if you have a Map object and want to preserve the order, the cleanest way to do so is entries() function:

<ul>
    <li *ngFor="let item of map.entries()">
        <span>key: {{item[0]}}</span>
        <span>value: {{item[1]}}</span>
    </li>
</ul>

Unable to install Android Studio in Ubuntu

None of these options worked for me on Ubuntu 12.10 (yeah, I need to upgrade). However, I found an easy solution. Download the source from here: https://github.com/miracle2k/android-platform_sdk/blob/master/emulator/mksdcard/mksdcard.c. Then simply compile with "gcc mksdcard.c -o mksdcard". Backup mksdcard in the SDK tools subfolder and replace with the newly compiled one. Android Studio will now be happy with your SDK.

Parsing a JSON string in Ruby

Don't see any answers here that mention parsing directly to an object other than a Hash, but it is possible using the poorly-documented object_class option(see https://ruby-doc.org/stdlib-2.7.1/libdoc/json/rdoc/JSON.html):

JSON.parse('{"foo":{"bar": 2}}', object_class: OpenStruct).foo.bar
=> 2

The better way to read that option is "The ruby class that a json object turns into", which explains why it defaults to Hash. Likewise, there is an array_class option for json arrays.

How do I generate random integers within a specific range in Java?

Here is a simple sample that shows how to generate random number from closed [min, max] range, while min <= max is true

You can reuse it as field in hole class, also having all Random.class methods in one place

Results example:

RandomUtils random = new RandomUtils();
random.nextInt(0, 0); // returns 0
random.nextInt(10, 10); // returns 10
random.nextInt(-10, 10); // returns numbers from -10 to 10 (-10, -9....9, 10)
random.nextInt(10, -10); // throws assert

Sources:

import junit.framework.Assert;
import java.util.Random;

public class RandomUtils extends Random {

    /**
     * @param min generated value. Can't be > then max
     * @param max generated value
     * @return values in closed range [min, max].
     */
    public int nextInt(int min, int max) {
        Assert.assertFalse("min can't be > then max; values:[" + min + ", " + max + "]", min > max);
        if (min == max) {
            return max;
        }

        return nextInt(max - min + 1) + min;
    }
}

Regular expression to match balanced parentheses

You need the first and last parentheses. Use something like this:

str.indexOf('('); - it will give you first occurrence

str.lastIndexOf(')'); - last one

So you need a string between,

String searchedString = str.substring(str1.indexOf('('),str1.lastIndexOf(')');

EC2 instance types's exact network performance?

FWIW CloudFront supports streaming as well. Might be better than plain streaming from instances.

How to use KeyListener

In addition to using KeyListener (as shown by others' answers), sometimes you have to ensure that the JComponent you are using is Focusable. This can be set by adding this to your component(if you are subclassing):

@Override
public void setFocusable(boolean b) {
    super.setFocusable(b);
}

And by adding this to your constructor:

setFocusable(true);

Or, if you are calling the function from a parent class/container:

JComponent childComponent = new JComponent();
childComponent.setFocusable(true);

And then doing all the KeyListener stuff mentioned by others.

get data from mysql database to use in javascript

You can't do it with only Javascript. You'll need some server-side code (PHP, in your case) that serves as a proxy between the DB and the client-side code.

Can't accept license agreement Android SDK Platform 24

Hope this will work for someone out there
I was facing the same issue! I had 2 sdks, named as sdk and sdk1. It was default linked to sdk but the working one was sdk1. So I went to Environment Varaible and added ANDROID_HOME and path of the sdk1, i.e. in my case was C:\Users\tripa_000\AppData\Local\Android\sdk1 , and it solved my problem!

Match groups in Python

You could create a little class that returns the boolean result of calling match, and retains the matched groups for subsequent retrieval:

import re

class REMatcher(object):
    def __init__(self, matchstring):
        self.matchstring = matchstring

    def match(self,regexp):
        self.rematch = re.match(regexp, self.matchstring)
        return bool(self.rematch)

    def group(self,i):
        return self.rematch.group(i)


for statement in ("I love Mary", 
                  "Ich liebe Margot", 
                  "Je t'aime Marie", 
                  "Te amo Maria"):

    m = REMatcher(statement)

    if m.match(r"I love (\w+)"): 
        print "He loves",m.group(1) 

    elif m.match(r"Ich liebe (\w+)"):
        print "Er liebt",m.group(1) 

    elif m.match(r"Je t'aime (\w+)"):
        print "Il aime",m.group(1) 

    else: 
        print "???"

Update for Python 3 print as a function, and Python 3.8 assignment expressions - no need for a REMatcher class now:

import re

for statement in ("I love Mary",
                  "Ich liebe Margot",
                  "Je t'aime Marie",
                  "Te amo Maria"):

    if m := re.match(r"I love (\w+)", statement):
        print("He loves", m.group(1))

    elif m := re.match(r"Ich liebe (\w+)", statement):
        print("Er liebt", m.group(1))

    elif m := re.match(r"Je t'aime (\w+)", statement):
        print("Il aime", m.group(1))

    else:
        print()

Node.js request CERT_HAS_EXPIRED

Add this at the top of your file:

process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

DANGEROUS This disables HTTPS / SSL / TLS checking across your entire node.js environment. Please see the solution using an https agent below.

How to compute the sum and average of elements in an array?

One sneaky way you could do it although it does require the use of (the much hated) eval().

var sum = eval(elmt.join('+')), avg = sum / elmt.length;
document.write("The sum of all the elements is: " + sum + " The average of all the elements is: " + avg + "<br/>");

Just thought I'd post this as one of those 'outside the box' options. You never know, the slyness might grant you (or taketh away) a point.

Android Recyclerview GridLayoutManager column spacing

class VerticalGridSpacingDecoration(private val spacing: Int) : RecyclerView.ItemDecoration() {

  override fun getItemOffsets(
    outRect: Rect,
    view: View,
    parent: RecyclerView,
    state: State
  ) {
    val layoutManager = parent.layoutManager as? GridLayoutManager
    if (layoutManager == null || layoutManager.orientation != VERTICAL) {
      return super.getItemOffsets(outRect, view, parent, state)
    }

    val spanCount = layoutManager.spanCount
    val position = parent.getChildAdapterPosition(view)
    val column = position % spanCount
    with(outRect) {
      left = if (column == 0) 0 else spacing / 2
      right = if (column == spanCount.dec()) 0 else spacing / 2
      top = if (position < spanCount) 0 else spacing
    }
  }
}

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

Why do we need boxing and unboxing in C#?

The best way to understand this is to look at lower-level programming languages C# builds on.

In the lowest-level languages like C, all variables go one place: The Stack. Each time you declare a variable it goes on the Stack. They can only be primitive values, like a bool, a byte, a 32-bit int, a 32-bit uint, etc. The Stack is both simple and fast. As variables are added they just go one on top of another, so the first you declare sits at say, 0x00, the next at 0x01, the next at 0x02 in RAM, etc. In addition, variables are often pre-addressed at compile-time, so their address is known before you even run the program.

In the next level up, like C++, a second memory structure called the Heap is introduced. You still mostly live in the Stack, but special ints called Pointers can be added to the Stack, that store the memory address for the first byte of an Object, and that Object lives in the Heap. The Heap is kind of a mess and somewhat expensive to maintain, because unlike Stack variables they don't pile linearly up and then down as a program executes. They can come and go in no particular sequence, and they can grow and shrink.

Dealing with pointers is hard. They're the cause of memory leaks, buffer overruns, and frustration. C# to the rescue.

At a higher level, C#, you don't need to think about pointers - the .Net framework (written in C++) thinks about these for you and presents them to you as References to Objects, and for performance, lets you store simpler values like bools, bytes and ints as Value Types. Underneath the hood, Objects and stuff that instantiates a Class go on the expensive, Memory-Managed Heap, while Value Types go in that same Stack you had in low-level C - super-fast.

For the sake of keeping the interaction between these 2 fundamentally different concepts of memory (and strategies for storage) simple from a coder's perspective, Value Types can be Boxed at any time. Boxing causes the value to be copied from the Stack, put in an Object, and placed on the Heap - more expensive, but, fluid interaction with the Reference world. As other answers point out, this will occur when you for example say:

bool b = false; // Cheap, on Stack
object o = b; // Legal, easy to code, but complex - Boxing!
bool b2 = (bool)o; // Unboxing!

A strong illustration of the advantage of Boxing is a check for null:

if (b == null) // Will not compile - bools can't be null
if (o == null) // Will compile and always return false

Our object o is technically an address in the Stack that points to a copy of our bool b, which has been copied to the Heap. We can check o for null because the bool's been Boxed and put there.

In general you should avoid Boxing unless you need it, for example to pass an int/bool/whatever as an object to an argument. There are some basic structures in .Net that still demand passing Value Types as object (and so require Boxing), but for the most part you should never need to Box.

A non-exhaustive list of historical C# structures that require Boxing, that you should avoid:

  • The Event system turns out to have a Race Condition in naive use of it, and it doesn't support async. Add in the Boxing problem and it should probably be avoided. (You could replace it for example with an async event system that uses Generics.)

  • The old Threading and Timer models forced a Box on their parameters but have been replaced by async/await which are far cleaner and more efficient.

  • The .Net 1.1 Collections relied entirely on Boxing, because they came before Generics. These are still kicking around in System.Collections. In any new code you should be using the Collections from System.Collections.Generic, which in addition to avoiding Boxing also provide you with stronger type-safety.

You should avoid declaring or passing your Value Types as objects, unless you have to deal with the above historical problems that force Boxing, and you want to avoid the performance hit of Boxing it later when you know it's going to be Boxed anyway.

Per Mikael's suggestion below:

Do This

using System.Collections.Generic;

var employeeCount = 5;
var list = new List<int>(10);

Not This

using System.Collections;

Int32 employeeCount = 5;
var list = new ArrayList(10);

Update

This answer originally suggested Int32, Bool etc cause boxing, when in fact they are simple aliases for Value Types. That is, .Net has types like Bool, Int32, String, and C# aliases them to bool, int, string, without any functional difference.

How do I match any character across multiple lines in a regular expression?

The question is, can . pattern match any character? The answer varies from engine to engine. The main difference is whether the pattern is used by a POSIX or non-POSIX regex library.

Special note about : they are not considered regular expressions, but . matches any char there, same as POSIX based engines.

Another note on and : the . matches any char by default (demo): str = "abcde\n fghij<Foobar>"; expression = '(.*)<Foobar>*'; [tokens,matches] = regexp(str,expression,'tokens','match'); (tokens contain a abcde\n fghij item).

Also, in all of 's regex grammars the dot matches line breaks by default. Boost's ECMAScript grammar allows you to turn this off with regex_constants::no_mod_m (source).

As for (it is POSIX based), use n option (demo): select regexp_substr('abcde' || chr(10) ||' fghij<Foobar>', '(.*)<Foobar>', 1, 1, 'n', 1) as results from dual

POSIX-based engines:

A mere . already matches line breaks, no need to use any modifiers, see (demo).

The (demo), (demo), (TRE, base R default engine with no perl=TRUE, for base R with perl=TRUE or for stringr/stringi patterns, use the (?s) inline modifier) (demo) also treat . the same way.

However, most POSIX based tools process input line by line. Hence, . does not match the line breaks just because they are not in scope. Here are some examples how to override this:

  • - There are multiple workarounds, the most precise but not very safe is sed 'H;1h;$!d;x; s/\(.*\)><Foobar>/\1/' (H;1h;$!d;x; slurps the file into memory). If whole lines must be included, sed '/start_pattern/,/end_pattern/d' file (removing from start will end with matched lines included) or sed '/start_pattern/,/end_pattern/{{//!d;};}' file (with matching lines excluded) can be considered.
  • - perl -0pe 's/(.*)<FooBar>/$1/gs' <<< "$str" (-0 slurps the whole file into memory, -p prints the file after applying the script given by -e). Note that using -000pe will slurp the file and activate 'paragraph mode' where Perl uses consecutive newlines (\n\n) as the record separator.
  • - grep -Poz '(?si)abc\K.*?(?=<Foobar>)' file. Here, z enables file slurping, (?s) enables the DOTALL mode for the . pattern, (?i) enables case insensitive mode, \K omits the text matched so far, *? is a lazy quantifier, (?=<Foobar>) matches the location before <Foobar>.
  • - pcregrep -Mi "(?si)abc\K.*?(?=<Foobar>)" file (M enables file slurping here). Note pcregrep is a good solution for Mac OS grep users.

See demos.

Non-POSIX-based engines:

  • - Use s modifier PCRE_DOTALL modifier: preg_match('~(.*)<Foobar>~s', $s, $m) (demo)
  • - Use RegexOptions.Singleline flag (demo):
    - var result = Regex.Match(s, @"(.*)<Foobar>", RegexOptions.Singleline).Groups[1].Value;
    - var result = Regex.Match(s, @"(?s)(.*)<Foobar>").Groups[1].Value;
  • - Use (?s) inline option: $s = "abcde`nfghij<FooBar>"; $s -match "(?s)(.*)<Foobar>"; $matches[1]
  • - Use s modifier (or (?s) inline version at the start) (demo): /(.*)<FooBar>/s
  • - Use re.DOTALL (or re.S) flags or (?s) inline modifier (demo): m = re.search(r"(.*)<FooBar>", s, flags=re.S) (and then if m:, print(m.group(1)))
  • - Use Pattern.DOTALL modifier (or inline (?s) flag) (demo): Pattern.compile("(.*)<FooBar>", Pattern.DOTALL)
  • - Use (?s) in-pattern modifier (demo): regex = /(?s)(.*)<FooBar>/
  • - Use (?s) modifier (demo): "(?s)(.*)<Foobar>".r.findAllIn("abcde\n fghij<Foobar>").matchData foreach { m => println(m.group(1)) }
  • - Use [^] or workarounds [\d\D] / [\w\W] / [\s\S] (demo): s.match(/([\s\S]*)<FooBar>/)[1]
  • (std::regex) Use [\s\S] or the JS workarounds (demo): regex rex(R"(([\s\S]*)<FooBar>)");
  • - Use the same approach as in JavaScript, ([\s\S]*)<Foobar>. (NOTE: The MultiLine property of the RegExp object is sometimes erroneously thought to be the option to allow . match across line breaks, while, in fact, it only changes the ^ and $ behavior to match start/end of lines rather than strings, same as in JS regex) behavior.)

  • - Use /m MULTILINE modifier (demo): s[/(.*)<Foobar>/m, 1]

  • - Base R PCRE regexps - use (?s): regmatches(x, regexec("(?s)(.*)<FooBar>",x, perl=TRUE))[[1]][2] (demo)
  • - in stringr/stringi regex funtions that are powered with ICU regex engine, also use (?s): stringr::str_match(x, "(?s)(.*)<FooBar>")[,2] (demo)
  • - Use the inline modifier (?s) at the start (demo): re: = regexp.MustCompile(`(?s)(.*)<FooBar>`)
  • - Use dotMatchesLineSeparators or (easier) pass the (?s) inline modifier to the pattern: let rx = "(?s)(.*)<Foobar>"
  • - Same as Swift, (?s) works the easiest, but here is how the option can be used: NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionDotMatchesLineSeparators error:&regexError];
  • , - Use (?s) modifier (demo): "(?s)(.*)<Foobar>" (in Google Spreadsheets, =REGEXEXTRACT(A2,"(?s)(.*)<Foobar>"))

NOTES ON (?s):

In most non-POSIX engines, (?s) inline modifier (or embedded flag option) can be used to enforce . to match line breaks.

If placed at the start of the pattern, (?s) changes the bahavior of all . in the pattern. If the (?s) is placed somewhere after the beginning, only those . will be affected that are located to the right of it unless this is a pattern passed to Python re. In Python re, regardless of the (?s) location, the whole pattern . are affected. The (?s) effect is stopped using (?-s). A modified group can be used to only affect a specified range of a regex pattern (e.g. Delim1(?s:.*?)\nDelim2.* will make the first .*? match across newlines and the second .* will only match the rest of the line).

POSIX note:

In non-POSIX regex engines, to match any char, [\s\S] / [\d\D] / [\w\W] constructs can be used.

In POSIX, [\s\S] is not matching any char (as in JavaScript or any non-POSIX engine) because regex escape sequences are not supported inside bracket expressions. [\s\S] is parsed as bracket expressions that match a single char, \ or s or S.

Remove all whitespaces from NSString

Use below marco and remove the space.

#define TRIMWHITESPACE(string) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]

in other file call TRIM :

    NSString *strEmail;
    strEmail = TRIM(@"     this is the test.");

May it will help you...

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

Since Stack Overflow’s broken RSS just resurrected this question for me, here’s my almost-general solution: JAValueToString

This lets you write JA_DUMP(cgPoint) and get cgPoint = {0, 0} logged.

Crystal Reports for VS2012 - VS2013 - VS2015 - VS2017 - VS2019

Here it is! - SP 25 works on Visual Studio 2019, SP 21 on Visual Studio 2017

SAP released SAP Crystal Reports, developer version for Microsoft Visual Studio

You can get it here (click "Installation package for Visual Studio IDE")

To integrate “SAP Crystal Reports, developer version for Microsoft Visual Studio” you must run the Install Executable. Running the MSI will not fully integrate Crystal Reports into VS. MSI files by definition are for runtime distribution only.

New In SP25 Release

Visual Studio 2019, Addressed incidents, Win10 1809, Security update

How can I customize the tab-to-space conversion factor?

I'm running version 1.21, but I think this may apply to earlier versions as well.

Take a look at the bottom right-hand side of the screen. You should see something that says Spaces or Tab-Size.

Mine shows spaces, →

Enter image description here

  1. Click on the Spaces (or Tab-Size)
  2. Choose Indent Using Spaces or Indent using Tabs
  3. Select the amount of spaces or tabs you like.

This only works per document, not project-wide. If you want to apply it project-wide, you need to also add "editor.detectIndentation": false to your user settings.

Int to byte array

Marc's answer is of course the right answer. But since he mentioned the shift operators and unsafe code as an alternative. I would like to share a less common alternative. Using a struct with Explicit layout. This is similar in principal to a C/C++ union.

Here is an example of a struct that can be used to get to the component bytes of the Int32 data type and the nice thing is that it is two way, you can manipulate the byte values and see the effect on the Int.

  using System.Runtime.InteropServices;

  [StructLayout(LayoutKind.Explicit)]
  struct Int32Converter
  {
    [FieldOffset(0)] public int Value;
    [FieldOffset(0)] public byte Byte1;
    [FieldOffset(1)] public byte Byte2;
    [FieldOffset(2)] public byte Byte3;
    [FieldOffset(3)] public byte Byte4;

    public Int32Converter(int value)
    {
      Byte1 = Byte2 = Byte3 = Byte4 = 0;
      Value = value;
    }

    public static implicit operator Int32(Int32Converter value)
    {
      return value.Value;
    }

    public static implicit operator Int32Converter(int value)
    {
      return new Int32Converter(value);
    }
  }

The above can now be used as follows

 Int32Converter i32 = 256;
 Console.WriteLine(i32.Byte1);
 Console.WriteLine(i32.Byte2);
 Console.WriteLine(i32.Byte3);
 Console.WriteLine(i32.Byte4);

 i32.Byte2 = 2;
 Console.WriteLine(i32.Value);

Of course the immutability police may not be excited about the last possiblity :)

How to ignore the first line of data when processing CSV data?

Because this is related to something I was doing, I'll share here.

What if we're not sure if there's a header and you also don't feel like importing sniffer and other things?

If your task is basic, such as printing or appending to a list or array, you could just use an if statement:

# Let's say there's 4 columns
with open('file.csv') as csvfile:
     csvreader = csv.reader(csvfile)
# read first line
     first_line = next(csvreader)
# My headers were just text. You can use any suitable conditional here
     if len(first_line) == 4:
          array.append(first_line)
# Now we'll just iterate over everything else as usual:
     for row in csvreader:
          array.append(row)

How do I run a spring boot executable jar in a Production environment?

This is a simple, you can use spring boot maven plugin to finish your code deploy.

the plugin config like:

<plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <jvmArguments>-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=${debug.port}
                    </jvmArguments>
                    <profiles>
                        <profile>test</profile>
                    </profiles>
                    <executable>true</executable>
                </configuration>
            </plugin>

And, the jvmArtuments is add for you jvm. profiles will choose a profile to start your app. executable can make your app driectly run.

and if you add mvnw to your project, or you have a maven enveriment. You can just call./mvnw spring-boot:run for mvnw or mvn spring-boot:run for maven.

How to replace existing value of ArrayList element in Java

You must use

list.remove(indexYouWantToReplace);

first.

Your elements will become like this. [zero, one, three]

then add this

list.add(indexYouWantedToReplace, newElement)

Your elements will become like this. [zero, one, new, three]

How to check if a number is between two values?

It's an old question, however might be useful for someone like me.

lodash has _.inRange() function https://lodash.com/docs/4.17.4#inRange

Example:

_.inRange(3, 2, 4);
// => true

Please note that this method utilizes the Lodash utility library, and requires access to an installed version of Lodash.

Difference between <input type='submit' /> and <button type='submit'>text</button>

In summary :

<input type="submit">

<button type="submit"> Submit </button>

Both by default will visually draw a button that performs the same action (submit the form).

However, it is recommended to use <button type="submit"> because it has better semantics, better ARIA support and it is easier to style.

Sorting options elements alphabetically using jQuery

Malakgeorge answer is nice an can be easily wrapped into a jQuery function:

$.fn.sortSelectByText = function(){
    this.each(function(){
        var selected = $(this).val(); 
        var opts_list = $(this).find('option');
        opts_list.sort(function(a, b) { return $(a).text() > $(b).text() ? 1 : -1; });
        $(this).html('').append(opts_list);
        $(this).val(selected); 
    })
    return this;        
}

What are the differences between B trees and B+ trees?

The image below helps show the differences between B+ trees and B trees.

Advantages of B+ trees:

  • Because B+ trees don't have data associated with interior nodes, more keys can fit on a page of memory. Therefore, it will require fewer cache misses in order to access data that is on a leaf node.
  • The leaf nodes of B+ trees are linked, so doing a full scan of all objects in a tree requires just one linear pass through all the leaf nodes. A B tree, on the other hand, would require a traversal of every level in the tree. This full-tree traversal will likely involve more cache misses than the linear traversal of B+ leaves.

Advantage of B trees:

  • Because B trees contain data with each key, frequently accessed nodes can lie closer to the root, and therefore can be accessed more quickly.

B and B+ tree

Is there a way to make a DIV unselectable?

Use

onselectstart="return false"

it prevents copying your content.

CSS selector based on element text?

It was probably discussed, but as of CSS3 there is nothing like what you need (see also "Is there a CSS selector for elements containing certain text?"). You will have to use additional markup, like this:

<li><span class="foo">some text</span></li>
<li>some other text</li>

Then refer to it the usual way:

li > span.foo {...}

How to keep :active css style after clicking an element

I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY

We're going to to be using a hidden checkbox.
This example includes one "on click - off click 'hover / active' state"

--

To make content itself clickable:

_x000D_
_x000D_
#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked ~ label
.my-div{background-color:#000}
_x000D_
<input type="checkbox" id="activate-div">
<label for="activate-div">
  <div class="my-div">
    //MY DIV CONTENT
  </div>
</label>
_x000D_
_x000D_
_x000D_

To make button change content:

_x000D_
_x000D_
#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked +
.my-div{background-color:#000}
_x000D_
<input type="checkbox" id="activate-div">
<div class="my-div">
  //MY DIV CONTENT
</div>

<label for="activate-div">
  //MY BUTTON STUFF
</label>
_x000D_
_x000D_
_x000D_

Hope it helps!!

Finding all the subsets of a set

An elegant recursive solution that corresponds to the best answer explanation above. The core vector operation is only 4 lines. credit to "Guide to Competitive Programming" book from Laaksonen, Antti.

// #include <iostream>
#include <vector>
using namespace std;

vector<int> subset;
void search(int k, int n) {
    if (k == n+1) {
    // process subset - put any of your own application logic
    // for (auto i : subset) cout<< i << " ";
    // cout << endl;
    }
    else {
        // include k in the subset
        subset.push_back(k);
        search(k+1, n);
        subset.pop_back();
        // don't include k in the subset
        search(k+1,n);
    }
}

int main() {
    // find all subset between [1,3]
    search(1, 3);
}

How to create a release signed apk file using Gradle?

You can also use -P command line option of gradle to help the signing. In your build.gradle, add singingConfigs like this:

signingConfigs {
   release {
       storeFile file("path/to/your/keystore")
       storePassword RELEASE_STORE_PASSWORD
       keyAlias "your.key.alias"
       keyPassword RELEASE_KEY_PASSWORD
   }
}

Then call gradle build like this:

gradle -PRELEASE_KEYSTORE_PASSWORD=******* -PRELEASE_KEY_PASSWORD=****** build

You can use -P to set storeFile and keyAlias if you prefer.

This is basically Destil's solution but with the command line options.

For more details on gradle properties, check the gradle user guide.

Lists in ConfigParser

Only primitive types are supported for serialization by config parser. I would use JSON or YAML for that kind of requirement.

How does OkHttp get Json string?

try {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
        .url(urls[0])
        .build();
    Response responses = null;

    try {
        responses = client.newCall(request).execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String jsonData = responses.body().string();
    JSONObject Jobject = new JSONObject(jsonData);
    JSONArray Jarray = Jobject.getJSONArray("employees");

    for (int i = 0; i < Jarray.length(); i++) {
        JSONObject object     = Jarray.getJSONObject(i);
    }
}

Example add to your columns:

JCol employees  = new employees();
colums.Setid(object.getInt("firstName"));
columnlist.add(lastName);           

How can I remove space (margin) above HTML header?

This css allowed chrome and firefox to render all other elements on my page normally and remove the margin above my h1 tag. Also, as a page is resized em can work better than px.

h1 {
  margin-top: -.3em;
  margin-bottom: 0em;
}

How do I make a text go onto the next line if it overflows?

In order to use word-wrap: break-word, you need to set a width (in px). For example:

div {
    width: 250px;
    word-wrap: break-word;
}

word-wrap is a CSS3 property, but it should work in all browsers, including IE 5.5-9.

PHP sessions that have already been started

It would be more efficient:

@session_start();

Avoiding error handler in the screen

Best,

AsyncTask Android example

Update: March 2020

According to Android developer official documentation, AsyncTask is now deprecated.

It's recommended to use kotlin corourines instead. Simply, it allows you to write asynchronous tasks in a sequential style.

Find an element in DOM based on an attribute value

Here is an example , How to search images in a document by src attribute :

document.querySelectorAll("img[src='https://pbs.twimg.com/profile_images/........jpg']");

PHP: HTTP or HTTPS?

$_SERVER['HTTPS']

This will contain a 'non-empty' value if the request was sent through HTTPS

PHP Server Variables

Convert a Unix timestamp to time in JavaScript

UNIX timestamp is number of seconds since 00:00:00 UTC on January 1, 1970 (according to Wikipedia).

Argument of Date object in Javascript is number of miliseconds since 00:00:00 UTC on January 1, 1970 (according to W3Schools Javascript documentation).

See code below for example:

    function tm(unix_tm) {
        var dt = new Date(unix_tm*1000);
        document.writeln(dt.getHours() + '/' + dt.getMinutes() + '/' + dt.getSeconds() + ' -- ' + dt + '<br>');

    }

tm(60);
tm(86400);

gives:

1/1/0 -- Thu Jan 01 1970 01:01:00 GMT+0100 (Central European Standard Time)
1/0/0 -- Fri Jan 02 1970 01:00:00 GMT+0100 (Central European Standard Time)

Postgresql GROUP_CONCAT equivalent?

Since 9.0 this is even easier:

SELECT id, 
       string_agg(some_column, ',')
FROM the_table
GROUP BY id

How to stop flask application without using ctrl-c

I did it slightly different using threads

from werkzeug.serving import make_server

class ServerThread(threading.Thread):

    def __init__(self, app):
        threading.Thread.__init__(self)
        self.srv = make_server('127.0.0.1', 5000, app)
        self.ctx = app.app_context()
        self.ctx.push()

    def run(self):
        log.info('starting server')
        self.srv.serve_forever()

    def shutdown(self):
        self.srv.shutdown()

def start_server():
    global server
    app = flask.Flask('myapp')
    ...
    server = ServerThread(app)
    server.start()
    log.info('server started')

def stop_server():
    global server
    server.shutdown()

I use it to do end to end tests for restful api, where I can send requests using the python requests library.

How to get Node.JS Express to listen only on localhost?

You are having this problem because you are attempting to console log app.address() before the connection has been made. You just have to be sure to console log after the connection is made, i.e. in a callback or after an event signaling that the connection has been made.

Fortunately, the 'listening' event is emitted by the server after the connection is made so just do this:

var express = require('express');
var http = require('http');

var app = express();
var server = http.createServer(app);

app.get('/', function(req, res) {
    res.send("Hello World!");
});

server.listen(3000, 'localhost');
server.on('listening', function() {
    console.log('Express server started on port %s at %s', server.address().port, server.address().address);
});

This works just fine in nodejs v0.6+ and Express v3.0+.

Deleting Elements in an Array if Element is a Certain value VBA

I know this is old, but here's the solution I came up with when I didn't like the ones I found.

-Loop through the array (Variant) adding each element and some divider to a string, unless it matches the one you want to remove -Then split the string on the divider

tmpString=""
For Each arrElem in GlobalArray
   If CStr(arrElem) = "removeThis" Then
      GoTo SkipElem
   Else
      tmpString =tmpString & ":-:" & CStr(arrElem)
   End If
SkipElem:
Next
GlobalArray = Split(tmpString, ":-:")

Obviously the use of strings creates some limitations, like needing to be sure of the information already in the array, and as-is this code makes the first array element blank, but it does what I need and with a little more work it could be more versatile.

Efficient way to return a std::vector in c++

A common pre-C++11 idiom is to pass a reference to the object being filled.

Then there is no copying of the vector.

void f( std::vector & result )
{
  /*
    Insert elements into result
  */
} 

Using Cygwin to Compile a C program; Execution error

If you are not comfortable with bash, you can continue to work in a standard windows command (i.e. DOS) shell.

For this to work you must add C:\cygwin\bin (or your local alternative) to the Windows PATH variable.

With this done, you may: 1) Open a command (DOS) shell 2) Change the directory to the location of your code (c:, then cd path\to\file) 3) gcc myProgram.c -o myProgram

As mentioned in nik's response, the "Using Cygwin" documentation is a great place to learn more.

Keras, How to get the output of each layer?

Based on all the good answers of this thread, I wrote a library to fetch the output of each layer. It abstracts all the complexity and has been designed to be as user-friendly as possible:

https://github.com/philipperemy/keract

It handles almost all the edge cases

Hope it helps!

A project with an Output Type of Class Library cannot be started directly

The project is a class library. It cannot be run or debugged without an executable project (F5 doesn't work!!!). You can only build the project (Ctrl+Shift+B).

If you want to debug the code add a console application project (set it as the start up project) to the solution and add the reference to the library.

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

I'm going to answer the literal question: no, there isn't a good reason you see VARCHAR(255) used so often (there are indeed reasons, as discussed in the other answers, just not good ones). You won't find many examples of projects that have failed catastrophically because the architect chose VARCHAR(300) instead of VARCHAR(255). This would be an issue of near-total insignificance even if you were talking about CHAR instead of VARCHAR.

Make a UIButton programmatically in Swift

Swift 4/5

let button = UIButton(frame: CGRect(x: 20, y: 20, width: 200, height: 60))
 button.setTitle("Email", for: .normal)
 button.backgroundColor = .white
 button.setTitleColor(UIColor.black, for: .normal)
 button.addTarget(self, action: #selector(self.buttonTapped), for: .touchUpInside)
 myView.addSubview(button)



@objc func buttonTapped(sender : UIButton) {
                //Write button action here
            }

Get device information (such as product, model) from adb command

The correct way to do it would be:

adb -s 123abc12 shell getprop

Which will give you a list of all available properties and their values. Once you know which property you want, you can give the name as an argument to getprop to access its value directly, like this:

adb -s 123abc12 shell getprop ro.product.model

The details in adb devices -l consist of the following three properties: ro.product.name, ro.product.model and ro.product.device.

Note that ADB shell ends lines with \r\n, which depending on your platform might or might not make it more difficult to access the exact value (e.g. instead of Nexus 7 you might get Nexus 7\r).

How can one use multi threading in PHP applications

I know this is an old question but for people searching, there is a PECL extension written in C that gives PHP multi-threading capability now, it's located here https://github.com/krakjoe/pthreads

How do I lowercase a string in Python?

Use .lower() - For example:

s = "Kilometer"
print(s.lower())

The official 2.x documentation is here: str.lower()
The official 3.x documentation is here: str.lower()

javac option to compile all java files under a given directory recursively

find . -name "*.java" -print | xargs javac 

Kinda brutal, but works like hell. (Use only on small programs, it's absolutely not efficient)

How to position a table at the center of div horizontally & vertically

I discovered that I had to include

body { width:100%; }

for "margin: 0 auto" to work for tables.

Best way to do a PHP switch with multiple values per case?

Switch in combination with variable variables will give you more flexibility:

<?php
$p = 'home'; //For testing

$p = ( strpos($p, 'users') !== false? 'users': $p);
switch ($p) { 
    default:
        $varContainer = 'current_' . $p; //Stores the variable [$current_"xyORz"] into $varContainer
        ${$varContainer} = 'current'; //Sets the VALUE of [$current_"xyORz"] to 'current'
    break;

}
//For testing
echo $current_home;
?>

To learn more, checkout variable variables and the examples I submitted to php manual:
Example 1: http://www.php.net/manual/en/language.variables.variable.php#105293
Example 2: http://www.php.net/manual/en/language.variables.variable.php#105282

PS: This example code is SMALL AND SIMPLE, just the way I like it. It's tested and works too

How to use sessions in an ASP.NET MVC 4 application?

Due to the stateless nature of the web, sessions are also an extremely useful way of persisting objects across requests by serialising them and storing them in a session.

A perfect use case of this could be if you need to access regular information across your application, to save additional database calls on each request, this data can be stored in an object and unserialised on each request, like so:

Our reusable, serializable object:

[Serializable]
public class UserProfileSessionData
{
    public int UserId { get; set; }

    public string EmailAddress { get; set; }

    public string FullName { get; set; }
}

Use case:

public class LoginController : Controller {

    [HttpPost]
    public ActionResult Login(LoginModel model)
    {
        if (ModelState.IsValid)
        {
            var profileData = new UserProfileSessionData {
                UserId = model.UserId,
                EmailAddress = model.EmailAddress,
                FullName = model.FullName
            }

            this.Session["UserProfile"] = profileData;
        }
    }

    public ActionResult LoggedInStatusMessage()
    {
        var profileData = this.Session["UserProfile"] as UserProfileSessionData;

        /* From here you could output profileData.FullName to a view and
        save yourself unnecessary database calls */
    }

}

Once this object has been serialised, we can use it across all controllers without needing to create it or query the database for the data contained within it again.

Inject your session object using Dependency Injection

In a ideal world you would 'program to an interface, not implementation' and inject your serializable session object into your controller using your Inversion of Control container of choice, like so (this example uses StructureMap as it's the one I'm most familiar with).

public class WebsiteRegistry : Registry
{
    public WebsiteRegistry()
    {
        this.For<IUserProfileSessionData>().HybridHttpOrThreadLocalScoped().Use(() => GetUserProfileFromSession());   
    }

    public static IUserProfileSessionData GetUserProfileFromSession()
    {
        var session = HttpContext.Current.Session;
        if (session["UserProfile"] != null)
        {
            return session["UserProfile"] as IUserProfileSessionData;
        }

        /* Create new empty session object */
        session["UserProfile"] = new UserProfileSessionData();

        return session["UserProfile"] as IUserProfileSessionData;
    }
}

You would then register this in your Global.asax.cs file.

For those that aren't familiar with injecting session objects, you can find a more in-depth blog post about the subject here.

A word of warning:

It's worth noting that sessions should be kept to a minimum, large sessions can start to cause performance issues.

It's also recommended to not store any sensitive data in them (passwords, etc).

Android Material: Status bar color won't change

Switch to AppCompatActivity and add a 25 dp paddingTop on the toolbar and turn on

<item name="android:windowTranslucentStatus">true</item>

Then, the will toolbar go up top the top

Doctrine and LIKE query

This is not possible with the magic methods, however you can achieve this using DQL (Doctrine Query Language). In your example, assuming you have entity named Orders with Product property, just go ahead and do the following:

$dql_query = $em->createQuery("
    SELECT o FROM AcmeCodeBundle:Orders o
    WHERE 
      o.OrderEmail = '[email protected]' AND
      o.Product LIKE 'My Products%'
");
$orders = $dql_query->getResult();

Should do exactly what you need.

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

In the build.gradle file for your app module, add this to the defaultConfig section (under the android section). This will write out the schema to a schemas subfolder of your project folder.

javaCompileOptions {
    annotationProcessorOptions {
        arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
    }
}

Like this:

// ...

android {
    
    // ... (compileSdkVersion, buildToolsVersion, etc)

    defaultConfig {

        // ... (applicationId, miSdkVersion, etc)
        
        javaCompileOptions {
            annotationProcessorOptions {
                arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }
   
    // ... (buildTypes, compileOptions, etc)

}

// ...

javac: invalid target release: 1.8

Your javac is not pointing to correct java.

Check where your javac is pointing using following command -

update-alternatives --config javac

If it is not pointed to the javac you want to compile with, point it to "/JAVA8_HOME/bin/javac", or which ever java you want to compile with.

How to define custom exception class in Java, the easiest way?

If you use the new class dialog in Eclipse you can just set the Superclass field to java.lang.Exception and check "Constructors from superclass" and it will generate the following:

package com.example.exception;

public class MyException extends Exception {

    public MyException() {
        // TODO Auto-generated constructor stub
    }

    public MyException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public MyException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }

    public MyException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

}

In response to the question below about not calling super() in the defualt constructor, Oracle has this to say:

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.

How to remove listview all items

ListView operates based on the underlying data in the Adapter. In order to clear the ListView you need to do two things:

  1. Clear the data that you set from adapter.
  2. Refresh the view by calling notifyDataSetChanged

For example, see the skeleton of SampleAdapter below that extends the BaseAdapter


public class SampleAdapter extends BaseAdapter {

    ArrayList<String> data;

    public SampleAdapter() {
        this.data = new ArrayList<String>();
    }

    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return data.get(position);
    }

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

    public View getView(int position, View convertView, ViewGroup parent) {
        // your View
        return null;
    }
}

Here you have the ArrayList<String> data as the data for your Adapter. While you might not necessary use ArrayList, you will have something similar in your code to represent the data in your ListView

Next you provide a method to clear this data, the implementation of this method is to clear the underlying data structure


public void clearData() {
    // clear the data
    data.clear();
}

If you are using any subclass of Collection, they will have clear() method that you could use as above.

Once you have this method, you want to call clearData and notifyDataSetChanged on your onClick thus the code for onClick will look something like:


// listView is your instance of your ListView
SampleAdapter sampleAdapter = (SampleAdapter)listView.getAdapter();
sampleAdapter.clearData();

// refresh the View
sampleAdapter.notifyDataSetChanged();

How to Handle Button Click Events in jQuery?

$('#btnSubmit').click(function(event){
    alert("Button Clicked");
});

or as you are using submit button so you can write your code in form's validate event like

$('#myForm').validate(function(){
    alert("Hello World!!");
});

How do I see all foreign keys to a table or column?

To find all tables containing a particular foreign key such as employee_id

SELECT DISTINCT TABLE_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('employee_id')
AND TABLE_SCHEMA='table_name';

Get key by value in dictionary

Try this one-liner to reverse a dictionary:

reversed_dictionary = dict(map(reversed, dictionary.items()))

How to connect to a docker container from outside the host (same network) [Windows]

TLDR: If you have Windows Firewall enabled, make sure that there is an exception for "vpnkit" on private networks.

For my particular case, I discovered that Windows Firewall was blocking my connection when I tried visiting my container's published port from another machine on my local network, because disabling it made everything work.

However, I didn't want to disable the firewall entirely just so I could access my container's service. This begged the question of which "app" was listening on behalf of my container's service. After finding another SO thread that taught me to use netstat -a -b to discover the apps behind the listening sockets on my machine, I learned that it was vpnkit.exe, which already had an entry in my Windows Firewall settings: but "private networks" was disabled on it, and once I enabled it, I was able to visit my container's service from another machine without having to completely disable the firewall.

Wampserver icon not going green fully, mysql services not starting up?

I had the same problem. Mysql didn't start.

  1. go to services.
  2. right click the wampmysqld go to properties.
  3. startup type select manual.
  4. right click and click start service.

worked for me.

How to send a correct authorization header for basic authentication

Per https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding and http://en.wikipedia.org/wiki/Basic_access_authentication , here is how to do Basic auth with a header instead of putting the username and password in the URL. Note that this still doesn't hide the username or password from anyone with access to the network or this JS code (e.g. a user executing it in a browser):

$.ajax({
  type: 'POST',
  url: http://theappurl.com/api/v1/method/,
  data: {},
  crossDomain: true,
  beforeSend: function(xhr) {
    xhr.setRequestHeader('Authorization', 'Basic ' + btoa(unescape(encodeURIComponent(YOUR_USERNAME + ':' + YOUR_PASSWORD))))
  }
});

How do I put variable values into a text string in MATLAB?

I was looking for something along what you wanted, but wanted to put it back into a variable.

So this is what I did

variable = ['hello this is x' x ', this is now y' y ', finally this is d:' d]

basically

variable = [str1 str2 str3 str4 str5 str6]

Composer killed while updating

Unfortuantely composer requires a lot of RAM & processing power. Here are a few things that I did, which combined, made the process bearable. This was on my cloud playpen env.

  1. You may be simply running out of RAM. Enable swap: https://www.digitalocean.com/community/search?q=add+swap (note: I think best practice is to add a seperate partition. Digitalocean's guide is appropriate for their environment)
  2. service mysql stop (kill your DB/mem-hog services to free some RAM - don't forget to start it again!)
  3. use a secondary terminal session running top to watch memory/swap consumption until process is complete.
  4. composer.phar update --prefer-dist -vvv (verbose output [still hangs at some points when working] and use distro zip files). Maybe try a --dry-run too?
  5. Composer is apparently know to run slower in older versions of PHP (e.g. 5.3x). It was still slow in 5.5.9 for me...

How do I create a comma-separated list using a SQL query?

Using COALESCE to Build Comma-Delimited String in SQL Server
http://www.sqlteam.com/article/using-coalesce-to-build-comma-delimited-string

Example:

DECLARE @EmployeeList varchar(100)

SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') + 
   CAST(Emp_UniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1

SELECT @EmployeeList

scrollbars in JTextArea

            txtarea = new JTextArea(); 
    txtarea.setRows(25);
    txtarea.setColumns(25);
    txtarea.setWrapStyleWord(true);
    JScrollPane scroll = new JScrollPane (txtarea);
    panel2.add(scroll); //Object of Jpanel

Above given lines automatically shows you both horizontal & vertical Scrollbars..

How to check type of variable in Java?

I wasn't happy with any of these answers, and the one that's right has no explanation and negative votes so I searched around, found some stuff and edited it so that it is easy to understand. Have a play with it, not as straight forward as one would hope.

//move your variable into an Object type
Object obj=whatYouAreChecking;
System.out.println(obj);

// moving the class type into a Class variable
Class cls=obj.getClass();
System.out.println(cls);

// convert that Class Variable to a neat String
String answer = cls.getSimpleName();
System.out.println(answer);

Here is a method:

public static void checkClass (Object obj) {
    Class cls = obj.getClass();
    System.out.println("The type of the object is: " + cls.getSimpleName());       
}

Installing PIL with pip

I had some errors during installation. Just in case somebody has this too. Despite that I already was sitting under admin user, but not root.

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/PIL'

Storing debug log for failure in /Users/wzbozon/Library/Logs/pip.log

Adding "sudo" solved the problem, with sudo it worked:

~/Documents/mv-server: $ sudo pip install Pillow

How to use border with Bootstrap

If you are using Bootstrap 4 and higher try this to put borders around your empty divs use border border-primary here is an example of my code:

<div class="row border border-primary">
        <div class="col border border-primary">logo</div>
        <div class="col border border-primary">navbar</div>
    </div>

Here is the link to the border utility in Bootstrap 4: https://getbootstrap.com/docs/4.2/utilities/borders/

How to POST form data with Spring RestTemplate?

How to POST mixed data: File, String[], String in one request.

You can use only what you need.

private String doPOST(File file, String[] array, String name) {
    RestTemplate restTemplate = new RestTemplate(true);

    //add file
    LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("file", new FileSystemResource(file));

    //add array
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://my_url");
    for (String item : array) {
        builder.queryParam("array", item);
    }

    //add some String
    builder.queryParam("name", name);

    //another staff
    String result = "";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
            new HttpEntity<>(params, headers);

    ResponseEntity<String> responseEntity = restTemplate.exchange(
            builder.build().encode().toUri(),
            HttpMethod.POST,
            requestEntity,
            String.class);

    HttpStatus statusCode = responseEntity.getStatusCode();
    if (statusCode == HttpStatus.ACCEPTED) {
        result = responseEntity.getBody();
    }
    return result;
}

The POST request will have File in its Body and next structure:

POST https://my_url?array=your_value1&array=your_value2&name=bob 

Origin http://localhost is not allowed by Access-Control-Allow-Origin

This approach resolved my issue to allow multiple domain

app.use(function(req, res, next) {
      var allowedOrigins = ['http://127.0.0.1:8020', 'http://localhost:8020', 'http://127.0.0.1:9000', 'http://localhost:9000'];
      var origin = req.headers.origin;
      if(allowedOrigins.indexOf(origin) > -1){
           res.setHeader('Access-Control-Allow-Origin', origin);
      }
      //res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8020');
      res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
      res.header('Access-Control-Allow-Credentials', true);
      return next();
    });

C# compiler error: "not all code paths return a value"

I like to beat dead horses, but I just wanted to make an additional point:

First of all, the problem is that not all conditions of your control structure have been addressed. Essentially, you're saying if a, then this, else if b, then this. End. But what if neither? There's no way to exit (i.e. not every 'path' returns a value).

My additional point is that this is an example of why you should aim for a single exit if possible. In this example you would do something like this:

bool result = false;
if(conditionA)
{
   DoThings();
   result = true;
}
else if(conditionB)
{
   result = false;
}
else if(conditionC)
{
   DoThings();
   result = true;
}

return result;

So here, you will always have a return statement and the method always exits in one place. A couple things to consider though... you need to make sure that your exit value is valid on every path or at least acceptable. For example, this decision structure only accounts for three possibilities but the single exit can also act as your final else statement. Or does it? You need to make sure that the final return value is valid on all paths. This is a much better way to approach it versus having 50 million exit points.

Can we open pdf file using UIWebView on iOS?

use this for open pdf file in webview

NSString *path = [[NSBundle mainBundle] pathForResource:@"mypdf" ofType:@"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
UIWebView *webView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
[[webView scrollView] setContentOffset:CGPointMake(0,500) animated:YES];
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollTo(0.0, 50.0)"]];
[webView loadRequest:request];
[self.view addSubview:webView];
[webView release];

Java variable number or arguments for a method

Variable number of arguments

It is possible to pass a variable number of arguments to a method. However, there are some restrictions:

  • The variable number of parameters must all be the same type
  • They are treated as an array within the method
  • They must be the last parameter of the method

To understand these restrictions, consider the method, in the following code snippet, used to return the largest integer in a list of integers:

private static int largest(int... numbers) {
     int currentLargest = numbers[0];
     for (int number : numbers) {
        if (number > currentLargest) {
            currentLargest = number;
        }
     }
     return currentLargest;
}

source Oracle Certified Associate Java SE 7 Programmer Study Guide 2012

When to use If-else if-else over switch statements and vice versa

Use switch every time you have more than 2 conditions on a single variable, take weekdays for example, if you have a different action for every weekday you should use a switch.

Other situations (multiple variables or complex if clauses you should Ifs, but there isn't a rule on where to use each.

How to avoid the "divide by zero" error in SQL?

There is no magic global setting 'turn division by 0 exceptions off'. The operation has to to throw, since the mathematical meaning of x/0 is different from the NULL meaning, so it cannot return NULL. I assume you are taking care of the obvious and your queries have conditions that should eliminate the records with the 0 divisor and never evaluate the division. The usual 'gotcha' is than most developers expect SQL to behave like procedural languages and offer logical operator short-circuit, but it does NOT. I recommend you read this article: http://www.sqlmag.com/Articles/ArticleID/9148/pg/2/2.html

Resetting a multi-stage form with jQuery

I usually do:

$('#formDiv form').get(0).reset()

or

$('#formId').get(0).reset()

Determine the path of the executing BASH script

Contributed by Stephane CHAZELAS on c.u.s. Assuming POSIX shell:

prg=$0
if [ ! -e "$prg" ]; then
  case $prg in
    (*/*) exit 1;;
    (*) prg=$(command -v -- "$prg") || exit;;
  esac
fi
dir=$(
  cd -P -- "$(dirname -- "$prg")" && pwd -P
) || exit
prg=$dir/$(basename -- "$prg") || exit 

printf '%s\n' "$prg"

How does DISTINCT work when using JPA and Hibernate

I would use JPA's constructor expression feature. See also following answer:

JPQL Constructor Expression - org.hibernate.hql.ast.QuerySyntaxException:Table is not mapped

Following the example in the question, it would be something like this.

SELECT DISTINCT new com.mypackage.MyNameType(c.name) from Customer c

JavaScript Editor Plugin for Eclipse

Complete the following steps in Eclipse to get plugins for JavaScript files:

  1. Open Eclipse -> Go to "Help" -> "Install New Software"
  2. Select the repository for your version of Eclipse. I have Juno so I selected http://download.eclipse.org/releases/juno
  3. Expand "Programming Languages" -> Check the box next to "JavaScript Development Tools"
  4. Click "Next" -> "Next" -> Accept the Terms of the License Agreement -> "Finish"
  5. Wait for the software to install, then restart Eclipse (by clicking "Yes" button at pop up window)
  6. Once Eclipse has restarted, open "Window" -> "Preferences" -> Expand "General" and "Editors" -> Click "File Associations" -> Add ".js" to the "File types:" list, if it is not already there
  7. In the same "File Associations" dialog, click "Add" in the "Associated editors:" section
  8. Select "Internal editors" radio at the top
  9. Select "JavaScript Viewer". Click "OK" -> "OK"

To add JavaScript Perspective: (Optional)
10. Go to "Window" -> "Open Perspective" -> "Other..."
11. Select "JavaScript". Click "OK"

To open .html or .js file with highlighted JavaScript syntax:
12. (Optional) Select JavaScript Perspective
13. Browse and Select .html or .js file in Script Explorer in [JavaScript Perspective] (Or Package Explorer [Java Perspective] Or PyDev Package Explorer [PyDev Perspective] Don't matter.)
14. Right-click on .html or .js file -> "Open With" -> "Other..."
15. Select "Internal editors"
16. Select "Java Script Editor". Click "OK" (see JavaScript syntax is now highlighted )

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

How to pass multiple values through command argument in Asp.net?

Use OnCommand event of imagebutton. Within it do

<asp:Button id="Button1" Text="Click" CommandName="Something" CommandArgument="your command arg" OnCommand="CommandBtn_Click" runat="server"/>

Code-behind:

void CommandBtn_Click(Object sender, CommandEventArgs e) 
{    
    switch(e.CommandName)
    {
        case "Something":
            // Do your code
            break;
        default:              
            break; 

    }
}

Leading zeros for Int in Swift

Details

Xcode 9.0.1, swift 4.0

Solutions

Data

import Foundation

let array = [0,1,2,3,4,5,6,7,8]

Solution 1

extension Int {

    func getString(prefix: Int) -> String {
        return "\(prefix)\(self)"
    }

    func getString(prefix: String) -> String {
        return "\(prefix)\(self)"
    }
}

for item in array {
    print(item.getString(prefix: 0))
}

for item in array {
    print(item.getString(prefix: "0x"))
}

Solution 2

for item in array {
    print(String(repeatElement("0", count: 2)) + "\(item)")
}

Solution 3

extension String {

    func repeate(count: Int, string: String? = nil) -> String {

        if count > 1 {
            let repeatedString = string ?? self
            return repeatedString + repeate(count: count-1, string: repeatedString)
        }
        return self
    }
}

for item in array {
    print("0".repeate(count: 3) + "\(item)")
}

How to convert a String to CharSequence?

That's a good question! You may get into troubles if you invoke API that uses generics and want to assign or return that result with a different subtype of the generic type. Java 8 helps to transform:

    List<String> input = new LinkedList<>(Arrays.asList("a", "b", "c"));
    List<CharSequence> result;
    
//    result = input; // <-- Type mismatch: cannot convert from List<String> to List<CharSequence>
    result = input.stream().collect(Collectors.toList());
    
    System.out.println(result);

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()

How can I get the root domain URI in ASP.NET?

This works also:

string url = HttpContext.Request.Url.Authority;

Package signatures do not match the previously installed version

I had this issue on a Samsung device, Uninstalling the app gave the same message. The problem was that the app was also installed in the phone's "Secure Folder" area. Worth checking if this is your scenario.

The controller for path was not found or does not implement IController

This problem also occurs if you don't include your controller class for compile-process in the .csproj files.

<Compile Include="YOUR_CONTROLLER_PATH.cs" />

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

To solve this problem you should use drawable -> new -> image asset and then add your images. You will then find the mipmap folder contains your images, and you can use it by @mibmab/img.

How (and why) to use display: table-cell (CSS)

It's even easier to use parent > child selector relationship so the inner div do not need to have their css classes to be defined explicitly:

_x000D_
_x000D_
.display-table {_x000D_
    display: table; _x000D_
}_x000D_
.display-table > div { _x000D_
    display: table-row; _x000D_
}_x000D_
.display-table > div > div { _x000D_
    display: table-cell;_x000D_
    padding: 5px;_x000D_
}
_x000D_
<div class="display-table">_x000D_
    <div>_x000D_
        <div>0, 0</div>_x000D_
        <div>0, 1</div>_x000D_
    </div>_x000D_
    <div>_x000D_
        <div>1, 0</div>_x000D_
        <div>1, 1</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to search and replace text in a file?

(pip install python-util)

from pyutil import filereplace

filereplace("somefile.txt","abcd","ram")

Will replace all occurences of "abcd" with "ram".
The function also supports regex by specifying regex=True

from pyutil import filereplace

filereplace("somefile.txt","\\w+","ram",regex=True)

Disclaimer: I'm the author (https://github.com/MisterL2/python-util)

How to play video with AVPlayerViewController (AVKit) in Swift

Swift 3.x - 5.x

Necessary: import AVKit, import AVFoundation

AVFoundation framework is needed even if you use AVPlayer

If you want to use AVPlayerViewController:

let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
let player = AVPlayer(url: videoURL!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
    playerViewController.player!.play()
}

or just AVPlayer:

let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")
let player = AVPlayer(url: videoURL!)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()

It's better to put this code into the method: override func viewDidAppear(_ animated: Bool) or somewhere after.


Objective-C

AVPlayerViewController:

NSURL *videoURL = [NSURL URLWithString:@"https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"];
AVPlayer *player = [AVPlayer playerWithURL:videoURL];
AVPlayerViewController *playerViewController = [AVPlayerViewController new];
playerViewController.player = player;
[self presentViewController:playerViewController animated:YES completion:^{
  [playerViewController.player play];
}];

or just AVPlayer:

NSURL *videoURL = [NSURL URLWithString:@"https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"];
AVPlayer *player = [AVPlayer playerWithURL:videoURL];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
playerLayer.frame = self.view.bounds;
[self.view.layer addSublayer:playerLayer];
[player play];

Why are empty catch blocks a bad idea?

I mean, for instance, sometimes you want to get some additional info from somewhere (webservice, database) and you really don't care if you'll get this info or not. So you try to get it, and if anything happens, that's ok, I'll just add a "catch (Exception ignored) {}" and that's all

So, going with your example, it's a bad idea in that case because you're catching and ignoring all exceptions. If you were catching only EInfoFromIrrelevantSourceNotAvailable and ignoring it, that would be fine, but you're not. You're also ignoring ENetworkIsDown, which may or may not be important. You're ignoring ENetworkCardHasMelted and EFPUHasDecidedThatOnePlusOneIsSeventeen, which are almost certainly important.

An empty catch block is not an issue if it's set up to only catch (and ignore) exceptions of certain types which you know to be unimportant. The situations in which it's a good idea to suppress and silently ignore all exceptions, without stopping to examine them first to see whether they're expected/normal/irrelevant or not, are exceedingly rare.

What are the differences between Pandas and NumPy+SciPy in Python?

Numpy is required by pandas (and by virtually all numerical tools for Python). Scipy is not strictly required for pandas but is listed as an "optional dependency". I wouldn't say that pandas is an alternative to Numpy and/or Scipy. Rather, it's an extra tool that provides a more streamlined way of working with numerical and tabular data in Python. You can use pandas data structures but freely draw on Numpy and Scipy functions to manipulate them.

Include headers when using SELECT INTO OUTFILE?

This is an alternative cheat if you are familiar with Python or R, and your table can fit into memory.

Import the SQL table into Python or R and then export from there as a CSV and you'll get the column names as well as the data.

Here's how I do it using R, requires the RMySQL library:

db <- dbConnect(MySQL(), user='user', password='password', dbname='myschema', host='localhost')

query <- dbSendQuery(db, "select * from mytable")
dataset <- fetch(query, n=-1)

write.csv(dataset, 'mytable_backup.csv')

It's a bit of a cheat but I found this was a quick workaround when my number of columns was too long to use the concat method above. Note: R will add a 'row.names' column at the start of the CSV so you'll want to drop that if you do need to rely on the CSV to recreate the table.

Select elements by attribute in CSS

    [data-value] {
  /* Attribute exists */
}

[data-value="foo"] {
  /* Attribute has this exact value */
}

[data-value*="foo"] {
  /* Attribute value contains this value somewhere in it */
}

[data-value~="foo"] {
  /* Attribute has this value in a space-separated list somewhere */
}

[data-value^="foo"] {
  /* Attribute value starts with this */
}

[data-value|="foo"] {
  /* Attribute value starts with this in a dash-separated list */
}

[data-value$="foo"] {
  /* Attribute value ends with this */
}

Global Git ignore

  1. Create a .gitignore file in your home directory
touch ~/.gitignore
  1. Add files to it (folders aren't recognised)

Example

# these work
*.gz
*.tmproj
*.7z

# these won't as they are folders
.vscode/
build/

# but you can do this
.vscode/*
build/*
  1. Check if a git already has a global gitignore
git config --get core.excludesfile
  1. Tell git where the file is
git config --global core.excludesfile '~/.gitignore'

Voila!!

Writing/outputting HTML strings unescaped

Apart from using @MvcHtmlString.Create(ViewBag.Stuff) as suggested by Dommer, I suggest you to also use AntiXSS library as suggested phill http://haacked.com/archive/2010/04/06/using-antixss-as-the-default-encoder-for-asp-net.aspx

It encodes almost all the possible XSS attack string.

How to navigate back to the last cursor position in Visual Studio Code?

Mac OS (MacBook Pro):

Back: CTRL(control) + - (Hyphen)

Back Forward: CTRL + Shift + - (Hyphen)

Set line spacing

Yup, as everyone's saying, line-height is the thing. Any font you are using, a mid-height character (such as a or ¦, not going through the upper or lower) should go with the same height-length at line-height: 0.6 to 0.65.

_x000D_
_x000D_
<div style="line-height: 0.65; font-family: 'Fira Code', monospace, sans-serif">_x000D_
aaaaa<br>_x000D_
aaaaa<br>_x000D_
aaaaa<br>_x000D_
aaaaa<br>_x000D_
aaaaa_x000D_
</div>_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div style="line-height: 0.6; font-family: 'Fira Code', monospace, sans-serif">_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦<br>_x000D_
¦¦¦¦¦¦¦¦¦¦_x000D_
</div>_x000D_
<br>_x000D_
<br>_x000D_
<strong>BUT</strong>_x000D_
<br>_x000D_
<br>_x000D_
<div style="line-height: 0.65; font-family: 'Fira Code', monospace, sans-serif">_x000D_
ddd<br>_x000D_
ƒƒƒ<br>_x000D_
ggg_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is JavaScript's highest integer value that a number can go to without losing precision?

>= ES6:

Number.MIN_SAFE_INTEGER;
Number.MAX_SAFE_INTEGER;

<= ES5

From the reference:

Number.MAX_VALUE;
Number.MIN_VALUE;

_x000D_
_x000D_
console.log('MIN_VALUE', Number.MIN_VALUE);
console.log('MAX_VALUE', Number.MAX_VALUE);

console.log('MIN_SAFE_INTEGER', Number.MIN_SAFE_INTEGER); //ES6
console.log('MAX_SAFE_INTEGER', Number.MAX_SAFE_INTEGER); //ES6
_x000D_
_x000D_
_x000D_

Removing Duplicate Values from ArrayList

public static void main(String[] args) {
    @SuppressWarnings("serial")
    List<Object> lst = new ArrayList<Object>() {
        @Override
        public boolean add(Object e) {
            if(!contains(e))
            return super.add(e);
            else
            return false;
        }
    };
    lst.add("ABC");
    lst.add("ABC");
    lst.add("ABCD");
    lst.add("ABCD");
    lst.add("ABCE");
    System.out.println(lst);

}

This is the better way

SQL Server: Multiple table joins with a WHERE clause

try this

DECLARE @Application TABLE(Id INT PRIMARY KEY, NAME VARCHAR(20))
INSERT @Application ( Id, NAME )
VALUES  ( 1,'Word' ), ( 2,'Excel' ), ( 3,'PowerPoint' )
DECLARE @software TABLE(Id INT PRIMARY KEY, ApplicationId INT, Version INT)
INSERT @software ( Id, ApplicationId, Version )
VALUES  ( 1,1, 2003 ), ( 2,1,2007 ), ( 3,2, 2003 ), ( 4,2,2007 ),( 5,3, 2003 ), ( 6,3,2007 )

DECLARE @Computer TABLE(Id INT PRIMARY KEY, NAME VARCHAR(20))
INSERT @Computer ( Id, NAME )
VALUES  ( 1,'Name1' ), ( 2,'Name2' )

DECLARE @Software_Computer  TABLE(Id INT PRIMARY KEY, SoftwareId int, ComputerId int)
INSERT @Software_Computer ( Id, SoftwareId, ComputerId )
VALUES  ( 1,1, 1 ), ( 2,4,1 ), ( 3,2, 2 ), ( 4,5,2 )

SELECT Computer.Name ComputerName, Application.Name ApplicationName, MAX(Software2.Version) Version
FROM @Application Application 
JOIN @Software Software
    ON Application.ID = Software.ApplicationID
CROSS JOIN @Computer Computer
LEFT JOIN @Software_Computer Software_Computer
    ON Software_Computer.ComputerId = Computer.Id AND Software_Computer.SoftwareId = Software.Id
LEFT JOIN @Software Software2
    ON Software2.ID = Software_Computer.SoftwareID
WHERE Computer.ID = 1 
GROUP BY Computer.Name, Application.Name

How to set JFrame to appear centered, regardless of monitor resolution?

I am using NetBeans IDE 7.3 and this is how I go about centralizing my JFrame Make sure you click on the JFrame Panel and go to your JFrame property bar,click on the Code bar and select Generate Center check box.

How to start and stop/pause setInterval?

The reason you're seeing this specific problem:

JSFiddle wraps your code in a function, so start() is not defined in the global scope.

enter image description here


Moral of the story: don't use inline event bindings. Use addEventListener/attachEvent.


Other notes:

Please don't pass strings to setTimeout and setInterval. It's eval in disguise.

Use a function instead, and get cozy with var and white space:

_x000D_
_x000D_
var input = document.getElementById("input"),
  add;

function start() {
  add = setInterval(function() {
    input.value++;
  }, 1000);
}

start();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="input" />
<input type="button" onclick="clearInterval(add)" value="stop" />
<input type="button" onclick="start()" value="start" />
_x000D_
_x000D_
_x000D_

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

Install gcc.

If you're on linux, use the package manager.

If you're on Windows, use MinGW.

How do I find the maximum of 2 numbers?

max(value,run)

should do it.

Bash loop ping successful

You don't need to use echo or grep. You could do this:

ping -oc 100000 8.8.8.8 > /dev/null && say "up" || say "down"

How to have a transparent ImageButton: Android

in run time, you can use following code

btn.setBackgroundDrawable(null);

jQuery posting valid json in request body

An actual JSON request would look like this:

data: '{"command":"on"}',

Where you're sending an actual JSON string. For a more general solution, use JSON.stringify() to serialize an object to JSON, like this:

data: JSON.stringify({ "command": "on" }),

To support older browsers that don't have the JSON object, use json2.js which will add it in.


What's currently happening is since you have processData: false, it's basically sending this: ({"command":"on"}).toString() which is [object Object]...what you see in your request.

How to convert a String into an ArrayList?

Let's take a question : Reverse a String. I shall do this using stream().collect(). But first I shall change the string into an ArrayList .

    public class StringReverse1 {
    public static void main(String[] args) {

        String a = "Gini Gina  Proti";

        List<String> list = new ArrayList<String>(Arrays.asList(a.split("")));

        list.stream()
        .collect(Collectors.toCollection( LinkedList :: new ))
        .descendingIterator()
        .forEachRemaining(System.out::println);



    }}
/*
The output :
i
t
o
r
P


a
n
i
G

i
n
i
G
*/

Complex numbers usage in python

In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:

>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)

The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)

The type of a complex number is complex, and you can use the type as a constructor if you prefer:

>>> complex(2,3)
(2+3j)

A complex number has some built-in accessors:

>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)

Several built-in functions support complex numbers:

>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)

The standard module cmath has more functions that handle complex numbers:

>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)

How can I define fieldset border color?

It does appear red on Firefox and IE 8. But perhaps you need to change the border-style too.

_x000D_
_x000D_
.field_set{_x000D_
  border-color: #F00;_x000D_
  border-style: solid;_x000D_
}
_x000D_
<fieldset class="field_set">_x000D_
  <legend>box</legend>_x000D_
  <table width="100%" border="0" cellspacing="0" cellpadding="0">_x000D_
    <tr>_x000D_
      <td>&nbsp;</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</fieldset>
_x000D_
_x000D_
_x000D_

alt text

How to copy selected files from Android with adb pull

As to the short script, the following runs on my Linux host

#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION="\.jpg"

while read MYFILE ; do
    adb pull "$DEVICE_DIR/$MYFILE" "$HOST_DIR/$MYFILE"
done < $(adb shell ls -1 "$DEVICE_DIR" | grep "$EXTENSION")

"ls minus one" lets "ls" show one file per line, and the quotation marks allow spaces in the filename.

How to create a box when mouse over text in pure CSS?

You can also do it by toggling between display: block on hover and display:none without hover to produce the effect.

Gson - convert from Json to a typed ArrayList<T>

If you want to use Arrays, it's pretty simple.

logs = gson.fromJson(br, JsonLog[].class); // line 6

Provide the JsonLog as an array JsonLog[].class

Get checkbox list values with jQuery

var aArray = [];
window.$( "#myDiv" ).find( "input[type=checkbox][checked]" ).each( function()
{
  aArray.push( this.name );

});

You can put it in a function and execute on click of the button.

Redirect after Login on WordPress

// add the code to your theme function.php
//for logout redirection
add_action('wp_logout','auto_redirect_after_logout');
function auto_redirect_after_logout(){
wp_redirect( home_url() );
exit();
}
//for login redirection
add_action('wp_login','auto_redirect_after_login');
function auto_redirect_after_login(){
wp_redirect( home_url() );
exit();
`enter code here`}

Checkout subdirectories in Git?

Actually, "narrow" or "partial" or "sparse" checkouts are under current, heavy development for Git. Note, you'll still have the full repository under .git. So, the other two posts are current for the current state of Git but it looks like we will be able to do sparse checkouts eventually. Checkout the mailing lists if you're interested in more details -- they're changing rapidly.

Fixed size div?

<div id="normal>text..</div>
<div id="small1" class="smallDiv"></div>
<div id="small2" class="smallDiv"></div>
<div id="small3" class="smallDiv"></div>

css:

.smallDiv { height: 150px; width: 150px; }