Programs & Examples On #Baseline

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

If you already have material-icons working in your web project, just need to update your reference in the html file and the used class for icons:

html reference:

Before

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />

After

<link href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp"
rel="stylesheet" />

material icons class:

After that just check wich className are you using:

Before:

<i className="material-icons">weekend</i>

After:

<i className="material-icons-outlined">weekend</i>

that works for me... Pura vida!

How to save final model using keras?

Saving a Keras model:

model = ...  # Get model (Sequential, Functional Model, or Model subclass)
model.save('path/to/location')

Loading the model back:

from tensorflow import keras
model = keras.models.load_model('path/to/location')

For more information, read Documentation

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

The best solution would be to do these steps :

  1. Delete the file called - V2__create_shipwreck.sql, clean and build the project again.
  2. Run the project again, login into h2 and delete the table called "schema_version".

    drop table schema_version;

  3. Now make V2__create_shipwreck.sql file with ddl and rerun the project again.

  4. Do remember this, add version 4.1.2 for flyway-core in pom.xml like

    <dependency>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-core</artifactId>
        <version>4.1.2</version>
    </dependency>
    

It should work now. Hope this will help.

How to use a Java8 lambda to sort a stream in reverse order?

If your stream elements implements Comparable then the solution becomes simpler:

 ...stream()
 .sorted(Comparator.reverseOrder())

How to include a font .ttf using CSS?

I know this is an old post but this solved my problem.

_x000D_
_x000D_
@font-face{_x000D_
  font-family: "Font Name";_x000D_
  src: url("../fonts/font-name.ttf") format("truetype");_x000D_
}
_x000D_
_x000D_
_x000D_

notice src:url("../fonts/font-name.ttf"); we use two periods to go back to the root directory and then into the fonts folder or wherever your file is located.

hope this helps someone down the line:) happy coding

get list of pandas dataframe columns based on data type

If you want a list of columns of a certain type, you can use groupby:

>>> df = pd.DataFrame([[1, 2.3456, 'c', 'd', 78]], columns=list("ABCDE"))
>>> df
   A       B  C  D   E
0  1  2.3456  c  d  78

[1 rows x 5 columns]
>>> df.dtypes
A      int64
B    float64
C     object
D     object
E      int64
dtype: object
>>> g = df.columns.to_series().groupby(df.dtypes).groups
>>> g
{dtype('int64'): ['A', 'E'], dtype('float64'): ['B'], dtype('O'): ['C', 'D']}
>>> {k.name: v for k, v in g.items()}
{'object': ['C', 'D'], 'int64': ['A', 'E'], 'float64': ['B']}

android.content.res.Resources$NotFoundException: String resource ID #0x0

When you try to set text in Edittext or textview you should pass only String format.

dateTime.setText(app.getTotalDl());

to

dateTime.setText(String.valueOf(app.getTotalDl()));

Playing m3u8 Files with HTML Video Tag

Use Flowplayer:

<link rel="stylesheet" href="//releases.flowplayer.org/7.0.4/commercial/skin/skin.css">
    <style>

   </style>
   <script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
  <script src="//releases.flowplayer.org/7.0.4/commercial/flowplayer.min.js"></script>
  <script src="//releases.flowplayer.org/hlsjs/flowplayer.hlsjs.min.js"></script> 
  <script>
  flowplayer(function (api) {
    api.on("load", function (e, api, video) {
      $("#vinfo").text(api.engine.engineName + " engine playing " + video.type);
    }); });
  </script>

<div class="flowplayer fixed-controls no-toggle no-time play-button obj"
      style="    width: 85.5%;
    height: 80%;
    margin-left: 7.2%;
    margin-top: 6%;
    z-index: 1000;" data-key="$812975748999788" data-live="true" data-share="false" data-ratio="0.5625"  data-logo="">
      <video autoplay="true" stretch="true">

         <source type="application/x-mpegurl" src="http://live.wmncdn.net/safaritv2/live2.stream/index.m3u8">
      </video>   
   </div>

Different methods are available in flowplayer.org website.

Bootstrap 3 panel header with buttons wrong position

You are part right. with <b>title</b> it looks fine, but I would like to use <h4>.

I have put <h4 style="display: inline;"> and it seams to work.

Now, I only need to add some vertival align.

How to center the content inside a linear layout?

android:layout_gravity is used for the layout itself

Use android:gravity="center" for children of your LinearLayout

So your code should be:

<LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_weight="1" >

Programmatically Creating UILabel

Does the following work ?

UIFont * customFont = [UIFont fontWithName:ProximaNovaSemibold size:12]; //custom font
NSString * text = [self fromSender];

CGSize labelSize = [text sizeWithFont:customFont constrainedToSize:CGSizeMake(380, 20) lineBreakMode:NSLineBreakByTruncatingTail];

UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(91, 15, labelSize.width, labelSize.height)];
fromLabel.text = text;
fromLabel.font = customFont;
fromLabel.numberOfLines = 1;
fromLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines; // or UIBaselineAdjustmentAlignCenters, or UIBaselineAdjustmentNone
fromLabel.adjustsFontSizeToFitWidth = YES;
fromLabel.adjustsLetterSpacingToFitWidth = YES;
fromLabel.minimumScaleFactor = 10.0f/12.0f;
fromLabel.clipsToBounds = YES;
fromLabel.backgroundColor = [UIColor clearColor];
fromLabel.textColor = [UIColor blackColor];
fromLabel.textAlignment = NSTextAlignmentLeft;
[collapsedViewContainer addSubview:fromLabel];

edit : I believe you may encounter a problem using both adjustsFontSizeToFitWidth and minimumScaleFactor. The former states that you also needs to set a minimumFontWidth (otherwhise it may shrink to something quite unreadable according to my test), but this is deprecated and replaced by the later.

edit 2 : Nevermind, outdated documentation. adjustsFontSizeToFitWidth needs minimumScaleFactor, just be sure no to pass it 0 as a minimumScaleFactor (integer division, 10/12 return 0). Small change on the baselineAdjustment value too.

Centering FontAwesome icons vertically and horizontally

If you are using twitter Bootstrap add the class text-center to your code.

<div class='login-icon'><i class="icon-lock text-center"></i></div>

Releasing memory in Python

Memory allocated on the heap can be subject to high-water marks. This is complicated by Python's internal optimizations for allocating small objects (PyObject_Malloc) in 4 KiB pools, classed for allocation sizes at multiples of 8 bytes -- up to 256 bytes (512 bytes in 3.3). The pools themselves are in 256 KiB arenas, so if just one block in one pool is used, the entire 256 KiB arena will not be released. In Python 3.3 the small object allocator was switched to using anonymous memory maps instead of the heap, so it should perform better at releasing memory.

Additionally, the built-in types maintain freelists of previously allocated objects that may or may not use the small object allocator. The int type maintains a freelist with its own allocated memory, and clearing it requires calling PyInt_ClearFreeList(). This can be called indirectly by doing a full gc.collect.

Try it like this, and tell me what you get. Here's the link for psutil.Process.memory_info.

import os
import gc
import psutil

proc = psutil.Process(os.getpid())
gc.collect()
mem0 = proc.get_memory_info().rss

# create approx. 10**7 int objects and pointers
foo = ['abc' for x in range(10**7)]
mem1 = proc.get_memory_info().rss

# unreference, including x == 9999999
del foo, x
mem2 = proc.get_memory_info().rss

# collect() calls PyInt_ClearFreeList()
# or use ctypes: pythonapi.PyInt_ClearFreeList()
gc.collect()
mem3 = proc.get_memory_info().rss

pd = lambda x2, x1: 100.0 * (x2 - x1) / mem0
print "Allocation: %0.2f%%" % pd(mem1, mem0)
print "Unreference: %0.2f%%" % pd(mem2, mem1)
print "Collect: %0.2f%%" % pd(mem3, mem2)
print "Overall: %0.2f%%" % pd(mem3, mem0)

Output:

Allocation: 3034.36%
Unreference: -752.39%
Collect: -2279.74%
Overall: 2.23%

Edit:

I switched to measuring relative to the process VM size to eliminate the effects of other processes in the system.

The C runtime (e.g. glibc, msvcrt) shrinks the heap when contiguous free space at the top reaches a constant, dynamic, or configurable threshold. With glibc you can tune this with mallopt (M_TRIM_THRESHOLD). Given this, it isn't surprising if the heap shrinks by more -- even a lot more -- than the block that you free.

In 3.x range doesn't create a list, so the test above won't create 10 million int objects. Even if it did, the int type in 3.x is basically a 2.x long, which doesn't implement a freelist.

Superscript in markdown (Github flavored)?

Comments about previous answers

The universal solution is using the HTML tag <sup>, as suggested in the main answer.
However, the idea behind Markdown is precisely to avoid the use of such tags:
The document should look nice as plain text, not only when rendered.

Another answer proposes using Unicode characters, which makes the document look nice as a plain text document but could reduce compatibility.

Finally, I would like to remember the simplest solution for some documents: the character ^.
Some Markdown implementation (e.g. MacDown in macOS) interprets the caret as an instruction for superscript.

Ex.
Sin^2 + Cos^2 = 1
Clearly, Stack Overflow does not interpret the caret as a superscript instruction. However, the text is comprehensible, and this is what really matters when using Markdown.

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

If you have different storybord files and if you have outlet references with out outlets creation in your header files then you just remove the connections by right clicking on files owner.

Files owner->Right click->remove unwanted connection over there.

Go through this for clear explanation. What does this mean? "'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X"

vertical alignment of text element in SVG

If you're testing this in IE, dominant-baseline and alignment-baseline are not supported.

The most effective way to center text in IE is to use something like this with "dy":

<text font-size="ANY SIZE" text-anchor="middle" "dy"="-.4em"> Ya Text </text>

The negative value will shift it up and a positive value of dy will shift it down. I've found using -.4em seems a bit more centered vertically to me than -.5em, but you'll be the judge of that.

What is default list styling (CSS)?

An answer for the future: CSS 4 will probably contain the revert keyword, which reverts a property to its value from the user or user-agent stylesheet [source]. As of writing this, only Safari supports this – check here for updates on browser support.

In your case you would use:

.my_container ol, .my_container ul {
    list-style: revert;
}

See also this other answer with some more details.

Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint

Be careful, that you do not use more than one constraint in the same direction and type.

For example: Vertical constraint for trailing = 15 and another one is >= 10.

Sometimes, Xcode creates some constraints you don't notice. You have to get rid of redundant constraints and the log warning will surely disappear.

enter image description here

Additionaly, you can read and detect some certain reasons, directly from the log:

NSLayoutConstraint:0xa338390 V:|-(15)-[UILabel:0xa331260] (Names: '|':UILabel:0xa330270 )>

This we can read as problem in UILabel constraint, it is leading vertical constraint being 15pt long.

NSLayoutConstraint:0x859ab20 H:-(13)-|[UIView:0x85a8fb0]...

This would be trailing horizontal constraint etc.

Align two inline-blocks left and right on same line

I think one possible solution to this is to use display: table:

.header {
  display: table;
  width: 100%;
  box-sizing: border-box;
}

.header > * {
  display: table-cell;
}

.header > *:last-child {
  text-align: right;  
}

h1 {
  font-size: 32px;
}

nav {
  vertical-align: baseline;
}

JSFiddle: http://jsfiddle.net/yxxrnn7j/1/

ARM compilation error, VFP registers used by executable, not object file

In my case CFLAGS = -O0 -g -Wall -I. -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=soft has helped. As you can see, i used it for my stm32f407.

What are the most common font-sizes for H1-H6 tags

Headings are normally bold-faced; that has been turned off for this demonstration of size correspondence. MSIE and Opera interpret these sizes the same, but note that Gecko browsers and Chrome interpret Heading 6 as 11 pixels instead of 10 pixels/font size 1, and Heading 3 as 19 pixels instead of 18 pixels/font size 4 (though it's difficult to tell the difference even in a direct comparison and impossible in use). It seems Gecko also limits text to no smaller than 10 pixels.

Ignore self-signed ssl cert using Jersey Client

worked for me with this code. May be its for Java 1.7

    TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // TODO Auto-generated method stub

        }

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // TODO Auto-generated method stub

        }
    }};

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        ;
    }

Formatting html email for Outlook

To be able to give you specific help, you's have to explain what particular parts specifically "get messed up", or perhaps offer a screenshot. It also helps to know what version of Outlook you encounter the problem in.

Either way, CampaignMonitor.com's CSS guide has often helped me out debugging email client inconsistencies.

From that guide you can see several things just won't work well or at all in Outlook, here are some highlights of the more important ones:

  • Various types of more sophisticated selectors, e.g. E:first-child, E:hover, E > F (Child combinator), E + F (Adjacent sibling combinator), E ~ F (General sibling combinator). This unfortunately means resorting to workarounds like inline styles.
  • Some font properties, e.g. white-space won't work.
  • The background-image property won't work.
  • There are several issues with the Box Model properties, most importantly height, width, and the max- versions are either not usable or have bugs for certain elements.
  • Positioning and Display issues (e.g. display, floats and position are all out).

In short: combining CSS and Outlook can be a pain. Be prepared to use many ugly workarounds.

PS. In your specific case, there are two minor issues in your html that may cause you odd behavior. There's "align=top" where you probably meant to use vertical-align. Also: cell-padding for tds doesn't exist.

exception in initializer error in java when using Netbeans

I got same error and it was due to older Lombok version. Check and update your Lombok version, Changes in Lombok

v1.18.4 - Many improvements for lombok's JDK10/11 support.

Align DIV's to bottom or baseline

