There is comma missing in your tuple.
insert the comma between the tuples as shown:
pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))
Do the same for all
You should create a ModelForm
(docs), which has a field that uses the PasswordInput
widget from the forms library.
It would look like this:
from django import models
class User(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=50)
from django import forms
class UserForm(forms.ModelForm):
class Meta:
model = User
widgets = {
'password': forms.PasswordInput(),
}
For more about using forms in a view, see this section of the docs.
Another way would be adding __getitem__, __setitem__ function
def __getitem__(self, key):
return getattr(self, key)
You can use self[key] to access now.
For some reason, you're re-instantiating the form after you check is_valid()
. Forms only get a cleaned_data
attribute when is_valid()
has been called, and you haven't called it on this new, second instance.
Just get rid of the second form = SearchForm(request.POST)
and all should be well.
Brant's solution is absolutely correct, but I needed to modify it to make it work with multiple select checkboxes and commit=false
. Here is my solution:
models.py
class Choices(models.Model):
description = models.CharField(max_length=300)
class Profile(models.Model):
user = models.ForeignKey(User, blank=True, unique=True, verbose_name_('user'))
the_choices = models.ManyToManyField(Choices)
forms.py
class ProfileForm(forms.ModelForm):
the_choices = forms.ModelMultipleChoiceField(queryset=Choices.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)
class Meta:
model = Profile
exclude = ['user']
views.py
if request.method=='POST':
form = ProfileForm(request.POST)
if form.is_valid():
profile = form.save(commit=False)
profile.user = request.user
profile.save()
form.save_m2m() # needed since using commit=False
else:
form = ProfileForm()
return render_to_response(template_name, {"profile_form": form}, context_instance=RequestContext(request))
You can use self.data
in the clean_email
method to access the POST data before validation. It should contain a key called newsletter_sub
or newsletter_unsub
depending on which button was pressed.
# in the context of a django.forms form
def clean(self):
if 'newsletter_sub' in self.data:
# do subscribe
elif 'newsletter_unsub' in self.data:
# do unsubscribe
You can use initial which is explained here
You have two options either populate the value when calling form constructor:
form = JournalForm(initial={'tank': 123})
or set the value in the form definition:
tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123)
I just was in about the same situation a day ago, and here are my 2 cents:
1) I found arguably the shortest and most concise demonstration of multiple model entry in single form here: http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/ .
In a nutshell: Make a form for each model, submit them both to template in a single <form>
, using prefix
keyarg and have the view handle validation. If there is dependency, just make sure you save the "parent"
model before dependant, and use parent's ID for foreign key before commiting save of "child" model. The link has the demo.
2) Maybe formsets can be beaten into doing this, but as far as I delved in, formsets are primarily for entering multiples of the same model, which may be optionally tied to another model/models by foreign keys. However, there seem to be no default option for entering more than one model's data and that's not what formset seems to be meant for.
Here is a slightly more involved version, based on christophe31's answer. It does not rely on the "readonly" attribute. This makes its problems, like select boxes still being changeable and datapickers still popping up, go away.
Instead, it wraps the form fields widget in a readonly widget, thus making the form still validate. The content of the original widget is displayed inside <span class="hidden"></span>
tags. If the widget has a render_readonly()
method it uses that as the visible text, otherwise it parses the HTML of the original widget and tries to guess the best representation.
import django.forms.widgets as f
import xml.etree.ElementTree as etree
from django.utils.safestring import mark_safe
def make_readonly(form):
"""
Makes all fields on the form readonly and prevents it from POST hacks.
"""
def _get_cleaner(_form, field):
def clean_field():
return getattr(_form.instance, field, None)
return clean_field
for field_name in form.fields.keys():
form.fields[field_name].widget = ReadOnlyWidget(
initial_widget=form.fields[field_name].widget)
setattr(form, "clean_" + field_name,
_get_cleaner(form, field_name))
form.is_readonly = True
class ReadOnlyWidget(f.Select):
"""
Renders the content of the initial widget in a hidden <span>. If the
initial widget has a ``render_readonly()`` method it uses that as display
text, otherwise it tries to guess by parsing the html of the initial widget.
"""
def __init__(self, initial_widget, *args, **kwargs):
self.initial_widget = initial_widget
super(ReadOnlyWidget, self).__init__(*args, **kwargs)
def render(self, *args, **kwargs):
def guess_readonly_text(original_content):
root = etree.fromstring("<span>%s</span>" % original_content)
for element in root:
if element.tag == 'input':
return element.get('value')
if element.tag == 'select':
for option in element:
if option.get('selected'):
return option.text
if element.tag == 'textarea':
return element.text
return "N/A"
original_content = self.initial_widget.render(*args, **kwargs)
try:
readonly_text = self.initial_widget.render_readonly(*args, **kwargs)
except AttributeError:
readonly_text = guess_readonly_text(original_content)
return mark_safe("""<span class="hidden">%s</span>%s""" % (
original_content, readonly_text))
# Usage example 1.
self.fields['my_field'].widget = ReadOnlyWidget(self.fields['my_field'].widget)
# Usage example 2.
form = MyForm()
make_readonly(form)
So, I've really tried to understand this, but it seems that Django still doesn't make this very straightforward. I'm not all that dumb, but I just can't see any (somewhat) simple solution.
I find it generally pretty ugly to have to override the Admin views for this sort of thing, and every example I find never fully applies to the Admin views.
This is such a common circumstance with the models I make that I find it appalling that there's no obvious solution to this...
I've got these classes:
# models.py
class Company(models.Model):
# ...
class Contract(models.Model):
company = models.ForeignKey(Company)
locations = models.ManyToManyField('Location')
class Location(models.Model):
company = models.ForeignKey(Company)
This creates a problem when setting up the Admin for Company, because it has inlines for both Contract and Location, and Contract's m2m options for Location are not properly filtered according to the Company that you're currently editing.
In short, I would need some admin option to do something like this:
# admin.py
class LocationInline(admin.TabularInline):
model = Location
class ContractInline(admin.TabularInline):
model = Contract
class CompanyAdmin(admin.ModelAdmin):
inlines = (ContractInline, LocationInline)
inline_filter = dict(Location__company='self')
Ultimately I wouldn't care if the filtering process was placed on the base CompanyAdmin, or if it was placed on the ContractInline. (Placing it on the inline makes more sense, but it makes it hard to reference the base Contract as 'self'.)
Is there anyone out there who knows of something as straightforward as this badly needed shortcut? Back when I made PHP admins for this sort of thing, this was considered basic functionality! In fact, it was always automatic, and had to be disabled if you really didn't want it!
You could use the string to index into a hash table of function pointers.
Edit: glib has a hash table implementation that supports strings as keys and arbitrary pointers as values: http://library.gnome.org/devel/glib/stable/glib-Hash-Tables.html
This one can also be used with less effort I believe (but I am in MVC 5)
@Html.Description(model => model.Story, 20, 50, new { })
When jQuery is not present you get $ is undefined
and not your message.
Did you check if you don't have a variable called $ somewhere before your code?
Inspect the value of $ in firebug to see what it is.
Slightly out of the question, but I can't resist to write a shorter code to your class assignment:
var i = 1;
$("ol li").each(function(){
$(this).addClass('olli' + i++);
});
Guys Its very interesting to know that many of us face the problem of replication of lookup value while using the Vlookup/Index with Match or Hlookup.... If we have duplicate value in a cell we all know, Vlookup will pick up against the first item would be matching in loopkup array....So here is solution for you all...
e.g.
in Column A we have field called company....
Column A Column B Column C
Company_Name Value
Monster 25000
Naukri 30000
WNS 80000
American Express 40000
Bank of America 50000
Alcatel Lucent 35000
Google 75000
Microsoft 60000
Monster 35000
Bank of America 15000
Now if you lookup the above dataset, you would see the duplicity is in Company Name at Row No# 10 & 11. So if you put the vlookup, the data will be picking up which comes first..But if you use the below formula, you can make your lookup value Unique and can pick any data easily without having any dispute or facing any problem
Put the formula in C2.........A2&"_"&COUNTIF(A2:$A$2,A2)
..........Result will be Monster_1
for first line item and for row no 10 & 11.....Monster_2, Bank of America_2
respectively....Here you go now you have the unique value so now you can pick any data easily now..
Cheers!!! Anil Dhawan
I created a module that works equal to the official Broadcastchannel but has fallbacks based on localstorage, indexeddb and unix-sockets. This makes sure it always works even with Webworkers or NodeJS. See pubkey:BroadcastChannel
Perhaps the most_common() method
Warning: For methods relying on JSON.parse
- Arrays and quote surrounded strings will pass too (ie. console.log(JSON.parse('[3]'), JSON.parse('"\uD800"'))
)
To avoid all non-object JSON primitives (boolean, null, array, number, string), I suggest using the following:
/* Validate a possible object ie. o = { "a": 2 } */
const isJSONObject = (o) =>
!!o && (typeof o === 'object') && !Array.isArray(o) &&
(() => { try { return Boolean(JSON.stringify(o)); } catch { return false } })()
/* Validate a possible JSON object represented as string ie. s = '{ "a": 3 }' */
function isJSONObjectString(s) {
try {
const o = JSON.parse(s);
return !!o && (typeof o === 'object') && !Array.isArray(o)
} catch {
return false
}
}
Code Explanation
Why not use the hasJsonStructure() answer?
Relying on toString()
is not a good idea. This is because different JavaScript Engines may return a different string representation. In general, methods which rely on this may fail in different environments or may be subject to fail later should the engine ever change the string result
Why is catching an exception not a hack?
It was brought up that catching an exception to determine something's validity is never the right way to go. This is generally good advice, but not always. In this case, exception catching is likely is the best route because it relies on the JavaScript engine's implementation of validating JSON data.
Relying on the JS engine offers the following advantages:
When given the opportunity to lean on the JavaScript engine, I'd suggest doing it. Particularly so in this case. Although it may feel hacky to catch an exception, you're really just handling two possible return states from an external method.
You can convert your string into a Uint8Array to get the raw data. Then create a Blob for that data and pass to URL.createObjectURL(blob) to convert the Blob into a URL that you pass to img.src.
var data = '424D5E070000000000003E00000028000000EF...';
// Convert the string to bytes
var bytes = new Uint8Array(data.length / 2);
for (var i = 0; i < data.length; i += 2) {
bytes[i / 2] = parseInt(data.substring(i, i + 2), /* base = */ 16);
}
// Make a Blob from the bytes
var blob = new Blob([bytes], {type: 'image/bmp'});
// Use createObjectURL to make a URL for the blob
var image = new Image();
image.src = URL.createObjectURL(blob);
document.body.appendChild(image);
You can try the complete example at: http://jsfiddle.net/nj82y73d/
I know this is a very old topic, but in case someone needs it
there is no pip
in python 3.4, so we have to use python -m ensurepip
to install pip
Just wanted to add a comment in BRPocock, but I don't have the sufficient privilegies.
So my contribution was for everyone trying to install IBM Integration Toolkit from IBM's Integration Bus bundle.
When you try to run "Installation Manager" command from folder /Integration_Toolkit/IM_Linux (the file to run is "install") you get the error showed in this post.
Further instructions to fix this problem you'll find in this IBM's web page: https://www-304.ibm.com/support/docview.wss?uid=swg21459143
Hope this helps for anybody trying to install that.
#content { margin:0 auto; display:table; float:none;}
_x000D_
<body>_x000D_
<div>_x000D_
<div id="content">_x000D_
I'm the content_x000D_
</div>_x000D_
</div>_x000D_
</body>
_x000D_
Get rid from your <Button>
wrap div using display:block
and float:left
in both <Button>
and <h1>
and specifying their width
with a position:relative
to your Section
. This approach has the advantage of not needing another div
only to position your <Button>
html
<section>
<h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>
<button>button</button>
</section>
? css
section {
position: relative;
width: 50%;
border: 1px solid;
float:left;
}
h1 {
display: block;
width:70%;
float:left;
}
button
{
position:relative;
top:0;
left:0;
float:left;
}
?
Utilities.sleep(milliseconds) creates a 'pause' in program execution, meaning it does nothing during the number of milliseconds you ask. It surely slows down your whole process and you shouldn't use it between function calls. There are a few exceptions though, at least that one that I know : in SpreadsheetApp when you want to remove a number of sheets you can add a few hundreds of millisecs between each deletion to allow for normal script execution (but this is a workaround for a known issue with this specific method). I did have to use it also when creating many sheets in a spreadsheet to avoid the Browser needing to be 'refreshed' after execution.
Here is an example :
function delsheets(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var numbofsheet=ss.getNumSheets();// check how many sheets in the spreadsheet
for (pa=numbofsheet-1;pa>0;--pa){
ss.setActiveSheet(ss.getSheets()[pa]);
var newSheet = ss.deleteActiveSheet(); // delete sheets begining with the last one
Utilities.sleep(200);// pause in the loop for 200 milliseconds
}
ss.setActiveSheet(ss.getSheets()[0]);// return to first sheet as active sheet (useful in 'list' function)
}
use this URL : "https://twitter.com/(userName)/profile_image?size=original"
If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient
, using TWTRAuthSession
.
This is the code snipe for iOS:
if let twitterId = session.userID{
let twitterClient = TWTRAPIClient(userID: twitterId)
twitterClient.loadUser(withID: twitterId) {(user, error) in
if let userName = user?.screenName{
let url = "https://twitter.com/\(userName)/profile_image?size=original")
}
}
}
Also to maintain accessibility, you should use this to determine your keycode:
c = e.which ? e.which : e.keyCode;
if (c == 13) ...
The CSS box model is rather complicated, particularly when it comes to scrolling content. While the browser uses the values from your CSS to draw boxes, determining all the dimensions using JS is not straight-forward if you only have the CSS.
That's why each element has six DOM properties for your convenience: offsetWidth
, offsetHeight
, clientWidth
, clientHeight
, scrollWidth
and scrollHeight
. These are read-only attributes representing the current visual layout, and all of them are integers (thus possibly subject to rounding errors).
Let's go through them in detail:
offsetWidth
, offsetHeight
: The size of the visual box incuding all borders. Can be calculated by adding width
/height
and paddings and borders, if the element has display: block
clientWidth
, clientHeight
: The visual portion of the box content, not including borders or scroll bars , but includes padding . Can not be calculated directly from CSS, depends on the system's scroll bar size.scrollWidth
, scrollHeight
: The size of all of the box's content, including the parts that are currently hidden outside the scrolling area. Can not be calculated directly from CSS, depends on the content.Since offsetWidth
takes the scroll bar width into account, we can use it to calculate the scroll bar width via the formula
scrollbarWidth = offsetWidth - clientWidth - getComputedStyle().borderLeftWidth - getComputedStyle().borderRightWidth
Unfortunately, we may get rounding errors, since offsetWidth
and clientWidth
are always integers, while the actual sizes may be fractional with zoom levels other than 1.
Note that this
scrollbarWidth = getComputedStyle().width + getComputedStyle().paddingLeft + getComputedStyle().paddingRight - clientWidth
does not work reliably in Chrome, since Chrome returns width
with scrollbar already substracted. (Also, Chrome renders paddingBottom to the bottom of the scroll content, while other browsers don't)
Works on Azure, doesn't require stored procs.
SELECT t.name, s.row_count from sys.tables t
JOIN sys.dm_db_partition_stats s
ON t.object_id = s.object_id
AND t.type_desc = 'USER_TABLE'
AND t.name not like '%dss%'
AND s.index_id IN (0,1)
Consider using default filter if it is what you need. For example:
{% set host = jabber.host | default(default.host) -%}
or use more fallback values with "hardcoded" one at the end like:
{% set connectTimeout = config.stackowerflow.connect.timeout | default(config.stackowerflow.timeout) | default(config.timeout) | default(42) -%}
Below is the most efficient method (by run-time) to cut off everything after the first By in a string. If By does not exist, the full string is returned. The result is in $sResult.
$sInputString = "Posted On April 6th By Some Dude";
$sControl = "By";
//Get Position Of 'By'
$iPosition = strpos($sInputString, " ".$sControl);
if ($iPosition !== false)
//Cut Off If String Exists
$sResult = substr($sInputString, 0, $iPosition);
else
//Deal With String Not Found
$sResult = $sInputString;
//$sResult = "Posted On April 6th"
If you don't want to be case sensitive, use stripos instead of strpos. If you think By might exist more than once and want to cut everything after the last occurrence, use strrpos.
Below is a less efficient method but it takes up less code space. This method is also more flexible and allows you to do any regular expression.
$sInputString = "Posted On April 6th By Some Dude";
$pControl = "By";
$sResult = preg_replace("' ".$pControl.".*'s", '', $sInputString);
//$sResult = "Posted On April 6th"
For example, if you wanted to remove everything after the day:
$sInputString = "Posted On April 6th By Some Dude";
$pControl = "[0-9]{1,2}[a-z]{2}"; //1 or 2 numbers followed by 2 lowercase letters.
$sResult = preg_replace("' ".$pControl.".*'s", '', $sInputString);
//$sResult = "Posted On April"
For case insensitive, add the i modifier like this:
$sResult = preg_replace("' ".$pControl.".*'si", '', $sInputString);
To get everything past the last By if you think there might be more than one, add an extra .* at the beginning like this:
$sResult = preg_replace("'.* ".$pControl.".*'si", '', $sInputString);
But here is also a really powerful way you can use preg_match to do what you may be trying to do:
$sInputString = "Posted On April 6th By Some Dude";
$pPattern = "'Posted On (.*?) By (.*?)'s";
if (preg_match($pPattern, $sInputString, $aMatch)) {
//Deal With Match
//$aMatch[1] = "April 6th"
//$aMatch[2] = "Some Dude"
} else {
//No Match Found
}
Regular expressions might seem confusing at first but they can be really powerful and your best friend once you master them! Good luck!
Similarly to the approved answer. If you want to create an array from dictionary keys:
np.array( tuple(dict.keys()) )
If you want to create an array from dictionary values:
np.array( tuple(dict.values()) )
Escape sequences (and variables too) work inside double quoted and heredoc strings. So change your code to:
echo '<p>' . $unit1 . "</p>\n";
PS: One clarification, single quotes strings do accept two escape sequences:
\'
when you want to use single quote inside single quoted strings\\
when you want to use backslash literallyIn case you have virtual env activated, django installed, django-admin --version prints the valid version - check if there is no circular import in the file you are executing.
Make sure that the htaccess file is readable by apache:
chmod 644 /var/www/abc/.htaccess
And make sure the directory it's in is readable and executable:
chmod 755 /var/www/abc/
I know this thread is really old but the solution from @Ivan Bondarenko helped me in my situation.
I had the following in my pom.xml
.
<build>
...
<plugins>
<plugin>
<groupId>com.consol.citrus</groupId>
<artifactId>citrus-remote-maven-plugin</artifactId>
<version>${citrus.version}</version>
<executions>
<execution>
<id>generate-citrus-war</id>
<goals>
<goal>test-war</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
What I wanted, was to disable the execution of generate-citrus-war
for a specific profile and this was the solution:
<profile>
<id>it</id>
<build>
<plugins>
<plugin>
<groupId>com.consol.citrus</groupId>
<artifactId>citrus-remote-maven-plugin</artifactId>
<version>${citrus.version}</version>
<executions>
<!-- disable generating the war for this profile -->
<execution>
<id>generate-citrus-war</id>
<phase/>
</execution>
<!-- do something else -->
<execution>
...
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
Simple implementation of showing a piece of text every two seconds as long the loop is running.
for (var i = 0; i < foo.length; i++) {
setInterval(function(){
console.log("I will appear every 2 seconds");
}, 2000);
break;
};
There are two solutions posted on that page. The one with lower votes I would recommend if possible.
If you are using HTML5 then it is perfectly valid to put a div
inside of a
. As long as the div doesn't also contain some other specific elements like other link tags.
<a href="Music.html">
<div id="music" class="nav">
Music I Like
</div>
</a>
The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative
to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index
at all from that example.
div { position: relative; }
.hyperspan {
position:absolute;
width:100%;
height:100%;
left:0;
top:0;
}
<div id="music" class="nav">Music I Like
<a href="http://www.google.com">
<span class="hyperspan"></span>
</a>
</div>
When you give absolute
positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative
to the parent div you tell the span to only be as big as that.
You can remove webdav module manually from GUI for the particular in IIS.
1) Goto the IIs.
2) Goto the respective site.
3) Open "Handler Mappings"
4) Scroll downn and select WebDav module. Right click on it and delete it.
Note: this will also update your web.config of the web app.
There is something wrong with your design. Try to make your classes represent real world things. For example:
You were very close, you can use this:
DELETE FROM table WHERE (col1,col2) IN ((1,2),(3,4),(5,6))
Please see this fiddle.
When I want to access the application file version (what is set in Assembly Information -> File version), say to set a label's text to it on form load to display the version, I have just used
versionlabel.Text = "Version " + Application.ProductVersion;
This approach requires a reference to System.Windows.Forms
.
Code snippet for both recursive and non-recursive approaches:
//helper method to get the list of files from the HDFS path
public static List<String>
listFilesFromHDFSPath(Configuration hadoopConfiguration,
String hdfsPath,
boolean recursive) throws IOException,
IllegalArgumentException
{
//resulting list of files
List<String> filePaths = new ArrayList<String>();
//get path from string and then the filesystem
Path path = new Path(hdfsPath); //throws IllegalArgumentException
FileSystem fs = path.getFileSystem(hadoopConfiguration);
//if recursive approach is requested
if(recursive)
{
//(heap issues with recursive approach) => using a queue
Queue<Path> fileQueue = new LinkedList<Path>();
//add the obtained path to the queue
fileQueue.add(path);
//while the fileQueue is not empty
while (!fileQueue.isEmpty())
{
//get the file path from queue
Path filePath = fileQueue.remove();
//filePath refers to a file
if (fs.isFile(filePath))
{
filePaths.add(filePath.toString());
}
else //else filePath refers to a directory
{
//list paths in the directory and add to the queue
FileStatus[] fileStatuses = fs.listStatus(filePath);
for (FileStatus fileStatus : fileStatuses)
{
fileQueue.add(fileStatus.getPath());
} // for
} // else
} // while
} // if
else //non-recursive approach => no heap overhead
{
//if the given hdfsPath is actually directory
if(fs.isDirectory(path))
{
FileStatus[] fileStatuses = fs.listStatus(path);
//loop all file statuses
for(FileStatus fileStatus : fileStatuses)
{
//if the given status is a file, then update the resulting list
if(fileStatus.isFile())
filePaths.add(fileStatus.getPath().toString());
} // for
} // if
else //it is a file then
{
//return the one and only file path to the resulting list
filePaths.add(path.toString());
} // else
} // else
//close filesystem; no more operations
fs.close();
//return the resulting list
return filePaths;
} // listFilesFromHDFSPath
Also worth noting the following from a document by the R Core Team summarizing changes in versions of R after v3.5.0 (here):
R has new serialization format (version 3) which supports custom serialization of ALTREP framework objects... Serialized data in format 3 cannot be read by versions of R prior to version 3.5.0.
I encountered this issue when I saved a workspace in v3.6.0, and then shared the file with a colleague that was using v3.4.2. I was able to resolve the issue by adding "version=2" to my save function.
BigDecimal decPrec = (BigDecimal)yo.get("Avg");
decPrec = decPrec.setScale(5, RoundingMode.CEILING);
String value= String.valueOf(decPrec);
This way you can set specific precision of a BigDecimal
.
The value of decPrec was 1.5726903423607562595809913132345426
which is rounded off to 1.57267
.
$.ajax({
url: "target.php",
type: "post",
data: "fname="+fname+"&lname="+lname,
}).done(function(data) {
alert(data);
});
You can easily use ng-show such as :
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div ng-show="isExists(item)">available</div>
<div ng-show="!isExists(item)">oh no, you don't have it</div>
</div>
For more complex tests, you can use ng-switch statements :
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div ng-switch on="isExists(item)">
<span ng-switch-when="true">Available</span>
<span ng-switch-default>oh no, you don't have it</span>
</div>
</div>
class Testclass
{
public $testvar;
function dosomething()
{
echo $this->testvar;
}
}
$Testclass = new Testclass();
$Testclass->testvar = "another value";
$Testclass->dosomething(); ////It will print "another value"
If you start out with:
let array = [
{name: "malcom", dogType: "four-legged"},
{name: "peabody", dogType: "three-legged"},
{name: "pablo", dogType: "two-legged"}
];
And you want a set of, say, names, you would do:
let namesSet = new Set(array.map(item => item.name));
If you really have:
var s = ['{"Select":"11", "PhotoCount":"12"}','{"Select":"21", "PhotoCount":"22"}'];
then simply:
var objs = $.map(s, $.parseJSON);
Try this:
var data = [{field:"Data",type:"date"}, {field:"Numero",type:"number"}];
var columns = {};
var index = 0;
$.each(data, function() {
columns[index] = {
field : this.field,
type : this.type
};
index++;
});
console.log(columns);
Splits an array in multiple arrays with a fixed maximum size.
public static <T extends Object> List<T[]> splitArray(T[] array, int max){
int x = array.length / max;
int r = (array.length % max); // remainder
int lower = 0;
int upper = 0;
List<T[]> list = new ArrayList<T[]>();
int i=0;
for(i=0; i<x; i++){
upper += max;
list.add(Arrays.copyOfRange(array, lower, upper));
lower = upper;
}
if(r > 0){
list.add(Arrays.copyOfRange(array, lower, (lower + r)));
}
return list;
}
Example - an Array of 11 shall be splitted into multiple Arrays not exceeding a size of 5:
// create and populate an array
Integer[] arr = new Integer[11];
for(int i=0; i<arr.length; i++){
arr[i] = i;
}
// split into pieces with a max. size of 5
List<Integer[]> list = ArrayUtil.splitArray(arr, 5);
// check
for(int i=0; i<list.size(); i++){
System.out.println("Array " + i);
for(int j=0; j<list.get(i).length; j++){
System.out.println(" " + list.get(i)[j]);
}
}
Output:
Array 0
0
1
2
3
4
Array 1
5
6
7
8
9
Array 2
10
If you're going to be adding to this dictionary frequently you'd want to take a class based approach, something similar to @Latty's answer in this SO question 2d-dictionary-with-many-keys-that-will-return-the-same-value.
However, if you have a static dictionary, and you need only access values by multiple keys then you could just go the very simple route of using two dictionaries. One to store the alias key association and one to store your actual data:
alias = {
'a': 'id1',
'b': 'id1',
'c': 'id2',
'd': 'id2'
}
dictionary = {
'id1': 1,
'id2': 2
}
dictionary[alias['a']]
If you need to add to the dictionary you could write a function like this for using both dictionaries:
def add(key, id, value=None)
if id in dictionary:
if key in alias:
# Do nothing
pass
else:
alias[key] = id
else:
dictionary[id] = value
alias[key] = id
add('e', 'id2')
add('f', 'id3', 3)
While this works, I think ultimately if you want to do something like this writing your own data structure is probably the way to go, though it could use a similar structure.
Your part:
$result = mysql_connect("localhost", "******", "*****") or die ("Could not save image name
Error: " . mysql_error());
mysql_select_db("project") or die("Could not select database");
mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
if($result) { echo "Image name saved into database
";
Doesn't make much sense, your connection shouldn't be named $result but that is a naming issue not a coding one.
What is a coding issue is if($result), your saying if you can connect to the database regardless of the insert query failing or succeeding you will output "Image saved into database".
Try adding do
$realresult = mysql_query("INSERT into dbProfiles (photo) VALUES('".$_FILES['filep']['name']."')");
and change the if($result) to $realresult
I suspect your query is failing, perhaps you have additional columns or something?
Try copy/pasting your query, replacing the ".$_FILES['filep']['name']." with test and running it in your query browser and see if it goes in.
I get the same error in WP when I use php ver 7.1.6 - just take your php version back to 7.0.20 and the error will disappear.
If you add a loop between the CancelAsync() and the RunWorkerAsync() like so it will solve your problem
private void combobox2_TextChanged(object sender, EventArgs e)
{
if (cmbDataSourceExtractor.IsBusy)
cmbDataSourceExtractor.CancelAsync();
while(cmbDataSourceExtractor.IsBusy)
Application.DoEvents();
var filledComboboxValues = new FilledComboboxValues{ V1 = combobox1.Text,
V2 = combobox2.Text};
cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues );
}
The while loop with the call to Application.DoEvents() will hault the execution of your new worker thread until the current one has properly cancelled, keep in mind you still need to handle the cancellation of your worker thread. With something like:
private void cmbDataSourceExtractor_DoWork(object sender, DoWorkEventArgs e)
{
if (this.cmbDataSourceExtractor.CancellationPending)
{
e.Cancel = true;
return;
}
// do stuff...
}
The Application.DoEvents() in the first code snippet will continue to process your GUI threads message queue so the even to cancel and update the cmbDataSourceExtractor.IsBusy property will still be processed (if you simply added a continue instead of Application.DoEvents() the loop would lock the GUI thread into a busy state and would not process the event to update the cmbDataSourceExtractor.IsBusy)
Try to set a longer max_execution_time
:
<IfModule mod_php5.c>
php_value max_execution_time 300
</IfModule>
<IfModule mod_php7.c>
php_value max_execution_time 300
</IfModule>
You really just need a single struct, and as mentioned in the comments the correct annotations on the field will yield the desired results. JSON is not some extremely variant data format, it is well defined and any piece of json, no matter how complicated and confusing it might be to you can be represented fairly easily and with 100% accuracy both by a schema and in objects in Go and most other OO programming languages. Here's an example;
package main
import (
"fmt"
"encoding/json"
)
type Data struct {
Votes *Votes `json:"votes"`
Count string `json:"count,omitempty"`
}
type Votes struct {
OptionA string `json:"option_A"`
}
func main() {
s := `{ "votes": { "option_A": "3" } }`
data := &Data{
Votes: &Votes{},
}
err := json.Unmarshal([]byte(s), data)
fmt.Println(err)
fmt.Println(data.Votes)
s2, _ := json.Marshal(data)
fmt.Println(string(s2))
data.Count = "2"
s3, _ := json.Marshal(data)
fmt.Println(string(s3))
}
https://play.golang.org/p/ScuxESTW5i
Based on your most recent comment you could address that by using an interface{}
to represent data besides the count, making the count a string and having the rest of the blob shoved into the interface{}
which will accept essentially anything. That being said, Go is a statically typed language with a fairly strict type system and to reiterate, your comments stating 'it can be anything' are not true. JSON cannot be anything. For any piece of JSON there is schema and a single schema can define many many variations of JSON. I advise you take the time to understand the structure of your data rather than hacking something together under the notion that it cannot be defined when it absolutely can and is probably quite easy for someone who knows what they're doing.
Select Xcode and Follow 4 steps that highlighted in photo and remove derived data then restart your project.
As a pure CSS solution for the close or 'times' symbol you can use the ISO code with the content property. I often use this for :after or :before pseudo selectors.
The content code is \00d7.
Example
div:after{
display: inline-block;
content: "\00d7"; /* This will render the 'X' */
}
You can then style and position the pseudo selector in any way you want. Hope this helps someone :).
You already attempt to filter out NULL
values with NOT NULL
. I have changed this to IS NOT NULL
in the WHERE
clause so it will execute. We can refactor this by removing the ISNULL
function in the AVG
method. Also, I doubt you'll actually need bigint
so we can remove the cast.
SELECT distinct
AVG(a.SecurityW) as Average1
,AVG(a.TransferW) as Average2
,AVG(a.StaffW) as Average3
FROM Table1 a, Table2 b
WHERE a.SecurityW <> 0 AND a.SecurityW IS NOT NULL
AND a.TransferW<> 0 AND a.TransferWIS IS NOT NULL
AND a.StaffW<> 0 AND a.StaffWIS IS NOT NULL
AND MONTH(a.ActualTime) = 4
AND YEAR(a.ActualTime) = 2013
Below code helped my object to be refreshed with fresh database values. The Entry(object).Reload() command forces the object to recall database values
GM_MEMBERS member = DatabaseObjectContext.GM_MEMBERS.FirstOrDefault(p => p.Username == username && p.ApplicationName == this.ApplicationName);
DatabaseObjectContext.Entry(member).Reload();
I do it this way. Precise? Maybe or maybe not. Try it
<html>
<head>
<title> Age Calculator</title>
</head>
<input type="date" id="startDate" value="2000-01-01">
<input type="date" id="endDate" value="2020-01-01">
<button onclick="getAge(new Date(document.getElementById('startDate').value), new Date(document.getElementById('endDate').value))">Check Age</button>
<script>
function getAge (startDate, endDate) {
var diff = endDate-startDate
var age = new Date(new Date("0000-01-01").getTime()+diff)
var years = age.getFullYear()
var months = age.getMonth()
var days = age.getDate()
console.log(years,"years",months,"months",days-1,"days")
return (years+"years "+ months+ "months"+ days,"days")
}
</script>
</html>
The LINEST function described in a previous answer is the way to go, but an easier way to show the 3 coefficients of the output is to additionally use the INDEX function. In one cell, type: =INDEX(LINEST(B2:B21,A2:A21^{1,2},TRUE,FALSE),1) (by the way, the B2:B21 and A2:A21 I used are just the same values the first poster who answered this used... of course you'd change these ranges appropriately to match your data). This gives the X^2 coefficient. In an adjacent cell, type the same formula again but change the final 1 to a 2... this gives the X^1 coefficient. Lastly, in the next cell over, again type the same formula but change the last number to a 3... this gives the constant. I did notice that the three coefficients are very close but not quite identical to those derived by using the graphical trendline feature under the charts tab. Also, I discovered that LINEST only seems to work if the X and Y data are in columns (not rows), with no empty cells within the range, so be aware of that if you get a #VALUE error.
Try > workdirectory/filename.txt
This would:
You can consider it equivalent to:
rm -f workdirectory/filename.txt; touch workdirectory/filename.txt
Executing easy. Getting the results can be hard.
Take a look at this question I asked Best way/tool to get the results from an oracle package procedure
The summary of it goes like this.
Assuming you had a Package named mypackage and procedure called getQuestions. It returns a refcursor and takes in string user name.
All you have to do is create new SQL File (file new). Set the connection and paste in the following and execute.
var r refcursor;
exec mypackage.getquestions(:r, 'OMG Ponies');
print r;
I tried t.boolean :active, :default => 1 in migration file for creating entire table. After ran that migration when i checked in db it made as null. Even though i told default as "1". After that slightly i changed migration file like this then it worked for me for setting default value on create table migration file.
t.boolean :active, :null => false,:default =>1. Worked for me.
My Rails framework version is 4.0.0
As an alternative to setting both the html
and body
element's heights to 100%
, you could also use viewport-percentage lengths.
5.1.2. Viewport-percentage lengths: the ‘vw’, ‘vh’, ‘vmin’, ‘vmax’ units
The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.
In this instance, you could use the value 100vh
- which is the height of the viewport.
body {
height: 100vh;
padding: 0;
}
body {
min-height: 100vh;
padding: 0;
}
This is supported in most modern browsers - support can be found here.
After researching a lot I feel most of the given answer will not work with dotnet core.
1.System.Diagnostics.Process.Start("http://google.com")
; -- Will not work with dotnet core
2.It will work but it will block the new window opening in case default browser is chrome
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.FileName = "http://some.domain.tld/bla";
myProcess.Start();
Below is the simplest and will work in all the scenarios.
Process.Start("explorer", url);
i had the same problem and I solved it.
var vm = new MessagesViewModel()
ko.applyBindings(vm)
function ShowMessagesList() {
vm.getData("MyParams")
}
setInterval(ShowMessagesList, 10000)
And then there is the original plugin ez-on-da-ice. Better yet, you can complain to me directly if there are issues. I promise you, I am mostly very responsive :).
With C++17 you can use std::filesystem
, in C++14 std::experimental::filesystem
is already available. Both allow the usage of filesystem::remove()
.
C++17:
#include <filesystem>
std::filesystem::remove("myEmptyDirectoryOrFile"); // Deletes empty directories or single files.
std::filesystem::remove_all("myDirectory"); // Deletes one or more files recursively.
C++14:
#include <experimental/filesystem>
std::experimental::filesystem::remove("myDirectory");
Note 1:
Those functions throw filesystem_error in case of errors. If you want to avoid catching exceptions, use the overloaded variants with std::error_code
as second parameter. E.g.
std::error_code errorCode;
if (!std::filesystem::remove("myEmptyDirectoryOrFile", errorCode)) {
std::cout << errorCode.message() << std::endl;
}
Note 2:
The conversion to std::filesystem::path
happens implicit from different encodings, so you can pass strings to filesystem::remove()
.
To answer the question:
What is the fastest way to stream live video using JavaScript? Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?
Yes, Websocket can be used to transmit over 30 fps and even 60 fps.
The main issue with Websocket is that it is low-level and you have to deal with may other issues than just transmitting video chunks. All in all it's a great transport for video and also audio.
Perform the following steps:
regedit
in the Run window.HKEY_LOCAL_MACHINE\SOFTWARE\ODBC
.You need to tell scp
where to send the file. In your command that is not working:
scp C:\Users\Admin\Desktop\WMU\5260\A2.c ~
You have not mentioned a remote server. scp
uses :
to delimit the host and path, so it thinks you have asked it to download a file at the path \Users\Admin\Desktop\WMU\5260\A2.c
from the host C
to your local home directory.
The correct upload command, based on your comments, should be something like:
C:\> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:
If you are running the command from your home directory, you can use a relative path:
C:\Users\Admin> pscp Desktop\WMU\5260\A2.c [email protected]:
You can also mention the directory where you want to this folder to be downloaded to at the remote server. i.e by just adding a path to the folder as below:
C:/> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:/home/path_to_the_folder/
1st check in your Web.xml that there are multiple < servlet mapping > tags with different names If so Delete the unwanted ones and Run.. This should work fine
OR
To resolve this issue, you have to delete the .snap file located in the directory .
Goto your Workspace of Eclipse which you are UsingPath --> workspace.metadata.plugins\org.eclipse.core.resources\snapfile
Delete the snap file.
After deleting this file, Delete the Tomcat Server Then also Delete the Server runtime which is selected as Apache tomcat. Then Add Server again and Goto Project-->Properties-->Project Facets-->Right side you will find Details and Runtimes Tabs. Click Runtimes and Check the box of Apache which is already there(If not exist add it)
Change port numbers and Run it.
seems if %%
followed with a %@
, the NSString
will go to some strange codes
try this and this worked for me
NSString *str = [NSString stringWithFormat:@"%@%@%@", @"%%",
[textfield text], @"%%"];
Alternatively you can do like this :
var _items = from a in StudentsGrades
group a by a.Name;
foreach (var _itemGroup in _items)
{
foreach (var _item in _itemGroup.OrderBy(a=>a.grade))
{
------------------------
--------------------------
}
}
Add these two line code into your xml view to give ripple effect on your cardView.
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
Sometimes it is useful to scroll the text with the K and J keys, so I have this "scroll mode" function in my .vimrc (also bound to zs).
See scroll_mode.vim.
Case C) is the fastest. Having this as an extension:
Public Module MyExtensions
<Extension()> _
Public Sub Add(Of T)(ByRef arr As T(), item As T)
Array.Resize(arr, arr.Length + 1)
arr(arr.Length - 1) = item
End Sub
End Module
Usage:
Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
arr.Add(newItem)
' --> duration for adding 100.000 items: 1 msec
' --> duration for adding 100.000.000 items: 1168 msec
Not very simple but:
a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,3].count(k)}.values.flatten
=> [1, 1, 2, 2]
Also handles the case for multiples in the 'subtrahend':
a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,1,3].count(k)}.values.flatten
=> [1, 2, 2]
EDIT: this is more an enhancement combining Norm212 and my answer to make a "functional" solution.
b = [1,1,3].each.with_object( a ) { |del| a.delete_at( a.index( del ) ) }
Put it in a lambda if needed:
subtract = lambda do |minuend, subtrahend|
subtrahend.each.with_object( minuend ) { |del| minuend.delete_at( minuend.index( del ) ) }
end
then:
subtract.call a, [1,1,3]
To check for local differences:
git diff myfile.txt
or you can use a diff tool (in case you'd like to revert some changes):
git difftool myfile.txt
To use git difftool
more efficiently, install and use your favourite GUI tool such as Meld, DiffMerge or OpenDiff.
Note: You can also use .
(instead of filename) to see current dir changes.
In order to check changes per each line, use: git blame
which will display which line was commited in which commit.
To view the actual file before the commit (where master
is your branch), run:
git show master:path/my_file
function getBackgroundColor($dom) {
var bgColor = "";
while ($dom[0].tagName.toLowerCase() != "html") {
bgColor = $dom.css("background-color");
if (bgColor != "rgba(0, 0, 0, 0)" && bgColor != "transparent") {
break;
}
$dom = $dom.parent();
}
return bgColor;
}
working properly under Chrome and Firefox
I’m reposting my answer to a similar question because no-one seems to have given it here and it’s much cleaner and neater:
Use the alternative buttons
property syntax:
$dialogDiv.dialog({
autoOpen: false,
modal: true,
width: 600,
resizable: false,
buttons: [
{
text: "Cancel",
"class": 'cancelButtonClass',
click: function() {
// Cancel code here
}
},
{
text: "Save",
"class": 'saveButtonClass',
click: function() {
// Save code here
}
}
],
close: function() {
// Close code here (incidentally, same as Cancel code)
}
});
this fails:
DECLARE @vPortalUID NVARCHAR(32)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
PRINT @nPortalUID
this works
DECLARE @vPortalUID NVARCHAR(36)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
PRINT @nPortalUID
the difference is NVARCHAR(36)
, your input parameter is too small!
* * * * * wget -O - http://yoursite.com/tasks.php >/dev/null 2>&1
That should work for you. Just have a wget
script that loads the page.
Using -O -
means that the output of the web request will be sent to STDOUT (standard output)
by adding >/dev/null
we instruct standard output to be redirect to a black hole.
by adding 2>&1
we instruct STDERR (errors) to also be sent to STDOUT, and thus all output will be sent to a blackhole. (so it will load the website, but never write a file anywhere)
I used exe4j to package all java jars into one final .exe file, which user can use it as normal windows application.
As described by RFC 6068, mailto allows you to specify subject and body, as well as cc fields. For example:
mailto:[email protected]?subject=Subject&body=message%20goes%20here
User doesn't need to click a link if you force it to be opened with JavaScript
window.location.href = "mailto:[email protected]?subject=Subject&body=message%20goes%20here";
Be aware that there is no single, standard way in which browsers/email clients handle mailto links (e.g. subject and body fields may be discarded without a warning). Also there is a risk that popup and ad blockers, anti-virus software etc. may silently block forced opening of mailto links.
showModalBottomSheet(
backgroundColor: Colors.transparent,
context: context, builder: (context) {
return Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft:Radius.circular(40) ,
topRight: Radius.circular(40)
),
),
padding: EdgeInsets.symmetric(vertical: 20,horizontal: 60),
child: Settings_Form(),
);
});
const remoteReq = request({
method: 'POST',
uri: 'http://host.com/api/upload',
headers: {
'Authorization': 'Bearer ' + req.query.token,
'Content-Type': req.headers['content-type'] || 'multipart/form-data;'
}
})
req.pipe(remoteReq);
remoteReq.pipe(res);
for the example above the solution would look like this:
import PILasOPENCV as Image
import PILasOPENCV as ImageDraw
import PILasOPENCV as ImageFont
# from PIL import ImageFont, ImageDraw, Image
import numpy as np
import cv2
image = cv2.imread("lena.jpg")
# Convert to PIL Image
cv2_im_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
pil_im = Image.fromarray(cv2_im_rgb)
draw = ImageDraw.Draw(pil_im)
# Choose a font
font = ImageFont.truetype("Roboto-Regular.ttf", 40)
# Draw the text
draw.text((0, 0), "Your Text Here", font=font)
# Save the image
cv2_im_processed = pil_im.getim()
cv2.imshow("cv2_im_processed", cv2_im_processed)
cv2.waitKey()
You have to use the SelectMany
extension method or its equivalent syntax in pure LINQ.
(from model in list
where model.application == "applicationname"
from user in model.users
where user.surname == "surname"
select new { user, model }).ToList();
gradlew
is a wrapper(w - character) that uses gradle
.
Under the hood gradlew
performs three main things:
gradle
versiongradle
taskUsing Gradle Wrapper we can distribute/share a project to everybody to use the same version and Gradle's functionality(compile, build, install...) even if it has not been installed.
To create a wrapper run:
gradle wrapper
This command generate:
gradle-wrapper.properties
will contain the information about the Gradle distribution
*./
Is used on Unix to specify the current directory
Use %0A
(URL encoding) instead of \n
(C encoding).
The columns in the result set of a select
query with group by
clause must be:
group by
criteria , or ...So, you can't do what you want to do in a single, simple query. The first thing to do is state your problem statement in a clear way, something like:
I want to find the individual claim row bearing the most recent creation date within each group in my claims table
Given
create table dbo.some_claims_table
(
claim_id int not null ,
group_id int not null ,
date_created datetime not null ,
constraint some_table_PK primary key ( claim_id ) ,
constraint some_table_AK01 unique ( group_id , claim_id ) ,
constraint some_Table_AK02 unique ( group_id , date_created ) ,
)
The first thing to do is identify the most recent creation date for each group:
select group_id ,
date_created = max( date_created )
from dbo.claims_table
group by group_id
That gives you the selection criteria you need (1 row per group, with 2 columns: group_id and the highwater created date) to fullfill the 1st part of the requirement (selecting the individual row from each group. That needs to be a virtual table in your final select
query:
select *
from dbo.claims_table t
join ( select group_id ,
date_created = max( date_created )
from dbo.claims_table
group by group_id
) x on x.group_id = t.group_id
and x.date_created = t.date_created
If the table is not unique by date_created
within group_id
(AK02), you you can get duplicate rows for a given group.
If you can change format of short date in the PC to "ddd yyyy-MM-dd" (only first parameter 'ddd' is compulsory), then following command returns-
c:\>vol | date
The current date is: Mon 2014-12-01
Then you can write you batch file -
@echo off
vol | date | find /i "sun" > nul
if not errorlevel 1 goto SUN
vol | date | find /i "mon" > nul
if not errorlevel 1 goto MON
# write block for other week days
goto END
:SUN
set fname="sun"
goto BACKUP
:MON
set fname="mon"
goto BACKUP
# write block for other week days
:BACKUP
echo %fname%
:END
The input() function returns a string which may contain a "list of numbers". You should have understood that the numbers[2] operation returns the third element of an iterable. A string is an iterable, but an iterable of characters, which isn't what you want - you want to average the numbers in the input string.
So there are two things you have to do before you can get to the averaging shown by garyprice:
Hint for step 1: you have to split the input string into non-space substrings.
Step 2 (convert string to integer) should be easy to find with google.
HTH
I was having the same problem while parsing the info.plist
file in my mac. However, the problem was fixed using the following command which turned the file into an XML.
plutil -convert xml1 info.plist
Hope that helps someone.
copy will do this. Please check the php-manual. Simple Google search should answer your last two questions ;)
Here is what I used to fade in/out Views, hope this helps someone.
private void crossFadeAnimation(final View fadeInTarget, final View fadeOutTarget, long duration){
AnimatorSet mAnimationSet = new AnimatorSet();
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(fadeOutTarget, View.ALPHA, 1f, 0f);
fadeOut.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
fadeOutTarget.setVisibility(View.GONE);
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
fadeOut.setInterpolator(new LinearInterpolator());
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(fadeInTarget, View.ALPHA, 0f, 1f);
fadeIn.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
fadeInTarget.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animator animation) {}
@Override
public void onAnimationCancel(Animator animation) {}
@Override
public void onAnimationRepeat(Animator animation) {}
});
fadeIn.setInterpolator(new LinearInterpolator());
mAnimationSet.setDuration(duration);
mAnimationSet.playTogether(fadeOut, fadeIn);
mAnimationSet.start();
}
one solution could be to find a way of pulling the numbers from the string and placing them in a column of just numbers the using the =MEDIAN() function giving the new number column as the range
Hey guys here is a simple test program that shows how to allocate and pass an array using new or malloc. Just cut, paste and run it. Have fun!
struct Coordinate
{
int x,y;
};
void resize( int **p, int size )
{
free( *p );
*p = (int*) malloc( size * sizeof(int) );
}
void resizeCoord( struct Coordinate **p, int size )
{
free( *p );
*p = (Coordinate*) malloc( size * sizeof(Coordinate) );
}
void resizeCoordWithNew( struct Coordinate **p, int size )
{
delete [] *p;
*p = (struct Coordinate*) new struct Coordinate[size];
}
void SomeMethod(Coordinate Coordinates[])
{
Coordinates[0].x++;
Coordinates[0].y = 6;
}
void SomeOtherMethod(Coordinate Coordinates[], int size)
{
for (int i=0; i<size; i++)
{
Coordinates[i].x = i;
Coordinates[i].y = i*2;
}
}
int main()
{
//static array
Coordinate tenCoordinates[10];
tenCoordinates[0].x=0;
SomeMethod(tenCoordinates);
SomeMethod(&(tenCoordinates[0]));
if(tenCoordinates[0].x - 2 == 0)
{
printf("test1 coord change successful\n");
}
else
{
printf("test1 coord change unsuccessful\n");
}
//dynamic int
int *p = (int*) malloc( 10 * sizeof(int) );
resize( &p, 20 );
//dynamic struct with malloc
int myresize = 20;
int initSize = 10;
struct Coordinate *pcoord = (struct Coordinate*) malloc (initSize * sizeof(struct Coordinate));
resizeCoord(&pcoord, myresize);
SomeOtherMethod(pcoord, myresize);
bool pass = true;
for (int i=0; i<myresize; i++)
{
if (! ((pcoord[i].x == i) && (pcoord[i].y == i*2)))
{
printf("Error dynamic Coord struct [%d] failed with (%d,%d)\n",i,pcoord[i].x,pcoord[i].y);
pass = false;
}
}
if (pass)
{
printf("test2 coords for dynamic struct allocated with malloc worked correctly\n");
}
//dynamic struct with new
myresize = 20;
initSize = 10;
struct Coordinate *pcoord2 = (struct Coordinate*) new struct Coordinate[initSize];
resizeCoordWithNew(&pcoord2, myresize);
SomeOtherMethod(pcoord2, myresize);
pass = true;
for (int i=0; i<myresize; i++)
{
if (! ((pcoord2[i].x == i) && (pcoord2[i].y == i*2)))
{
printf("Error dynamic Coord struct [%d] failed with (%d,%d)\n",i,pcoord2[i].x,pcoord2[i].y);
pass = false;
}
}
if (pass)
{
printf("test3 coords for dynamic struct with new worked correctly\n");
}
return 0;
}
Instead of calling containsKey() it is faster just to call map.get and check if the returned value is null or not.
Integer count = map.get(word);
if(count == null){
count = 0;
}
map.put(word, count + 1);
While Large Text File Viewer works great for just looking at a large file (and is free!), if the file is either a delimited or fixed-width file, then you should check out File Query. Not only can it open a file of any size (I have personally opened a 280GB file, but it can go larger), but it lets you query the file as though it was in a database as well, finding out any sort of information you could want from it.
It is not free though, so it is more for people that work with large files a lot, but if you have a one-off problem, you can just use the 30-day trial for free.
Best option would be
Add a compare validator to the web form. Set its controlToValidate. Set its Type property to Date. Set its operator property to DataTypeCheck eg:
<asp:CompareValidator
id="dateValidator" runat="server"
Type="Date"
Operator="DataTypeCheck"
ControlToValidate="txtDatecompleted"
ErrorMessage="Please enter a valid date.">
</asp:CompareValidator>
I was looking long and hard for a solution to this problem and the best I found was a root FTP server on the phone that you connect to on Windows with an FTP client like FileZilla, on the same WiFi network of course.
The root FTP server app I ended up using is FTP Droid. I tried a lot of other FTP apps with bigger download numbers but none of them worked for me for whatever reason. So install this app and set a user with home as / or wherever you want.
Then make note of the phone IP and connect with FileZilla and you should have access to the root of the phone. The biggest benefit I found is I can download entire folders and FTP will just queue it up and take care of it. So I downloaded all of my /data/data/ folder when I was looking for an app and could search on my PC. Very handy.
for /l %%a in (254, -1, 1) do (
for /l %%b in (1, 1, 254) do (
for %%c in (20, 168) do (
for %%e in (172, 192) do (
ping /n 1 %%e.%%c.%%b.%%a>>ping.txt
)
)
)
)
pause>nul
This is for SQL Server 2005. There are updated versions of the table for SQL Server 2008, SQL Server 2008 R2, SQL Server 2012 and SQL Server 2014.
The following table lists Microsoft SQL Server data types, their equivalents in the common language runtime (CLR) for SQL Server in the System.Data.SqlTypes namespace, and their native CLR equivalents in the Microsoft .NET Framework.
SQL Server data type CLR data type (SQL Server) CLR data type (.NET Framework)
varbinary SqlBytes, SqlBinary Byte[]
binary SqlBytes, SqlBinary Byte[]
varbinary(1), binary(1) SqlBytes, SqlBinary byte, Byte[]
image None None
varchar None None
char None None
nvarchar(1), nchar(1) SqlChars, SqlString Char, String, Char[]
nvarchar SqlChars, SqlString String, Char[]
nchar SqlChars, SqlString String, Char[]
text None None
ntext None None
uniqueidentifier SqlGuid Guid
rowversion None Byte[]
bit SqlBoolean Boolean
tinyint SqlByte Byte
smallint SqlInt16 Int16
int SqlInt32 Int32
bigint SqlInt64 Int64
smallmoney SqlMoney Decimal
money SqlMoney Decimal
numeric SqlDecimal Decimal
decimal SqlDecimal Decimal
real SqlSingle Single
float SqlDouble Double
smalldatetime SqlDateTime DateTime
datetime SqlDateTime DateTime
sql_variant None Object
User-defined type(UDT) None user-defined type
table None None
cursor None None
timestamp None None
xml SqlXml None
If you're really talking about the static text
<title>Foo & Bar</title>
stored in some file on the hard disk and served directly by a server, then yes: it probably doesn't need to be escaped.
However, since there is very little HTML content nowadays that's completely static, I'll add the following disclaimer that assumes that the HTML content is generated from some other source (database content, user input, web service call result, legacy API result, ...):
If you don't escape a simple &
, then chances are you also don't escape a &
or a
or <b>
or <script src="http://attacker.com/evil.js">
or any other invalid text. That would mean that you are at best displaying your content wrongly and more likely are suspectible to XSS attacks.
In other words: when you're already checking and escaping the other more problematic cases, then there's almost no reason to leave the not-totally-broken-but-still-somewhat-fishy standalone-& unescaped.
protected $primaryKey = 'SongID';
After adding to my model to tell the primary key because it was taking id(SongID) by default
As PPK points out here, in IE you can also use
e.cancelBubble = true;
In my case, Unity turned out to be a red herring. My problem was a result of different projects targeting different versions of .NET. Unity was set up right and everything was registered with the container correctly. Everything compiled fine. But the type was in a class library, and the class library was set to target .NET Framework 4.0. The WebApi project using Unity was set to target .NET Framework 4.5. Changing the class library to also target 4.5 fixed the problem for me.
I discovered this by commenting out the DI constructor and adding default constructor. I commented out the controller methods and had them throw NotImplementedException. I confirmed that I could reach the controller, and seeing my NotImplementedException told me it was instantiating the controller fine. Next, in the default constructor, I manually instantiated the dependency chain instead of relying on Unity. It still compiled, but when I ran it the error message came back. This confirmed for me that I still got the error even when Unity was out of the picture. Finally, I started at the bottom of the chain and worked my way up, commenting out one line at a time and retesting until I no longer got the error message. This pointed me in the direction of the offending class, and from there I figured out that it was isolated to a single assembly.
Seems based on benchmarks at JSPerf that using +=
is the fastest method, though not necessarily in every browser.
For building strings in the DOM, it seems to be better to concatenate the string first and then add to the DOM, rather then iteratively add it to the dom. You should benchmark your own case though.
(Thanks @zAlbee for correction)
I had the same problem in Catalina.sh of my tomcat for JPDA Options:
JPDA_OPTS="-agentlib:jdwp=transport=$JPDA_TRANSPORT,address=$JPDA_ADDRESS,server=y,suspend=$JPDA_SUSPEND"
After removing JPDA option from my command to start the Tomcat server, I was able to start the server on local environment.
Besides all the excellent solutions offered here I would like to offer a different solution.
I'm not sure if you're free to add dependencies, but if you can, you could add the https://code.google.com/p/guava-libraries/ as a dependency. This library adds support for many basic functional operations to Java and can make working with collections a lot easier and more readable.
In the code I replaced the type of the List by T, since I don't know what your list is typed to.
This problem can with guava be solved like this:
List<T> filteredList = new Arraylist<>(filter(list, not(XXX_EQUAL_TO_AAA)));
And somewhere else you then define XXX_EQUAL_TO_AAA as:
public static final Predicate<T> XXX_EQUAL_TO_AAA = new Predicate<T>() {
@Override
public boolean apply(T input) {
return input.getXXX().equalsIgnoreCase("AAA");
}
}
However, this is probably overkill in your situation. It's just something that becomes increasingly powerful the more you work with collections.
Ohw, also, you need these static imports:
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.Collections2.filter;
The way it's often done is as follows:
I find that this pattern comes up pretty frequently.
What's interesting about this method is that it allows one to insert N
elements into an empty array one-by-one in amortized O(N)
time without knowing N
in advance.
A jar file is simply a file containing a collection of java files. To make a jar file executable, you need to specify where the main
Class is in the jar file. Example code would be as follows.
public class JarExample {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
// your logic here
}
});
}
}
Compile your classes. To make a jar, you also need to create a Manifest File (MANIFEST.MF
). For example,
Manifest-Version: 1.0
Main-Class: JarExample
Place the compiled output class files (JarExample.class,JarExample$1.class) and the manifest file in the same folder. In the command prompt, go to the folder where your files placed, and create the jar using jar command. For example (if you name your manifest file as jexample.mf)
jar cfm jarexample.jar jexample.mf *.class
It will create executable jarexample.jar.
in input field make name same like
<input type="radio" name="option" value="option1">
<input type="radio" name="option" value="option2" >
<input type="radio" name="option" value="option3" >
<input type="radio" name="option" value="option3" >
If the input url is user input. this method gives the most appropriate host name. if not found gives back the input url.
private String getHostName(String urlInput) {
urlInput = urlInput.toLowerCase();
String hostName=urlInput;
if(!urlInput.equals("")){
if(urlInput.startsWith("http") || urlInput.startsWith("https")){
try{
URL netUrl = new URL(urlInput);
String host= netUrl.getHost();
if(host.startsWith("www")){
hostName = host.substring("www".length()+1);
}else{
hostName=host;
}
}catch (MalformedURLException e){
hostName=urlInput;
}
}else if(urlInput.startsWith("www")){
hostName=urlInput.substring("www".length()+1);
}
return hostName;
}else{
return "";
}
}
There's typically two levels of buffering involved:
The internal buffers are buffers created by the runtime/library/language that you're programming against and is meant to speed things up by avoiding system calls for every write. Instead, when you write to a file object, you write into its buffer, and whenever the buffer fills up, the data is written to the actual file using system calls.
However, due to the operating system buffers, this might not mean that the data is written to disk. It may just mean that the data is copied from the buffers maintained by your runtime into the buffers maintained by the operating system.
If you write something, and it ends up in the buffer (only), and the power is cut to your machine, that data is not on disk when the machine turns off.
So, in order to help with that you have the flush
and fsync
methods, on their respective objects.
The first, flush
, will simply write out any data that lingers in a program buffer to the actual file. Typically this means that the data will be copied from the program buffer to the operating system buffer.
Specifically what this means is that if another process has that same file open for reading, it will be able to access the data you just flushed to the file. However, it does not necessarily mean it has been "permanently" stored on disk.
To do that, you need to call the os.fsync
method which ensures all operating system buffers are synchronized with the storage devices they're for, in other words, that method will copy data from the operating system buffers to the disk.
Typically you don't need to bother with either method, but if you're in a scenario where paranoia about what actually ends up on disk is a good thing, you should make both calls as instructed.
Addendum in 2018.
Note that disks with cache mechanisms is now much more common than back in 2013, so now there are even more levels of caching and buffers involved. I assume these buffers will be handled by the sync/flush calls as well, but I don't really know.
Adding an answer because I was directed here after asking how to run a bash script from python. You receive an error OSError: [Errno 2] file not found
if your script takes in parameters. Lets say for instance your script took in a sleep time parameter: subprocess.call("sleep.sh 10")
will not work, you must pass it as an array: subprocess.call(["sleep.sh", 10])
ALTER TABLE provider ADD PRIMARY KEY(person,place,thing);
If a primary key already exists then you want to do this
ALTER TABLE provider DROP PRIMARY KEY, ADD PRIMARY KEY(person, place, thing);
Everything in python is considered as object so functions are also objects. So you can use this method as well.
def fun1():
fun1.var = 100
print(fun1.var)
def fun2():
print(fun1.var)
fun1()
fun2()
print(fun1.var)
XAMPP and WAMP are both web server applications for PHP and MYSQL with the apache server. When we consider IIS, it also a web-server like apache runs on windows only.
XWAMPP/WAMP - Windows,Apache,Mysql,PHP
IIS - Apache,SQL Server, ASP.NET
If you like to read more about XWAMPP vs WAMP
I think http makes request on port 80, even though I mentioned the complete host url in options object. When I run the server application which has the API, on port 80, which I was running previously on port 3000, it worked. Note that to run an application on port 80 you will need root privilege.
Error with the request: getaddrinfo EAI_AGAIN localhost:3000:80
Here is a complete code snippet
var http=require('http');
var options = {
protocol:'http:',
host: 'localhost',
port:3000,
path: '/iso/country/Japan',
method:'GET'
};
var callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
var request=http.request(options, callback);
request.on('error', function(err) {
// handle errors with the request itself
console.error('Error with the request:', err.message);
});
request.end();
Try this on Windows:
cmdkey /delete:LegacyGeneric:target=git:https://github.com
As the answers indicate (if you examine them carefully!), your question is ambiguous. What do you mean by "an A-z letter" or a digit?
If you want to know if a character is a Unicode letter or digit, then use the Character.isLetter
and Character.isDigit
methods.
If you want to know if a character is an ASCII letter or digit, then the best thing to do is to test by comparing with the character ranges 'a' to 'z', 'A' to 'Z' and '0' to '9'.
Note that all ASCII letters / digits are Unicode letters / digits ... but there are many Unicode letters / digits characters that are not ASCII. For example, accented letters, cyrillic, sanskrit, ...
The general solution is to do this:
Character.UnicodeBlock block = Character.UnicodeBlock.of(someCodePoint);
and then test to see if the block is one of the ones that you are interested in. In some cases you will need to test for multiple blocks. For example, there are (at least) 4 code blocks for Cyrillic characters and 7 for Latin. The Character.UnicodeBlock
class defines static constants for well-known blocks; see the javadocs.
Note that any code point will be in at most one block.
I think your question is a bit more general than I originally thought. type()
with one argument returns the type
or class
of the object. So if you have a = 'abc'
and use type(a)
this returns str
because the variable a
is a string. If b = 10
, type(b)
returns int
.
See also python documentation on type().
If you want a comparison you could use: if type(v) == h5py.h5r.Reference
(to check if it is a h5py.h5r.Reference
instance).
But it is recommended that one uses if isinstance(v, h5py.h5r.Reference)
but then also subclasses will evaluate to True
.
If you want to print the class use print v.__class__.__name__
.
More generally: You can compare if two instances have the same class by using type(v) is type(other_v)
or isinstance(v, other_v.__class__)
.
This example reads all objects from a stream of objects, it is assumed that you need CustomObjects instead of a Map:
ObjectMapper mapper = new ObjectMapper();
JsonParser parser = mapper.getFactory().createParser( source );
if(parser.nextToken() != JsonToken.START_ARRAY) {
throw new IllegalStateException("Expected an array");
}
while(parser.nextToken() == JsonToken.START_OBJECT) {
// read everything from this START_OBJECT to the matching END_OBJECT
// and return it as a tree model ObjectNode
ObjectNode node = mapper.readTree(parser);
CustomObject custom = mapper.convertValue( node, CustomObject.class );
// do whatever you need to do with this object
System.out.println( "" + custom );
}
parser.close();
This answer was composed by using : Use Jackson To Stream Parse an Array of Json Objects and Convert JsonNode into Object
You could try this
=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),FALSE, TRUE)
-or-
=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),"FALSE", "File found in row " & MATCH(<single column I value>,<entire column E range>,0))
you could replace <single column I value>
and <entire column E range>
with named ranged. That'd probably be the easiest.
Just drag that formula all the way down the length of your I column in whatever column you want.
static void Main(string[] args)
{
Console.WriteLine("geef een leeftijd");
int a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("geef een leeftijd");
int b = Convert.ToInt32(Console.ReadLine());
int einde = Sum(a, b);
Console.WriteLine(einde);
}
static int Sum(int x, int y)
{
int result = x + y;
return result;
}
Since it wasn't yet mentioned here, it may be worth to add one more option, package spverbatim
(no syntax highlighting):
\documentclass{article}
\usepackage{spverbatim}
\begin{document}
\begin{spverbatim}
Your code here
\end{spverbatim}
\end{document}
Also, if syntax highlighting is not required, package alltt
:
\documentclass{article}
\usepackage{alltt}
\begin{document}
\begin{alltt}
Your code here
\end{alltt}
\end{document}
Found on the documentation page of get_class, where it was posted by me at nwhiting dot com.
function get_class_name($object = null)
{
if (!is_object($object) && !is_string($object)) {
return false;
}
$class = explode('\\', (is_string($object) ? $object : get_class($object)));
return $class[count($class) - 1];
}
But the idea of namespaces is to structure your code. That also means that you can have classes with the same name in multiple namespaces. So theoretically, the object you pass could have the name (stripped) class name, while still being a totally different object than you expect.
Besides that, you might want to check for a specific base class, in which case get_class
doesn't do the trick at all. You might want to check out the operator instanceof
.
If you're using a Unix like OS (Linux, OSX, etc) then you can use a combination of find
and egrep
to search for require statements containing your package name:
find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni 'name-of-package' {} \;
If you search for the entire require('name-of-package')
statement, remember to use the correct type of quotation marks:
find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni 'require("name-of-package")' {} \;
or
find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni "require('name-of-package')" {} \;
The downside is that it's not fully automatic, i.e. it doesn't extract package names from package.json
and check them. You need to do this for each package yourself. Since package.json
is just JSON this could be remedied by writing a small script that uses child_process.exec
to run this command for each dependency. And make it a module. And add it to the NPM repo...
Use:
public static class StringExtensions
{
/// <summary>
/// Cut End. "12".SubstringFromEnd(1) -> "1"
/// </summary>
public static string SubstringFromEnd(this string value, int startindex)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Substring(0, value.Length - startindex);
}
}
I prefer an extension method here for two reasons:
Example: f1.Substring(directorypathLength).SubstringFromEnd(1)
Suppose I have the following table T
:
a b
--------
1 abc
1 def
1 ghi
2 jkl
2 mno
2 pqr
And I do the following query:
SELECT a, b
FROM T
GROUP BY a
The output should have two rows, one row where a=1
and a second row where a=2
.
But what should the value of b show on each of these two rows? There are three possibilities in each case, and nothing in the query makes it clear which value to choose for b in each group. It's ambiguous.
This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).
Fixing it might look like this:
SELECT a, MAX(b) AS x
FROM T
GROUP BY a
Now it's clear that you want the following result:
a x
--------
1 ghi
2 pqr
In order to get the popup exactly centered, it's a simple matter of applying a negative top margin of half the div height, and a negative left margin of half the div width. For this example, like so:
.div {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 50%;
}
I did it in one project of mine. I used MDB to store the data about bills and used Excel to render them, giving the user the possibility to adapt it.
In this case the best solution is:
Not to use any ADO/DAO in Excel. I implemented everything as public functions in MDB modules and called them directly from Excel. You can return even complex data objects, like arrays of strings etc by calling MDB functions with necessary arguments. This is similar to client/server architecture of modern web applications: you web application just does the rendering and user interaction, database and middle tier is then on the server side.
Use Excel forms for user interaction and for data visualisation.
I usually have a very last sheet with some names regions for settings: the path to MDB files, some settings (current user, password if needed etc.) -- so you can easily adapt your Excel implementation to different location of you "back-end" data.
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'// compulsory
compile 'com.squareup.retrofit2:converter-gson:2.1.0' //for retrofit conversion
Login APi Put Two Parameters
{
"UserId": "1234",
"Password":"1234"
}
Login Response
{
"UserId": "1234",
"FirstName": "Keshav",
"LastName": "Gera",
"ProfilePicture": "312.113.221.1/GEOMVCAPI/Files/1.500534651736E12p.jpg"
}
APIClient.java
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
class APIClient {
public static final String BASE_URL = "Your Base Url ";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
APIInterface interface
interface APIInterface {
@POST("LoginController/Login")
Call<LoginResponse> createUser(@Body LoginResponse login);
}
Login Pojo
package pojos;
import com.google.gson.annotations.SerializedName;
public class LoginResponse {
@SerializedName("UserId")
public String UserId;
@SerializedName("FirstName")
public String FirstName;
@SerializedName("LastName")
public String LastName;
@SerializedName("ProfilePicture")
public String ProfilePicture;
@SerializedName("Password")
public String Password;
@SerializedName("ResponseCode")
public String ResponseCode;
@SerializedName("ResponseMessage")
public String ResponseMessage;
public LoginResponse(String UserId, String Password) {
this.UserId = UserId;
this.Password = Password;
}
public String getUserId() {
return UserId;
}
public String getFirstName() {
return FirstName;
}
public String getLastName() {
return LastName;
}
public String getProfilePicture() {
return ProfilePicture;
}
public String getResponseCode() {
return ResponseCode;
}
public String getResponseMessage() {
return ResponseMessage;
}
}
MainActivity
package com.keshav.retrofitloginexampleworkingkeshav;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import pojos.LoginResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import utilites.CommonMethod;
public class MainActivity extends AppCompatActivity {
TextView responseText;
APIInterface apiInterface;
Button loginSub;
EditText et_Email;
EditText et_Pass;
private Dialog mDialog;
String userId;
String password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apiInterface = APIClient.getClient().create(APIInterface.class);
loginSub = (Button) findViewById(R.id.loginSub);
et_Email = (EditText) findViewById(R.id.edtEmail);
et_Pass = (EditText) findViewById(R.id.edtPass);
loginSub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkValidation()) {
if (CommonMethod.isNetworkAvailable(MainActivity.this))
loginRetrofit2Api(userId, password);
else
CommonMethod.showAlert("Internet Connectivity Failure", MainActivity.this);
}
}
});
}
private void loginRetrofit2Api(String userId, String password) {
final LoginResponse login = new LoginResponse(userId, password);
Call<LoginResponse> call1 = apiInterface.createUser(login);
call1.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
LoginResponse loginResponse = response.body();
Log.e("keshav", "loginResponse 1 --> " + loginResponse);
if (loginResponse != null) {
Log.e("keshav", "getUserId --> " + loginResponse.getUserId());
Log.e("keshav", "getFirstName --> " + loginResponse.getFirstName());
Log.e("keshav", "getLastName --> " + loginResponse.getLastName());
Log.e("keshav", "getProfilePicture --> " + loginResponse.getProfilePicture());
String responseCode = loginResponse.getResponseCode();
Log.e("keshav", "getResponseCode --> " + loginResponse.getResponseCode());
Log.e("keshav", "getResponseMessage --> " + loginResponse.getResponseMessage());
if (responseCode != null && responseCode.equals("404")) {
Toast.makeText(MainActivity.this, "Invalid Login Details \n Please try again", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Welcome " + loginResponse.getFirstName(), Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), "onFailure called ", Toast.LENGTH_SHORT).show();
call.cancel();
}
});
}
public boolean checkValidation() {
userId = et_Email.getText().toString();
password = et_Pass.getText().toString();
Log.e("Keshav", "userId is -> " + userId);
Log.e("Keshav", "password is -> " + password);
if (et_Email.getText().toString().trim().equals("")) {
CommonMethod.showAlert("UserId Cannot be left blank", MainActivity.this);
return false;
} else if (et_Pass.getText().toString().trim().equals("")) {
CommonMethod.showAlert("password Cannot be left blank", MainActivity.this);
return false;
}
return true;
}
}
CommonMethod.java
public class CommonMethod {
public static final String DISPLAY_MESSAGE_ACTION =
"com.codecube.broking.gcm";
public static final String EXTRA_MESSAGE = "message";
public static boolean isNetworkAvailable(Context ctx) {
ConnectivityManager connectivityManager
= (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public static void showAlert(String message, Activity context) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message).setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
try {
builder.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
activity_main.xml
<LinearLayout android:layout_width="wrap_content"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="@+id/imgLogin"
android:layout_width="200dp"
android:layout_height="150dp"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:padding="5dp"
android:background="@mipmap/ic_launcher_round"
/>
<TextView
android:id="@+id/txtLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imgLogin"
android:layout_centerHorizontal="true"
android:text="Holostik Track and Trace"
android:textSize="20dp"
android:visibility="gone" />
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/box_layout_margin_left"
android:layout_marginRight="@dimen/box_layout_margin_right"
android:layout_marginTop="8dp"
android:padding="@dimen/text_input_padding">
<EditText
android:id="@+id/edtEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:ems="10"
android:fontFamily="sans-serif"
android:gravity="top"
android:hint="Login ID"
android:maxLines="10"
android:paddingLeft="@dimen/edit_input_padding"
android:paddingRight="@dimen/edit_input_padding"
android:paddingTop="@dimen/edit_input_padding"
android:singleLine="true"></EditText>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textInputLayout1"
android:layout_marginLeft="@dimen/box_layout_margin_left"
android:layout_marginRight="@dimen/box_layout_margin_right"
android:padding="@dimen/text_input_padding">
<EditText
android:id="@+id/edtPass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:fontFamily="sans-serif"
android:hint="Password"
android:inputType="textPassword"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<RelativeLayout
android:id="@+id/rel12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textInputLayout2"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
>
<Button
android:id="@+id/loginSub"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="@drawable/border_button"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:layout_marginRight="10dp"
android:text="Login"
android:textColor="#ffffff" />
</RelativeLayout>
</LinearLayout>
I've had issues using AddDays(-1).
My solution is TimeSpan.
DateTime.Now - TimeSpan.FromDays(1);
int is_prime(int val)
{
int div,square;
if (val==2) return TRUE; /* 2 is prime */
if ((val&1)==0) return FALSE; /* any other even number is not */
div=3;
square=9; /* 3*3 */
while (square<val)
{
if (val % div == 0) return FALSE; /* evenly divisible */
div+=2;
square=div*div;
}
if (square==val) return FALSE;
return TRUE;
}
Handling of 2 and even numbers are kept out of the main loop which only handles odd numbers divided by odd numbers. This is because an odd number modulo an even number will always give a non-zero answer which makes those tests redundant. Or, to put it another way, an odd number may be evenly divisible by another odd number but never by an even number (E*E=>E, E*O=>E, O*E=>E and O*O=>O).
A division/modulus is really costly on the x86 architecture although how costly varies (see http://gmplib.org/~tege/x86-timing.pdf). Multiplications on the other hand are quite cheap.
YourJPanelForm stuff = new YourJPanelForm();
JOptionPane.showMessageDialog(null,stuff,"Your title here bro",JOptionPane.PLAIN_MESSAGE);
Your modal dialog awaits...
create the new name from scratch and delete the old one.
This little example shows how the $rootScope
emit a event that will be listen by a children scope in another controller.
(function(){
angular
.module('ExampleApp',[]);
angular
.module('ExampleApp')
.controller('ExampleController1', Controller1);
Controller1.$inject = ['$rootScope'];
function Controller1($rootScope) {
var vm = this,
message = 'Hi my children scope boy';
vm.sayHi = sayHi;
function sayHi(){
$rootScope.$broadcast('greeting', message);
}
}
angular
.module('ExampleApp')
.controller('ExampleController2', Controller2);
Controller2.$inject = ['$scope'];
function Controller2($scope) {
var vm = this;
$scope.$on('greeting', listenGreeting)
function listenGreeting($event, message){
alert(['Message received',message].join(' : '));
}
}
})();
http://codepen.io/gpincheiraa/pen/xOZwqa
The answer of @gayathri bottom explain technically the differences of all those methods in the scope angular concept and their implementations $scope
and $rootScope
.
You can use the following regular expression.
string.split(/ /)[0].replace(/[^\d]/g, '')
Add a reference to the ngForm
directive in your html code and this gives you access to the form.
<form #myForm="ngForm" (ngSubmit)="addPost(); myForm.reset()"> ... </form>
Or pass the form to the function:
<form #myForm="ngForm" (ngSubmit)="addPost(myForm)"> ... </form>
addPost(form: NgForm){
this.newPost = {
title: this.title,
body: this.body
}
this._postService.addPost(this.newPost);
form.resetForm(); // or form.reset();
}
The difference between resetForm
and reset
is that the former will clear the form fields as well as any validation, while the later will only clear the fields. Use resetForm after the form is validated and submitted, otherwise use reset.
Adding another example for people who can't get the above to work.
With button press:
<form #heroForm="ngForm">
...
<button type="button" class="btn btn-default" (click)="newHero(); heroForm.reset()">New Hero</button>
</form>
Same thing applies above, you can also choose to pass the form to the newHero
function.
WinSCp now supports S3 protocol
First, make sure your AWS user with S3 access permissions has an “Access key ID” created. You also have to know the “Secret access key”. Access keys are created and managed on Users page of IAM Management Console.
Make sure New site node is selected.
On the New site node, select Amazon S3 protocol.
Enter your AWS user Access key ID and Secret access key
Save your site settings using the Save button.
Login using the Login button.
You want to convert mdb to mysql (direct transfer to mysql or mysql dump)?
Try a software called Access to MySQL.
Access to MySQL is a small program that will convert Microsoft Access Databases to MySQL.
- Wizard interface.
- Transfer data directly from one server to another.
- Create a dump file.
- Select tables to transfer.
- Select fields to transfer.
- Transfer password protected databases.
- Supports both shared security and user-level security.
- Optional transfer of indexes.
- Optional transfer of records.
- Optional transfer of default values in field definitions.
- Identifies and transfers auto number field types.
- Command line interface.
- Easy install, uninstall and upgrade.
See the aforementioned link for a step-by-step tutorial with screenshots.
<?php
function plusTimetoOldtime($Old_Time,$getFormat,$Plus_Time) {
return date($getFormat,strtotime(date($getFormat,$Old_Time).$Plus_Time));
}
$Old_Time = strtotime("now");
$Plus_Time = '+1 day';
$getFormat = 'Y-m-d H:i:s';
echo plusTimetoOldtime($Old_Time,$getFormat,$Plus_Time);
?>
# here database details
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);
echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";
# here username is the column of my table(userregistration)
# it works perfectly
I don't recommend StartNew
unless you need that level of complexity.
If your async method is dependent on other async methods, the easiest approach is to use the async
keyword:
private static async Task<DateTime> CountToAsync(int num = 10)
{
for (int i = 0; i < num; i++)
{
await Task.Delay(TimeSpan.FromSeconds(1));
}
return DateTime.Now;
}
If your async method is doing CPU work, you should use Task.Run
:
private static async Task<DateTime> CountToAsync(int num = 10)
{
await Task.Run(() => ...);
return DateTime.Now;
}
You may find my async
/await
intro helpful.
Yes, you have a }
too many. Anyway, compressing yourself tends to result in errors.
function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("content").innerHTML = xmlhttp.responseText;
}
} // <-- end function?
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}
Use Closure Compiler instead.
Go for whatever is most readable and easily maintainable. Just because you can write it out in a single line doesn't mean that you should. Your existing solution is close to what I would use other than I would user iteritems to skip the value lookup, and I hate nested ifs if I can avoid them:
for key, val in d.iteritems():
if filter_string not in key:
continue
# do something
However if you realllly want something to let you iterate through a filtered dict then I would not do the two step process of building the filtered dict and then iterating through it, but instead use a generator, because what is more pythonic (and awesome) than a generator?
First we create our generator, and good design dictates that we make it abstract enough to be reusable:
# The implementation of my generator may look vaguely familiar, no?
def filter_dict(d, filter_string):
for key, val in d.iteritems():
if filter_string not in key:
continue
yield key, val
And then we can use the generator to solve your problem nice and cleanly with simple, understandable code:
for key, val in filter_dict(d, some_string):
# do something
In short: generators are awesome.
I am answering the title of the question rather than the original question which was more specific.
With the new features of Javascript like iterators and generator functions and objects, something like LINQ for Javascript becomes possible. Note that linq.js, for example, uses a completely different approach, using regular expressions, probably to overcome the lack of support in the language at the time.
With that being said, I've written a LINQ library for Javascript and you can find it at https://github.com/Siderite/LInQer. Comments and discussion at https://siderite.dev/blog/linq-in-javascript-linqer.
From previous answers, only Manipula seems to be what one would expect from a LINQ port in Javascript.
If you try:
echo "99%" |grep -o '[0-9]*'
It returns:
99
Here's the details on the -o
(or --only-matching
flag) works from the grep manual page.
Print only the matched (non-empty) parts of matching lines, with each such part on a separate output line. Output lines use the same delimiters as input, and delimiters are null bytes if -z (--null-data) is also used (see Other Options).
The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await
with Task'1.Result
, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.
I've rewritten your function and function call, which should fix your issue:
async Task<string> GetResponseString(string text)
{
var httpClient = new HttpClient();
var parameters = new Dictionary<string, string>();
parameters["text"] = text;
var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
var contents = await response.Content.ReadAsStringAsync();
return contents;
}
And your final function call:
Task<string> result = GetResponseString(text);
var finalResult = result.Result;
Or even better:
var finalResult = await GetResponseString(text);
Here's an approach using streams and java 8 if your lists have different types and you want to combine them to a list of another type.
public static void main(String[] args) {
List<String> list2 = new ArrayList<>();
List<Pair<Integer, String>> list1 = new ArrayList<>();
list2.add("asd");
list2.add("asdaf");
list1.add(new Pair<>(1, "werwe"));
list1.add(new Pair<>(2, "tyutyu"));
Stream stream = Stream.concat(list1.stream(), list2.stream());
List<Pair<Integer, String>> res = (List<Pair<Integer, String>>) stream
.map(item -> {
if (item instanceof String) {
return new Pair<>(0, item);
}
else {
return new Pair<>(((Pair<Integer, String>)item).getKey(), ((Pair<Integer, String>)item).getValue());
}
})
.collect(Collectors.toList());
}
Basically this error comes when you have not specified a password, it means that you have an incorrect password listed in some option file.
Read this DOC on understanding how to assign and manage Passwords to accounts.
Also , Check if the permission on the folder /var/lib/mysql/mysql
is 711 or not.
It's not too hard. Firstly, take a look at FileReader Interface.
So, when the form is submitted, catch the submission process and
var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = shipOff;
//reader.onloadstart = ...
//reader.onprogress = ... <-- Allows you to update a progress bar.
//reader.onabort = ...
//reader.onerror = ...
//reader.onloadend = ...
function shipOff(event) {
var result = event.target.result;
var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'
$.post('/myscript.php', { data: result, name: fileName }, continueSubmission);
}
Then, on the server side (i.e. myscript.php):
$data = $_POST['data'];
$fileName = $_POST['name'];
$serverFile = time().$fileName;
$fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $serverFile );
echo json_encode($returnData);
Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg
in /uploads/
on your server, and respond with a JSON variable (to a continueSubmission()
function) containing the fileName on the server.
Check out fwrite()
and jQuery.post()
.
On the above page it details how to use readAsBinaryString()
, readAsDataUrl()
, and readAsArrayBuffer()
for your other needs (e.g. images, videos, etc).
Here is an example of how to use strtok borrowed from MSDN.
And the relevant bits, you need to call it multiple times. The token
char* is the part you would stuff into an array (you can figure that part out).
char string[] = "A string\tof ,,tokens\nand some more tokens";
char seps[] = " ,\t\n";
char *token;
int main( void )
{
printf( "Tokens:\n" );
/* Establish string and get the first token: */
token = strtok( string, seps );
while( token != NULL )
{
/* While there are tokens in "string" */
printf( " %s\n", token );
/* Get next token: */
token = strtok( NULL, seps );
}
}
The above solution is good if all the data is of same dtype. Numpy arrays are homogeneous containers. When you do df.values
the output is an numpy array
. So if the data has int
and float
in it then output will either have int
or float
and the columns will loose their original dtype.
Consider df
a b
0 1 4
1 2 5
2 3 6
a float64
b int64
So if you want to keep original dtype, you can do something like
row_list = df.to_csv(None, header=False, index=False).split('\n')
this will return each row as a string.
['1.0,4', '2.0,5', '3.0,6', '']
Then split each row to get list of list. Each element after splitting is a unicode. We need to convert it required datatype.
def f(row_str):
row_list = row_str.split(',')
return [float(row_list[0]), int(row_list[1])]
df_list_of_list = map(f, row_list[:-1])
[[1.0, 4], [2.0, 5], [3.0, 6]]
I had to re-run ng update @angular/cli for angular-cli.json to be changed to angular.json
I have written a package in Golang which mimic the Python's range function:
Package https://github.com/thedevsaddam/iter
package main
import (
"fmt"
"github.com/thedevsaddam/iter"
)
func main() {
// sequence: 0-9
for v := range iter.N(10) {
fmt.Printf("%d ", v)
}
fmt.Println()
// output: 0 1 2 3 4 5 6 7 8 9
// sequence: 5-9
for v := range iter.N(5, 10) {
fmt.Printf("%d ", v)
}
fmt.Println()
// output: 5 6 7 8 9
// sequence: 1-9, increment by 2
for v := range iter.N(5, 10, 2) {
fmt.Printf("%d ", v)
}
fmt.Println()
// output: 5 7 9
// sequence: a-e
for v := range iter.L('a', 'e') {
fmt.Printf("%s ", string(v))
}
fmt.Println()
// output: a b c d e
}
Note: I have written for fun! Btw, sometimes it may be helpful
item = objects.Find(obj => obj.property==myValue);
I ran into an issue very similar to the original question that took me a little while to resolve.
Just incase anyone else is working on an MVC application and finds their way into this thread, make sure that you have a wildcard mapping to the appropriate .Net aspnet_isapi.dll defined. As soon as I did this, my app_offline.htm started behaving as expected.
On IIS Application Properties, select virtual Directory tab.
Under Application Settings, click the Configuration button.
Under Wildcard application maps, click the Insert button.
Enter C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll, click OK.
Take a look at SimpleDateFormat
. The code goes something like this:
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
e.printStackTrace();
}
You could use Microsoft.AspNetCore.Mvc.ControllerBase.StatusCode
and Microsoft.AspNetCore.Http.StatusCodes
to form your response, if you don't wish to hardcode specific numbers.
return StatusCode(StatusCodes.Status500InternalServerError);
UPDATE: Aug 2019
Perhaps not directly related to the original question but when trying to achieve the same result with Microsoft Azure Functions
I found that I had to construct a new StatusCodeResult
object found in the Microsoft.AspNetCore.Mvc.Core
assembly. My code now looks like this;
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
I think it is better to change default port of Skype.
Open skype. Go to Tools, Options, Connections, change the port.
Have a look at ImmutableMap JavaDoc: doc
There is information about that there:
Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.
Using jquery,
to store: $('#element_id').data('extra_tag', 'extra_info');
to retrieve: $('#element_id').data('extra_tag');
I strongly recommend you learn how to use layout managers to get the layout you want to see. null
layouts are fragile, and cause no end of trouble.
Try this source & check the comments.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class VolumeCalculator extends JFrame implements ActionListener {
private JTabbedPane jtabbedPane;
private JPanel options;
JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
myTitle;
JTextArea labelTubStatus;
public VolumeCalculator(){
setSize(400, 250);
setVisible(true);
setSize(400, 250);
setVisible(true);
setTitle("Volume Calculator");
setSize(300, 200);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
createOptions();
jtabbedPane = new JTabbedPane();
jtabbedPane.addTab("Options", options);
topPanel.add(jtabbedPane, BorderLayout.CENTER);
}
/* CREATE OPTIONS */
public void createOptions(){
options = new JPanel();
//options.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
options.add(labelOptions);
JTextField newTitle = new JTextField("Some Title");
//newTitle.setBounds(80, 40, 225, 20);
options.add(newTitle);
myTitle = new JTextField(20);
// myTitle WAS NEVER ADDED to the GUI!
options.add(myTitle);
//myTitle.setBounds(80, 40, 225, 20);
//myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
//newName.setBounds(60, 80, 150, 20);
newName.addActionListener(this);
options.add(newName);
JButton Exit = new JButton("Exit");
//Exit.setBounds(250, 80, 80, 20);
Exit.addActionListener(this);
options.add(Exit);
}
public void actionPerformed(ActionEvent event){
JButton button = (JButton) event.getSource();
String buttonLabel = button.getText();
if ("Exit".equalsIgnoreCase(buttonLabel)){
Exit_pressed();
return;
}
if ("Set New Name".equalsIgnoreCase(buttonLabel)){
New_Name();
return;
}
}
private void Exit_pressed(){
System.exit(0);
}
private void New_Name(){
System.out.println("'" + myTitle.getText() + "'");
this.setTitle(myTitle.getText());
}
private void Options(){
}
public static void main(String[] args){
JFrame frame = new VolumeCalculator();
frame.pack();
frame.setSize(380, 350);
frame.setVisible(true);
}
}
Before HTML5 we can use:
parent.location.hash = "hello";
and:
window.location.replace("http:www.example.com");
This method will reload your page, but HTML5 introduced the history.pushState(page, caption, replace_url)
that should not reload your page.
Using pyquaternion is extremely simple; to install it (while still in python), run in your console:
import pip;
pip.main(['install','pyquaternion'])
Once installed:
from pyquaternion import Quaternion
v = [3,5,0]
axis = [4,4,1]
theta = 1.2 #radian
rotated_v = Quaternion(axis=axis,angle=theta).rotate(v)
No way to do this that I know of, although I'm very curious to read if anyone has a good answer. I have been thinking about adding something like this to one of the apps my company builds, but have found no good way to do it.
The one thing I can think of (although not directly on point) is that I believe you can limit the total memory usage for a COM+ application in Windows. It would require the app to be written to run in COM+, of course, but it's the closest way I know of.
The working set stuff is good (Job Objects also control working sets), but that's not total memory usage, only real memory usage (paged in) at any one time. It may work for what you want, but afaik it doesn't limit total allocated memory.
Enter the mysql shell like this.
mysql --host=localhost --user=username --password --database=db
Then use the source command and a semicolon to seperate the commands.
source file1.sql; source file2; source file3;
For a new build, it could be that some dependencies aren't installed. For me it was Crystal Reports.
Even though setting a CSS height value to the select element does not work, the padding attribute works alright. Setting a top and bottom padding will make your select element look taller.
I've generally used xml drawables to create shadow/elevation on a pre-lollipop widget. Here, for example, is an xml drawable that can be used on pre-lollipop devices to simulate the floating action button's elevation.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="8px">
<layer-list>
<item>
<shape android:shape="oval">
<solid android:color="#08000000"/>
<padding
android:bottom="3px"
android:left="3px"
android:right="3px"
android:top="3px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#09000000"/>
<padding
android:bottom="2px"
android:left="2px"
android:right="2px"
android:top="2px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#10000000"/>
<padding
android:bottom="2px"
android:left="2px"
android:right="2px"
android:top="2px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#11000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#12000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#13000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#14000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#15000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#16000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#17000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
</layer-list>
</item>
<item>
<shape android:shape="oval">
<solid android:color="?attr/colorPrimary"/>
</shape>
</item>
</layer-list>
In place of ?attr/colorPrimary
you can choose any color. Here's a screenshot of the result:
The new version of SharePoint and Office (SharePoint 2010 and Office 2010) respectively are supposed to allow for this. This also includes the web based versions. I have seen Word and Excel in action do this, not sure about other client applications.
I am not sure about the specific implementation features you are asking about in terms of security though. Sorry.,=
Here is a discussion
http://blogs.msdn.com/b/sharepoint/archive/2009/10/19/sharepoint-2010.aspx
function tinyFriends() {
let myFriends = ["Mukit", "Ali", "Umor", "sabbir"]
let smallestFridend = myFriends[0];
for (i = 0; i < myFriends.length; i++) {
if (myFriends[i] < smallestFridend) {
smallestFridend = myFriends[i];
}
}
return smallestFridend
}
Give headercss position fixed.
.headercss {
width: 100%;
height: 320px;
background-color: #000000;
position: fixed;
top:0
}
Then give the content container a 320px padding-top, so it doesn't get behind the header.
This is the proposed answer on the Github repo:
// example without validators
const c = new FormControl('', { updateOn: 'blur' });
// example with validators
const c= new FormControl('', {
validators: Validators.required,
updateOn: 'blur'
});
Github : feat(forms): add updateOn blur option to FormControls
<a href="#"><button type="button" class="btn btn-info btn-block regular-link"> <span class="text">Create New Board</span></button></a>
We can use btn-block for automatic responsive.
If you're going to use Model.select
, then you might as well just use DISTINCT
, as it will return only the unique values. This is better because it means it returns less rows and should be slightly faster than returning a number of rows and then telling Rails to pick the unique values.
Model.select('DISTINCT rating')
Of course, this is provided your database understands the DISTINCT
keyword, and most should.
Use 'Smalldatetime' data type
select convert(smalldatetime, getdate())
will fetch
2015-01-08 15:27:00
WARNING! This is an incorrect solution. layers are added infinitely in the
drawRect
method (every time the view is drawn). You should NEVER add layers in thedrawRect
method. UselayoutSubview
instead.
You can draw a circle with this (Swift 3.0+):
let circlePath = UIBezierPath(arcCenter: CGPoint(x: 100, y: 100), radius: CGFloat(20), startAngle: CGFloat(0), endAngle: CGFloat(Double.pi * 2), clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
// Change the fill color
shapeLayer.fillColor = UIColor.clear.cgColor
// You can change the stroke color
shapeLayer.strokeColor = UIColor.red.cgColor
// You can change the line width
shapeLayer.lineWidth = 3.0
view.layer.addSublayer(shapeLayer)
With the code you have posted you are cropping the corners of the UIView
, not adding a circle to the view.
Here's a full example of using that method:
/// A special UIView displayed as a ring of color
class Ring: UIView {
override func drawRect(rect: CGRect) {
drawRingFittingInsideView()
}
internal func drawRingFittingInsideView() -> () {
let halfSize:CGFloat = min( bounds.size.width/2, bounds.size.height/2)
let desiredLineWidth:CGFloat = 1 // your desired value
let circlePath = UIBezierPath(
arcCenter: CGPoint(x:halfSize,y:halfSize),
radius: CGFloat( halfSize - (desiredLineWidth/2) ),
startAngle: CGFloat(0),
endAngle:CGFloat(M_PI * 2),
clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.CGPath
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.strokeColor = UIColor.redColor().CGColor
shapeLayer.lineWidth = desiredLineWidth
layer.addSublayer(shapeLayer)
}
}
Note, however there's an incredibly handy call:
let circlePath = UIBezierPath(ovalInRect: rect)
which does all the work of making the path. (Don't forget to inset it for the line thickness, which is also incredibly easy with CGRectInset
.)
internal func drawRingFittingInsideView(rect: CGRect) {
let desiredLineWidth:CGFloat = 4 // Your desired value
let hw:CGFloat = desiredLineWidth/2
let circlePath = UIBezierPath(ovalInRect: CGRectInset(rect,hw,hw))
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.CGPath
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.strokeColor = UIColor.redColor().CGColor
shapeLayer.lineWidth = desiredLineWidth
layer.addSublayer(shapeLayer)
}
In practice these days in Swift, you would certainly use @IBDesignable
and @IBInspectable
. Using these you can actually see and change the rendering, in Storyboard!
As you can see, it actually adds new features to the Inspector on the Storyboard, which you can change on the Storyboard:
/// A dot with a border, which you can control completely in Storyboard
@IBDesignable class Dot: UIView {
@IBInspectable var mainColor: UIColor = UIColor.blueColor() {
didSet {
print("mainColor was set here")
}
}
@IBInspectable var ringColor: UIColor = UIColor.orangeColor() {
didSet {
print("bColor was set here")
}
}
@IBInspectable var ringThickness: CGFloat = 4 {
didSet {
print("ringThickness was set here")
}
}
@IBInspectable var isSelected: Bool = true
override func drawRect(rect: CGRect) {
let dotPath = UIBezierPath(ovalInRect:rect)
let shapeLayer = CAShapeLayer()
shapeLayer.path = dotPath.CGPath
shapeLayer.fillColor = mainColor.CGColor
layer.addSublayer(shapeLayer)
if (isSelected) {
drawRingFittingInsideView(rect)
}
}
internal func drawRingFittingInsideView(rect: CGRect) {
let hw:CGFloat = ringThickness/2
let circlePath = UIBezierPath(ovalInRect: CGRectInset(rect,hw,hw) )
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.CGPath
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.strokeColor = ringColor.CGColor
shapeLayer.lineWidth = ringThickness
layer.addSublayer(shapeLayer)
}
}
Finally, note that if you have a UIView
(which is square, and which you set to say red in Storyboard) and you simply want to turn it in to a red circle, you can just do the following:
// Makes a UIView into a circular dot of color
class Dot: UIView {
override func layoutSubviews() {
layer.cornerRadius = bounds.size.width/2
}
}
Very interesting question. I think it's mainly a semantic meaning, and may also be due to historical reasons.
Although in current Android Activity and Service implementations, getApplication()
and getApplicationContext()
return the same object, there is no guarantee that this will always be the case (for example, in a specific vendor implementation).
So if you want the Application class you registered in the Manifest, you should never call getApplicationContext()
and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework).
Why does getApplicationContext()
exist in the first place ?
getApplication()
is only available in the Activity class and the Service class, whereas getApplicationContext()
is declared in the Context class.
That actually means one thing : when writing code in a broadcast receiver, which is not a context but is given a context in its onReceive method, you can only call getApplicationContext()
. Which also means that you are not guaranteed to have access to your application in a BroadcastReceiver.
When looking at the Android code, you see that when attached, an activity receives a base context and an application, and those are different parameters. getApplicationContext()
delegates it's call to baseContext.getApplicationContext()
.
One more thing : the documentation says that it most cases, you shouldn't need to subclass Application:
There is normally no need to subclass
Application
. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given aContext
which internally usesContext.getApplicationContext()
when first constructing the singleton.
I know this is not an exact and precise answer, but still, does that answer your question?
This method is very simple and you can modify your clone without modify the original array.
// Original Array_x000D_
let array = [{name: 'Rafael'}, {name: 'Matheus'}];_x000D_
_x000D_
// Cloning Array_x000D_
let clone = array.map(a => {return {...a}})_x000D_
_x000D_
// Editing the cloned array_x000D_
clone[1].name = 'Carlos';_x000D_
_x000D_
_x000D_
console.log('array', array)_x000D_
// [{name: 'Rafael'}, {name: 'Matheus'}]_x000D_
_x000D_
console.log('clone', clone)_x000D_
// [{name: 'Rafael'}, {name: 'Carlos'}]
_x000D_
In Angular 6, you can do this:
In your service file:
function_name(data) {
const url = `the_URL`;
let input = new FormData();
input.append('url', data); // "url" as the key and "data" as value
return this.http.post(url, input).pipe(map((resp: any) => resp));
}
In component.ts file: in any function say xyz,
xyz(){
this.Your_service_alias.function_name(data).subscribe(d => { // "data" can be your file or image in base64 or other encoding
console.log(d);
});
}
Here is an example to call your webservice using jQuery.get:
$.get("http://domain.com/webservice.asmx", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
In the example above, we call "webservice.asmx", passing two parameters: name and time. Then, getting the service output in the call back function.
Also when you call from http request it will work properly but when your try to call from net.tcp that time you get all this kind stuff
How to use an IF statement in the MySQL "select list":
select if (1>2, 2, 3); //returns 3
select if(1<2,'yes','no'); //returns yes
SELECT IF(STRCMP('test','test1'),'no','yes'); //returns no
How to use an IF statement in the MySQL where clause search condition list:
create table penguins (id int primary key auto_increment, name varchar(100))
insert into penguins (name) values ('rico')
insert into penguins (name) values ('kowalski')
insert into penguins (name) values ('skipper')
select * from penguins where 3 = id
-->3 skipper
select * from penguins where (if (true, 2, 3)) = id
-->2 kowalski
How to use an IF statement in the MySQL "having clause search conditions":
select * from penguins
where 1=1
having (if (true, 2, 3)) = id
-->1 rico
Use an IF statement with a column used in the select list to make a decision:
select (if (id = 2, -1, 1)) item
from penguins
where 1=1
--> 1
--> -1
--> 1
If statements embedded in SQL queries is a bad "code smell". Bad code has high "WTF's per minute" during code review. This is one of those things. If I see this in production with your name on it, I'm going to automatically not like you.
Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.
This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".
Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
strXls, True, "temp!"
get_current_user_id()
will return the current user id (an integer), or will return 0 if the user is not logged in.
if (get_current_user_id()) {
// display navbar here
}
More details here get_current_user_id().
Warning
If you run PowerShell from a cmd.exe window created by Powershell, the 2nd instance no longer waits for jobs to complete.
cmd> PowerShell
PS> Start-Process cmd.exe -Wait
Now from the new cmd window, run PowerShell again and within it start a 2nd cmd window: cmd2> PowerShell
PS> Start-Process cmd.exe -Wait
PS>
The 2nd instance of PowerShell no longer honors the -Wait request and ALL background process/jobs return 'Completed' status even thou they are still running !
I discovered this when my C# Explorer program is used to open a cmd.exe window and PS is run from that window, it also ignores the -Wait request. It appears that any PowerShell which is a 'win32 job' of cmd.exe fails to honor the wait request.
I ran into this with PowerShell version 3.0 on windows 7/x64
I was going insane trying to get my js files to refresh and I tried everything. Then I did a header check and remembered I was using Cloudflare!
In Cloudflare you can use dev mode to disable proxy.
A possible CSS ONLY solution can be achived with position: sticky;
The browser support is actually really good: https://caniuse.com/#search=position%3A%20sticky
here is an example: https://jsfiddle.net/0vcoa43L/7/
I use the following method:
public static <T> T getBean(final String beanName, final Class<T> clazz) {
ELContext elContext = FacesContext.getCurrentInstance().getELContext();
return (T) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, beanName);
}
This allows me to get the returned object in a typed manner.
You have $headers .= '...';
followed by $headers = '...';
; the second line is overwriting the first.
Just put the $headers .= "Bcc: $emailList\r\n";
say after the Content-type
line and it should be fine.
On a side note, the To
is generally required; mail servers might mark your message as spam otherwise.
$headers = "From: [email protected]\r\n" .
"X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";
As I answered here, you can remove spines from all your plots through style settings (style sheet or rcParams):
import matplotlib as mpl
mpl.rcParams['axes.spines.left'] = False
mpl.rcParams['axes.spines.right'] = False
mpl.rcParams['axes.spines.top'] = False
mpl.rcParams['axes.spines.bottom'] = False
array_slice() is best thing to try, following are the examples:
<?php
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 2); // returns "c", "d", and "e"
$output = array_slice($input, -2, 1); // returns "d"
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"
// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>
You can use and test uninitialized variables at least for their 'definedness'. Like this:
var iAmNotDefined;
alert(!iAmNotDefined); //true
//or
alert(!!iAmNotDefined); //false
Furthermore, there are many possibilites: if you're not interested in exact types use the '==' operator (or ![variable] / !![variable]) for comparison (that is what Douglas Crockford calls 'truthy' or 'falsy' I think). In that case assigning true or 1 or '1' to the unitialized variable always returns true when asked. Otherwise [if you need type safe comparison] use '===' for comparison.
var thisMayBeTrue;
thisMayBeTrue = 1;
alert(thisMayBeTrue == true); //=> true
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false
thisMayBeTrue = '1';
alert(thisMayBeTrue == true); //=> true
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false
// so, in this case, using == or !! '1' is implicitly
// converted to 1 and 1 is implicitly converted to true)
thisMayBeTrue = true;
alert(thisMayBeTrue == true); //=> true
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> true
thisMayBeTrue = 'true';
alert(thisMayBeTrue == true); //=> false
alert(!!thisMayBeTrue); //=> true
alert(thisMayBeTrue === true); //=> false
// so, here's no implicit conversion of the string 'true'
// it's also a demonstration of the fact that the
// ! or !! operator tests the 'definedness' of a variable.
PS: you can't test 'definedness' for nonexisting variables though. So:
alert(!!HelloWorld);
gives a reference Error ('HelloWorld is not defined')
(is there a better word for 'definedness'? Pardon my dutch anyway;~)
As @Nils mentionned, you can use the update_fields
keyword argument of the save()
method to manually specify the fields to update.
obj_instance = Model.objects.get(field=value)
obj_instance.field = new_value
obj_instance.field2 = new_value2
obj_instance.save(update_fields=['field', 'field2'])
The update_fields
value should be a list of the fields to update as strings.
See https://docs.djangoproject.com/en/2.1/ref/models/instances/#specifying-which-fields-to-save
Try this:
public static void main(String[] args) {
String str = "My name is Milan, people know me as Milan Vasic.";
Pattern p = Pattern.compile("(Milan)(?! Vasic)");
Matcher m = p.matcher(str);
StringBuffer sb = new StringBuffer();
while(m.find()) {
m.appendReplacement(sb, "Milan Vasic");
}
m.appendTail(sb);
System.out.println(sb);
}
After several attempts and going deep in Tomcat's source code I found out that the simple property useNaming="false" did the trick!! Now Tomcat resolves names java:/liferay instead of java:comp/env/liferay
This is simple css for Sign Mark.
ul li:after{opacity: 1;content: '\2713';right: 20px;position: absolute;font-size: 20px;font-weight: bold;}
Unless I grossly misunderstood your question, move overflow-x:scroll
from .search-table
to .search-table-outter
.
.search-table-outter {border:2px solid red; overflow-x:scroll;}
.search-table{table-layout: fixed; margin:40px auto 0px auto; }
As far as I know you can't give scrollbars to tables themselves.
it also can be a great idea using concat for EL + MAP + JSON problem like in this example :
#{myMap[''.concat(myid)].content}
I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the fragment. After researching the problem on Stack Overflow, I adopted the following solution:
volatile boolean running;
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
running=true;
...
}
public void onDestroy() {
super.onDestroy();
running=false;
...
}
Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.