I know this is old but this answer still applies to newer Core releases.
If by chance your DbContext
implementation is in a different project than your startup project and you run ef migrations
, you'll see this error because the command will not be able to invoke the application's startup code leaving your database provider without a configuration. To fix it, you have to let ef migrations
know where they're at.
dotnet ef migrations add MyMigration [-p <relative path to DbContext project>, -s <relative path to startup project>]
Both -s
and -p
are optionals that default to the current folder.
If you add double paranthesis to the ngModel reference you get a two-way binding to your model property. That property can then be read and used in the event handler. In my view that is the most clean approach.
<input type="checkbox" [(ngModel)]="myModel.property" (ngModelChange)="processChange()" />
Change the button to
<button id="search">Search</button>
and add the following script
var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
var keyWord = $('#Keyword').val();
$('#searchResults').load(url, { searchText: keyWord });
})
and modify the controller method to accept the search text
public ActionResult DisplaySearchResults(string searchText)
{
var model = // build list based on parameter searchText
return PartialView("SearchResults", model);
}
The jQuery .load
method calls your controller method, passing the value of the search text and updates the contents of the <div>
with the partial view.
Side note: The use of a <form>
tag and @Html.ValidationSummary()
and @Html.ValidationMessageFor()
are probably not necessary here. Your never returning the Index
view so ValidationSummary
makes no sense and I assume you want a null
search text to return all results, and in any case you do not have any validation attributes for property Keyword
so there is nothing to validate.
Edit
Based on OP's comments that SearchCriterionModel
will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit()
event
<input type="submit" value="Search" />
var url = '@Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
if (!$(this).valid()) {
return false; // prevent the ajax call if validation errors
}
var form = $(this).serialize();
$('#searchResults').load(url, form);
return false; // prevent the default submit action
})
and the controller method would be
public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
{
var model = // build list based on the properties of criteria
return PartialView("SearchResults", model);
}
My issue was similar - I had a new table i was creating that ahd to tie in to the identity users. After reading the above answers, realized it had to do with IsdentityUser and the inherited properites. I already had Identity set up as its own Context, so to avoid inherently tying the two together, rather than using the related user table as a true EF property, I set up a non-mapped property with the query to get the related entities. (DataManager is set up to retrieve the current context in which OtherEntity exists.)
[Table("UserOtherEntity")]
public partial class UserOtherEntity
{
public Guid UserOtherEntityId { get; set; }
[Required]
[StringLength(128)]
public string UserId { get; set; }
[Required]
public Guid OtherEntityId { get; set; }
public virtual OtherEntity OtherEntity { get; set; }
}
public partial class UserOtherEntity : DataManager
{
public static IEnumerable<OtherEntity> GetOtherEntitiesByUserId(string userId)
{
return Connect2Context.UserOtherEntities.Where(ue => ue.UserId == userId).Select(ue => ue.OtherEntity);
}
}
public partial class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
[NotMapped]
public IEnumerable<OtherEntity> OtherEntities
{
get
{
return UserOtherEntities.GetOtherEntitiesByUserId(this.Id);
}
}
}
If you are not wanting to use async
you can add .Result
to force the code to execute synchronously:
private string GetResponseString(string text)
{
var httpClient = new HttpClient();
var parameters = new Dictionary<string, string>();
parameters["text"] = text;
var response = httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters)).Result;
var contents = response.Content.ReadAsStringAsync().Result;
return contents;
}
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
E.g. thenReturn() may be missing.
For mocking of void methods try out below:
//Kotlin Syntax
Mockito.`when`(voidMethodCall())
.then {
Unit //Do Nothing
}
Same case (no DB and MigrationHistory table on Server). My steps:
I was getting the issue 'Newtonsoft.Json' already has a dependency defined for 'Microsoft.CSharp'
on the TeamCity build server.
I changed the "Update Mode" of the Nuget Installer build step from solution file to packages.config and NuGet.exe to the latest version (I had 3.5.0) and it worked !!
All proposed solutions didn't work for me but the closest one was from @Rishii.
I'm using AngularJS 1.4.4 and UI Bootstrap 0.13.3.
.directive('jsr310Compatible', ['dateFilter', 'dateParser', function(dateFilter, dateParser) {
return {
restrict: 'EAC',
require: 'ngModel',
priority: 1,
link: function(scope, element, attrs, ngModel) {
var dateFormat = 'yyyy-MM-dd';
ngModel.$parsers.push(function(viewValue) {
return dateFilter(viewValue, dateFormat);
});
ngModel.$validators.date = function (modelValue, viewValue) {
var value = modelValue || viewValue;
if (!attrs.ngRequired && !value) {
return true;
}
if (angular.isNumber(value)) {
value = new Date(value);
}
if (!value) {
return true;
}
else if (angular.isDate(value) && !isNaN(value)) {
return true;
}
else if (angular.isString(value)) {
var date = dateParser.parse(value, dateFormat);
return !isNaN(date);
}
else {
return false;
}
};
}
};
}])
According to this, DatabaseGeneratedOption.Identity is not detected by a specific migration if it's added after the table has been created, which is the case I run into. So I dropped the database and that specific migration and added a new migration, finally update the database, then everything works as expected. I am using EF 6.1, SQL2014 and VS2013.
You call writer.close();
in writeToFile
so the writer has been closed the second time you call writeToFile
.
Why don't you merge FileStatus
into writeToFile
?
this comes because you add some property to one of your model and you did not update-Database
. to solve this you have to remove it from model or you have to add-migration anyProperName
with that properties and Update-database
.
It work for window phone 8.1. You can try this.
Dictionary<string, object> _headerContents = new Dictionary<string, object>();
const String _lineEnd = "\r\n";
const String _twoHyphens = "--";
const String _boundary = "*****";
private async void UploadFile_OnTap(object sender, System.Windows.Input.GestureEventArgs e)
{
Uri serverUri = new Uri("http:www.myserver.com/Mp4UploadHandler", UriKind.Absolute);
string fileContentType = "multipart/form-data";
byte[] _boundarybytes = Encoding.UTF8.GetBytes(_twoHyphens + _boundary + _lineEnd);
byte[] _trailerbytes = Encoding.UTF8.GetBytes(_twoHyphens + _boundary + _twoHyphens + _lineEnd);
Dictionary<string, object> _headerContents = new Dictionary<string, object>();
SetEndHeaders(); // to add some extra parameter if you need
httpWebRequest = (HttpWebRequest)WebRequest.Create(serverUri);
httpWebRequest.ContentType = fileContentType + "; boundary=" + _boundary;
httpWebRequest.Method = "POST";
httpWebRequest.AllowWriteStreamBuffering = false; // get response after upload header part
var fileName = Path.GetFileName(MediaStorageFile.Path);
Stream fStream = (await MediaStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read)).AsStream(); //MediaStorageFile is a storage file from where you want to upload the file of your device
string fileheaderTemplate = "Content-Disposition: form-data; name=\"{0}\"" + _lineEnd + _lineEnd + "{1}" + _lineEnd;
long httpLength = 0;
foreach (var headerContent in _headerContents) // get the length of upload strem
httpLength += _boundarybytes.Length + Encoding.UTF8.GetBytes(string.Format(fileheaderTemplate, headerContent.Key, headerContent.Value)).Length;
httpLength += _boundarybytes.Length + Encoding.UTF8.GetBytes("Content-Disposition: form-data; name=\"uploadedFile\";filename=\"" + fileName + "\"" + _lineEnd).Length
+ Encoding.UTF8.GetBytes(_lineEnd).Length * 2 + _trailerbytes.Length;
httpWebRequest.ContentLength = httpLength + fStream.Length; // wait until you upload your total stream
httpWebRequest.BeginGetRequestStream((result) =>
{
try
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
using (Stream stream = request.EndGetRequestStream(result))
{
foreach (var headerContent in _headerContents)
{
WriteToStream(stream, _boundarybytes);
WriteToStream(stream, string.Format(fileheaderTemplate, headerContent.Key, headerContent.Value));
}
WriteToStream(stream, _boundarybytes);
WriteToStream(stream, "Content-Disposition: form-data; name=\"uploadedFile\";filename=\"" + fileName + "\"" + _lineEnd);
WriteToStream(stream, _lineEnd);
int bytesRead = 0;
byte[] buffer = new byte[2048]; //upload 2K each time
while ((bytesRead = fStream.Read(buffer, 0, buffer.Length)) != 0)
{
stream.Write(buffer, 0, bytesRead);
Array.Clear(buffer, 0, 2048); // Clear the array.
}
WriteToStream(stream, _lineEnd);
WriteToStream(stream, _trailerbytes);
fStream.Close();
}
request.BeginGetResponse(a =>
{ //get response here
try
{
var response = request.EndGetResponse(a);
using (Stream streamResponse = response.GetResponseStream())
using (var memoryStream = new MemoryStream())
{
streamResponse.CopyTo(memoryStream);
responseBytes = memoryStream.ToArray(); // here I get byte response from server. you can change depends on server response
}
if (responseBytes.Length > 0 && responseBytes[0] == 1)
MessageBox.Show("Uploading Completed");
else
MessageBox.Show("Uploading failed, please try again.");
}
catch (Exception ex)
{}
}, null);
}
catch (Exception ex)
{
fStream.Close();
}
}, httpWebRequest);
}
private static void WriteToStream(Stream s, string txt)
{
byte[] bytes = Encoding.UTF8.GetBytes(txt);
s.Write(bytes, 0, bytes.Length);
}
private static void WriteToStream(Stream s, byte[] bytes)
{
s.Write(bytes, 0, bytes.Length);
}
private void SetEndHeaders()
{
_headerContents.Add("sId", LocalData.currentUser.SessionId);
_headerContents.Add("uId", LocalData.currentUser.UserIdentity);
_headerContents.Add("authServer", LocalData.currentUser.AuthServerIP);
_headerContents.Add("comPort", LocalData.currentUser.ComPort);
}
Though agree with find() is most effective in your usecase. Still there is $match of aggregation framework, to ease the query of a big number of entries and generate a low number of results that hold value to you especially for grouping and creating new files.
PersonModel.aggregate([ { "$match": { $and : [{ 'favouriteFoods' : { $exists: true, $in: [ 'sushi']}}, ........ ] } }, { $project : {"_id": 0, "name" : 1} } ]);
I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).
e.g. (from the doc)
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
Try this:
Select
Id,
Salt,
Password,
BannedEndDate,
(Select Count(*)
From LoginFails
Where username = '" + LoginModel.Username + "' And IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "')
From Users
Where username = '" + LoginModel.Username + "'
And I recommend you strongly to use parameters in your query to avoid security risks with sql injection attacks!
Hope that helps!
An alternative to using a plugin is using an editor template. What you need to do is to create a template file in Shared\EditorTemplates
folder and call it String.cshtml
. Then put this in that file:
@Html.TextBox("",ViewData.TemplateInfo.FormattedModelValue,
new { placeholder = ViewData.ModelMetadata.Watermark })
Then use it in your view like this:
@Html.EditorFor(m=>Model.UnitPercent)
The downside, this works for properties of type string
, and you will have to create a template for each type
that you want support for a watermark.
Controller
public ActionResult Index()
{
//you don't need to include the category bc it does it by itself
//var model = db.Product.Include(c => c.Category).ToList()
ViewBag.Categories = db.Category.OrderBy(c => c.Name).ToList();
var model = db.Product.ToList()
return View(model);
}
View
you need to filter the model with the given category
like :=> Model.where(p=>p.CategoryID == category.CategoryID)
try this...
@foreach (var category in ViewBag.Categories)
{
<h3><u>@category.Name</u></h3>
<div>
@foreach (var product in Model.where(p=>p.CategoryID == category.CategoryID))
{
<table cellpadding="5" cellspacing"5" style="border:1px solid black; width:100%;background-color:White;">
<thead>
<tr>
<th style="background-color:black; color:white;">
@product.Title
@if (System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal("/admin", User, "GET"))
{
@Html.Raw(" - ")
@Html.ActionLink("Edit", "Edit", new { id = product.ID }, new { style = "background-color:black; color:white !important;" })
}
</th>
</tr>
</thead>
<tbody>
<tr>
<td style="background-color:White;">
@product.Description
</td>
</tr>
</tbody>
</table>
}
</div>
}
this works for me goto your model class and set error message above any prop
[Required(ErrorMessage ="This is Required Field")]
public string name { get; set; }
import namespace for Required by Ctrl+. and finally add this in view
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
you need check packagesToScan.
<bean id="entityManagerFactoryDB" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
<property name="dataSource" ref="dataSourceDB" />
<property name="persistenceUnitName" value="persistenceUnitDB" />
<property name="packagesToScan" value="at.naviclean.domain" />
//here
.....
Make the class serializable by implementing the interface java.io.Serializable
.
java.io.Serializable
- Marker Interface which does not have any methods in it.ObjectOutputStream
that this object is a serializable object.I faced similar issue.
The folder was shared and Authenticated Users permission was provided, which solved my issue.
I ran into this issue when the number of <th>
tags in the '' did not match the number of in the <tfoot>
section
<thead>
<tr>
<th></th>
<th>Subject Areas</th>
<th></th>
<th>Option(s)</th>
<tr>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
I know it's an old thread I worked with above answer and had to add:
header('Access-Control-Allow-Methods: GET, POST, PUT');
So my header looks like:
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');
And the problem was fixed.
Use Maven and use the maven-compiler-plugin to explicitly call the actual correct version JDK javac.exe command, because Maven could be running any version; this also catches the really stupid long standing bug in javac that does not spot runtime breaking class version jars and missing classes/methods/properties when compiling for earlier java versions! This later part could have easily been fixed in Java 1.5+ by adding versioning attributes to new classes, methods, and properties, or separate compiler versioning data, so is a quite stupid oversight by Sun and Oracle.
Remove/Delete the project from workspace. and Reimport the project to the workspace. This method worked for me.
Have you tried calling knockout's clean node method on your DOM element to dispose of the in memory bound objects?
var element = $('#elementId')[0];
ko.cleanNode(element);
Then applying the knockout bindings again on just that element with your new view models would update your view binding.
You can do it calling setRowSelectionInterval :
table.setRowSelectionInterval(0, 0);
to select the first row.
Your PersonSheets has a property int Id
, Id
isn't in the post, so modelbinding fails. Make Id nullable (int?) or send atleast Id = 0 with the POst .
If your DateTime
properties are nullable in the database then be sure to use DateTime?
for the associated object properties or EF will pass in DateTime.MinValue
for unassigned values which is outside of the range of what the SQL datetime type can handle.
One way would be store the current colour for each row within the model. Here's a simple model that is fixed at 3 columns and 3 rows:
static class MyTableModel extends DefaultTableModel {
List<Color> rowColours = Arrays.asList(
Color.RED,
Color.GREEN,
Color.CYAN
);
public void setRowColour(int row, Color c) {
rowColours.set(row, c);
fireTableRowsUpdated(row, row);
}
public Color getRowColour(int row) {
return rowColours.get(row);
}
@Override
public int getRowCount() {
return 3;
}
@Override
public int getColumnCount() {
return 3;
}
@Override
public Object getValueAt(int row, int column) {
return String.format("%d %d", row, column);
}
}
Note that setRowColour
calls fireTableRowsUpdated
; this will cause just that row of the table to be updated.
The renderer can get the model from the table:
static class MyTableCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
MyTableModel model = (MyTableModel) table.getModel();
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
c.setBackground(model.getRowColour(row));
return c;
}
}
Changing a row's colour would be as simple as:
model.setRowColour(1, Color.YELLOW);
I did it like this in my Jtable its autorefreshing after 300 ms;
DefaultTableModel tableModel = new DefaultTableModel(){
public boolean isCellEditable(int nRow, int nCol) {
return false;
}
};
JTable table = new JTable();
Timer t = new Timer(300, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addColumns();
remakeData(set);
table.setModel(model);
}
});
t.start();
private void addColumns() {
model.setColumnCount(0);
model.addColumn("NAME");
model.addColumn("EMAIL");}
private void remakeData(CollectionType< Objects > name) {
model.setRowCount(0);
for (CollectionType Objects : name){
String n = Object.getName();
String e = Object.getEmail();
model.insertRow(model.getRowCount(),new Object[] { n,e });
}}
I doubt it will do good with large number of objects like over 500, only other way is to implement TableModelListener in your class, but i did not understand how to use it well. look at http://download.oracle.com/javase/tutorial/uiswing/components/table.html#modelchange
I had the same problem with three projects in one solution and all of the suggestions didn't work until I made a reference in the reference file of the web site project to the project where the edmx file sits.
Reading the remark of Kleopatra (her 2nd time she suggested to have a look at javax.swing.JXTable, and now I Am sorry I didn't have a look the first time :) ) I suggest you follow the link
I had this solution for the same problem: (but I suggest you follow the link above) On resize the table, scale the table column widths to the current table total width. to do this I use a global array of ints for the (relative) column widths):
private int[] columnWidths=null;
I use this function to set the table column widths:
public void setColumnWidths(int[] widths){
int nrCols=table.getModel().getColumnCount();
if(nrCols==0||widths==null){
return;
}
this.columnWidths=widths.clone();
//current width of the table:
int totalWidth=table.getWidth();
int totalWidthRequested=0;
int nrRequestedWidths=columnWidths.length;
int defaultWidth=(int)Math.floor((double)totalWidth/(double)nrCols);
for(int col=0;col<nrCols;col++){
int width = 0;
if(columnWidths.length>col){
width=columnWidths[col];
}
totalWidthRequested+=width;
}
//Note: for the not defined columns: use the defaultWidth
if(nrRequestedWidths<nrCols){
log.fine("Setting column widths: nr of columns do not match column widths requested");
totalWidthRequested+=((nrCols-nrRequestedWidths)*defaultWidth);
}
//calculate the scale for the column width
double factor=(double)totalWidth/(double)totalWidthRequested;
for(int col=0;col<nrCols;col++){
int width = defaultWidth;
if(columnWidths.length>col){
//scale the requested width to the current table width
width=(int)Math.floor(factor*(double)columnWidths[col]);
}
table.getColumnModel().getColumn(col).setPreferredWidth(width);
table.getColumnModel().getColumn(col).setWidth(width);
}
}
When setting the data I call:
setColumnWidths(this.columnWidths);
and on changing I call the ComponentListener set to the parent of the table (in my case the JScrollPane that is the container of my table):
public void componentResized(ComponentEvent componentEvent) {
this.setColumnWidths(this.columnWidths);
}
note that the JTable table is also global:
private JTable table;
And here I set the listener:
scrollPane=new JScrollPane(table);
scrollPane.addComponentListener(this);
You must add setActionCommand
to the JRadioButton
then just do:
String entree = entreeGroup.getSelection().getActionCommand();
Example:
java = new JRadioButton("Java");
java.setActionCommand("Java");
c = new JRadioButton("C/C++");
c.setActionCommand("c");
System.out.println("Selected Radio Button: " +
buttonGroup.getSelection().getActionCommand());
You can extract the href from the a tag:
window.open(document.getElementById('redirect').href);
If you run PHPMyAdmin on localhost uncomment in file /etc/php5/apache2/php.ini
this line:
mysqli.allow_local_infile = On
Restart Apache:
sudo /etc/init.d/apache2 restart
df = df_try
for i in range(4):
df = df.append(df_try)
# Here, we have df_try times 5
df = df.append(df)
# Here, we have df_try times 10
You can update your python version to 3.8 in conda using the command
conda install -c anaconda python=3.8
as per https://anaconda.org/anaconda/python. Though not all packages support 3.8 yet, running
conda update --all
may resolve some dependency failures. You can also create a new environment called py38 using this command
conda create -n py38 python=3.8
Edit - note that the conda install
option will potentially take a while to solve the environment, and if you try to abort this midway through you will lose your Python installation (usually this means it will resort to non-conda pre-installed system Python installation).
JsonNode node = mapper.readValue("[{\"id\":\"value11\",\"name\": \"value12\",\"qty\":\"value13\"},"
System.out.println("id : "+node.findValues("id").get(0).asText());
this also done the trick.
To save your work and exit press Esc and then :wq (w for write and q for quit).
Alternatively, you could both save and exit by pressing Esc and then :x
To set another editor run export EDITOR=myFavoriteEdior
on your terminal, where myFavoriteEdior
can be vi
, gedit
, subl
(for sublime) etc.
Just notice that if you work with Fragments using ViewPager, it's pretty easy. You only need to call this method: setOffscreenPageLimit()
.
Accordign to the docs:
Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed.
Like this:
int counts[26];
memset(counts, 0, sizeof(counts));
char *p = string;
while (*p) {
counts[tolower(*p++) - 'a']++;
}
This code assumes that the string is null-terminated, and that it contains only characters a
through z
or A
through Z
, inclusive.
To understand how this works, recall that after conversion tolower
each letter has a code between a
and z
, and that the codes are consecutive. As the result, tolower(*p) - 'a'
evaluates to a number from 0
to 25
, inclusive, representing the letter's sequential number in the alphabet.
This code combines ++
and *p
to shorten the program.
onclick="return confirm('Log Out?')? window.open('?user=logout','_self'): void(0);"
Did this script and afterwards i tought i go check the internet too.
Yes this is an old threat but as there seems not to be any similar version i thought i'd contribute.
Easiest & simplest way works on all browsers with/in any element or field.
You can change window.open
to any other command to run when confirmation is TRUE
, same with void(0)
if conformation is NULL
or canceled.
You can't put a div directly inside a table but you can put div inside td
or th
element.
For that you need to do is make sure the div is inside an actual table cell, a td or th element, so do that:
HTML:-
<tr>
<td>
<div>
<p>I'm text in a div.</p>
</div>
</td>
</tr>
For more information :-
Getting MAC Address Using PHP: (Tested in Ubuntu 18.04) - 2020 Update
Here's the Code:
<?php
$mac = shell_exec("ip link | awk '{print $2}'");
preg_match_all('/([a-z0-9]+):\s+((?:[0-9a-f]{2}:){5}[0-9a-f]{2})/i', $mac, $matches);
$output = array_combine($matches[1], $matches[2]);
$mac_address_values = json_encode($output, JSON_PRETTY_PRINT);
echo $mac_address_values
?>
Output:
{
"lo": "00:00:00:00:00:00",
"enp0s25": "00:21:cc:d4:2a:23",
"wlp3s0": "84:3a:4b:03:3c:3a",
"wwp0s20u4": "7a:e3:2a:de:66:09"
}
It'll need to be something tailored to the needs, which are dependent on the structure you're presented with. For the example you've provided, this works:
$(document).ready(function(){
var $tmp = $('#listItem').children().remove();
$('#listItem').text('').append($tmp);
});
Demo: http://jquery.nodnod.net/cases/2385/run
But it's fairly dependent on the markup being similar to what you posted.
You can use list.sort
with its optional key
parameter and a lambda
expression:
>>> lst = [
... ['John',2],
... ['Jim',9],
... ['Jason',1]
... ]
>>> lst.sort(key=lambda x:x[1])
>>> lst
[['Jason', 1], ['John', 2], ['Jim', 9]]
>>>
This will sort the list in-place.
Note that for large lists, it will be faster to use operator.itemgetter
instead of a lambda
:
>>> from operator import itemgetter
>>> lst = [
... ['John',2],
... ['Jim',9],
... ['Jason',1]
... ]
>>> lst.sort(key=itemgetter(1))
>>> lst
[['Jason', 1], ['John', 2], ['Jim', 9]]
>>>
I don't know if there's a more elegant way with dynamically created objects, but using plain old reflection should work:
var nameOfProperty = "property1";
var propertyInfo = myObject.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(myObject, null);
GetProperty
will return null
if the type of myObject
does not contain a public property with this name.
EDIT: If the object is not a "regular" object but something implementing IDynamicMetaObjectProvider
, this approach will not work. Please have a look at this question instead:
Qberticus's answer is good, but one useful detail is missing. If you are implementing these in a library replace:
xmlns:whatever="http://schemas.android.com/apk/res/org.example.mypackage"
with:
xmlns:whatever="http://schemas.android.com/apk/res-auto"
Otherwise the application that uses the library will have runtime errors.
If you want to set 4 sides separately use:
border-width: 1px 2em 5px 0; /* top right bottom left */
border-style: solid dotted inset double;
border-color: #f00 #0f0 #00f #ff0;
use this: String customHtml =text ;
wb.loadDataWithBaseURL(null,customHtml,"text/html", "UTF-8", null);
With JRE 8 on XP there is another way - to use MSI to deploy package.
or (silent way, usable in batch file etc..)
for %%I in ("*.msi") do if exist "%%I" msiexec.exe /i %%I /qn EULA=0 SKIPLICENSE=1 PROG=0 ENDDIALOG=0
next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Read article :Difference between next() and nextLine()
Replace your while loop with :
while(r.hasNext()) {
scan = r.next();
System.out.println(scan);
if(scan.length()==0) {continue;}
//treatment
}
Using hasNext()
and next()
methods will resolve the issue.
You can use "translateX(-100%)" and "text-align: right" if your absolute element is "display: inline-block"
<div class="box">
<div class="absolute-right"></div>
</div>
<style type="text/css">
.box{
text-align: right;
}
.absolute-right{
display: inline-block;
position: absolute;
}
/*The magic:*/
.absolute-right{
-moz-transform: translateX(-100%);
-ms-transform: translateX(-100%);
-webkit-transform: translateX(-100%);
-o-transform: translateX(-100%);
transform: translateX(-100%);
}
</style>
You will get absolute-element aligned to the right relative its parent
I think your problem may lie in how your datepicker is setup. Why don't you disconnect the input... do not use altField. Instead explicitly set the values when the onSelect fires. This will give you control of each interaction; the user text field, and the datepicker.
Note: Sometimes you have to call the routine on .change() and not .onSelect() because onSelect can be called on different interactions that you are not expecting.
Pseudo Code:
$('#date').datepicker({
//altField: , //do not use
onSelect: function(date){
$('#date').val(date); //Set my textbox value
//Do your search routine
},
}).change(function(){
//Or do it here...
});
$('#date').change(function(){
var thisDate = $(this).val();
if(isValidDate(thisDate)){
$('#date').datepicker('setDate', thisDate); //Set my datepicker value
//Do your search routine
});
});
How (and why) to use display: table-cell (CSS)
I just wanted to mention, since I don't think any of the other answers did directly, that the answer to "why" is: there is no good reason, and you should probably never do this.
In my over a decade of experience in web development, I can't think of a single time I would have been better served to have a bunch of <div>
s with display
styles than to just have table elements.
The only hypothetical I could come up with is if you have tabular data stored in some sort of non-HTML-table format (eg. a CSV file). In a very specific version of this case it might be easier to just add <div>
tags around everything and then add descendent-based styles, instead of adding actual table tags.
But that's an extremely contrived example, and in all real cases I know of simply using table tags would be better.
I could help you out with the html:
<option value="">abc</option>
instead of
<option value="4">abc</option>
to set abc as the default value.
If you want to access event object as well as data passed, you have to pass event
and ticket.id
both as parameters, like following:
HTML
<input type="number" v-on:input="addToCart($event, ticket.id)" min="0" placeholder="0">
Javascript
methods: {
addToCart: function (event, id) {
// use event here as well as id
console.log('In addToCart')
console.log(id)
}
}
See working fiddle: https://jsfiddle.net/nee5nszL/
In case you are using vue-router, you may have to use $event in your v-on:input
method like following:
<input type="number" v-on:input="addToCart($event, num)" min="0" placeholder="0">
Here is working fiddle.
You haven't defined struct stasher_file
by your first definition. What you have defined is an nameless struct type and a variable stasher_file
of that type. Since there's no definition for such type as struct stasher_file
in your code, the compiler complains about incomplete type.
In order to define struct stasher_file
, you should have done it as follows
struct stasher_file {
char name[32];
int size;
int start;
int popularity;
};
Note where the stasher_file
name is placed in the definition.
Define tooltip text
<input type="text" id="firstname" name="firstname" tooltipText="Type in your firstname in this box">
Initialize and configure the script
<script type="text/javascript">
var tooltipObj = new DHTMLgoodies_formTooltip();
tooltipObj.setTooltipPosition('right');
tooltipObj.setPageBgColor('#EEE');
tooltipObj.setCloseMessage('Exit');
tooltipObj.initFormFieldTooltip();
</script>
Seems like nobody was able to answer the question so far :)
I use EclipseLink's MOXy to dynamically generate binding classes and then recursively go through the bound types. It is somewhat heavy, but it allows XPath value injection once the object tree is instantiated:
InputStream in = new FileInputStream(PATH_TO_XSD);
DynamicJAXBContext jaxbContext =
DynamicJAXBContextFactory.createContextFromXSD(in, null, Thread.currentThread().getContextClassLoader(), null);
DynamicType rootType = jaxbContext.getDynamicType(YOUR_ROOT_TYPE);
DynamicEntity root = rootType.newDynamicEntity();
traverseProps(jaxbContext, root, rootType, 0);
TraverseProps is pretty simple recursive method:
private void traverseProps(DynamicJAXBContext c, DynamicEntity e, DynamicType t, int level) throws DynamicException, InstantiationException, IllegalAccessException{
if (t!=null) {
logger.info(indent(level) + "type [" + t.getName() + "] of class [" + t.getClassName() + "] has " + t.getNumberOfProperties() + " props");
for (String pName:t.getPropertiesNames()){
Class<?> clazz = t.getPropertyType(pName);
logger.info(indent(level) + "prop [" + pName + "] in type: " + clazz);
//logger.info("prop [" + pName + "] in entity: " + e.get(pName));
if (clazz==null){
// need to create an instance of object
String updatedClassName = pName.substring(0, 1).toUpperCase() + pName.substring(1);
logger.info(indent(level) + "Creating new type instance for " + pName + " using following class name: " + updatedClassName );
DynamicType child = c.getDynamicType("generated." + updatedClassName);
DynamicEntity childEntity = child.newDynamicEntity();
e.set(pName, childEntity);
traverseProps(c, childEntity, child, level+1);
} else {
// just set empty value
e.set(pName, clazz.newInstance());
}
}
} else {
logger.warn("type is null");
}
}
Converting everything to XML is pretty easy:
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
The default constructor has no arguments. You need to specify a constructor:
public Friends( String firstName, String age) { ... }
From version 1.9 Easier and official way of getting json
from django.http import JsonResponse
from django.forms.models import model_to_dict
return JsonResponse( model_to_dict(modelinstance) )
public List<int> GetPositions(string source, string searchString)
{
List<int> ret = new List<int>();
int len = searchString.Length;
int start = -len;
while (true)
{
start = source.IndexOf(searchString, start + len);
if (start == -1)
{
break;
}
else
{
ret.Add(start);
}
}
return ret;
}
Call it like this:
List<int> list = GetPositions("bob is a chowder head bob bob sldfjl", "bob");
// list will contain 0, 22, 26
For disabling a button add css class disabled
to it . write
$("button").addClass('disabled')
There are two aspects to your questions: what are the technical aspects of using const
instead of var
and what are the human-related aspects of doing so.
The technical difference is significant. In compiled languages, a constant will be replaced at compile-time and its use will allow for other optimizations like dead code removal to further increase the runtime efficiency of the code. Recent (loosely used term) JavaScript engines actually compile JS code to get better performance, so using the const keyword would inform them that the optimizations described above are possible and should be done. This results in better performance.
The human-related aspect is about the semantics of the keyword. A variable is a data structure that contains information that is expected to change. A constant is a data structure that contains information that will never change. If there is room for error, var
should always be used. However, not all information that never changes in the lifetime of a program needs to be declared with const
. If under different circumstances the information should change, use var
to indicate that, even if the actual change doesn't appear in your code.
I tried use [disabled]="!editmode"
but it not work in my case.
This is my solution [disabled]="!editmode ? 'disabled': null"
, I share for whom concern.
<button [disabled]="!editmode ? 'disabled': null"
(click)='loadChart()'>
<div class="btn-primary">Load Chart</div>
</button>
Nothing worked for me until I found iisexpress-proxy.
Open command prompt as administrator, then run
npm install -g iisexpress-proxy
then
iisexpress-proxy 51123 to 81
assuming your Visual Studio project opens on localhost:51123 and you want to access on external IP address x.x.x.x:81
Edit: I am currently using ngrok
strcpy example:
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[]="Sample string" ;
char str2[40] ;
strcpy (str2,str1) ;
printf ("str1: %s\n",str1) ;
return 0 ;
}
Output: str1: Sample string
Your case:
A simple =
operator should do the job.
string str1="Sample string" ;
string str2 = str1 ;
One can invoke mysqldump locally against a remote server.
Example that worked for me:
mysqldump -h hostname-of-the-server -u mysql_user -p database_name > file.sql
I followed the mysqldump documentation on connection options.
using $('#introVideo').modal('show');
conflicts with bootstrap proper triggering. When you click on the link that opens the Modal it will close right after completing the fade animation.
Just remove the $('#introVideo').modal('show');
(using bootstrap v3.3.2)
Here is my code:
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">_x000D_
<!-- triggering Link -->_x000D_
<a id="videoLink" href="#0" class="video-hp" data-toggle="modal" data-target="#introVideo"><img src="img/someImage.jpg">toggle video</a>_x000D_
_x000D_
_x000D_
<!-- Intro video -->_x000D_
<div class="modal fade" id="introVideo" tabindex="-1" role="dialog" aria-labelledby="introductionVideo" aria-hidden="true">_x000D_
<div class="modal-dialog modal-lg">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<div class="embed-responsive embed-responsive-16by9">_x000D_
<iframe class="embed-responsive-item allowfullscreen"></iframe>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"> </script>_x000D_
_x000D_
<script>_x000D_
//JS_x000D_
_x000D_
$('#videoLink').click(function () {_x000D_
var src = 'https://www.youtube.com/embed/VI04yNch1hU;autoplay=1';_x000D_
// $('#introVideo').modal('show'); <-- remove this line_x000D_
$('#introVideo iframe').attr('src', src);_x000D_
});_x000D_
_x000D_
_x000D_
$('#introVideo button.close').on('hidden.bs.modal', function () {_x000D_
$('#introVideo iframe').removeAttr('src');_x000D_
})_x000D_
</script>
_x000D_
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE
OBJECT_ID = OBJECT_ID(N'[dbo].[Person]') AND name = 'DateOfBirth')
BEGIN
ALTER TABLE [dbo].[Person] ADD DateOfBirth DATETIME
END
I would use Apache Ant, which has an API to call tasks from Java code rather than from an XML build file.
Project p = new Project();
p.init();
Zip zip = new Zip();
zip.setProject(p);
zip.setDestFile(zipFile); // a java.io.File for the zip you want to create
zip.setBasedir(new File("D:\\reports"));
zip.setIncludes("january/**");
zip.perform();
Here I'm telling it to start from the base directory D:\reports
and zip up the january
folder and everything inside it. The paths in the resulting zip file will be the same as the original paths relative to D:\reports
, so they will include the january
prefix.
For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request
Big thanks to @swapnil for trying to help me debug this.
const data = {
grant_type: USER_GRANT_TYPE,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
scope: SCOPE_INT,
username: DEMO_EMAIL,
password: DEMO_PASSWORD
};
axios.post(TOKEN_URL, Querystring.stringify(data))
.then(response => {
console.log(response.data);
USER_TOKEN = response.data.access_token;
console.log('userresponse ' + response.data.access_token);
})
.catch((error) => {
console.log('error ' + error);
});
const AuthStr = 'Bearer '.concat(USER_TOKEN);
axios.get(URL, { headers: { Authorization: AuthStr } })
.then(response => {
// If request is good...
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
char largeSrt[] = "123456789-123"; // original string
char * substr;
substr = strchr(largeSrt, '-'); // we save the new string "-123"
int substringLength = strlen(largeSrt) - strlen(substr); // 13-4=9 (bigger string size) - (new string size)
char *newStr = malloc(sizeof(char) * substringLength + 1);// keep memory free to new string
strcpy(newStr, largeSrt, substringLength); // copy only 9 characters
newStr[substringLength] = '\0'; // close the new string with final character
printf("newStr=%s\n", newStr);
free(newStr); // you free the memory
My take on Christians solution.
git archive --prefix=deploy/ master | tar -x -C $TMPDIR | rsync $TMPDIR/deploy/ --copy-links -av [email protected]:/home/user/my_app && rm -rf $TMPDIR/deploy
itemdescription
is shorter than 38 chars. Which is why the StringOutOfBoundsException
is being thrown.
Checking .length() > 0
simply makes sure the String
has some not-null value, what you need to do is check that the length is long enough. You could try:
if(itemdescription.length() > 38)
...
First Look at this example :
The C code for a simple C program is given below
struct Foo {
char a;
int b;
double c;
} foo1,foo2;
void foo_assign(void)
{
foo1 = foo2;
}
int main(/*char *argv[],int argc*/)
{
foo_assign();
return 0;
}
The Equivalent ASM Code for foo_assign() is
00401050 <_foo_assign>:
401050: 55 push %ebp
401051: 89 e5 mov %esp,%ebp
401053: a1 20 20 40 00 mov 0x402020,%eax
401058: a3 30 20 40 00 mov %eax,0x402030
40105d: a1 24 20 40 00 mov 0x402024,%eax
401062: a3 34 20 40 00 mov %eax,0x402034
401067: a1 28 20 40 00 mov 0x402028,%eax
40106c: a3 38 20 40 00 mov %eax,0x402038
401071: a1 2c 20 40 00 mov 0x40202c,%eax
401076: a3 3c 20 40 00 mov %eax,0x40203c
40107b: 5d pop %ebp
40107c: c3 ret
As you can see that a assignment is simply replaced by a "mov" instruction in assembly, the assignment operator simply means moving data from one memory location to another memory location. The assignment will only do it for immediate members of a structures and will fail to copy when you have Complex datatypes in a structure. Here COMPLEX means that you cant have array of pointers ,pointing to lists.
An array of characters within a structure will itself not work on most compilers, this is because assignment will simply try to copy without even looking at the datatype to be of complex type.
Here is a snippet for not only closing modals without page refresh but when pressing enter it submits modal and closes without refresh
I have it set up on my site where I can have multiple modals and some modals process data on submit and some don't. What I do is create a unique ID for each modal that does processing. For example in my webpage:
HTML (modal footer):
<div class="modal-footer form-footer"><br>
<span class="caption">
<button id="PreLoadOrders" class="btn btn-md green btn-right" type="button" disabled>Add to Cart <i class="fa fa-shopping-cart"></i></button>
<button id="ClrHist" class="btn btn-md red btn-right" data-dismiss="modal" data-original-title="" title="Return to Scan Order Entry" type="cancel">Cancel <i class="fa fa-close"></i></a>
</span>
</div>
jQUERY:
$(document).ready(function(){
// Allow enter key to trigger preloadorders form
$(document).keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
if($(".trigger").is(".ok"))
$("#PreLoadOrders").trigger("click");
else
return;
}
});
});
As you can see this submit performs processing which is why I have this jQuery for this modal. Now let's say I have another modal within this webpage but no processing is performed and since one modal is open at a time I put another $(document).ready()
in a global php/js script that all pages get and I give the modal's close button a class called: ".modal-close"
:
HTML:
<div class="modal-footer caption">
<button type="submit" class="modal-close btn default" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
jQuery (include global.inc):
$(document).ready(function(){
// Allow enter key to trigger a particular button anywhere on page
$(document).keypress(function(e) {
if(e.which == 13) {
if($(".modal").is(":visible")){
$(".modal:visible").find(".modal-close").trigger('click');
}
}
});
});
Is it a .sql file or is it compressed (.zip, .gz, etc)? Compressed formats sometimes require more PHP resources so you could try uncompressing it before uploading.
However, there are other methods you can try also. If you have command-line access, just upload the file and import with the command line client mysql
(once at the mysql>
prompt, use databasename;
then source file.sql
).
Otherwise you can use the phpMyAdmin "UploadDir" feature to put the file on the server and have it appear within phpMyAdmin without having to also upload it from your local machine.
This link has information on using UploadDir and this one has some more tips and methods.
When using github, note that you can also target a specific commit (for example, of a fork you've made and updated) by appending its commit hash to the end of its clone url. For example:
"dependencies": {
"example": "https://github.com/owner_name/repo_name.git#9203e6166b343d7d8b3bb638775b41fe5de3524c"
}
Or you can target a git commit in your local file system if you use your project's .git directory, like so (on Windows; note the forward slashes):
"dependencies": {
"example": "file://C:/Projects/my-project/.git#9203e6166b343d7d8b3bb638775b41fe5de3524c"
}
This is one way of testing library code you've committed locally but not yet pushed to the repo.
we can groupby the 'name' and 'month' columns, then call agg() functions of Panda’s DataFrame objects.
The aggregation functionality provided by the agg() function allows multiple statistics to be calculated per group in one calculation.
df.groupby(['name', 'month'], as_index = False).agg({'text': ' '.join})
I think what you are asking is the difference between RPC Literal, Document Literal and Document Wrapped SOAP web services.
Note that Document web services are delineated into literal and wrapped as well and they are different - one of the primary difference is that the latter is BP 1.1 compliant and the former is not.
Also, in Document Literal the operation to be invoked is not specified in terms of its name whereas in Wrapped, it is. This, I think, is a significant difference in terms of easily figuring out the operation name that the request is for.
In terms of RPC literal versus Document Wrapped, the Document Wrapped request can be easily vetted / validated against the schema in the WSDL - one big advantage.
I would suggest using Document Wrapped as the web service type of choice due to its advantages.
SOAP on HTTP is the SOAP protocol bound to HTTP as the carrier. SOAP could be over SMTP or XXX as well. SOAP provides a way of interaction between entities (client and servers, for example) and both entities can marshal operation arguments / return values as per the semantics of the protocol.
If you were using XML over HTTP (and you can), it is simply understood to be XML payload on HTTP request / response. You would need to provide the framework to marshal / unmarshal, error handling and so on.
A detailed tutorial with examples of WSDL and code with emphasis on Java: SOAP and JAX-WS, RPC versus Document Web Services
What you're looking for is indeed part of the ANSI standards SQL:92, SQL:1999 and SQL:2003, ie a UNIQUE constraint must disallow duplicate non-NULL values but accept multiple NULL values.
In the Microsoft world of SQL Server however, a single NULL is allowed but multiple NULLs are not...
In SQL Server 2008, you can define a unique filtered index based on a predicate that excludes NULLs:
CREATE UNIQUE NONCLUSTERED INDEX idx_yourcolumn_notnull
ON YourTable(yourcolumn)
WHERE yourcolumn IS NOT NULL;
In earlier versions, you can resort to VIEWS with a NOT NULL predicate to enforce the constraint.
You've got what rebase
does backwards. git rebase master
does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master
, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master
on top of the current branch.
Another way, using inline style and the spread operator
style={{
...completed ? { textDecoration: completed } : {}
}}
That way be useful in some situations where you want to add a bunch of properties at the same time base on the condition.
Do I need to double the size of the .box div to 400px by 400px to match the new high res background image
No, but you do need to set the background-size
property to match the original dimensions:
@media (-webkit-min-device-pixel-ratio: 2),
(min-resolution: 192dpi) {
.box{
background:url('images/[email protected]') no-repeat top left;
background-size: 200px 200px;
}
}
EDIT
To add a little more to this answer, here is the retina detection query I tend to use:
@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and ( min--moz-device-pixel-ratio: 2),
only screen and ( -o-min-device-pixel-ratio: 2/1),
only screen and ( min-device-pixel-ratio: 2),
only screen and ( min-resolution: 192dpi),
only screen and ( min-resolution: 2dppx) {
}
NB. This min--moz-device-pixel-ratio:
is not a typo. It is a well documented bug in certain versions of Firefox and should be written like this in order to support older versions (prior to Firefox 16).
- Source
As @LiamNewmarch mentioned in the comments below, you can include the background-size
in your shorthand background
declaration like so:
.box{
background:url('images/[email protected]') no-repeat top left / 200px 200px;
}
However, I personally would not advise using the shorthand form as it is not supported in iOS <= 6 or Android making it unreliable in most situations.
Just use the Class method using this foobar->foobarfunc();
I don't think location.LatLng
is working, however this works:
results[0].geometry.location.lat(), results[0].geometry.location.lng()
Found it while exploring Get Lat Lon source code.
There is no way to get the memory address of a value in Python 2.7 in general. In Jython or PyPy, the implementation doesn't even know your value's address (and there's not even a guarantee that it will stay in the same place—e.g., the garbage collector is allowed to move it around if it wants).
However, if you only care about CPython, id
is already returning the address. If the only issue is how to format that integer in a certain way… it's the same as formatting any integer:
>>> hex(33)
0x21
>>> '{:#010x}'.format(33) # 32-bit
0x00000021
>>> '{:#018x}'.format(33) # 64-bit
0x0000000000000021
… and so on.
However, there's almost never a good reason for this. If you actually need the address of an object, it's presumably to pass it to ctypes
or similar, in which case you should use ctypes.addressof
or similar.
With the module pygame.draw shapes like rectangles, circles, polygons, liens, ellipses or arcs can be drawn. Some examples:
pygame.draw.rect
draws filled rectangular shapes or outlines. The arguments are the target Surface (i.s. the display), the color, the rectangle and the optional outline width. The rectangle argument is a tuple with the 4 components (x, y, width, height), where (x, y) is the upper left point of the rectangle. Alternatively, the argument can be a pygame.Rect
object:
pygame.draw.rect(window, color, (x, y, width, height))
rectangle = pygame.Rect(x, y, width, height)
pygame.draw.rect(window, color, rectangle)
pygame.draw.circle
draws filled circles or outlines. The arguments are the target Surface (i.s. the display), the color, the center, the radius and the optional outline width. The center argument is a tuple with the 2 components (x, y):
pygame.draw.circle(window, color, (x, y), radius)
pygame.draw.polygon
draws filled polygons or contours. The arguments are the target Surface (i.s. the display), the color, a list of points and the optional contour width. Each point is a tuple with the 2 components (x, y):
pygame.draw.polygon(window, color, [(x1, y1), (x2, y2), (x3, y3)])
Minimal example:
import pygame
pygame.init()
window = pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill((255, 255, 255))
pygame.draw.rect(window, (0, 0, 255), (20, 20, 160, 160))
pygame.draw.circle(window, (255, 0, 0), (100, 100), 80)
pygame.draw.polygon(window, (255, 255, 0),
[(100, 20), (100 + 0.8660 * 80, 140), (100 - 0.8660 * 80, 140)])
pygame.display.flip()
pygame.quit()
exit()
use default convertation class: Convert.ToDecimal(Double)
If you're getting this error, you're probably trying to write to wwwroot
. By default this is not allowed, for good reason.
Instead, consider storing your files somewhere besides wwwroot
. If you just need to serve the files, store them in a folder outside of inetpub
and use a virtual directory to make them visible to IIS.
Original answer:
For those running IIS on Windows Server:
By default, the IIS user does not have write permissions for the wwwroot
folder. This can be solved by granting full permissions to the IIS_IUSRS
user for wwwroot
.
C:/inetpub/
IIS_IUSRS ([server name]\IIS_IUSRS)
.You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).
This is a good understanding of data-binding. I think you've got that down.
For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.
I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.
I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.
<div rotate-on-click="45"></div>
First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.
function rotate(deg, elem) {
$(elem).css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
}
function addRotateOnClick($elems) {
$elems.each(function(i, elem) {
var deg = 0;
$(elem).click(function() {
deg+= parseInt($(this).attr('rotate-on-click'), 10);
rotate(deg, this);
});
});
}
addRotateOnClick($('[rotate-on-click]'));
app.directive('rotateOnClick', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var deg = 0;
element.bind('click', function() {
deg+= parseInt(attrs.rotateOnClick, 10);
element.css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
});
}
};
});
Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link
function (or compile
function).
Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.
This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?
The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.
Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:
Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.
Here are some things that modern frameworks are providing:
Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.
If you need to destroy a planet and you have a Death Star, use the Death star.
Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.
In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:
<clock></clock>
Done.
Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.
Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.
THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.
Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.
How about using recursive functions?
To get a value:
def getFromDict(dataDict, maplist):
first, rest = maplist[0], maplist[1:]
if rest:
# if `rest` is not empty, run the function recursively
return getFromDict(dataDict[first], rest)
else:
return dataDict[first]
And to set a value:
def setInDict(dataDict, maplist, value):
first, rest = maplist[0], maplist[1:]
if rest:
try:
if not isinstance(dataDict[first], dict):
# if the key is not a dict, then make it a dict
dataDict[first] = {}
except KeyError:
# if key doesn't exist, create one
dataDict[first] = {}
setInDict(dataDict[first], rest, value)
else:
dataDict[first] = value
DON'T USE A TRANSAPENT OR NULL LAYOUT because then the button (or the generic view) will no more highlight at click!!!
I had the same problem and finally I found the correct attribute from Android API to solve the problem. It can apply to any view.
Use this in the button specifications:
android:background="?android:selectableItemBackground"
Whenever I'm testing something with PHP/Curl, I try it from the command line first, figure out what works, and then port my options to PHP.
Yes, let's use Select
as an example
sample code: Columns("A").select
How to loop through Columns:
Method 1: (You can use index to replace the Excel Address)
For i = 1 to 100
Columns(i).Select
next i
Method 2: (Using the address)
For i = 1 To 100
Columns(Columns(i).Address).Select
Next i
EDIT: Strip the Column for OP
columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")
e.g. you want to get the 27th Column --> AA, you can get it this way
I use SDL_GetTicks from the SDL library.
No matter what $action is, it will always either not be "add" OR not be "delete", which is why the if condition always passes. What you want is to use && instead of ||:
(!isset($action)) || ($action !="add" && $action !="delete"))
I was trying to call a REST endpoint from a microservice and I was using the resttemplate's put method.
In my design if any error occurred inside the REST endpoint it should return a JSON error response, it was working for some calls but not for this put one, it returned the white label error page instead.
So I did some investigation and I found out that;
Spring try to understand the caller if it is a machine then it returns JSON response or if it is a browser than it returns the white label error page HTML.
As a result: my client app needed to say to REST endpoint that the caller is a machine, not a browser so for this the client app needed to add 'application/json' into the ACCEPT header explicitly for the resttemplate's 'put' method. I added this to the header and solved the problem.
my call to the endpoint:
restTemplate.put(url, request, param1, param2);
for above call I had to add below header param.
headers.set("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
or I tried to change put to exchange as well, in this case, exchange call added the same header for me and solved the problem too but I don't know why :)
restTemplate.exchange(....)
Using html5 I cooked up this one:
Some where on the page:
<h2 id="heading" data-activetab="@ViewBag.activetab">Some random text</h2>
The viewbag should just contain the id for the page/element eg.: "testing"
I created a site.js and added the scrip on the page:
/// <reference path="../jquery-2.1.0.js" />
$(document).ready(
function() {
var setactive = $("#heading").data("activetab");
var a = $('#' + setactive).addClass("active");
}
)
Now all you have to do is to add your id's to your navbar. Eg.:
<ul class="nav navbar-nav">
<li **id="testing" **>
@Html.ActionLink("Lalala", "MyAction", "MyController")
</li>
</ul>
All hail the data attribute :)
Add below method in your activity class.Here browser is nothing but your webview object.
Now you can view web contain page wise easily.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && browser.canGoBack()) {
browser.goBack();
return true;
}
return false;
}
http://blueimp.github.com/jQuery-File-Upload/ = great solution
According to their docs, the following browsers support drag & drop:
So return; does not really terminate your java program, it only terminates your java function (void). Because in your case the function is the main function of your application, return; will also terminate the application. But the return; in your example is useless, because the function will terminate directly after this return anyway...
The System.exit() will completly terminate your program and it will close any open window.
Through Android Studio:
TO ADD: @Christopher's answer does not work on API 7/8 (as per @Jonny's correct comment) IF you are using colours, instead of drawables. (In my testing, using drawables as per Christopher works fine)
Here is the FIX for 2.3 and below when using colours:
As per @Charles Harley, there is a bug in 2.3 and below where filling the list item with a colour causes the colour to flow out over the whole list. His fix is to define a shape
drawable containing the colour you want, and to use that instead of the colour.
I suggest looking at this link if you want to just use a colour as selector, and are targeting Android 2 (or at least allow for Android 2).
Simply remove the .value
from your code.
Set envFrmwrkPath = ActiveSheet.Range("D6").Value
instead of this, use:
Set envFrmwrkPath = ActiveSheet.Range("D6")
I had the same issue but have not found the maintenance.flag file in my Magento root. I simply deleted cache and sessions files and all worked again.
There is no difference in terms of functionality
The addwithvalue
method takes an object as the value. There is no type data type checking. Potentially, that could lead to error if data type does not match with SQL table. The add
method requires that you specify the Database type first. This helps to reduce such errors.
For more detail Please click here
This works for me.
Create a network with
docker network create --subnet=172.17.0.0/16 selnet
Run docker image
docker run --net selnet --ip 172.18.0.2 hub
At first, I got
docker: Error response from daemon: Invalid address 172.17.0.2: It does not belong to any of this network's subnets.
ERRO[0000] error waiting for container: context canceled
Solution: Increased the 2nd quadruple of the IP [.18. instead of .17.]
It may work with any character from the HTML Escape character list, but I had the same problem with a Java project. I used StringEscapeUtils.escapeHTML("Testing \" <br> <p>")
and the title was <a href=".." title="Test" <br> <p>">Testing</a>
.
It only worked for me when I changed the StringEscapeUtils to StringEscapeUtils.escapeJavascript("Testing \" <br> <p>")
and it worked in every browser.
Seems like you posted a new question after you realized that you were dealing with a simpler problem related to size_t
. I am glad that you did.
Anyways, You have a .c
source file, and most of the code looks as per C standards, except that #include <iostream>
and using namespace std;
C equivalent for the built-in functions of C++ standard #include<iostream>
can be availed through #include<stdio.h>
#include <iostream>
with #include <stdio.h>
, delete using namespace std;
With #include <iostream>
taken off, you would need a C standard alternative for cout << endl;
, which can be done by printf("\n");
or putchar('\n');
Out of the two options, printf("\n");
works the faster as I observed.
When used printf("\n");
in the code above in place of cout<<endl;
$ time ./thread.exe
1 2 3 4 5 6 7 8 9 10
real 0m0.031s
user 0m0.030s
sys 0m0.030s
When used putchar('\n');
in the code above in place of cout<<endl;
$ time ./thread.exe
1 2 3 4 5 6 7 8 9 10
real 0m0.047s
user 0m0.030s
sys 0m0.030s
Compiled with Cygwin gcc (GCC) 4.8.3
version. results averaged over 10 samples. (Took me 15 mins)
Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.
<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
<li class = "ui-divider">
{{ meter.DESCRIPTION }}
{{ htmlgeneration() }}
</li>
</ul>
Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:
Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:
Rory Gallagher Guitar
Gerry McAvoy Bass
Rod de'Ath Drums
Lou Martin Keyboards
Donkey Kong Sioux Self-Appointed Semi-official Stomper
Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)
Save the file as a CSV file.
Copy the contents of the CSV file to the clipboard
Verify that the "First row is column names" checkbox is checked
Paste the CSV data into the content area
Mash the "Convert CSV to JSON" button
With the data shown above, you will now have:
[
{
"MUSICIAN":"Rory Gallagher",
"INSTRUMENT":"Guitar"
},
{
"MUSICIAN":"Gerry McAvoy",
"INSTRUMENT":"Bass"
},
{
"MUSICIAN":"Rod D'Ath",
"INSTRUMENT":"Drums"
},
{
"MUSICIAN":"Lou Martin",
"INSTRUMENT":"Keyboards"
}
{
"MUSICIAN":"Donkey Kong Sioux",
"INSTRUMENT":"Self-Appointed Semi-Official Stomper"
}
]
With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.
Go here: http://jsonlint.com/
Paste the JSON into the content area
Pres the "Validate" button.
If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.
:: short answer :
:: perl -MCPAN -e "install PAR::Packer"
pp -o <<DesiredExeName>>.exe <<MyFancyPerlScript>>
:: long answer - create the following cmd , adjust vars to your taste ...
:: next_line_is_templatized
:: file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
:: disable the echo
@echo off
:: this is part of the name of the file - not used
set _Action=run
:: the name of the Product next_line_is_templatized
set _ProductName=morphus
:: the version of the current Product next_line_is_templatized
set _ProductVersion=1.2.3
:: could be dev , test , dev , prod next_line_is_templatized
set _ProductType=dev
:: who owns this Product / environment next_line_is_templatized
set _ProductOwner=ysg
:: identifies an instance of the tool ( new instance for this version could be created by simply changing the owner )
set _EnvironmentName=%_ProductName%.%_ProductVersion%.%_ProductType%.%_ProductOwner%
:: go the run dir
cd %~dp0
:: do 4 times going up
for /L %%i in (1,1,5) do pushd ..
:: The BaseDir is 4 dirs up than the run dir
set _ProductBaseDir=%CD%
:: debug echo BEFORE _ProductBaseDir is %_ProductBaseDir%
:: remove the trailing \
IF %_ProductBaseDir:~-1%==\ SET _ProductBaseDir=%_ProductBaseDir:~0,-1%
:: debug echo AFTER _ProductBaseDir is %_ProductBaseDir%
:: debug pause
:: The version directory of the Product
set _ProductVersionDir=%_ProductBaseDir%\%_ProductName%\%_EnvironmentName%
:: the dir under which all the perl scripts are placed
set _ProductVersionPerlDir=%_ProductVersionDir%\sfw\perl
:: The Perl script performing all the tasks
set _PerlScript=%_ProductVersionPerlDir%\%_Action%_%_ProductName%.pl
:: where the log events are stored
set _RunLog=%_ProductVersionDir%\data\log\compile-%_ProductName%.cmd.log
:: define a favorite editor
set _MyEditor=textpad
ECHO Check the variables
set _
:: debug PAUSE
:: truncate the run log
echo date is %date% time is %time% > %_RunLog%
:: uncomment this to debug all the vars
:: debug set >> %_RunLog%
:: for each perl pm and or pl file to check syntax and with output to logs
for /f %%i in ('dir %_ProductVersionPerlDir%\*.pl /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a %_RunLog% 2>&1
:: for each perl pm and or pl file to check syntax and with output to logs
for /f %%i in ('dir %_ProductVersionPerlDir%\*.pm /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a %_RunLog% 2>&1
:: now open the run log
cmd /c start /max %_MyEditor% %_RunLog%
:: this is the call without debugging
:: old
echo CFPoint1 OK The run cmd script %0 is executed >> %_RunLog%
echo CFPoint2 OK compile the exe file STDOUT and STDERR to a single _RunLog file >> %_RunLog%
cd %_ProductVersionPerlDir%
pp -o %_Action%_%_ProductName%.exe %_PerlScript% | tee -a %_RunLog% 2>&1
:: open the run log
cmd /c start /max %_MyEditor% %_RunLog%
:: uncomment this line to wait for 5 seconds
:: ping localhost -n 5
:: uncomment this line to see what is happening
:: PAUSE
::
:::::::
:: Purpose:
:: To compile every *.pl file into *.exe file under a folder
:::::::
:: Requirements :
:: perl , pp , win gnu utils tee
:: perl -MCPAN -e "install PAR::Packer"
:: text editor supporting <<textEditor>> <<FileNameToOpen>> cmd call syntax
:::::::
:: VersionHistory
:: 1.0.0 --- 2012-06-23 12:05:45 --- ysg --- Initial creation from run_morphus.cmd
:::::::
:: eof file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
from validate_email import validate_email
is_valid = validate_email('[email protected]',verify=True)
print(bool(is_valid))
See validate_email docs.
One work-around is to right-click on the result set and select "Save Results As...". This exports it to a CSV file with the entire contents of the column. Not perfect but worked well enough for me.
some thing as follows ::
Add this After the body tag
This is a rough sketch, you will need to modify it according to your needs.
<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");
var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");
var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");
f.appendChild(i);
f.appendChild(s);
//and some more input elements here
//and dont forget to add a submit button
document.getElementsByTagName('body')[0].appendChild(f);
</script>
I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
If you want to keep the heredoc indented for readability:
$ perl -pe 's/^\s*//' << EOF
line 1
line 2
EOF
The built-in method for supporting indented heredoc in Bash only supports leading tabs, not spaces.
Perl can be replaced with awk to save a few characters, but the Perl one is probably easier to remember if you know basic regular expressions.
To Move
item in list simply add:
// move item to index 0
Object object = ObjectList.get(index);
ObjectList.remove(index);
ObjectList.add(0,object);
To Swap
two items in list simply add:
// swap item 10 with 20
Collections.swap(ObjectList,10,20);
The simplest way is to create a VBA macro that wraps that function, like so:
Function UserNameWindows() As String
UserName = Environ("USERNAME")
End Function
Then call it from the cell:
=UserNameWindows()
See this article for more details, and other ways.
For people using jQuery, there is an excellent plugin for handling key events:
For capturing ?+S and Ctrl+S I'm using this:
$(window).bind('keydown.ctrl_s keydown.meta_s', function(event) {
event.preventDefault();
// Do something here
});
This should work in most versions of django, I am using it in 1.6.5:
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
urlpatterns = patterns('',
....
url(r'^(?P<location_id>\d+)/$', lambda x, location_id: HttpResponseRedirect(reverse('dailyreport_location', args=[location_id])), name='location_stats_redirect'),
....
)
You can still use the name of the url pattern instead of a hard coded url with this solution. The location_id parameter from the url is passed down to the lambda function.
I found what I think is a faster solution. Install Git for Windows from here: http://git-scm.com/download/win
That automatically adds its path to the system variable during installation if you tell the installer to do so (it asks for that). So you don't have to edit anything manually.
Just close and restart Android Studio if it's open and you're ready to go.
Try this:
header('location: xyz.php'); //thats all for redirecting to another php file
Just override the OnCreate method of FirebaseMessagingService. It is called when your app is in background:
public override void OnCreate()
{
// your code
base.OnCreate();
}
It is possible, just overwrite the Recaptcha Ajax callbacks. Working jsfiddle: http://jsfiddle.net/Vanit/Qu6kn/
You don't even need a proxy div because with the overwrites the DOM code won't execute. Call Recaptcha.reload() whenever you want to trigger the callbacks again.
function doSomething(challenge){
$(':input[name=recaptcha_challenge_field]').val(challenge);
$('img.recaptcha').attr('src', '//www.google.com/recaptcha/api/image?c='+challenge);
}
//Called on Recaptcha.reload()
Recaptcha.finish_reload = function(challenge,b,c){
doSomething(challenge);
}
//Called on page load
Recaptcha.challenge_callback = function(){
doSomething(RecaptchaState.challenge)
}
Recaptcha.create("YOUR_PUBLIC_KEY");
HEAD is short for current branch so git push -u origin HEAD works. Now to avoid this typing everytime I use alias:
git config --global alias.pp 'push -u origin HEAD'
After this, everytime I want to push branch created via git -b branch I can push it using:
git pp
Hope this saves time for someone!
A struct is a value type and a value type must have a default value as soon as it is declared.
MyClass m;
MyStruct m2;
If you declare two fields as above without instantiating either, then break the debugger, m
will be null but m2
will not. Given this, a parameterless constructor would make no sense, in fact all any constructor on a struct does is assign values, the thing itself already exists just by declaring it. Indeed m2 could quite happily be used in the above example and have its methods called, if any, and its fields and properties manipulated!
Riffing on a side question asked by the OP in a comment, i.e.:
what if I had a generator that yields the values from range(11) instead of a list. Would it be possible to replace values in the generator?
Sure, it's trivially easy...:
def replaceiniter(it, predicate, replacement=None):
for item in it:
if predicate(item): yield replacement
else: yield item
Just pass any iterable (including the result of calling a generator) as the first arg, the predicate to decide if a value must be replaced as the second arg, and let 'er rip.
For example:
>>> list(replaceiniter(xrange(11), lambda x: x%2))
[0, None, 2, None, 4, None, 6, None, 8, None, 10]
I always set the max like this:
<EditText
android:id="@+id/edit_blaze_it
android:layout_width="0dp"
android:layout_height="@dimen/too_high"
<!-- This is the line you need to write to set the max-->
android:maxLength="420"
/>
If you are using SQL Server:
ORDER_BY cast(registration_no as int) ASC
Here is the ES6 version:
let getTimeAfter30Mins = () => {
let timeAfter30Mins = new Date();
timeAfter30Mins = new Date(timeAfter30Mins.setMinutes(timeAfter30Mins.getMinutes() + 30));
};
Call it like:
getTimeAfter30Mins();
In Ubuntu with php7.3:
sudo apt install php7.3-soap
sudo service apache2 restart
Input Dimension Clarified:
Not a direct answer, but I just realized the word Input Dimension could be confusing enough, so be wary:
It (the word dimension alone) can refer to:
a) The dimension of Input Data (or stream) such as # N of sensor axes to beam the time series signal, or RGB color channel (3): suggested word=> "InputStream Dimension"
b) The total number /length of Input Features (or Input layer) (28 x 28 = 784 for the MINST color image) or 3000 in the FFT transformed Spectrum Values, or
"Input Layer / Input Feature Dimension"
c) The dimensionality (# of dimension) of the input (typically 3D as expected in Keras LSTM) or (#RowofSamples, #of Senors, #of Values..) 3 is the answer.
"N Dimensionality of Input"
d) The SPECIFIC Input Shape (eg. (30,50,50,3) in this unwrapped input image data, or (30, 250, 3) if unwrapped Keras:
Keras has its input_dim refers to the Dimension of Input Layer / Number of Input Feature
model = Sequential()
model.add(Dense(32, input_dim=784)) #or 3 in the current posted example above
model.add(Activation('relu'))
In Keras LSTM, it refers to the total Time Steps
The term has been very confusing, is correct and we live in a very confusing world!!
I find one of the challenge in Machine Learning is to deal with different languages or dialects and terminologies (like if you have 5-8 highly different versions of English, then you need to very high proficiency to converse with different speakers). Probably this is the same in programming languages too.
Oracle: Get a list of the full datatype in your table:
select data_type || '(' || data_length || ')'
from user_tab_columns where TABLE_NAME = 'YourTableName'
For the Spring Tool Suit (Extension of Eclipse), in Windows is
Alt + Shift + Q, C
This is my awesome solution for a div
with a dynamic (percentaged) height.
CSS
.vertical_placer{
background:red;
position:absolute;
height:43%;
width:100%;
display: table;
}
.inner_placer{
display: table-cell;
vertical-align: middle;
text-align:center;
}
.inner_placer svg{
position:relative;
color:#fff;
background:blue;
width:30%;
min-height:20px;
max-height:60px;
height:20%;
}
HTML
<div class="footer">
<div class="vertical_placer">
<div class="inner_placer">
<svg> some Text here</svg>
</div>
</div>
</div>
check this out dude
<?php
// we connect to example.com and port 3307
$link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
// we connect to localhost at port 3307
$link = mysql_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
Here's what worked for me:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<false/>
<key>NSExceptionDomains</key>
<dict>
<key><!-- your_remote_server.com / localhost --></key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<true/>
</dict>
<!-- add more domain here -->
</dict>
</dict>
I just wanna add this to help others and save some time:
if you are using: CFStreamCreatePairWithSocketToHost
. make sure your host
is the same with what you have in your .plist
or if you have separate domain for socket just add it there.
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)/*from .plist*/, (unsigned int)port, &readStream, &writeStream);
Hope this is helpful. Cheers. :)
Multiple parameters:
bounds.extend(marker.position);
bindInfoWindow(marker, map, infowindow,
'<b>' + response[i].driver_name + '</b><br>' +
'<b>' + moment(response[i].updated_at).fromNow() + '</b>
<button onclick="myFunction(\'' + response[i].id + '\',\'' + driversList + '\')">Click me</button>'
);
You could do it with the requests module as well:
url = 'http://winterolympicsmedals.com/medals.csv'
r = requests.get(url)
text = r.iter_lines()
reader = csv.reader(text, delimiter=',')
Here I want to share another method that prevent the error of model backing when context changed is:
1) Open your DbContext File
2) Add namespace using Microsoft.AspNet.Identity.EntityFramework;
3) public MyDbContext() : base("name=MyDbContext") { Database.SetInitializer(new DropCreateDatabaseAlways()); }
According to React philosophy component can't change its props. they should be received from the parent and should be immutable. Only parent can change the props of its children.
nice explanation on state vs props
also, read this thread Why can't I update props in react.js?
If you want to use android R
class
textView.setBackgroundColor(ContextCompat.getColor(getActivity(), android.R.color.transparent));
and don't forget to add support library to Gradle file
compile 'com.android.support:support-v4:23.3.0'
If you want to change Status Bar Style from the launch screen, You should take this way.
That isn't too easy to do with CSS, as it's not a behavioral language (ie JavaScript), the only easy way would be to use a JavaScript OnClick Event on your anchor and to return it as false, this is probably the shortest code you could use for that:
<a href="page.html" onclick="return false">page link</a>
Not exactly. You can't get two Stream
s out of one; this doesn't make sense -- how would you iterate over one without needing to generate the other at the same time? A stream can only be operated over once.
However, if you want to dump them into a list or something, you could do
stream.forEach((x) -> ((x == 0) ? heads : tails).add(x));
Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.
That option could be useful when copying very large files over a potentially unstable connection.
Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.
the probleme of these array of function are not in the "array form" but in the way these functions are called... then... try this.. with a simple eval()...
array_of_function = ["fx1()","fx2()","fx3()",.."fxN()"]
var zzz=[];
for (var i=0; i<array_of_function.length; i++)
{ var zzz += eval( array_of_function[i] ); }
it work's here, where nothing upper was doing the job at home... hopes it will help
This Method to get Google Username:
public String getUsername() {
AccountManager manager = AccountManager.get(this);
Account[] accounts = manager.getAccountsByType("com.google");
List<String> possibleEmails = new LinkedList<String>();
for (Account account : accounts) {
// TODO: Check possibleEmail against an email regex or treat
// account.name as an email address only for certain account.type
// values.
possibleEmails.add(account.name);
}
if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
String email = possibleEmails.get(0);
String[] parts = email.split("@");
if (parts.length > 0 && parts[0] != null)
return parts[0];
else
return null;
} else
return null;
}
simple this method call ....
And Get Google User in Gmail id::
accounts = AccountManager.get(this).getAccounts();
Log.e("", "Size: " + accounts.length);
for (Account account : accounts) {
String possibleEmail = account.name;
String type = account.type;
if (type.equals("com.google")) {
strGmail = possibleEmail;
Log.e("", "Emails: " + strGmail);
break;
}
}
After add permission in manifest;
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
To add on nathan gonzalez answer, please note you need to assign the replaced object after calling replace
function since it is not a mutator function:
myString = myString.replace('username1','');
==
is the correct operator to compare strings in Go. However, the strings that you read from STDIN with reader.ReadString
do not contain "a"
, but "a\n"
(if you look closely, you'll see the extra line break in your example output).
You can use the strings.TrimRight
function to remove trailing whitespaces from your input:
if strings.TrimRight(input, "\n") == "a" {
// ...
}
If using Visual Code one option is to add this to the settings.json file:
"eslint.options": {
"useEslintrc": false,
"parserOptions": {
"ecmaVersion": 2017
},
"env": {
"es6": true
}
}
There is a lot of incompatibility between different versions of cglib and lots of poor advice that can be googled on this subject (use ancient versions of cglib-nodeb, etc). After wrestling with this nonsense for 3 days with an ancient version of Spring (2.5.6)I have discovered:
If you really need single quotes, apostrophes, you can use
html | numeric | hex
‘ | ‘ | ‘ // for the left/beginning single-quote and
’ | ’ | ’ // for the right/ending single-quote
You should consider to specify SMTP configuration data in config file and do not overwrite them in a code - see SMTP configuration data at http://www.systemnetmail.com/faq/4.1.aspx
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="[email protected]">
<network defaultCredentials="false" host="smtp.example.com" port="25" userName="[email protected]" password="password"/>
</smtp>
</mailSettings>
</system.net>
Given
std::vector<Rule>& topPriorityRules;
The correct way to remove the first element of the referenced vector is
topPriorityRules.erase(topPriorityRules.begin());
which is exactly what you suggested.
Looks like i need to do iterator overloading.
There is no need to overload an iterator in order to erase first element of std::vector
.
P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front.
Yes. You need to stringify
the JSON
data orlse 400 bad request
error occurs as it cannot identify the data.
400 Bad Request
Bad Request. Your browser sent a request that this server could not understand.
Plus you need to add content type
and datatype
as well. If not you will encounter 415
error which says Unsupported Media Type
.
415 Unsupported Media Type
Try this.
var newData = {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work", "facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
};
var dataJson = JSON.stringify(newData);
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: dataJson,
error: function(e) {
console.log(e);
},
dataType: "json",
contentType: "application/json"
});
With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.
I was getting the same error on my Ubuntu 16.04 (Linux 4.14 kernel) in Google Compute Engine with K80 GPU. I upgraded the kernel to 4.15 from 4.14 and boom the problem was solved. Here is how I upgraded my Linux kernel from 4.14 to 4.15:
Step 1:
Check the existing kernel of your Ubuntu Linux:
uname -a
Step 2:
Ubuntu maintains a website for all the versions of kernel that have
been released. At the time of this writing, the latest stable release
of Ubuntu kernel is 4.15. If you go to this
link: http://kernel.ubuntu.com/~kernel-ppa/mainline/v4.15/, you will
see several links for download.
Step 3:
Download the appropriate files based on the type of OS you have. For 64
bit, I would download the following deb files:
wget http://kernel.ubuntu.com/~kernel-ppa/mainline/v4.15/linux-headers-
4.15.0-041500_4.15.0-041500.201802011154_all.deb
wget http://kernel.ubuntu.com/~kernel-ppa/mainline/v4.15/linux-headers-
4.15.0-041500-generic_4.15.0-041500.201802011154_amd64.deb
wget http://kernel.ubuntu.com/~kernel-ppa/mainline/v4.15/linux-image-
4.15.0-041500-generic_4.15.0-041500.201802011154_amd64.deb
Step 4:
Install all the downloaded deb files:
sudo dpkg -i *.deb
Step 5:
Reboot your machine and check if the kernel has been updated by:
uname -a
You should see that your kernel has been upgraded and hopefully nvidia-smi should work.
What is blob url? Why it is used?
BLOB is just byte sequence. Browser recognize it as byte stream. It is used to get byte stream from source.
A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.
Can i make my own blob url on a server?
Yes you can there are serveral ways to do so for example try http://php.net/manual/en/function.ibase-blob-echo.php
Read more on
The trick here is to put the library AFTER the module you are compiling. The problem is a reference thing. The linker resolves references in order, so when the library is BEFORE the module being compiled, the linker gets confused and does not think that any of the functions in the library are needed. By putting the library AFTER the module, the references to the library in the module are resolved by the linker.
scp -r C:/site user@server_ip:path
path
is the place, where site
will be copied into the remote server
EDIT: As I said in my comment, try pscp
, as you want to use scp
using PuTTY
.
The other option is WinSCP
You could:
Define a userStatus
parameter for the child component and provide the value when using this component from the parent:
@Component({
(...)
})
export class Profile implements OnInit {
@Input()
userStatus:UserStatus;
(...)
}
and in the parent:
<profile [userStatus]="userStatus"></profile>
Inject the parent into the child component:
@Component({
(...)
})
export class Profile implements OnInit {
constructor(app:App) {
this.userStatus = app.userStatus;
}
(...)
}
Be careful about cyclic dependencies between them.
The advantage to a single CSS file is transfer efficiency. Each HTTP request means a HTTP header response for each file requested, and that takes bandwidth.
I serve my CSS as a PHP file with the "text/css" mime type in the HTTP header. This way I can have multiple CSS files on the server side and use PHP includes to push them into a single file when requested by the user. Every modern browser receives the .php file with the CSS code and processes it as a .css file.
If you change a login user credential or add new login user then after you need to log in then you will have to restart the SQL Server Service. for that
Then go to SQL Server(MSSQLSERVER) and stop and start again
Now try to log in, I hope You can.
Thanks
$("tr.item").each(function() {
$this = $(this);
var value = $this.find("span.value").html();
var quantity = $this.find("input.quantity").val();
});
Classes also work well, such as:
<style>
form input .checkbox
{
/* your checkbox styling */
}
</style>
<form>
<input class="checkbox" type="checkbox" />
</form>
in case the above does not work for you. for me this did not for some reasons;
the UNIX numbers i am working on are from the Mozilla place.sqlite dates.
to make it work : i splitted the UNIX cells into two cells : one of the first 10 numbers (the date) and the other 4 numbers left (the seconds i believe)
Then i used this formula, =(A1/86400)+25569 where A1 contains the cell with the first 10 number; and it worked
FOR METEOR USERS:
moment locales are not installed by default in meteor, you only get the 'en' locale with the default installation.
So you use the code as shown correctly in other answers:
moment.locale('it').format('LLL');
but it will remain in english until you install the locale you need.
There is a nice, clean way of adding individual locales for moment in meteor (supplied by rzymek).
Install the moment package in the usual meteor way with:
meteor add rzymek:moment
Then just add the locales that you need, e.g. for italian:
meteor add rzymek:moment-locale-it
Or if you really want to add all available locales (adds about 30k to your page):
meteor add rzymek:moment-locales
If you want more compact code, I suggest using Apache Commons DbUtils. In this case:
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = // Retrieve connection
stmt = conn.prepareStatement(// Some SQL);
rs = stmt.executeQuery();
} catch(Exception e) {
// Error Handling
} finally {
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(stmt);
DbUtils.closeQuietly(conn);
}
CURL error code 7 (CURLE_COULDNT_CONNECT)
is very explicit ... it means Failed to connect() to host or proxy.
The following code would work on any system:
$ch = curl_init("http://google.com"); // initialize curl handle
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
print($data);
If you can not see google page then .. your URL is wrong
or you have some firewall
or restriction
issue.
See this; run
sudo update-java-alternatives --list
to list off all the Java installations on a machine by name and directory, and then run
sudo update-java-alternatives --set [JDK/JRE name e.g. java-8-oracle]
to choose which JRE/JDK to use.
If you want to use different JDKs/JREs for each Java task, you can run update-alternatives to configure one java executable at a time; you can run
sudo update-alternatives --config java[Tab]
to see the Java commands that can be configured (java, javac, javah, javaws, etc). And then
sudo update-alternatives --config [javac|java|javadoc|etc.]
will associate that Java task/command to a particular JDK/JRE.
You may also need to set JAVA_HOME for some applications: from this answer you can use
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")
for JREs, or
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:jre/bin/java::")
for JDKs.
I always use the isoformat()
function for this.
from datetime import date
today = date.today().isoformat()
print(today) # '2018-12-05'
Note that this also works on datetime objects if you need the time in standard format as well.
from datetime import datetime
now = datetime.today().isoformat()
print(now) # '2018-12-05T11:15:55.126382'
mysqli_error() needs you to pass the connection to the database as a parameter. Documentation here has some helpful examples:
http://php.net/manual/en/mysqli.error.php
Try altering your problem line like so and you should be in good shape:
$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error($myConnection));
This is answered in the Protractor FAQ: https://github.com/angular/protractor/blob/master/docs/faq.md#the-result-of-gettext-from-an-input-element-is-always-empty
The result of getText from an input element is always empty
This is a webdriver quirk. and elements always have empty getText values. Instead, try:
element.getAttribute('value')
As for question 2, yes, you should be able to use a fully qualified name for by.binding. I suspect that your template does not actually having an element that is bound to risk.name via {{}} or ng-bind.
This answer goes over some of the cases that have not been discussed above.
The return statement allows you to terminate the execution of a function before you reach the end. This causes the flow of execution to immediately return to the caller.
In line number 4:
def ret(n):
if n > 9:
temp = "two digits"
return temp #Line 4
else:
temp = "one digit"
return temp #Line 8
print("return statement")
ret(10)
After the conditional statement gets executed the ret()
function gets terminated due to return temp
(line 4).
Thus the print("return statement")
does not get executed.
Output:
two digits
This code that appears after the conditional statements, or the place the flow of control cannot reach, is the dead code.
Returning Values
In lines number 4 and 8, the return statement is being used to return the value of a temporary variable after the condition has been executed.
To bring out the difference between print and return:
def ret(n):
if n > 9:
print("two digits")
return "two digits"
else :
print("one digit")
return "one digit"
ret(25)
Output:
two digits
'two digits'
I've found a solution worked for me:
const handleDownload = async () => {
const req = await axios({
method: "get",
url: `/companies/${company.id}/data`,
responseType: "blob",
});
var blob = new Blob([req.data], {
type: req.headers["content-type"],
});
const link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = `report_${new Date().getTime()}.xlsx`;
link.click();
};
I just point a responseType: "blob"
DateTime dateTime = DateTime.Now ;
string today = dateTime.DayOfWeek.ToString();
string yesterday = dateTime.AddDays(-1).DayOfWeek.ToString(); //Fetch day i.e. Mon, Tues
string result = dateTime.AddDays(-1).ToString("yyyy-MM-dd");
The above snippet will work. It is also advisable to make single instance of DateTime.Now;
You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.
I would suggest you to don't modify web.config from your, because every time when change, it will restart your application.
However you can read web.config using System.Configuration.ConfigurationManager.AppSettings
checked
attribute is a boolean value so "checked"
value of other "string"
except boolean false
converts to true
.
Any string value will be true. Also presence of attribute make it true:
<input type="checkbox" checked>
You can make it uncheked only making boolean change in DOM using JS.
So the answer is: they are equal.
Old post but might help someone.
For me it happened because I renamed Assembly name
and Default namespace
of the project.
So I had to update ContextKey
in _MigrationHisotry
table to the new value of Assembly name
or Default namespace
. Honestly I don't know which one should be used, because for me both are same!
You can set CustomFormat property to "dd-MM-yyyy" in design mode and use dateTimePicker1.Text property to fetch string in "dd/MM/yyyy" format irrespective of display format.
An example using built in TimeUnit
.
long uptime = System.currentTimeMillis();
long days = TimeUnit.MILLISECONDS
.toDays(uptime);
uptime -= TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS
.toHours(uptime);
uptime -= TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS
.toMinutes(uptime);
uptime -= TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS
.toSeconds(uptime);
$ch = curl_init();
$data = array(
'client_id' => 'xx',
'client_secret' => 'xx',
'redirect_uri' => $x,
'grant_type' => 'xxx',
'code' => $xx,
);
$data = http_build_query($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_URL, "https://example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);
That is for removing any space that is when you getting text from any text field but if you want to remove space between string you can use
xyz =[xyz.text stringByReplacingOccurrencesOfString:@" " withString:@""];
It will replace empty space with no space and empty field is taken care of by below method:
searchbar.text=[searchbar.text stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
No need to get fancy, you can treat pthread_t
as a pointer without a cast:
printf("awesome worker thread id %p\n", awesome_worker_thread_id);
Output:
awesome worker thread id 0x6000485e0
I found this answer here and I'm using it like this.
Code from my Library:
$.fn.customContextMenu = function(callBack){
$(this).each(function(){
$(this).bind("contextmenu",function(e){
e.preventDefault();
callBack();
});
});
}
Code from my page's script:
$("#newmagazine").customContextMenu(function(){
alert("some code");
});
Bootstrap has 3 lines of CSS, within your bootstrap.css generated file that control the placeholder text color:
.form-control::-moz-placeholder {
color: #999999;
opacity: 1;
}
.form-control:-ms-input-placeholder {
color: #999999;
}
.form-control::-webkit-input-placeholder {
color: #999999;
}
Now if you add this to your own CSS file it won't override bootstrap's because it is less specific. So assmuning your form inside a then add that to your CSS:
form .form-control::-moz-placeholder {
color: #fff;
opacity: 1;
}
form .form-control:-ms-input-placeholder {
color: #fff;
}
form .form-control::-webkit-input-placeholder {
color: #fff;
}
Voila that will override bootstrap's CSS.
The only difference I see is that getJSON performs a GET request instead of a POST.
The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.
const http = require('http')
const server = http.createServer(function(request, response) {
console.dir(request.param)
if (request.method == 'POST') {
console.log('POST')
var body = ''
request.on('data', function(data) {
body += data
console.log('Partial body: ' + body)
})
request.on('end', function() {
console.log('Body: ' + body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('post received')
})
} else {
console.log('GET')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
}
})
const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)
If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation
var express = require('express')
var fs = require('fs')
var app = express()
app.use(express.bodyParser())
app.get('/', function(request, response) {
console.log('GET /')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
})
app.post('/', function(request, response) {
console.log('POST /')
console.dir(request.body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('thanks')
})
port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)
You should put the form inside each node and use ng-show
and ng-hide
to enable and disable editing, respectively. Something like this:
<li>
<span ng-hide="editing" ng-click="editing = true">{{bday.name}} | {{bday.date}}</span>
<form ng-show="editing" ng-submit="editing = false">
<label>Name:</label>
<input type="text" ng-model="bday.name" placeholder="Name" ng-required/>
<label>Date:</label>
<input type="date" ng-model="bday.date" placeholder="Date" ng-required/>
<br/>
<button class="btn" type="submit">Save</button>
</form>
</li>
The key points here are:
ng-model
to the local scopeng-show
to form
so we can show it while editingspan
with a ng-hide
to hide the content while editingng-click
, that could be in any other element, that toggles editing
to true
ng-submit
to toggle editing
to false
Here is your updated Plunker.
You can do it without setlocal
, because of the setlocal
command the variable won't survive an endlocal
because it was created in setlocal
. In this way the variable will be defined the right way.
To do that use this code:
set var1=A
set var2=B
set AB=hi
call set newvar=%%%var1%%var2%%%
echo %newvar%
Note: You MUST use call
before you set the variable or it won't work.
I have tested a full layout using flexbox it contains header, footer, main body with left, center and right panels and the panels can contain menu items or footer and headers that should scroll. Pretty complex
IE11 and even IE EDGE have some problems displaying the flex content but it can be overcome. I have tested it in most browsers and it seems to work.
Some fixed i have applies are IE11 height bug, Adding height:100vh and min-height:100% to the html/body. this also helps to not have to set height on container in the dom. Also make the body/html a flex container. Otherwise IE11 will compress the view.
html,body {
display: flex;
flex-flow:column nowrap;
height:100vh; /* fix IE11 */
min-height:100%; /* fix IE11 */
}
A fix for IE EDGE that overflows the flex container: overflow:hidden on main flex container. if you remove the overflow, IE EDGE wil push the content out of the viewport instead of containing it inside the flex main container.
main{
flex:1 1 auto;
overflow:hidden; /* IE EDGE overflow fix */
}
You can see my testing and example on my codepen page. I remarked the important css parts with the fixes i have applied and hope someone finds it useful.
For most of my select options, I start off with an option that simply says 'Please Select' or something similar and that option is always disabled. Then whenever you want to clear your select/option's you can do just do something like this.
Example
<select id="mySelectOption">
<option value="" selected disabled>Please select</option>
</select>
Answer
$('#mySelectOption').val('Please Select');
For me I just noticed that it was my .h archive with a '{'. Maye that can help someone =)
You need other headers, not only access-control-allow-origin. If your request have the "Access-Control-Allow-Origin" header, you must copy it into the response headers, If doesn't, you must check the "Origin" header and copy it into the response. If your request doesn't have Access-Control-Allow-Origin not Origin headers, you must return "*".
You can read the complete explanation here: http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server
and this is the function I'm using to write cross domain headers:
func writeCrossDomainHeaders(w http.ResponseWriter, req *http.Request) {
// Cross domain headers
if acrh, ok := req.Header["Access-Control-Request-Headers"]; ok {
w.Header().Set("Access-Control-Allow-Headers", acrh[0])
}
w.Header().Set("Access-Control-Allow-Credentials", "True")
if acao, ok := req.Header["Access-Control-Allow-Origin"]; ok {
w.Header().Set("Access-Control-Allow-Origin", acao[0])
} else {
if _, oko := req.Header["Origin"]; oko {
w.Header().Set("Access-Control-Allow-Origin", req.Header["Origin"][0])
} else {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
}
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
w.Header().Set("Connection", "Close")
}
You can use some thing like this
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div ng-app="" ng-init="btn1=false" ng-init="btn2=false">_x000D_
<p>_x000D_
<input type="submit" ng-disabled="btn1||btn2" ng-click="btn1=true" ng-model="btn1" />_x000D_
</p>_x000D_
<p>_x000D_
<button ng-disabled="btn1||btn2" ng-model="btn2" ng-click="btn2=true">Click Me!</button>_x000D_
</p>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
I believe you are using Bootstrap 3. If so, please try this code, here is the bootply
<header>
<div class="navbar navbar-static-top navbar-default">
<div class="navbar-header">
<a class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="glyphicon glyphicon-th-list"></span>
</a>
</div>
<div class="container" style="background:yellow;">
<a href="/">
<img src="img/logo.png" class="logo img-responsive">
</a>
<nav class="navbar-collapse collapse pull-right" style="line-height:150px; height:150px;">
<ul class="nav navbar-nav" style="display:inline-block;">
<li><a href="">Portfolio</a></li>
<li><a href="">Blog</a></li>
<li><a href="">Contact</a></li>
</ul>
</nav>
</div>
</div>
</header>
In command mode (press Esc if you are not sure) you can use:
You can use transitions instead:
.successfully-saved.hide-opacity{
opacity: 0;
}
.successfully-saved {
color: #FFFFFF;
text-align: center;
-webkit-transition: opacity 3s ease-in-out;
-moz-transition: opacity 3s ease-in-out;
-ms-transition: opacity 3s ease-in-out;
-o-transition: opacity 3s ease-in-out;
opacity: 1;
}
void 0
returns undefined and can not be overwritten while undefined
can be overwritten.
var undefined = "HAHA";
you need RequestOptions
let headers = new Headers({'Content-Type': 'application/json'});
headers.append('Authorization','Bearer ')
let options = new RequestOptions({headers: headers});
return this.http.post(APIname,body,options)
.map(this.extractData)
.catch(this.handleError);
for more check this link
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0
. The last element is at index n-1
, where n
is the Size
of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1
, you're going to get an error.
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1
because index
is no longer less than Length
.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <=
there? index
will now be out of range in the last loop iteration, because the loop thinks that Length
is a valid index, but it is not.
Lists work the same way, except that you generally use Count
instead of Length
. They still start at zero, and end at Count - 1
.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach
, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
This is an old post, but this is what works best for me:
A[np.random.choice(A.shape[0], num_rows_2_sample, replace=False)]
change the replace=False to True to get the same thing, but with replacement.
There are some good answers already with explanations of why the mixture of the non-static Context
method getText()
can't be used with your static final String
.
A good question to ask is: why do you want to do this? You are attempting to load a String
from your strings
resource, and populate its value into a public static
field. I assume that this is so that some of your other classes can access it? If so, there is no need to do this. Instead pass a Context
into your other classes and call context.getText(R.string.TTT)
from within them.
public class NonActivity {
public static void doStuff(Context context) {
String TTT = context.getText(R.string.TTT);
...
}
}
And to call this from your Activity
:
NonActivity.doStuff(this);
This will allow you to access your String
resource without needing to use a public static
field.
Recently i found the AribaWeb Framework which looks very promising. It offers good functionality (even AJAX), good documentation. written in Groovy/Java and even includes a Tomcat-Server. Trying to get into Spring really made me mad.
Rationale for the /
POSIX PATH rule
The rule was mentioned at: Why do you need ./ (dot-slash) before executable or script name to run it in bash? but I would like to explain why I think that is a good design in more detail.
First, an explicit full version of the rule is:
/
(e.g. ./someprog
, /bin/someprog
, ./bin/someprog
): CWD is used and PATH isn't/
(e.g. someprog
): PATH is used and CWD isn'tNow, suppose that running:
someprog
would search:
Then, if you wanted to run /bin/someprog
from your distro, and you did:
someprog
it would sometimes work, but others it would fail, because you might be in a directory that contains another unrelated someprog
program.
Therefore, you would soon learn that this is not reliable, and you would end up always using absolute paths when you want to use PATH, therefore defeating the purpose of PATH.
This is also why having relative paths in your PATH is a really bad idea. I'm looking at you, node_modules/bin
.
Conversely, suppose that running:
./someprog
Would search:
Then, if you just downloaded a script someprog
from a git repository and wanted to run it from CWD, you would never be sure that this is the actual program that would run, because maybe your distro has a:
/bin/someprog
which is in you PATH from some package you installed after drinking too much after Christmas last year.
Therefore, once again, you would be forced to always run local scripts relative to CWD with full paths to know what you are running:
"$(pwd)/someprog"
which would be extremely annoying as well.
Another rule that you might be tempted to come up with would be:
relative paths use only PATH, absolute paths only CWD
but once again this forces users to always use absolute paths for non-PATH scripts with "$(pwd)/someprog"
.
The /
path search rule offers a simple to remember solution to the about problem:
PATH
PATH
which makes it super easy to always know what you are running, by relying on the fact that files in the current directory can be expressed either as ./somefile
or somefile
, and so it gives special meaning to one of them.
Sometimes, is slightly annoying that you cannot search for some/prog
relative to PATH
, but I don't see a saner solution to this.
DECORATORS: to dynamically change the behaviour of DOM elements
@HostBinding: Dynamic binding custom logic to Host element
@HostBinding('class.active')
activeClass = false;
@HostListen: To Listen to events on Host element
@HostListener('click')
activeFunction(){
this.activeClass = !this.activeClass;
}
Host Element:
<button type='button' class="btn btn-primary btn-sm" appHost>Host</button>
If you want to see how to do a proper definition go into Sublime Text->Preferences->Key Bindings - Default and search for the command you want to override.
{ "keys": ["f12"], "command": "goto_definition" },
{ "keys": ["super+alt+down"], "command": "goto_definition" }
Those are two that show in my Default.
On Mac I copied the second to override.
in Sublime Text -> Preferences -> Key Bindings - User I added this
/* Beginning of File */
[
{
"keys": ["super+shift+i"], "command": "goto_definition"
}
]
/* End of File */
This binds it to the Command + Shift + 1 combination on mac.
Try this:
public static boolean deleteDir(File dir)
{
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i=0; i<children.length; i++)
return deleteDir(new File(dir, children[i]));
}
// The directory is now empty or this is a file so delete it
return dir.delete();
}
In my Controller, I merely added an HttpServletResponse parameter and manually added the headers, no filter or intercept required and it works fine:
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
httpServletResponse.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token, X-Csrf-Token, WWW-Authenticate, Authorization");
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "false");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
Since you have not mentioned what needs to be copied, I have left that section empty in the code below.
Also you don't need to move the email to the folder first and then run the macro in that folder. You can run the macro on the incoming mail and then move it to the folder at the same time.
This will get you started. I have commented the code so that you will not face any problem understanding it.
First paste the below mentioned code in the outlook module.
Then
When the new email arrives not only will the email move to the folder that you specify but data from it will be exported to Excel as well.
UNTESTED
Const xlUp As Long = -4162
Sub ExportToExcel(MyMail As MailItem)
Dim strID As String, olNS As Outlook.Namespace
Dim olMail As Outlook.MailItem
Dim strFileName As String
'~~> Excel Variables
Dim oXLApp As Object, oXLwb As Object, oXLws As Object
Dim lRow As Long
strID = MyMail.EntryID
Set olNS = Application.GetNamespace("MAPI")
Set olMail = olNS.GetItemFromID(strID)
'~~> Establish an EXCEL application object
On Error Resume Next
Set oXLApp = GetObject(, "Excel.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set oXLApp = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0
'~~> Show Excel
oXLApp.Visible = True
'~~> Open the relevant file
Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xls")
'~~> Set the relevant output sheet. Change as applicable
Set oXLws = oXLwb.Sheets("Sheet1")
lRow = oXLws.Range("A" & oXLApp.Rows.Count).End(xlUp).Row + 1
'~~> Write to outlook
With oXLws
'
'~~> Code here to output data from email to Excel File
'~~> For example
'
.Range("A" & lRow).Value = olMail.Subject
.Range("B" & lRow).Value = olMail.SenderName
'
End With
'~~> Close and Clean up Excel
oXLwb.Close (True)
oXLApp.Quit
Set oXLws = Nothing
Set oXLwb = Nothing
Set oXLApp = Nothing
Set olMail = Nothing
Set olNS = Nothing
End Sub
FOLLOWUP
To extract the contents from your email body, you can split it using SPLIT() and then parsing out the relevant information from it. See this example
Dim MyAr() As String
MyAr = Split(olMail.body, vbCrLf)
For i = LBound(MyAr) To UBound(MyAr)
'~~> This will give you the contents of your email
'~~> on separate lines
Debug.Print MyAr(i)
Next i
The best .let it's parent display :inline-block
or add a parent div
what CSS only have display :inline-block
.
read
does this:
user@host:~$ read -n1 -r -p "Press any key to continue..." key
[...]
user@host:~$
The -n1
specifies that it only waits for a single character. The -r
puts it into raw mode, which is necessary because otherwise, if you press something like backslash, it doesn't register until you hit the next key. The -p
specifies the prompt, which must be quoted if it contains spaces. The key
argument is only necessary if you want to know which key they pressed, in which case you can access it through $key
.
If you are using Bash, you can also specify a timeout with -t
, which causes read to return a failure when a key isn't pressed. So for example:
read -t5 -n1 -r -p 'Press any key in the next five seconds...' key
if [ "$?" -eq "0" ]; then
echo 'A key was pressed.'
else
echo 'No key was pressed.'
fi
help('nonlocal') The
nonlocal
statement
nonlocal_stmt ::= "nonlocal" identifier ("," identifier)*
The
nonlocal
statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.Names listed in a
nonlocal
statement, unlike to those listed in aglobal
statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).Names listed in a
nonlocal
statement must not collide with pre- existing bindings in the local scope.See also:
PEP 3104 - Access to Names in Outer Scopes
The specification for thenonlocal
statement.Related help topics: global, NAMESPACES
Source: Python Language Reference
Is super() is used to call the parent constructor?
Yes.
Pls explain about Super().
super()
is a special use of the super
keyword where you call a parameterless parent constructor. In general, the super
keyword can be used to call overridden methods, access hidden fields or invoke a superclass's constructor.
Here's the official tutorial
Maybe this code helps:
var chunk_size = 10;_x000D_
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];_x000D_
var groups = arr.map( function(e,i){ _x000D_
return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null; _x000D_
}).filter(function(e){ return e; });_x000D_
console.log({arr, groups})
_x000D_
It is due to android:targetSdkVersion="@string/app_name"
in your manifiest file.
Change it to:
<uses-sdk android:minSdkVersion="15" android:targetSdkVersion="15"/>
The targetSdkVersion
should be an integer, but @string/app_name
would be a string. I think this causing the error.
EDIT:
You have to add a default intent-filter
in your manifiest
file for the activity. Then only android can launch the activity. otherwise you will get the below error in your console window.
[2012-02-02 09:17:39 - Test] No Launcher activity found!
[2012-02-02 09:17:39 - Test] The launch will only sync the application package on the device!
Add the following to your <activity>
tag.
<activity android:name="HelloAndroid" android:launchMode="standard" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Java/JavaScript:
You could probably do it this way also, non-natively:
public void triggerButtonOnEnterKeyInTextField(String textFieldId, String clickableButId)
{
((JavascriptExecutor) driver).executeScript(
" elementId = arguments[0];
buttonId = arguments[1];
document.getElementById(elementId)
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode == 13) {
document.getElementById(buttonId).click();
}
});",
textFieldId,
clickableButId);
}
check for this by calling the library jquery after the noconflict.js or that this calling more than once jquery library after the noconflict.js
.project
When a project is created in the workspace, a project description file is automatically generated that describes the project. The sole purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace.
.classpath
Classpath specifies which Java source files and resource files in a project are considered by the Java builder and specifies how to find types outside of the project. The Java builder compiles the Java source files into the output folder and also copies the resources into it.
If you're short of "fancy tools", e.g. in some minimal Linux distribution, there is a solution with just cat
, sort
and uniq
:
cat includes.txt excludes.txt excludes.txt | sort | uniq --unique
Test:
seq 1 1 7 | sort --random-sort > includes.txt
seq 3 1 9 | sort --random-sort > excludes.txt
cat includes.txt excludes.txt excludes.txt | sort | uniq --unique
# Output:
1
2
This is also relatively fast, compared to grep
.
You can use the key code page in order to find the:
event.code
to diference the number keyboard.
function getNumberFromKeyEvent(event) {
if (event.code.indexOf('Numpad') === 0) {
var number = parseInt(event.code.replace('Numpad', ''), 10);
if (number >= 0 && number <= 9) {
// numbers from numeric keyboard
}
}
}
To supplement @artfulrobot's answer, if you want to show changed files between two branches:
git diff --name-status mybranch..myotherbranch
Be careful on precedence. If you place the newer branch first then it would show files as deleted rather than added.
Adding a grep
can refine things further:
git diff --name-status mybranch..myotherbranch | grep "A\t"
That will then show only files added in myotherbranch
.
If you are implementing your bot, keep stored a group name -> id table, and ask it with a command. Then you can also send per name.
If you want to listen to a native event on the root element of a component, you have to use the .native modifier for v-on
, like following:
<template>
<div id="app">
<test v-on:click.native="testFunction"></test>
</div>
</template>
or in shorthand, as suggested in comment, you can as well do:
<template>
<div id="app">
<test @click.native="testFunction"></test>
</div>
</template>
Finally I found answer myself. To add new icons in 2.3.2 bootstrap we have to add Font Awsome css in you file. After doing this we can override the styles with css to change the color and size.
<link href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
CSS
.brown{color:#9b846b}
If we want change the color of icon then just add brown class and icon will turn in brown color. It also provide icon of various size.
HTML
<p><i class="icon-camera-retro icon-large brown"></i> icon-camera-retro</p> <!--brown class added-->
<p><i class="icon-camera-retro icon-2x"></i> icon-camera-retro</p>
<p><i class="icon-camera-retro icon-3x"></i> icon-camera-retro</p>
<p><i class="icon-camera-retro icon-4x"></i> icon-camera-retro</p>
You simply need to add that line legend: { display: false }
Yes, that is one way to get the first line of output from a command.
If the command outputs anything to standard error that you would like to capture in the same manner, you need to redirect the standard error of the command to the standard output stream:
utility 2>&1 | head -n 1
There are many other ways to capture the first line too, including sed 1q
(quit after first line), sed -n 1p
(only print first line, but read everything), awk 'FNR == 1'
(only print first line, but again, read everything) etc.