_x000D_
_x000D_
td {_x000D_
  height: 150px;_x000D_
  width: 150px;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
b {_x000D_
  border: 1px solid black;_x000D_
}_x000D_
_x000D_
.child-2 {_x000D_
  vertical-align: bottom;_x000D_
}_x000D_
_x000D_
.child-3 {_x000D_
  vertical-align: top;_x000D_
}
_x000D_
<table border=1>_x000D_
  <tr>_x000D_
    <td class="child-1">_x000D_
      <b>child 1</b>_x000D_
    </td>_x000D_
    <td class="child-2">_x000D_
     <b>child 2</b>_x000D_
    </td>_x000D_
    <td class="child-3">_x000D_
      <b>child 3</b>_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

This is my solution

Improve INSERT-per-second performance of SQLite

Several tips:

  1. Put inserts/updates in a transaction.
  2. For older versions of SQLite - Consider a less paranoid journal mode (pragma journal_mode). There is NORMAL, and then there is OFF, which can significantly increase insert speed if you're not too worried about the database possibly getting corrupted if the OS crashes. If your application crashes the data should be fine. Note that in newer versions, the OFF/MEMORY settings are not safe for application level crashes.
  3. Playing with page sizes makes a difference as well (PRAGMA page_size). Having larger page sizes can make reads and writes go a bit faster as larger pages are held in memory. Note that more memory will be used for your database.
  4. If you have indices, consider calling CREATE INDEX after doing all your inserts. This is significantly faster than creating the index and then doing your inserts.
  5. You have to be quite careful if you have concurrent access to SQLite, as the whole database is locked when writes are done, and although multiple readers are possible, writes will be locked out. This has been improved somewhat with the addition of a WAL in newer SQLite versions.
  6. Take advantage of saving space...smaller databases go faster. For instance, if you have key value pairs, try making the key an INTEGER PRIMARY KEY if possible, which will replace the implied unique row number column in the table.
  7. If you are using multiple threads, you can try using the shared page cache, which will allow loaded pages to be shared between threads, which can avoid expensive I/O calls.
  8. Don't use !feof(file)!

I've also asked similar questions here and here.

Git for beginners: The definitive practical guide

git status is your friend, use it often. Good for answering questions like:

  • What did that command just do?
  • What branch am I on?
  • What changes am I about to commit, and have I forgotten anything?
  • Was I in the middle of something last time I worked on this project (days, weeks, or perhaps months ago)?

Unlike, say svn status, git status runs nigh-instantly even on large projects. I often found it reassuring while learning git to use it frequently, to make sure my mental model of what was going on was accurate. Now I mostly just use it to remind myself what I've changed since my last commit.

Obviously, it's much more useful if your .gitignore is sanely configured.

How to align checkboxes and their labels consistently cross-browsers

Maybe some folk are making the same mistake I did? Which was... I had set a width for the input boxes, because they were mostly of type 'text' , but then forgotten to over-ride that width for checkboxes - so my checkbox was trying to occupy a lot of excess width and so it was tough to align a label beside it.

.checkboxlabel {
    width: 100%;
    vertical-align: middle;
}
.checkbox {
    width: 20px !important;
}
<label for='acheckbox' class='checkboxlabel'>
    <input name="acheckbox" id='acheckbox' type="checkbox" class='checkbox'>Contact me</label>

Gives clickable labels and and proper alignment as far back as IE6 (using a class selector) and in late versions of Firefox, Safari and Chrome

What is the difference between float and double?

When using floating point numbers you cannot trust that your local tests will be exactly the same as the tests that are done on the server side. The environment and the compiler are probably different on you local system and where the final tests are run. I have seen this problem many times before in some TopCoder competitions especially if you try to compare two floating point numbers.

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

I got the same problem in my console application development and as a quick workaround,

go to project properties then,

click on signing tab and uncheck "Sign the ClickOnce Manifest".

Image Description:

enter image description here

enter image description here

FYI You can also see this less one minute video solution. The above picture is taken form the video.

Disabling browser print options (headers, footers, margins) from page?

I solved my problem using some css into the web page.

<style media="print">
   @page {
      size: auto;
      margin: 0;
  }
</style>

How to convert String to long in Java?

Use Long.parseLong()

 Long.parseLong("0", 10)        // returns 0L
 Long.parseLong("473", 10)      // returns 473L
 Long.parseLong("-0", 10)       // returns 0L
 Long.parseLong("-FF", 16)      // returns -255L
 Long.parseLong("1100110", 2)   // returns 102L
 Long.parseLong("99", 8)        // throws a NumberFormatException
 Long.parseLong("Hazelnut", 10) // throws a NumberFormatException
 Long.parseLong("Hazelnut", 36) // returns 1356099454469L
 Long.parseLong("999")          // returns 999L

Switch: Multiple values in one case?

You can use ifelse instead.but if you want to know how to use switch in this case.here is an example.

int age = Convert.ToInt32(txtBoxAge.Text);`
int flag;
if(age >= 1 && age <= 8) {
flag = 1;
} else if (age >= 9 && age <= 15) {
 flag = 2;
} else if (age >= 16 && age <= 100) {
 flag = 3;
} else {
 flag = 4;   
}
switch (flag) 

{
 case 1:
  MessageBox.Show("You are only " + age + " years old\n You must be kidding right.\nPlease fill in your *real* age.");
break;
case 2:
  MessageBox.Show("You are only " + age + " years old\n That's too young!");
break;
case 3:
  MessageBox.Show("You are " + age + " years old\n Perfect.");
break;
default:
  MessageBox.Show("You an old person.");
break;
}

hope that helps ! :)

How do I check if a directory exists? "is_dir", "file_exists" or both?

$year = date("Y");   
$month = date("m");   
$filename = "../".$year;   
$filename2 = "../".$year."/".$month;

if(file_exists($filename)){
    if(file_exists($filename2)==false){
        mkdir($filename2,0777);
    }
}else{
    mkdir($filename,0777);
}

How to define custom sort function in javascript?

It could be that the plugin is case-sensitive. Try inputting Te instead of te. You can probably have your results setup to not be case-sensitive. This question might help.

For a custom sort function on an Array, you can use any JavaScript function and pass it as parameter to an Array's sort() method like this:

_x000D_
_x000D_
var array = ['White 023', 'White', 'White flower', 'Teatr'];_x000D_
_x000D_
array.sort(function(x, y) {_x000D_
  if (x < y) {_x000D_
    return -1;_x000D_
  }_x000D_
  if (x > y) {_x000D_
    return 1;_x000D_
  }_x000D_
  return 0;_x000D_
});_x000D_
_x000D_
// Teatr White White 023 White flower_x000D_
document.write(array);
_x000D_
_x000D_
_x000D_

More Info here on Array.sort.

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.

However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.

In that case, you can use

jekyll serve --host 0.0.0.0

This binds your application to the host & next use following to connect to it from some other host

http://host's IP adress/4000 

Cannot bulk load. Operating system error code 5 (Access is denied.)

1) Open SQL 2) In Task Manager, you can check which account is running the SQL - it is probably not Michael-PC\Michael as Jan wrote.

The account that runs SQL need access to the shared folder.

Aggregate function in SQL WHERE-Clause

HAVING is like WHERE with aggregate functions, or you could use a subquery.

select EmployeeId, sum(amount)
from Sales
group by Employee
having sum(amount) > 20000

Or

select EmployeeId, sum(amount)
from Sales
group by Employee
where EmployeeId in (
    select max(EmployeeId) from Employees)

Inserting the iframe into react component

You can use property dangerouslySetInnerHTML, like this

_x000D_
_x000D_
const Component = React.createClass({_x000D_
  iframe: function () {_x000D_
    return {_x000D_
      __html: this.props.iframe_x000D_
    }_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <div dangerouslySetInnerHTML={ this.iframe() } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe> tag and pass it to new <iframe> tag, like that

_x000D_
_x000D_
/**_x000D_
 * getAttrs_x000D_
 * returns all attributes from TAG string_x000D_
 * @return Object_x000D_
 */_x000D_
const getAttrs = (iframeTag) => {_x000D_
  var doc = document.createElement('div');_x000D_
  doc.innerHTML = iframeTag;_x000D_
_x000D_
  const iframe = doc.getElementsByTagName('iframe')[0];_x000D_
  return [].slice_x000D_
    .call(iframe.attributes)_x000D_
    .reduce((attrs, element) => {_x000D_
      attrs[element.name] = element.value;_x000D_
      return attrs;_x000D_
    }, {});_x000D_
}_x000D_
_x000D_
const Component = React.createClass({_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <iframe {...getAttrs(this.props.iframe) } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"><div>
_x000D_
_x000D_
_x000D_

SQL query: Delete all records from the table except latest N?

This should work as well:

DELETE FROM [table] 
INNER JOIN (
    SELECT [id] 
    FROM (
        SELECT [id] 
        FROM [table] 
        ORDER BY [id] DESC
        LIMIT N
    ) AS Temp
) AS Temp2 ON [table].[id] = [Temp2].[id]

Disable vertical scroll bar on div overflow: auto

if you want to disable the scrollbar, but still able to scroll the content of inner DIV, use below code in css,

.divHideScroll::-webkit-scrollbar {
    width: 0 !important
}
.divHideScroll {
    overflow: -moz-scrollbars-none;
}
.divHideScroll {
    -ms-overflow-style: none;
}

divHideScroll is the class name of the target div.

It will work in all major browser (Chrome, Safari, Mozilla, Opera, and IE)

Extract year from date

if all your dates are the same width, you can put the dates in a vector and use substring

Date
a <- c("01/01/2009", "01/01/2010" , "01/01/2011")
substring(a,7,10) #This takes string and only keeps the characters beginning in position 7 to position 10

output

[1] "2009" "2010" "2011"

Why can't overriding methods throw exceptions broader than the overridden method?

It means that if a method declares to throw a given exception, the overriding method in a subclass can only declare to throw that exception or its subclass. For example:

class A {
   public void foo() throws IOException {..}
}

class B extends A {
   @Override
   public void foo() throws SocketException {..} // allowed

   @Override
   public void foo() throws SQLException {..} // NOT allowed
}

SocketException extends IOException, but SQLException does not.

This is because of polymorphism:

A a = new B();
try {
    a.foo();
} catch (IOException ex) {
    // forced to catch this by the compiler
}

If B had decided to throw SQLException, then the compiler could not force you to catch it, because you are referring to the instance of B by its superclass - A. On the other hand, any subclass of IOException will be handled by clauses (catch or throws) that handle IOException

The rule that you need to be able to refer to objects by their superclass is the Liskov Substitution Principle.

Since unchecked exceptions can be thrown anywhere then they are not subject to this rule. You can add an unchecked exception to the throws clause as a form of documentation if you want, but the compiler doesn't enforce anything about it.

Accessing Google Account Id /username via Android

String name = android.os.Build.USER;

if (!TextUtils.isEmpty(name)) {
    nameEdit.setText(name);
}

Why a function checking if a string is empty always returns true?

this is the short and effective solution, exactly what you're looking for :

return $input > null ? 'not empty' : 'empty' ;

How to sort a dataFrame in python pandas by two or more columns?

For large dataframes of numeric data, you may see a significant performance improvement via numpy.lexsort, which performs an indirect sort using a sequence of keys:

import pandas as pd
import numpy as np

np.random.seed(0)

df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])
df1 = pd.concat([df1]*100000)

def pdsort(df1):
    return df1.sort_values(['a', 'b'], ascending=[True, False])

def lex(df1):
    arr = df1.values
    return pd.DataFrame(arr[np.lexsort((-arr[:, 1], arr[:, 0]))])

assert (pdsort(df1).values == lex(df1).values).all()

%timeit pdsort(df1)  # 193 ms per loop
%timeit lex(df1)     # 143 ms per loop

One peculiarity is that the defined sorting order with numpy.lexsort is reversed: (-'b', 'a') sorts by series a first. We negate series b to reflect we want this series in descending order.

Be aware that np.lexsort only sorts with numeric values, while pd.DataFrame.sort_values works with either string or numeric values. Using np.lexsort with strings will give: TypeError: bad operand type for unary -: 'str'.

How to do a scatter plot with empty circles in Python?

From the documentation for scatter:

Optional kwargs control the Collection properties; in particular:

    edgecolors:
        The string ‘none’ to plot faces with no outlines
    facecolors:
        The string ‘none’ to plot unfilled outlines

Try the following:

import matplotlib.pyplot as plt 
import numpy as np 

x = np.random.randn(60) 
y = np.random.randn(60)

plt.scatter(x, y, s=80, facecolors='none', edgecolors='r')
plt.show()

example image

Note: For other types of plots see this post on the use of markeredgecolor and markerfacecolor.

How can I read pdf in python?

You can use textract module in python

Textract

for install

pip install textract

for read pdf

import textract
text = textract.process('path/to/pdf/file', method='pdfminer')

For detail Textract

Keeping session alive with Curl and PHP

You also need to set the option CURLOPT_COOKIEFILE.

The manual describes this as

The name of the file containing the cookie data. The cookie file can be in Netscape format, or just plain HTTP-style headers dumped into a file. If the name is an empty string, no cookies are loaded, but cookie handling is still enabled.

Since you are using the cookie jar you end up saving the cookies when the requests finish, but since the CURLOPT_COOKIEFILE is not given, cURL isn't sending any of the saved cookies on subsequent requests.

How to refresh datagrid in WPF

Reload the datasource of your grid after the update

myGrid.ItemsSource = null;
myGrid.ItemsSource = myDataSource;

The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel

I've seen your code in web.php as follows: Route::post('/edit/{id}','ProjectController@update');

Step 1: remove the {id} random parameter so it would be like this: Route::post('/edit','ProjectController@update');

Step 2: Then remove the @method('PUT') in your form, so let's say we'll just plainly use the POST method

Then how can I pass the ID to my method?

Step 1: make an input field in your form with the hidden attribute for example

<input type="hidden" value="{{$project->id}}" name="id">

Step 2: in your update method in your controller, fetch that ID for example:

$id = $request->input('id');

then you may not use it to find which project to edit

$project = Project::find($id)
//OR
$project = Project::where('id',$id);

Why is a "GRANT USAGE" created the first time I grant a user privileges?

As you said, in MySQL USAGE is synonymous with "no privileges". From the MySQL Reference Manual:

The USAGE privilege specifier stands for "no privileges." It is used at the global level with GRANT to modify account attributes such as resource limits or SSL characteristics without affecting existing account privileges.

USAGE is a way to tell MySQL that an account exists without conferring any real privileges to that account. They merely have permission to use the MySQL server, hence USAGE. It corresponds to a row in the `mysql`.`user` table with no privileges set.

The IDENTIFIED BY clause indicates that a password is set for that user. How do we know a user is who they say they are? They identify themselves by sending the correct password for their account.

A user's password is one of those global level account attributes that isn't tied to a specific database or table. It also lives in the `mysql`.`user` table. If the user does not have any other privileges ON *.*, they are granted USAGE ON *.* and their password hash is displayed there. This is often a side effect of a CREATE USER statement. When a user is created in that way, they initially have no privileges so they are merely granted USAGE.

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

Syntax of JSON

object = {} | { members }

  • members = pair | pair, members
  • pair = string : value

array = [] | [ elements ]

  • elements = value | value elements

value = string|number|object|array|true|false|null

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

The Problem might be from the driver name for example instead of DRIVER={MySQL ODBC 5.3 Driver} try DRIVER={MySQL ODBC 5.3 Unicode Driver} you can see the name of the driver from administration tool

How to restart remote MySQL server running on Ubuntu linux?

  • To restart mysql use this command

sudo service mysql restart

Or

sudo restart mysql

Reference

Setting multiple attributes for an element at once with JavaScript

You could make a helper function:

function setAttributes(el, attrs) {
  for(var key in attrs) {
    el.setAttribute(key, attrs[key]);
  }
}

Call it like this:

setAttributes(elem, {"src": "http://example.com/something.jpeg", "height": "100%", ...});

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

You'll have to uninstall XAMPP 1.7.2 and install XAMPP 1.7.0, which contains PHP 5.2.8.

D:\Documents and Settings\box>php -v

PHP 5.2.8 (cli) (built: Dec  8 2008 19:31:23)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
    with Zend Extension Manager v1.2.0, Copyright (c) 2003-2007, by Zend Technol
ogies
    with Zend Optimizer v3.3.3, Copyright (c) 1998-2007, by Zend Technologies

XAMPP 1.6.8 contains PHP 5.2.6.

D:\Documents and Settings\box>php -v
PHP 5.2.6 (cli) (built: May  2 2008 18:02:07)
Copyright (c) 1997-2008 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2008 Zend Technologies
    with Zend Extension Manager v1.2.0, Copyright (c) 2003-2007, by Zend Technol
ogies
    with Zend Optimizer v3.3.3, Copyright (c) 1998-2007, by Zend Technologies

How can I clear the Scanner buffer in Java?

You can't explicitly clear Scanner's buffer. Internally, it may clear the buffer after a token is read, but that's an implementation detail outside of the porgrammers' reach.

how to delete default values in text field using selenium?

You can use the code below. It selects the pre-existing value in the field and overwrites it with the new value.

driver.findElement(By.xpath("*enter your xpath here*")).sendKeys(Keys.chord(Keys.CONTROL, "a"),*enter the new value here*);

Encoding as Base64 in Java

I tried with the following code snippet. It worked well. :-)

com.sun.org.apache.xml.internal.security.utils.Base64.encode("The string to encode goes here");

Suppress command line output

mysqldump doesn't work with: >nul 2>&1
Instead use: 2> nul
This suppress the stderr message: "Warning: Using a password on the command line interface can be insecure"

What do 'real', 'user' and 'sys' mean in the output of time(1)?

Real shows total turn-around time for a process; while User shows the execution time for user-defined instructions and Sys is for time for executing system calls!

Real time includes the waiting time also (the waiting time for I/O etc.)

Converting any string into camel case

This builds on the answer by CMS by removing any non-alphabetic characters including underscores, which \w does not remove.

function toLowerCamelCase(str) {
    return str.replace(/[^A-Za-z0-9]/g, ' ').replace(/^\w|[A-Z]|\b\w|\s+/g, function (match, index) {
        if (+match === 0 || match === '-' || match === '.' ) {
            return ""; // or if (/\s+/.test(match)) for white spaces
        }
        return index === 0 ? match.toLowerCase() : match.toUpperCase();
    });
}

toLowerCamelCase("EquipmentClass name");
toLowerCamelCase("Equipment className");
toLowerCamelCase("equipment class name");
toLowerCamelCase("Equipment Class Name");
toLowerCamelCase("Equipment-Class-Name");
toLowerCamelCase("Equipment_Class_Name");
toLowerCamelCase("Equipment.Class.Name");
toLowerCamelCase("Equipment/Class/Name");
// All output e

How to configure a HTTP proxy for svn

You can find the instructions here. Basically you just add

[global]
http-proxy-host = ip.add.re.ss
http-proxy-port = 3128
http-proxy-compression = no

to your ~/.subversion/servers file.

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

No it is not possible, hence your runtime error.

But you can assign an instance of a derived class to a variable of base class type.

VBoxManage: error: Failed to create the host-only adapter

$sudo /Library/StartupItems/VirtualBox/VirtualBox restart

Worked great for me on Mac. This normally happens when I shut down my computer without running

$vagrant suspend

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

You're missing service name:

 SQL> connect username/password@hostname:port/SERVICENAME

EDIT

If you can connect to the database from other computer try running there:

select sys_context('USERENV','SERVICE_NAME') from dual

and

select sys_context('USERENV','SID') from dual

Apache HttpClient Interim Error: NoHttpResponseException

HttpClient 4.4 suffered from a bug in this area relating to validating possibly stale connections before returning to the requestor. It didn't validate whether a connection was stale, and this then results in an immediate NoHttpResponseException.

This issue was resolved in HttpClient 4.4.1. See this JIRA and the release notes

How to append binary data to a buffer in node.js

This is to help anyone who comes here looking for a solution that wants a pure approach. I would recommend understanding this problem because it can happen in lots of different places not just with a JS Buffer object. By understanding why the problem exists and how to solve it you will improve your ability to solve other problems in the future since this one is so fundamental.

For those of us that have to deal with these problems in other languages it is quite natural to devise a solution, but there are people who may not realize how to abstract away the complexities and implement a generally efficient dynamic buffer. The code below may have potential to be optimized further.

I have left the read method unimplemented to keep the example small in size.

The realloc function in C (or any language dealing with intrinsic allocations) does not guarantee that the allocation will be expanded in size with out moving the existing data - although sometimes it is possible. Therefore most applications when needing to store a unknown amount of data will use a method like below and not constantly reallocate, unless the reallocation is very infrequent. This is essentially how most file systems handle writing data to a file. The file system simply allocates another node and keeps all the nodes linked together, and when you read from it the complexity is abstracted away so that the file/buffer appears to be a single contiguous buffer.

For those of you who wish to understand the difficulty in just simply providing a high performance dynamic buffer you only need to view the code below, and also do some research on memory heap algorithms and how the memory heap works for programs.

Most languages will provide a fixed size buffer for performance reasons, and then provide another version that is dynamic in size. Some language systems opt for a third-party system where they keep the core functionality minimal (core distribution) and encourage developers to create libraries to solve additional or higher level problems. This is why you may question why a language does not provide some functionality. This small core functionality allows costs to be reduced in maintaining and enhancing the language, however you end up having to write your own implementations or depending on a third-party.

var Buffer_A1 = function (chunk_size) {
    this.buffer_list = [];
    this.total_size = 0;
    this.cur_size = 0;
    this.cur_buffer = [];
    this.chunk_size = chunk_size || 4096;

    this.buffer_list.push(new Buffer(this.chunk_size));
};

Buffer_A1.prototype.writeByteArrayLimited = function (data, offset, length) {
    var can_write = length > (this.chunk_size - this.cur_size) ? (this.chunk_size - this.cur_size) : length;

    var lastbuf = this.buffer_list.length - 1;

    for (var x = 0; x < can_write; ++x) {
        this.buffer_list[lastbuf][this.cur_size + x] = data[x + offset];
    }

    this.cur_size += can_write;
    this.total_size += can_write;

    if (this.cur_size == this.chunk_size) {
        this.buffer_list.push(new Buffer(this.chunk_size));
        this.cur_size = 0;
    }

    return can_write;
};

/*
    The `data` parameter can be anything that is array like. It just must
    support indexing and a length and produce an acceptable value to be
    used with Buffer.
*/
Buffer_A1.prototype.writeByteArray = function (data, offset, length) {
    offset = offset == undefined ? 0 : offset;
    length = length == undefined ? data.length : length;

    var rem = length;
    while (rem > 0) {
        rem -= this.writeByteArrayLimited(data, length - rem, rem);
    }
};

Buffer_A1.prototype.readByteArray = function (data, offset, length) {
    /*
        If you really wanted to implement some read functionality
        then you would have to deal with unaligned reads which could
        span two buffers.
    */
};

Buffer_A1.prototype.getSingleBuffer = function () {
    var obuf = new Buffer(this.total_size);
    var cur_off = 0;
    var x;

    for (x = 0; x < this.buffer_list.length - 1; ++x) {
        this.buffer_list[x].copy(obuf, cur_off);
        cur_off += this.buffer_list[x].length;
    }

    this.buffer_list[x].copy(obuf, cur_off, 0, this.cur_size);

    return obuf;
};

Prevent screen rotation on Android

The easiest way I found to do this was to put

this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

within onCreate, just after

setContentView(R.layout.activity_main);

so...

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

What size do you use for varchar(MAX) in your parameter declaration?

The maximum SqlDbType.VarChar size is 2147483647.

If you would use a generic oledb connection instead of sql, I found here there is also a LongVarChar datatype. Its max size is 2147483647.

cmd.Parameters.Add("@blah", OleDbType.LongVarChar, -1).Value = "very big string";

Does Visual Studio Code have box select/multi-line edit?

On Windows it's holding down Alt while box selecting. Once you have your selection then attempt your edit.

Change GitHub Account username

Yes, this is an old question. But it's misleading, as this was the first result in my search, and both the answers aren't correct anymore.

You can change your Github account name at any time.

To do this, click your profile picture > Settings > Account Settings > Change Username.

Links to your repositories will redirect to the new URLs, but they should be updated on other sites because someone who chooses your abandoned username can override the links. Links to your profile page will be 404'd.

For more information, see the official help page.

And furthermore, if you want to change your username to something else, but that specific username is being taken up by someone else who has been completely inactive for the entire time their account has existed, you can report their account for name squatting.

What underlies this JavaScript idiom: var self = this?

Yes, you'll see it everywhere. It's often that = this;.

See how self is used inside functions called by events? Those would have their own context, so self is used to hold the this that came into Note().

The reason self is still available to the functions, even though they can only execute after the Note() function has finished executing, is that inner functions get the context of the outer function due to closure.

How to edit nginx.conf to increase file size upload

First Navigate the Path of php.ini

sudo vi /etc/php/7.2/fpm/php.ini

then, next change

upload_max_filesize = 999M
post_max_size = 999M

then ESC-->:wq

Now Lastly Paste this command,

sudo systemctl restart php7.2-fpm.service

you are done.

Hibernate Union alternatives

You could use id in (select id from ...) or id in (select id from ...)

e.g. instead of non-working

from Person p where p.name="Joe"
union
from Person p join p.children c where c.name="Joe"

you could do

from Person p 
  where p.id in (select p1.id from Person p1 where p1.name="Joe") 
    or p.id in (select p2.id from Person p2 join p2.children c where c.name="Joe");

At least using MySQL, you will run into performance problems with it later, though. It's sometimes easier to do a poor man's join on two queries instead:

// use set for uniqueness
Set<Person> people = new HashSet<Person>((List<Person>) query1.list());
people.addAll((List<Person>) query2.list());
return new ArrayList<Person>(people);

It's often better to do two simple queries than one complex one.

EDIT:

to give an example, here is the EXPLAIN output of the resulting MySQL query from the subselect solution:

mysql> explain 
  select p.* from PERSON p 
    where p.id in (select p1.id from PERSON p1 where p1.name = "Joe") 
      or p.id in (select p2.id from PERSON p2 
        join CHILDREN c on p2.id = c.parent where c.name="Joe") \G
*************************** 1. row ***************************
           id: 1
  select_type: PRIMARY
        table: a
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 247554
        Extra: Using where
*************************** 2. row ***************************
           id: 3
  select_type: DEPENDENT SUBQUERY
        table: NULL
         type: NULL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: NULL
        Extra: Impossible WHERE noticed after reading const tables
*************************** 3. row ***************************
           id: 2
  select_type: DEPENDENT SUBQUERY
        table: a1
         type: unique_subquery
possible_keys: PRIMARY,name,sortname
          key: PRIMARY
      key_len: 4
          ref: func
         rows: 1
        Extra: Using where
3 rows in set (0.00 sec)

Most importantly, 1. row doesn't use any index and considers 200k+ rows. Bad! Execution of this query took 0.7s wheres both subqueries are in the milliseconds.

Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception

try adding this dependency org.apache.commons commons-exec 1.3

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

I'd like to share my experience of using Ant in building projects, *.properties files should be copied explicitly. This is because Ant will not compile *.properties files into the build working directory by default (javac just ignore *.properties). For example:

<target name="compile" depends="init">
    <javac destdir="${dst}" srcdir="${src}" debug="on" encoding="utf-8" includeantruntime="false">
        <include name="com/example/**" />
        <classpath refid="libs" />
    </javac>
    <copy todir="${dst}">
        <fileset dir="${src}" includes="**/*.properties" />
    </copy>
</target>

<target name="jars" depends="compile">
    <jar jarfile="${app_jar}" basedir="${dst}" includes="com/example/**/*.*" />
</target>

Please notice that 'copy' section under the 'compile' target, it will replicate *.properties files into the build working directory. Without the 'copy' section the jar file will not contain the properties files, then you may encounter the java.util.MissingResourceException.

Selecting Folder Destination in Java?

You could try something like this (as shown here: Select a Directory with a JFileChooser):

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;


public class DemoJFileChooser extends JPanel
   implements ActionListener {
   JButton go;

   JFileChooser chooser;
   String choosertitle;

  public DemoJFileChooser() {
    go = new JButton("Do it");
    go.addActionListener(this);
    add(go);
   }

  public void actionPerformed(ActionEvent e) {            
    chooser = new JFileChooser(); 
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle(choosertitle);
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    //
    // disable the "All files" option.
    //
    chooser.setAcceptAllFileFilterUsed(false);
    //    
    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { 
      System.out.println("getCurrentDirectory(): " 
         +  chooser.getCurrentDirectory());
      System.out.println("getSelectedFile() : " 
         +  chooser.getSelectedFile());
      }
    else {
      System.out.println("No Selection ");
      }
     }

  public Dimension getPreferredSize(){
    return new Dimension(200, 200);
    }

  public static void main(String s[]) {
    JFrame frame = new JFrame("");
    DemoJFileChooser panel = new DemoJFileChooser();
    frame.addWindowListener(
      new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
          System.exit(0);
          }
        }
      );
    frame.getContentPane().add(panel,"Center");
    frame.setSize(panel.getPreferredSize());
    frame.setVisible(true);
    }
}

How do I kill a process using Vb.NET or C#?

Killing the Word process outright is possible (see some of the other replies), but outright rude and dangerous: what if the user has important unsaved changes in an open document? Not to mention the stale temporary files this will leave behind...

This is probably as far as you can go in this regard (VB.NET):

    Dim proc = Process.GetProcessesByName("winword")
    For i As Integer = 0 To proc.Count - 1
        proc(i).CloseMainWindow()
    Next i

This will close all open Word windows in an orderly fashion (prompting the user to save his/her work if applicable). Of course, the user can always click 'Cancel' in this scenario, so you should be able to handle this case as well (preferably by putting up a "please close all Word instances, otherwise we can't continue" dialog...)

How to get the Touch position in android?

@Override
public boolean onTouchEvent(MotionEvent event)
{
    int x = (int)event.getX();
    int y = (int)event.getY();

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
        case MotionEvent.ACTION_UP:
    }

    return false;
}

The three cases are so that you can react to different types of events, in this example tapping or dragging or lifting the finger again.

Understanding timedelta

why do I have to pass seconds = uptime to timedelta

Because timedelta objects can be passed seconds, milliseconds, days, etc... so you need to specify what are you passing in (this is why you use the explicit key). Typecasting to int is superfluous as they could also accept floats.

and why does the string casting works so nicely that I get HH:MM:SS ?

It's not the typecasting that formats, is the internal __str__ method of the object. In fact you will achieve the same result if you write:

print datetime.timedelta(seconds=int(uptime))

How to set the Android progressbar's height?

Many solution here with lot of upvotes didn't work for me, even the accepted answer. I solved it by setting the scaleY, but isn't a good solution if you need too much height because the drawable comes pixelated.

Programmatically:


progressBar.setScaleY(2f);

XML Layout:


android:scaleY="2"

c# foreach (property in object)... Is there a simple way of doing this?

Use Reflection to do this

SomeClass A = SomeClass(...)
PropertyInfo[] properties = A.GetType().GetProperties();

How to remove symbols from a string with Python?

I often just open the console and look for the solution in the objects methods. Quite often it's already there:

>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello   s'

Short answer: Use string.replace().

Where is the syntax for TypeScript comments documented?

Future

The TypeScript team, and other TypeScript involved teams, plan to create a standard formal TSDoc specification. The 1.0.0 draft hasn't been finalised yet: https://github.com/Microsoft/tsdoc#where-are-we-on-the-roadmap

enter image description here

Current

TypeScript uses JSDoc. e.g.

/** This is a description of the foo function. */
function foo() {
}

To learn jsdoc : https://jsdoc.app/

Demo

But you don't need to use the type annotation extensions in JSDoc.

You can (and should) still use other jsdoc block tags like @returns etc.

Example

Just an example. Focus on the types (not the content).

JSDoc version (notice types in docs):

/**
 * Returns the sum of a and b
 * @param {number} a
 * @param {number} b
 * @returns {number}
 */
function sum(a, b) {
    return a + b;
}

TypeScript version (notice the re-location of types):

/**
 * Takes two numbers and returns their sum
 * @param a first input to sum
 * @param b second input to sum
 * @returns sum of a and b
 */
function sum(a: number, b: number): number {
    return a + b;
}

Form Validation With Bootstrap (jQuery)

You can get another validation on this tutorial : http://twitterbootstrap.org/bootstrap-form-validation

They use JQuery validation.

jquery.validate.js

jquery.validate.min.js

jquery-1.7.1.min.js

enter image description here

And you'll get the source code there.

 <form id="registration-form" class="form-horizontal">
 <h2>Sample Registration form <small>(Fill up the forms to get register)</small></h2>
 <div class="form-control-group">
        <label class="control-label" for="name">Your Name</label>
 <div class="controls">
          <input type="text" class="input-xlarge" name="name" id="name"></div>
 </div>
 <div class="form-control-group">
        <label class="control-label" for="name">User Name</label>
 <div class="controls">
          <input type="text" class="input-xlarge" name="username" id="username"></div>
 </div>
 <div class="form-control-group">
        <label class="control-label" for="name">Password</label>
 <div class="controls">
          <input type="password" class="input-xlarge" name="password" id="password">

</div>
</div>
<div class="form-control-group">
            <label class="control-label" for="name"> Retype Password</label>
<div class="controls">
              <input type="password" class="input-xlarge" name="confirm_password" id="confirm_password"></div>
</div>
<div class="form-control-group">
            <label class="control-label" for="email">Email Address</label>
<div class="controls">
              <input type="text" class="input-xlarge" name="email" id="email"></div>
</div>
<div class="form-control-group">
            <label class="control-label" for="message">Your Address</label>
<div class="controls">
              <textarea class="input-xlarge" name="address" id="address" rows="3"></textarea></div>
</div>
<div class="form-control-group">
            <label class="control-label" for="message"> Please agree to our policy</label>
<div class="controls">
             <input id="agree" class="checkbox" type="checkbox" name="agree"></div>
</div>
<div class="form-actions">
            <button type="submit" class="btn btn-success btn-large">Register</button>
            <button type="reset" class="btn">Cancel</button></div>
</form>

And The JQuery :

<script src="assets/js/jquery-1.7.1.min.js"></script>

<script src="assets/js/jquery.validate.js"></script>

<script src="script.js"></script>
<script>
            addEventListener('load', prettyPrint, false);
            $(document).ready(function(){
            $('pre').addClass('prettyprint linenums');
                  });

Here is the live example of the code: http://twitterbootstrap.org/live/bootstrap-form-validation/

Check the full tutorial: http://twitterbootstrap.org/bootstrap-form-validation/

happy coding.

numpy matrix vector multiplication

Simplest solution

Use numpy.dot or a.dot(b). See the documentation here.

>>> a = np.array([[ 5, 1 ,3], 
                  [ 1, 1 ,1], 
                  [ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])

This occurs because numpy arrays are not matrices, and the standard operations *, +, -, / work element-wise on arrays. Instead, you could try using numpy.matrix, and * will be treated like matrix multiplication.


Other Solutions

Also know there are other options:

  • As noted below, if using python3.5+ the @ operator works as you'd expect:

    >>> print(a @ b)
    array([16, 6, 8])
    
  • If you want overkill, you can use numpy.einsum. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.

    >>> np.einsum('ji,i->j', a, b)
    array([16, 6, 8])
    
  • As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul, which works like numpy.dot with two major exceptions: no scalar multiplication but it works with stacks of matrices.

    >>> np.matmul(a, b)
    array([16, 6, 8])
    
  • numpy.inner functions the same way as numpy.dot for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).

    >>> np.inner(a, b)
    array([16, 6, 8])
    
    # Beware using for matrix-matrix multiplication though!
    >>> b = a.T
    >>> np.dot(a, b)
    array([[35,  9, 10],
           [ 9,  3,  4],
           [10,  4,  6]])
    >>> np.inner(a, b) 
    array([[29, 12, 19],
           [ 7,  4,  5],
           [ 8,  5,  6]])
    

Rarer options for edge cases

  • If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot with the optional argument axes=1:

    >>> np.tensordot(a, b, axes=1)
    array([16,  6,  8])
    
  • Don't use numpy.vdot if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m vs n).

Is it possible to override / remove background: none!important with jQuery?

Why does not it work? Because the background CSS with background:none!important has one #ID

A CSS selector file that contains an #id will always have a higher value than one .class

If you want to work, you need add #id on your .image-list li like this:

#an-element .image-list li {
    display: inline-block;
    background-image: url("http://placekitten.com/150/50")!important;
    padding: 1em;
    border: 1px solid blue;
}

result here

How to reshape data from long to wide format

much easier way!

devtools::install_github("yikeshu0611/onetree") #install onetree package

library(onetree)
widedata=reshape_toWide(data = dat1,id = "name",j = "numbers",value.var.prefix = "value")
widedata

        name     value1     value2     value3     value4
   firstName  0.3407997 -0.7033403 -0.3795377 -0.7460474
  secondName -0.8981073 -0.3347941 -0.5013782 -0.1745357

if you want to go back from wide to long, only change Wide to Long, and no changes in objects.

reshape_toLong(data = widedata,id = "name",j = "numbers",value.var.prefix = "value")

        name numbers      value
   firstName       1  0.3407997
  secondName       1 -0.8981073
   firstName       2 -0.7033403
  secondName       2 -0.3347941
   firstName       3 -0.3795377
  secondName       3 -0.5013782
   firstName       4 -0.7460474
  secondName       4 -0.1745357

SQL Server - In clause with a declared variable

First, create a quick function that will split a delimited list of values into a table, like this:

CREATE FUNCTION dbo.udf_SplitVariable
(
    @List varchar(8000),
    @SplitOn varchar(5) = ','
)

RETURNS @RtnValue TABLE
(
    Id INT IDENTITY(1,1),
    Value VARCHAR(8000)
)

AS
BEGIN

--Account for ticks
SET @List = (REPLACE(@List, '''', ''))

--Account for 'emptynull'
IF LTRIM(RTRIM(@List)) = 'emptynull'
BEGIN
    SET @List = ''
END

--Loop through all of the items in the string and add records for each item
WHILE (CHARINDEX(@SplitOn,@List)>0)
BEGIN

    INSERT INTO @RtnValue (value)
    SELECT Value = LTRIM(RTRIM(SUBSTRING(@List, 1, CHARINDEX(@SplitOn, @List)-1)))  

    SET @List = SUBSTRING(@List, CHARINDEX(@SplitOn,@List) + LEN(@SplitOn), LEN(@List))

END

INSERT INTO @RtnValue (Value)
SELECT Value = LTRIM(RTRIM(@List))

RETURN

END 

Then call the function like this...

SELECT * 
FROM A
LEFT OUTER JOIN udf_SplitVariable(@ExcludedList, ',') f ON A.Id = f.Value
WHERE f.Id IS NULL

This has worked really well on our project...

Of course, the opposite could also be done, if that was the case (though not your question).

SELECT * 
FROM A
INNER JOIN udf_SplitVariable(@ExcludedList, ',') f ON A.Id = f.Value

And this really comes in handy when dealing with reports that have an optional multi-select parameter list. If the parameter is NULL you want all values selected, but if it has one or more values you want the report data filtered on those values. Then use SQL like this:

SELECT * 
FROM A
INNER JOIN udf_SplitVariable(@ExcludedList, ',') f ON A.Id = f.Value OR @ExcludeList IS NULL

This way, if @ExcludeList is a NULL value, the OR clause in the join becomes a switch that turns off filtering on this value. Very handy...

Localhost : 404 not found

Type in "netstat -ano" into your command line. I saw that it was showing something for Local Address port 0.0.0.0:80.

My issue was because I had SQL Server Reporting Services on Port 80. So I followed these instructions and changed the port # from 80 to 81:

http://seankilleen.com/2012/11/how-to-stop-sql-server-reporting-services-from-using-port-80-on-your-server-field-notes/

Here is a picture of my command line after I changed the port number for SQL Server Reporting Services:

enter image description here

If you are still having the same issue, read this forum:

http://forum.wampserver.com/read.php?2,66196,66233#REPLY

How do I get the current mouse screen coordinates in WPF?

Mouse.GetPosition(mWindow) gives you the mouse position relative to the parameter of your choice. mWindow.PointToScreen() convert the position to a point relative to the screen.

So mWindow.PointToScreen(Mouse.GetPosition(mWindow)) gives you the mouse position relative to the screen, assuming that mWindow is a window(actually, any class derived from System.Windows.Media.Visual will have this function), if you are using this inside a WPF window class, this should work.

Oracle: Call stored procedure inside the package

You're nearly there, just take out the EXECUTE:

DECLARE
  procId NUMBER;

BEGIN
  PKG1.INIT(1143824, 0, procId);
  DBMS_OUTPUT.PUT_LINE(procId);
END;

Remove non-utf8 characters from string

How about iconv:

http://php.net/manual/en/function.iconv.php

Haven't used it inside PHP itself but its always performed well for me on the command line. You can get it to substitute invalid characters.

laravel 5.3 new Auth::routes()

Here's Laravel 5.7, Laravel 5.8, Laravel 6.0, Laravel 7.0, and Laravel 8.0 (note a minor bc change in 6.0 to the email verification route).

// Authentication Routes...
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');

// Registration Routes...
Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController@register');

// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset')->name('password.update');

// Confirm Password (added in v6.2)
Route::get('password/confirm', 'Auth\ConfirmPasswordController@showConfirmForm')->name('password.confirm');
Route::post('password/confirm', 'Auth\ConfirmPasswordController@confirm');

// Email Verification Routes...
Route::get('email/verify', 'Auth\VerificationController@show')->name('verification.notice');
Route::get('email/verify/{id}/{hash}', 'Auth\VerificationController@verify')->name('verification.verify'); // v6.x
/* Route::get('email/verify/{id}', 'Auth\VerificationController@verify')->name('verification.verify'); // v5.x */
Route::get('email/resend', 'Auth\VerificationController@resend')->name('verification.resend');

You can verify these routes here:

100% width Twitter Bootstrap 3 template

You're right using div.container-fluid and you also need a div.row child. Then, the content must be placed inside without any grid columns. If you have a look at the docs you can find this text:

  • Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper alignment and padding.
  • Use rows to create horizontal groups of columns.

Not using grid columns it's ok as stated here:

  • Content should be placed within columns, and only columns may be immediate children of rows.

And looking at this example, you can read this text:

Full width, single column: No grid classes are necessary for full-width elements.

Here's a live example showing some elements using the correct layout. This way you don't need any custom CSS or hack.

understanding private setters

Credits to https://www.dotnetperls.com/property.

private setters are same as read-only fields. They can only be set in constructor. If you try to set from outside you get compile time error.

public class MyClass
{
    public MyClass()
    {
        // Set the private property.
        this.Name = "Sample Name from Inside";
    }
     public MyClass(string name)
    {
        // Set the private property.
        this.Name = name;
    }
    string _name;
    public string Name
    {
        get
        {
            return this._name;
        }
        private set
        {
            // Can only be called in this class.
            this._name = value;
        }
    }
}

class Program
{
    static void Main()
    {
        MyClass mc = new MyClass();
        Console.WriteLine(mc.name);

        MyClass mc2 = new MyClass("Sample Name from Outside");
        Console.WriteLine(mc2.name);
    }
}

Please see below screen shot when I tried to set it from outside of the class.

enter image description here

Call and receive output from Python script in Java?

I met the same problem before, also read the answers here, but doesn't found any satisfy solution can balance the compatibility, performance and well format output, the Jython can't work with extend C packages and slower than CPython. So finally I decided to invent the wheel myself, it took my 5 nights, I hope it can help you too: jpserve(https://github.com/johnhuang-cn/jpserve).

JPserve provides a simple way to call Python and exchange the result by well format JSON, few performance loss. The following is the sample code.

At first, start jpserve on Python side

>>> from jpserve.jpserve import JPServe
>>> serve = JPServe(("localhost", 8888))
>>> serve.start()

INFO:JPServe:JPServe starting...
INFO:JPServe:JPServe listening in localhost 8888

Then call Python from JAVA side:

PyServeContext.init("localhost", 8888);
PyExecutor executor = PyServeContext.getExecutor();
script = "a = 2\n"
    + "b = 3\n"
    + "_result_ = a * b";

PyResult rs = executor.exec(script);
System.out.println("Result: " + rs.getResult());

---
Result: 6

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

In my case all Internet access must run through a proxy and npm was not configured with the proxy to reach http://registry.npmjs.org.

I ran npm install --log-level verbose to get more information and saw that the response had HTML stating I was not authenticated with the proxy.

Running the following fixed it (replacing below with your username/password/proxy address:

npm config set proxy 'username:[email protected]'
npm config set https-proxy 'username:[email protected]'

I do not advise putting the password in raw text instead using something like cntlm to set up a local proxy that delegates to the real proxy.

How to call a function from another controller in angularjs?

You may use events to provide your data. Code like that:

app.controller('One', ['$scope', function ($scope) {
         $scope.parentmethod=function(){
                 $scope.$emit('one', res);// res - your data
         }
    }]);
    app.controller('two', ['$scope', function ($scope) {
         $scope.$on('updateMiniBasket', function (event, data) {
                ...
         });             
    }]);

Batch File: ( was unexpected at this time

Oh, dear. A few little problems...

As pointed out by others, you need to quote to protect against empty/space-containing entries, and use the !delayed_expansion! facility.

Two other matters of which you should be aware:

First, set/p will assign a user-input value to a variable. That's not news - but the gotcha is that pressing enter in response will leave the variable UNCHANGED - it will not ASSIGN a zero-length string to the variable (hence deleting the variable from the environment.) The safe method is:

 set "var="
 set /p var=

That is, of course, if you don't WANT enter to repeat the existing value.
Another useful form is

 set "var=default"
 set /p var=

or

 set "var=default"
 set /p "var=[%var%]"

(which prompts with the default value; !var! if in a block statement with delayedexpansion)

Second issue is that on some Windows versions (although W7 appears to "fix" this issue) ANY label - including a :: comment (which is a broken-label) will terminate any 'block' - that is, parenthesised compound statement)

jquery - is not a function error

This problem is "best" solved by using an anonymous function to pass-in the jQuery object thusly:

The Anonymous Function Looks Like:

<script type="text/javascript">
    (function($) {
        // You pass-in jQuery and then alias it with the $-sign
        // So your internal code doesn't change
    })(jQuery);
</script>

This is JavaScript's method of implementing (poor man's) 'Dependency Injection' when used alongside things like the 'Module Pattern'.

So Your Code Would Look Like:
Of course, you might want to make some changes to your internal code now, but you get the idea.

<script type="text/javascript">
    (function($) {
        $.fn.pluginbutton = function(options) {
            myoptions = $.extend({ left: true });
            return this.each(function() {
                var focus = false;
                if (focus === false) {
                    this.hover(function() {
                        this.animate({ backgroundPosition: "0 -30px" }, { duration: 0 });
                        this.removeClass('VBfocus').addClass('VBHover');
                    }, function() {
                        this.animate({ backgroundPosition: "0 0" }, { duration: 0 });
                        this.removeClass('VBfocus').removeClass('VBHover');
                    });
                }
                this.mousedown(function() {
                    focus = true
                    this.animate({ backgroundPosition: "0 30px" }, { duration: 0 });
                    this.addClass('VBfocus').removeClass('VBHover');
                }, function() {
                    focus = false;
                    this.animate({ backgroundPosition: "0 0" }, { duration: 0 });
                    this.removeClass('VBfocus').addClass('VBHover');
                });
            });
        }
    })(jQuery);
</script>

Disabling and enabling a html input button

Stick to php...

Why not only allow the button to appear once an above criteria is met.

<?
if (whatever == something) {
    $display = '<input id="Button" type="button" value="+" style="background-color:grey" onclick="Me();"/>';
    return $display;
}
?>

Map a network drive to be used by a service

A better way would be to use a symbolic link using mklink.exe. You can just create a link in the file system that any app can use. See http://en.wikipedia.org/wiki/NTFS_symbolic_link.

sudo: npm: command not found

For debian after installing node enter

curl -k -O -L https://npmjs.org/install.sh    
ln -s /usr/bin/nodejs /usr/bin/node  
sh install.sh

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

file_get_contents(php://input) - gets the raw POST data and you need to use this when you write APIs and need XML/JSON/... input that cannot be decoded to $_POST by PHP some example :

send by post JSON string

<input type="button" value= "click" onclick="fn()">
<script>
 function fn(){


    var js_obj = {plugin: 'jquery-json', version: 2.3};

    var encoded = JSON.stringify( js_obj );

var data= encoded


    $.ajax({
  type: "POST",
  url: '1.php',
  data: data,
  success: function(data){
    console.log(data);
  }

});

    }
</script>

1.php

//print_r($_POST); //empty!!! don't work ... 
var_dump( file_get_contents('php://input'));

Find mouse position relative to element

I had to get the cursor position inside a very wide div with scrollbar. The objective was to drag elements to any position of the div.

To get the mouse position on a far away position deep in the scrolling.

$('.canvas').on('mousemove', function(e){
    $(dragElement).parent().css('top', e.currentTarget.scrollTop + e.originalEvent.clientY );
    $(dragElement).parent().css('left', e.currentTarget.scrollLeft + e.originalEvent.clientX )
});

How do Python's any and all functions work?

I know this is old, but I thought it might be helpful to show what these functions look like in code. This really illustrates the logic, better than text or a table IMO. In reality they are implemented in C rather than pure Python, but these are equivalent.

def any(iterable):
    for item in iterable:
        if item:
            return True
    return False

def all(iterable):
    for item in iterable:
        if not item:
            return False
    return True

In particular, you can see that the result for empty iterables is just the natural result, not a special case. You can also see the short-circuiting behaviour; it would actually be more work for there not to be short-circuiting.

When Guido van Rossum (the creator of Python) first proposed adding any() and all(), he explained them by just posting exactly the above snippets of code.

What is the opposite of :hover (on mouse leave)?

Put your duration time in the non-hover selection:

li a {
  background-color: #111;
  transition:1s;
}

li a:hover {
  padding:19px;
}

jQuery 'input' event

Occurs when the text content of an element is changed through the user interface.

It's not quite an alias for keyup because keyup will fire even if the key does nothing (for example: pressing and then releasing the Control key will trigger a keyup event).

A good way to think about it is like this: it's an event that triggers whenever the input changes. This includes -- but is not limited to -- pressing keys which modify the input (so, for example, Ctrl by itself will not trigger the event, but Ctrl-V to paste some text will), selecting an auto-completion option, Linux-style middle-click paste, drag-and-drop, and lots of other things.

See this page and the comments on this answer for more details.

AppFabric installation failed because installer MSI returned with error code : 1603

I finally made it. I was able to install AppFabric for Win Server 2012 R2. I am not really sure what exact change made it worked. I saw and tried many many solutions from various websites but above solution of making changes to Registry - 'HKEY_CLASSES_ROOT'worked (please think twice before making changes to Registry on production environment - this was my demo environment so I just went ahead); I changed the temporary folder path but it did not worked first time. Then I deleted the registry entry and then uninstalled AppFabric 1.1 pre-installed instance from Control panel. Then I tried Installation and it worked. This also restored the Registry entry.

How to change or add theme to Android Studio?

File->Settings->Appearance & Behavior-> Appearance and In theme select Darcula and apply dark background theme editor.

How to call execl() in C with the proper arguments?

execl("/home/vlc", 
  "/home/vlc", "/home/my movies/the movie i want to see.mkv", 
  (char*) NULL);

You need to specify all arguments, included argv[0] which isn't taken from the executable.

Also make sure the final NULL gets cast to char*.

Details are here: http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html

How can I consume a WSDL (SOAP) web service in Python?

Right now (as of 2008), all the SOAP libraries available for Python suck. I recommend avoiding SOAP if possible. The last time we where forced to use a SOAP web service from Python, we wrote a wrapper in C# that handled the SOAP on one side and spoke COM out the other.

How do I cancel an HTTP fetch() request?

https://developers.google.com/web/updates/2017/09/abortable-fetch

https://dom.spec.whatwg.org/#aborting-ongoing-activities

// setup AbortController
const controller = new AbortController();
// signal to pass to fetch
const signal = controller.signal;

// fetch as usual
fetch(url, { signal }).then(response => {
  ...
}).catch(e => {
  // catch the abort if you like
  if (e.name === 'AbortError') {
    ...
  }
});

// when you want to abort
controller.abort();

works in edge 16 (2017-10-17), firefox 57 (2017-11-14), desktop safari 11.1 (2018-03-29), ios safari 11.4 (2018-03-29), chrome 67 (2018-05-29), and later.


on older browsers, you can use github's whatwg-fetch polyfill and AbortController polyfill. you can detect older browsers and use the polyfills conditionally, too:

import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'
import {fetch} from 'whatwg-fetch'

// use native browser implementation if it supports aborting
const abortableFetch = ('signal' in new Request('')) ? window.fetch : fetch

Kotlin Ternary Conditional Operator

Java's equivalent of ternary operator

a ? b : c

is a simple IF in Kotlin in one line

if(a) b else c

there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.

https://kotlinlang.org/docs/reference/control-flow.html#if-expression


Special case for Null comparison

you can use the Elvis operator

if ( a != null ) a else b
// equivalent to
a ?: b

Store a closure as a variable in Swift

In Swift 4 and 5. I created a closure variable containing two parameter dictionary and bool.

 var completionHandler:([String:Any], Bool)->Void = { dict, success  in
    if success {
      print(dict)
    }
  }

Calling the closure variable

self.completionHandler(["name":"Gurjinder singh"],true)

DISTINCT clause with WHERE

SELECT DISTINCT dbo.Table.Email,dbo.Table.FirstName dbo.Table.LastName, dbo.Table.DateOfBirth (etc) FROM dbo.Table.Contacts WHERE Email = 'name@email';

How to filter a RecyclerView with a SearchView

This is my take on expanding @klimat answer to not losing filtering animation.

public void filter(String query){
    int completeListIndex = 0;
    int filteredListIndex = 0;
    while (completeListIndex < completeList.size()){
        Movie item = completeList.get(completeListIndex);
        if(item.getName().toLowerCase().contains(query)){
            if(filteredListIndex < filteredList.size()) {
                Movie filter = filteredList.get(filteredListIndex);
                if (!item.getName().equals(filter.getName())) {
                    filteredList.add(filteredListIndex, item);
                    notifyItemInserted(filteredListIndex);
                }
            }else{
                filteredList.add(filteredListIndex, item);
                notifyItemInserted(filteredListIndex);
            }
            filteredListIndex++;
        }
        else if(filteredListIndex < filteredList.size()){
            Movie filter = filteredList.get(filteredListIndex);
            if (item.getName().equals(filter.getName())) {
                filteredList.remove(filteredListIndex);
                notifyItemRemoved(filteredListIndex);
            }
        }
        completeListIndex++;
    }
}

Basically what it does is looking through a complete list and adding/removing items to a filtered list one by one.

adb connection over tcp not working now

Step 1 . Go to Androidsdk\platform-tools on PC/Laptop

Step 2 :

Connect your device via USB and run:

adb kill-server

then run

adb tcpip 5555

you will see below message...

daemon not running. starting it now on port 5037 * daemon started successfully * restarting in TCP mode port: 5555

Step3:

Now open new CMD window,

Go to Androidsdk\platform-tools

Now run

adb connect xx.xx.xx.xx:5555 (xx.xx.xx.xx is device IP)

Step4: Disconnect your device from USB and it will work as if connected from your Android studio.

Add "Are you sure?" to my excel button, how can I?

On your existing button code, simply insert this line before the procedure:

If MsgBox("This will erase everything! Are you sure?", vbYesNo) = vbNo Then Exit Sub

This will force it to quit if the user presses no.

Running Java Program from Command Line Linux

Guys let's understand the syntax of it.

  1. If class file is present in the Current Dir.

    java -cp . fileName

  2. If class file is present within the Dir. Go to the Parent Dir and enter below cmd.

    java -cp . dir1.dir2.dir3.fileName

  3. If there is a dependency on external jars then,

    java -cp .:./jarName1:./jarName2 fileName

    Hope this helps.

SQLAlchemy: What's the difference between flush() and commit()?

Why flush if you can commit?

As someone new to working with databases and sqlalchemy, the previous answers - that flush() sends SQL statements to the DB and commit() persists them - were not clear to me. The definitions make sense but it isn't immediately clear from the definitions why you would use a flush instead of just committing.

Since a commit always flushes (https://docs.sqlalchemy.org/en/13/orm/session_basics.html#committing) these sound really similar. I think the big issue to highlight is that a flush is not permanent and can be undone, whereas a commit is permanent, in the sense that you can't ask the database to undo the last commit (I think)

@snapshoe highlights that if you want to query the database and get results that include newly added objects, you need to have flushed first (or committed, which will flush for you). Perhaps this is useful for some people although I'm not sure why you would want to flush rather than commit (other than the trivial answer that it can be undone).

In another example I was syncing documents between a local DB and a remote server, and if the user decided to cancel, all adds/updates/deletes should be undone (i.e. no partial sync, only a full sync). When updating a single document I've decided to simply delete the old row and add the updated version from the remote server. It turns out that due to the way sqlalchemy is written, order of operations when committing is not guaranteed. This resulted in adding a duplicate version (before attempting to delete the old one), which resulted in the DB failing a unique constraint. To get around this I used flush() so that order was maintained, but I could still undo if later the sync process failed.

See my post on this at: Is there any order for add versus delete when committing in sqlalchemy

Similarly, someone wanted to know whether add order is maintained when committing, i.e. if I add object1 then add object2, does object1 get added to the database before object2 Does SQLAlchemy save order when adding objects to session?

Again, here presumably the use of a flush() would ensure the desired behavior. So in summary, one use for flush is to provide order guarantees (I think), again while still allowing yourself an "undo" option that commit does not provide.

Autoflush and Autocommit

Note, autoflush can be used to ensure queries act on an updated database as sqlalchemy will flush before executing the query. https://docs.sqlalchemy.org/en/13/orm/session_api.html#sqlalchemy.orm.session.Session.params.autoflush

Autocommit is something else that I don't completely understand but it sounds like its use is discouraged: https://docs.sqlalchemy.org/en/13/orm/session_api.html#sqlalchemy.orm.session.Session.params.autocommit

Memory Usage

Now the original question actually wanted to know about the impact of flush vs. commit for memory purposes. As the ability to persist or not is something the database offers (I think), simply flushing should be sufficient to offload to the database - although committing shouldn't hurt (actually probably helps - see below) if you don't care about undoing.

sqlalchemy uses weak referencing for objects that have been flushed: https://docs.sqlalchemy.org/en/13/orm/session_state_management.html#session-referencing-behavior

This means if you don't have an object explicitly held onto somewhere, like in a list or dict, sqlalchemy won't keep it in memory.

However, then you have the database side of things to worry about. Presumably flushing without committing comes with some memory penalty to maintain the transaction. Again, I'm new to this but here's a link that seems to suggest exactly this: https://stackoverflow.com/a/15305650/764365

In other words, commits should reduce memory usage, although presumably there is a trade-off between memory and performance here. In other words, you probably don't want to commit every single database change, one at a time (for performance reasons), but waiting too long will increase memory usage.

Angular2 set value for formGroup

Yes you can use setValue to set value for edit/update purpose.

this.personalform.setValue({
      name: items.name,
      address: {
        city: items.address.city,
        country: items.address.country
      }
    });

You can refer http://musttoknow.com/use-angular-reactive-form-addinsert-update-data-using-setvalue-setpatch/ to understand how to use Reactive forms for add/edit feature by using setValue. It saved my time

EnterKey to press button in VBA Userform

You could also use the TextBox's On Key Press event handler:

'Keycode for "Enter" is 13
Private Sub TextBox1_KeyDown(KeyCode As Integer, Shift As Integer)
    If KeyCode = 13 Then
         Logincode_Click
    End If
End Sub

Textbox1 is an example. Make sure you choose the textbox you want to refer to and also Logincode_Click is an example sub which you call (run) with this code. Make sure you refer to your preferred sub

concat scope variables into string in angular directive expression

I've created a working CodePen example demonstrating how to do this.

Relevant HTML:

<section ng-app="app" ng-controller="MainCtrl">
  <a href="#" ng-click="doSomething('#/path/{{obj.val1}}/{{obj.val2}}')">Click Me</a><br>
  debug: {{debug.val}}
</section>

Relevant javascript:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.obj = {
    val1: 'hello',
    val2: 'world'
  };

  $scope.debug = {
    val: ''
  };

  $scope.doSomething = function(input) {
    $scope.debug.val = input;
  };
});

How to import and use image in a Vue single file component?

It is heavily suggested to make use of webpack when importing pictures from assets and in general for optimisation and pathing purposes

If you wish to load them by webpack you can simply use :src='require('path/to/file')' Make sure you use : otherwise it won't execute the require statement as Javascript.

In typescript you can do almost the exact same operation: :src="require('@/assets/image.png')"

Why the following is generally considered bad practice:

<template>
  <div id="app">
    <img src="./assets/logo.png">
  </div>
</template>

<script>
export default {
}
</script>

<style lang="scss">
</style> 

When building using the Vue cli, webpack is not able to ensure that the assets file will maintain a structure that follows the relative importing. This is due to webpack trying to optimize and chunk items appearing inside of the assets folder. If you wish to use a relative import you should do so from within the static folder and use: <img src="./static/logo.png">

MySQL add days to a date

update tablename set coldate=DATE_ADD(coldate, INTERVAL 2 DAY)

Conda update failed: SSL error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed

according to @jreback here https://github.com/conda/conda/issues/1166

conda config --set ssl_verify false 

will turn off this feature, e.g. here

jquery get all input from specific form

To iterate through all the inputs in a form you can do this:

$("form#formID :input").each(function(){
 var input = $(this); // This is the jquery object of the input, do what you will
});

This uses the jquery :input selector to get ALL types of inputs, if you just want text you can do :

$("form#formID input[type=text]")//...

etc.

How do I split an int into its digits?

A simple answer to this question can be:

  1. Read A Number "n" From The User.
  2. Using While Loop Make Sure Its Not Zero.
  3. Take modulus 10 Of The Number "n"..This Will Give You Its Last Digit.
  4. Then Divide The Number "n" By 10..This Removes The Last Digit of Number "n" since in int decimal part is omitted.
  5. Display Out The Number.

I Think It Will Help. I Used Simple Code Like:

#include <iostream>
using namespace std;
int main()
{int n,r;

    cout<<"Enter Your Number:";
    cin>>n;


    while(n!=0)
    {
               r=n%10;
               n=n/10;

               cout<<r;
    }
    cout<<endl;

    system("PAUSE");
    return 0;
}

Slide div left/right using jQuery

_x000D_
_x000D_
$(document).ready(function(){_x000D_
$("#left").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#left').hide("slide", { direction: "left" }, 500, function () {_x000D_
            $('#right').show("slide", { direction: "right" }, 500);_x000D_
        });_x000D_
    });_x000D_
    $("#right").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#right').hide("slide", { direction: "right" }, 500, function () {_x000D_
            $('#left').show("slide", { direction: "left" }, 500);_x000D_
        });_x000D_
    });_x000D_
_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
_x000D_
<div style="height:100%;width:100%;background:cyan" id="left">_x000D_
<h1>Hello im going left to hide and will comeback from left to show</h1>_x000D_
</div>_x000D_
<div style="height:100%;width:100%;background:blue;display:none" id="right">_x000D_
<h1>Hello im coming from right to sho and will go back to right to hide</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

$("#btnOpenEditing").off('click');
$("#btnOpenEditing").on('click', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('#mappingModel').hide("slide", { direction: "right" }, 500, function () {
        $('#fsEditWindow').show("slide", { direction: "left" }, 500);
    });
});

It will work like charm take a look at the demo.

How to keep the console window open in Visual C++?

just add system("pause") at the end of the code before return 0 like this

#include <stdlib.h>

int main()
{
    //some code goes here
    system("pause")
    return 0;
}

Get absolute path of initially run script

If you're looking for the absolute path relative to the server root, I've found that this works well:

$_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['SCRIPT_NAME'])

Is there a "not equal" operator in Python?

You can simply do:

if hi == hi:
    print "hi"
elif hi != bye:
     print "no hi"

Insert a line at specific line number with sed or awk

sed -i "" -e $'4 a\\n''Project_Name=sowstest' start

  • This line works fine in macOS

How to use vagrant in a proxy environment?

On a Windows host

open a CMD prompt;

set HTTP_PROXY=http://proxy.yourcorp.com:80
set HTTPS_PROXY=https://proxy.yourcorp.com:443

Substitute the address and port in the above snippets to whatever is appropriate for your situation. The above will remain set until you close the CMD prompt. If it works for you, consider adding them permanently to your environment variables so that you won't have to set them every time you open a new CMD prompt.

using if else with eval in aspx page

If you are trying to bind is a Model class, you can add a new readonly property to it like:

public string FormattedPercentage
{
    get
    {
        If(this.Percentage < 50)
            return "0 %";
        else 
            return string.Format("{0} %", this.Percentage)        
     }
}

Otherwise you can use Andrei's or kostas ch. suggestions if you cannot modify the class itself

Detect Click into Iframe using JavaScript

Based on Mohammed Radwan's answer I came up with the following jQuery solution. Basically what it does is keep track of what iFrame people are hovering. Then if the window blurs that most likely means the user clicked the iframe banner.

the iframe should be put in a div with an id, to make sure you know which iframe the user clicked on:

<div class='banner' bannerid='yyy'>
    <iframe src='http://somedomain.com/whatever.html'></iframe>
<div>

so:

$(document).ready( function() {
    var overiFrame = -1;
    $('iframe').hover( function() {
        overiFrame = $(this).closest('.banner').attr('bannerid');
    }, function() {
        overiFrame = -1
    });

... this keeps overiFrame at -1 when no iFrames are hovered, or the 'bannerid' set in the wrapping div when an iframe is hovered. All you have to do is check if 'overiFrame' is set when the window blurs, like so: ...

    $(window).blur( function() {
        if( overiFrame != -1 )
            $.post('log.php', {id:overiFrame}); /* example, do your stats here */
    });
});

Very elegant solution with a minor downside: if a user presses ALT-F4 when hovering the mouse over an iFrame it will log it as a click. This only happened in FireFox though, IE, Chrome and Safari didn't register it.

Thanks again Mohammed, very useful solution!

DateTime.Now.ToShortDateString(); replace month and day

Little addition to Jason's answer:

  1. The ToShortDateString() is culture-sensitive.

From MSDN:

The string returned by the ToShortDateString method is culture-sensitive. It reflects the pattern defined by the current culture's DateTimeFormatInfo object. For example, for the en-US culture, the standard short date pattern is "M/d/yyyy"; for the de-DE culture, it is "dd.MM.yyyy"; for the ja-JP culture, it is "yyyy/M/d". The specific format string on a particular computer can also be customized so that it differs from the standard short date format string.

That's mean it's better to use the ToString() method and define format explicitly (as Jason said). Although if this string appeas in UI the ToShortDateString() is a good solution because it returns string which is familiar to a user.

  1. If you need just today's date you can use DateTime.Today.

Sending email from Azure

Sending from a third party SMTP isn't restricted by or specific to Azure. Using System.Net.Mail, create your message, configure your SMTP client, send the email:

// create the message
var msg = new MailMessage();
msg.From = new MailAddress("[email protected]"); 
msg.To.Add(strTo); 
msg.Subject = strSubject; 
msg.IsBodyHtml = true; 
msg.Body = strMessage;

// configure the smtp server
var smtp = new SmtpClient("YourSMTPServer"); 
var = new System.Net.NetworkCredential("YourSMTPServerUserName", "YourSMTPServerPassword");

// send the message
smtp.Send(msg); 

UPDATE: I added a post on Medium about how to do this with an Azure Function - https://medium.com/@viperguynaz/building-a-serverless-contact-form-f8f0bff46ba9

What does MVW stand for?

It stands indeed for whatever, as in whatever works for you

MVC vs MVVM vs MVP. What a controversial topic that many developers can spend hours and hours debating and arguing about.

For several years +AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings and api improvements, it's now closer to MVVM – the $scope object could be considered the ViewModel that is being decorated by a function that we call a Controller.

Being able to categorize a framework and put it into one of the MV* buckets has some advantages. It can help developers get more comfortable with its apis by making it easier to create a mental model that represents the application that is being built with the framework. It can also help to establish terminology that is used by developers.

Having said, I'd rather see developers build kick-ass apps that are well-designed and follow separation of concerns, than see them waste time arguing about MV* nonsense. And for this reason, I hereby declare AngularJS to be MVW framework - Model-View-Whatever. Where Whatever stands for "whatever works for you".

Angular gives you a lot of flexibility to nicely separate presentation logic from business logic and presentation state. Please use it fuel your productivity and application maintainability rather than heated discussions about things that at the end of the day don't matter that much.

What is the most efficient/quickest way to loop through rows in VBA (excel)?

If you are just looping through 10k rows in column A, then dump the row into a variant array and then loop through that.

You can then either add the elements to a new array (while adding rows when needed) and using Transpose() to put the array onto your range in one move, or you can use your iterator variable to track which row you are on and add rows that way.

Dim i As Long
Dim varray As Variant

varray = Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row).Value

For i = 1 To UBound(varray, 1)
    ' do stuff to varray(i, 1)
Next

Here is an example of how you could add rows after evaluating each cell. This example just inserts a row after every row that has the word "foo" in column A. Not that the "+2" is added to the variable i during the insert since we are starting on A2. It would be +1 if we were starting our array with A1.

Sub test()

Dim varray As Variant
Dim i As Long

varray = Range("A2:A10").Value

'must step back or it'll be infinite loop
For i = UBound(varray, 1) To LBound(varray, 1) Step -1
    'do your logic and evaluation here
    If varray(i, 1) = "foo" Then
       'not how to offset the i variable 
       Range("A" & i + 2).EntireRow.Insert
    End If
Next

End Sub

How can I see what I am about to push with git?

You probably want to run git difftool origin/master.... that should show the unified diff of what is on your current branch that is not on the origin/master branch yet and display it in the graphical diff tool of your choice. To be most up-to-date, run git fetch first.

How to print color in console using System.out.println?

If you use Kotlin (which works seamlessly with Java), you can make such an enum:

enum class AnsiColor(private val colorNumber: Byte) {
    BLACK(0), RED(1), GREEN(2), YELLOW(3), BLUE(4), MAGENTA(5), CYAN(6), WHITE(7);

    companion object {
        private const val prefix = "\u001B"
        const val RESET = "$prefix[0m"
        private val isCompatible = "win" !in System.getProperty("os.name").toLowerCase()
    }

    val regular get() = if (isCompatible) "$prefix[0;3${colorNumber}m" else ""
    val bold get() = if (isCompatible) "$prefix[1;3${colorNumber}m" else ""
    val underline get() = if (isCompatible) "$prefix[4;3${colorNumber}m" else ""
    val background get() = if (isCompatible) "$prefix[4${colorNumber}m" else ""
    val highIntensity get() = if (isCompatible) "$prefix[0;9${colorNumber}m" else ""
    val boldHighIntensity get() = if (isCompatible) "$prefix[1;9${colorNumber}m" else ""
    val backgroundHighIntensity get() = if (isCompatible) "$prefix[0;10${colorNumber}m" else ""
}

And then use is as such: (code below showcases the different styles for all colors)

val sampleText = "This is a sample text"
enumValues<AnsiColor>().forEach { ansiColor ->
    println("${ansiColor.regular}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.bold}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.underline}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.background}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.highIntensity}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.boldHighIntensity}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.backgroundHighIntensity}$sampleText${AnsiColor.RESET}")
}

If running on Windows where these ANSI codes are not supported, the isCompatible check avoids issues by replacing the codes with empty string.

Subversion stuck due to "previous operation has not finished"?

I had taken .svn folder from my fellow developer and replaced my .svn folder with this. It worked for me. Don't know what may be other consequences!

How can I remove all objects but one from the workspace in R?

let's think in different way, what if we wanna remove a group? try this,

 rm(list=ls()[grep("xxx",ls())]) 

I personally don't like too many tables, variables on my screen, yet I can't avoid using them. So I name the temporary things starting with "xxx", so I can remove them after it is no longer used.

Django Admin - change header 'Django administration' text

Since I only use admin interface in my app, I put this in the admin.py :

admin.site.site_header = 'My administration'

Install GD library and freetype on Linux

Installing GD :

For CentOS / RedHat / Fedora :

sudo yum install php-gd

For Debian/ubuntu :

sudo apt-get install php5-gd

Installing freetype :

For CentOS / RedHat / Fedora :

sudo yum install freetype*

For Debian/ubuntu :

sudo apt-get install freetype*

Don't forget to restart apache after that (if you are using apache):

CentOS / RedHat / Fedora :

sudo /etc/init.d/httpd restart

Or

sudo service httpd restart

Debian/ubuntu :

sudo /etc/init.d/apache2 restart

Or

sudo service apache2 restart

Binding objects defined in code-behind

That's my way to bind to code behind (see property DataTemplateSelector)

public partial class MainWindow : Window
{
  public MainWindow()
  {
    this.DataTemplateSelector = new MyDataTemplateSelector();

    InitializeComponent();

    // ... more initializations ...
  }

  public DataTemplateSelector DataTemplateSelector { get; }

  // ... more code stuff ...
}

In XAML will referenced by RelativeSource via Ancestors up to containing Window, so I'm at my Window class and use the property via Path declaration:

<GridViewColumn Header="Value(s)"
                CellTemplateSelector="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataTemplateSelector}"/>

Setting of property DataTemplateSelector before call InitializeComponent depends on missing implementation of IPropertyChanged or use of implementation with DependencyProperty so no communication run on change of property DataTemplateSelector.

div inside table

You can't put a div directly inside a table, like this:

<!-- INVALID -->
<table>
  <div>
    Hello World
  </div>
</table>

Putting a div inside a td or th element is fine, however:

<!-- VALID -->
<table>
  <tr>
    <td>
      <div>
        Hello World
      </div>
    </td>
  </tr>
</table>

VS Code - Search for text in all files in a directory

What is NOT so obvious is that you can use the following pattern to recursively search

./src/**/*.html

so perhaps leave the following as the default for most of your typical searches to remind that there is such a thing

./src/**/

For example I was after an attribute for left-right justify/docking content, I could not remember except "start" so I did the following search which reveals to me "item-start"

enter image description here

This fixed my layout to enter image description here

Instead of enter image description here

Here is where "item-sart" goes in the template. enter image description here

Seeing the console's output in Visual Studio 2010?

Press Ctrl + F5 to run the program instead of F5.

How to create a label inside an <input> element?

I think its good to keep the Label and not to use placeholder as mentioned above. Its good for UX as explain here: https://www.smashingmagazine.com/2018/03/ux-contact-forms-essentials-conversions/

Here example with Label inside Input fields: codepen.io/jdax/pen/mEBJNa

Disable PHP in directory (including all sub-directories) with .htaccess

This will display the source code instead of executing it:

<VirtualHost *>
    ServerName sourcecode.testserver.me
    DocumentRoot /var/www/example
    AddType text/plain php
</VirtualHost>

I used it once to enable other co-worker to have read access to the source code from the local network (just a quick and dirty alternative).

WARNING !:

As Dan pointed it out sometime ago, this method should never be used in production. Please follow the accepted answer as it blocks any attempt to execute or display php files.

If you want users to share php files (and let others to display the source code), there are better ways to do it, like git, wiki, etc.

This method should be avoided! (you have been warned. Left it here for educational purposes)

mysqli::mysqli(): (HY000/2002): Can't connect to local MySQL server through socket 'MySQL' (2)

If it's a PHP issue, you could simply alter the configuration file php.ini wherever it's located and update the settings for PORT/SOCKET-PATH etc to make it connect to the server.

In my case, I opened the file php.ini and did

mysql.default_socket = /var/run/mysqld/mysqld.sock
mysqli.default_socket = /var/run/mysqld/mysqld.sock

And it worked straight away. I have to admit, I took hint from the accepted answer by @Joni

Storing database records into array

$memberId =$_SESSION['TWILLO']['Id'];

    $QueryServer=mysql_query("select * from smtp_server where memberId='".$memberId."'");
    $data = array();
    while($ser=mysql_fetch_assoc($QueryServer))
    {

     $data[$ser['Id']] =array('ServerName','ServerPort','Server_limit','email','password','status');

    }

How can I create an Asynchronous function in Javascript?

Edit: I totally misunderstood the question. In the browser, I would use setTimeout. If it was important that it ran in another thread, I would use Web Workers.

Make more than one chart in same IPython Notebook cell

Make the multiple axes first and pass them to the Pandas plot function, like:

fig, axs = plt.subplots(1,2)

df['korisnika'].plot(ax=axs[0])
df['osiguranika'].plot(ax=axs[1])

It still gives you 1 figure, but with two different plots next to each other.

Telling Python to save a .txt file to a certain directory on Windows and Mac

Use os.path.join to combine the path to the Documents directory with the completeName (filename?) supplied by the user.

import os
with open(os.path.join('/path/to/Documents',completeName), "w") as file1:
    toFile = raw_input("Write what you want into the field")
    file1.write(toFile)

If you want the Documents directory to be relative to the user's home directory, you could use something like:

os.path.join(os.path.expanduser('~'),'Documents',completeName)

Others have proposed using os.path.abspath. Note that os.path.abspath does not resolve '~' to the user's home directory:

In [10]: cd /tmp
/tmp

In [11]: os.path.abspath("~")
Out[11]: '/tmp/~'

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

Make Sure the Select Run/Debug Configuration is wear or mobile as per your installation in android studio...

Change Orientation of Bluestack : portrait/landscape mode

The newest version of BlueStacks has the ability to rotate the screen. Open the app and there's an icon in the lower right to rotate.

Removing all non-numeric characters from string in Python

>>> import re
>>> re.sub("[^0-9]", "", "sdkjh987978asd098as0980a98sd")
'987978098098098'

How to Set Variables in a Laravel Blade Template

Since Laravel 5.2.23, you have the @php Blade directive, which you can use inline or as block statement:

@php($old_section = "whatever")

or

@php
    $old_section = "whatever"
@endphp

double free or corruption (!prev) error in c program

I didn't check all the code but my guess is that the error is in the malloc call. You have to replace

 double *ptr = malloc(sizeof(double*) * TIME);

for

 double *ptr = malloc(sizeof(double) * TIME);

since you want to allocate size for a double (not the size of a pointer to a double).

Creating the Singleton design pattern in PHP5

You don't really need to use Singleton pattern because it's considered to be an antipattern. Basically there is a lot of reasons to not to implement this pattern at all. Read this to start with: Best practice on PHP singleton classes.

If after all you still think you need to use Singleton pattern then we could write a class that will allow us to get Singleton functionality by extending our SingletonClassVendor abstract class.

This is what I came with to solve this problem.

<?php
namespace wl;


/**
 * @author DevWL
 * @dosc allows only one instance for each extending class.
 * it acts a litle bit as registry from the SingletonClassVendor abstract class point of view
 * but it provides a valid singleton behaviour for its children classes
 * Be aware, the singleton pattern is consider to be an anti-pattern
 * mostly because it can be hard to debug and it comes with some limitations.
 * In most cases you do not need to use singleton pattern
 * so take a longer moment to think about it before you use it.
 */
abstract class SingletonClassVendor
{
    /**
     *  holds an single instance of the child class
     *
     *  @var array of objects
     */
    protected static $instance = [];

    /**
     *  @desc provides a single slot to hold an instance interchanble between all child classes.
     *  @return object
     */
    public static final function getInstance(){
        $class = get_called_class(); // or get_class(new static());
        if(!isset(self::$instance[$class]) || !self::$instance[$class] instanceof $class){
            self::$instance[$class] = new static(); // create and instance of child class which extends Singleton super class
            echo "new ". $class . PHP_EOL; // remove this line after testing
            return  self::$instance[$class]; // remove this line after testing
        }
        echo "old ". $class . PHP_EOL; // remove this line after testing
        return static::$instance[$class];
    }

    /**
     * Make constructor abstract to force protected implementation of the __constructor() method, so that nobody can call directly "new Class()".
     */
    abstract protected function __construct();

    /**
     * Make clone magic method private, so nobody can clone instance.
     */
    private function __clone() {}

    /**
     * Make sleep magic method private, so nobody can serialize instance.
     */
    private function __sleep() {}

    /**
     * Make wakeup magic method private, so nobody can unserialize instance.
     */
    private function __wakeup() {}

}

Use example:

/**
 * EXAMPLE
 */

/**
 *  @example 1 - Database class by extending SingletonClassVendor abstract class becomes fully functional singleton
 *  __constructor must be set to protected becaouse: 
 *   1 to allow instansiation from parent class 
 *   2 to prevent direct instanciation of object with "new" keword.
 *   3 to meet requierments of SingletonClassVendor abstract class
 */
class Database extends SingletonClassVendor
{
    public $type = "SomeClass";
    protected function __construct(){
        echo "DDDDDDDDD". PHP_EOL; // remove this line after testing
    }
}


/**
 *  @example 2 - Config ...
 */
class Config extends SingletonClassVendor
{
    public $name = "Config";
    protected function __construct(){
        echo "CCCCCCCCCC" . PHP_EOL; // remove this line after testing
    }
}

Just to prove that it works as expected:

/**
 *  TESTING
 */
$bd1 = Database::getInstance(); // new
$bd2 = Database::getInstance(); // old
$bd3 = Config::getInstance(); // new
$bd4 = Config::getInstance(); // old
$bd5 = Config::getInstance(); // old
$bd6 = Database::getInstance(); // old
$bd7 = Database::getInstance(); // old
$bd8 = Config::getInstance(); // old

echo PHP_EOL."COMPARE ALL DATABASE INSTANCES".PHP_EOL;
var_dump($bd1);
echo '$bd1 === $bd2' . ($bd1 === $bd2)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
echo '$bd2 === $bd6' . ($bd2 === $bd6)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
echo '$bd6 === $bd7' . ($bd6 === $bd7)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE

echo PHP_EOL;

echo PHP_EOL."COMPARE ALL CONFIG INSTANCES". PHP_EOL;
var_dump($bd3);
echo '$bd3 === $bd4' . ($bd3 === $bd4)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
echo '$bd4 === $bd5' . ($bd4 === $bd5)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
echo '$bd5 === $bd8' . ($bd5 === $bd8)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE

SFTP file transfer using Java JSch

The most trivial way to upload a file over SFTP with JSch is:

JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();

ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();

sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");

Similarly for a download:

sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");

You may need to deal with UnknownHostKey exception.

How to scan a folder in Java?

You can also use the FileFilter interface to filter out what you want. It is best used when you create an anonymous class that implements it:

import java.io.File;
import java.io.FileFilter;

public class ListFiles {
    public File[] findDirectories(File root) { 
        return root.listFiles(new FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory();
            }});
    }

    public File[] findFiles(File root) {
        return root.listFiles(new FileFilter() {
            public boolean accept(File f) {
                return f.isFile();
            }});
    }
}

redirect while passing arguments

I'm a little confused. "foo.html" is just the name of your template. There's no inherent relationship between the route name "foo" and the template name "foo.html".

To achieve the goal of not rewriting logic code for two different routes, I would just define a function and call that for both routes. I wouldn't use redirect because that actually redirects the client/browser which requires them to load two pages instead of one just to save you some coding time - which seems mean :-P

So maybe:

def super_cool_logic():
    # execute common code here

@app.route("/foo")
def do_foo():
    # do some logic here
    super_cool_logic()
    return render_template("foo.html")

@app.route("/baz")
def do_baz():
    if some_condition:
        return render_template("baz.html")
    else:
        super_cool_logic()
        return render_template("foo.html", messages={"main":"Condition failed on page baz"})

I feel like I'm missing something though and there's a better way to achieve what you're trying to do (I'm not really sure what you're trying to do)

JavaScript/jQuery - How to check if a string contain specific words

You're looking for the indexOf function:

if (str.indexOf("are") >= 0){//Do stuff}

IOError: [Errno 32] Broken pipe: Python

I haven't reproduced the issue, but perhaps this method would solve it: (writing line by line to stdout rather than using print)

import sys
with open('a.txt', 'r') as f1:
    for line in f1:
        sys.stdout.write(line)

You could catch the broken pipe? This writes the file to stdout line by line until the pipe is closed.

import sys, errno
try:
    with open('a.txt', 'r') as f1:
        for line in f1:
            sys.stdout.write(line)
except IOError as e:
    if e.errno == errno.EPIPE:
        # Handle error

You also need to make sure that othercommand is reading from the pipe before it gets too big - https://unix.stackexchange.com/questions/11946/how-big-is-the-pipe-buffer

Google Maps API OVER QUERY LIMIT per second limit


This approach is not correct beacuse of Google Server Overload. For more informations see https://gis.stackexchange.com/questions/15052/how-to-avoid-google-map-geocode-limit#answer-15365


By the way, if you wish to proceed anyway, here you can find a code that let you load multiple markers ajax sourced on google maps avoiding OVER_QUERY_LIMIT error.

I've tested on my onw server and it works!:

var lost_addresses = [];
    geocode_count  = 0;
    resNumber = 0;
    map = new GMaps({
       div: '#gmap_marker',
       lat: 43.921493,
       lng: 12.337646,
    });

function loadMarkerTimeout(timeout) {
    setTimeout(loadMarker, timeout)
}

function loadMarker() { 
    map.setZoom(6);         
    $.ajax({
            url: [Insert here your URL] ,
            type:'POST',
            data: {
                "action":   "loadMarker"
            },
            success:function(result){

                /***************************
                 * Assuming your ajax call
                 * return something like: 
                 *   array(
                 *      'status' => 'success',
                 *      'results'=> $resultsArray
                 *   );
                 **************************/

                var res=JSON.parse(result);
                if(res.status == 'success') {
                    resNumber = res.results.length;
                    //Call the geoCoder function
                    getGeoCodeFor(map, res.results);
                }
            }//success
    });//ajax
};//loadMarker()

$().ready(function(e) {
  loadMarker();
});

//Geocoder function
function getGeoCodeFor(maps, addresses) {
        $.each(addresses, function(i,e){                
                GMaps.geocode({
                    address: e.address,
                    callback: function(results, status) {
                            geocode_count++;        

                            if (status == 'OK') {       

                                //if the element is alreay in the array, remove it
                                lost_addresses = jQuery.grep(lost_addresses, function(value) {
                                    return value != e;
                                });


                                latlng = results[0].geometry.location;
                                map.addMarker({
                                        lat: latlng.lat(),
                                        lng: latlng.lng(),
                                        title: 'MyNewMarker',
                                    });//addMarker
                            } else if (status == 'ZERO_RESULTS') {
                                //alert('Sorry, no results found');
                            } else if(status == 'OVER_QUERY_LIMIT') {

                                //if the element is not in the losts_addresses array, add it! 
                                if( jQuery.inArray(e,lost_addresses) == -1) {
                                    lost_addresses.push(e);
                                }

                            } 

                            if(geocode_count == addresses.length) {
                                //set counter == 0 so it wont's stop next round
                                geocode_count = 0;

                                setTimeout(function() {
                                    getGeoCodeFor(maps, lost_addresses);
                                }, 2500);
                            }
                    }//callback
                });//GeoCode
        });//each
};//getGeoCodeFor()

Example:

_x000D_
_x000D_
map = new GMaps({_x000D_
  div: '#gmap_marker',_x000D_
  lat: 43.921493,_x000D_
  lng: 12.337646,_x000D_
});_x000D_
_x000D_
var jsonData = {  _x000D_
   "status":"success",_x000D_
   "results":[  _x000D_
  {  _x000D_
     "customerId":1,_x000D_
     "address":"Via Italia 43, Milano (MI)",_x000D_
     "customerName":"MyAwesomeCustomer1"_x000D_
  },_x000D_
  {  _x000D_
     "customerId":2,_x000D_
     "address":"Via Roma 10, Roma (RM)",_x000D_
     "customerName":"MyAwesomeCustomer2"_x000D_
  }_x000D_
   ]_x000D_
};_x000D_
   _x000D_
function loadMarkerTimeout(timeout) {_x000D_
  setTimeout(loadMarker, timeout)_x000D_
}_x000D_
_x000D_
function loadMarker() { _x000D_
  map.setZoom(6);_x000D_
 _x000D_
  $.ajax({_x000D_
    url: '/echo/html/',_x000D_
    type: "POST",_x000D_
    data: jsonData,_x000D_
    cache: false,_x000D_
    success:function(result){_x000D_
_x000D_
      var res=JSON.parse(result);_x000D_
      if(res.status == 'success') {_x000D_
        resNumber = res.results.length;_x000D_
        //Call the geoCoder function_x000D_
        getGeoCodeFor(map, res.results);_x000D_
      }_x000D_
    }//success_x000D_
  });//ajax_x000D_
  _x000D_
};//loadMarker()_x000D_
_x000D_
$().ready(function(e) {_x000D_
  loadMarker();_x000D_
});_x000D_
_x000D_
//Geocoder function_x000D_
function getGeoCodeFor(maps, addresses) {_x000D_
  $.each(addresses, function(i,e){    _x000D_
    GMaps.geocode({_x000D_
      address: e.address,_x000D_
      callback: function(results, status) {_x000D_
        geocode_count++;  _x000D_
        _x000D_
        console.log('Id: '+e.customerId+' | Status: '+status);_x000D_
        _x000D_
        if (status == 'OK') {  _x000D_
_x000D_
          //if the element is alreay in the array, remove it_x000D_
          lost_addresses = jQuery.grep(lost_addresses, function(value) {_x000D_
            return value != e;_x000D_
          });_x000D_
_x000D_
_x000D_
          latlng = results[0].geometry.location;_x000D_
          map.addMarker({_x000D_
            lat: latlng.lat(),_x000D_
            lng: latlng.lng(),_x000D_
            title: e.customerName,_x000D_
          });//addMarker_x000D_
        } else if (status == 'ZERO_RESULTS') {_x000D_
          //alert('Sorry, no results found');_x000D_
        } else if(status == 'OVER_QUERY_LIMIT') {_x000D_
_x000D_
          //if the element is not in the losts_addresses array, add it! _x000D_
          if( jQuery.inArray(e,lost_addresses) == -1) {_x000D_
            lost_addresses.push(e);_x000D_
          }_x000D_
_x000D_
        } _x000D_
_x000D_
        if(geocode_count == addresses.length) {_x000D_
          //set counter == 0 so it wont's stop next round_x000D_
          geocode_count = 0;_x000D_
_x000D_
          setTimeout(function() {_x000D_
            getGeoCodeFor(maps, lost_addresses);_x000D_
          }, 2500);_x000D_
        }_x000D_
      }//callback_x000D_
    });//GeoCode_x000D_
  });//each_x000D_
};//getGeoCodeFor()
_x000D_
#gmap_marker {_x000D_
  min-height:250px;_x000D_
  height:100%;_x000D_
  width:100%;_x000D_
  position: relative; _x000D_
  overflow: hidden;_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="http://maps.google.com/maps/api/js" type="text/javascript"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/gmaps.js/0.4.24/gmaps.min.js" type="text/javascript"></script>_x000D_
_x000D_
_x000D_
<div id="gmap_marker"></div> <!-- /#gmap_marker -->
_x000D_
_x000D_
_x000D_

Horizontal scroll on overflow of table

I think your overflow should be on the outer container. You can also explicitly set a min width for the columns. Like this:

.search-table-outter { overflow-x: scroll; }
th, td { min-width: 200px; }

Fiddle: http://jsfiddle.net/5WsEt/

How do I perform a Perl substitution on a string while keeping the original?

Another pre-5.14 solution: http://www.perlmonks.org/?node_id=346719 (see japhy's post)

As his approach uses map, it also works well for arrays, but requires cascading map to produce a temporary array (otherwise the original would be modified):

my @orig = ('this', 'this sucks', 'what is this?');
my @list = map { s/this/that/; $_ } map { $_ } @orig;
# @orig unmodified

Spark: Add column to dataframe conditionally

My bad, I had missed one part of the question.

Best, cleanest way is to use a UDF. Explanation within the code.

// create some example data...BY DataFrame
// note, third record has an empty string
case class Stuff(a:String,b:Int)
val d= sc.parallelize(Seq( ("a",1),("b",2),
     ("",3) ,("d",4)).map { x => Stuff(x._1,x._2)  }).toDF

// now the good stuff.
import org.apache.spark.sql.functions.udf
// function that returns 0 is string empty 
val func = udf( (s:String) => if(s.isEmpty) 0 else 1 )
// create new dataframe with added column named "notempty"
val r = d.select( $"a", $"b", func($"a").as("notempty") )

    scala> r.show
+---+---+--------+
|  a|  b|notempty|
+---+---+--------+
|  a|  1|    1111|
|  b|  2|    1111|
|   |  3|       0|
|  d|  4|    1111|
+---+---+--------+

How to fix "containing working copy admin area is missing" in SVN?

I just did 'svn revert /blabla' and it worked, the folder is back and I can svn delete it

cc1plus: error: unrecognized command line option "-std=c++11" with g++

I also got same error, compiling with -D flag fixed it, Try this:

g++ -Dstd=c++11

How to avoid using Select in Excel VBA

This is an example that will clear the contents of cell "A1" (or more if the selection type is xllastcell, etc.). All done without having to select the cells.

Application.GoTo Reference:=Workbook(WorkbookName).Worksheets(WorksheetName).Range("A1")
Range(Selection,selection(selectiontype)).clearcontents 

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

Regex to validate date format dd/mm/yyyy

"^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.]((19|20)\\d\\d)$"

will validate any date between 1900-2099

What's the difference between HEAD^ and HEAD~ in Git?

Here's a very good explanation taken verbatim from http://www.paulboxley.com/blog/2011/06/git-caret-and-tilde :

ref~ is shorthand for ref~1 and means the commit's first parent. ref~2 means the commit's first parent's first parent. ref~3 means the commit's first parent's first parent's first parent. And so on.

ref^ is shorthand for ref^1 and means the commit's first parent. But where the two differ is that ref^2 means the commit's second parent (remember, commits can have two parents when they are a merge).

The ^ and ~ operators can be combined.

enter image description here

How to count rows with SELECT COUNT(*) with SQLAlchemy?

Query for just a single known column:

session.query(MyTable.col1).count()

Enzyme - How to access and set <input> value?

So lots of different opinions here. The only thing that worked for me was none of the above, it was using input.props().value. I hope that helps.

Mongodb service won't start

I tried deleting the lock file, but the real reason that this happened to me was because I was using ~/data/db as the data directory. Mongo needs an absolute path to the database. Once I changed it to /home//data/db, I was in business.

How to prevent scanf causing a buffer overflow in C?

Most of the time a combination of fgets and sscanf does the job. The other thing would be to write your own parser, if the input is well formatted. Also note your second example needs a bit of modification to be used safely:

#define LENGTH          42
#define str(x)          # x
#define xstr(x)         str(x)

/* ... */ 
int nc = scanf("%"xstr(LENGTH)"[^\n]%*[^\n]", array); 

The above discards the input stream upto but not including the newline (\n) character. You will need to add a getchar() to consume this. Also do check if you reached the end-of-stream:

if (!feof(stdin)) { ...

and that's about it.

How to set default vim colorscheme

OS: Redhat enterprise edition

colo schema_name works fine if you are facing problems with colorscheme.

How to save picture to iPhone photo library?

The simplest way is:

UIImageWriteToSavedPhotosAlbum(myUIImage, nil, nil, nil);

For Swift, you can refer to Saving to the iOS photo library using swift

Spring MVC Missing URI template variable

@PathVariable is used to tell Spring that part of the URI path is a value you want passed to your method. Is this what you want, or are the variables supposed to be form data posted to the URI?

If you want form data, use @RequestParam instead of @PathVariable.

If you want @PathVariable, you need to specify placeholders in the @RequestMapping entry to tell Spring where the path variables fit in the URI. For example, if you want to extract a path variable called contentId, you would use:

@RequestMapping(value = "/whatever/{contentId}", method = RequestMethod.POST)

Edit: Additionally, if your path variable could contain a '.' and you want that part of the data, then you will need to tell Spring to grab everything, not just the stuff before the '.':

@RequestMapping(value = "/whatever/{contentId:.*}", method = RequestMethod.POST)

This is because the default behaviour of Spring is to treat that part of the URL as if it is a file extension, and excludes it from variable extraction.

Filtering Sharepoint Lists on a "Now" or "Today"

Warning about using TODAY (or any calcs in a column).

If you set up a filter and have JUST [Today] it it you should be fine.

But the moment you do something like [Today]-1 ... the view will no longer show up when trying to pick it for alerts.

Another microsoft wonder.

MySQL Workbench Edit Table Data is read only

MySQL will run in Read-Only mode when you fetch by joining two tables and columns from two tables are included in the result. Then you can't update the values directly.

Format date to MM/dd/yyyy in JavaScript

Try this; bear in mind that JavaScript months are 0-indexed, whilst days are 1-indexed.

_x000D_
_x000D_
var date = new Date('2010-10-11T00:00:00+05:30');_x000D_
    alert(((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '/' + date.getFullYear());
_x000D_
_x000D_
_x000D_

Making text background transparent but not text itself

box-shadow: inset 1px 2000px rgba(208, 208, 208, 0.54);

jQuery Clone table row

Try this.

HTML

<!-- Your table -->
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="table-data"> 
    <thead>
        <tr>
            <th>Name</th>
            <th>Location</th>
            <th>From</th>
            <th>To</th>
            <th>Add</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="text" autofocus placeholder="who" name="who" ></td>
            <td><input type="text" autofocus placeholder="location" name="location" ></td>
            <td><input type="text" placeholder="Start Date" name="datepicker_start" class="datepicker"></td>
            <td><input type="text" placeholder="End Date" name="datepicker_end" class="datepicker"></td>
            <td><input type="button" name="add" value="Add" class="tr_clone_add"></td>
        </tr>
    <tbody>
</table>

<!-- Model of new row -->
<table id="new-row-model" style="display: none"> 
    <tbody>
        <tr>
            <td><input type="text" autofocus placeholder="who" name="who" ></td>
            <td><input type="text" autofocus placeholder="location" name="location" ></td>
            <td><input type="text" placeholder="Start Date" name="datepicker_start" class="datepicker"></td>
            <td><input type="text" placeholder="End Date" name="datepicker_end" class="datepicker"></td>
            <td><input type="button" name="add" value="Add" class="tr_clone_add"></td>
        </tr>
    <tbody>
</table>

Script

$("input.tr_clone_add").live('click', function(){
    var new_row = $("#new-row-model tbody").clone();
    $("#table-data tbody").append(new_row.html());
});

When to use IList and when to use List

Microsoft guidelines as checked by FxCop discourage use of List<T> in public APIs - prefer IList<T>.

Incidentally, I now almost always declare one-dimensional arrays as IList<T>, which means I can consistently use the IList<T>.Count property rather than Array.Length. For example:

public interface IMyApi
{
    IList<int> GetReadOnlyValues();
}

public class MyApiImplementation : IMyApi
{
    public IList<int> GetReadOnlyValues()
    {
        List<int> myList = new List<int>();
        ... populate list
        return myList.AsReadOnly();
    }
}
public class MyMockApiImplementationForUnitTests : IMyApi
{
    public IList<int> GetReadOnlyValues()
    {
        IList<int> testValues = new int[] { 1, 2, 3 };
        return testValues;
    }
}

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Solutions:

Solution A:

  1. Download http://www.servlets.com/cos/index.html
  2. Invoke getParameters() on com.oreilly.servlet.MultipartRequest

Solution B:

  1. Download http://jakarta.Apache.org/commons/fileupload/
  2. Invoke readHeaders() in org.apache.commons.fileupload.MultipartStream

Solution C:

  1. Download http://users.boone.net/wbrameld/multipartformdata/
  2. Invoke getParameter on com.bigfoot.bugar.servlet.http.MultipartFormData

Solution D:

Use Struts. Struts 1.1 handles this automatically.

Reference: http://www.jguru.com/faq/view.jsp?EID=1045507

Convert integer to hex and hex to integer

Use master.dbo.fnbintohexstr(16777215) to convert to a varchar representation.

Error: Cannot find module 'ejs'

I installed both: express and ejs with the option --save:

npm install ejs --save npm install express --save

This way express and ejs are dependecies package.json file.

Http Post With Body

You can use HttpClient and HttpPost to send a json string as body:

public void post(String completeUrl, String body) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(completeUrl);
    httpPost.setHeader("Content-type", "application/json");
    try {
        StringEntity stringEntity = new StringEntity(body);
        httpPost.getRequestLine();
        httpPost.setEntity(stringEntity);

        httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Json body example:

{
  "param1": "value 1",
  "param2": 123,
  "testStudentArray": [
    {
      "name": "Test Name 1",
      "gpa": 3.5
    },
    {
      "name": "Test Name 2",
      "gpa": 3.8
    }
  ]
}

What are the differences between a pointer variable and a reference variable in C++?

Basic meaning of pointer(*) is "Value at address of" which means whatever address you provide it will give value at that address. Once you change the address it will give the new value, while reference variable used to reference any particular variable and which can't be change to reference any other variable in future.

How to Solve Max Connection Pool Error

Before you begin to curse your application you need to check this:

  1. Is your application the only one using that instance of SQL Server. a. If the answer to that is NO then you need to investigate how the other applications are consuming resources on your SQl Server.run b. If the answer is yes then you must investigate your application.

  2. Run SQL Server Profiler and check what activity is happening in other applications (1a) using SQL Server and check your application as well (1b).

  3. If indeed your application is starved off of resources then you need to make farther investigations. For more read on this http://sqlserverplanet.com/troubleshooting/sql-server-slowness

Android - Launcher Icon Size

I would create separate images for each one:

LDPI should be 36 x 36.

MDPI should be 48 x 48.

TVDPI should be 64 x 64.

HDPI should be 72 x 72.

XHDPI should be 96 x 96.

XXHDPI should be 144 x 144.

XXXHDPI should be 192 x 192.

Then just put each of them in the separate stalks of the drawable folder.

You are also required to give a large version of your icon when uploading your app onto the Google Play Store and this should be WEB 512 x 512. This is so large so that Google can rescale it to any size in order to advertise your app throughout the Google Play Store and not add pixelation to your logo.

Basically, all of the other icons should be in proportion to the 'baseline' icon, MDPI at 48 x 48.

LDPI is MDPI x 0.75.

TVDPI is MDPI x 1.33.

HDPI is MDPI x 1.5.

XHDPI is MDPI x 2.

XXHDPI is MDPI x 3.

XXXHDPI is MDPI x 4.

This is all explained on the Iconography page of the Android Developers website: http://developer.android.com/design/style/iconography.html

Ternary operators in JavaScript without an "else"

To use a ternary operator without else inside of an array or object declaration, you can use the ES6 spread operator, ...():

const cond = false;
const arr = [
  ...(cond ? ['a'] : []),
  'b',
];
    // ['b']

And for objects:

const cond = false;
const obj = {
  ...(cond ? {a: 1} : {}),
  b: 2,
};
    // {b: 2}

Original source

Spring,Request method 'POST' not supported

You are missimg @ModelAttribute annotation for UserProfessionalForm professionalForm parameter in forgotPassword method.

@RequestMapping(value = "proffessional", method = RequestMethod.POST)
public @ResponseBody
String forgotPassword(@ModelAttribute UserProfessionalForm professionalForm,
        BindingResult result, Model model) {

    UserProfileVO userProfileVO = new UserProfileVO();
    userProfileVO.setUser(sessionData.getUser());
    userService.saveUserProfile(userProfileVO);
    model.addAttribute("professional", professionalForm);
    return "Your Professional Details Updated";
}

How to figure out the SMTP server host?

Email tech support at your client's hosting provider and ask for the information.

Where can I find error log files?

This will defiantly help you,

https://davidwinter.me/enable-php-error-logging/

OR

In php.ini: (vim /etc/php.ini Or Sudo vim /usr/local/etc/php/7.1/php.ini)

display_errors = Off

log_errors = On

error_log = /var/log/php-errors.log

Make the log file, and writable by www-data:

sudo touch /var/log/php-errors.log

/var/log/php-errors.log

sudo chown :www

Thanks,

How to extract extension from filename string in Javascript?

var x = "1.txt";
alert (x.substring(x.indexOf(".")+1));

note 1: this will not work if the filename is of the form file.example.txt
note 2: this will fail if the filename is of the form file

Status bar and navigation bar appear over my view's bounds in iOS 7

In my case having loadView() interrupted
this code: self.edgesForExtendedLayout = UIRectEdgeNone

but after deleting loadView() everything worked fine

Ruby on Rails generates model field:type - what are the options for field:type?

$ rails g model Item name:string description:text product:references

I too found the guides difficult to use. Easy to understand, but hard to find what I am looking for.

Also, I have temp projects that I run the rails generate commands on. Then once I get them working I run it on my real project.

Reference for the above code: http://guides.rubyonrails.org/getting_started.html#associating-models

How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5

I had the same error message when I was working with calling a stored procedure that takes two input parameters and returns 3 values using SELECT statement and I solved the issue like below in EF Code First Approach

 SqlParameter @TableName = new SqlParameter()
        {
            ParameterName = "@TableName",
            DbType = DbType.String,
            Value = "Trans"
        };

SqlParameter @FieldName = new SqlParameter()
        {
            ParameterName = "@FieldName",
            DbType = DbType.String,
            Value = "HLTransNbr"
        };


object[] parameters = new object[] { @TableName, @FieldName };

List<Sample> x = this.Database.SqlQuery<Sample>("EXEC usp_NextNumberBOGetMulti @TableName, @FieldName", parameters).ToList();


public class Sample
{
    public string TableName { get; set; }
    public string FieldName { get; set; }
    public int NextNum { get; set; }
}

UPDATE: It looks like with SQL SERVER 2005 missing EXEC keyword is creating problem. So to allow it to work with all SQL SERVER versions I updated my answer and added EXEC in below line

 List<Sample> x = this.Database.SqlQuery<Sample>(" EXEC usp_NextNumberBOGetMulti @TableName, @FieldName", param).ToList();

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

I used the following two steps which I found in the comments/posts linked in the other answers:

Step one: Convert the x.509 cert and key to a pkcs12 file

openssl pkcs12 -export -in server.crt -inkey server.key \
               -out server.p12 -name [some-alias] \
               -CAfile ca.crt -caname root

Note: Make sure you put a password on the pkcs12 file - otherwise you'll get a null pointer exception when you try to import it. (In case anyone else had this headache). (Thanks jocull!)

Note 2: You might want to add the -chain option to preserve the full certificate chain. (Thanks Mafuba)

Step two: Convert the pkcs12 file to a Java keystore

keytool -importkeystore \
        -deststorepass [changeit] -destkeypass [changeit] -destkeystore server.keystore \
        -srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass some-password \
        -alias [some-alias]

Finished

OPTIONAL Step zero: Create self-signed certificate

openssl genrsa -out server.key 2048
openssl req -new -out server.csr -key server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Cheers!

How can I download a specific Maven artifact in one command line?

Here's an example to get ASM-7 using Maven 3.6:

mvn dependency:get -DremoteRepositories=maven.apache.org -Dartifact=org.ow2.asm:7.0:sources:jar

Or you can download the jar from here: https://search.maven.org/search?q=g:org.ow2.asm%20AND%20a:asm and then

mvn install:install-file -DgroupId=org.ow2.asm -DartifactId=asm -Dversion=7.0 -Dclassifier=sources -Dpackaging=jar -Dfile=/path/to/asm-7.0.jar

Getting a count of objects in a queryset in django

Another way of doing this would be using Aggregation. You should be able to achieve a similar result using a single query. Such as this:

Item.objects.values("contest").annotate(Count("id"))

I did not test this specific query, but this should output a count of the items for each value in contests as a dictionary.

How to convert float to int with Java

Math.round also returns an integer value, so you don't need to typecast.

int b = Math.round(float a);

How do you wait for input on the same Console.WriteLine() line?

Use Console.Write instead, so there's no newline written:

Console.Write("What is your name? ");
var name = Console.ReadLine();

Will #if RELEASE work like #if DEBUG does in C#?

RELEASE is not defined, but you can use

#if (!DEBUG)
  ...
#endif

How to set RelativeLayout layout params in code not in xml?

    RelativeLayout layout = new RelativeLayout(this);
    RelativeLayout.LayoutParams labelLayoutParams = new RelativeLayout.LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    layout.setLayoutParams(labelLayoutParams);


   // If you want to add some controls in this Relative Layout
    labelLayoutParams = new RelativeLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    labelLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);


    ImageView mImage = new ImageView(this);
    mImage.setBackgroundResource(R.drawable.popupnew_bg);        
    layout.addView(mImage,labelLayoutParams);

    setContentView(layout);

List of tuples to dictionary

The dict constructor accepts input exactly as you have it (key/value tuples).

>>> l = [('a',1),('b',2)]
>>> d = dict(l)
>>> d
{'a': 1, 'b': 2}

From the documentation:

For example, these all return a dictionary equal to {"one": 1, "two": 2}:

dict(one=1, two=2)
dict({'one': 1, 'two': 2})
dict(zip(('one', 'two'), (1, 2)))
dict([['two', 2], ['one', 1]])

Find and replace words/lines in a file

Any decent text editor has a search&replace facility that supports regular expressions.

If however, you have reason to reinvent the wheel in Java, you can do:

Path path = Paths.get("test.txt");
Charset charset = StandardCharsets.UTF_8;

String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("foo", "bar");
Files.write(path, content.getBytes(charset));

This only works for Java 7 or newer. If you are stuck on an older Java, you can do:

String content = IOUtils.toString(new FileInputStream(myfile), myencoding);
content = content.replaceAll(myPattern, myReplacement);
IOUtils.write(content, new FileOutputStream(myfile), myencoding);

In this case, you'll need to add error handling and close the streams after you are done with them.

IOUtils is documented at http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/IOUtils.html

Declare a variable in DB2 SQL

I imagine this forum posting, which I quote fully below, should answer the question.


Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):

BEGIN ATOMIC
 DECLARE example VARCHAR(15) ;
 SET example = 'welcome' ;
 SELECT *
 FROM   tablename
 WHERE  column1 = example ;
END

or (in any environment):

WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM   tablename, t
WHERE  column1 = example

or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):

CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM   tablename
WHERE  column1 = example ;

How to redirect user's browser URL to a different page in Nodejs?

In Express you can use

res.redirect('http://example.com');

to redirect user from server.

To include a status code 301 or 302 it can be used

res.redirect(301, 'http://example.com');

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

I encountered this in a Docker image, with a non-AWS S3 endpoint, when using the latest awscli version available to Debian stretch, i.e. version 1.11.13.

Upgrading to CLI version 1.16.84 resolved the issue.

To install the latest version of the CLI with a Dockerfile based on a Debian stretch image, instead of:

RUN apt-get update
RUN apt-get install -y awscli
RUN aws --version

Use:

RUN apt-get update
RUN apt-get install -y python-pip
RUN pip install awscli
RUN aws --version

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

git status shows modifications, git checkout -- <file> doesn't remove them

This issue can also occur when a contributor to the repo works on a Linux machine, or windows with Cygwin and file permissions are changed. Git only knows of 755 and 644.

Example of this issue and how to check for it:

git diff styleguide/filename

diff --git a/filename b/filename
old mode 100644
new mode 100755

To avoid this, you should make sure you setup git correctly using

git config --global core.filemode false

Child with max-height: 100% overflows parent

_x000D_
_x000D_
.container {_x000D_
  background: blue;_x000D_
  padding: 10px;_x000D_
  max-height: 200px;_x000D_
  max-width: 200px;_x000D_
  float: left;_x000D_
  margin-right: 20px;_x000D_
}_x000D_
_x000D_
.img1 {_x000D_
  display: block;_x000D_
  max-height: 100%;_x000D_
  max-width: 100%;_x000D_
}_x000D_
_x000D_
.img2 {_x000D_
  display: block;_x000D_
  max-height: inherit;_x000D_
  max-width: inherit;_x000D_
}
_x000D_
<!-- example 1  -->_x000D_
<div class="container">_x000D_
  <img class='img1' src="http://via.placeholder.com/350x450" />_x000D_
</div>_x000D_
_x000D_
<!-- example 2  -->_x000D_
_x000D_
<div class="container">_x000D_
  <img class='img2' src="http://via.placeholder.com/350x450" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

I played around a little. On a larger image in firefox, I got a good result with using the inherit property value. Will this help you?

.container {
    background: blue;
    padding: 10px;
    max-height: 100px;
    max-width: 100px;
    text-align:center;
}

img {
    max-height: inherit;
    max-width: inherit;
}

Rearrange columns using cut

Just as an addition to answers that suggest to duplicate the columns and then to do cut. For duplication, paste etc. will work only for files, but not for streams. In that case, use sed instead.

cat file.txt | sed s/'.*'/'&\t&'/ | cut -f2,3

This works on both files and streams, and this is interesting if instead of just reading from a file with cat, you do something interesting before re-arranging the columns.

By comparison, the following does not work:

cat file.txt | paste - - | cut -f2,3

Here, the double stdin placeholder paste does not duplicate stdin, but reads the next line.

How to Retrieve value from JTextField in Java Swing?

Just use event.getSource() frim within actionPerformed

Cast it to the component

for Ex, if you need combobox

JComboBox comboBox = (JComboBox) event.getSource();
JTextField txtField = (JTextField) event.getSource();

use appropriate api to get the value,

for Ex.

Object selected = comboBox.getSelectedItem();  etc.