I had the same problem. Docker running but couldn't access it through CLI.
For me the problem was solved by executing "Docker Quickstart Terminal.app". This is located in the "/Applications/Docker/" folder. As long as I work in this instance of the Terminal app Docker works perfectly. If a second window is needed I have to run the "Quickstart" app once more.
I have a Docker for Mac installation. Therefore I am not sure if my solution is valid for a Homebrew installation.
The "Docker Quickstart Terminal" app seems to be essentially some applescripts to launch the terminal app and a bash start script that initialise all the necessary environment variables.
Hope this helps someone else !
There are a couple of ways:
To delete it directly:
SomeModel.objects.filter(id=id).delete()
To delete it from an instance:
instance1 = SomeModel.objects.get(id=id)
instance1.delete()
// don't use same name
(From http://git.or.cz/gitwiki/GitTips#head-9f87cd21bcdf081a61c29985604ff4be35a5e6c0)
How to change commits deeper in history
Since history in Git is immutable, fixing anything but the most recent commit (commit which is not branch head) requires that the history is rewritten from the changed commit and forward.
You can use StGIT for that, initialize branch if necessary, uncommitting up to the commit you want to change, pop to it if necessary, make a change then refresh patch (with -e option if you want to correct commit message), then push everything and stg commit.
Or you can use rebase to do that. Create new temporary branch, rewind it to the commit you want to change using git reset --hard, change that commit (it would be top of current head), then rebase branch on top of changed commit, using git rebase --onto .
Or you can use git rebase --interactive, which allows various modifications like patch re-ordering, collapsing, ...
I think that should answer your question. However, note that if you have pushed code to a remote repository and people have pulled from it, then this is going to mess up their code histories, as well as the work they've done. So do it carefully.
you can add security provider by editing java.security by adding security.provider.=org.bouncycastle.jce.provider.BouncyCastleProvider
or add a line in your top of your class
Security.addProvider(new BouncyCastleProvider());
you can use below line to specify provider while specifying algorithms
Cipher cipher = Cipher.getInstance("AES", "SunJCE");
if you are using other provider like Bouncy Castle then
Cipher cipher = Cipher.getInstance("AES", "BC");
See the announcement for ASP.NET Core 3 Preview 4, which explains that this tool is no longer built-in and requires an explicit install:
The dotnet ef tool is no longer part of the .NET Core SDK
This change allows us to ship
dotnet ef
as a regular .NET CLI tool that can be installed as either a global or local tool. For example, to be able to manage migrations or scaffold aDbContext
, installdotnet ef
as a global tool typing the following command:
dotnet tool install --global dotnet-ef
To install a specific version of the tool, use the following command:
dotnet tool install --global dotnet-ef --version 3.1.4
The reason for the change is explained in the docs:
Why
This change allows us to distribute and update
dotnet ef
as a regular .NET CLI tool on NuGet, consistent with the fact that the EF Core 3.0 is also always distributed as a NuGet package.
In addition, you might need to add the following NuGet packages to your project:
Through switch
case it's impossible.You can go with nested if statements.
if(number>=1 && number<=4){
//Do something
}else if(number>=5 && number<=9){
//Do something
}
For Java, I highly recommend Core Java. It's a large tome (or two large tomes), but I've found it to be one of the best references on Java I've read.
As an complement to Stefan Steiger answer: (as it doesn't look nice as a comment)
Extending String prototype:
String.prototype.b64encode = function() {
return btoa(unescape(encodeURIComponent(this)));
};
String.prototype.b64decode = function() {
return decodeURIComponent(escape(atob(this)));
};
Usage:
var str = "äöüÄÖÜçéèñ";
var encoded = str.b64encode();
console.log( encoded.b64decode() );
NOTE:
As stated in the comments, using unescape
is not recommended as it may be removed in the future:
Warning: Although unescape() is not strictly deprecated (as in "removed from the Web standards"), it is defined in Annex B of the ECMA-262 standard, whose introduction states: … All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification.
Note: Do not use unescape to decode URIs, use decodeURI or decodeURIComponent instead.
For Intellij 14.0.0 the Application server option is available under View > Tools window > Application Server (But if it is enable, i mean if you have any plugin installed)
With HttpWebRequest.GetRequestStream
Code example from http://msdn.microsoft.com/en-us/library/d4cek6cc.aspx
string postData = "firstone=" + inputData;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);
// Set the content type of the data being posted.
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
// Set the content length of the string being posted.
myHttpWebRequest.ContentLength = byte1.Length;
Stream newStream = myHttpWebRequest.GetRequestStream ();
newStream.Write (byte1, 0, byte1.Length);
From one of my own code:
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = this.credentials;
request.Method = method;
request.ContentType = "application/atom+xml;type=entry";
using (Stream requestStream = request.GetRequestStream())
using (var xmlWriter = XmlWriter.Create(requestStream, new XmlWriterSettings() { Indent = true, NewLineHandling = NewLineHandling.Entitize, }))
{
cmisAtomEntry.WriteXml(xmlWriter);
}
try
{
return (HttpWebResponse)request.GetResponse();
}
catch (WebException wex)
{
var httpResponse = wex.Response as HttpWebResponse;
if (httpResponse != null)
{
throw new ApplicationException(string.Format(
"Remote server call {0} {1} resulted in a http error {2} {3}.",
method,
uri,
httpResponse.StatusCode,
httpResponse.StatusDescription), wex);
}
else
{
throw new ApplicationException(string.Format(
"Remote server call {0} {1} resulted in an error.",
method,
uri), wex);
}
}
catch (Exception)
{
throw;
}
Try following code. It is working for me....
UPDATE TableOne
SET
field1 =(SELECT TableTwo.field1 FROM TableTwo WHERE TableOne.id=TableTwo.id),
field2 =(SELECT TableTwo.field2 FROM TableTwo WHERE TableOne.id=TableTwo.id)
WHERE TableOne.id = (SELECT TableTwo.id
FROM TableTwo
WHERE TableOne.id = TableTwo.id)
lPerson = dt.AsEnumerable().Select(s => new Person()
{
Name = s.Field<string>("Name"),
SurName = s.Field<string>("SurName"),
Age = s.Field<int>("Age"),
InsertDate = s.Field<DateTime>("InsertDate")
}).ToList();
Link to working DotNetFiddle Example
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Data.DataSetExtensions;
public static void Main()
{
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("SurName", typeof(string));
dt.Columns.Add("Age", typeof(int));
dt.Columns.Add("InsertDate", typeof(DateTime));
var row1= dt.NewRow();
row1["Name"] = "Adam";
row1["SurName"] = "Adam";
row1["Age"] = 20;
row1["InsertDate"] = new DateTime(2020, 1, 1);
dt.Rows.Add(row1);
var row2 = dt.NewRow();
row2["Name"] = "John";
row2["SurName"] = "Smith";
row2["Age"] = 25;
row2["InsertDate"] = new DateTime(2020, 3, 12);
dt.Rows.Add(row2);
var row3 = dt.NewRow();
row3["Name"] = "Jack";
row3["SurName"] = "Strong";
row3["Age"] = 32;
row3["InsertDate"] = new DateTime(2020, 5, 20);
dt.Rows.Add(row3);
List<Person> lPerson = new List<Person>();
lPerson = dt.AsEnumerable().Select(s => new Person()
{
Name = s.Field<string>("Name"),
SurName = s.Field<string>("SurName"),
Age = s.Field<int>("Age"),
InsertDate = s.Field<DateTime>("InsertDate")
}).ToList();
foreach(Person pers in lPerson)
{
Console.WriteLine("{0} {1} {2} {3}", pers.Name, pers.SurName, pers.Age, pers.InsertDate);
}
}
public class Person
{
public string Name { get; set; }
public string SurName { get; set; }
public int Age { get; set; }
public DateTime InsertDate { get; set; }
}
}
len = max(key for (item, key) in list)
newlist = [[] for i in range(len+1)]
for item,key in list:
newlist[key].append(item)
You can do it in a single list comprehension, perhaps more elegant but O(n**2):
[[item for (item,key) in list if key==i] for i in range(max(key for (item,key) in list)+1)]
Management Studio->Tools->SQL Server Profiler.
If it is not installed see this link
I normally use on
instead of click
. It allow me to add more events listeners to a specific function.
$(document).on("click touchend", ".class1, .class2, .class3", function () {
//do stuff
});
Go to "Run" and execute this:
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir
NOTE: run as administrator.
To remove first Character of string in PHP,
$string = "abcdef";
$new_string = substr($string, 1);
echo $new_string;
Generates: "bcdef"
Phone numbers are hard. For a more robust, international solution, I would recommend this well-maintained PHP port of Google's libphonenumber library.
Using it like this,
use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumber;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberUtil;
$phoneUtil = PhoneNumberUtil::getInstance();
$numberString = "+12123456789";
try {
$numberPrototype = $phoneUtil->parse($numberString, "US");
echo "Input: " . $numberString . "\n";
echo "isValid: " . ($phoneUtil->isValidNumber($numberPrototype) ? "true" : "false") . "\n";
echo "E164: " . $phoneUtil->format($numberPrototype, PhoneNumberFormat::E164) . "\n";
echo "National: " . $phoneUtil->format($numberPrototype, PhoneNumberFormat::NATIONAL) . "\n";
echo "International: " . $phoneUtil->format($numberPrototype, PhoneNumberFormat::INTERNATIONAL) . "\n";
} catch (NumberParseException $e) {
// handle any errors
}
you will get the following output:
Input: +12123456789
isValid: true
E164: +12123456789
National: (212) 345-6789
International: +1 212-345-6789
I'd recommend using the E164
format for duplicate checks. You could also check whether the number is a actually mobile number or not (using PhoneNumberUtil::getNumberType()
), or whether it's even a US number (using PhoneNumberUtil::getRegionCodeForNumber()
).
As a bonus, the library can handle pretty much any input. If you, for instance, choose to run 1-800-JETBLUE
through the code above, you will get
Input: 1-800-JETBLUE
isValid: true
E164: +18005382583
National: (800) 538-2583
International: +1 800-538-2583
Neato.
It works just as nicely for countries other than the US. Just use another ISO country code in the parse()
argument.
For example, a logout button can be written like this:
<button class="btn btn-primary" onclick="location.href={% url 'logout'%}">Logout</button>
Where logout endpoint:
#urls.py:
url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),
It's old but thought I'd add my two cents... Not sure if it will work but try using a KeyValuePair:
List<KeyValuePair<?, ?>> LinkList = new List<KeyValuePair<?, ?>>();
LinkList.Add(new KeyValuePair<?, ?>(Object, Object));
You'll end up with something like this:
LinkList[0] = <Object, Object>
LinkList[1] = <Object, Object>
LinkList[2] = <Object, Object>
and so on...
A local action will run once for each remote host (in parallel). If you want a unique file per host, make sure to put the inventory_hostname as part of the file name.
- local_action: copy content={{ foo_result }} dest=/path/to/destination/{{ inventory_hostname }}file
If you instead want a single file with all host's information, one way is to have a serial task (don't want to append in parallel) and then append to the file with a module (lineinfile is capable, or could pipe with a shell command)
- hosts: web_servers
serial: 1
tasks:
- local_action: lineinfile line={{ foo_result }} path=/path/to/destination/file
Alternatively, you can add a second play/role/task to the playbook which runs against only local host. Then access the variable from each of the hosts where the registration command ran inside a template Access Other Hosts Variables Docs Template Module Docs
$NewTime = mktime(date('G'), date('i'), date('s'), date('n'), date('j') + $DaysToAdd, date('Y'));
From mktime documentation:
mktime() is useful for doing date arithmetic and validation, as it will automatically calculate the correct value for out-of-range input.
The advantage of this method is that you can add or subtract any time interval (hours, minutes, seconds, days, months, or years) in an easy to read line of code.
Beware there is a tradeoff in performance, as this code is about 2.5x slower than strtotime("+1 day") due to all the calls to the date() function. Consider re-using those values if you are in a loop.
datetime.datetime.fromtimestamp()
is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp()
expects Unix timestamp, in seconds.
Do it like that:
>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)
and the result is:
>>> date
datetime.datetime(2012, 3, 16, 1, 0)
Does it answer your question?
EDIT: J.F. Sebastian correctly suggested to use true division by 1e3
(float 1000
). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int
when dividing (using /
operator) int
by int
(this is called floor division). By replacing the divisor 1000
(being an int
) with the 1e3
divisor (being representation of 1000
as float) or with float(1000)
(or 1000.
etc.), the division becomes true division. Python 2.x returns float
when dividing int
by float
, float
by int
, float
by float
etc. And when there is some fractional part in the timestamp passed to fromtimestamp()
method, this method's result also contains information about that fractional part (as the number of microseconds).
--Code for same server
USE [mydb1]
GO
INSERT INTO dbo.mytable1 (
column1
,column2
,column3
,column4
)
SELECT column1
,column2
,column3
,column4
FROM [mydb2].dbo.mytable2 --WHERE any condition
/*
steps-
1- [mydb1] means our opend connection database
2- mytable1 the table in mydb1 database where we want insert record
3- mydb2 another database.
4- mytable2 is database table where u fetch record from it.
*/
--Code for different server
USE [mydb1]
SELECT *
INTO mytable1
FROM OPENDATASOURCE (
'SQLNCLI'
,'Data Source=XXX.XX.XX.XXX;Initial Catalog=mydb2;User ID=XXX;Password=XXXX'
).[mydb2].dbo.mytable2
/* steps -
1- [mydb1] means our opend connection database
2- mytable1 means create copy table in mydb1 database where we want
insert record
3- XXX.XX.XX.XXX - another server name.
4- mydb2 another server database.
5- write User id and Password of another server credential
6- mytable2 is another server table where u fetch record from it. */
The accepted answer is invalid with the double EXEC (only need the first EXEC):
DECLARE @returnvalue int;
EXEC @returnvalue = SP_SomeProc
PRINT @returnvalue
And you still need to call PRINT (at least in Visual Studio).
An other solution:
interface bar {
length: number;
}
bars = [{
length: 1
} as bar];
Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.
Here's how to do it for Internet Explorer:
function copy (str)
{
//for IE ONLY!
window.clipboardData.setData('Text',str);
}
Here is a rough but more declarative solution. I haven't been able to get it down to a single annotation, but this seems to work well. Also not sure about performance on large data sets.
Given this JSON:
{
"list": [
{
"wrapper": {
"name": "Jack"
}
},
{
"wrapper": {
"name": "Jane"
}
}
]
}
And these model objects:
public class RootObject {
@JsonProperty("list")
@JsonDeserialize(contentUsing = SkipWrapperObjectDeserializer.class)
@SkipWrapperObject("wrapper")
public InnerObject[] innerObjects;
}
and
public class InnerObject {
@JsonProperty("name")
public String name;
}
Where the Jackson voodoo is implemented like:
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface SkipWrapperObject {
String value();
}
and
public class SkipWrapperObjectDeserializer extends JsonDeserializer<Object> implements
ContextualDeserializer {
private Class<?> wrappedType;
private String wrapperKey;
public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException {
SkipWrapperObject skipWrapperObject = property
.getAnnotation(SkipWrapperObject.class);
wrapperKey = skipWrapperObject.value();
JavaType collectionType = property.getType();
JavaType collectedType = collectionType.containedType(0);
wrappedType = collectedType.getRawClass();
return this;
}
@Override
public Object deserialize(JsonParser parser, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.readTree(parser);
JsonNode wrapped = objectNode.get(wrapperKey);
Object mapped = mapIntoObject(wrapped);
return mapped;
}
private Object mapIntoObject(JsonNode node) throws IOException,
JsonProcessingException {
JsonParser parser = node.traverse();
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(parser, wrappedType);
}
}
Hope this is useful to someone!
In my case, the file ~/.curlrc had a wrong proxy configured.
I have found this to be the easiest and most efficient way to get JSON from a webpage when using Python 3:
import json,urllib.request
data = urllib.request.urlopen("https://api.github.com/users?since=100").read()
output = json.loads(data)
print (output)
I'm guessing you don't have a jquery form plugin included. ajaxSubmit
isn't a core jquery function, I believe.
Something like this : http://jquery.malsup.com/form/
UPD
<script src="http://malsup.github.com/jquery.form.js"></script>
Got this error in Entity Framework 6 with this code at runtime:
var fileEventsSum = db.ImportInformations.Sum(x => x.FileEvents)
Update from LeandroSoares:
Use this for single execution:
var fileEventsSum = db.ImportInformations.Sum(x => (int?)x.FileEvents) ?? 0
Original:
Changed to this and then it worked:
var fileEventsSum = db.ImportInformations.Any() ? db.ImportInformations.Sum(x => x.FileEvents) : 0;
The accepted answer is wrong. The quote is correct, the assertion that PUT and POST must have it is incorrect. There is no requirement that PUT or POST actually have additional content. Nor is there a prohibition against GET actually having content.
The RFCs say exactly what they mean .. IFF your side (client OR origin server) will be sending additional content, beyond the HTTP headers, it SHOULD specify a Content-Type header. But note it is allowable to omit the Content-Type and still include content (say, by using a Content-Length header).
select method > right click > References > Workspace/Project (your preferred context )
or
(Ctrl+Shift+G)
This will show you a Search view containing the hierarchy of class and method which using this method.
We just released preview driver for Node.JS for SQL Server connectivity. You can find it here: Introducing the Microsoft Driver for Node.JS for SQL Server.
The driver supports callbacks (here, we're connecting to a local SQL Server instance):
// Query with explicit connection
var sql = require('node-sqlserver');
var conn_str = "Driver={SQL Server Native Client 11.0};Server=(local);Database=AdventureWorks2012;Trusted_Connection={Yes}";
sql.open(conn_str, function (err, conn) {
if (err) {
console.log("Error opening the connection!");
return;
}
conn.queryRaw("SELECT TOP 10 FirstName, LastName FROM Person.Person", function (err, results) {
if (err) {
console.log("Error running query!");
return;
}
for (var i = 0; i < results.rows.length; i++) {
console.log("FirstName: " + results.rows[i][0] + " LastName: " + results.rows[i][1]);
}
});
});
Alternatively, you can use events (here, we're connecting to SQL Azure a.k.a Windows Azure SQL Database):
// Query with streaming
var sql = require('node-sqlserver');
var conn_str = "Driver={SQL Server Native Client 11.0};Server={tcp:servername.database.windows.net,1433};UID={username};PWD={Password1};Encrypt={Yes};Database={databasename}";
var stmt = sql.query(conn_str, "SELECT FirstName, LastName FROM Person.Person ORDER BY LastName OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY");
stmt.on('meta', function (meta) { console.log("We've received the metadata"); });
stmt.on('row', function (idx) { console.log("We've started receiving a row"); });
stmt.on('column', function (idx, data, more) { console.log(idx + ":" + data);});
stmt.on('done', function () { console.log("All done!"); });
stmt.on('error', function (err) { console.log("We had an error :-( " + err); });
If you run into any problems, please file an issue on Github: https://github.com/windowsazure/node-sqlserver/issues
First of all, return
is a keyword and exit
is a function.
That said, here's a simplest of explanations.
return
It returns a value from a function.
exit
It exits out of or abandons the current shell.
Take a look at ?legend
and try this:
legend('topright', names(a)[-1] ,
lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)
For Mac Users if command + fn + f12
or command + f12
is not working, then your key map is not selected as "Mac Os X". To select key map follow the below steps.
Android Studio -> Preferences -> Keymap -> From the drop down Select "Mac OS X" -> Click Apply -> OK.
I think that what you have to do is make a thorough check of some properties that will always be in a dom element, but their combination won't most likely be in another object, like so:
var isDom = function (inp) {
return inp && inp.tagName && inp.nodeName && inp.ownerDocument && inp.removeAttribute;
};
Another way to achieve this is as below
=IF(ISERROR(TRIM(MID(TRIM(D14),SEARCH("|",SUBSTITUTE(TRIM(D14)," ","|",LEN(TRIM(D14))-LEN(SUBSTITUTE(TRIM(D14)," ","")))),LEN(TRIM(D14))))),TRIM(D14),TRIM(MID(TRIM(D14),SEARCH("|",SUBSTITUTE(TRIM(D14)," ","|",LEN(TRIM(D14))-LEN(SUBSTITUTE(TRIM(D14)," ","")))),LEN(TRIM(D14)))))
Answer to add multiple markers.
UPDATE (GEOCODE MULTIPLE ADDRESSES)
Here's the working Example Geocoding with multiple addresses.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var delay = 100;
var infowindow = new google.maps.InfoWindow();
var latlng = new google.maps.LatLng(21.0000, 78.0000);
var mapOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var bounds = new google.maps.LatLngBounds();
function geocodeAddress(address, next) {
geocoder.geocode({address:address}, function (results,status)
{
if (status == google.maps.GeocoderStatus.OK) {
var p = results[0].geometry.location;
var lat=p.lat();
var lng=p.lng();
createMarker(address,lat,lng);
}
else {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
nextAddress--;
delay++;
} else {
}
}
next();
}
);
}
function createMarker(add,lat,lng) {
var contentString = add;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map,
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
bounds.extend(marker.position);
}
var locations = [
'New Delhi, India',
'Mumbai, India',
'Bangaluru, Karnataka, India',
'Hyderabad, Ahemdabad, India',
'Gurgaon, Haryana, India',
'Cannaught Place, New Delhi, India',
'Bandra, Mumbai, India',
'Nainital, Uttranchal, India',
'Guwahati, India',
'West Bengal, India',
'Jammu, India',
'Kanyakumari, India',
'Kerala, India',
'Himachal Pradesh, India',
'Shillong, India',
'Chandigarh, India',
'Dwarka, New Delhi, India',
'Pune, India',
'Indore, India',
'Orissa, India',
'Shimla, India',
'Gujarat, India'
];
var nextAddress = 0;
function theNext() {
if (nextAddress < locations.length) {
setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay);
nextAddress++;
} else {
map.fitBounds(bounds);
}
}
theNext();
</script>
As we can resolve this issue with setTimeout()
function.
Still we should not geocode known locations every time you load your page as said by @geocodezip
Another alternatives of these are explained very well in the following links:
How To Avoid GoogleMap Geocode Limit!
For many it's a permission issue, but for me it turns out the error was brought about by a mistake in the form I was trying to submit. To be specific i had accidentally put ">" sign after the value of "action". So I would suggest you take a second look at your code
check if the array is null first so you would avoid a null pointer exception
logic in any language: if array is null or is empty :do ....
Something like this should work:
SELECT *
FROM table_name
WHERE primary_key IN (SELECT primary_key
FROM
(
SELECT primary_key, SYS.DBMS_RANDOM.RANDOM
FROM table_name
ORDER BY 2
)
WHERE rownum <= 10 );
I know it's a very old comment, but still:
Instead of using single bracket (dfTest['A'])
, use double brackets (dfTest[['A']])
.
i.e: min_max_scaler.fit_transform(dfTest[['A']])
.
I believe this will give the desired result.
This answer predates version 1.1.5 where a proper ternary in the $parse
function wasn't available. Use this answer if you're on a lower version, or as an example of filters:
angular.module('myApp.filters', [])
.filter('conditional', function() {
return function(condition, ifTrue, ifFalse) {
return condition ? ifTrue : ifFalse;
};
});
And then use it as
<i ng-class="checked | conditional:'icon-check':'icon-check-empty'"></i>
If they're all local to you, then here's the offset:
SELECT GETDATE() AS CurrentTime, GETUTCDATE() AS UTCTime
and you should be able to update all the data using:
UPDATE SomeTable
SET DateTimeStamp = DATEADD(hh, DATEDIFF(hh, GETDATE(), GETUTCDATE()), DateTimeStamp)
Would that work, or am I missing another angle of this problem?
You'll need a using System.Net.Http
at the top.
You are disabling only on document.ready
and this happens only once when DOM
is ready but you need to disable
in keyup event too when textbox gets empty. Also change $(this).val.length
to $(this).val().length
$(document).ready(function(){
$('.sendButton').attr('disabled',true);
$('#message').keyup(function(){
if($(this).val().length !=0)
$('.sendButton').attr('disabled', false);
else
$('.sendButton').attr('disabled',true);
})
});
Or you can use conditional operator instead of if statement. also use prop instead of attr as attribute is not recommended by jQuery 1.6 and above for disabled, checked etc.
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method, jQuery docs
$(document).ready(function(){
$('.sendButton').prop('disabled',true);
$('#message').keyup(function(){
$('.sendButton').prop('disabled', this.value == "" ? true : false);
})
});
It's an indication that connection pooling is being used (which is a good thing).
I've been happily using pympler for such tasks. It's compatible with many versions of Python -- the asizeof
module in particular goes back to 2.2!
For example, using hughdbrown's example but with from pympler import asizeof
at the start and print asizeof.asizeof(v)
at the end, I see (system Python 2.5 on MacOSX 10.5):
$ python pymp.py
set 120
unicode 32
tuple 32
int 16
decimal 152
float 16
list 40
object 0
dict 144
str 32
Clearly there is some approximation here, but I've found it very useful for footprint analysis and tuning.
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
More information can be found at Google Maps API - LatLng
Wget does not support multiple socket connections in order to speed up download of files.
I think we can do a bit better than gmarian answer.
The correct way is to use aria2
.
aria2c -x 16 -s 16 [url]
# | |
# | |
# | |
# ---------> the number of connections here
InnoDB works slightly different that MyISAM and they both are viable options. You should use what you think it fits the project.
Some keypoints will be:
Notes:
Notes2: - I am reading this book "High performance MySQL", the author says "InnoDB loads data and creates indexes slower than MyISAM", this could also be a very important factor when deciding what to use.
using Array.prototype.reduce():
const arrayOfObjects = [
{ plants: 'men' },
{ smart:'dumb' },
{ peace: 'war' }
]
const sentence = 'plants are smart'
arrayOfObjects.reduce(
(f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence
)
// as a reusable function
const replaceManyStr = (obj, sentence) => obj.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence)
const result = replaceManyStr(arrayOfObjects , sentence1)
Example
// ///////////// 1. replacing using reduce and objects_x000D_
_x000D_
// arrayOfObjects.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence)_x000D_
_x000D_
// replaces the key in object with its value if found in the sentence_x000D_
// doesn't break if words aren't found_x000D_
_x000D_
// Example_x000D_
_x000D_
const arrayOfObjects = [_x000D_
{ plants: 'men' },_x000D_
{ smart:'dumb' },_x000D_
{ peace: 'war' }_x000D_
]_x000D_
const sentence1 = 'plants are smart'_x000D_
const result1 = arrayOfObjects.reduce((f, s) => `${f}`.replace(Object.keys(s)[0], s[Object.keys(s)[0]]), sentence1)_x000D_
_x000D_
console.log(result1)_x000D_
_x000D_
// result1: _x000D_
// men are dumb_x000D_
_x000D_
_x000D_
// Extra: string insertion python style with an array of words and indexes_x000D_
_x000D_
// usage_x000D_
_x000D_
// arrayOfWords.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence)_x000D_
_x000D_
// where arrayOfWords has words you want to insert in sentence_x000D_
_x000D_
// Example_x000D_
_x000D_
// replaces as many words in the sentence as are defined in the arrayOfWords_x000D_
// use python type {0}, {1} etc notation_x000D_
_x000D_
// five to replace_x000D_
const sentence2 = '{0} is {1} and {2} are {3} every {5}'_x000D_
_x000D_
// but four in array? doesn't break_x000D_
const words2 = ['man','dumb','plants','smart']_x000D_
_x000D_
// what happens ?_x000D_
const result2 = words2.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence2)_x000D_
_x000D_
console.log(result2)_x000D_
_x000D_
// result2: _x000D_
// man is dumb and plants are smart every {5}_x000D_
_x000D_
// replaces as many words as are defined in the array_x000D_
// three to replace_x000D_
const sentence3 = '{0} is {1} and {2}'_x000D_
_x000D_
// but five in array_x000D_
const words3 = ['man','dumb','plant','smart']_x000D_
_x000D_
// what happens ? doesn't break_x000D_
const result3 = words3.reduce((f, s, i) => `${f}`.replace(`{${i}}`, s), sentence3)_x000D_
_x000D_
console.log(result3)_x000D_
_x000D_
// result3: _x000D_
// man is dumb and plants
_x000D_
I think the correct access method is using the index:
df_2.loc[:,'D'] = df_2['B']
if you want to do it with pure HTML solution ,you can delete the border in the table if you want...or you can add align="center" attribute to your img tag like this:
<img align="center" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />
see the fiddle : http://jsfiddle.net/Lk2Rh/27/
but still it better to handling this with CSS, i suggest you that.
[class*="test"],[class="second"] {
background: #ffff00;
}
From your config file, it seems like you're only excluding node_modules
from being parsed with babel-loader
, but not from being bundled.
In order to exclude node_modules
and native node libraries from bundling, you need to:
target: 'node'
to your webpack.config.js
. This will exclude native node modules (path, fs, etc.) from being bundled.node_modules
.So your result config file should look like:
var nodeExternals = require('webpack-node-externals');
...
module.exports = {
...
target: 'node', // in order to ignore built-in modules like path, fs, etc.
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
...
};
Improving the solution described here: https://stackoverflow.com/a/52875875/10299604
With after_request
we can handle the CORS response headers avoiding to add extra code to our endpoints:
### CORS section
@app.after_request
def after_request_func(response):
origin = request.headers.get('Origin')
if request.method == 'OPTIONS':
response = make_response()
response.headers.add('Access-Control-Allow-Credentials', 'true')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
response.headers.add('Access-Control-Allow-Headers', 'x-csrf-token')
response.headers.add('Access-Control-Allow-Methods',
'GET, POST, OPTIONS, PUT, PATCH, DELETE')
if origin:
response.headers.add('Access-Control-Allow-Origin', origin)
else:
response.headers.add('Access-Control-Allow-Credentials', 'true')
if origin:
response.headers.add('Access-Control-Allow-Origin', origin)
return response
### end CORS section
fopen()
will open a resource in the same directory as the file executing the command. In other words, if you're just running the file ~/test.php, your script will create ~/myText.txt.
This can get a little confusing if you're using any URL rewriting (such as in an MVC framework) as it will likely create the new file in whatever the directory contains the root index.php file.
Also, you must have correct permissions set and may want to test before writing to the file. The following would help you debug:
$fp = fopen("myText.txt","wb");
if( $fp == false ){
//do debugging or logging here
}else{
fwrite($fp,$content);
fclose($fp);
}
fit()
method mentioned by @Saullo Castro provides maximum likelihood estimates (MLE). The best distribution for your data is the one give you the highest can be determined by several different ways: such as
1, the one that gives you the highest log likelihood.
2, the one that gives you the smallest AIC, BIC or BICc values (see wiki: http://en.wikipedia.org/wiki/Akaike_information_criterion, basically can be viewed as log likelihood adjusted for number of parameters, as distribution with more parameters are expected to fit better)
3, the one that maximize the Bayesian posterior probability. (see wiki: http://en.wikipedia.org/wiki/Posterior_probability)
Of course, if you already have a distribution that should describe you data (based on the theories in your particular field) and want to stick to that, you will skip the step of identifying the best fit distribution.
scipy
does not come with a function to calculate log likelihood (although MLE method is provided), but hard code one is easy: see Is the build-in probability density functions of `scipy.stat.distributions` slower than a user provided one?
It may be nicer one to use slice like :
string.slice(1, -1)
yum update
helped me out. After I had
wget: symbol lookup error: wget: undefined symbol: psl_latest
I agree with @Richard Morgan ... what you are doing should be working, so more information may be needed.
Microsoft has some suggestions on options to protect your Excel 2003 worksheets.
Here is a little more info ...
From help files (Protect Method):
expression.Protect(Password, Structure, Windows)
expression Required. An expression that returns a Workbook object.
Password Optional Variant. A string that specifies a case-sensitive password for the worksheet or workbook. If this argument is omitted, you can unprotect the worksheet or workbook without using a password. Otherwise, you must specify the password to unprotect the worksheet or workbook. If you forget the password, you cannot unprotect the worksheet or workbook. It's a good idea to keep a list of your passwords and their corresponding document names in a safe place.
Structure Optional Variant. True to protect the structure of the workbook (the relative position of the sheets). The default value is False.
Windows Optional Variant. True to protect the workbook windows. If this argument is omitted, the windows aren’t protected.
ActiveWorkbook.Protect Password:="password", Structure:=True, Windows:=True
If you want to work at the worksheet level, I used something similar years ago when I needed to protect/unprotect:
Sub ProtectSheet()
ActiveSheet.Protect "password", True, True
End Sub
Sub UnProtectSheet()
ActiveSheet.Unprotect "password"
End Sub
Sub protectAll()
Dim myCount
Dim i
myCount = Application.Sheets.Count
Sheets(1).Select
For i = 1 To myCount
ActiveSheet.Protect "password", true, true
If i = myCount Then
End
End If
ActiveSheet.Next.Select
Next i
End Sub
string var = "12345678";
var = var[^4..];
// var = "5678"
You can use two different techniques to achieve this.
The first one is with javascript: set the scrollTop property of the scrollable element (e.g. document.body.scrollTop = 1000;
).
The second is setting the link to point to a specific id in the page e.g.
<a href="mypage.html#sectionOne">section one</a>
Then if in your target page you'll have that ID the page will be scrolled automatically.
You could just use the imageView's image cache. It will render the entire view as it is layed out (scaled,bordered with a background etc) to a new bitmap.
just make sure it built.
imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();
there's your bitmap as the screen saw it.
I run into this issue too. I was including bootstrap.js AND bootstrap-modal.js. If you already have bootstrap.js, you don't need to include popover.
we can query the msdb in many ways to get the details.
few are
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%'
You need
.abc,.ab {
display: none;
}
#f:hover ~ .ab {
display: block;
}
#s:hover ~ .abc {
display: block;
}
#s:hover ~ .a,
#f:hover ~ .a{
display: none;
}
Updated demo at http://jsfiddle.net/gaby/n5fzB/2/
The problem in your original CSS was that the ,
in css selectors starts a completely new selector. it is not combined.. so #f:hover ~ .abc,.a
means #f:hover ~ .abc
and .a
. You set that to display:none
so it was always set to be hidden for all .a
elements.
Besides formatting, puts
returns a nonnegative integer if successful or EOF
if unsuccessful; while printf
returns the number of characters printed (not including the trailing null).
In the XML file set the android:checkedButton
field in your RadioGroup
, with the id of your default RadioButton
:
<RadioGroup
....
android:checkedButton="@+id/button_1">
<RadioButton
android:id="@+id/button_1"
...../>
<RadioButton
android:id="@+id/button_2"
...../>
<RadioButton
android:id="@+id/button_3"
...../>
</RadioGroup>
Regarding @Suragch's Alternative to "Remove element of unknown index":
There is a more powerful version of "indexOf(element)" that will match on a predicate instead of the object itself. It goes by the same name but it called by myObjects.indexOf{$0.property = valueToMatch}. It returns the index of the first matching item found in myObjects array.
If the element is an object/struct, you may want to remove that element based on a value of one of its properties. Eg, you have a Car class having car.color property, and you want to remove the "red" car from your carsArray.
if let validIndex = (carsArray.indexOf{$0.color == UIColor.redColor()}) {
carsArray.removeAtIndex(validIndex)
}
Foreseeably, you could rework this to remove "all" red cars by embedding the above if statement within a repeat/while loop, and attaching an else block to set a flag to "break" out of the loop.
var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
print(myInt.runtimeType);
var myDouble = double.parse('123.45');
assert(myInt is double);
print(myDouble); // 123.45
print(myDouble.runtimeType);
I had this problem and I made a tool to export an HTML table to CSV file. The problem I had with FileSaver.js is that this tool grabs the table with html format, this is why some people can't open the file in excel or google. All you have to do is export the js file and then call the function. This is the github url https://github.com/snake404/tableToCSV if someone has the same problem.
Add border-collapse: collapse
into the style
attribute value of the inner table
element. You could alternatively add the attribute cellspacing=0
there, but then you would have a double border between the cells.
I.e.:
<table class="main-story-image" style="float: left; width: 180px; margin: 0 25px 25px 25px; border-collapse: collapse">
You would use an MvcHtmlString
if you want to pass raw HTML to an MVC helper method and you don't want the helper method to encode the HTML.
It seems that you don't have WRITE permission on /tmp
.
Edit the configuration variable session.save_path with the function session_save_path() to 1 directory above public_html
(so external users wouldn't access the info).
In case anyone still hunting the cause of this hateful issue, there comes a solution to nail the causing file. https://www.drupal.org/node/1622904#comment-10768958 from Drupal
community.
And I quote:
Edit
includes/bootstrap.inc:
function drupal_load()
. It is a short function. Find following line:
include_once DRUPAL_ROOT . '/' . $filename;
Temporarily replace it by
ob_start();
include_once DRUPAL_ROOT . '/' . $filename;
$value = ob_get_contents();
ob_end_clean();
if ($value !== '') {
$filename = check_plain($filename);
$value = check_plain($value);
print "File '$filename' produced unforgivable content: '$value'.";
exit;
}
Visual Studio code is great for this - open a folder, right click both files and compare.
I solved it using this package (@mdi/font) and importing it on main.js:
import '@mdi/font/css/materialdesignicons.css'
jQuery("html,body").animate({scrollTop: jQuery("#your-elemm-id-where you want to scroll").offset().top-<some-number>}, 500, 'swing', function() {
alert("Finished animating");
});
Another way is to use the DateTime class, this way you can also specify the timezone. Note: PHP 5.3 or higher.
// For the current date
function isTodayWeekend() {
$currentDate = new DateTime("now", new DateTimeZone("Europe/Amsterdam"));
return $currentDate->format('N') >= 6;
}
If you need to be able to check a certain date string, you can use DateTime::createFromFormat
function isWeekend($date) {
$inputDate = DateTime::createFromFormat("d-m-Y", $date, new DateTimeZone("Europe/Amsterdam"));
return $inputDate->format('N') >= 6;
}
The beauty of this way is that you can specify the timezone without changing the timezone globally in PHP, which might cause side-effects in other scripts (for ex. Wordpress).
The latest release of Requests will build CookieJars for you from simple dictionaries.
import requests
cookies = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}
r = requests.post('http://wikipedia.org', cookies=cookies)
Enjoy :)
I think you want to lowercase the checked value? Try:
var jIsHasKids = $('#chkIsHasKids:checked').val().toLowerCase();
or you want to check it, then get its value as lowercase:
var jIsHasKids = $('#chkIsHasKids').attr("checked", true).val().toLowerCase();
You can also fit a set of a data to whatever function you like using curve_fit
from scipy.optimize
. For example if you want to fit an exponential function (from the documentation):
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b, c):
return a * np.exp(-b * x) + c
x = np.linspace(0,4,50)
y = func(x, 2.5, 1.3, 0.5)
yn = y + 0.2*np.random.normal(size=len(x))
popt, pcov = curve_fit(func, x, yn)
And then if you want to plot, you could do:
plt.figure()
plt.plot(x, yn, 'ko', label="Original Noised Data")
plt.plot(x, func(x, *popt), 'r-', label="Fitted Curve")
plt.legend()
plt.show()
(Note: the *
in front of popt
when you plot will expand out the terms into the a
, b
, and c
that func
is expecting.)
I had same issue using different dependancy what helped me is to set scope to compile.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>compile</scope>
</dependency>
Here is representation of screen eclipse to make hierarachical.
I honestly doubt it, for a number of reasons, but the most important one is that there are some instructions that are allowed in 32-bit mode, but not in 64-bit mode. Specifically, the REX prefix that is used to encode some instructions and registers in 64-bit mode is a byte of the form 0x4f:0x40, but in 32 bit mode the same byte is either INC or DEC with a fixed operand.
Because of this, any 64-bit instruction that is prefixed by REX will be interpreted as either INC or DEC, and won't give the VMM the chance to emulate the 64-bit instruction (for instance by signaling an undefined opcode exception).
The only way it might be done is to use a trap exception to return to the VMM after each and every instruction so that it can see if it needs special 64-bit handling. I simply can't see that happening.
You can use reflection.
Type typeOfMyObject = myObject.GetType();
PropertyInfo[] properties =typeOfMyObject.GetProperties();
Here is the actual VIM code that generates the swap file extensions:
/*
* Change the ".swp" extension to find another file that can be used.
* First decrement the last char: ".swo", ".swn", etc.
* If that still isn't enough decrement the last but one char: ".svz"
* Can happen when editing many "No Name" buffers.
*/
if (fname[n - 1] == 'a') /* ".s?a" */
{
if (fname[n - 2] == 'a') /* ".saa": tried enough, give up */
{
EMSG(_("E326: Too many swap files found"));
vim_free(fname);
fname = NULL;
break;
}
--fname[n - 2]; /* ".svz", ".suz", etc. */
fname[n - 1] = 'z' + 1;
}
--fname[n - 1]; /* ".swo", ".swn", etc. */
This will generate swap files of the format:
[._]*.s[a-v][a-z]
[._]*.sw[a-p]
[._]s[a-v][a-z]
[._]sw[a-p]
Which is pretty much what is included in github's own gitignore file for VIM.
As others have correctly noted, this .gitignore will also ignore .svg image files and .swf adobe flash files.
On Mac/Linux, you'll need to enter the following entry in your ~/.bashrc
:
export PATH="/usr/lib/google-cloud-sdk/bin:$PATH"
fun openAppInPlayStore(appPackageName: String) {
try {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$appPackageName")))
} catch (exception: android.content.ActivityNotFoundException) {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$appPackageName")))
}
}
Since you are using $.ajax
, and not $.getJSON
, your return type is plain text. you need to now convert data
into a JSON object.
you can either do this by changing your $.ajax
to $.getJSON
(which is a shorthand for $.ajax
, only preconfigured to fetch json).
Or you can parse the data
string into JSON after you receive it, like so:
success: function (data) {
var obj = $.parseJSON(data);
console.log(obj);
},
Since both projects are under the same solution, there's a simpler way for the include files and linker as described in https://docs.microsoft.com/en-us/cpp/build/adding-references-in-visual-cpp-projects?view=vs-2019 :
#include "../libProject/libHeader.h"
).You lookup the value of the data with findData()
and then use setCurrentIndex()
QComboBox* combo = new QComboBox;
combo->addItem("100",100.0); // 2nd parameter can be any Qt type
combo->addItem .....
float value=100.0;
int index = combo->findData(value);
if ( index != -1 ) { // -1 for not found
combo->setCurrentIndex(index);
}
Maybe i'm a little too late, but can't we check like this:
@IBAction func Button(sender: AnyObject) {
if textField1.text.utf16Count == 0 || textField2.text.utf16Count == 0 {
}
}
koding.com has a free VM running Ubuntu. The specs are pretty good, 1 gig memory for example. They have a terminal online you can access through their website, or use SSH. The VM will go to sleep approximately 20 minutes after you log out. The reason is to discourage users from running live production code on the VM. The VM resides behind a proxy. Running web servers that only speak HTTP (port 80) should work just fine, but I think you'll get into a lot of trouble whenever you want to work directly with other ports. Many mind-like alternatives offer similar setups. Good luck!
I had the same idea as you but given all restrictions everybody keep imposing everywhere I feel that I must go out and pay for a VPS.
Thanks all who attempted to help.
For me this script was helpful. It process only flat JSON and don't take care of types, but automate some routine
String str =
"{"
+ "'title': 'Computing and Information systems',"
+ "'id' : 1,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Level one CIS',"
+ "'id' : 2,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Intro To Computing and Internet',"
+ "'id' : 3,"
+ "'children': 'false',"
+ "'groups':[]"
+ "}]"
+ "}]"
+ "}";
JSONObject json = new JSONObject(str);
Iterator<String> iterator = json.keys();
System.out.println("Fields:");
while (iterator.hasNext() ){
System.out.println(String.format("public String %s;", iterator.next()));
}
System.out.println("public void Parse (String str){");
System.out.println("JSONObject json = new JSONObject(str);");
iterator = json.keys();
while (iterator.hasNext() ){
String key = iterator.next();
System.out.println(String.format("this.%s = json.getString(\"%s\");",key,key ));
System.out.println("}");
user.dir
is the "User working directory" according to the Java Tutorial, System Properties
int? is the same thing as Nullable. It allows you to have "null" values in your int.
I did this in visual studios and it worked perfectly; comparing arrays index by index with short this code.
private void compareButton_Click(object sender, EventArgs e)
{
int[] answer = { 1, 3, 4, 6, 8, 9, 5, 4, 0, 6 };
int[] exam = { 1, 2, 3, 6, 8, 9, 5, 4, 0, 7 };
int correctAnswers = 0;
int wrongAnswers = 0;
for (int index = 0; index < answer.Length; index++)
{
if (answer[index] == exam[index])
{
correctAnswers += 1;
}
else
{
wrongAnswers += 1;
}
}
outputLabel.Text = ("The matching numbers are " + correctAnswers +
"\n" + "The non matching numbers are " + wrongAnswers);
}
the output will be; The matching numbers are 7 The non matching numbers are 3
Either
Or as a last resort,
_
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Edit - i would avoid setting flags as it will interfere with normal flow of event and history stack.
'make' is a command for UNIX/Linux. Instead of it, use 'nmake' command in MS Windows. Or you'd better use an emulator like CYGWIN.
Agreed. The basic philosophy of REST is to use the web infrastructure. The HTTP Status codes are the messaging framework that allows parties to communicate with each other without increasing the HTTP payload. They are already established universal codes conveying the status of response, and therefore, to be truly RESTful, the applications must use this framework to communicate the response status.
Sending an error response in a HTTP 200 envelope is misleading, and forces the client (api consumer) to parse the message, most likely in a non-standard, or proprietary way. This is also not efficient - you will force your clients to parse the HTTP payload every single time to understand the "real" response status. This increases processing, adds latency, and creates an environment for the client to make mistakes.
The above solutions did not work for me, but this code from Select2's own website did:
$('select').val('US'); // Select the option with a value of 'US'
$('select').trigger('change'); // Notify any JS components that the value changed
Hope this helps for anyone who is struggling, like I was.
In swift 3 use:
let url = URL(string: "Whatever url you have(eg: https://google.com)")
sudo apt-get install libz-dev
in ubuntu.
It's better to use $(window).scroll()
rather than $('#Eframe').on("mousewheel")
$('#Eframe').on("mousewheel")
will not trigger if people manually scroll using up and down arrows on the scroll bar or grabbing and dragging the scroll bar itself.
$(window).scroll(function(){
var scrollPos = $(document).scrollTop();
console.log(scrollPos);
});
If #Eframe
is an element with overflow:scroll
on it and you want it's scroll position. I think this should work (I haven't tested it though).
$('#Eframe').scroll(function(){
var scrollPos = $('#Eframe').scrollTop();
console.log(scrollPos);
});
I´d say MoDisco is by far the most powerful one (though probably not the easiest one to work with).
MoDisco is a generic reverse engineering framework (so that you can customize your reverse engineering project, with MoDisco you can even reverse engineer the behaviour of the java methods, not only the structure and signatures) but also includes some predefined features like the generation of class diagrams out of Java code that you need.
Try this.
1.write a custom filter
package com.dtd.util;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CORSFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
httpResponse.addHeader("Access-Control-Allow-Origin", "*");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
2.add to web.xml
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>com.dtd.util.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
For a virtual function you need to provide implementation in the base class. However derived class can override this implementation with its own implementation. Normally , for pure virtual functions implementation is not provided. You can make a function pure virtual with =0
at the end of function declaration. Also, a class containing a pure virtual function is abstract i.e. you can not create a object of this class.
Truth be told there are many, many resources explaining how to do this already out on the web:
Git: how to reverse-merge a commit?
Git: how to reverse-merge a commit?
Undoing Merges, from Git's blog (retrieved from archive.org's Wayback Machine)
So I guess I'll just summarize some of these:
git revert <merge commit hash>
This creates an extra "revert" commit saying you undid a merge
git reset --hard <commit hash *before* the merge>
This reset history to before you did the merge. If you have commits after the merge you will need to cherry-pick
them on to afterwards.
But honestly this guide here is better than anything I can explain, with diagrams! :)
This worked for me for Eclipse-Luna:
Great answers!
One thing that I would like to clarify deeper is nonatomic
/atomic
.
The user should understand that this property - "atomicity" spreads only on the attribute's reference and not on it's contents.
I.e. atomic
will guarantee the user atomicity for reading/setting the pointer and only the pointer to the attribute.
For example:
@interface MyClass: NSObject
@property (atomic, strong) NSDictionary *dict;
...
In this case it is guaranteed that the pointer to the dict
will be read/set in the atomic manner by different threads.
BUT the dict
itself (the dictionary dict
pointing to) is still thread unsafe, i.e. all read/add operations to the dictionary are still thread unsafe.
If you need thread safe collection you either have bad architecture (more often) OR real requirement (more rare). If it is "real requirement" - you should either find good&tested thread safe collection component OR be prepared for trials and tribulations writing your own one. It latter case look at "lock-free", "wait-free" paradigms. Looks like rocket-science at a first glance, but could help you achieving fantastic performance in comparison to "usual locking".
This happened when i downloaded fabric.io on Eclipse Mars but Restarting computer solved this problem for me.
My solution, it´s make with jquery-chosen and bootstrap, the id is for jquery chosen, tested and working, I had problems concatenating @foreach but now work with a double @foreach and double @if:
<div class="form-group">
<label for="tagLabel">Tags: </label>
<select multiple class="chosen-tag" id="tagLabel" name="tag_id[]" required>
@foreach($tags as $id => $name)
@if (is_array(Request::old('tag_id')))
<option value="{{ $id }}"
@foreach (Request::old('tag_id') as $idold)
@if($idold==$id)
selected
@endif
@endforeach
style="padding:5px;">{{ $name }}</option>
@else
<option value="{{ $id }}" style="padding:5px;">{{ $name }}</option>
@endif
@endforeach
</select>
</div>
this is the code por jquery chosen (the blade.php code doesn´t need this code to work)
$(".chosen-tag").chosen({
placeholder_text_multiple: "Selecciona alguna etiqueta",
no_results_text: "No hay resultados para la busqueda",
search_contains: true,
width: '500px'
});
You may use this in shell:
wget -r --no-parent http://abc.tamu.edu/projects/tzivi/repository/revisions/2/raw/tzivi/
The Parameters are:
-r //recursive Download
and
--no-parent // Don´t download something from the parent directory
If you don't want to download the entire content, you may use:
-l1 just download the directory (tzivi in your case)
-l2 download the directory and all level 1 subfolders ('tzivi/something' but not 'tivizi/somthing/foo')
And so on. If you insert no -l
option, wget
will use -l 5
automatically.
If you insert a -l 0
you´ll download the whole Internet, because wget
will follow every link it finds.
To expand on Yuchen's answer, you can include files and paths as a link. This is not the same thing as adding the existing items because it doesn't make an extra copy in your project's folder structure. It is useful if you want one canonical folder / file etc to be used in a lot of different places but you only want to maintain one version/copy of it.
Here is an example of what you can add to a *.csproj
file to create the link
<Compile Include="$(Codez)\z.Libraries\Common\Strings\RegexExtensions.cs">
<Link>Helpers\RegexExtensions.cs</Link>
</Compile>
<Compile Include="..\..\z.Libraries\MoreLINQ\MoreLinq\ExceptBy.cs">
<Link>Helpers\ExceptBy.cs</Link>
</Compile>
<Content Include="C:\Codez\Libs\Folder\OtherFolder\**\*.*">
<Link>%(RecursiveDir)%(Filename)%(Extension)</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
$(Codez)
is a Windows Environment variable I defined, you can use the built-in Environment variables in the same manner.
The last example group is a bunch of content files I need in the final output. See https://stackoverflow.com/a/11808911/492 and other answers & links there for more on that.
More MSBuild info at https://msdn.microsoft.com/en-us/library/bb629388.aspx
This may also be useful: {{ form.field.as_hidden }}
SELECT
*
FROM
[SERVER2NAME].[THEDB].[THEOWNER].[THETABLE]
You can also look at using Linked Servers. Linked servers can be other types of data sources too such as DB2 platforms. This is one method for trying to access DB2 from a SQL Server TSQL or Sproc call...
Getting fresh set of binaries from Source control helped.
Thanks
As of this writing, it was necessary to:
Given a regular expression of (foobar)
you can reference the first group using $1
and so on if you have more groups in the replace input field.
Like others have mentioned, I think of roles as containers for more granular permissions.
Although I found the Hierarchy Role implementation to be lacking fine control of these granular permission.
So I created a library to manage the relationships and inject the permissions as granted authorities in the security context.
I may have a set of permissions in the app, something like CREATE, READ, UPDATE, DELETE, that are then associated with the user's Role.
Or more specific permissions like READ_POST, READ_PUBLISHED_POST, CREATE_POST, PUBLISH_POST
These permissions are relatively static, but the relationship of roles to them may be dynamic.
Example -
@Autowired
RolePermissionsRepository repository;
public void setup(){
String roleName = "ROLE_ADMIN";
List<String> permissions = new ArrayList<String>();
permissions.add("CREATE");
permissions.add("READ");
permissions.add("UPDATE");
permissions.add("DELETE");
repository.save(new RolePermissions(roleName, permissions));
}
You may create APIs to manage the relationship of these permissions to a role.
I don't want to copy/paste another answer, so here's the link to a more complete explanation on SO.
https://stackoverflow.com/a/60251931/1308685
To re-use my implementation, I created a repo. Please feel free to contribute!
https://github.com/savantly-net/spring-role-permissions
Inside Eclipse I've used the Clay plugin (ex Clay-Azurri). The free version allows to introspect ("reverse engineer") an existing DB schema (via JDBC) and make a diagram of some selected tables.
This is the classroom problem called 'Longest sequence finder'. I have given some simple code that worked for me, also my inputs are lists of a sequence which can also be a string:
def longest_substring(list1,list2):
both=[]
if len(list1)>len(list2):
small=list2
big=list1
else:
small=list1
big=list2
removes=0
stop=0
for i in small:
for j in big:
if i!=j:
removes+=1
if stop==1:
break
elif i==j:
both.append(i)
for q in range(removes+1):
big.pop(0)
stop=1
break
removes=0
return both
Thank you so much for this. I have modified it to work with Windows. I have also put a low timeout so, the IP's that have no return will not sit and wait for 5 seconds each. This is from hochl source code.
import subprocess
import os
with open(os.devnull, "wb") as limbo:
for n in xrange(200, 240):
ip="10.2.7.{0}".format(n)
result=subprocess.Popen(["ping", "-n", "1", "-w", "200", ip],
stdout=limbo, stderr=limbo).wait()
if result:
print ip, "inactive"
else:
print ip, "active"
Just change the ip= for your scheme and the xrange for the hosts.
The primary flag seems to only work for vagrant ssh
for me.
In the past I have used the following method to hack around the issue.
# stage box intended for configuration closely matching production if ARGV[1] == 'stage' config.vm.define "stage" do |stage| box_setup stage, \ "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml" end end
You can edit the hosts file on windows or linux Windows : C:\Windows\System32\Drivers\etc\hosts Linux : /etc/hosts
localhost name resolution is handled within DNS itself.
127.0.0.1 mywebsite.com
after you finish your tests you just comment the line you add to disable it
127.0.0.1 mywebsite.com
Open the svg using Inkscape.
Inkscape is a svg editor it is a bit like Illustrator but as it is built specifically for svg it handles it way better. It is a free software and it's available @ https://inkscape.org/en/
done
all rect/circle have been converted to path
All you have to do is use the runas
command to run your program as Administrator (with a caveat).
runas /user:Administrator "cmdName parameters"
In my case, this was
runas /user:Administator "cmd.exe /C %CD%\installer.cmd %CD%"
Note that you must use Quotation marks, else the runas command will gobble up the switch option to cmd.
Also note that the administrative shell (cmd.exe) starts up in the C:\Windows\System32 folder. This isn't what I wanted, but it was easy enough to pass in the current path to my installer, and to reference it using an absolute path.
Using runas this way requires the administrative account to be enabled, which is not the default on Windows 7 or Vista. However, here is a great tutorial on how to enable it, in three different ways:
I myself enabled it by opening Administrative Tools, Local Security Policy, then navigating to Local Policies\Security Options and changing the value of the Accounts: Administrative Account Status policy to Enabled, which is none of the three ways shown in the link.
An even easier way:
C:> net user Administrator /active:yes
You have to use implicitly unwrapped optionals so that Swift can cope with circular dependencies (parent <-> child of the UI components in this case) during the initialization phase.
@IBOutlet var imgBook: UIImageView!
@IBOutlet var titleBook: UILabel!
@IBOutlet var pageBook: UILabel!
Read this doc, they explain it all nicely.
This approach is without using
max()
function
a = [1,2,3,4,6,7,99,88,999]
max_num = 0
for i in a:
if i > max_num:
max_num = i
print(max_num)
Also if you want to find the index of the resulting max,
print(a.index(max_num))
Direct approach by using function max()
max() function returns the item with the highest value, or the item with the highest value in an iterable
Example: when you have to find max on integers/numbers
a = (1, 5, 3, 9)
print(max(a))
>> 9
Example: when you have string
x = max("Mike", "John", "Vicky")
print(x)
>> Vicky
It basically returns the name with the highest value, ordered alphabetically.
To check whether postfix is running or not
sudo postfix status
If it is not running, start it.
sudo postfix start
Then telnet to localhost port 25 to test the email id
ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix
Hi,
Are you there?
regards,
Admin
.
Do not forget the . at the end, which indicates end of line
{JAVA_1_4_HOME}/bin/javacyou can try also...
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
<showDeprecation>true</showDeprecation>
<showWarnings>true</showWarnings>
<executable>{JAVA_HOME_1_7}/bin/javac</executable>
<fork>true</fork>
</configuration>
</plugin>
It is printing the statement twice because it is printing it for both the parent and the child. The parent has a parent id of 0
Try something like this:
pid_t pid;
pid = fork();
if (pid == 0)
printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(),getppid());
else
printf("This is the parent process. My pid is %d and my parent's id is %d.\n", getpid(), getppid() );
I had the same problem using special characters as delimiters on JSP. When the special characters got posted to the servlet, they all got messed up. I solved the issue by using the following conversion:
String str = new String (request.getParameter("string").getBytes ("iso-8859-1"), "UTF-8");
You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.
<resource-ref>
introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.
So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB
name. The container finds that web.xml has a <resource-ref>
element for jdbc/primaryDB
, so it will look into the container-specific configuration, that contains something similar to the following:
<resource-ref>
<res-ref-name>jdbc/primaryDB</res-ref-name>
<jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>
Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer
.
The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.
I had the same issue and couldn't get my Nexus 6P to show up as an available device until I changed the connection type from "Charging" to "Photo Transfer(PTP)" and installed the Google USB driver while in PTP mode. Installing the driver prior to that while in Charging mode yielded no results.
Another reason you may see this error that I haven't seen posted yet, especially if you are using Jenkins, is that your certificate's private key needs "Allow all applications to access this item" selected.
Enable in php 7 try below command
sudo apt-get install php7.0-curl
As for me this problem occurs because i installed Material Library for IOS. to solve this issue
1: Go to Build Settings of your target app.
2: Search for Other linker flags
3: Open the other linker flags and check for the library which is mention in the error.
4: remove that flag.
5: Clean and build.
I hope this fix your issue.
Use setText(str)
method of JLabel
to dynamically change text displayed. In actionPerform of button write this:
jLabel.setText("new Value");
A simple demo code will be:
JFrame frame = new JFrame("Demo");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(250,100);
final JLabel label = new JLabel("flag");
JButton button = new JButton("Change flag");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
label.setText("new value");
}
});
frame.add(label, BorderLayout.NORTH);
frame.add(button, BorderLayout.CENTER);
frame.setVisible(true);
you can use WeakMaps for implementing private property in ES6 class and benefits of String propeties and methods in JavaScript language like below:
const _items = new WeakMap();
class Stack {
constructor() {
_items.set(this, []);
}
push(obj) {
_items.get(this).push(obj);
}
pop() {
const L = _items.get(this).length;
if(L===0)
throw new Error('Stack is empty');
return _items.get(this).pop();
}
peek() {
const items = _items.get(this);
if(items.length === 0)
throw new Error ('Stack is empty');
return items[items.length-1];
}
get count() {
return _items.get(this).length;
}
}
const stack = new Stack();
//now in console:
//stack.push('a')
//stack.push(1)
//stack.count => 2
//stack.peek() => 1
//stack.pop() => 1
//stack.pop() => "a"
//stack.count => 0
//stack.pop() => Error Stack is empty
For those with Spring Boot you have to add the module to your context and it will be added to your configuration like this.
@Bean
public Module jodaTimeModule() {
return new JodaModule();
}
And if you want to use the new java8 time module jsr-310.
@Bean
public Module jodaTimeModule() {
return new JavaTimeModule();
}
Be aware that changing locale is process-wide and not thread safe (iow., can have side effects or can affect other code executed within the same process).
My proposition: check out the Babel package. Some means of integrating with Django templates are available.
Arrays
in Java have a defined size, you cannot change it later by adding or removing elements (you can read some basics here).
Instead, use a List
:
ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.
Of course, if you know beforehand how many strings you are going to put in your array, you can create an array of that size and set the elements by using the correct position:
String[] myarray = new String[numberofstrings];
myarray[23] = string24; //this sets the 24'th (first index is 0) element to string24.
You can set its startup type to manual in services.msc. This way it will not start automatically unless required. Simply get the name of the service from services.msc as shown here:
You can create batch files to start and stop the service fairly easily as well. Now use this name in batch files.
Your start.bat:
net start "mysql"
And in your stop.bat:
net stop "mysql"
You can find the latest features of the .NET Framework 4.5 beta here
It breaks down the changes to the framework in the following categories:
You sound like you are more interested in the Web section as this shows the changes to ASP.NET 4.5. The rest of the changes can be found under the other headings.
You can also see some of the features that were new when the .NET Framework 4.0 was shipped here.
I ran into this problem after a complete removal and then fresh install of MySQL. Specifically:
Library not loaded: /usr/local/opt/mysql/lib/libmysqlclient.20.dylib
I had not even touched my Rails app.
Reinstalling the mysql2
gem solved this problem.
$ gem uninstall mysql2
$ gem install mysql2 -v 0.3.18 # (specifying the version found in my Gemfile.lock)
[MySQL 5.7.10, Rails 4.0.0, Ruby 2.0.0, Mac OS X Yosemite 10.10]
Open app.config on client side and add maxBufferSize and maxReceivedMessageSize attributes if it is not available
Original
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Service1Soap"/>
</basicHttpBinding>
</bindings>
After Edit/Update
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Service1Soap" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"/>
</basicHttpBinding>
</bindings>
Here is simple way to handle the above.
In Html Template we put Post
<form action="/useradd/addnewroute/" method="post" id="login-form">{% csrf_token %}
<!-- add details of form here-->
<form>
<form action="/useradd/addarea/" method="post" id="login-form">{% csrf_token %}
<!-- add details of form here-->
<form>
In View
def addnewroute(request):
if request.method == "POST":
# do something
def addarea(request):
if request.method == "POST":
# do something
In URL Give needed info like
urlpatterns = patterns('',
url(r'^addnewroute/$', views.addnewroute, name='addnewroute'),
url(r'^addarea/', include('usermodules.urls')),
Jesse Beder's solution is likely the best, but if you don't like the names typeid gives you (I think gcc gives you mangled names for instance), you can do something like:
template<typename T>
struct TypeParseTraits;
#define REGISTER_PARSE_TYPE(X) template <> struct TypeParseTraits<X> \
{ static const char* name; } ; const char* TypeParseTraits<X>::name = #X
REGISTER_PARSE_TYPE(int);
REGISTER_PARSE_TYPE(double);
REGISTER_PARSE_TYPE(FooClass);
// etc...
And then use it like
throw ParseError(TypeParseTraits<T>::name);
EDIT:
You could also combine the two, change name
to be a function that by default calls typeid(T).name()
and then only specialize for those cases where that's not acceptable.
First check the value of session.save_path
using ini_get('session.save_path')
or phpinfo()
. If that is non-empty, then it will show where the session files are saved. In many scenarios it is empty by default, in which case read on:
On Ubuntu or Debian machines, if session.save_path
is not set, then session files are saved in /var/lib/php5
.
On RHEL and CentOS systems, if session.save_path
is not set, session files will be saved in /var/lib/php/session
I think that if you compile PHP from source, then when session.save_path
is not set, session files will be saved in /tmp
(I have not tested this myself though).
I prefer to not set the error_reporting
inside my code. But in one case, a legacy product, there are so many notices, that they must be hidden.
So I used following snippet to set the serverside configured value for error_reporting
but subtract the E_NOTICE
s.
error_reporting(error_reporting() & ~E_NOTICE);
Now the error reporting setting can further be configured in php.ini
or .htaccess
. Only notices will always be disabled.
How can I declare a class type, so that I ensure the object is a constructor of a general class?
A Constructor type could be defined as:
type AConstructorTypeOf<T> = new (...args:any[]) => T;
class A { ... }
function factory(Ctor: AConstructorTypeOf<A>){
return new Ctor();
}
const aInstance = factory(A);
I believe using --no-index
is what you're looking for:
git diff [<options>] --no-index [--] <path> <path>
as mentioned in the git manual:
This form is to compare the given two paths on the filesystem. You can omit the
--no-index
option when running the command in a working tree controlled by Git and at least one of the paths points outside the working tree, or when running the command outside a working tree controlled by Git.
One option is to work with profiles. Create a file called application-test.yml, move all properties you need for those tests to that file and then add the @ActiveProfiles
annotation to your test class:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest
@ActiveProfiles("test") // Like this
public class MyIntTest{
}
Be aware, it will additionally load the application-test.yml, so all properties that are in application.yml are still going to be applied as well. If you don't want that, either use a profile for those as well, or override them in your application-test.yml.
Of course. The whole idea of abstract classes is that they can contain some behaviour or data which you require all sub-classes to contain. Think of the simple example of WheeledVehicle - it should have a numWheels member variable. You want all sub classes to have this variable. Remember that abstract classes are a very useful feature when developing APIs, as they can ensure that people who extend your API won't break it.
You could always just use gcc via cygwin.
You can write like this:
span{
margin-left:10px;
}
span:first-child{
margin-left:0;
}
Since I don't find a simple answer just adding more this will be JSP page. save this content to a jsp file once you run you can see the values of the selected displayed.
Update: save the file as test.jsp and run it on any web/app server
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<%@ page import="java.lang.*" %>
<%@ page import="java.io.*" %>
<% String[] a = request.getParameterValues("multiple");
if(a!=null)
{
for(int i=0;i<a.length;i++){
//out.println(Integer.parseInt(a[i])); //If integer
out.println(a[i]);
}}
%>
<html>
<body>
<form action="test.jsp" method="get">
<select name="multiple" multiple="multiple"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>
<input type="submit">
</form>
</body>
</html>
You partial looks much like an editor template so you could include it as such (assuming of course that your partial is placed in the ~/views/controllername/EditorTemplates
subfolder):
@Html.EditorFor(model => model.SomePropertyOfTypeLocaleBaseModel)
Or if this is not the case simply:
@Html.Partial("nameOfPartial", Model)
You have to decompose the full object to reach the entry
array.
Assuming REPONSE_JSON_OBJECT
is already a parsed JSONObject
.
REPONSE_JSON_OBJECT.getJSONObject("result")
.getJSONObject("map")
.getJSONArray("entry");
This is what I have done in order to get the column "first_name" fill the space when all the columns cannot do it.
When the grid go to small the column "first_name" gets almost invisible (very thin) so I can set the DataGridViewAutoSizeColumnMode to AllCells as the others visible columns. For performance issues it´s important to set them to None before data binding it and set back to AllCell in the DataBindingComplete event handler of the grid. Hope it helps!
private void dataGridView1_Resize(object sender, EventArgs e)
{
int ColumnsWidth = 0;
foreach(DataGridViewColumn col in dataGridView1.Columns)
{
if (col.Visible) ColumnsWidth += col.Width;
}
if (ColumnsWidth <dataGridView1.Width)
{
dataGridView1.Columns["first_name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
else if (dataGridView1.Columns["first_name"].Width < 10) dataGridView1.Columns["first_name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}
In script is usefull something like this:
if [ ! -d /etc/nginx ]; then ln -s /usr/local/nginx/conf/ /etc/nginx > /dev/null 2>&1; fi
it prevents before re-create "bad" looped symlink after re-run script
revalidate()
just request to layout the container, when you experienced simply call revalidate()
works, it could be caused by the updating of child components bounds triggers the repaint()
when their bounds are changed during the re-layout. In the case you mentioned, only component removed and no component bounds are changed, this case no repaint()
is "accidentally" triggered.
As simple as:
your_map.begin()->first // key
your_map.begin()->second // value
In my case (using XCode 10.0) nothing worked but this:
File > Project Settings... > Shared Project Settings: > Build System --> Selected "Legacy Build System" instead of the default "New Build System (Default)".
You can use the bindParam
or bindValue
methods to help prepare your statement.
It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name));
Especially if you are binding multiple values/variables.
Check the clear, easy to read example below:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
If you are expecting multiple rows remove the LIMIT 1
and change the fetch method into fetchAll
:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetchAll(PDO::FETCH_ASSOC);
//$check will now hold an array of returned rows.
//let's say we need the second result, i.e. index of 1
$row_id = $check[1]['id'];
// do something
}
Since nobody has mentioned it, I'd like to add that Facebook chat is written in Erlang.
The thing is that decimal numbers defaults to double. And since double doesn't fit into float you have to tell explicitely you intentionally define a float. So go with:
float b = 3.6f;
You need an appropriate permission in manifest.xml
:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
out.flush()
check the out
is not null..
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/PhysicsSketchpad";
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "sketchpad" + pad.t_id + ".png");
FileOutputStream fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
try something like this
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("select folder");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
We have an application that allows the user to set "parameters" in the page. What we do is set those params on the URL, using React Router (in conjunction with History) and a library that URI-encodes JavaScript objects into a format that can be used as your query string.
When the user selects an option, we can push the value of that onto the current route with:
history.push({pathname: 'path/', search: '?' + Qs.stringify(params)});
pathname
can be the current path. In your case params
would look something like:
{
selectedOption: 5
}
Then at the top level of the React tree, React Router will update the props
of that component with a prop of location.search
which is the encoded value we set earlier, so there will be something in componentWillReceiveProps
like:
params = Qs.parse(nextProps.location.search.substring(1));
this.setState({selectedOption: params.selectedOption});
Then that component and its children will re-render with the updated setting. As the information is on the URL it can be bookmarked (or emailed around - this was our use case) and a refresh will leave the app in the same state. This has been working really well for our application.
React Router: https://github.com/reactjs/react-router
History: https://github.com/ReactTraining/history
The query string library: https://github.com/ljharb/qs
var url = "http://www.example.com";
window.open(url, '_blank');
with(dfr[dfr$var3 < 155,], plot(var1, var2))
should do the trick.
Edit regarding multiple conditions:
with(dfr[(dfr$var3 < 155) & (dfr$var4 > 27),], plot(var1, var2))
For this you can use CSS3 background-size
property. Write like this:
#div2{
background-image:url(http://s7.static.hootsuite.com/3-0-48/images/themes/classic/streams/message-gradient.png);
-moz-background-size:100% 100%;
-webkit-background-size:100% 100%;
background-size:100% 100%;
height:180px;
width:200px;
border: 1px solid red;
}
Check this: http://jsfiddle.net/qdzaw/1/
The ECMAscript standard does not specify which sort algorithm is to be used. Indeed, different browsers feature different sort algorithms. For example, Mozilla/Firefox's sort() is not stable (in the sorting sense of the word) when sorting a map. IE's sort() is stable.
Try to browse the service in the browser and in the Https mode, if it is not brow-sable then it proves the reason for this error. Now, to solve this error you need to check :
try
$request->request->get('acme_demobundle_usertype')['username']
inspect attribute name of your formular field
And to add to this answer, make sure the image itself has a transparent background.
Update the file oracle/jdbc/defaultConnectionProperties.properties in whatever version of the library (i.e. inside your jar) you are using to contain the line below:
oracle.jdbc.timezoneAsRegion=false
In Visual Studio 2010 right click your project name. Hit "View Windows Settings", this generates and opens a file called "app.manifest". Within this file replace "asInvoker" with "requireAdministrator" as explained in the commented sections within the file.
Add "name" attribute and keep the name same for all the radio buttons in a form.
i.e.,
<input type="radio" name="test" value="value1"> Value 1
<input type="radio" name="test" value="value2"> Value 2
<input type="radio" name="test" value="value3"> Value 3
Hope that would help.
You can wrap it in your own function:
function isNullAndUndef(variable) {
return (variable !== null && variable !== undefined);
}
More universal way is to set search_path (should work in PostgreSQL 7.x and above):
SET search_path TO myschema;
Note that set schema myschema
is an alias to above command that is not available in 8.x.
See also: http://www.postgresql.org/docs/9.3/static/ddl-schemas.html
Rails' ActiveSupport adds underscore to the String using the following:
class String
def underscore
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end
Then you can do fun stuff:
"CamelCase".underscore
=> "camel_case"
Consider changing your markup to this:
<span id="someId">onlineff</span>
Then you can use this script:
var x = document.getElementById('someId');
x.style.color = '#00FF00';
see it here: http://jsfiddle.net/2ANmM/
Edit:
It actually just occurred to me that in Xcode 7b4, UI testing now has
expectationForPredicate:evaluatedWithObject:handler:
Original:
Another way is to spin the run loop for a set amount of time. Really only useful if you know how much (estimated) time you'll need to wait for
Obj-C:
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow: <<time to wait in seconds>>]]
Swift:
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate(timeIntervalSinceNow: <<time to wait in seconds>>))
This is not super useful if you need to test some conditions in order to continue your test. To run conditional checks, use a while
loop.
For those using JQuery Mobile
, the above solutions break popup dialog. This will keep links within webapp and allow for popups.
$(document).on('click','a', function (event) {
if($(this).attr('href').indexOf('#') == 0) {
return true;
}
event.preventDefault();
window.location = $(this).attr('href');
});
Could also do it by:
$(document).on('click','a', function (event){
if($(this).attr('data-rel') == 'popup'){
return true;
}
event.preventDefault();
window.location = $(this).attr('href');
});
If you are serializing your data object, it will not be a proper json object. Take what you have, and just wrap the data object in a JSON.stringify()
.
$http({
url: '/user_to_itsr',
method: "POST",
data: JSON.stringify({application:app, from:d1, to:d2}),
headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
$scope.users = data.users; // assign $scope.persons here as promise is resolved here
}).error(function (data, status, headers, config) {
$scope.status = status + ' ' + headers;
});
I found this nice summary of which annotations are picked up by which declarations. By studying it you will find that <context:component-scan/>
recognizes a superset of annotations recognized by <context:annotation-config/>
, namely:
@Component
, @Service
, @Repository
, @Controller
, @Endpoint
@Configuration
, @Bean
, @Lazy
, @Scope
, @Order
, @Primary
, @Profile
, @DependsOn
, @Import
, @ImportResource
As you can see <context:component-scan/>
logically extends <context:annotation-config/>
with CLASSPATH component scanning and Java @Configuration features.
You only need to copy <iframe> from the YouTube Embed section (click on SHARE below the video and then EMBED and copy the entire iframe).
Bootstrap 4:
<div class="w-100"></div>
Source: https://v4-alpha.getbootstrap.com/layout/grid/#equal-width-multi-row