Here it fails at Array.apply(null, new Array(1000000))
and not the .map
call.
All functions arguments must fit on callstack(at least pointers of each argument), so in this they are too many arguments for the callstack.
You need to the understand what is call stack.
Stack is a LIFO data structure, which is like an array that only supports push and pop methods.
Let me explain how it works by a simple example:
function a(var1, var2) {
var3 = 3;
b(5, 6);
c(var1, var2);
}
function b(var5, var6) {
c(7, 8);
}
function c(var7, var8) {
}
When here function a
is called, it will call b
and c
. When b
and c
are called, the local variables of a
are not accessible there because of scoping roles of Javascript, but the Javascript engine must remember the local variables and arguments, so it will push them into the callstack. Let's say you are implementing a JavaScript engine with the Javascript language like Narcissus.
We implement the callStack as array:
var callStack = [];
Everytime a function called we push the local variables into the stack:
callStack.push(currentLocalVaraibles);
Once the function call is finished(like in a
, we have called b
, b
is finished executing and we must return to a
), we get back the local variables by poping the stack:
currentLocalVaraibles = callStack.pop();
So when in a
we want to call c
again, push the local variables in the stack. Now as you know, compilers to be efficient define some limits. Here when you are doing Array.apply(null, new Array(1000000))
, your currentLocalVariables
object will be huge because it will have 1000000
variables inside. Since .apply
will pass each of the given array element as an argument to the function. Once pushed to the call stack this will exceed the memory limit of call stack and it will throw that error.
Same error happens on infinite recursion(function a() { a() }
) as too many times, stuff has been pushed to the call stack.
Note that I'm not a compiler engineer and this is just a simplified representation of what's going on. It really is more complex than this. Generally what is pushed to callstack is called stack frame which contains the arguments, local variables and the function address.
Use the function Contains
from the strings package.
import (
"strings"
)
strings.Contains("something", "some") // true
In a nutshell, this is the code which works for me :)
WebDriver driver;
WebElement element;
String value;
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].value='"+ value +"';", element);
By default, git will update execute file permissions if you change them. It will not change or track any other permissions.
If you don't see any changes when modifying execute permission, you probably have a configuration in git which ignore file mode.
Look into your project, in the .git
folder for the config
file and you should see something like this:
[core]
filemode = false
You can either change it to true
in your favorite text editor, or run:
git config core.filemode true
Then, you should be able to commit normally your files. It will only commit the permission changes.
You should define the style on the td
element like so:
<html>
<head>
<style type="text/css">
.bb
{
border-bottom: solid 1px black;
}
</style>
</head>
<body>
<table>
<tr>
<td>
Test 1
</td>
</tr>
<tr>
<td class="bb">
Test 2
</td>
</tr>
</table>
</body>
</html>
This means that you are doing a foreach on something that is not an array.
Check out all your foreach statements, and look if the thing before the as
, to make sure it is actually an array. Use var_dump
to dump it.
Then fix the one where it isn't an array.
How to reproduce this error:
<?php
$skipper = "abcd";
foreach ($skipper as $item){ //the warning happens on this line.
print "ok";
}
?>
Make sure $skipper
is an array.
The answer below is related to this deprecation warning occurring in the Fragments tutorial on the Android developer website and may not be related to the posts above.
I used this code on the tutorial lesson and it did worked.
public void onAttach(Context context){
super.onAttach(context);
Activity activity = getActivity();
I was worried that activity maybe null as what the documentation states.
getActivity
FragmentActivity getActivity () Return the FragmentActivity this fragment is currently associated with. May return null if the fragment is associated with a Context instead.
But the onCreate on the main_activity clearly shows that the fragment was loaded and so after this method, calling get activity from the fragment will return the main_activity class.
getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, firstFragment).commit();
I hope I am correct with this. I am an absolute newbie.
If you are using IIS Express and launch it via a command prompt, it will leave the DOS window open, and you will see Console.Write
statements there.
So for example get a command window open and type:
"C:\Program Files (x86)\IIS Express\iisexpress" /path:C:\Projects\Website1 /port:1655
This assumes you have a website directory at C:\Projects\Website1. It will start IIS Express and serve the pages in your website directory. It will leave the command windows open, and you will see output information there. Let's say you had a file there, default.aspx, with this code in it:
<%@ Page Language="C#" %>
<html>
<body>
<form id="form1" runat="server">
Hello!
<% for(int i = 0; i < 6; i++) %>
<% { Console.WriteLine(i.ToString()); }%>
</form>
</body>
</html>
Arrange your browser and command windows so you can see them both on the screen. Now type into your browser: http://localhost:1655/
. You will see Hello! on the webpage, but in the command window you will see something like
Request started: "GET" http://localhost:1655/
0
1
2
3
4
5
Request ended: http://localhost:1655/default.aspx with HTTP status 200.0
I made it simple by having the code in a code block in the markup, but any console statements in your code-behind or anywhere else in your code will show here as well.
Probably like this :
import datetime
now = datetime.datetime.now()
now.strftime('%Y/%m/%d %H:%M:%S.%f')[:-3]
# [:-3] => Removing the 3 last characters as %f is for microsecs.
This is a working BackButton component (React 0.14):
var React = require('react');
var Router = require('react-router');
var History = Router.History;
var BackButton = React.createClass({
mixins: [ History ],
render: function() {
return (
<button className="back" onClick={this.history.goBack}>{this.props.children}</button>
);
}
});
module.exports = BackButton;
You can off course do something like this if there is no history:
<button className="back" onClick={goBack}>{this.props.children}</button>
function goBack(e) {
if (/* no history */) {
e.preventDefault();
} else {
this.history.goBack();
}
}
Make the the table-cell position relative, then make the inner div position absolute, with top/right/bottom/left all set to 0px.
.table-cell {
display: table-cell;
position: relative;
}
.inner-div {
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
}
Based on VonC and Michele Milidoni answers I've created this bookmarklet which displays downloads statistics of github hosted released binaries.
Note: Because of issues with browsers related to Content Security Policy implementation, bookmarklets can temporarily violate some CSP directives and basically may not function properly when running on github while CSP is enabled.
Though its highly discouraged, you can disable CSP in Firefox as a temporary workaround. Open up about:config and set security.csp.enable to false.
Your code sample didn't expand on part of your topic, namely symbols, and so that part of the question went unanswered.
If you have two strings, foo and bar, and both can be either a string or a symbol, you can test equality with
foo.to_s == bar.to_s
It's a little more efficient to skip the string conversions on operands with known type. So if foo is always a string
foo == bar.to_s
But the efficiency gain is almost certainly not worth demanding any extra work on behalf of the caller.
Prior to Ruby 2.2, avoid interning uncontrolled input strings for the purpose of comparison (with strings or symbols), because symbols are not garbage collected, and so you can open yourself to denial of service through resource exhaustion. Limit your use of symbols to values you control, i.e. literals in your code, and trusted configuration properties.
Ruby 2.2 introduced garbage collection of symbols.
try this
SELECT group_name, employees, surveys, COUNT( surveys ) AS test1,
concat(round(( surveys/employees * 100 ),2),'%') AS percentage
FROM a_test
GROUP BY employees
file_name=test.log
# set first K lines:
K=1000
# line count (N):
N=$(wc -l < $file_name)
# length of the bottom file:
L=$(( $N - $K ))
# create the top of file:
head -n $K $file_name > top_$file_name
# create bottom of file:
tail -n $L $file_name > bottom_$file_name
Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so
split -l 300000 file_name
will output xaa
with 300k lines and xab
with 100k lines, for an input with 400k lines.
After trying a whole bunch of fixes including:
Here is My fix: I figured you cannot break it more so I opened up my phone and removed the proximity sensor all together from the motherboard. The sensor tester app now shows "no_value" where it use to give "Distance: 0" and my screen no longer goes black after dialing. Please note I can only confirm this working on a Samsung I8190 Galaxy S III mini with CM MOD 5.1.1. Here is a picture of the device i removed: I have removed it using a SMD solder station's heat gun at 400 degrees, some tweezers and flux.But a sharp hobby knife might work too.
map3 = new HashMap<>();
map3.putAll(map1);
map3.putAll(map2);
I've been searching for a simpler solution using only loops and if statements, and this is what I came up with. The program also works with negative integers and correctly rejects any mixed inputs that may contain both integers and other characters.
#include <stdio.h>
#include <stdlib.h> // Used for atoi() function
#include <string.h> // Used for strlen() function
#define TRUE 1
#define FALSE 0
int main(void)
{
char n[10]; // Limits characters to the equivalent of the 32 bits integers limit (10 digits)
int intTest;
printf("Give me an int: ");
do
{
scanf(" %s", n);
intTest = TRUE; // Sets the default for the integer test variable to TRUE
int i = 0, l = strlen(n);
if (n[0] == '-') // Tests for the negative sign to correctly handle negative integer values
i++;
while (i < l)
{
if (n[i] < '0' || n[i] > '9') // Tests the string characters for non-integer values
{
intTest = FALSE; // Changes intTest variable from TRUE to FALSE and breaks the loop early
break;
}
i++;
}
if (intTest == TRUE)
printf("%i\n", atoi(n)); // Converts the string to an integer and prints the integer value
else
printf("Retry: "); // Prints "Retry:" if tested FALSE
}
while (intTest == FALSE); // Continues to ask the user to input a valid integer value
return 0;
}
Tried the given example, but over VPN and with 400k+ keys it was too slow for me. Also it did not give me the key objects.
I wrote a small Python called tool redis-mass-get to combine KEYS
and MGET
requests against Redis:
# installation:
pip install redis-mass-get
# pipeline example CSV:
redis-mass-get -f csv -och redis://my.redis.url product:* | less
# write to json-file example with progress indicator:
redis-mass-get -d results.json -jd redis://my.redis.url product:*
It supports JSON, CSV and TXT output to file or stdout
for usage in pipes. More info can be found at: Reading multiple key/values from Redis.
Using %lf
will help you in solving this problem.
Use :
scanf("%lf",&doub)
this works for me:
cmake -D DBUILD_SHARED_LIBS=ON DBUILD_STATIC_LIBS=ON DBUILD_TESTS=ON ..
Second case is also inefficient in terms of String pool, you have to explicitly call intern() on return reference to make it intern.
Just append :after
to your #alertlist li:hover
selector the same way you do with your #alertlist li.selected
selector:
#alertlist li.selected:after, #alertlist li:hover:after
{
position:absolute;
top: 0;
right:-10px;
bottom:0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid #303030;
content: "";
}
public static void ExportToExcel(DataGridView dgView)
{
Microsoft.Office.Interop.Excel.Application excelApp = null;
try
{
// instantiating the excel application class
excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Worksheet currentWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)currentWorkbook.ActiveSheet;
currentWorksheet.Columns.ColumnWidth = 18;
if (dgView.Rows.Count > 0)
{
currentWorksheet.Cells[1, 1] = DateTime.Now.ToString("s");
int i = 1;
foreach (DataGridViewColumn dgviewColumn in dgView.Columns)
{
// Excel work sheet indexing starts with 1
currentWorksheet.Cells[2, i] = dgviewColumn.Name;
++i;
}
Microsoft.Office.Interop.Excel.Range headerColumnRange = currentWorksheet.get_Range("A2", "G2");
headerColumnRange.Font.Bold = true;
headerColumnRange.Font.Color = 0xFF0000;
//headerColumnRange.EntireColumn.AutoFit();
int rowIndex = 0;
for (rowIndex = 0; rowIndex < dgView.Rows.Count; rowIndex++)
{
DataGridViewRow dgRow = dgView.Rows[rowIndex];
for (int cellIndex = 0; cellIndex < dgRow.Cells.Count; cellIndex++)
{
currentWorksheet.Cells[rowIndex + 3, cellIndex + 1] = dgRow.Cells[cellIndex].Value;
}
}
Microsoft.Office.Interop.Excel.Range fullTextRange = currentWorksheet.get_Range("A1", "G" + (rowIndex + 1).ToString());
fullTextRange.WrapText = true;
fullTextRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
}
else
{
string timeStamp = DateTime.Now.ToString("s");
timeStamp = timeStamp.Replace(':', '-');
timeStamp = timeStamp.Replace("T", "__");
currentWorksheet.Cells[1, 1] = timeStamp;
currentWorksheet.Cells[1, 2] = "No error occured";
}
using (SaveFileDialog exportSaveFileDialog = new SaveFileDialog())
{
exportSaveFileDialog.Title = "Select Excel File";
exportSaveFileDialog.Filter = "Microsoft Office Excel Workbook(*.xlsx)|*.xlsx";
if (DialogResult.OK == exportSaveFileDialog.ShowDialog())
{
string fullFileName = exportSaveFileDialog.FileName;
// currentWorkbook.SaveCopyAs(fullFileName);
// indicating that we already saved the workbook, otherwise call to Quit() will pop up
// the save file dialogue box
currentWorkbook.SaveAs(fullFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, System.Reflection.Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
currentWorkbook.Saved = true;
MessageBox.Show("Error memory exported successfully", "Exported to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (excelApp != null)
{
excelApp.Quit();
}
}
}
One more solution for the pile, change your .m file to .mm so that it becomes Objective-C++ and use C++ raw literals, like this:
const char *sql_query = R"(SELECT word_id
FROM table1, table2
WHERE table2.word_id = table1.word_id
ORDER BY table1.word ASC)";
Raw literals ignore everything until the termination sequence, which in the default case is parenthesis-quote.
If the parenthesis-quote sequence has to appear in the string somewhere, you can easily specify a custom delimiter too, like this:
const char *sql_query = R"T3RM!N8(
SELECT word_id
FROM table1, table2
WHERE table2.word_id = table1.word_id
ORDER BY table1.word ASC
)T3RM!N8";
The problem is with percentage sizing. You are not defining the size of the parent div (the new one), so the browser can not report the size to the Google Maps API. Giving the wrapper div a specific size, or a percentage size if the size of its parent can be determined, will work.
See this explanation from Mike Williams' Google Maps API v2 tutorial:
If you try to use style="width:100%;height:100%" on your map div, you get a map div that has zero height. That's because the div tries to be a percentage of the size of the
<body>
, but by default the<body>
has an indeterminate height.There are ways to determine the height of the screen and use that number of pixels as the height of the map div, but a simple alternative is to change the
<body>
so that its height is 100% of the page. We can do this by applying style="height:100%" to both the<body>
and the<html>
. (We have to do it to both, otherwise the<body>
tries to be 100% of the height of the document, and the default for that is an indeterminate height.)
Add the 100% size to html and body in your css
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
Add it inline to any divs that don't have an id:
<body>
<div style="height:100%; width: 100%;">
<div id="map-canvas"></div>
</div>
</body>
The class Date/Timestamp
represents a specific instant in time, with millisecond precision, since January 1, 1970, 00:00:00 GMT. So this time difference (from epoch to current time) will be same in all computers across the world with irrespective of Timezone.
Date/Timestamp
doesn't know about the given time is on which timezone.
If we want the time based on timezone we should go for the Calendar or SimpleDateFormat classes in java.
If you try to print a Date/Timestamp object using toString()
, it will convert and print the time with the default timezone of your machine.
So we can say (Date/Timestamp).getTime() object will always have UTC (time in milliseconds)
To conclude Date.getTime()
will give UTC time, but toString()
is on locale specific timezone, not UTC.
The below code gives you a date (time in milliseconds) with specified timezones. The only problem here is you have to give date in string format.
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
dateFormatLocal.setTimeZone(timeZone);
java.util.Date parsedDate = dateFormatLocal.parse(date);
Use dateFormat.format
for taking input Date (which is always UTC), timezone and return date as String.
If you print the parsedDate
object, the time will be in default timezone.
But you can store the UTC time in DB like below.
Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Timestamp tsSchedStartTime = new Timestamp (parsedDate.getTime());
if (tsSchedStartTime != null) {
stmt.setTimestamp(11, tsSchedStartTime, calGMT );
} else {
stmt.setNull(11, java.sql.Types.DATE);
}
While pushing a repository to Github through Vs Studio code I deleted whole folder and they were not available in Recycle bin also. Here is how I recovered those files. For Windows.
The method is to restore the previous version of the Drive in which the deleted file existed
I had deleted files from G: drive, the below images are self explanatory
Open properties menu of the drive
In properties go to previous versions tab, where you can find the previously stored versions of that drive along with date at time of backup use open or click on restore to get the previous version of that drive.
Note: Manipulations in the drive after restore point won't be available
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']}
Files related for deployment (and others temporary items) are created in standalone/tmp/vfs (Virtual File System). You may add a policy at startup for evicting temporary files :
-Djboss.vfs.cache=org.jboss.virtual.plugins.cache.IterableTimedVFSCache
-Djboss.vfs.cache.TimedPolicyCaching.lifetime=1440
Here's a method that only uses splitting and joining. It's a little more readable so thought it was worth sharing:
String.prototype.replaceLast = function (what, replacement) {
var pcs = this.split(what);
var lastPc = pcs.pop();
return pcs.join(what) + replacement + lastPc;
};
You can use https://appery.io/ It is the same phonegap but in very convinient wrapper
I am using a .Net Core 2.1 Web Application and could not get a single answer here to work. I either got a blank parameter (if the method was called at all) or a 500 server error. I started playing with every possible combination of answers and finally got a working result.
In my case the solution was as follows:
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: mycontrolleraction,
data: JSON.stringify(things)
});
[HttpPost]
public IActionResult NewBranch([FromBody]IEnumerable<Thing> things)
{
return Ok();
}
Naming the content
data: { content: nodes }, // Server error 500
Not having the contentType = Server error 500
dataType
is not needed, despite what some answers say, as that is used for the response decoding (so not relevant to the request examples here).List<Thing>
also works in the controller methodStatic classes can be useful in certain situations, but there is a potential to abuse and/or overuse them, like most language features.
As Dylan Smith already mentioned, the most obvious case for using a static class is if you have a class with only static methods. There is no point in allowing developers to instantiate such a class.
The caveat is that an overabundance of static methods may itself indicate a flaw in your design strategy. I find that when you are creating a static function, its a good to ask yourself -- would it be better suited as either a) an instance method, or b) an extension method to an interface. The idea here is that object behaviors are usually associated with object state, meaning the behavior should belong to the object. By using a static function you are implying that the behavior shouldn't belong to any particular object.
Polymorphic and interface driven design are hindered by overusing static functions -- they cannot be overriden in derived classes nor can they be attached to an interface. Its usually better to have your 'helper' functions tied to an interface via an extension method such that all instances of the interface have access to that shared 'helper' functionality.
One situation where static functions are definitely useful, in my opinion, is in creating a .Create() or .New() method to implement logic for object creation, for instance when you want to proxy the object being created,
public class Foo
{
public static Foo New(string fooString)
{
ProxyGenerator generator = new ProxyGenerator();
return (Foo)generator.CreateClassProxy
(typeof(Foo), new object[] { fooString }, new Interceptor());
}
This can be used with a proxying framework (like Castle Dynamic Proxy) where you want to intercept / inject functionality into an object, based on say, certain attributes assigned to its methods. The overall idea is that you need a special constructor because technically you are creating a copy of the original instance with special added functionality.
If you have named datasets in the hdf file then you can use the following code to read and convert these datasets in numpy arrays:
import h5py
file = h5py.File('filename.h5', 'r')
xdata = file.get('xdata')
xdata= np.array(xdata)
If your file is in a different directory you can add the path in front of'filename.h5'
.
A good reason is for security - this can prevent CSRF attacks because this header cannot be added to the AJAX request cross domain without the consent of the server via CORS.
Only the following headers are allowed cross domain:
- Accept
- Accept-Language
- Content-Language
- Last-Event-ID
- Content-Type
any others cause a "pre-flight" request to be issued in CORS supported browsers.
Without CORS it is not possible to add X-Requested-With
to a cross domain XHR request.
If the server is checking that this header is present, it knows that the request didn't initiate from an attacker's domain attempting to make a request on behalf of the user with JavaScript. This also checks that the request wasn't POSTed from a regular HTML form, of which it is harder to verify it is not cross domain without the use of tokens. (However, checking the Origin
header could be an option in supported browsers, although you will leave old browsers vulnerable.)
You may wish to combine this with a token, because Flash running on Safari on OSX can set this header if there's a redirect step. It appears it also worked on Chrome, but is now remediated. More details here including different versions affected.
OWASP Recommend combining this with an Origin and Referer check:
This defense technique is specifically discussed in section 4.3 of Robust Defenses for Cross-Site Request Forgery. However, bypasses of this defense using Flash were documented as early as 2008 and again as recently as 2015 by Mathias Karlsson to exploit a CSRF flaw in Vimeo. But, we believe that the Flash attack can't spoof the Origin or Referer headers so by checking both of them we believe this combination of checks should prevent Flash bypass CSRF attacks. (NOTE: If anyone can confirm or refute this belief, please let us know so we can update this article)
However, for the reasons already discussed checking Origin can be tricky.
Written a more in depth blog post on CORS, CSRF and X-Requested-With here.
string s1 = "Hello! world!";
string s2 = s1.Trim('!');
in (backend.php) be sure to include include
session_start();
-Taylor http://www.hawkessolutions.com
Another option would be to use Angular's built-in pub-sub architecture in order to notify your directive to focus. Similar to the other approaches, but it's then not directly tied to a property, and is instead listening in on it's scope for a particular key.
Directive:
angular.module("app").directive("focusOn", function($timeout) {
return {
restrict: "A",
link: function(scope, element, attrs) {
scope.$on(attrs.focusOn, function(e) {
$timeout((function() {
element[0].focus();
}), 10);
});
}
};
});
HTML:
<input type="text" name="text_input" ng-model="ctrl.model" focus-on="focusTextInput" />
Controller:
//Assume this is within your controller
//And you've hit the point where you want to focus the input:
$scope.$broadcast("focusTextInput");
equal_freq
from funModeling
takes a vector and the number of bins (based on equal frequency):
das <- data.frame(anim=1:15,
wt=c(181,179,180.5,201,201.5,245,246.4,
189.3,301,354,369,205,199,394,231.3))
das$wt_bin=funModeling::equal_freq(das$wt, 3)
table(das$wt_bin)
#[179,201) [201,246) [246,394]
# 5 5 5
The solution for me was to check the case sensitivity of the username. A lot of people are mentioning that the URL is case sensitive, but it seems the username is as well!
check your environment variables for http and https
The existing entries might be creating some issues. Try deleting those entries.
Run "npm install" again.
I used to send some values from my listview
How to send
mListview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Favorite clickedObj = (Favorite) parent.getItemAtPosition(position);
Bundle args = new Bundle();
args.putString("tar_name", clickedObj.getNameTarife());
args.putString("fav_name", clickedObj.getName());
FragmentManager fragmentManager = getSupportFragmentManager();
TarifeDetayPopup userPopUp = new TarifeDetayPopup();
userPopUp.setArguments(args);
userPopUp.show(fragmentManager, "sam");
return false;
}
});
How to receive inside onCreate() method of DialogFragment
Bundle mArgs = getArguments();
String nameTrife = mArgs.getString("tar_name");
String nameFav = mArgs.getString("fav_name");
String name = "";
// Kotlin upload
val fm = supportFragmentManager
val dialogFragment = AddProgFargmentDialog() // my custom FargmentDialog
var args: Bundle? = null
args?.putString("title", model.title);
dialogFragment.setArguments(args)
dialogFragment.show(fm, "Sample Fragment")
// receive
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (getArguments() != null) {
val mArgs = arguments
var myDay= mArgs.getString("title")
}
}
If you don't want any dependency on Spring's HATEOAS or javax.*
namespace, use ServletUriComponentsBuilder
to get URI of current request:
import org.springframework.web.util.UriComponentsBuilder;
ServletUriComponentsBuilder.fromCurrentRequest();
ServletUriComponentsBuilder.fromCurrentRequestUri();
By printing multiple values separated by a comma:
print "I have", card.price
The print statement will output each expression separated by spaces, followed by a newline.
If you need more complex formatting, use the ''.format()
method:
print "I have: {0.price}".format(card)
or by using the older and semi-deprecated %
string formatting operator.
Hope this will help someone looking for a perfect answer
Copying a folder or file from a server with a port defined to another server or local machine
scp -r -P port user@IP_address:/home/file/pathDirectory .
**Note:** The last . on the command directs it to copy everything in that folder to your directory of preference
The ConverterParameter
property can not be bound because it is not a dependency property.
Since Binding
is not derived from DependencyObject
none of its properties can be dependency properties. As a consequence, a Binding can never be the target object of another Binding.
There is however an alternative solution. You could use a MultiBinding
with a multi-value converter instead of a normal Binding:
<Style TargetType="FrameworkElement">
<Setter Property="Visibility">
<Setter.Value>
<MultiBinding Converter="{StaticResource AccessLevelToVisibilityConverter}">
<Binding Path="Tag" RelativeSource="{RelativeSource Mode=FindAncestor,
AncestorType=UserControl}"/>
<Binding Path="Tag" RelativeSource="{RelativeSource Mode=Self}"/>
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
The multi-value converter gets an array of source values as input:
public class AccessLevelToVisibilityConverter : IMultiValueConverter
{
public object Convert(
object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values.All(v => (v is bool && (bool)v))
? Visibility.Visible
: Visibility.Hidden;
}
public object[] ConvertBack(
object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
Felix Kling's way will work, (actually beat me to the punch), but I was also going to suggest to use
$('#next').die().live('click', stopMoving);
this might be a better way to do it if you run into problems and strange behaviors when the element is clicked multiple times.
jQuery API specifically says not to bind to beforeunload, and instead should bind directly to the window.onbeforeunload, I just ran across a pretty bad memory in part due binding to beforeunload with jQuery.
read this, split function has an overload takes an array consist of seperators http://msdn.microsoft.com/en-us/library/system.stringsplitoptions.aspx
When you press ctrl + space, look in the Status bar below.. It will display a message saying IntelliSense is unavailable for C++ / CLI, if it doesn't support it.. The message will look like this -
It's an old question, but I found this can be done easily with Spacy. Once the document is read, a simple api similarity
can be used to find the cosine similarity between the document vectors.
import spacy
nlp = spacy.load('en')
doc1 = nlp(u'Hello hi there!')
doc2 = nlp(u'Hello hi there!')
doc3 = nlp(u'Hey whatsup?')
print doc1.similarity(doc2) # 0.999999954642
print doc2.similarity(doc3) # 0.699032527716
print doc1.similarity(doc3) # 0.699032527716
I love the Swift language, but using NSAttributedString
with a Swift Range
that is not compatible with NSRange
has made my head hurt for too long. So to get around all that garbage I devised the following methods to return an NSMutableAttributedString
with the highlighted words set with your color.
This does not work for emojis. Modify if you must.
extension String {
func getRanges(of string: String) -> [NSRange] {
var ranges:[NSRange] = []
if contains(string) {
let words = self.components(separatedBy: " ")
var position:Int = 0
for word in words {
if word.lowercased() == string.lowercased() {
let startIndex = position
let endIndex = word.characters.count
let range = NSMakeRange(startIndex, endIndex)
ranges.append(range)
}
position += (word.characters.count + 1) // +1 for space
}
}
return ranges
}
func highlight(_ words: [String], this color: UIColor) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: self)
for word in words {
let ranges = getRanges(of: word)
for range in ranges {
attributedString.addAttributes([NSForegroundColorAttributeName: color], range: range)
}
}
return attributedString
}
}
Usage:
// The strings you're interested in
let string = "The dog ran after the cat"
let words = ["the", "ran"]
// Highlight words and get back attributed string
let attributedString = string.highlight(words, this: .yellow)
// Set attributed string
label.attributedText = attributedString
For reading full response in Angular you should add the observe option:
{ observe: 'response' }
return this.http.get(`${environment.serverUrl}/api/posts/${postId}/comments/?page=${page}&size=${size}`, { observe: 'response' });
String to yyyy-MM-dd date format: Example:
TxtCalStDate.Text = Convert.ToDateTime(objItem["StartDate"]).ToString("yyyy/MM/dd");
Use Concat
or Union
extension methods. You have to make sure that you have this direction using System.Linq;
in order to use LINQ extensions methods.
Use the AddRange
method.
A slightly shorter solution, that only moves the item to the end, not anywhere is this:
l += [l.pop(0)]
For example:
>>> l = [1,2,3,4,5]
>>> l += [l.pop(0)]
>>> l
[2, 3, 4, 5, 1]
You could search for the corresponding key or you could "invert" the dictionary, but considering how you use it, it would be best if you just iterated over key/value pairs in the first place, which you can do with items()
. Then you have both directly in variables and don't need a lookup at all:
for key, value in PIX0.items():
NUM = input("What is the Resolution of %s?" % key)
if NUM == value:
You can of course use that both ways then.
Or if you don't actually need the dictionary for something else, you could ditch the dictionary and have an ordinary list of pairs.
You need to do custom SQL as exemplified in this snippet:
Or in a custom manager as shown in the online Django docs:
I accepted trebleCode's answer, but I wanted to provide a bit more detail regarding the steps I took to install the nupkg of interest pswindowsupdate.2.0.0.4.nupkg
on my unconnected Win 7 machine by way of following trebleCode's answer.
First: after digging around a bit, I think I found the MS docs that trebleCode refers to:
Bootstrap the NuGet provider and NuGet.exe
To continue, as trebleCode stated, I did the following
Install NuGet provider on my connected machine
On a connected machine (Win 10 machine), from the PS command line, I ran Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 -Force
. The Nuget software was obtained from the 'Net and installed on my local connected machine.
After the install I found the NuGet provider software at C:\Program Files\PackageManagement\ProviderAssemblies
(Note: the folder name \ProviderAssemblies
as opposed to \ReferenceAssemblies
was the one minor difference relative to trebleCode's answer.
The provider software is in a folder structure like this:
C:\Program Files\PackageManagement\ProviderAssemblies
\NuGet
\2.8.5.208
\Microsoft.PackageManagement.NuGetProvider.dll
Install NuGet provider on my unconnected machine
I copied the \NuGet folder (and all its children) from the connected machine onto a thumb drive and copied it to C:\Program Files\PackageManagement\ProviderAssemblies
on my unconnected (Win 7) machine
I started PS (v5) on my unconnected (Win 7) machine and ran Import-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201
to import the provider to the current PowerShell
session.
I ran Get-PackageProvider -ListAvailable
and saw this (NuGet appears where it was not present before):
Name Version DynamicOptions
---- ------- --------------
msi 3.0.0.0 AdditionalArguments
msu 3.0.0.0
NuGet 2.8.5.208 Destination, ExcludeVersion, Scope, SkipDependencies, Headers, FilterOnTag, Contains, AllowPrereleaseVersions, ConfigFile, SkipValidate
PowerShellGet 1.0.0.1 PackageManagementProvider, Type, Scope, AllowClobber, SkipPublisherCheck, InstallUpdate, NoPathUpdate, Filter, Tag, Includes, DscResource, RoleCapability, Command, PublishLocati...
Programs 3.0.0.0 IncludeWindowsInstaller, IncludeSystemComponent
Create local repository on my unconnected machine
On unconnected (Win 7) machine, I created a folder to serve as my PS repository (say, c:\users\foo\Documents\PSRepository
)
I registered the repo: Register-PSRepository -Name fooPsRepository -SourceLocation c:\users\foo\Documents\PSRepository -InstallationPolicy Trusted
Install the NuGet package
I obtained and copied the nupkg pswindowsupdate.2.0.0.4.nupkg
to c:\users\foo\Documents\PSRepository
on my unconnected Win7 machine
I learned the name of the module by executing Find-Module -Repository fooPsRepository
Version Name Repository Description
------- ---- ---------- -----------
2.0.0.4 PSWindowsUpdate fooPsRepository This module contain functions to manage Windows Update Client.
I installed the module by executing Install-Module -Name pswindowsupdate
I verified the module installed by executing Get-Command –module PSWindowsUpdate
CommandType Name Version Source
----------- ---- ------- ------
Alias Download-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Alias Get-WUInstall 2.0.0.4 PSWindowsUpdate
Alias Get-WUList 2.0.0.4 PSWindowsUpdate
Alias Hide-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Alias Install-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Alias Show-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Alias UnHide-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Alias Uninstall-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Cmdlet Add-WUServiceManager 2.0.0.4 PSWindowsUpdate
Cmdlet Enable-WURemoting 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUApiVersion 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUHistory 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUInstallerStatus 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUJob 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WULastResults 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WURebootStatus 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUServiceManager 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUSettings 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUTest 2.0.0.4 PSWindowsUpdate
Cmdlet Invoke-WUJob 2.0.0.4 PSWindowsUpdate
Cmdlet Remove-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Cmdlet Remove-WUServiceManager 2.0.0.4 PSWindowsUpdate
Cmdlet Set-WUSettings 2.0.0.4 PSWindowsUpdate
Cmdlet Update-WUModule 2.0.0.4 PSWindowsUpdate
I think I'm good to go
I had a problem where the value was not set because of a syntax error before the call.
$("#someId").value(33); //script bailed here without showing any errors Note: .value instead of .val
$("#gate").val('Gateway 2'); //this line didn't work.
Check for syntax errors before the call.
That first line is pretty messed up. It only needs to be:
var cleanText = text.replace(/\xA0/g,' ');
That should be all you need.
It's not an array of arrays. It's an observable of observable(s).
The following returns an observable stream of string.
requestStream
.map(function(requestUrl) {
return requestUrl;
});
While this returns an observable stream of observable stream of json
requestStream
.map(function(requestUrl) {
return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
});
flatMap
flattens the observable automatically for us so we can observe the json stream directly
One way would be created a JsonObject and iterating through the parameters. For example
JsonObject jobj = new Gson().fromJson(jsonString, JsonObject.class);
Then you can extract bean values like:
String fieldValue = jobj.get(fieldName).getAsString();
boolean fieldValue = jobj.get(fieldName).getAsBoolean();
int fieldValue = jobj.get(fieldName).getAsInt();
Hope this helps.
cat ip_addresses | sort | uniq -c | sort -nr | awk '{print $2 " " $1}'
this command would give you desired output
I found another way may be it will help you
=INDEX( SORT( A5:D ; 1 ; FALSE) ; 1 )
-will return last row
More info from anab here: https://groups.google.com/forum/?fromgroups=#!topic/How-to-Documents/if0_fGVINmI
The gem that makes it all too easy to obtain the result as a string (in today's numpy versions) is hidden in denis answer:
np.array2string
>>> import numpy as np
>>> x=np.random.random(10)
>>> np.array2string(x, formatter={'float_kind':'{0:.3f}'.format})
'[0.599 0.847 0.513 0.155 0.844 0.753 0.920 0.797 0.427 0.420]'
instead of
self.theTable.tableFooterView = tableFooter;
try
[self.theTable.tableFooterView addSubview:tableFooter];
Creating an isolate scope is undesirable. I would avoid using the scope attribute and do something like this. scope:true gives you a new child scope but not isolate. Then use parse to point a local scope variable to the same object the user has supplied to the ngModel attribute.
app.directive('myDir', ['$parse', function ($parse) {
return {
restrict: 'EA',
scope: true,
link: function (scope, elem, attrs) {
if(!attrs.ngModel) {return;}
var model = $parse(attrs.ngModel);
scope.model = model(scope);
}
};
}]);
how about checking the version of Python you are using first.
import six
if six.PY2:
import ConfigParser as configparser
else:
import configparser
const [text, setText] = useState('');
const onChangeText = (text) => {
if (+text) {
setText(text);
}
};
<TextInput
keyboardType="numeric"
value={text}
onChangeText={onChangeText}
/>
This should save from physical keyboards
you can save the original queue to a temporary queue. Then you simply do your normal pop on the temporary queue to go through the original one, for example:
queue tmp_q = original_q; //copy the original queue to the temporary queue
while (!tmp_q.empty())
{
q_element = tmp_q.front();
std::cout << q_element <<"\n";
tmp_q.pop();
}
At the end, the tmp_q will be empty but the original queue is untouched.
If you just want to print object then
console.log(JSON.stringify(data)); //this will convert json to string;
If you want to access value of field in object then use
console.log(data.input_data);
THIS IS FINAL CODE FOR CHECK BOTH INT AND FLOAT
function isInt(n) {
if(typeof n == 'number' && Math.Round(n) % 1 == 0) {
return true;
} else {
return false;
}
}
OR
function isInt(n) {
return typeof n == 'number' && Math.Round(n) % 1 == 0;
}
some great answers here, but they do not tackle how to use super()
in the case where different classes in the hierarchy have different signatures ... especially in the case of __init__
to answer that part and to be able to effectively use super()
i'd suggest reading my answer super() and changing the signature of cooperative methods.
here's just the solution to this scenario:
- the top-level classes in your hierarchy must inherit from a custom class like
SuperObject
:- if classes can take differing arguments, always pass all arguments you received on to the super function as keyword arguments, and, always accept
**kwargs
.
class SuperObject:
def __init__(self, **kwargs):
print('SuperObject')
mro = type(self).__mro__
assert mro[-1] is object
if mro[-2] is not SuperObject:
raise TypeError(
'all top-level classes in this hierarchy must inherit from SuperObject',
'the last class in the MRO should be SuperObject',
f'mro={[cls.__name__ for cls in mro]}'
)
# super().__init__ is guaranteed to be object.__init__
init = super().__init__
init()
example usage:
class A(SuperObject):
def __init__(self, **kwargs):
print("A")
super(A, self).__init__(**kwargs)
class B(SuperObject):
def __init__(self, **kwargs):
print("B")
super(B, self).__init__(**kwargs)
class C(A):
def __init__(self, age, **kwargs):
print("C",f"age={age}")
super(C, self).__init__(age=age, **kwargs)
class D(B):
def __init__(self, name, **kwargs):
print("D", f"name={name}")
super(D, self).__init__(name=name, **kwargs)
class E(C,D):
def __init__(self, name, age, *args, **kwargs):
print( "E", f"name={name}", f"age={age}")
super(E, self).__init__(name=name, age=age, *args, **kwargs)
E(name='python', age=28)
output:
E name=python age=28
C age=28
A
D name=python
B
SuperObject
None of the other answers resize the text based off the amount of text and the size of the doughnut. Here is a small script you can use to dynamically place any amount of text in the middle, and it will automatically resize it.
Example: http://jsfiddle.net/kdvuxbtj/
It will take any amount of text in the doughnut sized perfect for the doughnut. To avoid touching the edges you can set a side-padding as a percentage of the diameter of the inside of the circle. If you don't set it, it will default to 20. You also the color, the font, and the text. The plugin takes care of the rest.
The plugin code will start with a base font size of 30px. From there it will check the width of the text and compare it against the radius of the circle and resize it based off the circle/text width ratio.
It has a default minimum font size of 20px. If the text would exceed the bounds at the minimum font size, it will wrap the text. The default line height when wrapping the text is 25px, but you can change it. If you set the default minimum font size to false, the text will become infinitely small and will not wrap.
It also has a default max font size of 75px in case there is not enough text and the lettering would be too big.
This is the plugin code
Chart.pluginService.register({
beforeDraw: function(chart) {
if (chart.config.options.elements.center) {
// Get ctx from string
var ctx = chart.chart.ctx;
// Get options from the center object in options
var centerConfig = chart.config.options.elements.center;
var fontStyle = centerConfig.fontStyle || 'Arial';
var txt = centerConfig.text;
var color = centerConfig.color || '#000';
var maxFontSize = centerConfig.maxFontSize || 75;
var sidePadding = centerConfig.sidePadding || 20;
var sidePaddingCalculated = (sidePadding / 100) * (chart.innerRadius * 2)
// Start with a base font of 30px
ctx.font = "30px " + fontStyle;
// Get the width of the string and also the width of the element minus 10 to give it 5px side padding
var stringWidth = ctx.measureText(txt).width;
var elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;
// Find out how much the font can grow in width.
var widthRatio = elementWidth / stringWidth;
var newFontSize = Math.floor(30 * widthRatio);
var elementHeight = (chart.innerRadius * 2);
// Pick a new font size so it will not be larger than the height of label.
var fontSizeToUse = Math.min(newFontSize, elementHeight, maxFontSize);
var minFontSize = centerConfig.minFontSize;
var lineHeight = centerConfig.lineHeight || 25;
var wrapText = false;
if (minFontSize === undefined) {
minFontSize = 20;
}
if (minFontSize && fontSizeToUse < minFontSize) {
fontSizeToUse = minFontSize;
wrapText = true;
}
// Set font settings to draw it correctly.
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
var centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);
ctx.font = fontSizeToUse + "px " + fontStyle;
ctx.fillStyle = color;
if (!wrapText) {
ctx.fillText(txt, centerX, centerY);
return;
}
var words = txt.split(' ');
var line = '';
var lines = [];
// Break words up into multiple lines if necessary
for (var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = ctx.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > elementWidth && n > 0) {
lines.push(line);
line = words[n] + ' ';
} else {
line = testLine;
}
}
// Move the center up depending on line height and number of lines
centerY -= (lines.length / 2) * lineHeight;
for (var n = 0; n < lines.length; n++) {
ctx.fillText(lines[n], centerX, centerY);
centerY += lineHeight;
}
//Draw text in center
ctx.fillText(line, centerX, centerY);
}
}
});
And you use the following options in your chart object
options: {
elements: {
center: {
text: 'Red is 2/3 the total numbers',
color: '#FF6384', // Default is #000000
fontStyle: 'Arial', // Default is Arial
sidePadding: 20, // Default is 20 (as a percentage)
minFontSize: 20, // Default is 20 (in px), set to false and text will not wrap.
lineHeight: 25 // Default is 25 (in px), used for when text wraps
}
}
}
Credit to @Jenna Sloan for help with the math used in this solution.
for example on debian
sudo gpasswd -a svn-admin www-data
sudo chgrp -R www-data svn/
sudo chmod -R g=rwsx svn/
http://php.net/manual/en/function.unlink.php
Unlink can safely remove a single file; just make sure the file you are removing it actually a file and not a directory ('.' or '..')
if (is_file($filepath))
{
unlink($filepath);
}
You could also use the generic function cbind()
and lm()
without the intercept:
cbind(lm(d$Rate1~-1+d$Name)$coef,lm(d$Rate2~-1+d$Name)$coef)
> [,1] [,2]
>d$NameAira 16.33333 47.00000
>d$NameBen 31.33333 50.33333
>d$NameCat 44.66667 54.00000
Okay. If you do not want to store the file in database and store in the application, like assets (custom folder), you can define non-db instance variable defined by attr_accessor: document and use form_for - f.file_field
to get the file,
In controller,
@person = Person.new(person_params)
Here person_params
return whitelisted params[:person]
(define yourself)
Save file as,
dir = "#{Rails.root}/app/assets/custom_path"
FileUtils.mkdir(dir) unless File.directory? dir
document = @person.document.document_file_name # check document uploaded params
File.copy_stream(@font.document, "#{dir}/#{document}")
Note, Add this path in .gitignore
& if you want to use this file again add this path asset_path
an of application by application.rb
Whenever form read file field, it get store in tmp folder, later you can store at your place, I gave example to store at assets
note: Storing files like this will increase the size of the application, better to store in the database using paperclip
.
You do not include a <scope>
tag in your dependency. If you add it, your dependency becomes something like:
<dependency>
<groupId>org.openrdf.sesame</groupId>
<artifactId>sesame-runtime</artifactId>
<version>2.7.2</version>
<scope> ... </scope>
</dependency>
The "scope" tag tells maven at which stage of the build your dependency is needed. Examples for the values to put inside are "test", "provided" or "runtime" (omit the quotes in your pom). I do not know your dependency so I cannot tell you what value to choose. Please consult the Maven documentation and the documentation of your dependency.
The accepted answer is really old (and now wrong). Here's the information (with source) based on the current version of Connect (3.0) / Express (4.0).
http / https createServer
which simply takes a callback(req,res) e.g.
var server = http.createServer(function (request, response) {
// respond
response.write('hello client!');
response.end();
});
server.listen(3000);
Middleware is basically any software that sits between your application code and some low level API. Connect extends the built-in HTTP server functionality and adds a plugin framework. The plugins act as middleware and hence connect is a middleware framework
The way it does that is pretty simple (and in fact the code is really short!). As soon as you call var connect = require('connect'); var app = connect();
you get a function app
that can:
.use
(source) to manage plugins (that comes from here because of this simple line of code). Because of 1.) you can do the following :
var app = connect();
// Register with http
http.createServer(app)
.listen(3000);
Combine with 2.) and you get:
var connect = require('connect');
// Create a connect dispatcher
var app = connect()
// register a middleware
.use(function (req, res, next) { next(); });
// Register with http
http.createServer(app)
.listen(3000);
Connect provides a utility function to register itself with http
so that you don't need to make the call to http.createServer(app)
. Its called listen
and the code simply creates a new http server, register's connect as the callback and forwards the arguments to http.listen
. From source
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
So, you can do:
var connect = require('connect');
// Create a connect dispatcher and register with http
var app = connect()
.listen(3000);
console.log('server running on port 3000');
It's still your good old http.createServer
with a plugin framework on top.
ExpressJS and connect are parallel projects. Connect is just a middleware framework, with a nice use
function. Express does not depend on Connect (see package.json). However it does the everything that connect does i.e:
createServer
like connect since it too is just a function that can take a req
/res
pair (source). listen
function to register itself with httpIn addition to what connect provides (which express duplicates), it has a bunch of more features. e.g.
The use
function of ExpressJS and connect is compatible and therefore the middleware is shared. Both are middleware frameworks, express just has more than a simple middleware framework.
My opinion: you are informed enough ^based on above^ to make your own choice.
http.createServer
if you are creating something like connect / expressjs from scratch. http.createServer
Most people should just use ExpressJS.
These might have been true as some point in time, but wrong now:
that inherits an extended version of http.Server
Wrong. It doesn't extend it and as you have seen ... uses it
Express does to Connect what Connect does to the http module
Express 4.0 doesn't even depend on connect. see the current package.json dependencies section
These commands worked for me:
npm uninstall -g cordova
npm uninstall -g ionic
A MIME type is a label used to identify a type of data. It is used so software can know how to handle the data. It serves the same purpose on the Internet that file extensions do on Microsoft Windows.
So if a server says "This is text/html" the client can go "Ah, this is an HTML document, I can render that internally", while if the server says "This is application/pdf" the client can go "Ah, I need to launch the FoxIt PDF Reader plugin that the user has installed and that has registered itself as the application/pdf handler."
You'll most commonly find them in the headers of HTTP messages (to describe the content that an HTTP server is responding with or the formatting of the data that is being POSTed in a request) and in email headers (to describe the message format and attachments).
Persist should be called only on new entities, while merge
is meant to reattach detached entities.
If you're using the assigned generator, using merge
instead of persist
can cause a redundant SQL statement.
Also, calling merge for managed entities is also a mistake since managed entities are automatically managed by Hibernate, and their state is synchronized with the database record by the dirty checking mechanism upon flushing the Persistence Context.
All above options are failed, I got the permanent solution for this.
Add below line in package.json under dependencies and run npm install
. This will add nodemon package to node_modules and there you go, enjoy the coding.
"nodemon": "^1.17.*"
Go to File> Project Structure (or press Ctrl+Alt+Shift+S), A popup will open now go to SDK Location Tab you will find JDK Location there refer this image to be more clear.
$ git diff tag1 tag2
or show log between them:
$ git log tag1..tag2
sometimes it may be convenient to see only the list of files that were changed:
$ git diff tag1 tag2 --stat
and then look at the differences for some particular file:
$ git diff tag1 tag2 -- some/file/name
A tag is only a reference to the latest commit 'on that tag', so that you are doing a diff on the commits between them.
(Make sure to do git pull --tags
first)
Also, a good reference: http://learn.github.com/p/diff.html
MailMessage msg = new MailMessage();
msg.Body = ....;
msg.To.Add(...);
msg.To.Add(...);
SmtpClient smtp = new SmtpClient();
smtp.Send(msg);
To
is a MailAddressCollection
, so you can add how many addresses you need.
If you need a display name, try this:
MailAddress to = new MailAddress(
String.Format("{0} <{1}>",display_name, address));
There are two ways to think about your phrase "application heap size available":
How much heap can my app use before a hard error is triggered? And
How much heap should my app use, given the constraints of the Android OS version and hardware of the user's device?
There is a different method for determining each of the above.
For item 1 above: maxMemory()
which can be invoked (e.g., in your main activity's onCreate()
method) as follows:
Runtime rt = Runtime.getRuntime();
long maxMemory = rt.maxMemory();
Log.v("onCreate", "maxMemory:" + Long.toString(maxMemory));
This method tells you how many total bytes of heap your app is allowed to use.
For item 2 above: getMemoryClass()
which can be invoked as follows:
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass();
Log.v("onCreate", "memoryClass:" + Integer.toString(memoryClass));
This method tells you approximately how many megabytes of heap your app should use if it wants to be properly respectful of the limits of the present device, and of the rights of other apps to run without being repeatedly forced into the onStop()
/ onResume()
cycle as they are rudely flushed out of memory while your elephantine app takes a bath in the Android jacuzzi.
This distinction is not clearly documented, so far as I know, but I have tested this hypothesis on five different Android devices (see below) and have confirmed to my own satisfaction that this is a correct interpretation.
For a stock version of Android, maxMemory()
will typically return about the same number of megabytes as are indicated in getMemoryClass()
(i.e., approximately a million times the latter value).
The only situation (of which I am aware) for which the two methods can diverge is on a rooted device running an Android version such as CyanogenMod, which allows the user to manually select how large a heap size should be allowed for each app. In CM, for example, this option appears under "CyanogenMod settings" / "Performance" / "VM heap size".
NOTE: BE AWARE THAT SETTING THIS VALUE MANUALLY CAN MESS UP YOUR SYSTEM, ESPECIALLY if you select a smaller value than is normal for your device.
Here are my test results showing the values returned by maxMemory()
and getMemoryClass()
for four different devices running CyanogenMod, using two different (manually-set) heap values for each:
In addition to the above, I tested on a Novo7 Paladin tablet running Ice Cream Sandwich. This was essentially a stock version of ICS, except that I've rooted the tablet through a simple process that does not replace the entire OS, and in particular does not provide an interface that would allow the heap size to be manually adjusted.
For that device, here are the results:
Also (per Kishore in a comment below):
And (per akauppi's comment):
Per a comment from cmcromance:
And (per tencent's comments):
Other Devices
I haven't tested these two methods using the special android:largeHeap="true" manifest option available since Honeycomb, but thanks to cmcromance and tencent we do have some sample largeHeap values, as reported above.
My expectation (which seems to be supported by the largeHeap numbers above) would be that this option would have an effect similar to setting the heap manually via a rooted OS - i.e., it would raise the value of maxMemory()
while leaving getMemoryClass()
alone. There is another method, getLargeMemoryClass(), that indicates how much memory is allowable for an app using the largeHeap setting. The documentation for getLargeMemoryClass() states, "most applications should not need this amount of memory, and should instead stay with the getMemoryClass() limit."
If I've guessed correctly, then using that option would have the same benefits (and perils) as would using the space made available by a user who has upped the heap via a rooted OS (i.e., if your app uses the additional memory, it probably will not play as nicely with whatever other apps the user is running at the same time).
Note that the memory class apparently need not be a multiple of 8MB.
We can see from the above that the getMemoryClass()
result is unchanging for a given device/OS configuration, while the maxMemory() value changes when the heap is set differently by the user.
My own practical experience is that on the G1 (which has a memory class of 16), if I manually select 24MB as the heap size, I can run without erroring even when my memory usage is allowed to drift up toward 20MB (presumably it could go as high as 24MB, although I haven't tried this). But other similarly large-ish apps may get flushed from memory as a result of my own app's pigginess. And, conversely, my app may get flushed from memory if these other high-maintenance apps are brought to the foreground by the user.
So, you cannot go over the amount of memory specified by maxMemory()
. And, you should try to stay within the limits specified by getMemoryClass()
. One way to do that, if all else fails, might be to limit functionality for such devices in a way that conserves memory.
Finally, if you do plan to go over the number of megabytes specified in getMemoryClass()
, my advice would be to work long and hard on the saving and restoring of your app's state, so that the user's experience is virtually uninterrupted if an onStop()
/ onResume()
cycle occurs.
In my case, for reasons of performance I'm limiting my app to devices running 2.2 and above, and that means that almost all devices running my app will have a memoryClass of 24 or higher. So I can design to occupy up to 20MB of heap and feel pretty confident that my app will play nice with the other apps the user may be running at the same time.
But there will always be a few rooted users who have loaded a 2.2 or above version of Android onto an older device (e.g., a G1). When you encounter such a configuration, ideally, you ought to pare down your memory use, even if maxMemory()
is telling you that you can go much higher than the 16MB that getMemoryClass()
is telling you that you should be targeting. And if you cannot reliably ensure that your app will live within that budget, then at least make sure that onStop()
/ onResume()
works seamlessly.
getMemoryClass()
, as indicated by Diane Hackborn (hackbod) above, is only available back to API level 5 (Android 2.0), and so, as she advises, you can assume that the physical hardware of any device running an earlier version of the OS is designed to optimally support apps occupying a heap space of no more than 16MB.
By contrast, maxMemory()
, according to the documentation, is available all the way back to API level 1. maxMemory()
, on a pre-2.0 version, will probably return a 16MB value, but I do see that in my (much later) CyanogenMod versions the user can select a heap value as low as 12MB, which would presumably result in a lower heap limit, and so I would suggest that you continue to test the maxMemory()
value, even for versions of the OS prior to 2.0. You might even have to refuse to run in the unlikely event that this value is set even lower than 16MB, if you need to have more than maxMemory()
indicates is allowed.
v is a query parameter, technically you need to consider cases ala: http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk
In .NET I would recommend to use System.Web.HttpUtility.ParseQueryString
HttpUtility.ParseQueryString(url)["v"];
And you don't even need to check the key, as it will return null if the key is not in the collection.
Besides formatting, puts
returns a nonnegative integer if successful or EOF
if unsuccessful; while printf
returns the number of characters printed (not including the trailing null).
You can also use the clock_gettime. This method can be used to measure:
Code is as follows:
#include < time.h >
#include <iostream>
int main(){
timespec ts_beg, ts_end;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts_beg);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts_end);
std::cout << (ts_end.tv_sec - ts_beg.tv_sec) + (ts_end.tv_nsec - ts_beg.tv_nsec) / 1e9 << " sec";
}
`
Arrays have numerical indexes. So,
a = new Array();
a['a1']='foo';
a['a2']='bar';
and
b = new Array(2);
b['b1']='foo';
b['b2']='bar';
are not adding elements to the array, but adding .a1
and .a2
properties to the a
object (arrays are objects too). As further evidence, if you did this:
a = new Array();
a['a1']='foo';
a['a2']='bar';
console.log(a.length); // outputs zero because there are no items in the array
Your third option:
c=['c1','c2','c3'];
is assigning the variable c
an array with three elements. Those three elements can be accessed as: c[0]
, c[1]
and c[2]
. In other words, c[0] === 'c1'
and c.length === 3
.
Javascript does not use its array functionality for what other languages call associative arrays where you can use any type of key in the array. You can implement most of the functionality of an associative array by just using an object in javascript where each item is just a property like this.
a = {};
a['a1']='foo';
a['a2']='bar';
It is generally a mistake to use an array for this purpose as it just confuses people reading your code and leads to false assumptions about how the code works.
This is null-safe
Number tmp = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
Long value1 = tmp == null ? null : tmp.longValue();
I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.
var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
.Select (m => new
{
UserName = u.UserProfile.UserName,
RoleName = u.Roles.RoleName
});
You could also use matrix multiplication (aka dot product):
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [0,1,2]
c = numpy.diag(b)
numpy.dot(c,a)
Which is more elegant is probably a matter of taste.
As per current versions, Android doesn't ask for permission to interact with the internet but you can add the below code which will help for users using older versions Just add these in AndroidManifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
From your description, what you probably want is os.Readdirnames.
func (f *File) Readdirnames(n int) (names []string, err error)
Readdirnames reads the contents of the directory associated with file and returns a slice of up to n names of files in the directory, in directory order. Subsequent calls on the same file will yield further names.
...
If n <= 0, Readdirnames returns all the names from the directory in a single slice.
Snippet:
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
names, err := file.Readdirnames(0)
if err != nil {
return err
}
fmt.Println(names)
Credit to SquattingSlavInTracksuit's comment; I'd have suggested promoting their comment to an answer if I could.
For those using jQuery there's a convenient method: http://api.jquery.com/change/
Pure JS equivalent for jQuery hide()/show() :
function hide(el) {
el.style.visibility = 'hidden';
return el;
}
function show(el) {
el.style.visibility = 'visible';
return el;
}
hide(document.querySelector(".test"));
// hide($('.test')[0]) // usage with jQuery
We use return el
due to satisfy fluent interface "desing pattern".
Here is working example.
Below I also provide HIGHLY unrecommended alternative, which is however probably more "close to question" answer:
HTMLElement.prototype.hide = function() {
this.style.visibility = 'hidden';
return this;
}
HTMLElement.prototype.show = function() {
this.style.visibility = 'visible';
return this;
}
document.querySelector(".test1").hide();
// $('.test1')[0].hide(); // usage with jQuery
of course this not implement jQuery 'each' (given in @JamesAllardice answer) because we use pure js here.
Working example is here.
We recently had the issue when trying to run the code from Visual Studio. In that case you need to do
TOOLS > OPTIONS > Projects and Solutions > WEB PROJECTS and check the "Use the 64 bit version of IIS Express for web sites and projects".
require(stringr)
Define a very simple function
str_words <- function(sentence) {
str_count(sentence, " ") + 1
}
Check
str_words(This is a sentence with six words)
Give ID to legend and apply css. Like add id hello to legend() the css is as follw:
#legend legend {
display: block;
width: 100%;
padding: 0;
margin-bottom: 20px;
font-size: 21px;
line-height: inherit;
color: #333333;
border: 0;
border-bottom: 1px solid #e5e5e5;
}
EDIT [Added suggestion from Dan Nissenbaum]:
By one convention, .hpp files are used when the prototypes are defined in the header itself. Such definitions in headers are useful in case of templates, since the compiler generates the code for each type only on template instantiation. Hence, if they are not defined in header files, their definitions will not be resolved at link time from other compilation units. If your project is a C++ only project that makes heavy use of templates, this convention will be useful.
Certain template libraries that adhere to this convention provide headers with .hpp extensions to indicate that they do not have corresponding .cpp files.
another convention is to use .h for C headers and .hpp for C++; a good example would be the boost library.
Quote from Boost FAQ,
File extensions communicate the "type" of the file, both to humans and to computer programs. The '.h' extension is used for C header files, and therefore communicates the wrong thing about C++ header files. Using no extension communicates nothing and forces inspection of file contents to determine type. Using '.hpp' unambiguously identifies it as C++ header file, and works well in actual practice. (Rainer Deyke)
The assertNotNull()
method means "a passed parameter must not be null
": if it is null then the test case fails.
The assertNull()
method means "a passed parameter must be null
": if it is not null then the test case fails.
String str1 = null;
String str2 = "hello";
// Success.
assertNotNull(str2);
// Fail.
assertNotNull(str1);
// Success.
assertNull(str1);
// Fail.
assertNull(str2);
You could build up a new array without the undesired element, then assign it back to the old array. This works in bash
:
array=(pluto pippo)
new_array=()
for value in "${array[@]}"
do
[[ $value != pluto ]] && new_array+=($value)
done
array=("${new_array[@]}")
unset new_array
This yields:
echo "${array[@]}"
pippo
No its not. Use Meyers CSS reset :) http://meyerweb.com/eric/tools/css/reset/
css
div {
width: 100px;
height: 100px;
border-radius: 50%;
background: red;
}
html
<div></div>
In my case, I modified directory tag.
From
<Directory "D:/Devel/matysart/matysart_dev1">
Allow from all
Order Deny,Allow
</Directory>
To
<Directory "D:/Devel/matysart/matysart_dev1">
Require local
</Directory>
And it seriously worked. It's seems changed with Apache 2.4.2.
For IntelliJ 2019:
Intellij IDEA -> Preferences -> Build, Execution, Deployment -> Build Tools -> Gradle -> Gradle JVM
Select correct version.
Use:
docker inspect -f "{{.Name}} {{.Config.Cmd}}" $(docker ps -a -q)
... it does a "docker inspect" for all containers.
I prefer to use mutex mechanism in such cases, but if you really want to use boolean, then you should declare it as volatile (to provide the change visibility across threads) and just run the body-less cycle with that boolean as a condition :
//.....some class
volatile boolean someBoolean;
Thread someThread = new Thread() {
@Override
public void run() {
//some actions
while (!someBoolean); //wait for condition
//some actions
}
};
Tried this on firefox, works http://jsfiddle.net/Tm26Q/1/
$(function(){
/** Just to mimic a blinking box on the page**/
setInterval(function(){$("div#box").hide();},2001);
setInterval(function(){$("div#box").show();},1000);
/**/
});
$("div#box").on("DOMAttrModified",
function(){if($(this).is(":visible"))console.log("visible");});
UPDATE
Currently the Mutation Events (like
DOMAttrModified
used in the solution) are replaced by MutationObserver, You can use that to detect DOM node changes like in the above case.
Notably for me on NodeJS, if I'm working with databases and my field names are underscore separated, I also use them in the struct keys.
This is because db fields have a lot of acronyms/abbreviations so something like appSNSInterfaceRRTest looks a bit messy but app_sns_interface_rr_test is nicer.
In Javascript variables are all camelCase and class names (constructors) are ProperCase, so you'd see something like
var devTask = {
task_id: 120,
store_id: 2118,
task_name: 'generalLedger'
};
or
generalLedgerTask = new GeneralLedgerTask( devTask );
And of course in JSON keys/strings are wrapped in double quotes, but then you just use the JSON.stringify and pass in JS objects, so don't need to worry about that.
I struggled with this a bit until I found this happy medium between JSON and JS naming conventions.
Slack has a cool way of making tabs small viewport friendly on some of their admin pages. I made something similar using bootstrap. It's kind of a tabs ? dropdown.
Demo: http://jsbin.com/nowuyi/1
Here's what it looks like on a big viewport:
Here's how it looks collapsed on a small viewport:
Here's how it looks expanded on a small viewport:
the HTML is exactly the same as default bootstrap tabs.
There is a small JS snippet, which requires jquery (and inserts two span elements into the DOM):
$.fn.responsiveTabs = function() {
this.addClass('responsive-tabs');
this.append($('<span class="glyphicon glyphicon-triangle-bottom"></span>'));
this.append($('<span class="glyphicon glyphicon-triangle-top"></span>'));
this.on('click', 'li.active > a, span.glyphicon', function() {
this.toggleClass('open');
}.bind(this));
this.on('click', 'li:not(.active) > a', function() {
this.removeClass('open');
}.bind(this));
};
$('.nav.nav-tabs').responsiveTabs();
And then there is a lot of css (less):
@xs: 768px;
.responsive-tabs.nav-tabs {
position: relative;
z-index: 10;
height: 42px;
overflow: visible;
border-bottom: none;
@media(min-width: @xs) {
border-bottom: 1px solid #ddd;
}
span.glyphicon {
position: absolute;
top: 14px;
right: 22px;
&.glyphicon-triangle-top {
display: none;
}
@media(min-width: @xs) {
display: none;
}
}
> li {
display: none;
float: none;
text-align: center;
&:last-of-type > a {
margin-right: 0;
}
> a {
margin-right: 0;
background: #fff;
border: 1px solid #DDDDDD;
@media(min-width: @xs) {
margin-right: 4px;
}
}
&.active {
display: block;
a {
@media(min-width: @xs) {
border-bottom-color: transparent;
}
border: 1px solid #DDDDDD;
border-radius: 2px;
}
}
@media(min-width: @xs) {
display: block;
float: left;
}
}
&.open {
span.glyphicon {
&.glyphicon-triangle-top {
display: block;
@media(min-width: @xs) {
display: none;
}
}
&.glyphicon-triangle-bottom {
display: none;
}
}
> li {
display: block;
a {
border-radius: 0;
}
&:first-of-type a {
border-radius: 2px 2px 0 0;
}
&:last-of-type a {
border-radius: 0 0 2px 2px;
}
}
}
}
It is amusing to return 418 I'm a teapot
to requests that are obviously crafted or malicious and "can't happen", such as failing CSRF check or missing request properties.
2.3.2 418 I'm a teapot
Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.
To keep it reasonably serious, I restrict usage of funny error codes to RESTful endpoints that are not directly exposed to the user.
Here is the Code snippet to find the closest element to a number from an array in Complexity O(nlog(n)) :-
Input :- {1,60,0,-10,100,87,56} Element:- 56 Closest Number in Array:- 60
Source Code (Java):
package com.algo.closestnumberinarray;
import java.util.TreeMap;
public class Find_Closest_Number_In_Array {
public static void main(String arsg[]) {
int array[] = { 1, 60, 0, -10, 100, 87, 69 };
int number = 56;
int num = getClosestNumber(array, number);
System.out.println("Number is=" + num);
}
public static int getClosestNumber(int[] array, int number) {
int diff[] = new int[array.length];
TreeMap<Integer, Integer> keyVal = new TreeMap<Integer, Integer>();
for (int i = 0; i < array.length; i++) {
if (array[i] > number) {
diff[i] = array[i] - number;
keyVal.put(diff[i], array[i]);
} else {
diff[i] = number - array[i];
keyVal.put(diff[i], array[i]);
}
}
int closestKey = keyVal.firstKey();
int closestVal = keyVal.get(closestKey);
return closestVal;
}
}
og:title
is one of the open graph meta tags. og:...
properties define objects in a social graph. They are used for example by Facebook.
og:title
stands for the title of your object as it should appear within the graph (see here for more http://ogp.me/ )
I know this is an "older" post. This question and the provided answers helped me get ideas for my own problem. I think this solution addresses the OP question (intersecting borders with 4 and 2 columns depending on display)
Fiddle: https://jsfiddle.net/tqmfpwhv/1/
css based on OP information, media query at end is for med & lg view.
.vr-all {
padding:0px;
border-right:1px solid #CC0000;
}
.vr-xs {
padding:0px;
}
.vr-md {
padding:0px;
}
.hrspacing { padding:0px; }
.hrcolor {
border-color: #CC0000;
border-style: solid;
border-bottom: 1px;
margin:0px;
padding:0px;
}
/* for medium and up */
@media(min-width:992px){
.vr-xs {
border-right:1px solid #CC0000;
}
}
html adjustments to OP provided code. Red border and Img links for example.
<div class="container">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="one">
<h5>Rich Media Ad Production</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" />
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="two">
<h5>Web Design & Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for only x-small/small viewports -->
<div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="three">
<h5>Mobile Apps Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="four">
<h5>Creative Design</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for for all viewports -->
<div class="col-xs-12 hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="five">
<h5>Web Analytics</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-xs" id="six">
<h5>Search Engine Marketing</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<!-- hr for only x-small/small viewports -->
<div class="col-xs-12 col-sm-12 hidden-md hidden-lg hrspacing"><hr class="hrcolor"></div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-all" id="seven">
<h5>Mobile Apps Development</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
<div class="col-xs-6 col-sm-6 col-md-3 text-center vr-md" id="eight">
<h5>Quality Assurance</h5>
<img src="http://png-1.findicons.com/files/icons/2338/reflection/128/mobile_phone.png" >
</div>
</div>
</div>
For me non of the above worked and I had to do as below, and it worked,
sudo -E add-apt-repository ppa:openjdk-r/ppa
and then,
sudo apt-get update
sudo apt-get install openjdk-8-jdk
Reference: https://askubuntu.com/questions/644188/updating-jdk-7-to-8-unable-to-locate-package
In Manifest theme sets with style name (AppTheme and myDialog)/ You can set new styles in styles.xml
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MyActivity2"
android:label="@string/title_activity_my_activity2"
android:theme="@style/myDialog"
>
</activity>
</application>
styles.xml example
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Black">
<!-- Customize your theme here. -->
</style>
<style name="myDialog" parent="android:Theme.Dialog">
</style>
In parent you set actualy the theme
An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.
Maybe this will help
http://www.math.utah.edu/docs/info/gawk_5.html
awk '$3 ~ /snow|snowman/' dummy_file
Try Vim, emacs (has a low maximum buffer size limit if compiled in 32-bit mode), hex tools
That's perfectly normal.
If you want gulp-cli
available on the command line, you need to install it globally.
npm install --global gulp-cli
Also, node_modules/.bin/
isn't in your $PATH
. But it is automatically added by npm when running npm scripts (see this blog post for reference).
So you could add scripts
to your package.json
file:
{
"name": "your-app",
"version": "0.0.1",
"scripts": {
"gulp": "gulp",
"minify": "gulp minify"
}
}
You could then run npm run gulp
or npm run minify
to launch gulp tasks.
Another way to do that is StringTokenizer. ex:-
public static void main(String[] args) {
String str = "This is a sample string";
StringTokenizer st = new StringTokenizer(str," ");
String starr[]=new String[st.countTokens()];
while (st.hasMoreElements()) {
starr[i++]=st.nextElement();
}
}
We offer a tool called DocFlex/XML XSDDoc that allows you to enjoy both things at once:
The diagrams in fact are generated not by us, but by Altova XMLSpy. We implemented an Integration with XMLSpy (with the full support of all diagram hyperlinks):
Here you can see the full this doc: http://www.filigris.com/docflex-xml/xsddoc/examples/html/XMLSchema/index.html
The whole thing provides a functionality not offered by any single vendor right now on the market!
Some our customers were so impressed that they purchased an extra license for XMLSpy only because of our tool. (That's no joke!)
Currently, we've also implemented similar integrations with other XML editors:
See: http://www.filigris.com/docflex-xml/OxygenXML/demo/html/xslt20/index.html
See: http://www.filigris.com/docflex-xml/LiquidXML/demo/html/XMLSchema/index.html
Concerning what all those diagrams depict... Essentially, they are all about content model of XSD elements (as well as other XSD components that lead to elements: complexTypes, element/attribute groups). It seems, there are two approaches here:
I personally believe that the diagrams generated by XMLSpy are more useful.
Yet, there were no attempts so far (at least known to me) to depict graphically anything else contained in XML schemas, although one can imagine many...
The one the eclipse run in is the default java installed in the system (unless set specifically in the eclipse.ini file, use the -vm option). You can of course add more Java runtimes and use them for your projects
The string you've written is the right one, but it is specific to your environment. If you want to know the exact update then run the following code:
public class JavaVersion {
public static void main(String[] args) {
System.out.println(System.getProperty("java.runtime.version"));
}
}
You're using span6
and span2
. Both of these classes are "float:left
" meaning, if possible they will always try to sit next to each other.
Twitter bootstrap is based on a 12 grid system. So you should generally always get the span**#**
to add up to 12.
E.g.: span4
+ span4
+ span4
OR span6
+ span6
OR span4
+ span3
+ span5
.
To force a span down though, without listening to the previous float you can use twitter bootstraps clearfix
class. To do this, your code should look like this:
<ul class="nav nav-tabs span2">
<li><a href="./index.html"><i class="icon-black icon-music"></i></a></li>
<li><a href="./about.html"><i class="icon-black icon-eye-open"></i></a></li>
<li><a href="./team.html"><i class="icon-black icon-user"></i></a></li>
<li><a href="./contact.html"><i class="icon-black icon-envelope"></i></a></li>
</ul>
<!-- Notice this following line -->
<div class="clearfix"></div>
<div class="well span6">
<h3>I wish this appeared on the next line without having to gratuitously use BR!</h3>
</div>
java
packages are base, and javax
packages are extensions.
Swing was an extension because AWT was the original UI API. Swing came afterwards, in version 1.1.
And in swift, you don't need to import "QuartzCore/QuartzCore.h"
Just use:
button.layer.borderWidth = 0.8
button.layer.borderColor = (UIColor( red: 0.5, green: 0.5, blue:0, alpha: 1.0 )).cgColor
or
button.layer.borderWidth = 0.8
button.layer.borderColor = UIColor.grayColor().cgColor
If you're using a graphical tool. It shows you the schema right next to the table name. In case of DB Browser For Sqlite, click to open the database(top right corner), navigate and open your database, you'll see the information populated in the table as below.
right click on the record/table_name, click on copy create statement and there you have it.
Hope it helped some beginner who failed to work with the commandline.
Install yaml from the PyYAML home pagee: http://www.pyyaml.org/wiki/PyYAML
Select the appropriate version for your OS and Python.
For a quick non-JQuery function...
function jsonToQueryString(json) {
return '?' +
Object.keys(json).map(function(key) {
return encodeURIComponent(key) + '=' +
encodeURIComponent(json[key]);
}).join('&');
}
Note this doesn't handle arrays or nested objects.
Add to the info plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
import Alamofire
class AlamofireDataManager {
fileprivate let queue: DispatchQueue
init(queue: DispatchQueue) { self.queue = queue }
private func createError(message: String, code: Int) -> Error {
return NSError(domain: "dataManager", code: code, userInfo: ["message": message ])
}
private func make(session: URLSession = URLSession.shared, request: URLRequest, closure: ((Result<[String: Any]>) -> Void)?) {
Alamofire.request(request).responseJSON { response in
let complete: (Result<[String: Any]>) ->() = { result in DispatchQueue.main.async { closure?(result) } }
switch response.result {
case .success(let value): complete(.success(value as! [String: Any]))
case .failure(let error): complete(.failure(error))
}
}
}
func searchRequest(term: String, closure: ((Result<[String: Any]>) -> Void)?) {
guard let url = URL(string: "https://itunes.apple.com/search?term=\(term.replacingOccurrences(of: " ", with: "+"))") else { return }
let request = URLRequest(url: url)
make(request: request) { response in closure?(response) }
}
}
private lazy var alamofireDataManager = AlamofireDataManager(queue: DispatchQueue(label: "DataManager.queue", qos: .utility))
//.........
alamofireDataManager.searchRequest(term: "jack johnson") { result in
print(result.value ?? "no data")
print(result.error ?? "no error")
}
import Foundation
class DataManager {
fileprivate let queue: DispatchQueue
init(queue: DispatchQueue) { self.queue = queue }
private func createError(message: String, code: Int) -> Error {
return NSError(domain: "dataManager", code: code, userInfo: ["message": message ])
}
private func make(session: URLSession = URLSession.shared, request: URLRequest, closure: ((_ json: [String: Any]?, _ error: Error?)->Void)?) {
let task = session.dataTask(with: request) { [weak self] data, response, error in
self?.queue.async {
let complete: (_ json: [String: Any]?, _ error: Error?) ->() = { json, error in DispatchQueue.main.async { closure?(json, error) } }
guard let self = self, error == nil else { complete(nil, error); return }
guard let data = data else { complete(nil, self.createError(message: "No data", code: 999)); return }
do {
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
complete(json, nil)
}
} catch let error { complete(nil, error); return }
}
}
task.resume()
}
func searchRequest(term: String, closure: ((_ json: [String: Any]?, _ error: Error?)->Void)?) {
let url = URL(string: "https://itunes.apple.com/search?term=\(term.replacingOccurrences(of: " ", with: "+"))")
let request = URLRequest(url: url!)
make(request: request) { json, error in closure?(json, error) }
}
}
private lazy var dataManager = DataManager(queue: DispatchQueue(label: "DataManager.queue", qos: .utility))
// .......
dataManager.searchRequest(term: "jack johnson") { json, error in
print(error ?? "nil")
print(json ?? "nil")
print("Update views")
}
One thing you should be very aware of when dealing with encryption:
Trying to be clever and inventing your own thing usually will leave you with something insecure.
You'd probably be best off using one of the cryptography extensions that come with PHP.
Kotlin version below (Updated version of @paul-burke response:
fun openPDFDocument(context: Context, filename: String) {
//Create PDF Intent
val pdfFile = File(Environment.getExternalStorageDirectory().absolutePath + "/" + filename)
val pdfIntent = Intent(Intent.ACTION_VIEW)
pdfIntent.setDataAndType(Uri.fromFile(pdfFile), "application/pdf")
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
//Create Viewer Intent
val viewerIntent = Intent.createChooser(pdfIntent, "Open PDF")
context.startActivity(viewerIntent)
}
Another easy way:
SELECT Date, User, Status, Notes
FROM Test_Most_Recent
WHERE Date in ( SELECT MAX(Date) from Test_Most_Recent group by User)
You can use ManualResetEvent. Reset the event before you fire secondary thread and then use the WaitOne() method to block the current thread. You can then have secondary thread set the ManualResetEvent which would cause the main thread to continue. Something like this:
ManualResetEvent oSignalEvent = new ManualResetEvent(false);
void SecondThread(){
//DoStuff
oSignalEvent.Set();
}
void Main(){
//DoStuff
//Call second thread
System.Threading.Thread oSecondThread = new System.Threading.Thread(SecondThread);
oSecondThread.Start();
oSignalEvent.WaitOne(); //This thread will block here until the reset event is sent.
oSignalEvent.Reset();
//Do more stuff
}
If you want to keep (')
apostrophe in the database use this below code:
$new_value = str_replace("'","\'", $value);
$new_value
can store in database.
I've ended up with the solution below, which can work with either an attribute, <a href="..." disabled="disabled">
, or a class <a href="..." class="disabled">
:
CSS Styles:
a[disabled=disabled], a.disabled {
color: gray;
cursor: default;
}
a[disabled=disabled]:hover, a.disabled:hover {
text-decoration: none;
}
Javascript (in jQuery ready):
$("a[disabled], a.disabled").on("click", function(e){
var $this = $(this);
if ($this.is("[disabled=disabled]") || $this.hasClass("disabled"))
e.preventDefault();
})
Double toBeTruncated = new Double("2.25");
Double truncatedDouble = new BigDecimal(toBeTruncated).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
it will return 2.3
You say
The string is exactly what was written to the file (with the addition of a "\0" at the end, but I don't think that even does anything).
In fact, it does do something (it causes your code to throw a FormatException
:"Invalid character in a Base-64 string") because the Convert.FromBase64String
does not consider "\0" to be a valid Base64 character.
byte[] data1 = Convert.FromBase64String("AAAA\0"); // Throws exception
byte[] data2 = Convert.FromBase64String("AAAA"); // Works
Solution: Get rid of the zero termination. (Maybe call .Trim("\0")
)
Notes:
The MSDN docs for Convert.FromBase64String
say it will throw a FormatException
when
The length of s, ignoring white space characters, is not zero or a multiple of 4.
-or-
The format of s is invalid. s contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.
and that
The base 64 digits in ascending order from zero are the uppercase characters 'A' to 'Z', lowercase characters 'a' to 'z', numerals '0' to '9', and the symbols '+' and '/'.
Depending on how secure you need the configuration files or how reliable your application is, http://activemq.apache.org/encrypted-passwords.html may be a good solution for you.
If you are not too afraid of the password being decrypted and it can be really simple to configure using a bean to store the password key. However, if you need more security you can set an environment variable with the secret and remove it after launch. With this you have to worry about the application / server going down and not application not automatically relaunching.
To remove newlines, use tr:
tr -d '\n'
If you want to replace each newline with a single space:
tr '\n' ' '
The error ba: Event not found
is coming from csh, and is due to csh trying to match !ba
in your history list. You can escape the !
and write the command:
sed ':a;N;$\!ba;s/\n/ /g' # Suitable for csh only!!
but sed is the wrong tool for this, and you would be better off using a shell that handles quoted strings more reasonably. That is, stop using csh and start using bash.
If you're still having this problem, try this:
In Win7 MS has decided to comment the localhost line with that msg that says it's handled in dns. I'm still not exactly clear what they're getting at, except maybe that they're telling folks to use dns for localhost resolution instead of the hosts file. Probably safer that way, anyway.
java.version
is a system property that exists in every JVM. There are two possible formats for it:
1.6.0_23
, 1.7.0
, 1.7.0_80
, 1.8.0_211
9.0.1
, 11.0.4
, 12
, 12.0.1
Here is a trick to extract the major version: If it is a 1.x.y_z
version string, extract the character at index 2 of the string. If it is a x.y.z
version string, cut the string to its first dot character, if one exists.
private static int getVersion() {
String version = System.getProperty("java.version");
if(version.startsWith("1.")) {
version = version.substring(2, 3);
} else {
int dot = version.indexOf(".");
if(dot != -1) { version = version.substring(0, dot); }
} return Integer.parseInt(version);
}
Now you can check the version much more comfortably:
if(getVersion() < 6) {
// ...
}
A variant using Bat/Powershell (need .net framework):
replace.bat :
@echo off
call:DoReplace "Findstr" "replacestr" test.txt test1.txt
exit /b
:DoReplace
echo ^(Get-Content "%3"^) ^| ForEach-Object { $_ -replace %1, %2 } ^| Set-Content %4>Rep.ps1
Powershell.exe -executionpolicy ByPass -File Rep.ps1
if exist Rep.ps1 del Rep.ps1
echo Done
pause
If your inputs are not different enough for a simple hash to use the entire color spectrum, you can use a seeded random number generator instead of a hash function.
I'm using the color coder from Joe Freeman's answer, and David Bau's seeded random number generator.
function stringToColour(str) {
Math.seedrandom(str);
var rand = Math.random() * Math.pow(255,3);
Math.seedrandom(); // don't leave a non-random seed in the generator
for (var i = 0, colour = "#"; i < 3; colour += ("00" + ((rand >> i++ * 8) & 0xFF).toString(16)).slice(-2));
return colour;
}
personally i use underscore for this kind of stuff... so
a = _.find(results,function(rw){ return rw.id == 2 });
then "a" would be the row that you wanted of your array where the id was equal to 2
ps2> start-job {start-sleep 20}
i have not yet figured out how to get stdout in realtime, start-job requires you to poll stdout with get-job
update: i couldn't start-job to easily do what i want which is basically the bash & operator. here's my best hack so far
PS> notepad $profile #edit init script -- added these lines
function beep { write-host `a }
function ajp { start powershell {ant java-platform|out-null;beep} } #new window, stderr only, beep when done
function acjp { start powershell {ant clean java-platform|out-null;beep} }
PS> . $profile #re-load profile script
PS> ajp
For MongoDB earlier than 2.6, the command to add a root user is addUser
(e.g.)
db.addUser({user:'admin',pwd:'<password>',roles:["root"]})
You can do either…
$qb->where('e.fecha BETWEEN :monday AND :sunday')
->setParameter('monday', $monday->format('Y-m-d'))
->setParameter('sunday', $sunday->format('Y-m-d'));
or…
$qb->where('e.fecha > :monday')
->andWhere('e.fecha < :sunday')
->setParameter('monday', $monday->format('Y-m-d'))
->setParameter('sunday', $sunday->format('Y-m-d'));
Your project needs to reference assembly System.Web.dll
. Server is an object of type HttpServerUtility
. Example:
HttpContext.Current.Server.MapPath(path);
If your background image is a vertically aligned sprite sheet, you can horizontally center each sprite like this:
#doit {
background-image: url('images/pic.png');
background-repeat: none;
background-position: 50% [y position of sprite];
}
If your background image is a horizontally aligned sprite sheet, you can vertically center each sprite like this:
#doit {
background-image: url('images/pic.png');
background-repeat: none;
background-position: [x position of sprite] 50%;
}
If your sprite sheet is compact, or you are not trying to center your background image in one of the aforementioned scenarios, these solutions do not apply.
you can download USBview and get all the information you need. Along with the list of devices it will also show you the configuration of each device.
round_to_2dp
is a user-defined function, and nothing can be done unless you posted the declaration of that function.
However, my guess is doing this: number_format($number, 2);
Put this code wherever you want to insert a new line:
bufferedWriter.newLine();
The simplest & the best solution:
mylist.OrderBy(s => s.GetType().GetProperty("PropertyName").GetValue(s));
Doesn't SELECT LEN(column_name)
work?
It may be helpful for someone, although there is no precise answer to this question.
My soap url has a non-standard port(9087 for example), and firewall blocked that request and I took each time this error:
ERROR - 2017-12-19 20:44:11 --> Fatal Error - SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://soalurl.test:9087/orawsv?wsdl' : failed to load external entity "http://soalurl.test:9087/orawsv?wsdl"
I allowed port in firewall and solved the error!
The easiest way I've found to place objects on the left is using FlowLayout.
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
adding a component normally to this panel will place it on the left
Just a small correction to the first answer in this thread.
Even for Stack, you need to create new object with generics if you are using Stack from java util packages.
Right usage:
Stack<Integer> s = new Stack<Integer>();
Stack<String> s1 = new Stack<String>();
s.push(7);
s.push(50);
s1.push("string");
s1.push("stack");
if used otherwise, as mentioned in above post, which is:
/*
Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);
*/
Although this code works fine, has unsafe or unchecked operations which results in error.
Will generate exactly what you want:
D1 = {2:3, 1:89, 4:5, 3:0}
sort_dic = {}
for i in sorted(D1):
sort_dic.update({i:D1[i]})
print sort_dic
{1: 89, 2: 3, 3: 0, 4: 5}
But this is not the correct way to do this, because, It could show a distinct behavior with different dictionaries, which I have learned recently. Hence perfect way has been suggested by Tim In the response of my Query which I am sharing here.
from collections import OrderedDict
sorted_dict = OrderedDict(sorted(D1.items(), key=lambda t: t[0]))
just uncomment this lines in libraries/database_interface.lib.php
if (! empty($GLOBALS['collation_connection'])) {
// PMA_DBI_query("SET CHARACTER SET 'utf8';", $link, PMA_DBI_QUERY_STORE);
//PMA_DBI_query("SET collation_connection = '" .
//PMA_sqlAddslashes($GLOBALS['collation_connection']) . "';", $link, PMA_DBI_QUERY_STORE);
} else {
//PMA_DBI_query("SET NAMES 'utf8' COLLATE 'utf8_general_ci';", $link, PMA_DBI_QUERY_STORE);
}
if you store data in utf8 without storing charset you do not need phpmyadmin to re-convert again the connection. This will work.
Adding to the evolving nature of the answer to this question, starting with r2016b, MATLAB will implicitly expand singleton dimensions, removing the need for bsxfun
in many cases.
From the r2016b release notes:
Implicit Expansion: Apply element-wise operations and functions to arrays with automatic expansion of dimensions of length 1
Implicit expansion is a generalization of scalar expansion. With scalar expansion, a scalar expands to be the same size as another array to facilitate element-wise operations. With implicit expansion, the element-wise operators and functions listed here can implicitly expand their inputs to be the same size, as long as the arrays have compatible sizes. Two arrays have compatible sizes if, for every dimension, the dimension sizes of the inputs are either the same or one of them is 1. See Compatible Array Sizes for Basic Operations and Array vs. Matrix Operations for more information.
Element-wise arithmetic operators — +, -, .*, .^, ./, .\ Relational operators — <, <=, >, >=, ==, ~= Logical operators — &, |, xor Bit-wise functions — bitand, bitor, bitxor Elementary math functions — max, min, mod, rem, hypot, atan2, atan2d
For example, you can calculate the mean of each column in a matrix A, and then subtract the vector of mean values from each column with A - mean(A).
Previously, this functionality was available via the bsxfun function. It is now recommended that you replace most uses of bsxfun with direct calls to the functions and operators that support implicit expansion. Compared to using bsxfun, implicit expansion offers faster speed, better memory usage, and improved readability of code.
I think you mean:
unsigned long n;
printf("%lu", n); // unsigned long
or
long n;
printf("%ld", n); // signed long
Try this:
this.approved_by = IsNullOrEmpty(planRec.approved_by) ? "" : planRec.approved_by.toString();
You can also use the null-coalescing operator as other have said - since no one has given an example that works with your code here is one:
this.approved_by = planRec.approved_by ?? planRec.approved_by.toString();
But this example only works since a possible value for this.approved_by
is the same as one of the potential values that you wish to set it to. For all other cases you will need to use the conditional operator as I showed in my first example.
Based on my comment to the accepted answer, there are a lot potential pitfalls that you may encounter by declaring font-sizes smaller than 12px
. By declaring styles that lead to computed font-sizes of less than 12px
, like so:
html {
font-size: 8px;
}
p {
font-size: 1.4rem;
}
// Computed p size: 11px.
You'll run into issues with browsers, like Chrome with a Chinese language pack that automatically renders any font sizes computed under 12px
as 12px
. So, the following is true:
h6 {
font-size: 12px;
}
p {
font-size: 8px;
}
// Both render at 12px in Chrome with a Chinese language pack.
// How unpleasant of a surprise.
I would also argue that for accessibility reasons, you generally shouldn't use sizes under 12px. You might be able to make a case for captions and the like, but again--prepare to be surprised under some browser setups, and prepared to make your grandma squint when she's trying to read your content.
I would instead, opt for something like this:
h1 {
font-size: 2.5rem;
}
h2 {
font-size: 2.25rem;
}
h3 {
font-size: 2rem;
}
h4 {
font-size: 1.75rem;
}
h5 {
font-size: 1.5rem;
}
h6 {
font-size: 1.25rem;
}
p {
font-size: 1rem;
}
@media (max-width: 480px) {
html {
font-size: 12px;
}
}
@media (min-width: 480px) {
html {
font-size: 13px;
}
}
@media (min-width: 768px) {
html {
font-size: 14px;
}
}
@media (min-width: 992px) {
html {
font-size: 15px;
}
}
@media (min-width: 1200px) {
html {
font-size: 16px;
}
}
You'll find that tons of sites that have to focus on accessibility use rather large font sizes, even for p
elements.
As a side note, setting margin-bottom
equal to the font-size
usually also tends to be attractive, i.e.:
h1 {
font-size: 2.5rem;
margin-bottom: 2.5rem;
}
Good luck.
Motivation: User would like to Retrieve aws instance metadata.
Solution:
The IP address 169.254.169.254
is a link-local address (and is valid only from the instance) aws gives us link with dedicated Restful API for Retrieving metadata of our running instance (Note that you are not billed for HTTP requests used to retrieve instance metadata and user data) . for Additional Documentation
Example:
//Request:
curl http://169.254.169.254/latest/meta-data/instance-id
//Response
ami-123abc
You able to get additional metadata labels of your instance using this link http://169.254.169.254/latest/meta-data/<metadata-field>
just choose the right tags:
var counter = 0;
function getSlug(tokens) {
var slug = '';
if (!!tokens.length) {
slug = tokens.shift();
slug = slug.toLowerCase();
slug += getSlug(tokens);
counter += 1;
console.log('THE SLUG ELEMENT IS: %s, counter is: %s', slug, counter);
}
return slug;
}
var mySlug = getSlug(['This', 'Is', 'My', 'Slug']);
console.log('THE SLUG IS: %s', mySlug);
Notice that the counter
counts "backwards" in regards to what slug
's value is. This is because of the position at which we are logging these values, as the function recurs before logging -- so, we essentially keep nesting deeper and deeper into the call-stack before logging takes place.
Once the recursion meets the final call-stack item, it trampolines "out" of the function calls, whereas, the first increment of counter
occurs inside of the last nested call.
I know this is not a "fix" on the Questioner's code, but given the title I thought I'd generically exemplify Recursion for a better understanding of recursion, outright.
You could have the value of the input field copied to a hidden field whenever focus leaves the input field (which should do what you want). See code below:
<script>
$(document).ready(function(){
$('#myInputElement').bind('change', function(){
var newvalue = $(this).val();
});
$('#myInputElement').blur(function(){
$('#myHiddenInput').val($(this).val());
});
});
</script>
<input id="myInputElement" type="text">
(untested, but it should work).
first()
if:If there are zero emissions and you are not explicitly handling it (with catchError
) then that error will get propagated up, possibly cause an unexpected problem somewhere else and can be quite tricky to track down - especially if it's coming from an end user.
You're safer off using take(1)
for the most part provided that:
take(1)
not emitting anything if the source completes without an emission.first(x => x > 10)
)Note: You can use a predicate with take(1)
like this: .pipe( filter(x => x > 10), take(1) )
. There is no error with this if nothing is ever greater than 10.
single()
If you want to be even stricter, and disallow two emissions you can use single()
which errors if there are zero or 2+ emissions. Again you'd need to handle errors in that case.
Tip: Single
can occasionally be useful if you want to ensure your observable chain isn't doing extra work like calling an http service twice and emitting two observables. Adding single
to the end of the pipe will let you know if you made such a mistake. I'm using it in a 'task runner' where you pass in a task observable that should only emit one value, so I pass the response through single(), catchError()
to guarantee good behavior.
first()
instead of take(1)
?aka. How can first
potentially cause more errors?
If you have an observable that takes something from a service and then pipes it through first()
you should be fine most of the time. But if someone comes along to disable the service for whatever reason - and changes it to emit of(null)
or NEVER
then any downstream first()
operators would start throwing errors.
Now I realize that might be exactly what you want - hence why this is just a tip. The operator first
appealed to me because it sounded slightly less 'clumsy' than take(1)
but you need to be careful about handling errors if there's ever a chance of the source not emitting. Will entirely depend on what you're doing though.
Consider also .pipe(defaultIfEmpty(42), first())
if you have a default value that should be used if nothing is emitted. This would of course not raise an error because first
would always receive a value.
Note that defaultIfEmpty
is only triggered if the stream is empty, not if the value of what is emitted is null
.
df['year_month']=df.datetime_column.apply(lambda x: str(x)[:7])
This worked fine for me, didn't think pandas would interpret the resultant string date as date, but when i did the plot, it knew very well my agenda and the string year_month where ordered properly... gotta love pandas!
It can also be caused by piping out of a pair of curly braces on a line.
This fails:
{ /usr/local/bin/mycommand ; outputstatus=$? } >> /var/log/mycommand.log 2>&1h
do_something
#Get NOW that saved output status for the following $? invocation
sh -c "exit $outputstatus"
do_something_more
while this is allowed:
{
/usr/local/bin/mycommand
outputstatus=$?
} >> /var/log/mycommand.log 2>&1h
do_something
#Get NOW that saved output status for the following $? invocation
sh -c "exit $outputstatus"
do_something_more
The answer by Acyra lead the right way if you want to set attributes inside the controller, but has many inaccuracies.
Yes, you can do it directly with the FormBuilder by using the attr
attribute (introduced here for the 2.1 version and here for the 2.0) to the array of options as follows:
->add('birthdate', 'date',array(
'input' => 'datetime',
'widget' => 'single_text',
'attr' => array('class'=>'calendar')
))
It is not true that the "functionality is broken". It works very well!
It is not true that Symfony2 applies the HTML class
attribute to both the label and the input (at least from the 2.1 version).
Moreover, since the attr
attribute is an array itself, you can pass any HTML attribute you want to render for the field. It is very helpful if you wanna pass the HTML5 data-
attributes.
Issue resolved after installing Google Play Services (NEVER needed them until now, removed because used too many resources on my Android 2.3), and do the following steps:
Clear data for the following apps:
Restart your phone.
Settings > Devices
. It may take a half-hour to several hours to appear.When your phone has shown up in the Play Store with the date registered as today's date, proceed with the next steps, but not before.
Apps > All > Google Play services
.follow this video https://www.youtube.com/watch?v=883HjO06_E0 for how to download and install Android SDK components manually
all these annotations are type of stereo type type of annotation,the difference between these three annotations are
- If we add the @Component then it tells the role of class is a component class it means it is a class consisting some logic,but it does not tell whether a class containing a specifically business or persistence or controller logic so we don't use directly this @Component annotation
- If we add @Service annotation then it tells that a role of class consisting business logic
- If we add @Repository on top of class then it tells that a class consisting persistence logic
- Here @Component is a base annotation for @Service,@Repository and @Controller annotations
for example
package com.spring.anno;
@Service
public class TestBean
{
public void m1()
{
//business code
}
}
package com.spring.anno;
@Repository
public class TestBean
{
public void update()
{
//persistence code
}
}
@Service
or @Repositroy
or @Controller
annotation by default @Component
annotation is going to existence on top of the classtry {
} catch (javax.script.ScriptException ex) {
// System.out.println(ex.getMessage());
}
How about comparing the original value of the field and the changed value of the field and deducting the difference as the pasted value? This catches the pasted text correctly even if there is existing text in the field.
function text_diff(first, second) {
var start = 0;
while (start < first.length && first[start] == second[start]) {
++start;
}
var end = 0;
while (first.length - end > start && first[first.length - end - 1] == second[second.length - end - 1]) {
++end;
}
end = second.length - end;
return second.substr(start, end - start);
}
$('textarea').bind('paste', function () {
var self = $(this);
var orig = self.val();
setTimeout(function () {
var pasted = text_diff(orig, $(self).val());
console.log(pasted);
});
});
Convert the Special characters to apostrophe,
Data <- gsub("[^0-9A-Za-z///' ]","'" , Data ,ignore.case = TRUE)
Below code it to remove extra ''' apostrophe
Data <- gsub("''","" , Data ,ignore.case = TRUE)
Use gsub(..)
function for replacing the special character with apostrophe
RegexBuddy is telling me if you want to include it at the beginning, this is the correct syntax:
"(?i)\\b(\\w+)\\b(\\s+\\1)+\\b"
You can use varargs for optional parameters:
public class Booyah {
public static void main(String[] args) {
woohoo(1);
woohoo(2, 3);
}
static void woohoo(int required, Integer... optional) {
Integer lala;
if (optional.length == 1) {
lala = optional[0];
} else {
lala = 2;
}
System.out.println(required + lala);
}
}
Also it's important to note the use of Integer
over int
. Integer
is a wrapper around the primitive int
, which allows one to make comparisons with null
as necessary.
Use select setval('payments_id_seq', 21, true);
setval
contains 3 parameters:
sequence_name
nextval
The use of true or false in 3rd parameter of setval is as follows:
SELECT setval('payments_id_seq', 21); // Next nextval will return 22
SELECT setval('payments_id_seq', 21, true); // Same as above
SELECT setval('payments_id_seq', 21, false); // Next nextval will return 21
The better way to avoid hard-coding of sequence name, next sequence value and to handle empty column table correctly, you can use the below way:
SELECT setval(pg_get_serial_sequence('table_name', 'id'), coalesce(max(id), 0)+1 , false) FROM table_name;
where table_name
is the name of the table, id
is the primary key
of the table
SELECT tab.*,
row_number() OVER () as rnum
FROM tab;
Here's the relevant section in the docs.
P.S. This, in fact, fully matches the answer in the referenced question.
The code itself is working correctly. The problem is, that the program working path is pointing to other place than you think.
Use this line and see where the path is:
System.out.println(new File(".").getAbsoluteFile());
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
Just in case, someone out there having same issue but changing file permission doesn't solve the issue, add this line to your config.inc.php
file
<?php
// other config goes here . . .
$cfg['CheckConfigurationPermissions'] = false;
And you're good to go.
In my case, I'm using windows 10 WSL with phpmyadmin installed on D:
drive. There's no way to (for now) change file permission on local disk through WSL unless your installation directory is inside WSL filesystem it-self. There's updates according to this issue, but still on insider build.
Cheers.
I´d like to mention, that I used spring boot version 1.4.0 and since this version you can only write:
@Component
public class MongoConnection {
@Value("${spring.data.mongodb.host}")
private String mongoHost;
@Value("${spring.data.mongodb.port}")
private int mongoPort;
@Value("${spring.data.mongodb.database}")
private String mongoDB;
}
Then inject class whenever you want.
EDIT:
From nowadays I would use @ConfigurationProperties because you are able to inject property values in your POJOs. Keep hierarchical sort above your properties. Moreover, you can put validations above POJOs attributes and so on. Take a look at the link
In the head section of your html document:
<link rel="stylesheet" type="text/css" href="/path/to/ABCD.css">
Your css file should be css only and not contain any markup.
I looked everywhere for an answer and finally this worked for me:
SELECT Lower(Substring(MASTER.dbo.Fn_varbintohexstr(0x21232F297A57A5A743894A0E4A801FC3), 3, 8000))
Outputs to (string):
21232f297a57a5a743894a0e4a801fc3
You can use it in your WHERE or JOIN conditions as well in case you want to compare/match varbinary records with strings
The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):
Mikhail,
The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.
Good luck with your implementation.
/* comment here */
here is an example: SELECT 1 /* this is an in-line comment */ + 1;
Use of the argmin method for numpy arrays.
import numpy as np
np.argmin(myList)
However, it is not the fastest method: it is 3 times slower than OP's answer on my computer. It may be the most concise one though.
Found the issue. Qt Creator wants you to use a compiler listed under one of their Qt libraries. Use the Maintenance Tool to install this.
To do so:
Go to Tools -> Options.... Select Build & Run on left. Open Kits tab. You should have Manual -> Desktop (default) line in list. Choose it. Now select something like Qt 5.5.1 in PATH (qt5) in Qt version combobox and click Apply button. From now you should be able to create, build and run empty Qt project.