Programs & Examples On #Inclusion

How to check if all of the following items are in a list?

Operators like <= in Python are generally not overriden to mean something significantly different than "less than or equal to". It's unusual for the standard library does this--it smells like legacy API to me.

Use the equivalent and more clearly-named method, set.issubset. Note that you don't need to convert the argument to a set; it'll do that for you if needed.

set(['a', 'b']).issubset(['a', 'b', 'c'])

Target Unreachable, identifier resolved to null in JSF 2.2

  1. You need

    @ManagedBean(name="userBean")

  2. Make sure you have getUser() method.

  3. Type of setUser() method should be void.

  4. Make sure that User class has proper setters and getters as well.

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

I came here with the same Error, though one with a different origin.

It is caused by unsupported float index in 1.12.0 and newer numpy versions even if the code should be considered as valid.

An int type is expected, not a np.float64

Solution: Try to install numpy 1.11.0

sudo pip install -U numpy==1.11.0.

How do I remove all null and empty string values from an object?

There is a very simple way to remove NULL values from JSON object. By default JSON object includes NULL values. Following can be used to remove NULL from JSON string

JsonConvert.SerializeObject(yourClassObject, new JsonSerializerSettings() {
                                       NullValueHandling = NullValueHandling.Ignore})) 

Is not an enclosing class Java

In case if Parent class is singleton use following way:

Parent.Child childObject = (Parent.getInstance()).new Child();

where getInstance() will return parent class singleton object.

SQL, How to Concatenate results?

In mysql you'd use the following function:

SELECT GROUP_CONCAT(ModuleValue, ",") FROM Table_X WHERE ModuleID=@ModuleID

I am not sure which dialect you are using.

Single vs double quotes in JSON

I recently came up against a very similar problem, and believe my solution would work for you too. I had a text file which contained a list of items in the form:

["first item", 'the "Second" item', "thi'rd", 'some \\"hellish\\" \'quoted" item']

I wanted to parse the above into a python list but was not keen on eval() as I couldn't trust the input. I tried first using JSON but it only accepts double quoted items, so I wrote my own very simple lexer for this specific case (just plug in your own "stringtoparse" and you will get as output list: 'items')

#This lexer takes a JSON-like 'array' string and converts single-quoted array items into escaped double-quoted items,
#then puts the 'array' into a python list
#Issues such as  ["item 1", '","item 2 including those double quotes":"', "item 3"] are resolved with this lexer
items = []      #List of lexed items
item = ""       #Current item container
dq = True       #Double-quotes active (False->single quotes active)
bs = 0          #backslash counter
in_item = False #True if currently lexing an item within the quotes (False if outside the quotes; ie comma and whitespace)
for c in stringtoparse[1:-1]:   #Assuming encasement by brackets
    if c=="\\": #if there are backslashes, count them! Odd numbers escape the quotes...
        bs = bs + 1
        continue                    
    if (dq and c=='"') or (not dq and c=="'"):  #quote matched at start/end of an item
        if bs & 1==1:   #if escaped quote, ignore as it must be part of the item
            continue
        else:   #not escaped quote - toggle in_item
            in_item = not in_item
            if item!="":            #if item not empty, we must be at the end
                items += [item]     #so add it to the list of items
                item = ""           #and reset for the next item
            continue                
    if not in_item: #toggle of single/double quotes to enclose items
        if dq and c=="'":
            dq = False
            in_item = True
        elif not dq and c=='"':
            dq = True
            in_item = True
        continue
    if in_item: #character is part of an item, append it to the item
        if not dq and c=='"':           #if we are using single quotes
            item += bs * "\\" + "\""    #escape double quotes for JSON
        else:
            item += bs * "\\" + c
        bs = 0
        continue

Hopefully it is useful to somebody. Enjoy!

z-index not working with fixed positioning

since your over div doesn't have a positioning, the z-index doesn't know where and how to position it (and with respect to what?). Just change your over div's position to relative, so there is no side effects on that div and then the under div will obey to your will.

here is your example on jsfiddle: Fiddle

edit: I see someone already mentioned this answer!

How can I calculate divide and modulo for integers in C#?

There is also Math.DivRem

quotient = Math.DivRem(dividend, divisor, out remainder);

What is path of JDK on Mac ?

The location has changed from Java 6 (provided by Apple) to Java 7 and onwards (provided by Oracle). The best generic way to find this out is to run

/usr/libexec/java_home

This is the natively supported way to find out both the path to the default Java installation as well as all alternative ones present.

If you check out its help text (java_home -h), you'll see that you can use this command to reliably start a Java program on OS X (java_home --exec ...), with the ability to explicitly specify the desired Java version and architecture, or even request the user to install it if missing.

A more pedestrian approach, but one which will help you trace specifically which Java installation the command java resolves into, goes like this:

  1. run

    which java
    
  2. if that gives you something like /usr/bin/java, which is a symbolic link to the real location, run

    ls -l `which java`
    

    On my system, this outputs

    /usr/bin/java -> /Library/Java/JavaVirtualMachines/jdk1.7.0_25.jdk/Contents/Home/bin/java
    

    and therefrom you can read the Java home directory;

  3. if usr/bin/java points to another symbolic link, recursively apply the same approach with

    ls -l <whatever the /usr/bin/java symlink points to>
    

An important variation is the setup you get if you start by installing Apple's Java and later install Oracle's. In that case Step 2 above will give you

/usr/bin/java -> /System/Library/Frameworks/JavaVM.framework/Commands/java

and that particular java binary is a stub which will resolve the actual java command to call by consulting the JAVA_HOME environment variable and, if it's not set or doesn't point to a Java home directory, will fall back to calling java_home. It is important to have this in mind when debugging your setup.

How to restart remote MySQL server running on Ubuntu linux?

sudo service mysql stop;
sudo service mysql start;

If the above process will not work let's check one the given code above you can stop Mysql server and again start server

Pytesseract : "TesseractNotFound Error: tesseract is not installed or it's not in your path", how do I fix this?

Perhaps this is happening because, even if Tesseract is correctly installed, you have not installed your language, as was my case. Fortunately this is very easy to fix, and I did not even need to mess with tesseract_cmd.

sudo apt-get install tesseract-ocr -y
sudo apt-get install tesseract-ocr-spa -y
tesseract --list-langs

Note that in the second line we have specified -spa for Spanish.

If installation has been successful, you should get a list of your available languages, like:

List of available languages (3):
eng
osd
spa

I found this at this blog post (Spanish). There is also a post for installation of Spanish language in Windows (not as easy apparently).

Note: since the question uses lang = 'eng', it is likely this is not the answer in that specific case. But the same error may happen in this other situation, which is why I posted the answer here.

how do I give a div a responsive height

I know this is a little late to the party but you could use viewport units

From caniuse.com:

Viewport units: vw, vh, vmin, vmax - CR Length units representing 1% of the viewport size for viewport width (vw), height (vh), the smaller of the two (vmin), or the larger of the two (vmax).

Support: http://caniuse.com/#feat=viewport-units

_x000D_
_x000D_
div {_x000D_
/* 25% of viewport */_x000D_
  height: 25vh;_x000D_
  width: 15rem;_x000D_
  background-color: #222;_x000D_
  color: #eee;_x000D_
  font-family: monospace;_x000D_
  padding: 2rem;_x000D_
}
_x000D_
<div>responsive height</div>
_x000D_
_x000D_
_x000D_

How to skip the first n rows in sql query

This works with all DBRM/SQL, it is standard ANSI:

SELECT *
  FROM owner.tablename A
 WHERE condition
  AND  n+1 <= (
         SELECT COUNT(DISTINCT b.column_order)
           FROM owner.tablename B
          WHERE condition
            AND b.column_order>a.column_order
          )
ORDER BY a.column_order DESC

How to set up a squid Proxy with basic username and password authentication?

Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)

Basic squid conf

/etc/squid3/squid.conf instead of the super bloated default config file

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

# Choose the port you want. Below we set it to default 3128.
http_port 3128

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

For squid 2.x you need to edit /etc/squid/squid.conf file and place:

auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

For the many people that asked me: the 2 tools produce different file formats:

  • htdigest stores the password in plain text.
  • htpasswd stores the password hashed (various hashing algos are available)

Despite this difference in format basic_ncsa_auth will still be able to parse a password file generated with htdigest. Hence you can alternatively use:

sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like

Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.

On Ubuntu 14.04 htdigest and htpasswd are both available in the [apache2-utils][1] package.

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

Squid config file is stored at /usr/local/etc/squid.conf.

Comment or remove following line:

http_access allow localnet

Then similar to linux config (but with updated paths) add this:

auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Note that path to basic_ncsa_auth may be different since it depends on installed version when using brew, you can verify this with ls /usr/local/Cellar/squid/. Also note that you should add the above just bellow the following section:

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

Now generate yourself a user:password basic auth credential (note: htpasswd and htdigest are also both available on MacOS)

htpasswd -c /usr/local/etc/squid_passwords username_you_like

Restart the squid service

brew services restart squid

Rails: Using greater than/less than with a where statement

I've only tested this in Rails 4 but there's an interesting way to use a range with a where hash to get this behavior.

User.where(id: 201..Float::INFINITY)

will generate the SQL

SELECT `users`.* FROM `users`  WHERE (`users`.`id` >= 201)

The same can be done for less than with -Float::INFINITY.

I just posted a similar question asking about doing this with dates here on SO.

>= vs >

To avoid people having to dig through and follow the comments conversation here are the highlights.

The method above only generates a >= query and not a >. There are many ways to handle this alternative.

For discrete numbers

You can use a number_you_want + 1 strategy like above where I'm interested in Users with id > 200 but actually look for id >= 201. This is fine for integers and numbers where you can increment by a single unit of interest.

If you have the number extracted into a well named constant this may be the easiest to read and understand at a glance.

Inverted logic

We can use the fact that x > y == !(x <= y) and use the where not chain.

User.where.not(id: -Float::INFINITY..200)

which generates the SQL

SELECT `users`.* FROM `users` WHERE (NOT (`users`.`id` <= 200))

This takes an extra second to read and reason about but will work for non discrete values or columns where you can't use the + 1 strategy.

Arel table

If you want to get fancy you can make use of the Arel::Table.

User.where(User.arel_table[:id].gt(200))

will generate the SQL

"SELECT `users`.* FROM `users` WHERE (`users`.`id` > 200)"

The specifics are as follows:

User.arel_table              #=> an Arel::Table instance for the User model / users table
User.arel_table[:id]         #=> an Arel::Attributes::Attribute for the id column
User.arel_table[:id].gt(200) #=> an Arel::Nodes::GreaterThan which can be passed to `where`

This approach will get you the exact SQL you're interested in however not many people use the Arel table directly and can find it messy and/or confusing. You and your team will know what's best for you.

Bonus

Starting in Rails 5 you can also do this with dates!

User.where(created_at: 3.days.ago..DateTime::Infinity.new)

will generate the SQL

SELECT `users`.* FROM `users` WHERE (`users`.`created_at` >= '2018-07-07 17:00:51')

Double Bonus

Once Ruby 2.6 is released (December 25, 2018) you'll be able to use the new infinite range syntax! Instead of 201..Float::INFINITY you'll be able to just write 201... More info in this blog post.

CSS table layout: why does table-row not accept a margin?

See the CSS 2.1 standard, section 17.5.3. When you use display:table-row, the height of the DIV is solely determined by the height of the table-cell elements in it. Thus, margin, padding, and height on those elements have no effect.

http://www.w3.org/TR/CSS2/tables.html

How to properly upgrade node using nvm

if you have 4.2 and want to install 5.0.0 then

nvm install v5.0.0 --reinstall-packages-from=4.2

the answer of gabrielperales is right except that he missed the "=" sign at the end. if you don't put the "=" sign then new node version will be installed but the packages won't be installed.

