If taskkill /F /T /PID <pid>
does not work.
Try opening your terminal elevated using Run as Administrator
.
Search cmd
in your windows menu, and right click Run as Administrator
,
then run the command again. This worked for me.
If you are echoing out the json response and your headers don't match */json then you can use the built in jQuery.parseJSON api to parse the response.
response = '{"name":"John"}';
var obj = jQuery.parseJSON(response);
alert( obj.name === "John" );
This is not possible as of May 2017, because Postman only works with HTTP methods such as POST, GET, PUT, DELETE.
P/S: There is a request for this if you want to upvote: github.com/postmanlabs/postman-app-support/issues/4009
For anyone who has upgraded recently from 6.x to 6.7.0.
Deleting the /Users/{YOUR USERNAME}/.npm
folder solved my issues with npm install
.
I also, ran some of these commands suggested by https://npm.community/t/crash-npm-err-cb-never-called/858/93?u=jasonfoglia
sudo npm cache clean -f
sudo npm install -g n
But I'm not sure which actually worked until I deleted the folder. So if you experience this issue and just delete the .npm folder fixing your issue please note that in the comments.
Remember.. inherits is case sensitive for C# (not so for vb.net)
Found that out the hard way.
I had the same problem, and a easy way i found to solve that was to make everything in the modal's body responsive(using boostrap classes) and my problem were solved.
startInfo.Arguments = "/c \"netsh http add sslcert ipport=127.0.0.1:8085 certhash=0000000000003ed9cd0c315bbb6dc1c08da5e6 appid={00112233-4455-6677-8899-AABBCCDDEEFF} clientcertnegotiation=enable\"";
and...
startInfo.Arguments = "/c \"makecert -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer\"";
The /c
tells cmd to quit once the command has completed. Everything after /c
is the command you want to run (within cmd
), including all of the arguments.
Pass the date into the function.
<?php
function getTheDay($date)
{
$curr_date=strtotime(date("Y-m-d H:i:s"));
$the_date=strtotime($date);
$diff=floor(($curr_date-$the_date)/(60*60*24));
switch($diff)
{
case 0:
return "Today";
break;
case 1:
return "Yesterday";
break;
default:
return $diff." Days ago";
}
}
?>
I've found some success with this:
/^((ftp|http|https):\/\/)?www\.([A-z]+)\.([A-z]{2,})/
It's obviously not perfect but it handled my cases pretty well
LinearLayout - In LinearLayout, views are organized either in vertical or horizontal orientation.
RelativeLayout - RelativeLayout is way more complex than LinearLayout, hence provides much more functionalities. Views are placed, as the name suggests, relative to each other.
FrameLayout - It behaves as a single object and its child views are overlapped over each other. FrameLayout takes the size of as per the biggest child element.
Coordinator Layout - This is the most powerful ViewGroup introduced in Android support library. It behaves as FrameLayout and has a lot of functionalities to coordinate amongst its child views, for example, floating button and snackbar, Toolbar with scrollable view.
Typically you'll need cookies to log into a site, which means cookielib, urllib and urllib2. Here's a class which I wrote back when I was playing Facebook web games:
import cookielib
import urllib
import urllib2
# set these to whatever your fb account is
fb_username = "[email protected]"
fb_password = "secretpassword"
class WebGamePlayer(object):
def __init__(self, login, password):
""" Start up... """
self.login = login
self.password = password
self.cj = cookielib.CookieJar()
self.opener = urllib2.build_opener(
urllib2.HTTPRedirectHandler(),
urllib2.HTTPHandler(debuglevel=0),
urllib2.HTTPSHandler(debuglevel=0),
urllib2.HTTPCookieProcessor(self.cj)
)
self.opener.addheaders = [
('User-agent', ('Mozilla/4.0 (compatible; MSIE 6.0; '
'Windows NT 5.2; .NET CLR 1.1.4322)'))
]
# need this twice - once to set cookies, once to log in...
self.loginToFacebook()
self.loginToFacebook()
def loginToFacebook(self):
"""
Handle login. This should populate our cookie jar.
"""
login_data = urllib.urlencode({
'email' : self.login,
'pass' : self.password,
})
response = self.opener.open("https://login.facebook.com/login.php", login_data)
return ''.join(response.readlines())
You won't necessarily need the HTTPS or Redirect handlers, but they don't hurt, and it makes the opener much more robust. You also might not need cookies, but it's hard to tell just from the form that you've posted. I suspect that you might, purely from the 'Remember me' input that's been commented out.
Here is an example
import numpy as np
import matplotlib.pyplot as plt
x = np.random.rand(100)
y = np.random.rand(100)
t = np.arange(100)
plt.scatter(x, y, c=t)
plt.show()
Here you are setting the color based on the index, t
, which is just an array of [1, 2, ..., 100]
.
Perhaps an easier-to-understand example is the slightly simpler
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(100)
y = x
t = x
plt.scatter(x, y, c=t)
plt.show()
Note that the array you pass as c
doesn't need to have any particular order or type, i.e. it doesn't need to be sorted or integers as in these examples. The plotting routine will scale the colormap such that the minimum/maximum values in c
correspond to the bottom/top of the colormap.
You can change the colormap by adding
import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.cmap_name)
Importing matplotlib.cm
is optional as you can call colormaps as cmap="cmap_name"
just as well. There is a reference page of colormaps showing what each looks like. Also know that you can reverse a colormap by simply calling it as cmap_name_r
. So either
plt.scatter(x, y, c=t, cmap=cm.cmap_name_r)
# or
plt.scatter(x, y, c=t, cmap="cmap_name_r")
will work. Examples are "jet_r"
or cm.plasma_r
. Here's an example with the new 1.5 colormap viridis:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(100)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')
plt.show()
You can add a colorbar by using
plt.scatter(x, y, c=t, cmap='viridis')
plt.colorbar()
plt.show()
Note that if you are using figures and subplots explicitly (e.g. fig, ax = plt.subplots()
or ax = fig.add_subplot(111)
), adding a colorbar can be a bit more involved. Good examples can be found here for a single subplot colorbar and here for 2 subplots 1 colorbar.
<div className="display__lbl_input">
<input
type="checkbox"
onChange={this.handleChangeFilGasoil}
value="Filter Gasoil"
name="Filter Gasoil"
id=""
/>
<label htmlFor="">Filter Gasoil</label>
</div>
handleChangeFilGasoil = (e) => {
if(e.target.checked){
this.setState({
checkedBoxFG:e.target.value
})
console.log(this.state.checkedBoxFG)
}
else{
this.setState({
checkedBoxFG : ''
})
console.log(this.state.checkedBoxFG)
}
};
There is a simple way:
Android:
String macAddress =
android.provider.Settings.Secure.getString(this.getApplicationContext().getContentResolver(), "android_id");
Xamarin:
Settings.Secure.GetString(this.ContentResolver, "android_id");
The DataTable has a collection .Rows
of DataRow elements.
Each DataRow corresponds to one row in your database, and contains a collection of columns.
In order to access a single value, do something like this:
foreach(DataRow row in YourDataTable.Rows)
{
string name = row["name"].ToString();
string description = row["description"].ToString();
string icoFileName = row["iconFile"].ToString();
string installScript = row["installScript"].ToString();
}
There is no such font as “Calibri (Body)”. You probably saw this string in Microsoft Word font selection menu, but it’s not a font name (see e.g. the explanation Font: +body (in W07)).
So use just font-family: Calibri
or, better, font-family: Calibri, sans-serif
. (There is no adequate backup font for Calibri, but the odds are that when Calibri is not available, the browser’s default sans-serif font suits your design better than the browser’s default font, which is most often a serif font.)
In navigateExtra we can pass only some specific name as argument otherwise it showing error like below: For Ex- Here I want to pass customer key in router navigate and I pass like this-
this.Router.navigate(['componentname'],{cuskey: {customerkey:response.key}});
but it showing some error like below:
Argument of type '{ cuskey: { customerkey: any; }; }' is not assignable to parameter of type 'NavigationExtras'.
Object literal may only specify known properties, and 'cuskey' does not exist in type 'NavigationExt## Heading ##ras'
.
Solution: we have to write like this:
this.Router.navigate(['componentname'],{state: {customerkey:response.key}});
Note :- Certainly in python-3x you need to use Range function It works to generate numbers on demand, standard method to use Range function to make a list of consecutive numbers is
x=list(range(10))
#"list"_will_make_all_numbers_generated_by_range_in_a_list
#number_in_range_(10)_is_an_option_you_can_change_as_you_want
print (x)
#Output_is_ [0,1,2,3,4,5,6,7,8,9]
Also if you want to make an function to generate a list of consecutive numbers by using Range function watch this code !
def consecutive_numbers(n) :
list=[i for i in range(n)]
return (list)
print(consecutive_numbers(10))
Good Luck!
I've used the following advice from the docs https://symfony.com/doc/current/console/request_context.html to get absolute urls in emails:
# config/services.yaml
parameters:
router.request_context.host: 'example.org'
router.request_context.scheme: 'https'
What worked for me was:
$('select option').each(function(){$(this).removeAttr('selected');});
In your action method, return Json(object) to return JSON to your page.
public ActionResult SomeActionMethod() {
return Json(new {foo="bar", baz="Blech"});
}
Then just call the action method using Ajax. You could use one of the helper methods from the ViewPage such as
<%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>
SomeMethod would be a javascript method that then evaluates the Json object returned.
If you want to return a plain string, you can just use the ContentResult:
public ActionResult SomeActionMethod() {
return Content("hello world!");
}
ContentResult by default returns a text/plain as its contentType.
This is overloadable so you can also do:
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
Where A
is your 2D array:
import numpy as np
A[np.isnan(A)] = 0
The function isnan
produces a bool array indicating where the NaN
values are. A boolean array can by used to index an array of the same shape. Think of it like a mask.
I use a combined version:
if(session_id() == '' || !isset($_SESSION)) {
// session isn't started
session_start();
}
In Java 8 you can use String.join()
:
List<String> list = Arrays.asList("foo", "bar", "baz");
String joined = String.join(" and ", list); // "foo and bar and baz"
Also have a look at this answer for a Stream API example.
var startTime = new Date('2012/10/09 12:00');
var endTime = new Date('2013/10/09 12:00');
var difference = endTime.getTime() - startTime.getTime(); // This will give difference in milliseconds
var resultInMinutes = Math.round(difference / 60000);
pushing a value (not necessarily stored in a register) means writing it to the stack.
popping means restoring whatever is on top of the stack into a register. Those are basic instructions:
push 0xdeadbeef ; push a value to the stack
pop eax ; eax is now 0xdeadbeef
; swap contents of registers
push eax
mov eax, ebx
pop ebx
You're not actually going out after the values. You would need to gather them like this:
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;
You could put all of these in one array:
var myArray = [ title, name, tickets ];
Or many arrays:
var titleArr = [ title ];
var nameArr = [ name ];
var ticketsArr = [ tickets ];
Or, if the arrays already exist, you can use their .push()
method to push new values onto it:
var titleArr = [];
function addTitle ( title ) {
titleArr.push( title );
console.log( "Titles: " + titleArr.join(", ") );
}
Your save button doesn't work because you refer to this.form
, however you don't have a form on the page. In order for this to work you would need to have <form>
tags wrapping your fields:
I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit
The new form follows:
<form>
<h1>Please enter data</h1>
<input id="title" type="text" />
<input id="name" type="text" />
<input id="tickets" type="text" />
<input type="button" value="Save" onclick="insert()" />
<input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>
There is still some room for improvement, such as removing the onclick
attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).
I've also made some changes to your JavaScript. I start by creating three empty arrays:
var titles = [];
var names = [];
var tickets = [];
Now that we have these, we'll need references to our input fields.
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
I'm also getting a reference to our message display box.
var messageBox = document.getElementById("display");
The insert()
function uses the references to each input field to get their value. It then uses the push()
method on the respective arrays to put the current value into the array.
Once it's done, it cals the clearAndShow()
function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
This function, as previously stated, starts by setting the .value
property of each input to an empty string. It then clears out the .innerHTML
of our message box. Lastly, it calls the join()
method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.
function clearAndShow () {
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
The final result can be used online at http://jsbin.com/ufanep/2/edit
Three possibilities in Java 8:
List<String> list = Arrays.asList("Alice", "Bob", "Charlie")
String result = String.join(" and ", list);
result = list.stream().collect(Collectors.joining(" and "));
result = list.stream().reduce((t, u) -> t + " and " + u).orElse("");
You can do it like this.
String to byte array
String stringToConvert = "This String is 76 characters long and will be converted to an array of bytes";
byte[] theByteArray = stringToConvert.getBytes();
http://www.javadb.com/convert-string-to-byte-array
Byte array to String
byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
String value = new String(byteArray);
Marknote is a nice lightweight cross-browser JavaScript XML parser. It's object-oriented and it's got plenty of examples, plus the API is documented. It's fairly new, but it has worked nicely in one of my projects so far. One thing I like about it is that it will read XML directly from strings or URLs and you can also use it to convert the XML into JSON.
Here's an example of what you can do with Marknote:
var str = '<books>' +
' <book title="A Tale of Two Cities"/>' +
' <book title="1984"/>' +
'</books>';
var parser = new marknote.Parser();
var doc = parser.parse(str);
var bookEls = doc.getRootElement().getChildElements();
for (var i=0; i<bookEls.length; i++) {
var bookEl = bookEls[i];
// alerts "Element name is 'book' and book title is '...'"
alert("Element name is '" + bookEl.getName() +
"' and book title is '" +
bookEl.getAttributeValue("title") + "'"
);
}
The following is nasty, but serves to demonstrate how you can treat functions like any other kind of object.
var foo = function () { alert('default function'); }
function pickAFunction(a_or_b) {
var funcs = {
a: function () {
alert('a');
},
b: function () {
alert('b');
}
};
foo = funcs[a_or_b];
}
foo();
pickAFunction('a');
foo();
pickAFunction('b');
foo();
You can use this code to get your desire output
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'color': ['red','red','red','blue','blue','blue'], 'x': [0,1,2,3,4,5],'y': [0,1,2,9,16,25]})
print df
color x y
0 red 0 0
1 red 1 1
2 red 2 2
3 blue 3 9
4 blue 4 16
5 blue 5 25
To plot graph
a = df.iloc[[i for i in xrange(0,len(df)) if df['x'][i]==df['y'][i]]].plot(x='x',y='y',color = 'red')
df.iloc[[i for i in xrange(0,len(df)) if df['y'][i]== df['x'][i]**2]].plot(x='x',y='y',color = 'blue',ax=a)
plt.show()
Output
If you need a button like this:
You can use RaisedButton
and use the child property to do this. You need to add a Row and inside row you can add a Text
widget and an Icon
Widget to achieve this. If you want to use png image, you can use similar widget to achieve this.
RaisedButton(
onPressed: () {},
color: Theme.of(context).accentColor,
child: Padding(
padding: EdgeInsets.fromLTRB(
SizeConfig.safeBlockHorizontal * 5,
0,
SizeConfig.safeBlockHorizontal * 5,
0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'Continue',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w700,
color: Colors.white,
),
),
Icon(
Icons.arrow_forward,
color: Colors.white,
)
],
),
),
),
use Object.keys:
Object.keys(this.formErrors).map(key => {
this.formErrors[key] = '';
const control = form.get(key);
if(control && control.dirty && !control.valid) {
const messages = this.validationMessages[key];
Object.keys(control.errors).map(key2 => {
this.formErrors[key] += messages[key2] + ' ';
});
}
});
Below I found elegant way of doing this while googling ---
/ detect IE
var IEversion = detectIE();
if (IEversion !== false) {
document.getElementById('result').innerHTML = 'IE ' + IEversion;
} else {
document.getElementById('result').innerHTML = 'NOT IE';
}
// add details to debug result
document.getElementById('details').innerHTML = window.navigator.userAgent;
/**
* detect IE
* returns version of IE or false, if browser is not Internet Explorer
*/
function detectIE() {
var ua = window.navigator.userAgent;
// Test values; Uncomment to check result …
// IE 10
// ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
// IE 11
// ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
// IE 12 / Spartan
// ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';
// Edge (IE 12+)
// ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586';
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
// IE 10 or older => return version number
return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}
var trident = ua.indexOf('Trident/');
if (trident > 0) {
// IE 11 => return version number
var rv = ua.indexOf('rv:');
return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
}
var edge = ua.indexOf('Edge/');
if (edge > 0) {
// Edge (IE 12+) => return version number
return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}
// other browser
return false;
}
The problem, as the Traceback says, comes from the line x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
. Let's replace it in its context:
i + 1 >= len(x)
<=> i >= 0
, the element x[i+1]
doesn't exist. Here, this element doesn't exist since the beginning of the for loop.To solve this, you must replace x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
by x.append(x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ))
.
SELECT * FROM my_table;
where my_table
is the name of your table.
EDIT:
psql -c "SELECT * FROM my_table"
or just psql
and then type your queries.
I met the same problem. (Window 10 environment) I solved it by deleting the JAVA_HOME="C:\Program Files\Java\jdk1.8.0_161\bin" in the User Variables instead of adding to the System Variables directly.
Then I test that editing JAVA_HOME="C:\Program Files\Java\jdk1.8.0_161\" worked too. When I run "mvn -version" in command prompt window, it shows "Java home: C:\Program Files\Java\jdk1.8.0_161\jre".
In conclusion, I guess the JAVA_HOME shouldn't include bin directory.
On OSX, saving video frames and still images only worked for me when I gave a full path to cvSaveImage:
cvSaveImage("/Users/nicc/image.jpg",img);
I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:
var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";
console.log( JSON.stringify(display) );
This will print:
["none","block","none"]
This is how JSON actually serializes array. However what you want to see is something like:
{"0":"none","1":"block","2":"none"}
To get this format you want to serialize object, not array. So let's rewrite above code like this:
var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";
console.log( JSON.stringify(display2) );
This will print in the format you want.
You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console
The problem seems to be a mis-placed )
. In your sample you have the %
outside of the print()
, you should move it inside:
Use this:
print("%s. %s appears %s times." % (str(i), key, str(wordBank[key])))
Or you can do this way :
((TextView)findViewById(R.id.this_is_the_id_of_textview)).setText("Test");
this should be close!
public static void OpenWithDefaultProgram(string path)
{
Process fileopener = new Process();
fileopener.StartInfo.FileName = "explorer";
fileopener.StartInfo.Arguments = "\"" + path + "\"";
fileopener.Start();
}
Sure.
.orElseThrow(() -> new MyException(someArgument))
The answer here is not clear, so I wanted to add more detail.
Using the link provided above, I performed the following step.
In my XML config manager I changed the "Provider" to SQLOLEDB.1 rather than SQLNCLI.1. This got me past this error.
This information is available at the link the OP posted in the Answer.
The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/
It looks like it is a bug open for this issue: Prettier Bug
None of above solution worked for me. The only thing that worked was, adding this line of code in package.json:
"prettier": {
"singleQuote": true
},
Put the source in a folder outside yourt workspace. Rightclick in the project-explorer, and select "Import..."
Import the project in your workspace as an Android project. Try to build it, and make sure it is marked as a library project. Also make sure it is build with Google API support, if not you will get compile errors.
Then, in right click on your main project in the project explorer. Select properties, then select Android on the left. In the library section below, click "Add"..
The mapview-balloons library should now be available to add to your project..
This is the cleanest solution there is:
mvn org.apache.maven.plugins:maven-help-plugin:3.2.0:evaluate \
-Dexpression=project.version -q -DforceStdout
Advantages:
pom.xml
Note:
maven-help-plugin
version 3.2.0
(and above) has forceStdout
option. You may replace 3.2.0
in above command with a newer version from the list of available versions of mvn-help-plugin from artifactory, if available.-q
suppresses verbose messages ([INFO]
, [WARN]
etc.)Alternatively, you can add this entry in your pom.xml
, under plugins
section:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-help-plugin</artifactId>
<version>3.2.0</version>
</plugin>
and then run above command compactly as follows:
mvn help:evaluate -Dexpression=project.groupId -q -DforceStdout
If you want to fetch groupId
and artifactId
as well, check this answer.
You can do like..
DataRow[] dr = dtbl.Select("SUM(Amount)");
txtTotalAmount.Text = Convert.ToString(dr[0]);
When you want to show an URL of remote branches, try:
git remote -v
I assume you used splice
something like this?
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) !== -1) {
arrayOfObjects.splice(i, 1);
}
}
All you need to do to fix the bug is decrement i
for the next time around, then (and looping backwards is also an option):
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) !== -1) {
arrayOfObjects.splice(i, 1);
i--;
}
}
To avoid linear-time deletions, you can write array elements you want to keep over the array:
var end = 0;
for (var i = 0; i < arrayOfObjects.length; i++) {
var obj = arrayOfObjects[i];
if (listToDelete.indexOf(obj.id) === -1) {
arrayOfObjects[end++] = obj;
}
}
arrayOfObjects.length = end;
and to avoid linear-time lookups in a modern runtime, you can use a hash set:
const setToDelete = new Set(listToDelete);
let end = 0;
for (let i = 0; i < arrayOfObjects.length; i++) {
const obj = arrayOfObjects[i];
if (setToDelete.has(obj.id)) {
arrayOfObjects[end++] = obj;
}
}
arrayOfObjects.length = end;
which can be wrapped up in a nice function:
const filterInPlace = (array, predicate) => {_x000D_
let end = 0;_x000D_
_x000D_
for (let i = 0; i < array.length; i++) {_x000D_
const obj = array[i];_x000D_
_x000D_
if (predicate(obj)) {_x000D_
array[end++] = obj;_x000D_
}_x000D_
}_x000D_
_x000D_
array.length = end;_x000D_
};_x000D_
_x000D_
const toDelete = new Set(['abc', 'efg']);_x000D_
_x000D_
const arrayOfObjects = [{id: 'abc', name: 'oh'},_x000D_
{id: 'efg', name: 'em'},_x000D_
{id: 'hij', name: 'ge'}];_x000D_
_x000D_
filterInPlace(arrayOfObjects, obj => !toDelete.has(obj.id));_x000D_
console.log(arrayOfObjects);
_x000D_
If you don’t need to do it in place, that’s Array#filter
:
const toDelete = new Set(['abc', 'efg']);
const newArray = arrayOfObjects.filter(obj => !toDelete.has(obj.id));
In more object way:
$today = new \DateTimeImmutable('today');
example:
echo (new \DateTimeImmutable('today'))->format('Y-m-d H:i:s');
// will output: 2019-05-16 00:00:00
and:
echo (new \DateTimeImmutable())->format('Y-m-d H:i:s');
echo (new \DateTimeImmutable('now'))->format('Y-m-d H:i:s');
// will output: 2019-05-16 14:00:35
Your selector is missing a .
and though you say you want to change the border-color
- you're adding and removing a class that sets the background-color
Yes, you can use regular expressions
in C#.
Using regular expressions with C#
:
using System.Text.RegularExpressions;
string your_String = "Hello@Hello&Hello(Hello)";
string my_String = Regex.Replace(your_String, @"[^0-9a-zA-Z]+", ",");
The solution to this question is:
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="dummy.xsl"?>
<item>
<summary>
<![CDATA[Tootsie roll tiramisu macaroon wafer carrot cake. <br />
Danish topping sugar plum tart bonbon caramels cake.]]>
</summary>
</item>
by adding the <br />
inside the the <![CDATA]]>
this allows the line to break, thus creating a new line!
If your Docker MySQL host is running correctly you can connect to it from local machine, but you should specify host, port and protocol like this:
mysql -h localhost -P 3306 --protocol=tcp -u root
Change 3306 to port number you have forwarded from Docker container (in your case it will be 12345).
Because you are running MySQL inside Docker container, socket is not available and you need to connect through TCP. Setting "--protocol" in the mysql command will change that.
Look at this Howto in the MSDN Documentation: Run the Transact-SQL Debugger - it's not with PRINT statements, but maybe it helps you anyway to debug your code.
This YouTube video: SQL Server 2008 T-SQL Debugger shows the use of the Debugger.
=> Stored procedures are written in Transact-SQL. This allows you to debug all Transact-SQL code and so it's like debugging in Visual Studio with defining breakpoints and watching the variables.
public string BuildAbsolute(PathString path, QueryString query = default(QueryString), FragmentString fragment = default(FragmentString))
{
var rq = httpContext.Request;
return Microsoft.AspNetCore.Http.Extensions.UriHelper.BuildAbsolute(rq.Scheme, rq.Host, rq.PathBase, path, query, fragment);
}
CD E:\Documents and Settings\All Users\Application Data
E:\Documents and Settings\All Users\Application Data>REGSVR32 xyz.dll
You have to check if you have the folder with name manager
inside the folder webapps
in your tomcat.
Rubens-MacBook-Pro:tomcat rfanjul$ ls -la webapps/
total 16
drwxr-xr-x 8 rfanjul staff 272 21 May 12:20 .
drwxr-xr-x 14 rfanjul staff 476 21 May 12:22 ..
-rw-r--r--@ 1 rfanjul staff 6148 21 May 12:20 .DS_Store
drwxr-xr-x 19 rfanjul staff 646 17 Feb 15:13 ROOT
drwxr-xr-x 51 rfanjul staff 1734 17 Feb 15:13 docs
drwxr-xr-x 6 rfanjul staff 204 17 Feb 15:13 examples
drwxr-xr-x 7 rfanjul staff 238 17 Feb 15:13 host-manager
drwxr-xr-x 8 rfanjul staff 272 17 Feb 15:13 manager
After that you will be sure that you have this permmint for you user in the file conf/tomcat-users.xml
:
<role rolename="admin-gui"/>
<role rolename="manager-gui"/>
<user username="test" password="test" roles="admin-gui,manager-gui"/>
restart tomcat and stat tomcat again.
sh bin/shutdown.sh
sh bin/startup.sh
I hope that will works fine for you.
Breadth first search
Queue<TreeNode> queue = new LinkedList<BinaryTree.TreeNode>() ;
public void breadth(TreeNode root) {
if (root == null)
return;
queue.clear();
queue.add(root);
while(!queue.isEmpty()){
TreeNode node = queue.remove();
System.out.print(node.element + " ");
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
}
Please read the example in rfc6749 sec 7.1 first.
The bearer token is a type of access token, which does NOT require PoP(proof-of-possession) mechanism.
PoP means kind of multi-factor authentication to make access token more secure. ref
Proof-of-Possession refers to Cryptographic methods that mitigate the risk of Security Tokens being stolen and used by an attacker. In contrast to 'Bearer Tokens', where mere possession of the Security Token allows the attacker to use it, a PoP Security Token cannot be so easily used - the attacker MUST have both the token itself and access to some key associated with the token (which is why they are sometimes referred to 'Holder-of-Key' (HoK) tokens).
Maybe it's not the case, but I would say,
BTW, there's a draft of "OAuth 2.0 Proof-of-Possession (PoP) Security Architecture" now.
Try something like this.
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Redirect } from 'react-router'
import SignUpForm from '../../register/components/SignUpForm';
import styles from './PagesStyles.css';
import axios from 'axios';
import Footer from '../../shared/components/Footer';
class SignUpPage extends React.Component {
constructor(props) {
super(props);
this.state = {
errors: {},
callbackResponse: null,
client: {
userclient: '',
clientname: '',
clientbusinessname: '',
password: '',
confirmPassword: ''
}
};
this.processForm = this.processForm.bind(this);
this.changeClient = this.changeClient.bind(this);
}
changeClient(event) {
const field = event.target.name;
const client = this.state.client;
client[field] = event.target.value;
this.setState({
client
});
}
processForm(event) {
event.preventDefault();
const userclient = this.state.client.userclient;
const clientname = this.state.client.clientname;
const clientbusinessname = this.state.client.clientbusinessname;
const password = this.state.client.password;
const confirmPassword = this.state.client.confirmPassword;
const formData = { userclient, clientname, clientbusinessname, password, confirmPassword };
axios.post('/signup', formData, { headers: {'Accept': 'application/json'} })
.then((response) => {
this.setState({
callbackResponse: {response.data},
});
}).catch((error) => {
const errors = error.response.data.errors ? error.response.data.errors : {};
errors.summary = error.response.data.message;
this.setState({
errors
});
});
}
const renderMe = ()=>{
return(
this.state.callbackResponse
? <SignUpForm
onSubmit={this.processForm}
onChange={this.changeClient}
errors={this.state.errors}
client={this.state.client}
/>
: <Redirect to="/"/>
)}
render() {
return (
<div className={styles.section}>
<div className={styles.container}>
<img src={require('./images/lisa_principal_bg.png')} className={styles.fullImageBackground} />
{renderMe()}
<Footer />
</div>
</div>
);
}
}
export default SignUpPage;
Try Error.captureStackTrace(targetObject[, constructorOpt]).
const myObj = {};
function c() {
// pass
}
function b() {
Error.captureStackTrace(myObj)
c()
}
function a() {
b()
}
a()
console.log(myObj.stack)
The function a
and b
are captured in error stack and stored in myObj
.
The JSON spec requires UTF-8 support by decoders. As a result, all JSON decoders can handle UTF-8 just as well as they can handle the numeric escape sequences. This is also the case for Javascript interpreters, which means JSONP will handle the UTF-8 encoded JSON as well.
The ability for JSON encoders to use the numeric escape sequences instead just offers you more choice. One reason you may choose the numeric escape sequences would be if a transport mechanism in between your encoder and the intended decoder is not binary-safe.
Another reason you may want to use numeric escape sequences is to prevent certain characters appearing in the stream, such as <
, &
and "
, which may be interpreted as HTML sequences if the JSON code is placed without escaping into HTML or a browser wrongly interprets it as HTML. This can be a defence against HTML injection or cross-site scripting (note: some characters MUST be escaped in JSON, including "
and \
).
Some frameworks, including PHP's implementation of JSON, always do the numeric escape sequences on the encoder side for any character outside of ASCII. This is intended for maximum compatibility with limited transport mechanisms and the like. However, this should not be interpreted as an indication that JSON decoders have a problem with UTF-8.
So, I guess you just could decide which to use like this:
Just use UTF-8, unless your method of storage or transport between encoder and decoder is not binary-safe.
Otherwise, use the numeric escape sequences.
Substr() normally (i.e. PHP and Perl) works this way:
s = Substr(s, beginning, LENGTH)
So the parameters are beginning
and LENGTH
.
But Python's behaviour is different; it expects beginning and one after END (!). This is difficult to spot by beginners. So the correct replacement for Substr(s, beginning, LENGTH) is
s = s[ beginning : beginning + LENGTH]
If @Region
is not a null
value (lets say @Region = 'South'
) it will not return rows where the Region field is null, regardless of the value of ANSI_NULLS.
ANSI_NULLS will only make a difference when the value of @Region
is null
, i.e. when your first query essentially becomes the second one.
In that case, ANSI_NULLS ON will not return any rows (because null = null
will yield an unknown boolean value (a.k.a. null
)) and ANSI_NULLS OFF will return any rows where the Region field is null (because null = null
will yield true
)
EDIT: The fetch request will still be running in the background and will most likely log an error in your console.
Indeed the Promise.race
approach is better.
See this link for reference Promise.race()
Race means that all Promises will run at the same time, and the race will stop as soon as one of the promises returns a value. Therefore, only one value will be returned. You could also pass a function to call if the fetch times out.
fetchWithTimeout(url, {
method: 'POST',
body: formData,
credentials: 'include',
}, 5000, () => { /* do stuff here */ });
If this piques your interest, a possible implementation would be :
function fetchWithTimeout(url, options, delay, onTimeout) {
const timer = new Promise((resolve) => {
setTimeout(resolve, delay, {
timeout: true,
});
});
return Promise.race([
fetch(url, options),
timer
]).then(response => {
if (response.timeout) {
onTimeout();
}
return response;
});
}
Use Sessions.
Page1:
session_start();
$_SESSION['message'] = "Some message"
Page2:
session_start();
var_dump($_SESSION['message']);
Use a 1 line batch file in your install:
SETX PATH "C:\Windows"
run the bat file
Now place your .exe in c:\windows, and you're done.
you may type the 'exename' in command-line and it'll run it.
I've wrote yet another JavaScript library, it might be better for you since it's very sensitive with the least possible false positives, fast and small in size. I'm currently actively maintaining it so please do test it in the demo page and see how it would work for you.
There are some things to change in your code:
0x7634706d
: out = cv2.VideoWriter('output.mp4',0x7634706d , 20.0, (640,480))
You're using S_ISREG()
and S_ISDIR()
correctly, you're just using them on the wrong thing.
In your while((dit = readdir(dip)) != NULL)
loop in main
, you're calling stat
on currentPath
over and over again without changing currentPath
:
if(stat(currentPath, &statbuf) == -1) {
perror("stat");
return errno;
}
Shouldn't you be appending a slash and dit->d_name
to currentPath
to get the full path to the file that you want to stat
? Methinks that similar changes to your other stat
calls are also needed.
Solution to the original question
You called a non-static method statically. To make a public function static in the model, would look like this:
public static function {
}
In General:
Post::get()
In this particular instance:
Post::take(2)->get()
One thing to be careful of, when defining relationships and scope, that I had an issue with that caused a 'non-static method should not be called statically' error is when they are named the same, for example:
public function category(){
return $this->belongsTo('App\Category');
}
public function scopeCategory(){
return $query->where('category', 1);
}
When I do the following, I get the non-static error:
Event::category()->get();
The issue, is that Laravel is using my relationship method called category, rather than my category scope (scopeCategory). This can be resolved by renaming the scope or the relationship. I chose to rename the relationship:
public function cat(){
return $this->belongsTo('App\Category', 'category_id');
}
Please observe that I defined the foreign key (category_id) because otherwise Laravel would have looked for cat_id instead, and it wouldn't have found it, as I had defined it as category_id in the database.
If your SSH proxy connection is going to be used often, you don't have to pass them as parameters each time. you can add the following lines to ~/.ssh/config
Host foobar.example.com
ProxyCommand nc -X connect -x proxyhost:proxyport %h %p
ServerAliveInterval 10
then to connect use
ssh foobar.example.com
Source:
http://www.perkin.org.uk/posts/ssh-via-http-proxy-in-osx.html
for inserting data into table you can write
insert into tablename values(column_name1,column_name2,column_name3);
but write the column_name
in the sequence as per sequence in table ...
[Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:
extension=php_ldap.dll
Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin Restart Apache. You can now use functions of the LDAP Module!
Indices imply lots of comparisons.
Typically, strings are longer than integers and collation rules may be applied for comparison, so comparing strings is usually more computationally intensive task than comparing integers.
Sometimes, though, it's faster to use a string as a primary key than to make an extra join with a string to numerical id
table.
Here's an example of a SP that both returns a table and a return value. I don't know if you need the return the "Return Value" and I have no idea about MATLAB and what it requires.
CREATE PROCEDURE test
AS
BEGIN
SELECT * FROM sys.databases
RETURN 27
END
--Use this to test
DECLARE @returnval int
EXEC @returnval = test
SELECT @returnval
myString.toInt()
- convert the string value into int .
Swift 3.x
If you have an integer hiding inside a string, you can convertby using the integer's constructor, like this:
let myInt = Int(textField.text)
As with other data types (Float and Double) you can also convert by using NSString:
let myString = "556"
let myInt = (myString as NSString).integerValue
The function 'numerically' below serves the purpose of sorting array of numbers numerically in many cases when provided as a callback function:
function numerically(a, b){
return a-b;
}
array.sort(numerically);
But in some rare instances, where array contains very large and negative numbers, an overflow error can occur as the result of a-b gets smaller than the smallest number that JavaScript can cope with.
So a better way of writing numerically function is as follows:
function numerically(a, b){
if(a < b){
return -1;
} else if(a > b){
return 1;
} else {
return 0;
}
}
Since git 2.13, it is possible to solve this using newly introduced Conditional includes.
An example:
Global config ~/.gitconfig
[user]
name = John Doe
email = [email protected]
[includeIf "gitdir:~/work/"]
path = ~/work/.gitconfig
Work specific config ~/work/.gitconfig
[user]
email = [email protected]
SET out_number=SQRT(input_number);
Instead of this write:
select SQRT(input_number);
Please don't write SET out_number
and your input parameter should be:
PROCEDURE `test`.`my_sqrt`(IN input_number INT, OUT out_number FLOAT)
Maybe you can use matplotlib for this, you can also plot normal images with it. If you call show() the image pops up in a window. Take a look at this:
The pointsize command scales the size of points, but does not affect the size of dots.
In other words, plot ... with points ps 2
will generate points of twice the normal size, but for plot ... with dots ps 2
the "ps 2
" part is ignored.
You could use circular points (pt 7
), which look just like dots.
Another option is to use find and then pass it through sed.
find /path/to/files -type f -exec sed -i 's/oldstring/new string/g' {} \;
For anyone else arriving here from Google search on how to do a string replacement on all columns (for example, if one has multiple columns like the OP's 'range' column):
Pandas has a built in replace
method available on a dataframe object.
df.replace(',', '-', regex=True)
Source: Docs
Here are a few hints:
BigDecimal
for computations if you need the precision that it offers (Money values often need this).NumberFormat
class for display. This class will take care of localization issues for amounts in different currencies. However, it will take in only primitives; therefore, if you can accept the small change in accuracy due to transformation to a double
, you could use this class.NumberFormat
class, use the scale()
method on the BigDecimal
instance to set the precision and the rounding method.PS: In case you were wondering, BigDecimal
is always better than double
, when you have to represent money values in Java.
PPS:
Creating BigDecimal
instances
This is fairly simple since BigDecimal
provides constructors to take in primitive values, and String
objects. You could use those, preferably the one taking the String
object. For example,
BigDecimal modelVal = new BigDecimal("24.455");
BigDecimal displayVal = modelVal.setScale(2, RoundingMode.HALF_EVEN);
Displaying BigDecimal
instances
You could use the setMinimumFractionDigits
and setMaximumFractionDigits
method calls to restrict the amount of data being displayed.
NumberFormat usdCostFormat = NumberFormat.getCurrencyInstance(Locale.US);
usdCostFormat.setMinimumFractionDigits( 1 );
usdCostFormat.setMaximumFractionDigits( 2 );
System.out.println( usdCostFormat.format(displayVal.doubleValue()) );
Its actually very simple: simply Rotate the list view to lay on its side
mlistView.setRotation(-90);
Then upon inflating the children, that should be inside the getView method. you rotate the children to stand up straight:
mylistViewchild.setRotation(90);
Edit: if your ListView doesnt fit properly after rotation, place the ListView inside this RotateLayout like this:
<com.github.rongi.rotate_layout.layout.RotateLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:angle="90"> <!-- Specify rotate angle here -->
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</com.github.rongi.rotate_layout.layout.RotateLayout>
I have met the same issue today. After trying various method, I realize that just put the code of sizing inside $(window).load(function() {})
instead of document.ready
would solve part of issue (if you are not ajaxing the page).
import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions)
with open('data.csv', 'r') as f:
for rec in csv.DictReader(f):
for l, col in zip(data, cols):
l.append(float(rec[col]))
print data
# [[3.0, 3.0], [0.01, 0.01]]
I don't know C# but, if it turns out there's not a convenient API way to get it, one of the ways you can do so is by following the logic:
today -> +1 month -> set day of month to 1 -> -1 day
Of course, that assumes you have date math of that type.
IF YOU HAVE PEM FILE: In Eclipse go to Window > Preferences > Network Connections > SSH2, and then add path to your PEM file to "Private keys" and that should solve the problem.
The best way to do it is to put the Django admin templates inside your project. So your templates would be in templates/admin
while the stock Django admin templates would be in say template/django_admin
. Then, you can do something like the following:
templates/admin/change_form.html
{% extends 'django_admin/change_form.html' %}
Your stuff here
If you're worried about keeping the stock templates up to date, you can include them with svn externals or similar.
I think you are talking about ctrl + shift + F, by default it should be on "look in: entire solution" and there you go.
$insert_data = mysql_real_escape_string($input_data);
Assuming that you have the data stored as $input_data
1) Dependency
compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.8.8'
2) Annotation with date-time format.
public class RestObject {
private LocalDateTime timestamp;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public LocalDateTime getTimestamp() {
return timestamp;
}
}
3) Spring Config.
@Configuration
public class JacksonConfig {
@Bean
@Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
System.out.println("Config is starting.");
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return objectMapper;
}
}
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
This is what I'm using to get the running jobs (principally so I can kill the ones which have probably hung):
SELECT
job.Name, job.job_ID
,job.Originating_Server
,activity.run_requested_Date
,datediff(minute, activity.run_requested_Date, getdate()) AS Elapsed
FROM
msdb.dbo.sysjobs_view job
INNER JOIN msdb.dbo.sysjobactivity activity
ON (job.job_id = activity.job_id)
WHERE
run_Requested_date is not null
AND stop_execution_date is null
AND job.name like 'Your Job Prefix%'
As Tim said, the MSDN / BOL documentation is reasonably good on the contents of the sysjobsX tables. Just remember they are tables in MSDB.
The marked answer seems outdated and it won't work.
Facebook now only gives unique ID related to app which isn't equal to userId and profileUrl and username will come out to be empty.
Doing me?fields=id,name,links
is also depreciated after Graph Version 2.4
The only option now is to request for user_links permission from your developer console.
and the pass it in scope when doing facebook login
scope: ['user_link'] }
or by doing an api call
Simple URL :
https://www.google.com/maps/dir/?api=1&destination=lat,lng
This url is specific for routing.
Reference : https://developers.google.com/maps/documentation/urls/guide#directions-action
//By using jquery json parser
var obj = $.parseJSON('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(obj['jobtitel']);
//By using javasript json parser
var t = JSON.parse('{"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}');
alert(t['jobtitel'])
As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON strings use the native JSON.parse method instead.
Use this Code
string DirectoryName = "Sample Name For Directory Or File";
Path.GetInvalidFileNameChars()
.Where(x => DirectoryName.Contains(x))
.Count() > 0 || DirectoryName == "con"
Try sorting the array first. Then after it's sorted, if the array has an even amount of elements the mean of the middle two is the median, if it has a odd number, the middle element is the median.
Try negation operator !
before $(this)
:
if (!$(this).parent().next().is('ul')){
unsorted_list.sort(key=lambda x: x[3])
I found out that single quote > double quote > wrapped in ampersands did work. So, for me it looks like this:
=QUERY('Youth Conference Registration'!C:Y,"select C where Y = '"&A1&"'", 0)
This counts the rows of the inner query:
select count(*) from (
select count(SID)
from Test
where Date = '2012-12-10'
group by SID
) t
However, in this case the effect of that is the same as this:
select count(distinct SID) from Test where Date = '2012-12-10'
Open and read the file.
Reader r = new BufferedReader(filename);
String ret = "";
while((String s = r.nextLine()!=null))
{
ret+=s;
}
return ret;
If you set the text state, why not use that directly?
_handlePress(event) {
var username=this.state.text;
Of course the variable naming could be more descriptive than 'text' but your call.
.contents {
width: 50%;
border: 1px solid black;
height: 300px;
overflow: auto;
}
table {
position: relative;
}
th {
position: sticky;
top: 0;
background: #ffffff;
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="contents">
<table class="table">
<thead>
<tr>
<th>colunn 1</th>
<th>colunn 2</th>
<th>colunn 3</th>
<th>colunn 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>Example 1</td>
<td>Example 2</td>
<td>Example 3</td>
<td>Example 4</td>
<tr>
<tr>
<td>Example 1</td>
<td>Example 2</td>
<td>Example 3</td>
<td>Example 4</td>
<tr>
<tr>
<td>Example 1</td>
<td>Example 2</td>
<td>Example 3</td>
<td>Example 4</td>
<tr>
<tr>
<td>Example 1</td>
<td>Example 2</td>
<td>Example 3</td>
<td>Example 4</td>
<tr>
<tr>
<td>Example 1</td>
<td>Example 2</td>
<td>Example 3</td>
<td>Example 4</td>
<tr>
<tr>
<td>Example 1</td>
<td>Example 2</td>
<td>Example 3</td>
<td>Example 4</td>
<tr>
<tr>
<td>Example 1</td>
<td>Example 2</td>
<td>Example 3</td>
<td>Example 4</td>
<tr>
<tr>
<td>Example 1</td>
<td>Example 2</td>
<td>Example 3</td>
<td>Example 4</td>
<tr>
<tr>
<td>Example 1</td>
<td>Example 2</td>
<td>Example 3</td>
<td>Example 4</td>
<tr>
<tr>
<td>Example 1</td>
<td>Example 2</td>
<td>Example 3</td>
<td>Example 4</td>
<tr>
</tbody>
</table>
</div>
_x000D_
If each user has its own SQL Server login you could try this
select
so.name, su.name, so.crdate
from
sysobjects so
join
sysusers su on so.uid = su.uid
order by
so.crdate
This is a known issue in Chrome and resolved in latest versions. Please refer https://bugs.chromium.org/p/chromium/issues/detail?id=942440 for more details.
Progress Bar in Layout
<ProgressBar
android:id="@+id/download_progressbar"
android:layout_width="200dp"
android:layout_height="24dp"
android:background="@drawable/download_progress_bg_track"
android:progressDrawable="@drawable/download_progress_style"
style="?android:attr/progressBarStyleHorizontal"
android:indeterminate="false"
android:indeterminateOnly="false" />
download_progress_style.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/progress">
<scale
android:useIntrinsicSizeAsMinimum="true"
android:scaleWidth="100%"
android:drawable="@drawable/store_download_progress" />
</item>
Pretty much similar to nightcoder's solution except it's easier to raise primes if you want to.
PS: This is one of those times where you puke a little in your mouth, knowing that this could be refactored into one method with 9 default's but it would be slower, so you just close your eyes and try to forget about it.
/// <summary>
/// Try not to look at the source code. It works. Just rely on it.
/// </summary>
public static class HashHelper
{
private const int PrimeOne = 17;
private const int PrimeTwo = 23;
public static int GetHashCode<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10)
{
unchecked
{
int hash = PrimeOne;
hash = hash * PrimeTwo + arg1.GetHashCode();
hash = hash * PrimeTwo + arg2.GetHashCode();
hash = hash * PrimeTwo + arg3.GetHashCode();
hash = hash * PrimeTwo + arg4.GetHashCode();
hash = hash * PrimeTwo + arg5.GetHashCode();
hash = hash * PrimeTwo + arg6.GetHashCode();
hash = hash * PrimeTwo + arg7.GetHashCode();
hash = hash * PrimeTwo + arg8.GetHashCode();
hash = hash * PrimeTwo + arg9.GetHashCode();
hash = hash * PrimeTwo + arg10.GetHashCode();
return hash;
}
}
public static int GetHashCode<T1, T2, T3, T4, T5, T6, T7, T8, T9>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9)
{
unchecked
{
int hash = PrimeOne;
hash = hash * PrimeTwo + arg1.GetHashCode();
hash = hash * PrimeTwo + arg2.GetHashCode();
hash = hash * PrimeTwo + arg3.GetHashCode();
hash = hash * PrimeTwo + arg4.GetHashCode();
hash = hash * PrimeTwo + arg5.GetHashCode();
hash = hash * PrimeTwo + arg6.GetHashCode();
hash = hash * PrimeTwo + arg7.GetHashCode();
hash = hash * PrimeTwo + arg8.GetHashCode();
hash = hash * PrimeTwo + arg9.GetHashCode();
return hash;
}
}
public static int GetHashCode<T1, T2, T3, T4, T5, T6, T7, T8>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8)
{
unchecked
{
int hash = PrimeOne;
hash = hash * PrimeTwo + arg1.GetHashCode();
hash = hash * PrimeTwo + arg2.GetHashCode();
hash = hash * PrimeTwo + arg3.GetHashCode();
hash = hash * PrimeTwo + arg4.GetHashCode();
hash = hash * PrimeTwo + arg5.GetHashCode();
hash = hash * PrimeTwo + arg6.GetHashCode();
hash = hash * PrimeTwo + arg7.GetHashCode();
hash = hash * PrimeTwo + arg8.GetHashCode();
return hash;
}
}
public static int GetHashCode<T1, T2, T3, T4, T5, T6, T7>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7)
{
unchecked
{
int hash = PrimeOne;
hash = hash * PrimeTwo + arg1.GetHashCode();
hash = hash * PrimeTwo + arg2.GetHashCode();
hash = hash * PrimeTwo + arg3.GetHashCode();
hash = hash * PrimeTwo + arg4.GetHashCode();
hash = hash * PrimeTwo + arg5.GetHashCode();
hash = hash * PrimeTwo + arg6.GetHashCode();
hash = hash * PrimeTwo + arg7.GetHashCode();
return hash;
}
}
public static int GetHashCode<T1, T2, T3, T4, T5, T6>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6)
{
unchecked
{
int hash = PrimeOne;
hash = hash * PrimeTwo + arg1.GetHashCode();
hash = hash * PrimeTwo + arg2.GetHashCode();
hash = hash * PrimeTwo + arg3.GetHashCode();
hash = hash * PrimeTwo + arg4.GetHashCode();
hash = hash * PrimeTwo + arg5.GetHashCode();
hash = hash * PrimeTwo + arg6.GetHashCode();
return hash;
}
}
public static int GetHashCode<T1, T2, T3, T4, T5>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
{
unchecked
{
int hash = PrimeOne;
hash = hash * PrimeTwo + arg1.GetHashCode();
hash = hash * PrimeTwo + arg2.GetHashCode();
hash = hash * PrimeTwo + arg3.GetHashCode();
hash = hash * PrimeTwo + arg4.GetHashCode();
hash = hash * PrimeTwo + arg5.GetHashCode();
return hash;
}
}
public static int GetHashCode<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
unchecked
{
int hash = PrimeOne;
hash = hash * PrimeTwo + arg1.GetHashCode();
hash = hash * PrimeTwo + arg2.GetHashCode();
hash = hash * PrimeTwo + arg3.GetHashCode();
hash = hash * PrimeTwo + arg4.GetHashCode();
return hash;
}
}
public static int GetHashCode<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3)
{
unchecked
{
int hash = PrimeOne;
hash = hash * PrimeTwo + arg1.GetHashCode();
hash = hash * PrimeTwo + arg2.GetHashCode();
hash = hash * PrimeTwo + arg3.GetHashCode();
return hash;
}
}
public static int GetHashCode<T1, T2>(T1 arg1, T2 arg2)
{
unchecked
{
int hash = PrimeOne;
hash = hash * PrimeTwo + arg1.GetHashCode();
hash = hash * PrimeTwo + arg2.GetHashCode();
return hash;
}
}
}
Try this way:
<%= f.select(:object_field, ['Item 1', ...], {}, { :class => 'my_style_class' }) %>
select
helper takes two options hashes, one for select, and the second for html options. So all you need is to give default empty options as first param after list of items and then add your class to html_options
.
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select
You can use any one these [starting from the fastest]
$("#moo") > $("#foo #moo") > $("div#foo span#moo") > $("#foo span") > $("#foo > #moo")
Rules for padding:
Why Rule 2: Consider the following struct,
If we were to create an array(of 2 structs) of this struct, No padding will be required at the end:
Therefore, size of struct = 8 bytes
Assume we were to create another struct as below:
If we were to create an array of this struct, there are 2 possibilities, of the number of bytes of padding required at the end.
A. If we add 3 bytes at the end and align it for int and not Long:
B. If we add 7 bytes at the end and align it for Long:
The start address of the second array is a multiple of 8(i.e 24). The size of the struct = 24 bytes
Therefore, by aligning the start address of the next array of the struct to a multiple of the largest member(i.e if we were to create an array of this struct, the first address of the second array must start at an address which is a multiple of the largest member of the struct. Here it is, 24(3 * 8)), we can calculate the number of padding bytes required at the end.
jQuery serialize
closely mimics how a standard form would be serialized by the browser before being appended to the query string or POST body in the request. Unchecked checkboxes aren't included by the browser, which makes sense really because they have a boolean state -- they're either selected by the user (included) or not selected by the user (not included).
If you need it to be in the serialized, you should ask yourself "why? why not just check for its existence in the data?".
Bear in mind that if the way JavaScript serializes form data behaves differently to the way the browser does it then you're eliminating any chance of graceful degradation for your form. If you still absolutely need to do it, just use a <select>
box with Yes/No as options. At least then, users with JS disabled aren't alienated from your site and you're not going against the defined behaviour in the HTML specification.
<select id="event_allDay" name="event_allDay">
<option value="0" selected>No</option>
<option value="1">Yes</option>
</select>
I've seen this employed on some sites in the past and always thought to myself, "why don't they just use a checkbox"?
Do it in the controller ( controller as syntax below)
controller:
vm.question= {};
vm.question.active = true;
form
<input ng-model="vm.question.active" type="checkbox" id="active" name="active">
SQL Wildcards are enough for this purpose. Follow this link: http://www.w3schools.com/SQL/sql_wildcards.asp
you need to use a query like this:
select * from mytable where msisdn like '%7%'
or
select * from mytable where msisdn like '56655%'
In the controller add following lines when you make the cunstructor
i.e, after
parent::Controller();
add below lines
$this->load->helper('lang_translate');
$this->lang->load('nl_site', 'nl'); // ('filename', 'directory')
create helper file lang_translate_helper.php with following function and put it in directory system\application\helpers
function label($label, $obj)
{
$return = $obj->lang->line($label);
if($return)
echo $return;
else
echo $label;
}
for each of the language, create a directory with language abbrevation like en, nl, fr, etc., under system\application\languages
create language file in above (respective) directory which will contain $lang array holding pairs label=>language_value as given below
nl_site_lang.php
$lang['welcome'] = 'Welkom';
$lang['hello word'] = 'worde Witaj';
en_site_lang.php
$lang['welcome'] = 'Welcome';
$lang['hello word'] = 'Hello Word';
you can store multiple files for same language with differently as per the requirement e.g, if you want separate language file for managing backend (administrator section) you can use it in controller as $this->lang->load('nl_admin', 'nl');
nl_admin_lang.php
$lang['welcome'] = 'Welkom';
$lang['hello word'] = 'worde Witaj';
and finally to print the label in desired language, access labels as below in view
label('welcome', $this);
OR
label('hello word', $this);
note the space in hello & word you can use it like this way as well :)
whene there is no lable defined in the language file, it will simply print it what you passed to the function label.
I implemented many automation cases based on REST Assured , a jave DSL for testing restful service. https://code.google.com/p/rest-assured/
The syntax is easy, it supports json and xml. https://code.google.com/p/rest-assured/wiki/Usage
Before that, I tried SOAPUI and had some issues with the free version. Plus the cases are in xml files which hard to extend and reuse, simply I don't like
The following worked, but only after I upgraded PSEXEC to 2.1 from Microsoft.
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System] "LocalAccountTokenFilterPolicy"=dword:00000001 See: http://forum.sysinternals.com/topic10924.html
I had a slightly older version that didn't work. I used it to do some USMT work via Dell kace, worked a treat :)
Since you have not mentioned what needs to be copied, I have left that section empty in the code below.
Also you don't need to move the email to the folder first and then run the macro in that folder. You can run the macro on the incoming mail and then move it to the folder at the same time.
This will get you started. I have commented the code so that you will not face any problem understanding it.
First paste the below mentioned code in the outlook module.
Then
When the new email arrives not only will the email move to the folder that you specify but data from it will be exported to Excel as well.
UNTESTED
Const xlUp As Long = -4162
Sub ExportToExcel(MyMail As MailItem)
Dim strID As String, olNS As Outlook.Namespace
Dim olMail As Outlook.MailItem
Dim strFileName As String
'~~> Excel Variables
Dim oXLApp As Object, oXLwb As Object, oXLws As Object
Dim lRow As Long
strID = MyMail.EntryID
Set olNS = Application.GetNamespace("MAPI")
Set olMail = olNS.GetItemFromID(strID)
'~~> Establish an EXCEL application object
On Error Resume Next
Set oXLApp = GetObject(, "Excel.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set oXLApp = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0
'~~> Show Excel
oXLApp.Visible = True
'~~> Open the relevant file
Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xls")
'~~> Set the relevant output sheet. Change as applicable
Set oXLws = oXLwb.Sheets("Sheet1")
lRow = oXLws.Range("A" & oXLApp.Rows.Count).End(xlUp).Row + 1
'~~> Write to outlook
With oXLws
'
'~~> Code here to output data from email to Excel File
'~~> For example
'
.Range("A" & lRow).Value = olMail.Subject
.Range("B" & lRow).Value = olMail.SenderName
'
End With
'~~> Close and Clean up Excel
oXLwb.Close (True)
oXLApp.Quit
Set oXLws = Nothing
Set oXLwb = Nothing
Set oXLApp = Nothing
Set olMail = Nothing
Set olNS = Nothing
End Sub
FOLLOWUP
To extract the contents from your email body, you can split it using SPLIT() and then parsing out the relevant information from it. See this example
Dim MyAr() As String
MyAr = Split(olMail.body, vbCrLf)
For i = LBound(MyAr) To UBound(MyAr)
'~~> This will give you the contents of your email
'~~> on separate lines
Debug.Print MyAr(i)
Next i
$('#summary').load('ajax.php', function() {
alert('Loaded.');
});
You can also use the didSet
to set the variable to a different value. This does not cause the observer to be called again as stated in Properties guide. For example, it is useful when you want to limit the value as below:
let minValue = 1
var value = 1 {
didSet {
if value < minValue {
value = minValue
}
}
}
value = -10 // value is minValue now.
I'm guessing EventDate
is a char or varchar and not a date otherwise your order by clause would be fine.
You can use CONVERT to change the values to a date and sort by that
SELECT *
FROM
vw_view
ORDER BY
CONVERT(DateTime, EventDate,101) DESC
The problem with that is, as Sparky points out in the comments, if EventDate has a value that can't be converted to a date the query won't execute.
This means you should either exclude the bad rows or let the bad rows go to the bottom of the results
To exclude the bad rows just add WHERE IsDate(EventDate) = 1
To let let the bad dates go to the bottom you need to use CASE
e.g.
ORDER BY
CASE
WHEN IsDate(EventDate) = 1 THEN CONVERT(DateTime, EventDate,101)
ELSE null
END DESC
I think it is good for you.
BigDecimal.valueOf([LONG_VALUE]).doubleValue()
How about this code? :D
Now as from angular2 beta 8 we can use *ngIf
and *ngFor
on same component see here.
Alternate:
Sometimes we can't use HTML tags inside another like in tr
, th
(table
) or in li
(ul
). We cannot use another HTML tag but we have to perform some action in same situation so we can HTML5 feature tag <template>
in this way.
<template ngFor #abc [ngForOf]="someArray">
code here....
</template>
<template [ngIf]="show">
code here....
</template>
For more information about structural directives in angular2 see here.
var json = jQuery.parseJSON(s); //If you have jQuery.
Since the comment looks cluttered, please use the parse function after enclosing those square brackets inside the quotes.
var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];
Change the above code to
var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
Eg:
$(document).ready(function() {
var s= '[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
s = jQuery.parseJSON(s);
alert( s[0]["Select"] );
});
And then use the parse function. It'll surely work.
EDIT :Extremely sorry that I gave the wrong function name. it's jQuery.parseJSON
Edit (30 April 2020):
Editing since I got an upvote for this answer. There's a browser native function available instead of JQuery (for nonJQuery users), JSON.parse("<json string here>")
The value for your onClick
attribute should be a function, not a function call.
<button type="submit" onClick={function(){removeTaskFunction(todo)}}>Submit</button>
I agree with what Joachim Sauer said, not possible to know (the variable type! not value type!) unless your variable is a class attribute (and you would have to retrieve class fields, get the right field by name...)
Actually for me it's totally impossible that any a.xxx().yyy()
method give you the right answer since the answer would be different on the exact same object, according to the context in which you call this method...
As teehoo said, if you know at compile a defined list of types to test you can use instanceof but you will also get subclasses returning true...
One possible solution would also be to inspire yourself from the implementation of java.lang.reflect.Field
and create your own Field
class, and then declare all your local variables as this custom Field
implementation... but you'd better find another solution, i really wonder why you need the variable type, and not just the value type?
The following code displays which JRadiobutton is selected from Buttongroup on click of a button.
It is done by looping through all JRadioButtons in a particular buttonGroup.
JRadioButton firstRadioButton=new JRadioButton("Female",true);
JRadioButton secondRadioButton=new JRadioButton("Male");
//Create a radio button group using ButtonGroup
ButtonGroup btngroup=new ButtonGroup();
btngroup.add(firstRadioButton);
btngroup.add(secondRadioButton);
//Create a button with text ( What i select )
JButton button=new JButton("What i select");
//Add action listener to created button
button.addActionListener(this);
//Get selected JRadioButton from ButtonGroup
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==button)
{
Enumeration<AbstractButton> allRadioButton=btngroup.getElements();
while(allRadioButton.hasMoreElements())
{
JRadioButton temp=(JRadioButton)allRadioButton.nextElement();
if(temp.isSelected())
{
JOptionPane.showMessageDialog(null,"You select : "+temp.getText());
}
}
}
}
Python has a built in any() function for exactly this purpose.
You probably need to use reflection to get the types of them to check. To get the type of the List: Get generic type of java.util.List
See help(Sys.sleep)
.
For example, from ?Sys.sleep
testit <- function(x)
{
p1 <- proc.time()
Sys.sleep(x)
proc.time() - p1 # The cpu usage should be negligible
}
testit(3.7)
Yielding
> testit(3.7)
user system elapsed
0.000 0.000 3.704
Changing back navigation icon differs for ActionBar and Toolbar.
For ActionBar override homeAsUpIndicator
attribute:
<style name="CustomThemeActionBar" parent="android:Theme.Holo">
<item name="homeAsUpIndicator">@drawable/ic_nav_back</item>
</style>
For Toolbar override navigationIcon
attribute:
<style name="CustomThemeToolbar" parent="Theme.AppCompat.Light.NoActionBar">
<item name="navigationIcon">@drawable/ic_nav_back</item>
</style>
Everyone should use this source link:
http://mongodb.github.com/node-mongodb-native/contents.html
Answer to the question:
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON,
assert = require('assert');
var db = new Db('integration_tests', new Server("127.0.0.1", 27017,
{auto_reconnect: false, poolSize: 4}), {w:0, native_parser: false});
// Establish connection to db
db.open(function(err, db) {
assert.equal(null, err);
// Add a user to the database
db.addUser('user', 'name', function(err, result) {
assert.equal(null, err);
// Authenticate
db.authenticate('user', 'name', function(err, result) {
assert.equal(true, result);
db.close();
});
});
});
# SOCKS5 proxy for HTTP/HTTPS
proxiesDict = {
'http' : "socks5://1.2.3.4:1080",
'https' : "socks5://1.2.3.4:1080"
}
# SOCKS4 proxy for HTTP/HTTPS
proxiesDict = {
'http' : "socks4://1.2.3.4:1080",
'https' : "socks4://1.2.3.4:1080"
}
# HTTP proxy for HTTP/HTTPS
proxiesDict = {
'http' : "1.2.3.4:1080",
'https' : "1.2.3.4:1080"
}
I faced the same problem and seems that there have been many changes by google.
I can tell you the steps for installing purely via command line from scratch. I tested it on Ubuntu on 22 Feb 2021.
export ANDROID_SDK_ROOT=/usr/lib/android-sdk
sudo mkdir -p $ANDROID_SDK_ROOT
sudo apt-get install openjdk-8-jdk
Go to https://developer.android.com/studio/index.html Then down to Command line tools only Click on Linux link, accept the agreement and instead of downloading right click and copy link address
cd $ANDROID_SDK_ROOT
sudo wget https://dl.google.com/android/repository/commandlinetools-linux-6858069_latest.zip
sudo unzip commandlinetools-linux-6858069_latest.zip
Rename the unpacked directory from cmdline-tools to tools, and place it under $ANDROID_SDK_ROOT/cmdline-tools, so now it should look like: $ANDROID_SDK_ROOT/cmdline-tools/tools. And inside it, you should have: NOTICE.txt bin lib source.properties.
PATH=$PATH:$ANDROID_SDK_ROOT/cmdline-tools/latest/bin:$ANDROID_SDK_ROOT/cmdline-tools/tools/bin
This had no effect for me, hence the next step
cd $ANDROID_SDK_ROOT/cmdline-tools/tools/bin
yes | sudo sdkmanager --licenses
Finally, run this inside your project
sudo ./gradlew assembleDebug
This creates an APK named -debug.apk at //build/outputs/apk/debug The file is already signed with the debug key and aligned with zipalign, so you can immediately install it on a device.
https://gist.github.com/guipmourao/3e7edc951b043f6de30ca15a5cc2be40
Android Command line tools sdkmanager always shows: Warning: Could not create settings
"Failed to install the following Android SDK packages as some licences have not been accepted" error
https://developer.android.com/studio/build/building-cmdline#sign_cmdline
I had commented out the ::1 line in my hosts file.
Something like this:
Dim rng As Range
Dim row As Range
Dim cell As Range
Set rng = Range("A1:C2")
For Each row In rng.Rows
For Each cell in row.Cells
'Do Something
Next cell
Next row
Make argument object extends from <a>
,
and use open
function of fancybox in click event via delegate.
var paramsFancy={
'autoScale': true,
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'speedIn': 500,
'speedOut': 300,
'autoDimensions': true,
'centerOnScroll': true,
'href' : '#contentdiv'
};
$(document).delegate('a[href=#modalMine]','click',function(){
/*Now you can call your function ,
you can change fields of paramsFancy via this function */
myfunction(this);
paramsFancy.href=$(this).attr('href');
$.fancybox.open(paramsFancy);
});
Use Hosts Commander. It's simple and powerful. Translated description (from russian) here.
hosts add another.dev 192.168.1.1 # Remote host
hosts add test.local # 127.0.0.1 used by default
hosts set myhost.dev # new comment
hosts rem *.local
hosts enable local*
hosts disable localhost
...and many others...
Usage:
hosts - run hosts command interpreter
hosts <command> <params> - execute hosts command
Commands:
add <host> <aliases> <addr> # <comment> - add new host
set <host|mask> <addr> # <comment> - set ip and comment for host
rem <host|mask> - remove host
on <host|mask> - enable host
off <host|mask> - disable host
view [all] <mask> - display enabled and visible, or all hosts
hide <host|mask> - hide host from 'hosts view'
show <host|mask> - show host in 'hosts view'
print - display raw hosts file
format - format host rows
clean - format and remove all comments
rollback - rollback last operation
backup - backup hosts file
restore - restore hosts file from backup
recreate - empty hosts file
open - open hosts file in notepad
The best solution I've found is Respond.js especially if your main concern is making sure your responsive design works in IE8. It's pretty lightweight at 1kb when min/gzipped and you can make sure only IE8 clients load it:
<!--[if lt IE 9]>
<script src="respond.min.js"></script>
<![endif]-->
It's also the recommended method if you're using bootstrap: http://getbootstrap.com/getting-started/#support-ie8-ie9
Try this header file in your code
stdbool.h
This must work
I've gotten around this by using the td elements in the row:
$(ui.item).children("td").effect("highlight", { color: "#4ca456" }, 1000);
Animating the row itself causes strange behaviour, mostly async animation problems.
For the above code, I am highlighting a row that gets dragged and dropped around in the table to highlight that the update has succeeded. Hope this helps someone.
you can try this too And it will work:
DECLARE
a NUMBER;
b NUMBER;
BEGIN
a :=: a; --this will take input from user
b :=: b;
DBMS_OUTPUT.PUT_LINE('a = '|| a);
DBMS_OUTPUT.PUT_LINE('b = '|| b);
END;
I also Had to filter based on the URL pattern(/{servicename}/api/stats/)in java code .
if (path.startsWith("/{servicename}/api/statistics/")) {
validatingAuthToken(((HttpServletRequest) request).getHeader("auth_token"));
filterChain.doFilter(request, response);
}
But its bizarre, that servlet doesn't support url pattern other than (/*), This should be a very common case for servlet API's !
Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.
SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean,
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)
I was looking at the answers and... realized that nobody thought about FLOAT numbers (with dot)!
Using grep is great too.
-E means extended regexp
-q means quiet (doesn't echo)
-qE is the combination of both.
To test directly in the command line:
$ echo "32" | grep -E ^\-?[0-9]?\.?[0-9]+$
# answer is: 32
$ echo "3a2" | grep -E ^\-?[0-9]?\.?[0-9]+$
# answer is empty (false)
$ echo ".5" | grep -E ^\-?[0-9]?\.?[0-9]+$
# answer .5
$ echo "3.2" | grep -E ^\-?[0-9]?\.?[0-9]+$
# answer is 3.2
Using in a bash script:
check=`echo "$1" | grep -E ^\-?[0-9]*\.?[0-9]+$`
if [ "$check" != '' ]; then
# it IS numeric
echo "Yeap!"
else
# it is NOT numeric.
echo "nooop"
fi
To match JUST integers, use this:
# change check line to:
check=`echo "$1" | grep -E ^\-?[0-9]+$`
Perhaps you could turn some of the arguments into member variables. If you need that much state a class sounds like a good idea to me.
As of version 17.0, you can format with the dt
accessor:
dates.dt.strftime('%Y-%m-%d')
If you're looking to quickly implement this in a Rails controller action to send a JSON response:
def index
my_json = '{ "key": "value" }'
render json: JSON.pretty_generate( JSON.parse my_json )
end
!important
is a part of CSS1.
Browsers supporting it: IE5.5+, Firefox 1+, Safari 3+, Chrome 1+.
It means, something like:
Use me, if there is nothing important else around!
Cant say it better.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace data_seniens
{
class Program
{
static void Main(string[] args)
{
//new list
float [] x=new float[]{11.25f,18.0f,20.0f,10.75f,9.50f, 11.25f, 18.0f, 20.0f, 10.75f, 9.50f };
//variable
float eat_sleep_area=x[1]+x[3];
//print
foreach (var VARIABLE in x)
{
if (VARIABLE < x[7])
{
Console.WriteLine(VARIABLE);
}
}
//keep app run
Console.ReadLine();
}
}
}
You can also do this easily with gitk.
> gitk branch1 branch2
First click on the tip of branch1. Now right-click on the tip of branch2 and select Diff this->selected.
Following solution is very basic and simple approach to send data from VC2 to VC1 using delegate .
PS: This solution is made in Xcode 9.X and Swift 4
Declared a protocol and created a delegate var into ViewControllerB
import UIKit
//Declare the Protocol into your SecondVC
protocol DataDelegate {
func sendData(data : String)
}
class ViewControllerB : UIViewController {
//Declare the delegate property in your SecondVC
var delegate : DataDelegate?
var data : String = "Send data to ViewControllerA."
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func btnSendDataPushed(_ sender: UIButton) {
// Call the delegate method from SecondVC
self.delegate?.sendData(data:self.data)
dismiss(animated: true, completion: nil)
}
}
ViewControllerA confirms the protocol and expected to receive data via delegate method sendData
import UIKit
// Conform the DataDelegate protocol in ViewControllerA
class ViewControllerA : UIViewController , DataDelegate {
@IBOutlet weak var dataLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func presentToChild(_ sender: UIButton) {
let childVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier:"ViewControllerB") as! ViewControllerB
//Registered delegate
childVC.delegate = self
self.present(childVC, animated: true, completion: nil)
}
// Implement the delegate method in ViewControllerA
func sendData(data : String) {
if data != "" {
self.dataLabel.text = data
}
}
}
Both 'is' and 'as' are valid syntax. Output is disabled by default. Try a procedure that also enables output...
create or replace procedure temp_proc is
begin
DBMS_OUTPUT.ENABLE(1000000);
DBMS_OUTPUT.PUT_LINE('Test');
end;
...and call it in a PLSQL block...
begin
temp_proc;
end;
...as SQL is non-procedural.
Assuming the list is already data bound you can simply set the SelectedValue
property on your dropdown list.
list.DataSource = GetListItems(); // <-- Get your data from somewhere.
list.DataValueField = "ValueProperty";
list.DataTextField = "TextProperty";
list.DataBind();
list.SelectedValue = myValue.ToString();
The value of the myValue
variable would need to exist in the property specified within the DataValueField
in your controls databinding.
UPDATE:
If the value of myValue
doesn't exist as a value with the dropdown list options it will default to select the first option in the dropdown list.
My finding is as below. If I compile using the Android Studio UI, and the APK generated, I can't just
adb install <xxx.apk>
It will generate Failure [INSTALL_FAILED_TEST_ONLY]
I need to compile it using the gradle i.e. ./gradlew app:assembleRelease
. Then only the generated apk, then it can only be installed.
This is because the Android Studio UI Compile, only generate test apk for a particular device, while ./gradlew app:assembleRelease
command is the actual apk generation to be installed on all device (and upload to playstore)
This is used in several apps to clean user-generated content removing extra spacing/returns etc but retains the meaning of spaces.
text.replace(/[\n\r\s\t]+/g, ' ')
Constructors are not inherited, you must create a new, identically prototyped constructor in the subclass that maps to its matching constructor in the superclass.
Here is an example of how this works:
class Foo {
Foo(String str) { }
}
class Bar extends Foo {
Bar(String str) {
// Here I am explicitly calling the superclass
// constructor - since constructors are not inherited
// you must chain them like this.
super(str);
}
}
The Hashtable
is a loosely-typed data structure, so you can add keys and values of any type to the Hashtable
. The Dictionary
class is a type-safe Hashtable
implementation, and the keys and values are strongly typed. When creating a Dictionary
instance, you must specify the data types for both the key and value.
Let's solve that using recursion...
ArrayList<Integer> al = new ArrayList<>();
void intToArray(int num){
if( num != 0){
int temp = num %10;
num /= 10;
intToArray(num);
al.add(temp);
}
}
Explanation:
Suppose the value of num
is 12345.
During the first call of the function, temp
holds the value 5 and a value of num
= 1234. It is again passed to the function, and now temp
holds the value 4 and the value of num
is 123... This function calls itself till the value of num
is not equal to 0.
Stack trace:
temp - 5 | num - 1234
temp - 4 | num - 123
temp - 3 | num - 12
temp - 2 | num - 1
temp - 1 | num - 0
And then it calls the add method of ArrayList and the value of temp
is added to it, so the value of list is:
ArrayList - 1
ArrayList - 1,2
ArrayList - 1,2,3
ArrayList - 1,2,3,4
ArrayList - 1,2,3,4,5
Yes, for Virtualbox provider do something like this:
Vagrant.configure("2") do |config|
# ...other options...
config.vm.provider "virtualbox" do |p|
p.name = "something-else"
end
end
you must use datepart()
like
datepart(hour , getdate())
I think you want to remove the last five characters ('.', 'n', 'u', 'l', 'l'):
path = path.substring(0, path.length() - 5);
Note how you need to use the return value - strings are immutable, so substring
(and other methods) don't change the existing string - they return a reference to a new string with the appropriate data.
Or to be a bit safer:
if (path.endsWith(".null")) {
path = path.substring(0, path.length() - 5);
}
However, I would try to tackle the problem higher up. My guess is that you've only got the ".null" because some other code is doing something like this:
path = name + "." + extension;
where extension
is null. I would conditionalise that instead, so you never get the bad data in the first place.
(As noted in a question comment, you really should look through the String
API. It's one of the most commonly-used classes in Java, so there's no excuse for not being familiar with it.)
Just notepad ~/.bashrc
from the git bash shell and save your file.That should be all.
NOTE: Please ensure that you need to restart your terminal for changes to be reflected.
With jQuery:
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function()
{
//file not exists
},
success: function()
{
//file exists
}
});
EDIT:
Here is the code for checking 404 status, without using jQuery
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
Small changes and it could check for status HTTP status code 200 (success), instead.
EDIT 2: Since sync XMLHttpRequest is deprecated, you can add a utility method like this to do it async:
function executeIfFileExist(src, callback) {
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (this.readyState === this.DONE) {
callback()
}
}
xhr.open('HEAD', src)
}
If you want to call a different size for the button inline, you would probably do it like this:
<div class="button" style="width:60px;height:100px;">This is a button</div>
Or, a better way to have different sizes (say there will be 3 standard sizes for the button) would be to have classes just for size.
For example, you would call your button like this:
<div class="button small">This is a button</div>
And in your CSS
.button.small { width: 60px; height: 100px; }
and just create classes for each size you wish to have. That way you still have the perks of using a stylesheet in case say, you want to change the size of all the small buttons at once.
My fix for this was my child table needed to be populated before the parent table.
I had two tables: UserDetails and Login linked by an email address. I therefore had to insert into the UserDetails first before inserting into the Login table:
insert into UserDetails (Email, Name, Telephone, Department) values ('Email', 'Name', 'number', 'IT');
Then:
insert into Login (UserID, UserType, Email, Username, Password) VALUES (001, 'SYS-USR-ADMIN', 'Email', 'Name', 'Password')
var datep = $('#datepicker').val();
if(Date.parse(datep)-Date.parse(new Date())<0)
{
// do something
}
Another thing you can do is just drag a folder from your computer into the GitHub repository page. This folder does have to have at least 1 item in it, though.
My implementation as an Int extension. Will generate random numbers in range from..<to
public extension Int {
static func random(from: Int, to: Int) -> Int {
guard to > from else {
assertionFailure("Can not generate negative random numbers")
return 0
}
return Int(arc4random_uniform(UInt32(to - from)) + UInt32(from))
}
}
Another thing to note is that if you want a absolute element to be confined to a parent element then you need to set the parent element's position to relative. That will keep the child element contained within the parent element and it won't be "relative" to the entire window.
I wrote a blog post that gives a simple example that creates the following affect:
That has a green div that is absolutely positioned to the bottom of the parent yellow div.
1 http://blog.troygrosfield.com/2013/02/11/working-with-css-positions-creating-a-simple-progress-bar/
I tried all the solutions mentioned above, then did not work. I have 3 tables one below the other. The last one over flowed. I fixed it using:
/* Grid Definition */
table {
word-break: break-word;
}
For IE11 in edge mode, you need to set this to word-break:break-all
Well, you are using both frame.setSize()
and frame.pack()
.
You should use one of them at one time.
Using setSize()
you can give the size of frame you want but if you use pack()
, it will automatically change the size of the frames according to the size of components in it. It will not consider the size you have mentioned earlier.
Try removing frame.pack()
from your code or putting it before setting size and then run it.
You do the same way as any other character matching, but you use \uXXXX where XXXX is the unicode number of the character.
Have a look at the error - 'log4j:ERROR setFile(null,false) call failed. java.io.FileNotFoundException: logs (Access is denied)'
It seems there's a log file named as 'logs' to which access is denied i.e it is not having sufficient permissions to write logs. Try by giving write permissions to the 'logs' log file. Hope it helps.
I had this problem and it took me hours to figure out. The mainly reason of this error is the SoapClient cannot stream the web service file from the host. I uncommented this line "extension=php_openssl.dll" in my php.ini file and it works.
Even using some of the comments above this took way longer to work out that should be necessary. Hopefully this example helps someone else.
Create a radio_button.xml in the drawable directory.
<?xml version="1.0" encoding="utf-8"?>
<!-- An element which allows two drawable items to be listed.-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/radio_button_checked" /> <!--pressed -->
<item android:drawable="@drawable/radio_button_unchecked" /> <!-- Normal -->
</selector>
Then in the xml for the fragment should look something like
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="1"
android:button="@drawable/radio_button"
android:paddingLeft="10dp" />
<RadioButton
android:id="@+id/radioButton2"
android:layout_marginLeft="10dp"
android:paddingLeft="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:button="@drawable/radio_button" />
</RadioGroup>
</LinearLayout>
</layout>
I just figured out that json_encode
does only escape \n
if it's used within single quotes.
echo json_encode("Hello World\n");
// results in "Hello World\n"
And
echo json_encode('Hello World\n');
// results in "Hello World\\\n"
I agree that Google's Gson
is clear and easy to use. But you should create a result class for getting an instance from JSON string. If you can't clarify the result class, use json-simple
:
// import static org.hamcrest.CoreMatchers.is;
// import static org.junit.Assert.assertThat;
// import org.json.simple.JSONObject;
// import org.json.simple.JSONValue;
// import org.junit.Test;
@Test
public void json2Object() {
// given
String jsonString = "{\"name\" : \"John\",\"age\" : \"20\","
+ "\"address\" : \"some address\","
+ "\"someobject\" : {\"field\" : \"value\"}}";
// when
JSONObject object = (JSONObject) JSONValue.parse(jsonString);
// then
@SuppressWarnings("unchecked")
Set<String> keySet = object.keySet();
for (String key : keySet) {
Object value = object.get(key);
System.out.printf("%s=%s (%s)\n", key, value, value.getClass()
.getSimpleName());
}
assertThat(object.get("age").toString(), is("20"));
}
Pros and cons of Gson
and json-simple
is pretty much like pros and cons of user-defined Java Object and Map
. The object you define is clear for all fields (name and type), but less flexible than Map
.
make position absolute
for that div.
What I like to do is the following (but make sure to read to the end to use the proper type of constants):
internal static class ColumnKeys
{
internal const string Date = "Date";
internal const string Value = "Value";
...
}
Read this to know why const
might not be what you want. Possible type of constants are:
const
fields. Do not use across assemblies (public
or protected
) if value might change in future because the value will be hardcoded at compile-time in those other assemblies. If you change the value, the old value will be used by the other assemblies until they are re-compiled.static readonly
fieldsstatic
property without set
A simple fix that I use to add space in horizontal legends, simply add spaces in the labels (see extract below):
scale_fill_manual(values=c("red","blue","white"),
labels=c("Label of category 1 ",
"Label of category 2 ",
"Label of category 3"))
What you actually have is an Activity (even if it looks like a Dialog), therefore you should call setFinishOnTouchOutside(false)
from your activity if you want to keep it open when the background activity is clicked.
EDIT: This only works with android API level 11 or greater
Agree with the Money pattern: Handling currencies is just too cumbersome when you use decimals.
If you create a Currency-class, you can then put all the logic relating to money there, including a correct ToString()-method, more control of parsing values and better control of divisions.
Also, with a Currency class, there is no chance of unintentionally mixing money up with other data.
To do this for oracle sql, the syntax would be:
,SUBSTR(col,INSTR(col,'-',1,2)+1) AS new_field
for this example, I look for the second '-' and take the substring to the end
+= is an assignment. When you use it you're really saying ‘some_list2= some_list2+['something']’. Assignments involve rebinding, so:
l= []
def a1(x):
l.append(x) # works
def a2(x):
l= l+[x] # assign to l, makes l local
# so attempt to read l for addition gives UnboundLocalError
def a3(x):
l+= [x] # fails for the same reason
The += operator should also normally create a new list object like list+list normally does:
>>> l1= []
>>> l2= l1
>>> l1.append('x')
>>> l1 is l2
True
>>> l1= l1+['x']
>>> l1 is l2
False
However in reality:
>>> l2= l1
>>> l1+= ['x']
>>> l1 is l2
True
This is because Python lists implement __iadd__() to make a += augmented assignment short-circuit and call list.extend() instead. (It's a bit of a strange wart this: it usually does what you meant, but for confusing reasons.)
In general, if you're appending/extended an existing list, and you want to keep the reference to the same list (instead of making a new one), it's best to be explicit and stick with the append()/extend() methods.
with open(filename, 'a') as f:
df.to_csv(f, header=f.tell()==0)
You could try qemu, which is what the Android emulator uses. I believe it actually emulates the ARM hardware.
Here is the tutorial to install GBD.
Usually GNU Debugger might not be in your computer, so you would install it first. The installation steps are basic "configure", "make", and "make install".
Once installed, try which gdb
in terminal, to find the executable path of GDB.
You can always use the
echo "Column1`tColumn2`tColumn3..." >> results.csv
You will need to put "`t" between the columns to separates the variables into their own column. Here is the way I wrote my script:
echo "Host`tState" >> results.csv
$names = Get-Content "hostlist.txt"
foreach ($name in $names) {
$count = 0
$count2 = 13490
if ( Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue ) {
echo "$name`tUp" >> results.csv
}
else {
echo "$name`tDown" >> results.csv
}
$count++
Write-Progress -Activity "Gathering Information" -status "Pinging Hosts..." -percentComplete ($count / $count2 *100)
}
This is the easiest way to me. The output I get is :
Host|State
----------
H1 |Up
H2 |UP
H3 |Down
You can play around with the look, but that's the basic idea. The $count is just a progress bar if you want to spice up the look
a possible solution could be
create a batch file
there do a loop on lib directory for all files inside it and set each file unside lib on classpath
then after that run the jar
source for loop in batch file for info on loops
In case you have only one controller and you want to access every action on root you can skip controller name like this
routes.MapRoute(
"Default",
"{action}/{id}",
new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);