source: sitepoint

Use nginx to serve static files from subdirectories of a given directory

It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:

When location matches the last part of the directive’s value: it is better to use the root directive instead:

which would yield:

server {
  listen        8080;
  server_name   www.mysite.com mysite.com;
  error_log     /home/www-data/logs/nginx_www.error.log;
  error_page    404    /404.html;

  location /public/doc/ {
    autoindex on;
    root  /home/www-data/mysite;
  } 

  location = /404.html {
    root /home/www-data/mysite/static/html;
  }       
}

how to check if string contains '+' character

Why not just:

int plusIndex = s.indexOf("+");
if (plusIndex != -1) {
    String before = s.substring(0, plusIndex);
    // Use before
}

It's not really clear why your original version didn't work, but then you didn't say what actually happened. If you want to split not using regular expressions, I'd personally use Guava:

Iterable<String> bits = Splitter.on('+').split(s);
String firstPart = Iterables.getFirst(bits, "");

If you're going to use split (either the built-in version or Guava) you don't need to check whether it contains + first - if it doesn't there'll only be one result anyway. Obviously there's a question of efficiency, but it's simpler code:

// Calling split unconditionally
String[] parts = s.split("\\+");
s = parts[0];

Note that writing String[] parts is preferred over String parts[] - it's much more idiomatic Java code.

Adding local .aar files to Gradle build using "flatDirs" is not working

This line includes all aar and jar files from libs folder:

implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs/')

Filter multiple values on a string column in dplyr

Using the base package:

df <- data.frame(days = c(88, 11, 2, 5, 22, 1, 222, 2), name = c("Lynn", "Tom", "Chris", "Lisa", "Kyla", "Tom", "Lynn", "Lynn"))

# Three lines
target <- c("Tom", "Lynn")
index <- df$name %in% target
df[index, ]

# One line
df[df$name %in% c("Tom", "Lynn"), ] 

Output:

  days name
1   88 Lynn
2   11  Tom
6    1  Tom
7  222 Lynn
8    2 Lynn

Using sqldf:

library(sqldf)
# Two alternatives:
sqldf('SELECT *
      FROM df 
      WHERE name = "Tom" OR name = "Lynn"')
sqldf('SELECT *
      FROM df 
      WHERE name IN ("Tom", "Lynn")')

angular ng-repeat in reverse

I would sugest using array native reverse method is always better choice over creating filter or using $index.

<div ng-repeat="friend in friends.reverse()">{{friend.name}}</div>

Plnkr_demo.

Monitor the Graphics card usage

If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:

Screenshot from MSDN: enter image description here

Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:

In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.

Source: http://blogs.msdn.com/b/ianhu/archive/2014/12/16/gpu-usage-for-directx-in-visual-studio.aspx

Explain the different tiers of 2 tier & 3 tier architecture?

In a modern two-tier architecture, the server holds both the application and the data. The application resides on the server rather than the client, probably because the server will have more processing power and disk space than the PC.

In a three-tier architecture, the data and applications are split onto seperate servers, with the server-side distributed between a database server and an application server. The client is a front end, simply requesting and displaying data. Reason being that each server will be dedicated to processing either data or application requests, hence a more manageable system and less contention for resources will occur.

You can refer to Difference between three tier vs. n-tier

How to get root directory in yii2

To get the base URL you can use this (would return "http:// localhost/yiistore2/upload")

Yii::app()->baseUrl

The following Code would return just "localhost/yiistore2/upload" without http[s]://

Yii::app()->getBaseUrl(true)

Or you could get the webroot path (would return "d:\wamp\www\yii2store")

Yii::getPathOfAlias('webroot')

Enable PHP Apache2

If anyone gets

ERROR: Module phpX.X does not exist!

just install the module for your current php version:

apt-get install libapache2-mod-phpX.X

ASP.NET Setting width of DataBound column in GridView

<asp:GridView ID="GridView1" AutoGenerateEditButton="True" 
ondatabound="gv_DataBound" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" width="600px">

<Columns>
                <asp:BoundField HeaderText="UserId" 
                DataField="UserId" 
                SortExpression="UserId" ItemStyle-Width="400px"></asp:BoundField>
   </Columns>
</asp:GridView>

Should I Dispose() DataSet and DataTable?

No need to Dispose() because DataSet inherit MarshalByValueComponent class and MarshalByValueComponent implement IDisposable Interface

Add / remove input field dynamically with jQuery

enter image description here You should be able to create and remove input field dynamically by using jquery using this method(https://www.adminspress.com/onex/view/uaomui), Even you can able to generate input fields in bulk and export to string.

Jquery Ajax Loading image

Please note that: ajaxStart / ajaxStop is not working for ajax jsonp request (ajax json request is ok)

I am using jquery 1.7.2 while writing this.

here is one of the reference I found: http://bugs.jquery.com/ticket/8338

Submit HTML form on self page

If you are submitting a form using php be sure to use:

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

for security.

how to pass data in an hidden field from one jsp page to another?

The code from Alex works great. Just note that when you use request.getParameter you must use a request dispatcher

//Pass results back to the client
RequestDispatcher dispatcher =   getServletContext().getRequestDispatcher("TestPages/ServiceServlet.jsp");
dispatcher.forward(request, response);

What port is used by Java RMI connection?

The port is available here: java.rmi.registry.Registry.REGISTRY_PORT (1099)

How to undo a git pull?

Find the <SHA#> for the commit you want to go. You can find it in github or by typing git log or git reflog show at the command line and then do git reset --hard <SHA#>

compare differences between two tables in mysql

 select t1.user_id,t2.user_id 
 from t1 left join t2 ON t1.user_id = t2.user_id 
 and t1.username=t2.username 
 and t1.first_name=t2.first_name 
 and t1.last_name=t2.last_name

try this. This will compare your table and find all matching pairs, if any mismatch return NULL on left.

Attach IntelliJ IDEA debugger to a running Java process

Also I use Tomcat GUI app (in my case: C:\tomcat\bin\Tomcat9w.bin).

  • Go to Java tab:

    enter image description here

  • Set your Java properties, for example:

    Java virtual machine

    C:\Program Files\Java\jre-10.0.2\bin\server\jvm.dll

    Java virtual machine

    C:\tomcat\bin\bootstrap.jar;C:\tomcat\bin\tomcat-juli.jar

    Java Options:

    -Dcatalina.home=C:\tomcat

    -Dcatalina.base=C:\tomcat

    -Djava.io.tmpdir=C:\tomcat\temp

    -Djava.util.logging.config.file=C:\tomcat\conf\logging.properties

    -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8000

    Java 9 options:

    --add-opens=java.base/java.lang=ALL-UNNAMED

    --add-opens=java.base/java.io=ALL-UNNAMED

    --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED

Plot size and resolution with R markdown, knitr, pandoc, beamer

I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```

Then all the images will be written as PDF files, and LaTeX will be happy.

Your second problem is you are mixing up the HTML units with LaTeX units in out.width / out.height. LaTeX and HTML are very different technologies. You should not expect \maxwidth to work in HTML, or 200px in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width / out.height (use fig.width / fig.height and let LaTeX use the original size).

What is the difference between substr and substring?

substring(): It has 2 parameters "start" and "end".

  • start parameter is required and specifies the position where to start the extraction.
  • end parameter is optional and specifies the position where the extraction should end.

If the end parameter is not specified, all the characters from the start position till the end of the string are extracted.

_x000D_
_x000D_
var str = "Substring Example";_x000D_
var result = str.substring(0, 10);_x000D_
alert(result);_x000D_
_x000D_
Output : Substring
_x000D_
_x000D_
_x000D_

If the value of start parameter is greater than the value of the end parameter, this method will swap the two arguments. This means start will be used as end and end will be used as start.

_x000D_
_x000D_
var str = "Substring Example";_x000D_
var result = str.substring(10, 0);_x000D_
alert(result);_x000D_
_x000D_
Output : Substring
_x000D_
_x000D_
_x000D_

substr(): It has 2 parameters "start" and "count".

  • start parameter is required and specifies the position where to start the extraction.

  • count parameter is optional and specifies the number of characters to extract.

_x000D_
_x000D_
var str = "Substr Example";_x000D_
var result = str.substr(0, 10);_x000D_
alert(result);_x000D_
_x000D_
_x000D_
Output : Substr Exa
_x000D_
_x000D_
_x000D_

If the count parameter is not specified, all the characters from the start position till the end of the string are extracted. If count is 0 or negative, an empty string is returned.

_x000D_
_x000D_
var str = "Substr Example";_x000D_
var result = str.substr(11);_x000D_
alert(result);_x000D_
_x000D_
Output : ple
_x000D_
_x000D_
_x000D_

Global variables in header file

Dont define varibale in header file , do declaration in header file(good practice ) .. in your case it is working because multiple weak symbols .. Read about weak and strong symbol ....link :http://csapp.cs.cmu.edu/public/ch7-preview.pdf

This type of code create problem while porting.

How do I convert two lists into a dictionary?

with Python 3.x, goes for dict comprehensions

keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')

dic = {k:v for k,v in zip(keys, values)}

print(dic)

More on dict comprehensions here, an example is there:

>>> print {i : chr(65+i) for i in range(4)}
    {0 : 'A', 1 : 'B', 2 : 'C', 3 : 'D'}

How to use null in switch

switch ((i != null) ? i : DEFAULT_VALUE) {
        //...
}

php - How do I fix this illegal offset type error

Use trim($source) before $s[$source].

Escape double quotes in Java

Use Java's replaceAll(String regex, String replacement)

For example, Use a substitution char for the quotes and then replace that char with \"

String newstring = String.replaceAll("%","\"");

or replace all instances of \" with \\\"

String newstring = String.replaceAll("\"","\\\"");

How do I append a node to an existing XML file in java

You can parse the existing XML file into DOM and append new elements to the DOM. Very similar to what you did with creating brand new XML. I am assuming you do not have to worry about duplicate server. If you do have to worry about that, you will have to go through the elements in the DOM to check for duplicates.

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

/* parse existing file to DOM */
Document document = documentBuilder.parse(new File("exisgint/xml/file"));

Element root = document.getDocumentElement();

for (Server newServer : Collection<Server> bunchOfNewServers){
  Element server = Document.createElement("server");
  /* create and setup the server node...*/

 root.appendChild(server);
}

/* use whatever method to output DOM to XML (for example, using transformer like you did).*/

How to determine an object's class?

Use Object.getClass(). It returns the runtime type of the object.

Copy struct to struct in C

memcpy expects the first two arguments to be void*.

Try: memcpy( (void*)&RTCclk, (void*)&RTCclkBuffert, sizeof(RTCclk) );

P.S. although not necessary, convention dictates the brackets for the sizeof operator. You can get away with a lot in C that leaves code impossible to maintain, so following convention is the mark of a good (employable) C programmer.

Replace image src location using CSS

you can use: content:url("image.jpg")

<style>
.your-class-name{
    content: url("http://imgur.com/SZ8Cm.jpg");
}
</style>

<img class="your-class-name" src="..."/>

How to top, left justify text in a <td> cell that spans multiple rows

 <td rowspan="2" style="text-align:left;vertical-align:top;padding:0">Save a lot</td>

That should do it.

Write objects into file with Node.js

Building on what deb2fast said I would also pass in a couple of extra parameters to JSON.stringify() to get it to pretty format:

fs.writeFileSync('./data.json', JSON.stringify(obj, null, 2) , 'utf-8');

The second param is an optional replacer function which you don't need in this case so null works.

The third param is the number of spaces to use for indentation. 2 and 4 seem to be popular choices.

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

Try to run Maven from the command line or type "-X" in the text field - you can't break anything this way, at the worst, you'll get an error (I don't have Netbeans; in Eclipse, there is a checkbox "Debug" for this).

When running with debug output enabled, you should see the paths which the exec-maven-plugin plugin uses.

The next step would then be to copy the command into a command prompt or terminal and execute it manually to see if you get a useful error message there.

How do I programmatically "restart" an Android app?

IntentCompat.makeMainSelectorActivity - Last tested on 11/2020

The app will be restored with the launcher activity and the old process will be killed.

Works from Api 15.

public static void restart(Context context){
    Intent mainIntent = IntentCompat.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_LAUNCHER);
    mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.getApplicationContext().startActivity(mainIntent);
    System.exit(0);
}

Open a PDF using VBA in Excel

Use Shell "program file path file path you want to open".

Example:

Shell "c:\windows\system32\mspaint.exe c:users\admin\x.jpg"

Setting network adapter metric priority in Windows 7

I had the same problem on Windows 7 64-bit Pro. I adjusted network adapters binding using Control panel but nothing changed. Also metrics where showing that Win should use Ethernet adapter as primary, but it didn't.

Then a tried to uninstall Ethernet adapter driver and then install it again (without restart) and then I checked metrics for sure.

After this, Windows started prioritize Ethernet adapter.

How to declare a global variable in C++

You declare the variable as extern in a common header:

//globals.h
extern int x;

And define it in an implementation file.

//globals.cpp
int x = 1337;

You can then include the header everywhere you need access to it.

I suggest you also wrap the variable inside a namespace.

PHPMailer AddAddress()

You need to call the AddAddress function once for each E-Mail address you want to send to. There are only two arguments for this function: recipient_email_address and recipient_name. The recipient name is optional and will not be used if not present.

$mailer->AddAddress('[email protected]', 'First Name');
$mailer->AddAddress('[email protected]', 'Second Name');
$mailer->AddAddress('[email protected]', 'Third Name');

You could use an array to store the recipients and then use a for loop. I hope it helps.

How to convert Moment.js date to users local timezone?

Here's what I did:

var timestamp = moment.unix({{ time }});
var utcOffset = moment().utcOffset();
var local_time = timestamp.add(utcOffset, "minutes");
var dateString = local_time.fromNow();

Where {{ time }} is the utc timestamp.

How do I count columns of a table

SELECT count(*)
FROM information_schema.columns
WHERE table_name = 'tbl_ifo'

What does "javax.naming.NoInitialContextException" mean?

It means that there is no initial context :)

But seriously folks, JNDI (javax.naming) is all about looking up objects or resources from some directory or provider. To look something up, you need somewhere to look (this is the InitialContext). NoInitialContextException means "I want to find the telephone number for John Smith, but I have no phonebook to look in".

An InitialContext can be created in any number of ways. It can be done manually, for instance creating a connection to an LDAP server. It can also be set up by an application server inside which you run your application. In this case, the container (application server) already provides you with a "phonebook", through which you can look up anything the application server makes available. This is often configurable and a common way of moving this type of configuration from the application implementation to the container, where it can be shared across all applications in the server.

UPDATE: from the code snippet you post it looks like you are trying to run code stand-alone that is meant to be run in an application server. In this case, the code attempting to get a connection to a database from the "phonebook". This is one of the resources that is often configured in the application server container. So, rather than having to manage configuration and connections to the database in your code, you can configure it in your application server and simple ask for a connection (using JNDI) in your code.

Codeigniter : calling a method of one controller from other

You can do like

$result= file_get_contents(site_url('[ADDRESS TO CONTROLLER FUNCTION]'));

Replace [ADDRESS TO CONTROLLER FUNCTION] by the way we use in site_url();

You need to echo output in controller function instead of return.

How can I get a collection of keys in a JavaScript dictionary?

For new browsers: Object.keys( MY_DICTIONARY ) will return an array of keys. Else you may want to go the old school way:

var keys = []
for(var key in dic) keys.push( key );

What is the difference between a static and const variable?

Static variables are common across all instances of a type.

constant variables are specific to each individual instance of a type but their values are known and fixed at compile time and it cannot be changed at runtime.

unlike constants, static variable values can be changed at runtime.

Maven not found in Mac OSX mavericks

For me I had a AdoptOpenJDK 8 installed, instead of SE JDK 8. For which it was not able to recognize JAVA_HOME or mvn commands.

Check your java_home /usr/libexec/java_home -V and use JAVA SE SDK if it is different.

Then follow the above steps to install maven and check again

Angular 2 Sibling Component Communication

You need to set up the parent-child relationship between your components. The problem is that you might simply inject the child components in the constructor of the parent component and store it in a local variable. Instead, you should declare the child components in your parent component by using the @ViewChild property declarator. This is how your parent component should look like:

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ListComponent } from './list.component';
import { DetailComponent } from './detail.component';

@Component({
  selector: 'app-component',
  template: '<list-component></list-component><detail-component></detail-component>',
  directives: [ListComponent, DetailComponent]
})
class AppComponent implements AfterViewInit {
  @ViewChild(ListComponent) listComponent:ListComponent;
  @ViewChild(DetailComponent) detailComponent: DetailComponent;

  ngAfterViewInit() {
    // afther this point the children are set, so you can use them
    this.detailComponent.doSomething();
  }
}

https://angular.io/docs/ts/latest/api/core/index/ViewChild-var.html

https://angular.io/docs/ts/latest/cookbook/component-communication.html#parent-to-view-child

Beware, the child component will not be available in the constructor of the parent component, just after the ngAfterViewInit lifecycle hook is called. To catch this hook simple implement the AfterViewInit interface in you parent class the same way you would do with OnInit.

But, there are other property declarators as explained in this blog note: http://blog.mgechev.com/2016/01/23/angular2-viewchildren-contentchildren-difference-viewproviders/

Advantages of std::for_each over for loop

There are a lot of good reasons in other answers but all seem to forget that for_each allows you to use reverse or pretty much any custom iterator when for loop always starts with begin() iterator.

Example with reverse iterator:

std::list<int> l {1,2,3};
std::for_each(l.rbegin(), l.rend(), [](auto o){std::cout<<o;});

Example with some custom tree iterator:

SomeCustomTree<int> a{1,2,3,4,5,6,7};
auto node = a.find(4);
std::for_each(node.breadthFirstBegin(), node.breadthFirstEnd(), [](auto o){std::cout<<o;});

How can I delete all of my Git stashes at once?

To delete all stashes older than 40 days, use:

git reflog expire --expire-unreachable=40.days refs/stash

Add --dry-run to see which stashes are deleted.

See https://stackoverflow.com/a/44829516/946850 for an explanation and much more detail.

Rails 4 Authenticity Token

When you define you own html form then you have to include authentication token string ,that should be sent to controller for security reasons. If you use rails form helper to generate the authenticity token is added to form as follow.

<form accept-charset="UTF-8" action="/login/signin" method="post">
  <div style="display:none">
    <input name="utf8" type="hidden" value="&#x2713;" />
    <input name="authenticity_token" type="hidden" value="x37DrAAwyIIb7s+w2+AdoCR8cAJIpQhIetKRrPgG5VA=">
  </div>
    ...
</form>

So the solution to the problem is either to add authenticity_token field or use rails form helpers rather then compromising security etc.

Check list of words in another string

if any(word in 'some one long two phrase three' for word in list_):

The program can't start because MSVCR110.dll is missing from your computer

You can download the required files from the Microsoft website or online or reinstall the Visual studio 2012 to fix this.

How can I view the contents of an ElasticSearch index?

You can view any existing index by using the below CURL. Please replace the index-name with your actual name before running and it will run as is.

View the index content

curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name?pretty

And the output will include an index(see settings in output) and its mappings too and it will look like below output -

{
  "index_name": {
    "aliases": {},
    "mappings": {
      "collection_name": {
        "properties": {
          "test_field": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }
       }
    },
    "settings": {
      "index": {
        "creation_date": "1527377274366",
        "number_of_shards": "5",
        "number_of_replicas": "1",
        "uuid": "6QfKqbbVQ0Gbsqkq7WZJ2g",
        "version": {
          "created": "6020299"
        },
        "provided_name": "index_name"
      }
    }
  }
}

View ALL the data under this index

curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name/_search?pretty

Easy way to export multiple data.frame to multiple Excel worksheets

There's a new library in town, from rOpenSci: writexl

Portable, light-weight data frame to xlsx exporter based on libxlsxwriter. No Java or Excel required

I found it better and faster than the above suggestions (working with the dev version):

library(writexl)
sheets <- list("sheet1Name" = sheet1, "sheet2Name" = sheet2) #assume sheet1 and sheet2 are data frames
write_xlsx(sheets, "path/to/location")

Android: combining text & image on a Button or ImageButton

You can call setBackground() on a Button to set the background of the button.

Any text will appear above the background.

If you are looking for something similar in xml there is: android:background attribute which works the same way.

Converting camel case to underscore case in ruby

Here's how Rails does it:

   def underscore(camel_cased_word)
     camel_cased_word.to_s.gsub(/::/, '/').
       gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
       gsub(/([a-z\d])([A-Z])/,'\1_\2').
       tr("-", "_").
       downcase
   end

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

Swift error : signal SIGABRT how to solve it

I had the same problem. In my case I just overwrote the file

GoogleService-Info.plist

on that path:

Platform\ios\YOUR_APP_NAME\Resources\Resources

In my case the files were present without data.

Default argument values in JavaScript functions

You cannot add default values for function parameters. But you can do this:

function tester(paramA, paramB){
 if (typeof paramA == "undefined"){
   paramA = defaultValue;
 }
 if (typeof paramB == "undefined"){
   paramB = defaultValue;
 }
}

How to read from stdin with fgets()?

If you want to concatenate the input, then replace printf("%s\n", buffer); with strcat(big_buffer, buffer);. Also create and initialize the big buffer at the beginning: char *big_buffer = new char[BIG_BUFFERSIZE]; big_buffer[0] = '\0';. You should also prevent a buffer overrun by verifying the current buffer length plus the new buffer length does not exceed the limit: if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE). The modified program would look like this:

#include <stdio.h>
#include <string.h>

#define BUFFERSIZE 10
#define BIG_BUFFERSIZE 1024

int main (int argc, char *argv[])
{
    char buffer[BUFFERSIZE];
    char *big_buffer = new char[BIG_BUFFERSIZE];
    big_buffer[0] = '\0';
    printf("Enter a message: \n");
    while(fgets(buffer, BUFFERSIZE , stdin) != NULL)
    {
        if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE)
        {
            strcat(big_buffer, buffer);
        }
    }
    return 0;
}

Browse for a directory in C#

Please don't try and roll your own with a TreeView/DirectoryInfo class. For one thing there are many nice features you get for free (icons/right-click/networks) by using SHBrowseForFolder. For another there are a edge cases/catches you will likely not be aware of.

Difference between agile and iterative and incremental development

  • Iterative - you don't finish a feature in one go. You are in a code >> get feedback >> code >> ... cycle. You keep iterating till done.
  • Incremental - you build as much as you need right now. You don't over-engineer or add flexibility unless the need is proven. When the need arises, you build on top of whatever already exists. (Note: differs from iterative in that you're adding new things.. vs refining something).
  • Agile - you are agile if you value the same things as listed in the agile manifesto. It also means that there is no standard template or checklist or procedure to "do agile". It doesn't overspecify.. it just states that you can use whatever practices you need to "be agile". Scrum, XP, Kanban are some of the more prescriptive 'agile' methodologies because they share the same set of values. Continuous and early feedback, frequent releases/demos, evolve design, etc.. hence they can be iterative and incremental.

How can I set multiple CSS styles in JavaScript?

You can write a function that will set declarations individually in order not to overwrite any existing declarations that you don't supply. Let's say you have this object parameter list of declarations:

const myStyles = {
  'background-color': 'magenta',
  'border': '10px dotted cyan',
  'border-radius': '5px',
  'box-sizing': 'border-box',
  'color': 'yellow',
  'display': 'inline-block',
  'font-family': 'monospace',
  'font-size': '20px',
  'margin': '1em',
  'padding': '1em'
};

You might write a function that looks like this:

function applyStyles (el, styles) {
  for (const prop in styles) {
    el.style.setProperty(prop, styles[prop]);
  }
};

which takes an element and an object property list of style declarations to apply to that object. Here's a usage example:

const p = document.createElement('p');
p.textContent = 'This is a paragraph.';
document.body.appendChild(p);

applyStyles(p, myStyles);
applyStyles(document.body, {'background-color': 'grey'});

_x000D_
_x000D_
// styles to apply_x000D_
const myStyles = {_x000D_
  'background-color': 'magenta',_x000D_
  'border': '10px dotted cyan',_x000D_
  'border-radius': '5px',_x000D_
  'box-sizing': 'border-box',_x000D_
  'color': 'yellow',_x000D_
  'display': 'inline-block',_x000D_
  'font-family': 'monospace',_x000D_
  'font-size': '20px',_x000D_
  'margin': '1em',_x000D_
  'padding': '1em'_x000D_
};_x000D_
_x000D_
function applyStyles (el, styles) {_x000D_
  for (const prop in styles) {_x000D_
    el.style.setProperty(prop, styles[prop]);_x000D_
  }_x000D_
};_x000D_
_x000D_
// create example paragraph and append it to the page body_x000D_
const p = document.createElement('p');_x000D_
p.textContent = 'This is a paragraph.';_x000D_
document.body.appendChild(p);_x000D_
_x000D_
// when the paragraph is clicked, call the function, providing the_x000D_
// paragraph and myStyles object as arguments_x000D_
p.onclick = (ev) => {_x000D_
  applyStyles(p, myStyles);_x000D_
}_x000D_
_x000D_
// this time, target the page body and supply an object literal_x000D_
applyStyles(document.body, {'background-color': 'grey'});
_x000D_
_x000D_
_x000D_

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

How to create a jQuery function (a new jQuery method or plugin)?

You can always do this:

jQuery.fn.extend({
   myfunction: function(param){
       // code here
   },
});
OR
jQuery.extend({
   myfunction: function(param){
       // code here
   },
});
$(element).myfunction(param);

MySQL Cannot drop index needed in a foreign key constraint

Step 1

List foreign key ( NOTE that its different from index name )

SHOW CREATE TABLE  <Table Name>

The result will show you the foreign key name.

Format:

CONSTRAINT `FOREIGN_KEY_NAME` FOREIGN KEY (`FOREIGN_KEY_COLUMN`) REFERENCES `FOREIGN_KEY_TABLE` (`id`),

Step 2

Drop (Foreign/primary/key) Key

ALTER TABLE <Table Name> DROP FOREIGN KEY <Foreign key name>

Step 3

Drop the index.

String Pattern Matching In Java

That's just a matter of String.contains:

if (input.contains("{item}"))

If you need to know where it occurs, you can use indexOf:

int index = input.indexOf("{item}");
if (index != -1) // -1 means "not found"
{
    ...
}

That's fine for matching exact strings - if you need real patterns (e.g. "three digits followed by at most 2 letters A-C") then you should look into regular expressions.

EDIT: Okay, it sounds like you do want regular expressions. You might want something like this:

private static final Pattern URL_PATTERN =
    Pattern.compile("/\\{[a-zA-Z0-9]+\\}/");

...

if (URL_PATTERN.matches(input).find())

Creating hard and soft links using PowerShell

I wrote a PowerShell module that has native wrappers for MKLINK. https://gist.github.com/2891103

Includes functions for:

  • New-Symlink
  • New-HardLink
  • New-Junction

Captures the MKLINK output and throws proper PowerShell errors when necessary.

How to fix C++ error: expected unqualified-id

For anyone with this situation: I saw this error when I accidentally used my_first_scope::my_second_scope::true in place of simply true, like this:

bool my_var = my_first_scope::my_second_scope::true;

instead of:

bool my_var = true;

This is because I had a macro which caused MY_MACRO(true) to expand into my_first_scope::my_second_scope::true, by mistake, and I was actually calling bool my_var = MY_MACRO(true);.

Here's a quick demo of this type of scoping error:

Program (you can run it online here: https://onlinegdb.com/BkhFBoqUw):

#include <iostream>
#include <cstdio>

namespace my_first_scope 
{
namespace my_second_scope
{
} // namespace my_second_scope
} // namespace my_first_scope

int main()
{
    printf("Hello World\n");
    
    bool my_var = my_first_scope::my_second_scope::true;
    
    std::cout << my_var << std::endl;

    return 0;
}

Output (build error):

main.cpp: In function ‘int main()’:
main.cpp:27:52: error: expected unqualified-id before ‘true’
     bool my_var = my_first_scope::my_second_scope::true;
                                                    ^~~~

Notice the error: error: expected unqualified-id before ‘true’, and where the arrow under the error is pointing. Apparently the "unqualified-id" in my case is the double colon (::) scope operator I have just before true.

When I add in the macro and use it (run this new code here: https://onlinegdb.com/H1eevs58D):

#define MY_MACRO(input) my_first_scope::my_second_scope::input

...

bool my_var = MY_MACRO(true);

I get this new error instead:

main.cpp: In function ‘int main()’:
main.cpp:29:28: error: expected unqualified-id before ‘true’
     bool my_var = MY_MACRO(true);
                            ^
main.cpp:16:58: note: in definition of macro ‘MY_MACRO’
 #define MY_MACRO(input) my_first_scope::my_second_scope::input
                                                          ^~~~~

Crystal Reports 13 And Asp.Net 3.5

I had this same problem and resolved it by making sure all references to the previous version of crystal from the Web Config file, the server, and the publishing workstation were removed. Other than the full trust basically everything that user707217 did, I did and it worked for my upgraded Web application

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

Open the sql file in your text editor;

1. Search: utf8mb4_unicode_ci Replace: utf8_general_ci (Replace All)

2. Search: utf8mb4_unicode_520_ci Replace: utf8_general_ci (Replace All)

3. Search: utf8mb4 Replace: utf8 (Replace All)

Save and upload!

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 use String.Format?

Besides being a bit easier to read and adding a few more operators, it's also beneficial if your application is internationalized. A lot of times the variables are numbers or key words which will be in a different order for different languages. By using String.Format, your code can remain unchanged while different strings will go into resource files. So, the code would end up being

String.Format(resource.GetString("MyResourceString"), str1, str2, str3);

While your resource strings end up being

English: "blah blah {0} blah blah {1} blah {2}"

Russian: "{0} blet blet blet {2} blet {1}"

Where Russian may have different rules on how things get addressed so the order is different or sentence structure is different.

SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

Use the following Statement:

IF EXISTS(SELECT * FROM prueba )
then
  UPDATE prueba
  SET nombre = '1', apellido = '1' 
  WHERE cedula = 'ct'
ELSE 
  INSERT INTO prueba (cedula, nombre, apellido)
  VALUES ('ct', 'ct', 'ct');

How do I display a MySQL error in PHP for a long query that depends on the user input?

I use the following to turn all error reporting on for MySQLi

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

*NOTE: don't use this in a production environment.

how to remove empty strings from list, then remove duplicate values from a list

Amiram Korach solution is indeed tidy. Here's an alternative for the sake of versatility.

var count = dtList.Count;
// Perform a reverse tracking.
for (var i = count - 1; i > -1; i--)
{
    if (dtList[i]==string.Empty) dtList.RemoveAt(i);
}
// Keep only the unique list items.
dtList = dtList.Distinct().ToList();

Git push error pre-receive hook declined

GitLab by default marks master branch as protected (See part Protecting your code in https://about.gitlab.com/2014/11/26/keeping-your-code-protected/ why). If so in your case, then this can help:

Open your project > Settings > Repository and go to "Protected branches", find "master" branch into the list and click "Unprotect" and try again.

via https://gitlab.com/gitlab-com/support-forum/issues/40

For version 8.11 and above how-to here: https://docs.gitlab.com/ee/user/project/protected_branches.html#restricting-push-and-merge-access-to-certain-users

How to add 20 minutes to a current date?

Use .getMinutes() to get the current minutes, then add 20 and use .setMinutes() to update the date object.

var twentyMinutesLater = new Date();
twentyMinutesLater.setMinutes(twentyMinutesLater.getMinutes() + 20);

intelliJ IDEA 13 error: please select Android SDK

check if you have installed all the add-ons that are necessary. Also I recommend you to use a real android phone for debugging. It's better, It's real and faster.

Python: get key of index in dictionary

You could do something like this:

i={'foo':'bar', 'baz':'huh?'}
keys=i.keys()  #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")]  #'foo'

However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.

As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.

Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:

d={'i':1, 'j':1}

In that case, it is impossible to know whether you want i or j and in fact no answer here will be able to tell you which ('i' or 'j') will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.

How to efficiently build a tree from a flat structure?

Store IDs of the objects in a hash table mapping to the specific object. Enumerate through all the objects and find their parent if it exists and update its parent pointer accordingly.

class MyObject
{ // The actual object
    public int ParentID { get; set; }
    public int ID { get; set; }
}

class Node
{
    public List<Node> Children = new List<Node>();
    public Node Parent { get; set; }
    public MyObject AssociatedObject { get; set; }
}

IEnumerable<Node> BuildTreeAndGetRoots(List<MyObject> actualObjects)
{
    Dictionary<int, Node> lookup = new Dictionary<int, Node>();
    actualObjects.ForEach(x => lookup.Add(x.ID, new Node { AssociatedObject = x }));
    foreach (var item in lookup.Values) {
        Node proposedParent;
        if (lookup.TryGetValue(item.AssociatedObject.ParentID, out proposedParent)) {
            item.Parent = proposedParent;
            proposedParent.Children.Add(item);
        }
    }
    return lookup.Values.Where(x => x.Parent == null);
}

When to use async false and async true in ajax function in jquery

ShowPopUpForToDoList: function (id, apprId, tab) {
    var snapShot = "isFromAlert";
    if (tab != "Request")
        snapShot = "isFromTodoList";
    $.ajax({
        type: "GET",
        url: common.GetRootUrl('ActionForm/SetParamForToDoList'),
        data: { id: id, tab: tab },
        async:false,
        success: function (data) {
            ActionForm.EditActionFormPopup(id, snapShot);
        }
    });
},

Here SetParamForToDoList will be excecuted first after the function ActionForm.EditActionFormPopup will fire.

How do I get a value of datetime.today() in Python that is "timezone aware"?

If you get current time and date in python then import date and time,pytz package in python after you will get current date and time like as..

from datetime import datetime
import pytz
import time
str(datetime.strftime(datetime.now(pytz.utc),"%Y-%m-%d %H:%M:%S%t"))

Recursively find files with a specific extension

Using bash globbing (if find is not a must)

ls Robert.{pdf,jpg} 

Disabling browser caching for all browsers from ASP.NET

I'm going to test adding the no-store tag to our site to see if this makes a difference to browser caching (Chrome has sometimes been caching the pages). I also found this article very useful on documentation on how and why caching works and will look at ETag's next if the no-store is not reliable:

http://www.mnot.net/cache_docs/

http://en.wikipedia.org/wiki/HTTP_ETag

SQL Server 2008 - Help writing simple INSERT Trigger

check this code:

CREATE TRIGGER trig_Update_Employee ON [EmployeeResult] FOR INSERT AS Begin   
    Insert into Employee (Name, Department)  
    Select Distinct i.Name, i.Department   
        from Inserted i
        Left Join Employee e on i.Name = e.Name and i.Department = e.Department
        where e.Name is null
End

Git commit date

if you got troubles with windows cmd command and .bat just escape percents like that

git show -s --format=%%ct

The % character has a special meaning for command line parameters and FOR parameters. To treat a percent as a regular character, double it: %%

Syntax : Escape Characters, Delimiters and Quotes

Add property to an array of objects

  Object.defineProperty(Results, "Active", {value : 'true',
                       writable : true,
                       enumerable : true,
                       configurable : true});

Download file from an ASP.NET Web API method using AngularJS

In your component i.e angular js code:

function getthefile (){
window.location.href='http://localhost:1036/CourseRegConfirm/getfile';
};

Reading local text file into a JavaScript array

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

SQL Server : SUM() of multiple rows including where clauses

Try this:

SELECT
   PropertyId,
   SUM(Amount) as TOTAL_COSTS
FROM
   MyTable
WHERE
   EndDate IS NULL
GROUP BY
   PropertyId

What is monkey patching?

Monkey patching can only be done in dynamic languages, of which python is a good example. Changing a method at runtime instead of updating the object definition is one example;similarly, adding attributes (whether methods or variables) at runtime is considered monkey patching. These are often done when working with modules you don't have the source for, such that the object definitions can't be easily changed.

This is considered bad because it means that an object's definition does not completely or accurately describe how it actually behaves.

Node.js spawn child process and get terminal output live

It's much easier now (6 years later)!

Spawn returns a childObject, which you can then listen for events with. The events are:

  • Class: ChildProcess
    • Event: 'error'
    • Event: 'exit'
    • Event: 'close'
    • Event: 'disconnect'
    • Event: 'message'

There are also a bunch of objects from childObject, they are:

  • Class: ChildProcess
    • child.stdin
    • child.stdout
    • child.stderr
    • child.stdio
    • child.pid
    • child.connected
    • child.kill([signal])
    • child.send(message[, sendHandle][, callback])
    • child.disconnect()

See more information here about childObject: https://nodejs.org/api/child_process.html

Asynchronous

If you want to run your process in the background while node is still able to continue to execute, use the asynchronous method. You can still choose to perform actions after your process completes, and when the process has any output (for example if you want to send a script's output to the client).

child_process.spawn(...); (Node v0.1.90)

var spawn = require('child_process').spawn;
var child = spawn('node ./commands/server.js');

// You can also use a variable to save the output 
// for when the script closes later
var scriptOutput = "";

child.stdout.setEncoding('utf8');
child.stdout.on('data', function(data) {
    //Here is where the output goes

    console.log('stdout: ' + data);

    data=data.toString();
    scriptOutput+=data;
});

child.stderr.setEncoding('utf8');
child.stderr.on('data', function(data) {
    //Here is where the error output goes

    console.log('stderr: ' + data);

    data=data.toString();
    scriptOutput+=data;
});

child.on('close', function(code) {
    //Here you can get the exit code of the script

    console.log('closing code: ' + code);

    console.log('Full output of script: ',scriptOutput);
});

Here's how you would use a callback + asynchronous method:

var child_process = require('child_process');

console.log("Node Version: ", process.version);

run_script("ls", ["-l", "/home"], function(output, exit_code) {
    console.log("Process Finished.");
    console.log('closing code: ' + exit_code);
    console.log('Full output of script: ',output);
});

console.log ("Continuing to do node things while the process runs at the same time...");

// This function will output the lines from the script 
// AS is runs, AND will return the full combined output
// as well as exit code when it's done (using the callback).
function run_script(command, args, callback) {
    console.log("Starting Process.");
    var child = child_process.spawn(command, args);

    var scriptOutput = "";

    child.stdout.setEncoding('utf8');
    child.stdout.on('data', function(data) {
        console.log('stdout: ' + data);

        data=data.toString();
        scriptOutput+=data;
    });

    child.stderr.setEncoding('utf8');
    child.stderr.on('data', function(data) {
        console.log('stderr: ' + data);

        data=data.toString();
        scriptOutput+=data;
    });

    child.on('close', function(code) {
        callback(scriptOutput,code);
    });
}

Using the method above, you can send every line of output from the script to the client (for example using Socket.io to send each line when you receive events on stdout or stderr).

Synchronous

If you want node to stop what it's doing and wait until the script completes, you can use the synchronous version:

child_process.spawnSync(...); (Node v0.11.12+)

Issues with this method:

  • If the script takes a while to complete, your server will hang for that amount of time!
  • The stdout will only be returned once the script has finished running. Because it's synchronous, it cannot continue until the current line has finished. Therefore it's unable to capture the 'stdout' event until the spawn line has finished.

How to use it:

var child_process = require('child_process');

var child = child_process.spawnSync("ls", ["-l", "/home"], { encoding : 'utf8' });
console.log("Process finished.");
if(child.error) {
    console.log("ERROR: ",child.error);
}
console.log("stdout: ",child.stdout);
console.log("stderr: ",child.stderr);
console.log("exist code: ",child.status);

How to use IntelliJ IDEA to find all unused code?

Just use Analyze | Inspect Code with appropriate inspection enabled (Unused declaration under Declaration redundancy group).

Using IntelliJ 11 CE you can now "Analyze | Run Inspection by Name ... | Unused declaration"

QByteArray to QString

You can use QTextCodec to convert the bytearray to a string:

QString DataAsString = QTextCodec::codecForMib(1015)->toUnicode(Data);

(1015 is UTF-16, 1014 UTF-16LE, 1013 UTF-16BE, 106 UTF-8)

From your example we can see that the string "test" is encoded as "t\0 e\0 s\0 t\0 \0 \0" in your encoding, i.e. every ascii character is followed by a \0-byte, or resp. every ascii character is encoded as 2 bytes. The only unicode encoding in which ascii letters are encoded in this way, are UTF-16 or UCS-2 (which is a restricted version of UTF-16), so in your case the 1015 mib is needed (assuming your local endianess is the same as the input endianess).

Convert array values from string to int?

Another technique is to type-hint (coerce) the incoming values to int type after exploding the string.

Note that these techniques will work as demonstrated in my demo link unless you have set php to use strict typing.

The following techniques should not be used to sanitize non-numeric strings; it assumes that all values will be numeric.

If float values are passed into these techniques, they will be truncated/floored to integers.

Code: (Demo)

$string = "1,2,3";
$array = explode(',', $string);
var_dump($array);

echo "\n---\n";
array_walk($array, function(int &$int){;});
var_dump($array);

echo "\n---\n";
var_dump(
    array_map(function(int $i){ return $i; }, explode(',', $string))
);

echo "\n---\n";
var_dump(
    array_map(fn(int $i) => $i, explode(',', $string)) // PHP 7.4 arrow function syntax
);

Output:

array(3) {
  [0]=> string(1) "1"
  [1]=> string(1) "2"
  [2]=> string(1) "3"
}

---
array(3) {
  [0]=> int(1)
  [1]=> int(2)
  [2]=> int(3)
}

---
array(3) {
  [0]=> int(1)
  [1]=> int(2)
  [2]=> int(3)
}

---
array(3) {
  [0]=> int(1)
  [1]=> int(2)
  [2]=> int(3)
}

How To fix white screen on app Start up?

you should disable Instant Run android studio Settings.

File>Settings>Build,Execution, Deployment>Instant Run unCheck all options shown there.

Note: White screen Issue due to Instant Run is only for Debug builds,this Issue will not appear on release builds.

Convert array into csv

I'm using the following function for that; it's an adaptation from one of the man entries in the fputscsv comments. And you'll probably want to flatten that array; not sure what happens if you pass in a multi-dimensional one.

/**
  * Formats a line (passed as a fields  array) as CSV and returns the CSV as a string.
  * Adapted from http://us3.php.net/manual/en/function.fputcsv.php#87120
  */
function arrayToCsv( array &$fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
    $delimiter_esc = preg_quote($delimiter, '/');
    $enclosure_esc = preg_quote($enclosure, '/');

    $output = array();
    foreach ( $fields as $field ) {
        if ($field === null && $nullToMysqlNull) {
            $output[] = 'NULL';
            continue;
        }

        // Enclose fields containing $delimiter, $enclosure or whitespace
        if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
            $output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
        }
        else {
            $output[] = $field;
        }
    }

    return implode( $delimiter, $output );
}

EditText underline below text property

change your colorAccent which color you need that color set on colorAccent and run you get the output

Understanding typedefs for function pointers in C

A very easy way to understand typedef of function pointer:

int add(int a, int b)
{
    return (a+b);
}

typedef int (*add_integer)(int, int); //declaration of function pointer

int main()
{
    add_integer addition = add; //typedef assigns a new variable i.e. "addition" to original function "add"
    int c = addition(11, 11);   //calling function via new variable
    printf("%d",c);
    return 0;
}

Data truncated for column?

By issuing this statement:

ALTER TABLES call MODIFY incoming_Cid CHAR;

... you omitted the length parameter. Your query was therefore equivalent to:

ALTER TABLE calls MODIFY incoming_Cid CHAR(1);

You must specify the field size for sizes larger than 1:

ALTER TABLE calls MODIFY incoming_Cid CHAR(34);

Generating sql insert into for Oracle

You can do that in PL/SQL Developer v10.
1. Click on Table that you want to generate script for.
2. Click Export data.
3. Check if table is selected that you want to export data for.
4. Click on SQL inserts tab.
5. Add where clause if you don't need the whole table.
6. Select file where you will find your SQL script.
7. Click export.
enter image description here

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

React - uncaught TypeError: Cannot read property 'setState' of undefined

This is due to this.delta not being bound to this.

In order to bind set this.delta = this.delta.bind(this) in the constructor:

constructor(props) {
    super(props);

    this.state = {
        count : 1
    };

    this.delta = this.delta.bind(this);
}

Currently, you are calling bind. But bind returns a bound function. You need to set the function to its bound value.

Get last 30 day records from today date in SQL Server

I dont know why all these complicated answers are on here but this is what I would do

where pdate >= CURRENT_TIMESTAMP -30

OR WHERE CAST(PDATE AS DATE) >= GETDATE() -30

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

Most of the answers provided here address the number of incoming requests to your backend webservice, not the number of outgoing requests you can make from your ASP.net application to your backend service.

It's not your backend webservice that is throttling your request rate here, it is the number of open connections your calling application is willing to establish to the same endpoint (same URL).

You can remove this limitation by adding the following configuration section to your machine.config file:

<configuration>
  <system.net>
    <connectionManagement>
      <add address="*" maxconnection="65535"/>
    </connectionManagement>
  </system.net>
</configuration>

You could of course pick a more reasonable number if you'd like such as 50 or 100 concurrent connections. But the above will open it right up to max. You can also specify a specific address for the open limit rule above rather than the '*' which indicates all addresses.

MSDN Documentation for System.Net.connectionManagement

Another Great Resource for understanding ConnectManagement in .NET

Hope this solves your problem!

EDIT: Oops, I do see you have the connection management mentioned in your code above. I will leave my above info as it is relevant for future enquirers with the same problem. However, please note there are currently 4 different machine.config files on most up to date servers!

There is .NET Framework v2 running under both 32-bit and 64-bit as well as .NET Framework v4 also running under both 32-bit and 64-bit. Depending on your chosen settings for your application pool you could be using any one of these 4 different machine.config files! Please check all 4 machine.config files typically located here:

  • C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG
  • C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG
  • C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config
  • C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config

How to fix getImageData() error The canvas has been tainted by cross-origin data?

I meet the same problem today, and solve it by the code follows.

html code:

<div style='display: none'>
  <img id='img' src='img/iak.png' width='600' height='400' />
</div>
<canvas id='iak'>broswer don't support canvas</canvas>

js code:

var canvas = document.getElementById('iak')
var iakImg = document.getElementById('img')
var ctx = canvas.getContext('2d')
var image = new Image()
image.src=iakImg.src
image.onload = function () {
   ctx.drawImage(image,0,0)
   var data = ctx.getImageData(0,0,600,400)
}

code like above, and there is no cross-domain problem.

Using HTML5/Canvas/JavaScript to take in-browser screenshots

Heres an example using: getDisplayMedia

document.body.innerHTML = '<video style="width: 100%; height: 100%; border: 1px black solid;"/>';

navigator.mediaDevices.getDisplayMedia()
.then( mediaStream => {
  const video = document.querySelector('video');
  video.srcObject = mediaStream;
  video.onloadedmetadata = e => {
    video.play();
    video.pause();
  };
})
.catch( err => console.log(`${err.name}: ${err.message}`));

Also worth checking out is the Screen Capture API docs.

Android Shared preferences for creating one time activity (example)

public class Preferences {

public static final String PREF_NAME = "your preferences name";

@SuppressWarnings("deprecation")
public static final int MODE = Context.MODE_WORLD_WRITEABLE;

public static final String USER_ID = "USER_ID_NEW";
public static final String USER_NAME = "USER_NAME";

public static final String NAME = "NAME";
public static final String EMAIL = "EMAIL";
public static final String PHONE = "PHONE";
public static final String address = "address";

public static void writeBoolean(Context context, String key, boolean value) {
    getEditor(context).putBoolean(key, value).commit();
}

public static boolean readBoolean(Context context, String key,
        boolean defValue) {
    return getPreferences(context).getBoolean(key, defValue);
}

public static void writeInteger(Context context, String key, int value) {
    getEditor(context).putInt(key, value).commit();

}

public static int readInteger(Context context, String key, int defValue) {
    return getPreferences(context).getInt(key, defValue);
}

public static void writeString(Context context, String key, String value) {
    getEditor(context).putString(key, value).commit();

}

public static String readString(Context context, String key, String defValue) {
    return getPreferences(context).getString(key, defValue);
}

public static void writeFloat(Context context, String key, float value) {
    getEditor(context).putFloat(key, value).commit();
}

public static float readFloat(Context context, String key, float defValue) {
    return getPreferences(context).getFloat(key, defValue);
}

public static void writeLong(Context context, String key, long value) {
    getEditor(context).putLong(key, value).commit();
}

public static long readLong(Context context, String key, long defValue) {
    return getPreferences(context).getLong(key, defValue);
}

public static SharedPreferences getPreferences(Context context) {
    return context.getSharedPreferences(PREF_NAME, MODE);
}

public static Editor getEditor(Context context) {
    return getPreferences(context).edit();
}

}

****Use Preferences to Write value using:-****

Preferences.writeString(getApplicationContext(),
                    Preferences.NAME, "dev");

****Use Preferences to Read value using:-****

Preferences.readString(getApplicationContext(), Preferences.NAME,
                    "");

Read only file system on Android

I found this article from google, and thought I'd add the steps necessary on a Sony Xperia Z (4.2.2).

The Sony has a watchdog process which detects when you've changed ro to rw on / and /system (these are the only ones I was trying to modify) and possibly others.

The following was what I ran to perform the changes I was trying to achieve. I pasted these into a window, because removing the execute bit from /sbin/ric needs to be done quickly in order to stop it restarting itself. (I tried stop ric; this doesn't work - although it worked on a previous version of android on the phone).

pkill -9 ric; mount -o rw,remount -t rootfs /
chmod 640 /sbin/ric
mount -o rw,remount /system

I modified the hosts file here, so this is the place you make the changes you need to the filesystem. To leave things the way we found them, do this:

mount -o ro,remount /system
chmod 750 /sbin/ric
mount -o ro,remount -t rootfs /

At which point ric should automatically restart. (It restarted for me automatically.)

Vue template or render function not defined yet I am using neither?

As a Summary of all the posts

This error:

[Vue warn]: Failed to mount component: template or render function not defined.

You're getting because of a certain problem that's preventing your component from being mounted.

This can be caused by a lot of different issues, as you can see from the different posts here. Debug your component thoroughly, and be aware of everything that is maybe not done correctly and might prevent the mount.

I was getting the error when my component file was not encoded correctly...

SQL Server SELECT into existing table

SELECT ... INTO ... only works if the table specified in the INTO clause does not exist - otherwise, you have to use:

INSERT INTO dbo.TABLETWO
SELECT col1, col2
  FROM dbo.TABLEONE
 WHERE col3 LIKE @search_key

This assumes there's only two columns in dbo.TABLETWO - you need to specify the columns otherwise:

INSERT INTO dbo.TABLETWO
  (col1, col2)
SELECT col1, col2
  FROM dbo.TABLEONE
 WHERE col3 LIKE @search_key

AngularJS : Custom filters and ng-repeat

If you still want a custom filter you can pass in the search model to the filter:

<article data-ng-repeat="result in results | cartypefilter:search" class="result">

Where definition for the cartypefilter can look like this:

app.filter('cartypefilter', function() {
  return function(items, search) {
    if (!search) {
      return items;
    }

    var carType = search.carType;
    if (!carType || '' === carType) {
      return items;
    }

    return items.filter(function(element, index, array) {
      return element.carType.name === search.carType;
    });

  };
});

http://plnkr.co/edit/kBcUIayO8tQsTTjTA2vO?p=preview

My Routes are Returning a 404, How can I Fix Them?

  1. setup .env file
  2. configure index.html
  3. make sure u have .htaccess
  4. sudo service apache2 restart

most probably it's due to cache problems

Bash: If/Else statement in one line

There is no need to explicitly check $?. Just do:

ps aux | grep some_proces[s] > /tmp/test.txt && echo 1 || echo 0 

Note that this relies on echo not failing, which is certainly not guaranteed. A more reliable way to write this is:

if ps aux | grep some_proces[s] > /tmp/test.txt; then echo 1; else echo 0; fi

Avoid trailing zeroes in printf()

What about something like this (might have rounding errors and negative-value issues that need debugging, left as an exercise for the reader):

printf("%.0d%.4g\n", (int)f/10, f-((int)f-(int)f%10));

It's slightly programmatic but at least it doesn't make you do any string manipulation.

Stylesheet not loaded because of MIME-type

As mentioned solutions in this post, some of the solutions worked for me, but CSS does not apply on the page.

Simply, I just moved the "css" directory into the "Assest/" directory and everything works fine.

<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="assets/css/site.css" >

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

I just found my own solution to this problem, or at least my problem.
I was using justify-content: space-around instead of justify-content: space-between;.

This way the end elements will stick to the top and bottom, and you could have custom margins if you wanted.

Chrome violation : [Violation] Handler took 83ms of runtime

It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.

4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.

If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.

How to remove CocoaPods from a project?

pod deintegrate

After this cmd, no traces of Cocoapods left in your project.

But your workspace referencing the Pods project still remains, you need to should remove below 3 files manually:

xx.xcworkspace
Podifle
Podfile.lock

Then you can use your project again.

Have fun!

Test CocoaPod version = 1.2.0

Rails: Why "sudo" command is not recognized?

Sudo is a Unix specific command designed to allow a user to carry out administrative tasks with the appropriate permissions.

Windows does not have (need?) this.

Run the command with the sudo removed from the start.

100% Min Height CSS layout

First you should create a div with id='footer' after your content div and then simply do this.

Your HTML should look like this:

<html>
    <body>
        <div id="content">
            ...
        </div>
        <div id="footer"></div>
    </body>
</html>

And the CSS:

?html, body {
    height: 100%;   
}
#content {
    height: 100%;
}
#footer {
    clear: both;        
}

How do I make HttpURLConnection use a proxy?

For Java 1.8 and higher you must set -Djdk.http.auth.tunneling.disabledSchemes= to make proxies with Basic Authorization working with https.

UIView Infinite 360 degree rotation animation?

In Swift, you can use the following code for infinite rotation:

Swift 4

extension UIView {
    private static let kRotationAnimationKey = "rotationanimationkey"

    func rotate(duration: Double = 1) {
        if layer.animation(forKey: UIView.kRotationAnimationKey) == nil {
            let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")

            rotationAnimation.fromValue = 0.0
            rotationAnimation.toValue = Float.pi * 2.0
            rotationAnimation.duration = duration
            rotationAnimation.repeatCount = Float.infinity

            layer.add(rotationAnimation, forKey: UIView.kRotationAnimationKey)
        }
    }

    func stopRotating() {
        if layer.animation(forKey: UIView.kRotationAnimationKey) != nil {
            layer.removeAnimation(forKey: UIView.kRotationAnimationKey)
        }
    }
}

Swift 3

let kRotationAnimationKey = "com.myapplication.rotationanimationkey" // Any key

func rotateView(view: UIView, duration: Double = 1) {
    if view.layer.animationForKey(kRotationAnimationKey) == nil {
        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")

        rotationAnimation.fromValue = 0.0
        rotationAnimation.toValue = Float(M_PI * 2.0)
        rotationAnimation.duration = duration
        rotationAnimation.repeatCount = Float.infinity

        view.layer.addAnimation(rotationAnimation, forKey: kRotationAnimationKey)
    }
}

Stopping is like:

func stopRotatingView(view: UIView) {
    if view.layer.animationForKey(kRotationAnimationKey) != nil {
        view.layer.removeAnimationForKey(kRotationAnimationKey)
    }
}

adding .css file to ejs

You can use this

     var fs = require('fs');
     var myCss = {
         style : fs.readFileSync('./style.css','utf8');
     };

     app.get('/', function(req, res){
       res.render('index.ejs', {
       title: 'My Site',
       myCss: myCss
      });
     });

put this on template

   <%- myCss.style %>

just build style.css

  <style>
    body { 
     background-color: #D8D8D8;
     color: #444;
   }
  </style>

I try this for some custom css. It works for me

How do I read a specified line in a text file?

If each line is a fixed length then you can open a Stream around it, seek (bytes per line) * n into the file and read your line from there.

using( Stream stream = File.Open(fileName, FileMode.Open) )
{
    stream.Seek(bytesPerLine * (myLine - 1), SeekOrigin.Begin);
    using( StreamReader reader = new StreamReader(stream) )
    {
        string line = reader.ReadLine();
    }
}

Alternatively you could just use the StreamReader to read lines until you found the one you wanted. That way's slower but still an improvement over reading every single line.

using( Stream stream = File.Open(fileName, FileMode.Open) )
{
    using( StreamReader reader = new StreamReader(fileStream) )
    {
        string line = null;
        for( int i = 0; i < myLineNumber; ++i )
        {
            line = reader.ReadLine();
        }
    }
}

Return content with IHttpActionResult for non-OK response

@mayabelle you can create IHttpActionResult concrete and wrapped those code like this:

public class NotFoundPlainTextActionResult : IHttpActionResult
{
    public NotFoundPlainTextActionResult(HttpRequestMessage request, string message)
    {
        Request = request;
        Message = message;
    }

    public string Message { get; private set; }
    public HttpRequestMessage Request { get; private set; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(ExecuteResult());
    }

    public HttpResponseMessage ExecuteResult()
    {
        var response = new HttpResponseMessage();

        if (!string.IsNullOrWhiteSpace(Message))
            //response.Content = new StringContent(Message);
            response = Request.CreateErrorResponse(HttpStatusCode.NotFound, new Exception(Message));

        response.RequestMessage = Request;
        return response;
    }
}

When should I use nil and NULL in Objective-C?

This will help you to understand the difference between nil, NIL and null.

The below link may help you in some way:

http://nshipster.com/nil/

nil -> literal null value for Objective-C objects.

Nil -> literal null value for Objective-C classes.

NULL -> literal null value for C pointers.

NSNULL -> singleton object used to represent null.

Permanently hide Navigation Bar in an activity

From Google documentation:

You can hide the navigation bar on Android 4.0 and higher using the SYSTEM_UI_FLAG_HIDE_NAVIGATION flag. This snippet hides both the navigation bar and the status bar:

View decorView = getWindow().getDecorView();
// Hide both the navigation bar and the status bar.
// SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
// a general rule, you should design your app to hide the status bar whenever you
// hide the navigation bar.
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
              | View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);

http://developer.android.com/training/system-ui/navigation.html

Getting a random value from a JavaScript array

Recursive, standalone function which can return any number of items (identical to lodash.sampleSize):

function getRandomElementsFromArray(array, numberOfRandomElementsToExtract = 1) {
    const elements = [];

    function getRandomElement(arr) {
        if (elements.length < numberOfRandomElementsToExtract) {
            const index = Math.floor(Math.random() * arr.length)
            const element = arr.splice(index, 1)[0];

            elements.push(element)

            return getRandomElement(arr)
        } else {
            return elements
        }
    }

    return getRandomElement([...array])
}

How to change the style of a DatePicker in android?

Calendar calendar = Calendar.getInstance();

DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), R.style.DatePickerDialogTheme, new DatePickerDialog.OnDateSetListener() {
  public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    Calendar newDate = Calendar.getInstance();
    newDate.set(year, monthOfYear, dayOfMonth);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
    String date = simpleDateFormat.format(newDate.getTime());
  }
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));

datePickerDialog.show();

And use this style:

<style name="DatePickerDialogTheme" parent="Theme.AppCompat.Light.Dialog">
  <item name="colorAccent">@color/colorPrimary</item>
</style>

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

Easy done:

(?<=\[)(.*?)(?=\])

Technically that's using lookaheads and lookbehinds. See Lookahead and Lookbehind Zero-Width Assertions. The pattern consists of:

  • is preceded by a [ that is not captured (lookbehind);
  • a non-greedy captured group. It's non-greedy to stop at the first ]; and
  • is followed by a ] that is not captured (lookahead).

Alternatively you can just capture what's between the square brackets:

\[(.*?)\]

and return the first captured group instead of the entire match.

How to disable registration new users in Laravel

LAravel 5.6

Auth::routes([
    'register' => false, // Registration Routes...
    'reset' => false, // Password Reset Routes...
    'verify' => false, // Email Verification Routes...
]);

Ruby on Rails: How do I add placeholder text to a f.text_field?

In your view template, set a default value:

f.text_field :password, :value => "password"

In your Javascript (assuming jquery here):

$(document).ready(function() {
  //add a handler to remove the text
});

Shortest way to print current year in a website

Here's the ultimate shortest most responsible version that even works both AD and BC.

[drum rolls...]

<script>document.write(Date().split` `[3])</script>

That's it. 6 Bytes shorter than the accepted answer.

If you need to be ES5 compatible, you can settle for:

<script>document.write(Date().split(' ')[3])</script>

Split string into list in jinja?

After coming back to my own question after 5 year and seeing so many people found this useful, a little update.

A string variable can be split into a list by using the split function (it can contain similar values, set is for the assignment) . I haven't found this function in the official documentation but it works similar to normal Python. The items can be called via an index, used in a loop or like Dave suggested if you know the values, it can set variables like a tuple.

{% set list1 = variable1.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}

or

{% set list1 = variable1.split(';') %}
{% for item in list1 %}
    <p>{{ item }}<p/>
{% endfor %} 

or

{% set item1, item2 = variable1.split(';') %}
The grass is {{ item1 }} and the boat is {{ item2 }}

Using 24 hour time in bootstrap timepicker

To pick only time with 24 hr time format, use

$('#datetimepicker').datetimepicker({
            format: 'HH:mm'
 });

If you want to pick 24 hr time format with date also, use

$('#datetimepicker').datetimepicker({
         format: 'MM/DD/YYYY HH:mm'
 });

Example :

_x000D_
_x000D_
$(function() {_x000D_
  $('#datetimepicker1').datetimepicker({_x000D_
            format: 'HH:mm'_x000D_
  });_x000D_
  _x000D_
  $('#datetimepicker2').datetimepicker({_x000D_
            format: 'MM/DD/YYYY HH:mm'_x000D_
  });_x000D_
  $('#datetimepicker3').datetimepicker({_x000D_
      format: 'hh:mm A',_x000D_
  });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>_x000D_
_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css">_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class='col-sm-6'>_x000D_
      <div class="form-group">_x000D_
        <span>Select 24 hour time format</span>_x000D_
        <div class='input-group date' id='datetimepicker1'>_x000D_
          <input type='text' class="form-control" />_x000D_
          <span class="input-group-addon">_x000D_
            <span class="glyphicon glyphicon-calendar"></span>_x000D_
          </span>_x000D_
        </div>_x000D_
        <br/>_x000D_
        <span>Select time with Date</span>_x000D_
        <div class='input-group date' id='datetimepicker2'>_x000D_
          <input type='text' class="form-control" />_x000D_
          <span class="input-group-addon">_x000D_
            <span class="glyphicon glyphicon-calendar"></span>_x000D_
          </span>_x000D_
        </div>_x000D_
        <br/>_x000D_
        <span>Select 12 hour time format</span>_x000D_
        <div class='input-group date' id='datetimepicker3'>_x000D_
          <input type='text' class="form-control" />_x000D_
          <span class="input-group-addon">_x000D_
            <span class="glyphicon glyphicon-calendar"></span>_x000D_
          </span>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

For more info

Run a vbscript from another vbscript

I saw the below code working. Simple, but I guess not documented. Anyone else used the 'Execute' command ?

   Dim body, my_script_file
   Set Fso = CreateObject("Scripting.FileSystemObject")


   Set my_script_file = fso.OpenTextFile(FILE)
   body = my_script_file.ReadAll
    my_script_file.Close

    Execute body

Where do I put image files, css, js, etc. in Codeigniter?

you can put the css folder inside the assest folder(you name it any name) in the directory of your project as:

- ci_app
- application 
- views      
- assets 
  - css 
    - style.css 

... when you want to load that file in a page, you can use base_url()function as this way: <head> <link rel='stylesheet' href='<?php echo base_url();?>assets/css/style.css'> </head> and you are sure to add base_url of your project in the config.php file as this:

$config['base_url'] = 'http://localhost/ci_app';

Remove all elements contained in another array

How about the simplest possible:

_x000D_
_x000D_
var myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];_x000D_
var toRemove = ['b', 'c', 'g'];_x000D_
_x000D_
var myArray = myArray.filter((item) => !toRemove.includes(item));_x000D_
console.log(myArray)
_x000D_
_x000D_
_x000D_

Adding and removing extensionattribute to AD object

Or the -Remove parameter

Set-ADUser -Identity anyUser -Remove @{extensionAttribute4="myString"}

Do I need a content-type header for HTTP GET requests?

The accepted answer is wrong. The quote is correct, the assertion that PUT and POST must have it is incorrect. There is no requirement that PUT or POST actually have additional content. Nor is there a prohibition against GET actually having content.

The RFCs say exactly what they mean .. IFF your side (client OR origin server) will be sending additional content, beyond the HTTP headers, it SHOULD specify a Content-Type header. But note it is allowable to omit the Content-Type and still include content (say, by using a Content-Length header).

Ansible: get current target host's IP address

Simple debug command:

ansible -i inventory/hosts.yaml -m debug -a "var=hostvars[inventory_hostname]" all

output:

"hostvars[inventory_hostname]": {
    "ansible_check_mode": false, 
    "ansible_diff_mode": false, 
    "ansible_facts": {}, 
    "ansible_forks": 5, 
    "ansible_host": "192.168.10.125", 
    "ansible_inventory_sources": [
        "/root/workspace/ansible-minicros/inventory/hosts.yaml"
    ], 
    "ansible_playbook_python": "/usr/bin/python2", 
    "ansible_port": 65532, 
    "ansible_verbosity": 0, 
    "ansible_version": {
        "full": "2.8.5", 
        "major": 2, 
        "minor": 8, 
        "revision": 5, 
        "string": "2.8.5"
    }, 

get host ip address:

ansible -i inventory/hosts.yaml -m debug -a "var=hostvars[inventory_hostname].ansible_host" all

zk01 | SUCCESS => {
    "hostvars[inventory_hostname].ansible_host": "192.168.10.125"
}

How to round up value C# to the nearest integer?

Use Math.Ceiling to round up

Math.Ceiling(0.5); // 1

Use Math.Round to just round

Math.Round(0.5, MidpointRounding.AwayFromZero); // 1

And Math.Floor to round down

Math.Floor(0.5); // 0

Unique Key constraints for multiple columns in Entity Framework

Recently added a composite key with the uniqueness of 2 columns using the approach that 'chuck' recommended, thank @chuck. Only this approached looked cleaner to me:

public int groupId {get; set;}

[Index("IX_ClientGrouping", 1, IsUnique = true)]
public int ClientId { get; set; }

[Index("IX_ClientGrouping", 2, IsUnique = true)]
public int GroupName { get; set; }

Adding blur effect to background in swift

You should always use .dark for style and add the following code to make it look cool

    blurEffectView.backgroundColor = .black
    blurEffectView.alpha = 0.4

How to write lists inside a markdown table?

another solution , you can add <br> tag to your table

    |Method name| Behavior |
    |--|--|
    | OnAwakeLogicController(); | Its called when MainLogicController is loaded into the memory , its also hold the following actions :- <br> 1. Checking Audio Settings <br>2. Initializing Level Controller|

enter image description here

Random word generator- Python

There are a number of dictionary files available online - if you're on linux, a lot of (all?) distros come with an /etc/dictionaries-common/words file, which you can easily parse (words = open('/etc/dictionaries-common/words').readlines(), eg) for use.

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

In the %run magic documentation you can find:

-i run the file in IPython’s namespace instead of an empty one. This is useful if you are experimenting with code written in a text editor which depends on variables defined interactively.

Therefore, supplying -i does the trick:

%run -i 'script.py'

The "correct" way to do it

Maybe the command above is just what you need, but with all the attention this question gets, I decided to add a few more cents to it for those who don't know how a more pythonic way would look like.
The solution above is a little hacky, and makes the code in the other file confusing (Where does this x variable come from? and what is the f function?).

I'd like to show you how to do it without actually having to execute the other file over and over again.
Just turn it into a module with its own functions and classes and then import it from your Jupyter notebook or console. This also has the advantage of making it easily reusable and jupyters contextassistant can help you with autocompletion or show you the docstring if you wrote one.
If you're constantly editing the other file, then autoreload comes to your help.

Your example would look like this:
script.py

import matplotlib.pyplot as plt

def myplot(f, x):
    """
    :param f: function to plot
    :type f: callable
    :param x: values for x
    :type x: list or ndarray

    Plots the function f(x).
    """
    # yes, you can pass functions around as if
    # they were ordinary variables (they are)
    plt.plot(x, f(x))
    plt.xlabel("Eje $x$",fontsize=16)
    plt.ylabel("$f(x)$",fontsize=16)
    plt.title("Funcion $f(x)$")

Jupyter console

In [1]: import numpy as np

In [2]: %load_ext autoreload

In [3]: %autoreload 1

In [4]: %aimport script

In [5]: def f(x):
      :     return np.exp(-x ** 2)
      :
      :

In [6]: x = np.linspace(-1, 3, 100)

In [7]: script.myplot(f, x)

In [8]: ?script.myplot
Signature: script.myplot(f, x)
Docstring:
:param f: function to plot
:type f: callable
:param x: x values
:type x: list or ndarray
File:      [...]\script.py
Type:      function

Center text in div?

Add to the selector containing the text

margin:auto;

Format y axis as percent

For those who are looking for the quick one-liner:

plt.gca().set_yticklabels(['{:.0f}%'.format(x*100) for x in plt.gca().get_yticks()]) 

Or if you are using Latex as the axis text formatter, you have to add one backslash '\'

plt.gca().set_yticklabels(['{:.0f}\%'.format(x*100) for x in plt.gca().get_yticks()]) 

Using the AND and NOT Operator in Python

You should write :

if (self.a != 0) and (self.b != 0) :

"&" is the bit wise operator and does not suit for boolean operations. The equivalent of "&&" is "and" in Python.

A shorter way to check what you want is to use the "in" operator :

if 0 not in (self.a, self.b) :

You can check if anything is part of a an iterable with "in", it works for :

  • Tuples. I.E : "foo" in ("foo", 1, c, etc) will return true
  • Lists. I.E : "foo" in ["foo", 1, c, etc] will return true
  • Strings. I.E : "a" in "ago" will return true
  • Dict. I.E : "foo" in {"foo" : "bar"} will return true

As an answer to the comments :

Yes, using "in" is slower since you are creating an Tuple object, but really performances are not an issue here, plus readability matters a lot in Python.

For the triangle check, it's easier to read :

0 not in (self.a, self.b, self.c)

Than

(self.a != 0) and (self.b != 0) and (self.c != 0) 

It's easier to refactor too.

Of course, in this example, it really is not that important, it's very simple snippet. But this style leads to a Pythonic code, which leads to a happier programmer (and losing weight, improving sex life, etc.) on big programs.

Spring RestTemplate GET with parameters

If your url is http://localhost:8080/context path?msisdn={msisdn}&email={email}

then

Map<String,Object> queryParams=new HashMap<>();
queryParams.put("msisdn",your value)
queryParams.put("email",your value)

works for resttemplate exchange method as described by you

How to install Anaconda on RaspBerry Pi 3 Model B

On Raspberry Pi 3 Model B - Installation of Miniconda (bundled with Python 3)

Go and get the latest version of miniconda for Raspberry Pi - made for armv7l processor and bundled with Python 3 (eg.: uname -m)

wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
md5sum Miniconda3-latest-Linux-armv7l.sh
bash Miniconda3-latest-Linux-armv7l.sh

After installation, source your updated .bashrc file with source ~/.bashrc. Then enter the command python --version, which should give you:

Python 3.4.3 :: Continuum Analytics, Inc.

How to determine the screen width in terms of dp or dip at runtime in Android?

Simplified for Kotlin:

val widthDp = resources.displayMetrics.run { widthPixels / density }
val heightDp = resources.displayMetrics.run { heightPixels / density }

How to merge specific files from Git branches

I am in same situation, I want to merge a file from a branch which has many commits on it on 2 branch. I tried many ways above and other I found on the internet and all failed (because commit history is complex) so I decide to do my way (the crazy way).

git merge <other-branch>
cp file-to-merge file-to-merge.example
git reset --hard HEAD (or HEAD^1 if no conflicts happen)
cp file-to-merge.example file-to-merge

Is it possible to run an .exe or .bat file on 'onclick' in HTML

No, that would be a huge security breach. Imagine if someone could run

format c:

whenever you visted their website.

clearing select using jquery

use .empty()

 $('select').empty().append('whatever');

you can also use .html() but note

When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Consider the following HTML:

alternative: --- If you want only option elements to-be-remove, use .remove()

$('select option').remove();

Set scroll position

You can use window.scrollTo(), like this:

window.scrollTo(0, 0); // values are x,y-offset

Include another JSP file

1.<a href="index.jsp?p=products">Products</a> when user clicks on Products link,you can directly call products.jsp.

I mean u can maintain name of the JSP file same as parameter Value.

<%
 if(request.getParameter("p")!=null)
 { 
   String contextPath="includes/";
   String p = request.getParameter("p");
   p=p+".jsp";
   p=contextPath+p;

%>    

<%@include file="<%=p%>" %>

<% 
 }
%>

or

2.you can maintain external resource file with key,value pairs. like below

products : products.jsp

customer : customers.jsp

you can programatically retrieve the name of JSP file from properies file.

this way you can easily change the name of JSP file

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

This problem was caused for me by this error which appeared just prior in the application error log.

"A read operation on a large object failed while sending data to the client. A common cause for this is if the application is running in READ UNCOMMITTED isolation level. This connection will be terminated."

I was storing PDFs in a SQL table and when attempting to SELECT from that table it spit out that error, which resulted in the error mentioned in your question.

The solution was to delete the columns that had large amounts of text, in my case Base64 encoded files.

Remove all unused resources from an android project

Since ADT 16 you can use Android Lint. It is really amazing tool.

Android Lint is a new tool for ADT 16 (and Tools 16) which scans Android project sources for potential bugs.

Here are some examples of the types of errors that it looks for:

  • Missing translations (and unused translations)
  • Layout performance problems (all the issues the old layoutopt tool used to find, and more)
  • Unused resources
  • Inconsistent array sizes (when arrays are defined in multiple configurations)
  • Accessibility and internationalization problems (hardcoded strings, missing contentDescription, etc)
  • Icon problems (like missing densities, duplicate icons, wrong sizes, etc)
  • Usability problems (like not specifying an input type on a text field)
  • Manifest errors and many more.

However, it has some issues (don't know if they're already fixed) and if you want to delete hundreds of supposedly unused resources I'd recommend to manually compile project several times during resource removing to be sure that Lint didn't remove something needed.

PHP Accessing Parent Class Variable

With parent::$bb; you try to retrieve the static constant defined with the value of $bb.

Instead, do:

echo $this->bb;

Note: you don't need to call parent::_construct if B is the only class that calls it. Simply don't declare __construct in B class.

WordPress: get author info from post id

I figured it out.

<?php $author_id=$post->post_author; ?>
<img src="<?php the_author_meta( 'avatar' , $author_id ); ?> " width="140" height="140" class="avatar" alt="<?php echo the_author_meta( 'display_name' , $author_id ); ?>" />
<?php the_author_meta( 'user_nicename' , $author_id ); ?> 

Continue For loop

For the case you do not use "DO": this is my solution for a FOR EACH with nested If conditional statements:

For Each line In lines
    If <1st condition> Then
        <code if 1st condition>
        If <2nd condition> Then
            If <3rd condition> Then
                GoTo ContinueForEach
            Else
                <code else 3rd condition>
            End If
        Else
            <code else 2nd condition>
        End If
    Else
        <code else 1st condition>
    End If
ContinueForEach:
Next

How to generate range of numbers from 0 to n in ES2015 only?

A lot of these solutions build on instantiating real Array objects, which can get the job done for a lot of cases but can't support cases like range(Infinity). You could use a simple generator to avoid these problems and support infinite sequences:

function* range( start, end, step = 1 ){
  if( end === undefined ) [end, start] = [start, 0];
  for( let n = start; n < end; n += step ) yield n;
}

Examples:

Array.from(range(10));     // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
Array.from(range(10, 20)); // [ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]

i = range(10, Infinity);
i.next(); // { value: 10, done: false }
i.next(); // { value: 11, done: false }
i.next(); // { value: 12, done: false }
i.next(); // { value: 13, done: false }
i.next(); // { value: 14, done: false }

Allow scroll but hide scrollbar

Try this:

HTML:

<div id="container">
    <div id="content">
        // Content here
    </div>
</div>

CSS:

#container{
    height: 100%;
    width: 100%;
    overflow: hidden;
}

#content{
    width: 100%;
    height: 99%;
    overflow: auto;
    padding-right: 15px;
}

html, body{
    height: 99%;
    overflow:hidden;
}

JSFiddle Demo

Tested on FF and Safari.

URL.Action() including route values

You also can use in this form:

<a href="@Url.Action("Information", "Admin", null)"> Admin</a>

Inserting an image with PHP and FPDF

Please note that you should not use any png when you are testing this , first work with jpg .

$myImage = "images/logos/mylogo.jpg";  // this is where you get your Image

$pdf->Image($myImage, 5, $pdf->GetY(), 33.78);

How to know the git username and email saved during configuration?

The command git config --list will list the settings. There you should also find user.name and user.email.

How to set timeout in Retrofit library?

For Retrofit1.9 with OkHttp3 users, here is the solution,

.setClient(new Ok3Client(new OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).build()))

Blade if(isset) is not working Laravel

@isset($usersType)
  // $usersType is defined and is not null...
@endisset

For a detailed explanation refer documentation:

In addition to the conditional directives already discussed, the @isset and @empty directives may be used as convenient shortcuts for their respective PHP functions

Validation for 10 digit mobile number and focus input field on invalid

you can also use jquery for this

  var phoneNumber = 8882070980;
            var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;

            if (filter.test(phoneNumber)) {
              if(phoneNumber.length==10){
                   var validate = true;
              } else {
                  alert('Please put 10  digit mobile number');
                  var validate = false;
              }
            }
            else {
              alert('Not a valid number');
              var validate = false;
            }

         if(validate){
          //number is equal to 10 digit or number is not string 
          enter code here...
        }

What is the difference between .yaml and .yml extension?

File extensions do not have any bearing or impact on the content of the file. You can hold YAML content in files with any extension: .yml, .yaml or indeed anything else.

The (rather sparse) YAML FAQ recommends that you use .yaml in preference to .yml, but for historic reasons many Windows programmers are still scared of using extensions with more than three characters and so opt to use .yml instead.

So, what really matters is what is inside the file, rather than what its extension is.

Textarea to resize based on content length

You can achieve this by using a span and a textarea.

You have to update the span with the text in textarea each time the text is changed. Then set the css width and height of the textarea to the span's clientWidth and clientHeight property.

Eg:

.textArea {
    border: #a9a9a9 1px solid;
    overflow: hidden;
    width:  expression( document.getElementById("spnHidden").clientWidth );
    height: expression( document.getElementById("spnHidden").clientHeight );
}

PHP str_replace replace spaces with underscores

I'll suggest that you use this as it will check for both single and multiple occurrence of white space (as suggested by Lucas Green).

$journalName = preg_replace('/\s+/', '_', $journalName);

instead of:

$journalName = str_replace(' ', '_', $journalName);

jQuery .ready in a dynamically inserted iframe

I answered a similar question (see Javascript callback when IFRAME is finished loading?). You can obtain control over the iframe load event with the following code:

function callIframe(url, callback) {
    $(document.body).append('<IFRAME id="myId" ...>');
    $('iframe#myId').attr('src', url);

    $('iframe#myId').load(function() {
        callback(this);
    });
}

In dealing with iframes I found good enough to use load event instead of document ready event.

In a javascript array, how do I get the last 5 elements, excluding the first element?

You can call:

arr.slice(Math.max(arr.length - 5, 1))

If you don't want to exclude the first element, use

arr.slice(Math.max(arr.length - 5, 0))

PHP class not found but it's included

As a more systematic and structured solution you could define folders where your classes are stored and create an autoloader (__autoload()) which will search the class files in defined places:

require_once("../settings.php");
define('DIR_CLASSES', '/path/to/the/classes/folder/'); // this can be inside your settings.php

$user = new User();
$user->createUser($_POST["username"], $_POST["email"], $_POST["password"]);

function __autoload($classname) { 
    if(file_exists(DIR_CLASSES . 'class' . $classname . '.php')) {
        include_once(DIR_CLASSES . 'class' . $classname . '.php'); // looking for the class in the project's classes folder
    } else {
        include_once($classname . '.php'); // looking for the class in include_path
    }
} 

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

This error can also be caused by the fact that Controllers must have (in their name) the word Controller; viz: HomeController; unless you implement your own ControllerFactory.

Escape dot in a regex range

If you using JavaScript to test your Regex, try \\. instead of \..

It acts on the same way because JS remove first backslash.

Case statement with multiple values in each 'when' block

Another nice way to put your logic in data is something like this:

# Initialization.
CAR_TYPES = {
  foo_type: ['honda', 'acura', 'mercedes'],
  bar_type: ['toyota', 'lexus']
  # More...
}
@type_for_name = {}
CAR_TYPES.each { |type, names| names.each { |name| @type_for_name[type] = name } }

case @type_for_name[car]
when :foo_type
  # do foo things
when :bar_type
  # do bar things
end