foreach (DictionaryEntry entry in Hashtable)
{
datagridviewTZ.Rows.Add(entry.Key.ToString(), entry.Value.ToString());
}
MS Office Interop is slow and even Microsoft does not recommend Interop usage on server side and cannot be use to import large Excel files. For more details see why not to use OLE Automation from Microsoft point of view.
Instead, you can use any Excel library, like EasyXLS for example. This is a code sample that shows how to read the Excel file:
ExcelDocument workbook = new ExcelDocument();
DataSet ds = workbook.easy_ReadXLSActiveSheet_AsDataSet("excel.xls");
DataTable dataTable = ds.Tables[0];
If your Excel file has multiple sheets or for importing only ranges of cells (for better performances) take a look to more code samples on how to import Excel to DataTable in C# using EasyXLS.
I was also getting same issue as i tried using value 0 in non-based indexing,i.e starting with 1, not with zero
user this full solution to convert gridview to datatable
public DataTable gridviewToDataTable(GridView gv)
{
DataTable dtCalculate = new DataTable("TableCalculator");
// Create Column 1: Date
DataColumn dateColumn = new DataColumn();
dateColumn.DataType = Type.GetType("System.DateTime");
dateColumn.ColumnName = "date";
// Create Column 3: TotalSales
DataColumn loanBalanceColumn = new DataColumn();
loanBalanceColumn.DataType = Type.GetType("System.Double");
loanBalanceColumn.ColumnName = "loanbalance";
DataColumn offsetBalanceColumn = new DataColumn();
offsetBalanceColumn.DataType = Type.GetType("System.Double");
offsetBalanceColumn.ColumnName = "offsetbalance";
DataColumn netloanColumn = new DataColumn();
netloanColumn.DataType = Type.GetType("System.Double");
netloanColumn.ColumnName = "netloan";
DataColumn interestratecolumn = new DataColumn();
interestratecolumn.DataType = Type.GetType("System.Double");
interestratecolumn.ColumnName = "interestrate";
DataColumn interestrateperdaycolumn = new DataColumn();
interestrateperdaycolumn.DataType = Type.GetType("System.Double");
interestrateperdaycolumn.ColumnName = "interestrateperday";
// Add the columns to the ProductSalesData DataTable
dtCalculate.Columns.Add(dateColumn);
dtCalculate.Columns.Add(loanBalanceColumn);
dtCalculate.Columns.Add(offsetBalanceColumn);
dtCalculate.Columns.Add(netloanColumn);
dtCalculate.Columns.Add(interestratecolumn);
dtCalculate.Columns.Add(interestrateperdaycolumn);
foreach (GridViewRow row in gv.Rows)
{
DataRow dr;
dr = dtCalculate.NewRow();
dr["date"] = DateTime.Parse(row.Cells[0].Text);
dr["loanbalance"] = double.Parse(row.Cells[1].Text);
dr["offsetbalance"] = double.Parse(row.Cells[2].Text);
dr["netloan"] = double.Parse(row.Cells[3].Text);
dr["interestrate"] = double.Parse(row.Cells[4].Text);
dr["interestrateperday"] = double.Parse(row.Cells[5].Text);
dtCalculate.Rows.Add(dr);
}
return dtCalculate;
}
//?Creating a new row with the structure of the table:
DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);
//Giving values to the columns of the row(this row is supposed to have 28 columns):
for (int i = 0; i < 28; i++)
{
row[i] = i.ToString();
}
The .before
argument in dplyr::add_row
can be used to specify the row.
dplyr::add_row(
cars,
speed = 0,
dist = 0,
.before = 3
)
#> speed dist
#> 1 4 2
#> 2 4 10
#> 3 0 0
#> 4 7 4
#> 5 7 22
#> 6 8 16
#> ...
With Lodash you can create a template and you can do that following way:
<div class="container">
<div class="row justify-content-center">
<div class="col-12">
<table id="tblEntAttributes" class="table">
<tbody>
<tr>
<td>
chkboxId
</td>
<td>
chkboxValue
</td>
<td>
displayName
</td>
<td>
logicalName
</td>
<td>
dataType
</td>
</tr>
</tbody>
</table>
<button class="btn btn-primary" id="test">appendTo</button>
</div>
</div>
</div>
And here goes the javascript:
var count = 1;
window.addEventListener('load', function () {
var compiledRow = _.template("<tr><td><input type=\"checkbox\" id=\"<%= chkboxId %>\" value=\"<%= chkboxValue %>\"></td><td><%= displayName %></td><td><%= logicalName %></td><td><%= dataType %></td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td><td><input type=\"checkbox\" id=\"chkAllPrimaryAttrs\" name=\"chkAllPrimaryAttrs\" value=\"chkAllPrimaryAttrs\"></td></tr>");
document.getElementById('test').addEventListener('click', function (e) {
var ajaxData = { 'chkboxId': 'chkboxId-' + count, 'chkboxValue': 'chkboxValue-' + count, 'displayName': 'displayName-' + count, 'logicalName': 'logicalName-' + count, 'dataType': 'dataType-' + count };
var tableRowData = compiledRow(ajaxData);
$("#tblEntAttributes tbody").append(tableRowData);
count++;
});
});
Here it is in jsbin
Adding a new row in a DGV with no rows with Add() raises SelectionChanged event before you can insert any data (or bind an object in Tag property).
Create a clone row from RowTemplate is safer imho:
//assuming that you created columns (via code or designer) in myDGV
DataGridViewRow row = (DataGridViewRow) myDGV.RowTemplate.Clone();
row.CreateCells(myDGV, "cell1", "cell2", "cell3");
myDGV.Rows.Add(row);
Is it very expensive to do this by json convert? But at least you have a 2 line solution and its generic. It does not matter eather if your datatable contains more or less fields than the object class:
Dim sSql = $"SELECT '{jobID}' AS ConfigNo, 'MainSettings' AS ParamName, VarNm AS ParamFieldName, 1 AS ParamSetId, Val1 AS ParamValue FROM StrSVar WHERE NmSp = '{sAppName} Params {jobID}'"
Dim dtParameters As DataTable = DBLib.GetDatabaseData(sSql)
Dim paramListObject As New List(Of ParameterListModel)()
If (Not dtParameters Is Nothing And dtParameters.Rows.Count > 0) Then
Dim json = Newtonsoft.Json.JsonConvert.SerializeObject(dtParameters).ToString()
paramListObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of ParameterListModel))(json)
End If
I have done it accessing the controls inside the cell control. Find in all control collections.
ControlCollection cc = (ControlCollection)e.Row.Controls[1].Controls;
Label lbCod = (Label)cc[1];
I came across the same issue recently. I had to insert new rows in a document with hidden rows and faced the same issues with you. After some search and some emails in apache poi list, it seems like a bug in shiftrows() when a document has hidden rows.
Here is a little something I cooked up today. Seems to work for me. Basically you override the Add method in your base namespace to do a check and then call the base's Add method in order to actually add it. Hope this works for you
using System;
using System.Collections.Generic;
using System.Collections;
namespace Main
{
internal partial class Dictionary<TKey, TValue> : System.Collections.Generic.Dictionary<TKey, TValue>
{
internal new virtual void Add(TKey key, TValue value)
{
if (!base.ContainsKey(key))
{
base.Add(key, value);
}
}
}
internal partial class List<T> : System.Collections.Generic.List<T>
{
internal new virtual void Add(T item)
{
if (!base.Contains(item))
{
base.Add(item);
}
}
}
public class Program
{
public static void Main()
{
Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(1,"b");
dic.Add(1,"a");
dic.Add(2,"c");
dic.Add(1, "b");
dic.Add(1, "a");
dic.Add(2, "c");
string val = "";
dic.TryGetValue(1, out val);
Console.WriteLine(val);
Console.WriteLine(dic.Count.ToString());
List<string> lst = new List<string>();
lst.Add("b");
lst.Add("a");
lst.Add("c");
lst.Add("b");
lst.Add("a");
lst.Add("c");
Console.WriteLine(lst[2]);
Console.WriteLine(lst.Count.ToString());
}
}
}
Code for Find the Column Name same as using the Like
in sql.
foreach (DataGridViewColumn column in GrdMarkBook.Columns)
//GrdMarkBook is Data Grid name
{
string HeaderName = column.HeaderText.ToString();
// This line Used for find any Column Have Name With Exam
if (column.HeaderText.ToString().ToUpper().Contains("EXAM"))
{
int CoumnNo = column.Index;
}
}
I prefer approach of Tommy Carlier, but with a little change.
foreach (DataColumn column in row.Table.Columns)
if (!row.IsNull(column))
return false;
return true;
I suppose this approach looks more simple and bright.
If DAO
use
RS.Move 0, RS.LastModified
lngID = RS!AutoNumberFieldName
If ADO
use
cn.Execute "INSERT INTO TheTable.....", , adCmdText + adExecuteNoRecords
Set rs = cn.Execute("SELECT @@Identity", , adCmdText)
Debug.Print rs.Fields(0).Value
cn
being a valid ADO connection, @@Identity
will return the last
Identity
(Autonumber) inserted on this connection.
Note that @@Identity
might be troublesome because the last generated value may not be the one you are interested in. For the Access database engine, consider a VIEW
that joins two tables, both of which have the IDENTITY
property, and you INSERT INTO
the VIEW
. For SQL Server, consider if there are triggers that in turn insert records into another table that also has the IDENTITY
property.
BTW DMax
would not work as if someone else inserts a record just after you've inserted one but before your Dmax
function finishes excecuting, then you would get their record.
Delete the row from the table dtPrf_Mstr rather than from the grid view.
A few points:
1) "DataBind()" is only for web apps (not windows apps).
2) Your code looks very 'JAVAish' (not a bad thing, just an observation).
Try this:
mnuActionLanguage.ComboBox.DataSource = languages;
If that doesn't work... then I'm assuming that your datasource is being stepped on somewhere else in the code.
Looks like FB just changed the app dev page again and added a feature called "Server IP Whitelist".
Use dictionary comprehension way,
x = {k:v for k,v in enumerate(states) if v == True}
Input:
states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
Output:
{4: True, 5: True, 7: True}
Maybe, this approach is better, https://saucelabs.com/mobile, mobile testing in the cloud with selenium
You can use this OnLoad or during fetch infos from DB
In HTML Add following code:
<div id="divLoading">
<p id="loading">
<img src="~/images/spinner.gif">
</p>
In CSS add following Code:
#divLoading {
margin: 0px;
display: none;
padding: 0px;
position: absolute;
right: 0px;
top: 0px;
width: 100%;
height: 100%;
background-color: rgb(255, 255, 255);
z-index: 30001;
opacity: 0.8;}
#loading {
position: absolute;
color: White;
top: 50%;
left: 45%;}
if you want to show and hide from JS:
document.getElementById('divLoading').style.display = 'none'; //Not Visible
document.getElementById('divLoading').style.display = 'block';//Visible
You can use lodash sortBy (https://lodash.com/docs/4.17.4#sortBy).
Your code could be like:
const myArray = [
{
"id":25,
"name":"Anakin Skywalker",
"createdAt":"2017-04-12T12:48:55.000Z",
"updatedAt":"2017-04-12T12:48:55.000Z"
},
{
"id":1,
"name":"Luke Skywalker",
"createdAt":"2017-04-12T11:25:03.000Z",
"updatedAt":"2017-04-12T11:25:03.000Z"
}
]
const myOrderedArray = _.sortBy(myArray, o => o.name)
// datimetime displays in the datePicker is 11/24/2011 12:00:00 AM
// you could split this by space and set the value to date only
Script:
if ($("#StartDate").val() != '') {
var arrDate = $('#StartDate').val().split(" ");
$('#StartDate').val(arrDate[0]);
}
Markup:
<div class="editor-field">
@Html.LabelFor(model => model.StartDate, "Start Date")
@Html.TextBoxFor(model => model.StartDate, new { @class = "date-picker-needed" })
</div>
Hopes this helps..
None seems to mention the actual math of the probability of it occurring.
First, let's assume we can use the entire 128 bit space (Guid v4 only uses 122 bits).
We know that the general probability of NOT getting a duplicate in n
picks is:
(1-1/2128)(1-2/2128)...(1-(n-1)/2128)
Because 2128 is much much larger than n
, we can approximate this to:
(1-1/2128)n(n-1)/2
And because we can assume n
is much much larger than 0, we can approximate that to:
(1-1/2128)n^2/2
Now we can equate this to the "acceptable" probability, let's say 1%:
(1-1/2128)n^2/2 = 0.01
Which we solve for n
and get:
n = sqrt(2* log 0.01 / log (1-1/2128))
Which Wolfram Alpha gets to be 5.598318 × 1019
To put that number into perspective, lets take 10000 machines, each having a 4 core CPU, doing 4Ghz and spending 10000 cycles to generate a Guid and doing nothing else. It would then take ~111 years before they generate a duplicate.
You can transpose the array if you want to get the length of the other dimension.
len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]]).T)
public boolean newEquals(String str1, String str2)
{
int len = str1.length();
int len1 = str2.length();
if(len==len1)
{
for(int i=0,j=0;i<str1.length();i++,j++)
{
if(str1.charAt(i)!=str2.charAt(j))
return false;
}`enter code here`
}
return true;
}
Years after everyone's answer, I too want to present how I did it for my project
/// <summary>
/// /Reads an excel file and converts it into dataset with each sheet as each table of the dataset
/// </summary>
/// <param name="filename"></param>
/// <param name="headers">If set to true the first row will be considered as headers</param>
/// <returns></returns>
public DataSet Import(string filename, bool headers = true)
{
var _xl = new Excel.Application();
var wb = _xl.Workbooks.Open(filename);
var sheets = wb.Sheets;
DataSet dataSet = null;
if (sheets != null && sheets.Count != 0)
{
dataSet = new DataSet();
foreach (var item in sheets)
{
var sheet = (Excel.Worksheet)item;
DataTable dt = null;
if (sheet != null)
{
dt = new DataTable();
var ColumnCount = ((Excel.Range)sheet.UsedRange.Rows[1, Type.Missing]).Columns.Count;
var rowCount = ((Excel.Range)sheet.UsedRange.Columns[1, Type.Missing]).Rows.Count;
for (int j = 0; j < ColumnCount; j++)
{
var cell = (Excel.Range)sheet.Cells[1, j + 1];
var column = new DataColumn(headers ? cell.Value : string.Empty);
dt.Columns.Add(column);
}
for (int i = 0; i < rowCount; i++)
{
var r = dt.NewRow();
for (int j = 0; j < ColumnCount; j++)
{
var cell = (Excel.Range)sheet.Cells[i + 1 + (headers ? 1 : 0), j + 1];
r[j] = cell.Value;
}
dt.Rows.Add(r);
}
}
dataSet.Tables.Add(dt);
}
}
_xl.Quit();
return dataSet;
}
you could also do it this way, in my case i use it before and after an h1 (brute force it ehehehe)
.titleImage::before {
content: "--------";
letter-spacing: -3px;
}
.titreImage::after {
content: "--------";
letter-spacing: -3px;
}
If the letter spacing makes it so the line get in the text just use a margin to push it away!
Well to make the decimal into a percent you can do this,
float percentage = (correct * 100.0f) / questionNum;
Sadly, many JSON C++ libraries have APIs that are non trivial to use, while JSON was intended to be easy to use.
So I tried jsoncpp from the gSOAP tools on the JSON doc shown in one of the answers above and this is the code generated with jsoncpp to construct a JSON object in C++ which is then written in JSON format to std::cout:
value x(ctx);
x["appDesc"]["description"] = "SomeDescription";
x["appDesc"]["message"] = "SomeMessage";
x["appName"]["description"] = "Home";
x["appName"]["message"] = "Welcome";
x["appName"]["imp"][0] = "awesome";
x["appName"]["imp"][1] = "best";
x["appName"]["imp"][2] = "good";
std::cout << x << std::endl;
and this is the code generated by jsoncpp to parse JSON from std::cin and extract its values (replace USE_VAL
as needed):
value x(ctx);
std::cin >> x;
if (x.soap->error)
exit(EXIT_FAILURE); // error parsing JSON
#define USE_VAL(path, val) std::cout << path << " = " << val << std::endl
if (x.has("appDesc"))
{
if (x["appDesc"].has("description"))
USE_VAL("$.appDesc.description", x["appDesc"]["description"]);
if (x["appDesc"].has("message"))
USE_VAL("$.appDesc.message", x["appDesc"]["message"]);
}
if (x.has("appName"))
{
if (x["appName"].has("description"))
USE_VAL("$.appName.description", x["appName"]["description"]);
if (x["appName"].has("message"))
USE_VAL("$.appName.message", x["appName"]["message"]);
if (x["appName"].has("imp"))
{
for (int i2 = 0; i2 < x["appName"]["imp"].size(); i2++)
USE_VAL("$.appName.imp[]", x["appName"]["imp"][i2]);
}
}
This code uses the JSON C++ API of gSOAP 2.8.28. I don't expect people to change libraries, but I think this comparison helps to put JSON C++ libraries in perspective.
If all else fails, look for duplication. I was misdirected by the explicit initial reference to constructors and destructors until I read a reference in another post. It's any unresolved method. In my case, I thought I had replaced the declaration that used char *xml
as the parameter with one using the unnecessarily troublesome const char *xml
, but instead, I had created a new one and left the other one in place.
From the Errata:
ModelState.AddRuleViolations(dinner.GetRuleViolations());
Should be:
ModelState.AddModelErrors(dinner.GetRuleViolations());
If you import the module (.py) file you are creating now from another python script it will not execute the code within
if __name__ == '__main__':
...
If you run the script directly from the console, it will be executed.
Python does not use or require a main() function. Any code that is not protected by that guard will be executed upon execution or importing of the module.
This is expanded upon a little more at python.berkely.edu
I use to just create it without parameters, and then edit the registry HKLM\System\CurrentControlSet\Services\[YourService]
.
If you're wanting to run the script and end at a prompt (so you can inspect variables, etc), then use:
python -i test.py
That will run the script and then drop you into a Python interpreter.
You can simply add this when you are using same controller to redirect
var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;
I used the answer from Jonathan to google inserting images into LaTeX and if you would like to insert an image named image1.jpg and have it centered, your code might look like this in Rmarkdown
\begin{center}
\includegraphics{image1}
\end{center}
Keep in mind that LaTex is not asking for the file exention (.jpg). This question helped me get my answer. Thanks.
just to help, if any one want to limit post length at home page
.. then can use below code to do that..
the below code is simply a modification of @bfred.it
Sir
add_filter("the_content", "break_text");
function limit_text($text){
if(is_front_page())
{
$length = 250;
if(strlen($text)<$length+10) return $text; //don't cut if too short
$break_pos = strpos($text, ' ', $length); //find next space after desired length
$visible = substr($text, 0, $break_pos);
return balanceTags($visible) . "... <a href='".get_permalink()."'>read more</a>";
}else{
return $text;
}
}
string[] TobeDistinct = {"Name","City","State"};
DataTable dtDistinct = GetDistinctRecords(DTwithDuplicate, TobeDistinct);
//Following function will return Distinct records for Name, City and State column.
public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
{
DataTable dtUniqRecords = new DataTable();
dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
return dtUniqRecords;
}
In Java8 you use the new Time API, and convert an Instant in to a ZonedDateTime Using the UTC TimeZone
First, you need to make sure your server is configured to allow wildcard subdomains. I achieved that in JustHost by creating a subomain manually named *
. I also specified a folder called subdomains
as the document root for wildcard subdomains. Add this to a .htaccess
file in your subdomains folder:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.website\.com$
RewriteCond %{HTTP_HOST} ^(\w+)\.website\.com$
RewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\1
RewriteRule ^(.*)$ /%1/$1 [QSA]
Finally, all you need to do is create a folder in your subdomains folder, then place the subdomain's files in that directory.
Inspired by this post and by the Stack Overflow question that led me here -- Is it possible to insert multiple rows at a time in an SQLite database? -- I've posted my first Git repository:
https://github.com/rdpoor/CreateOrUpdate
which bulk loads an array of ActiveRecords into MySQL, SQLite or PostgreSQL databases. It includes an option to ignore existing records, overwrite them or raise an error. My rudimentary benchmarks show a 10x speed improvement compared to sequential writes -- YMMV.
I'm using it in production code where I frequently need to import large datasets, and I'm pretty happy with it.
Make an event when it's clicked and then manually change the value of true to the name of what the check box represents, then the name or true will evaluate the same and you can get all the values instead of a list of true/false. Ex:
component.html
<form [formGroup]="customForm" (ngSubmit)="onSubmit()">
<div class="form-group" *ngFor="let parameter of parameters"> <!--I iterate here to list all my checkboxes -->
<label class="control-label" for="{{parameter.Title}}"> {{parameter.Title}} </label>
<div class="checkbox">
<input
type="checkbox"
id="{{parameter.Title}}"
formControlName="{{parameter.Title}}"
(change)="onCheckboxChange($event)"
> <!-- ^^THIS^^ is the important part -->
</div>
</div>
</form>
component.ts
onCheckboxChange(event) {
//We want to get back what the name of the checkbox represents, so I'm intercepting the event and
//manually changing the value from true to the name of what is being checked.
//check if the value is true first, if it is then change it to the name of the value
//this way when it's set to false it will skip over this and make it false, thus unchecking
//the box
if(this.customForm.get(event.target.id).value) {
this.customForm.patchValue({[event.target.id] : event.target.id}); //make sure to have the square brackets
}
}
This catches the event after it was already changed to true or false by Angular Forms, if it's true I change the name to the name of what the checkbox represents, which if needed will also evaluate to true if it's being checked for true/false as well.
You need to merge the remote branch into your current branch by running git pull
.
If your local branch is already up-to-date, you may also need to run git pull --rebase
.
A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.
Something like:
File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
In my case, I use rails framework and require jQuery twice. I think that is a possible reason.
You can first check app/assets/application.js file. If the jquery and bootstrap-sprockets appears, then there is not need for a second library require. The file should be similar to this:
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .
Then check app/views/layouts/application.html.erb, and remove the script for requiring jquery. For example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
I think sometimes when newbies use multiple tutorial code examples will cause this issue.
var top = $('html').offset().top;
should do it.
edit: this is the negative of $(document).scrollTop()
Resolved it with VS update.
Resolution: Microsoft has published a fix for all impacted versions of Microsoft Visual Studio.
Visual Studio 2013 –
Download Visual Studio 2013 Update 4 For more information on the Visual Studio 2013 Update 4, please refer to: Visual Studio 2013 Update 4 KB Article Visual Studio 2012
An update to address this issue for Microsoft Visual Studio 2012 has been published: KB3002339 To install this update directly from the Microsoft Download Center, here Visual Studio 2010 SP1
An update to address this issue for Microsoft Visual Studio 2010 SP1 has been published: KB3002340 This update is available from Windows Update To install this update directly from the Microsoft Download Center, here
If you want your dates to conform a particular format or formats then use DateTime.TryParseExact
otherwise that is the default behaviour of DateTime.TryParse
This method tries to ignore unrecognized data, if possible, and fills in missing month, day, and year information with the current date. If s contains only a date and no time, this method assumes the time is 12:00 midnight. If s includes a date component with a two-digit year, it is converted to a year in the current culture's current calendar based on the value of the Calendar.TwoDigitYearMax property. Any leading, inner, or trailing white space character in s is ignored.
If you want to confirm against multiple formats then look at DateTime.TryParseExact Method (String, String[], IFormatProvider, DateTimeStyles, DateTime) overload. Example from the same link:
string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM",
"5/1/2009 6:32:00", "05/01/2009 06:32",
"05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"};
DateTime dateValue;
foreach (string dateString in dateStrings)
{
if (DateTime.TryParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None,
out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
// The example displays the following output:
// Converted '5/1/2009 6:32 PM' to 5/1/2009 6:32:00 PM.
// Converted '05/01/2009 6:32:05 PM' to 5/1/2009 6:32:05 PM.
// Converted '5/1/2009 6:32:00' to 5/1/2009 6:32:00 AM.
// Converted '05/01/2009 06:32' to 5/1/2009 6:32:00 AM.
// Converted '05/01/2009 06:32:00 PM' to 5/1/2009 6:32:00 PM.
// Converted '05/01/2009 06:32:00' to 5/1/2009 6:32:00 AM.
Current time with AM/PM designator:
DateTime.Now.ToString("hh:mm:ss tt", System.Globalization.DateTimeFormatInfo.InvariantInfo)
DateTime.Now.ToString("hh:mm:ss.fff tt", System.Globalization.DateTimeFormatInfo.InvariantInfo)
Current time using 0-23 hour notation:
DateTime.Now.ToString("HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo)
DateTime.Now.ToString("HH:mm:ss.fff", System.Globalization.DateTimeFormatInfo.InvariantInfo)
You can also add a UriComponentsBuilder
to the method signature of your controller method. Spring will inject an instance of the builder created from the current request.
@GetMapping
public ResponseEntity<MyResponse> doSomething(UriComponentsBuilder uriComponentsBuilder) {
URI someNewUriBasedOnCurrentRequest = uriComponentsBuilder
.replacePath(null)
.replaceQuery(null)
.pathSegment("some", "new", "path")
.build().toUri();
//...
}
Using the builder you can directly start creating URIs based on the current request e.g. modify path segments.
Topshelf is an OSS project which was started after this question was answered and it makes Windows service much, MUCH easier.I highly recommend looking into it.
I've used this in the past, since we typically use razor syntax for coding
@using (Html.BeginForm("actionName", "controllerName", FormMethod.Post, new { target = "_blank" }))
{
// add hidden and form filed here
}
With async actions (timers, ajax) you can override the property isDefaultPrevented
like this:
$('a').click(function(evt){
e.preventDefault();
// in async handler (ajax/timer) do these actions:
setTimeout(function(){
// override prevented flag to prevent jquery from discarding event
evt.isDefaultPrevented = function(){ return false; }
// retrigger with the exactly same event data
$(this).trigger(evt);
}, 1000);
}
This is most complete way of retriggering the event with the exactly same data.
In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.
If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line
git config core.autocrlf true
If you want to make an intelligent decision how git should handle this, read the documentation
Here is a snippet
Formatting and Whitespace
Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.
core.autocrlf
If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.
Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:
$ git config --global core.autocrlf true
If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:
$ git config --global core.autocrlf input
This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.
If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:
$ git config --global core.autocrlf false
Don't know (as for now) why, but this one helped:
@media print {
html, body {
border: 1px solid white;
height: 99%;
page-break-after: avoid;
page-break-before: avoid;
}
}
Hope someone will save his hair while fighting with the problem... ;)
Your script is being executed before the body
element has even loaded.
There are a couple ways to workaround this.
Wrap your logic in an event listener for DOMContentLoaded
.
In doing so, the callback will be executed when the body
element has loaded.
document.addEventListener('DOMContentLoaded', function () {
// ...
// Place code here.
// ...
});
Depending on your needs, you can alternatively attach a load
event listener to the window
object:
window.addEventListener('load', function () {
// ...
// Place code here.
// ...
});
For the difference between between the DOMContentLoaded
and load
events, see this question.
<script>
element, and load JavaScript last:Right now, your <script>
element is being loaded in the <head>
element of your document. This means that it will be executed before the body
has loaded. Google developers recommends moving the <script>
tags to the end of your page so that all the HTML content is rendered before the JavaScript is processed.
<!DOCTYPE html>
<html>
<head></head>
<body>
<p>Some paragraph</p>
<!-- End of HTML content in the body tag -->
<script>
<!-- Place your script tags here. -->
</script>
</body>
</html>
Not including the action attribute opens the page up to iframe clickjacking attacks, which involve a few simple steps:
References
it depends if your div is in position: absolute / fixed or relative / static
for position: absolute & fixed
<div style="position: absolute; /*or fixed*/;
width: 50%;
height: 300px;
left: 50%;
top:100px;
margin: 0 0 0 -25%">blblablbalba</div>
The trick here is to have a negative margin half the width of the object
for position: relative & static
<div style="position: relative; /*or static*/;
width: 50%;
height: 300px;
margin: 0 auto">blblablbalba</div>
for both techniques, it is imperative to set the width.
According to Collections Framework Overview you have two balanced tree implementations:
This issue occurred to me when I was sending an invalid HTTP Authorization header. I forgot to base64 encode it.
Having trouble wrapping my head around this.
Have a rewrite rule with four conditions.
The first three conditions A, B, C are to be AND which is then OR with D
RewriteCond A true
RewriteCond B false
RewriteCond C [OR] true
RewriteCond D true
RewriteRule ...
But that seems to be an expression of A and B and (C or D) = false (don't rewrite)
How can I get to the desired expression? (A and B and C) or D = true (rewrite)
Preferably without using the additional steps of setting environment variables.
HELP!!!
Simple way to start, try jQuery
$("#links").load("/Main_Page #jq-p-Getting-Started li");
More at jQuery Docs
Another way to do screen scraping in a much more structured way is to use YQL or Yahoo Query Language. It will return the scraped data structured as JSON or xml.
e.g.
Let's scrape stackoverflow.com
select * from html where url="http://stackoverflow.com"
will give you a JSON array (I chose that option) like this
"results": {
"body": {
"noscript": [
{
"div": {
"id": "noscript-padding"
}
},
{
"div": {
"id": "noscript-warning",
"p": "Stack Overflow works best with JavaScript enabled"
}
}
],
"div": [
{
"id": "notify-container"
},
{
"div": [
{
"id": "header",
"div": [
{
"id": "hlogo",
"a": {
"href": "/",
"img": {
"alt": "logo homepage",
"height": "70",
"src": "http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png",
"width": "250"
}
……..
The beauty of this is that you can do projections and where clauses which ultimately gets you the scraped data structured and only the data what you need (much less bandwidth over the wire ultimately)
e.g
select * from html where url="http://stackoverflow.com" and
xpath='//div/h3/a'
will get you
"results": {
"a": [
{
"href": "/questions/414690/iphone-simulator-port-for-windows-closed",
"title": "Duplicate: Is any Windows simulator available to test iPhone application? as a hobbyist who cannot afford a mac, i set up a toolchain kit locally on cygwin to compile objecti … ",
"content": "iphone\n simulator port for windows [closed]"
},
{
"href": "/questions/680867/how-to-redirect-the-web-page-in-flex-application",
"title": "I have a button control ....i need another web page to be redirected while clicking that button .... how to do that ? Thanks ",
"content": "How\n to redirect the web page in flex application ?"
},
…..
Now to get only the questions we do a
select title from html where url="http://stackoverflow.com" and
xpath='//div/h3/a'
Note the title in projections
"results": {
"a": [
{
"title": "I don't want the function to be entered simultaneously by multiple threads, neither do I want it to be entered again when it has not returned yet. Is there any approach to achieve … "
},
{
"title": "I'm certain I'm doing something really obviously stupid, but I've been trying to figure it out for a few hours now and nothing is jumping out at me. I'm using a ModelForm so I can … "
},
{
"title": "when i am going through my project in IE only its showing errors A runtime error has occurred Do you wish to debug? Line 768 Error:Expected')' Is this is regarding any script er … "
},
{
"title": "I have a java batch file consisting of 4 execution steps written for analyzing any Java application. In one of the steps, I'm adding few libs in classpath that are needed for my co … "
},
{
……
Once you write your query it generates a url for you
in our case.
So ultimately you end up doing something like this
var titleList = $.getJSON(theAboveUrl);
and play with it.
Beautiful, isn’t it?
If needing only glyphicon classes in CSS:
@font-face{font-family:'Glyphicons Halflings';src:url('https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot');src:url('https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),url('https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.woff') format('woff'),url('https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;}_x000D_
.glyphicon-asterisk:before{content:"\2a";}_x000D_
.glyphicon-plus:before{content:"\2b";}_x000D_
.glyphicon-euro:before{content:"\20ac";}_x000D_
.glyphicon-minus:before{content:"\2212";}_x000D_
.glyphicon-cloud:before{content:"\2601";}_x000D_
.glyphicon-envelope:before{content:"\2709";}_x000D_
.glyphicon-pencil:before{content:"\270f";}_x000D_
.glyphicon-glass:before{content:"\e001";}_x000D_
.glyphicon-music:before{content:"\e002";}_x000D_
.glyphicon-search:before{content:"\e003";}_x000D_
.glyphicon-heart:before{content:"\e005";}_x000D_
.glyphicon-star:before{content:"\e006";}_x000D_
.glyphicon-star-empty:before{content:"\e007";}_x000D_
.glyphicon-user:before{content:"\e008";}_x000D_
.glyphicon-film:before{content:"\e009";}_x000D_
.glyphicon-th-large:before{content:"\e010";}_x000D_
.glyphicon-th:before{content:"\e011";}_x000D_
.glyphicon-th-list:before{content:"\e012";}_x000D_
.glyphicon-ok:before{content:"\e013";}_x000D_
.glyphicon-remove:before{content:"\e014";}_x000D_
.glyphicon-zoom-in:before{content:"\e015";}_x000D_
.glyphicon-zoom-out:before{content:"\e016";}_x000D_
.glyphicon-off:before{content:"\e017";}_x000D_
.glyphicon-signal:before{content:"\e018";}_x000D_
.glyphicon-cog:before{content:"\e019";}_x000D_
.glyphicon-trash:before{content:"\e020";}_x000D_
.glyphicon-home:before{content:"\e021";}_x000D_
.glyphicon-file:before{content:"\e022";}_x000D_
.glyphicon-time:before{content:"\e023";}_x000D_
.glyphicon-road:before{content:"\e024";}_x000D_
.glyphicon-download-alt:before{content:"\e025";}_x000D_
.glyphicon-download:before{content:"\e026";}_x000D_
.glyphicon-upload:before{content:"\e027";}_x000D_
.glyphicon-inbox:before{content:"\e028";}_x000D_
.glyphicon-play-circle:before{content:"\e029";}_x000D_
.glyphicon-repeat:before{content:"\e030";}_x000D_
.glyphicon-refresh:before{content:"\e031";}_x000D_
.glyphicon-list-alt:before{content:"\e032";}_x000D_
.glyphicon-flag:before{content:"\e034";}_x000D_
.glyphicon-headphones:before{content:"\e035";}_x000D_
.glyphicon-volume-off:before{content:"\e036";}_x000D_
.glyphicon-volume-down:before{content:"\e037";}_x000D_
.glyphicon-volume-up:before{content:"\e038";}_x000D_
.glyphicon-qrcode:before{content:"\e039";}_x000D_
.glyphicon-barcode:before{content:"\e040";}_x000D_
.glyphicon-tag:before{content:"\e041";}_x000D_
.glyphicon-tags:before{content:"\e042";}_x000D_
.glyphicon-book:before{content:"\e043";}_x000D_
.glyphicon-print:before{content:"\e045";}_x000D_
.glyphicon-font:before{content:"\e047";}_x000D_
.glyphicon-bold:before{content:"\e048";}_x000D_
.glyphicon-italic:before{content:"\e049";}_x000D_
.glyphicon-text-height:before{content:"\e050";}_x000D_
.glyphicon-text-width:before{content:"\e051";}_x000D_
.glyphicon-align-left:before{content:"\e052";}_x000D_
.glyphicon-align-center:before{content:"\e053";}_x000D_
.glyphicon-align-right:before{content:"\e054";}_x000D_
.glyphicon-align-justify:before{content:"\e055";}_x000D_
.glyphicon-list:before{content:"\e056";}_x000D_
.glyphicon-indent-left:before{content:"\e057";}_x000D_
.glyphicon-indent-right:before{content:"\e058";}_x000D_
.glyphicon-facetime-video:before{content:"\e059";}_x000D_
.glyphicon-picture:before{content:"\e060";}_x000D_
.glyphicon-map-marker:before{content:"\e062";}_x000D_
.glyphicon-adjust:before{content:"\e063";}_x000D_
.glyphicon-tint:before{content:"\e064";}_x000D_
.glyphicon-edit:before{content:"\e065";}_x000D_
.glyphicon-share:before{content:"\e066";}_x000D_
.glyphicon-check:before{content:"\e067";}_x000D_
.glyphicon-move:before{content:"\e068";}_x000D_
.glyphicon-step-backward:before{content:"\e069";}_x000D_
.glyphicon-fast-backward:before{content:"\e070";}_x000D_
.glyphicon-backward:before{content:"\e071";}_x000D_
.glyphicon-play:before{content:"\e072";}_x000D_
.glyphicon-pause:before{content:"\e073";}_x000D_
.glyphicon-stop:before{content:"\e074";}_x000D_
.glyphicon-forward:before{content:"\e075";}_x000D_
.glyphicon-fast-forward:before{content:"\e076";}_x000D_
.glyphicon-step-forward:before{content:"\e077";}_x000D_
.glyphicon-eject:before{content:"\e078";}_x000D_
.glyphicon-chevron-left:before{content:"\e079";}_x000D_
.glyphicon-chevron-right:before{content:"\e080";}_x000D_
.glyphicon-plus-sign:before{content:"\e081";}_x000D_
.glyphicon-minus-sign:before{content:"\e082";}_x000D_
.glyphicon-remove-sign:before{content:"\e083";}_x000D_
.glyphicon-ok-sign:before{content:"\e084";}_x000D_
.glyphicon-question-sign:before{content:"\e085";}_x000D_
.glyphicon-info-sign:before{content:"\e086";}_x000D_
.glyphicon-screenshot:before{content:"\e087";}_x000D_
.glyphicon-remove-circle:before{content:"\e088";}_x000D_
.glyphicon-ok-circle:before{content:"\e089";}_x000D_
.glyphicon-ban-circle:before{content:"\e090";}_x000D_
.glyphicon-arrow-left:before{content:"\e091";}_x000D_
.glyphicon-arrow-right:before{content:"\e092";}_x000D_
.glyphicon-arrow-up:before{content:"\e093";}_x000D_
.glyphicon-arrow-down:before{content:"\e094";}_x000D_
.glyphicon-share-alt:before{content:"\e095";}_x000D_
.glyphicon-resize-full:before{content:"\e096";}_x000D_
.glyphicon-resize-small:before{content:"\e097";}_x000D_
.glyphicon-exclamation-sign:before{content:"\e101";}_x000D_
.glyphicon-gift:before{content:"\e102";}_x000D_
.glyphicon-leaf:before{content:"\e103";}_x000D_
.glyphicon-eye-open:before{content:"\e105";}_x000D_
.glyphicon-eye-close:before{content:"\e106";}_x000D_
.glyphicon-warning-sign:before{content:"\e107";}_x000D_
.glyphicon-plane:before{content:"\e108";}_x000D_
.glyphicon-random:before{content:"\e110";}_x000D_
.glyphicon-comment:before{content:"\e111";}_x000D_
.glyphicon-magnet:before{content:"\e112";}_x000D_
.glyphicon-chevron-up:before{content:"\e113";}_x000D_
.glyphicon-chevron-down:before{content:"\e114";}_x000D_
.glyphicon-retweet:before{content:"\e115";}_x000D_
.glyphicon-shopping-cart:before{content:"\e116";}_x000D_
.glyphicon-folder-close:before{content:"\e117";}_x000D_
.glyphicon-folder-open:before{content:"\e118";}_x000D_
.glyphicon-resize-vertical:before{content:"\e119";}_x000D_
.glyphicon-resize-horizontal:before{content:"\e120";}_x000D_
.glyphicon-hdd:before{content:"\e121";}_x000D_
.glyphicon-bullhorn:before{content:"\e122";}_x000D_
.glyphicon-certificate:before{content:"\e124";}_x000D_
.glyphicon-thumbs-up:before{content:"\e125";}_x000D_
.glyphicon-thumbs-down:before{content:"\e126";}_x000D_
.glyphicon-hand-right:before{content:"\e127";}_x000D_
.glyphicon-hand-left:before{content:"\e128";}_x000D_
.glyphicon-hand-up:before{content:"\e129";}_x000D_
.glyphicon-hand-down:before{content:"\e130";}_x000D_
.glyphicon-circle-arrow-right:before{content:"\e131";}_x000D_
.glyphicon-circle-arrow-left:before{content:"\e132";}_x000D_
.glyphicon-circle-arrow-up:before{content:"\e133";}_x000D_
.glyphicon-circle-arrow-down:before{content:"\e134";}_x000D_
.glyphicon-globe:before{content:"\e135";}_x000D_
.glyphicon-tasks:before{content:"\e137";}_x000D_
.glyphicon-filter:before{content:"\e138";}_x000D_
.glyphicon-fullscreen:before{content:"\e140";}_x000D_
.glyphicon-dashboard:before{content:"\e141";}_x000D_
.glyphicon-heart-empty:before{content:"\e143";}_x000D_
.glyphicon-link:before{content:"\e144";}_x000D_
.glyphicon-phone:before{content:"\e145";}_x000D_
.glyphicon-usd:before{content:"\e148";}_x000D_
.glyphicon-gbp:before{content:"\e149";}_x000D_
.glyphicon-sort:before{content:"\e150";}_x000D_
.glyphicon-sort-by-alphabet:before{content:"\e151";}_x000D_
.glyphicon-sort-by-alphabet-alt:before{content:"\e152";}_x000D_
.glyphicon-sort-by-order:before{content:"\e153";}_x000D_
.glyphicon-sort-by-order-alt:before{content:"\e154";}_x000D_
.glyphicon-sort-by-attributes:before{content:"\e155";}_x000D_
.glyphicon-sort-by-attributes-alt:before{content:"\e156";}_x000D_
.glyphicon-unchecked:before{content:"\e157";}_x000D_
.glyphicon-expand:before{content:"\e158";}_x000D_
.glyphicon-collapse-down:before{content:"\e159";}_x000D_
.glyphicon-collapse-up:before{content:"\e160";}_x000D_
.glyphicon-log-in:before{content:"\e161";}_x000D_
.glyphicon-flash:before{content:"\e162";}_x000D_
.glyphicon-log-out:before{content:"\e163";}_x000D_
.glyphicon-new-window:before{content:"\e164";}_x000D_
.glyphicon-record:before{content:"\e165";}_x000D_
.glyphicon-save:before{content:"\e166";}_x000D_
.glyphicon-open:before{content:"\e167";}_x000D_
.glyphicon-saved:before{content:"\e168";}_x000D_
.glyphicon-import:before{content:"\e169";}_x000D_
.glyphicon-export:before{content:"\e170";}_x000D_
.glyphicon-send:before{content:"\e171";}_x000D_
.glyphicon-floppy-disk:before{content:"\e172";}_x000D_
.glyphicon-floppy-saved:before{content:"\e173";}_x000D_
.glyphicon-floppy-remove:before{content:"\e174";}_x000D_
.glyphicon-floppy-save:before{content:"\e175";}_x000D_
.glyphicon-floppy-open:before{content:"\e176";}_x000D_
.glyphicon-credit-card:before{content:"\e177";}_x000D_
.glyphicon-transfer:before{content:"\e178";}_x000D_
.glyphicon-cutlery:before{content:"\e179";}_x000D_
.glyphicon-header:before{content:"\e180";}_x000D_
.glyphicon-compressed:before{content:"\e181";}_x000D_
.glyphicon-earphone:before{content:"\e182";}_x000D_
.glyphicon-phone-alt:before{content:"\e183";}_x000D_
.glyphicon-tower:before{content:"\e184";}_x000D_
.glyphicon-stats:before{content:"\e185";}_x000D_
.glyphicon-sd-video:before{content:"\e186";}_x000D_
.glyphicon-hd-video:before{content:"\e187";}_x000D_
.glyphicon-subtitles:before{content:"\e188";}_x000D_
.glyphicon-sound-stereo:before{content:"\e189";}_x000D_
.glyphicon-sound-dolby:before{content:"\e190";}_x000D_
.glyphicon-sound-5-1:before{content:"\e191";}_x000D_
.glyphicon-sound-6-1:before{content:"\e192";}_x000D_
.glyphicon-sound-7-1:before{content:"\e193";}_x000D_
.glyphicon-copyright-mark:before{content:"\e194";}_x000D_
.glyphicon-registration-mark:before{content:"\e195";}_x000D_
.glyphicon-cloud-download:before{content:"\e197";}_x000D_
.glyphicon-cloud-upload:before{content:"\e198";}_x000D_
.glyphicon-tree-conifer:before{content:"\e199";}_x000D_
.glyphicon-tree-deciduous:before{content:"\e200";}_x000D_
.glyphicon-briefcase:before{content:"\1f4bc";}_x000D_
.glyphicon-calendar:before{content:"\1f4c5";}_x000D_
.glyphicon-pushpin:before{content:"\1f4cc";}_x000D_
.glyphicon-paperclip:before{content:"\1f4ce";}_x000D_
.glyphicon-camera:before{content:"\1f4f7";}_x000D_
.glyphicon-lock:before{content:"\1f512";}_x000D_
.glyphicon-bell:before{content:"\1f514";}_x000D_
.glyphicon-bookmark:before{content:"\1f516";}_x000D_
.glyphicon-fire:before{content:"\1f525";}_x000D_
.glyphicon-wrench:before{content:"\1f527";}
_x000D_
I found Royi Namir's answer useful but expanded upon it to create it as a function. I renamed the variables to what made sense to me but you can translate them back easily enough, if desired.
Also, the code in Royi's answer already handled the case where the character being searched from does not exist (it starts from the beginning of the string), but I wanted to also handle cases where the character that is being searched to does not exist.
In that case it acts in a similar manner by starting from the searched from character and returning the rest of the characters to the end of the string.
CREATE FUNCTION [dbo].[getValueBetweenTwoStrings](@inputString
NVARCHAR(4000), @stringToSearchFrom NVARCHAR(4000), @stringToSearchTo
NVARCHAR(4000))
RETURNS NVARCHAR(4000)
AS
BEGIN
DECLARE @retVal NVARCHAR(4000)
DECLARE @stringToSearchFromSearchPattern NVARCHAR(4000) = '%' +
@stringToSearchFrom + '%'
SELECT @retVal = SUBSTRING (
@inputString,
PATINDEX(@stringToSearchFromSearchPattern, @inputString) + LEN(@stringToSearchFrom),
(CASE
CHARINDEX(
@stringToSearchTo,
@inputString,
PATINDEX(@stringToSearchFromSearchPattern, @inputString) + LEN(@stringToSearchFrom))
WHEN
0
THEN
LEN(@inputString) + 1
ELSE
CHARINDEX(
@stringToSearchTo,
@inputString,
PATINDEX(@stringToSearchFromSearchPattern, @inputString) + LEN(@stringToSearchFrom))
END) - (PATINDEX(@stringToSearchFromSearchPattern, @inputString) + LEN(@stringToSearchFrom))
)
RETURN @retVal
END
Usage:
SELECT dbo.getValueBetweenTwoStrings('images/test.jpg','/','.') AS MyResult
Windows 7/10: If your C:\Program Files
(or wherever R is installed) is blocked for writing, as mine is, then you'll get frustrated editing RProfile.site
(as I did). As specified above, I updated R_LIBS_USER
and it worked. However, even after reading the fine manual several times and extensive searching, it took me several hours to do this. In the spirit of saving someone else time...
Let's assume you want your packages to reside in C:\R\Library
:
C:\R\Library
Start
--> Control Panel
--> User Accounts
--> Change my environmental variables
Environmental Variables
window pops up. If you see R_LIBS_USER
, highlight it and click Edit
. Otherwise click New
. Both actions open a window with fields for Variable
and Value
.R_LIBS_USER
was already there, and the value was a path to my desktop. I added to the path the folder that I created, separated by semicolon as mentioned above. C:\R\Library;C:\Users\Eric.Krantz\Desktop\R stuff\Packages
. NOTE: I could have removed the path to the Desktop location and simply left C:\R\Library
.There's no need to add space before closing quote if path doesn't contain trailing backslash, so following command should work:
robocopy "C:\Source Path" "C:\Destination Path" /option1 /option2...
But, following will not work:
robocopy "C:\Source Path\" "C:\Destination Path\" /option1 /option2...
This is due to the escaping issue that is described here:
The \ escape can cause problems with quoted directory paths that contain a trailing backslash because the closing quote " at the end of the line will be escaped \".
This tutorial gives a simple, yet elegant, solution, which i transcribe:
#include <sstream>
#include <string>
#include <stdexcept>
class BadConversion : public std::runtime_error {
public:
BadConversion(std::string const& s)
: std::runtime_error(s)
{ }
};
inline std::string stringify(double x)
{
std::ostringstream o;
if (!(o << x))
throw BadConversion("stringify(double)");
return o.str();
}
...
std::string my_val = stringify(val);
ProgressDialog pd = new ProgressDialog(yourActivity.this);
pd.show();
With Modernizr you can target your hovers specifically for no-touch devices:
(Note: this doesn't run on StackOverflow's snippet system, check the jsfiddle instead)
/* this one is sticky */
#regular:hover, #regular:active {
opacity: 0.5;
}
/* this one isn't */
html.no-touch #no-touch:hover, #no-touch:active {
opacity: 0.5;
}
Note that :active
doesn't need to be targeted with .no-touch
because it works as expected on both mobile and desktop.
You can do it the following way:
DoCmd.OpenQuery "yourQueryName", acViewNormal, acEdit
OR
CurrentDb.OpenRecordset("yourQueryName")
Here's what I did in case someone finds it useful (I used a lot of things according to the rest of the answers in this thread):
First I adjusted the layout settings as needed. This changes the window size immediately so it was easier to set the exact size that I wanted. By the way I didn't know that I can also have visible width smaller than width buffer. This was nice since I usually hate a long line to be wrapped.
Then after clicking ok, I opened regedit.exe and went to "HKEY_CURRENT_USER\Console". There is a new child entry there "%SystemRoot%_system32_cmd.exe". I right clicked on that and selected Export:
I saved this as "cmd_settings.reg". Then I created a batch script that imports those settings, invokes my original batch script (name batch_script.bat) and then deletes what I imported in order for the command line window to return to default settings:
regedit /s cmd_settings.reg
start /wait batch_script.bat
reg delete "HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_cmd.exe" /f
This is a sample batch that could be invoked ("batch_script.bat"):
@echo off
echo test!
pause
exit
Don't forget the exit command at the end of your script if you want the reg delete line to run after the script execution.
Why is this happening?
The entire ext/mysql
PHP extension, which provides all functions named with the prefix mysql_
, was officially deprecated in PHP v5.5.0 and removed in PHP v7.
It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.
The manual has contained warnings against its use in new code since June 2011.
How can I fix it?
As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql
. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.
They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.
Hashphp.org has an excellent tutorial on migrating from ext/mysql
to PDO.
I understand that it's possible to suppress deprecation errors by setting
error_reporting
inphp.ini
to excludeE_DEPRECATED
:error_reporting = E_ALL ^ E_DEPRECATED
What will happen if I do that?
Yes, it is possible to suppress such error messages and continue using the old ext/mysql
extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.
Note also that this technique will suppress all E_DEPRECATED
messages, not just those to do with the ext/mysql
extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @
—however this will suppress all errors raised by that expression, not just E_DEPRECATED
ones.
You are starting a new project.
There is absolutely no reason to use ext/mysql
—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.
You have (your own) legacy codebase that currently depends upon ext/mysql
.
It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.
Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.
Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.
The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.
Consider whether you really need to upgrade to PHP v5.5 at this time.
You should begin planning to replace ext/mysql
with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.
However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
You are using a third party project that depends upon ext/mysql
.
Consider whether you really need to upgrade to PHP v5.5 at this time.
Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
It is absolutely essential to perform regression testing.
Using Rendertron is an option. Under the hood, this is a headless Chrome exposing the following endpoints:
/render/:url
: Access this route e.g. with requests.get
if you are interested in the DOM. /screenshot/:url
: Access this route if you are interested in a screenshot.You would install rendertron with npm, run rendertron
in one terminal, access http://localhost:3000/screenshot/:url
and save the file, but a demo is available at render-tron.appspot.com making it possible to run this Python3 snippet locally without installing the npm package:
import requests
BASE = 'https://render-tron.appspot.com/screenshot/'
url = 'https://google.com'
path = 'target.jpg'
response = requests.get(BASE + url, stream=True)
# save file, see https://stackoverflow.com/a/13137873/7665691
if response.status_code == 200:
with open(path, 'wb') as file:
for chunk in response:
file.write(chunk)
How about something like this ...
var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };
var g = l1.GroupBy( i => i );
foreach( var grp in g )
{
Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
}
Edit per comment: I will try and do this justice. :)
In my example, it's a Func<int, TKey>
because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an IGrouping<int,int>
(a grouping of ints keyed by an int). If I changed it to (i => i.ToString()
) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ...
private string SampleMethod( int i )
{
// magically return "One" if i == 1, "Two" if i == 2, etc.
}
So, that's a Func that would take an int and return a string, just like ...
i => // magically return "One" if i == 1, "Two" if i == 2, etc.
But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.
If you're using .Net 4 you can use the overload for string.Join
that takes an IEnumerable if you have them in a List, too:
string.Join(", ", strings);
ORDER_BY cast(registration_no as unsigned) ASC
explicitly converts the value to a number. Another possibility to achieve the same would be
ORDER_BY registration_no + 0 ASC
which will force an implicit conversation.
Actually you should check the table definition and change it. You can change the data type to int
like this
ALTER TABLE your_table MODIFY COLUMN registration_no int;
If you're more comfortable PCRE regex syntax, which
you have [g]vim compiled with perl feature, test using
:ver and inspect features; if +perl is there you're good to go)
try search/replace using
:perldo s///
Example. Swap src and alt attributes in img tag:
<p class="logo"><a href="/"><img src="/caminoglobal_en/includes/themes/camino/images/header_logo.png" alt=""></a></p>
:perldo s/(src=".*?")\s+(alt=".*?")/$2 $1/
<p class="logo"><a href="/"><img alt="" src="/caminoglobal_en/includes/themes/camino/images/header_logo.png"></a></p>
With Guava 15 you can also simply use:
Set s = Sets.newConcurrentHashSet();
Here is another solution, If you are using ES6 using spread operator:
var arr = [0, 21, 22, 7];
const indexOfMaxValue = arr.indexOf(Math.max(...arr));
simple:
scriptdir = replace(WScript.ScriptFullName,WScript.ScriptName,"")
This is an old question, but is high ranked on Google. I almost can't believe on the highest voted answers, because running a node.js process inside a screen session, with the &
or even with the nohup
flag -- all of them -- are just workarounds.
Specially the screen/tmux solution, which should really be considered an amateur solution. Screen and Tmux are not meant to keep processes running, but for multiplexing terminal sessions. It's fine, when you are running a script on your server and want to disconnect. But for a node.js server your don't want your process to be attached to a terminal session. This is too fragile. To keep things running you need to daemonize the process!
There are plenty of good tools to do that.
PM2: http://pm2.keymetrics.io/
# basic usage
$ npm install pm2 -g
$ pm2 start server.js
# you can even define how many processes you want in cluster mode:
$ pm2 start server.js -i 4
# you can start various processes, with complex startup settings
# using an ecosystem.json file (with env variables, custom args, etc):
$ pm2 start ecosystem.json
One big advantage I see in favor of PM2 is that it can generate the system startup script to make the process persist between restarts:
$ pm2 startup [platform]
Where platform
can be ubuntu|centos|redhat|gentoo|systemd|darwin|amazon
.
forever.js: https://github.com/foreverjs/forever
# basic usage
$ npm install forever -g
$ forever start app.js
# you can run from a json configuration as well, for
# more complex environments or multi-apps
$ forever start development.json
Init scripts:
I'm not go into detail about how to write a init script, because I'm not an expert in this subject and it'd be too long for this answer, but basically they are simple shell scripts, triggered by OS events. You can read more about this here
Docker:
Just run your server in a Docker container with -d
option and, voilá, you have a daemonized node.js server!
Here is a sample Dockerfile (from node.js official guide):
FROM node:argon
# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install
# Bundle app source
COPY . /usr/src/app
EXPOSE 8080
CMD [ "npm", "start" ]
Then build your image and run your container:
$ docker build -t <your username>/node-web-app .
$ docker run -p 49160:8080 -d <your username>/node-web-app
Hope this helps somebody landing on this page. Always use the proper tool for the job. It'll save you a lot of headaches and over hours!
If you want to re-filter the json data you can use following method. Given example is getting all document data from couchdb.
{
Gson gson = new Gson();
String resultJson = restTemplate.getForObject(url+"_all_docs?include_docs=true", String.class);
JSONObject object = (JSONObject) new JSONParser().parse(resultJson);
JSONArray rowdata = (JSONArray) object.get("rows");
List<Object>list=new ArrayList<Object>();
for(int i=0;i<rowdata.size();i++) {
JSONObject index = (JSONObject) rowdata.get(i);
JSONObject data = (JSONObject) index.get("doc");
list.add(data);
}
// convert your list to json
String devicelist = gson.toJson(list);
return devicelist;
}
I (using PostgrSQL on PGadmin4) queried for results that are after or on 21st Nov 2017 at noon, like this (considering the display format of hours on my database):
select * from Table1 where FIELD >='2017-11-21 12:00:00'
The one thing that adds clatter is the repeated stringVar
:
stringVar[stringVar.index(stringVar.startIndex, offsetBy: ...)
In Swift 4
An extension can reduce some of that:
extension String {
func index(at location: Int) -> String.Index {
return self.index(self.startIndex, offsetBy: location)
}
}
Then, usage:
let string = "abcde"
let to = string[..<string.index(at: 3)] // abc
let from = string[string.index(at: 3)...] // de
It should be noted that to
and from
are type Substring
(or String.SubSequance
). They do not allocate new strings and are more efficient for processing.
To get back a String
type, Substring
needs to be casted back to String
:
let backToString = String(from)
This is where a string is finally allocated.
I found two main problems with that implementation. First, when you import the vue.js
script you use type="JavaScript"
as content-type
which is wrong. You should remove this type
parameter because by default script
tags have text/javascript
as default content-type
. Or, just replace the type
parameter with the correct content-type
which is type="text/javascript"
.
The second problem is that your script is embedded in the same HTML file means that it may be triggered first and probably the vue.js
file was not loaded yet. You can fix this using a jQuery snippet $(function(){ /* ... */ });
or adding a javascript function as shown in this example:
// Verifies if the document is ready_x000D_
function ready(f) {_x000D_
/in/.test(document.readyState) ? setTimeout('ready(' + f + ')', 9) : f();_x000D_
}_x000D_
_x000D_
ready(function() {_x000D_
var demo = new Vue({_x000D_
el: '#demo',_x000D_
data: {_x000D_
message: 'Hello Vue.js!'_x000D_
}_x000D_
})_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
<div id="demo">_x000D_
<p>{{message}}</p>_x000D_
<input v-model="message">_x000D_
</div>
_x000D_
Changing the ng-src
value is actually very simple. Like this:
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>
Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/
you can define it like this :
let table = $('.datatable-sales').DataTable({
processing: true,
responsive: true,
serverSide: true,
ajax: {
url: "<?php echo site_url("your url"); ?>",
cache: false,
type: "POST",
data: {
<?php echo your api; ?>,
}
}
or like this :
$.get({url: <?php echo json_encode(site_url('your api'))?>, cache: false})
hope it helps
An alternative that also has the added benefit of easily logging its output:
hexs = "13 00 00 00 08 00"
logging.debug(hexs)
key = bytearray.fromhex(hexs)
allows you to do easy substitutions like so:
hexs = "13 00 00 00 08 {:02X}".format(someByte)
logging.debug(hexs)
key = bytearray.fromhex(hexs)
The best tool I found useful and worked every time is code review (with good code reviewers).
Other than code review, I'd first try Page Heap. Page Heap takes a few seconds to set up and with luck it might pinpoint your problem.
If no luck with Page Heap, download Debugging Tools for Windows from Microsoft and learn to use the WinDbg. Sorry couldn't give you more specific help, but debuging multi-threaded heap corruption is more an art than science. Google for "WinDbg heap corruption" and you should find many articles on the subject.
I prefer java's built in TimeUnit library
long seconds = TimeUnit.MINUTES.toSeconds(8);
SQLExplorer is a great Eclipse plugin or standalone interface that works with many different database systems, either with dedicated drivers or with ODBC.
In my case, My principal was kafka/[email protected]
I got below lines in the terminal:
>>> KrbKdcReq send: #bytes read=190
>>> KdcAccessibility: remove kerberos.niroshan.com
>>> KDCRep: init() encoding tag is 126 req type is 13
>>>KRBError:
cTime is Thu Oct 05 03:42:15 UTC 1995 812864535000
sTime is Fri May 31 06:43:38 UTC 2019 1559285018000
suSec is 111309
error code is 7
error Message is Server not found in Kerberos database
cname is kafka/[email protected]
sname is kafka/[email protected]
msgType is 30
After hours of checking, I just found the below line has a wrong value in kafka_2.12-2.2.0/server.properties
listeners=SASL_PLAINTEXT://kafka.com:9092
Also I got two entries of kafka.niroshan.com
and kafka.com
for same IP address.
I changed it to as listeners=SASL_PLAINTEXT://kafka.niroshan.com:9092
Then it worked!
According to the below link, the principal should contain the Fully Qualified Domain Name (FQDN) of each host and it should be matched with the principal.
https://docs.oracle.com/cd/E19253-01/816-4557/planning-25/index.html
This can be useful to see the progress of long insert queries, make any rough estimates (like COUNT(*)
or rough SUM(*)
) etc.
In other words, the results the dirty read queries return are fine as long as you treat them as estimates and don't make any critical decisions based upon them.
I had this problem, or one that looked superficially similar, yesterday. It turned out that I wasn't being careful when mixing jQuery and prototype. I found several solutions at http://docs.jquery.com/Using_jQuery_with_Other_Libraries. I opted for
var $j = jQuery.noConflict();
but there are other reasonable options described there.
You should've kept that DOM ready function
$(function() {
$("#projectKey").change(function() {
alert( $('option:selected', this).text() );
});
});
The document isn't ready if you added the javascript before the elements in the DOM, you have to either use a DOM ready function or add the javascript after the elements, the usual place is right before the </body>
tag
JavaScript automatically inserts semicolons whilst interpreting your code, so if you put the value of the return statement below the line, it won't be returned:
Your Code:
return
5
JavaScript Interpretation:
return;
5;
Thus, nothing is returned, because of JavaScript's auto semicolon insertion
Try to add ReactiveFormsModule in your component as well.
import { FormGroup, FormArray, FormBuilder,
Validators,ReactiveFormsModule } from '@angular/forms';
You can try using the ReadDir function in the io/ioutil
package. Per the docs:
ReadDir reads the directory named by dirname and returns a list of sorted directory entries.
The resulting slice contains os.FileInfo
types, which provide the methods listed here. Here is a basic example that lists the name of everything in the current directory (folders are included but not specially marked - you can check if an item is a folder by using the IsDir()
method):
package main
import (
"fmt"
"io/ioutil"
"log"
)
func main() {
files, err := ioutil.ReadDir("./")
if err != nil {
log.Fatal(err)
}
for _, f := range files {
fmt.Println(f.Name())
}
}
I would simply change a column name to the dataset with the new name I want with the following code: names(dataset)[index_value] <- "new_col_name"
You might find it very useful to sample Redis keys and group them by type. Salvatore has written a tool called redis-sampler that issues about 10000 RANDOMKEY
commands followed by a TYPE
on retrieved keys. In a matter of seconds, or minutes, you should get a fairly accurate view of the distribution of key types.
I've written an extension (unfortunately not anywhere open-source because it's work related), that adds a bit of introspection of key names via regexs that give you an idea of what kinds of application keys (according to whatever naming structure you're using), are stored in Redis. Combined with the more general output of redis-sampler, this should give you an extremely good idea of what's going on.
You can change background-color and use !important;
.btn-primary {_x000D_
background-color: #003c79 !important;_x000D_
border-color: #15548b !important;_x000D_
color: #fff;_x000D_
}_x000D_
_x000D_
.btn-primary:hover {_x000D_
background-color: #4289c6 !important;_x000D_
border-color: #3877ae !important;_x000D_
color: #fff;_x000D_
}_x000D_
_x000D_
.btn-primary.focus, .btn-primary:focus {_x000D_
background-color: #4289c6 !important;_x000D_
border-color: #3877ae !important;_x000D_
color: #fff;_x000D_
}
_x000D_
I use new Date().getTime()
, which will avoid collisions unless you have multiple requests happening within the same millisecond:
$.get('/getdata?_=' + new Date().getTime(), function(data) {
console.log(data);
});
Edit: This answer is several years old. It still works (hence I haven't deleted it), but there are better/cleaner ways of achieving this now. My preference is for this method, but this answer is also useful if you want to disable caching for every request during the lifetime of a page.
Using Javascript, all you need is document.createElement
and setAttribute
.
var input = document.createElement("input");
input.setAttribute('type', 'text');
Then you can use appendChild
to append the created element to the desired parent element.
var parent = document.getElementById("parentDiv");
parent.appendChild(input);
Unwind segues are used to "go back" to some view controller from which, through a number of segues, you got to the "current" view controller.
Imagine you have something a MyNavController
with A
as its root view controller. Now you use a push segue to B
. Now the navigation controller has A and B in its viewControllers
array, and B is visible. Now you present C
modally.
With unwind segues, you could now unwind "back" from C
to B
(i.e. dismissing the modally presented view controller), basically "undoing" the modal segue. You could even unwind all the way back to the root view controller A
, undoing both the modal segue and the push segue.
Unwind segues make it easy to backtrack. For example, before iOS 6, the best practice for dismissing presented view controllers was to set the presenting view controller as the presented view controller’s delegate, then call your custom delegate method, which then dismisses the presentedViewController. Sound cumbersome and complicated? It was. That’s why unwind segues are nice.
Your question is difficult to understand, but if you want to select the numbers from 1
to 100
, then this should do the trick:
Select Rownum r
From dual
Connect By Rownum <= 100
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<EventSetter Event="MouseDoubleClick" Handler="listViewItem_MouseDoubleClick" />
</Style>
</ListView.ItemContainerStyle>
The only difficulty then is if you are interested in the underlying object the listviewitem maps to e.g.
private void listViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
ListViewItem item = sender as ListViewItem;
object obj = item.Content;
}
Most of these answers explain what %n
does (which is to print nothing and to write the number of characters printed thus far to an int
variable), but so far no one has really given an example of what use it has. Here is one:
int n;
printf("%s: %nFoo\n", "hello", &n);
printf("%*sBar\n", n, "");
will print:
hello: Foo
Bar
with Foo and Bar aligned. (It's trivial to do that without using %n
for this particular example, and in general one always could break up that first printf
call:
int n = printf("%s: ", "hello");
printf("Foo\n");
printf("%*sBar\n", n, "");
Whether the slightly added convenience is worth using something esoteric like %n
(and possibly introducing errors) is open to debate.)
InnoDB allows you to add a new foreign key constraint to a table by using ALTER TABLE:
ALTER TABLE tbl_name
ADD [CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
On the other hand, if MyISAM has advantages over InnoDB in your context, why would you want to create foreign key constraints at all. You can handle this on the model level of your application. Just make sure the columns which you want to use as foreign keys are indexed!
Well, the simplest way using LINQ would be something like this:
list = list.OrderBy(x => x.AVC ? 0 : 1)
.ToList();
or
list = list.OrderByDescending(x => x.AVC)
.ToList();
I believe that the natural ordering of bool
values is false < true
, but the first form makes it clearer IMO, because everyone knows that 0 < 1
.
Note that this won't sort the original list itself - it will create a new list, and assign the reference back to the list
variable. If you want to sort in place, you should use the List<T>.Sort
method.
The HTML attribute required="required"
is a statement telling the browser that this field is required in order for the form to be valid. (required="required"
is the XHTML form, just using required
is equivalent)
The Angular attribute ng-required="yourCondition"
means 'isRequired(yourCondition)' and sets the HTML attribute dynamically for you depending on your condition.
Also note that the HTML version is confusing, it is not possible to write something conditional like required="true"
or required="false"
, only the presence of the attribute matters (present means true) ! This is where Angular helps you out with ng-required
.
This can help you
namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", image ); // Show our image inside it.
There is no way to do pure text search in whole work workspace/project via a shortcut that I know of (and it is a PITA), but this will find references in the workspace:
I'll share a code which has Basic Auth Header form data request body,
let username = 'test-name';
let password = 'EbQZB37gbS2yEsfs';
let formdata = new FormData();
let headers = new Headers();
formdata.append('grant_type','password');
formdata.append('username','testname');
formdata.append('password','qawsedrf');
headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password));
fetch('https://www.example.com/token.php', {
method: 'POST',
headers: headers,
body: formdata
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
data: responseJson
})
})
.catch((error) => {
console.error(error);
});
Controller as version (recommended)
Here the template
<div ng-app="example" ng-controller="myController as $ctrl">
<input type="text" ng-model="$ctrl.searchText" />
<button ng-click="$ctrl.check()">Check!</button>
{{ $ctrl.searchText }}
</div>
The JS
angular.module('example', [])
.controller('myController', function() {
var vm = this;
vm.check = function () {
console.log(vm.searchText);
};
});
An example: http://codepen.io/Damax/pen/rjawoO
The best will be to use component with Angular 2.x or Angular 1.5 or upper
########Old way (NOT recommended)
This is NOT recommended because a string is a primitive, highly recommended to use an object instead
Try this in your markup
<input type="text" ng-model="searchText" />
<button ng-click="check(searchText)">Check!</button>
{{ searchText }}
and this in your controller
$scope.check = function (searchText) {
console.log(searchText);
}
Make sure you somehow use results which are computed in benchmarked code. Otherwise your code can be optimized away.
A simple Android Easy QR Code Library. It is very easy to use, to use this library follow these steps.
Step 1. Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Step 2. Add the dependency:
dependencies {
compile 'com.github.mrasif:easyqrlibrary:v1.0.0'
}
Step 1. Add the JitPack repository to your build file:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Step 2. Add the dependency:
<dependency>
<groupId>com.github.mrasif</groupId>
<artifactId>easyqrlibrary</artifactId>
<version>v1.0.0</version>
</dependency>
Step 1. Add the JitPack repository to your build.sbt file:
resolvers += "jitpack" at "https://jitpack.io"
Step 2. Add the dependency:
libraryDependencies += "com.github.mrasif" % "easyqrlibrary" % "v1.0.0"
Step 1. Add it in your project.clj at the end of repositories:
:repositories [["jitpack" "https://jitpack.io"]]
Step 2. Add the dependency:
:dependencies [[com.github.mrasif/easyqrlibrary "v1.0.0"]]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="@+id/tvData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="No QR Data"/>
<Button
android:id="@+id/btnQRScan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="QR Scan"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView tvData;
Button btnQRScan;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData=findViewById(R.id.tvData);
btnQRScan=findViewById(R.id.btnQRScan);
btnQRScan.setOnClickListener(this);
}
@Override
public void onClick(View view){
switch (view.getId()){
case R.id.btnQRScan: {
Intent intent=new Intent(MainActivity.this, QRScanner.class);
startActivityForResult(intent, EasyQR.QR_SCANNER_REQUEST);
} break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case EasyQR.QR_SCANNER_REQUEST: {
if (resultCode==RESULT_OK){
tvData.setText(data.getStringExtra(EasyQR.DATA));
}
} break;
}
}
}
For customized scanner screen just add these lines when you start the scanner Activity.
Intent intent=new Intent(MainActivity.this, QRScanner.class);
intent.putExtra(EasyQR.IS_TOOLBAR_SHOW,true);
intent.putExtra(EasyQR.TOOLBAR_DRAWABLE_ID,R.drawable.ic_audiotrack_dark);
intent.putExtra(EasyQR.TOOLBAR_TEXT,"My QR");
intent.putExtra(EasyQR.TOOLBAR_BACKGROUND_COLOR,"#0588EE");
intent.putExtra(EasyQR.TOOLBAR_TEXT_COLOR,"#FFFFFF");
intent.putExtra(EasyQR.BACKGROUND_COLOR,"#000000");
intent.putExtra(EasyQR.CAMERA_MARGIN_LEFT,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_TOP,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_RIGHT,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_BOTTOM,50);
startActivityForResult(intent, EasyQR.QR_SCANNER_REQUEST);
You are done. Ref. Link: https://mrasif.github.io/easyqrlibrary
Below is an example of a method in a Java controller.
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public HttpStatus something(@RequestBody MyModel myModel)
{
return HttpStatus.OK;
}
By using @RequestBody annotation you will get your values mapped with the model you created in your system for handling any specific call. While by using @ResponseBody you can send anything back to the place from where the request was generated. Both things will be mapped easily without writing any custom parser etc.
I came across this error while making a segue from a table view controller to a view controller because I had forgotten to specify the custom class name for the view controller in the main storyboard.
Something simple that is worth checking if all else looks ok
You could use a bit of jQuery:
$('input:radio').click(function(){
$('label#' + $(this).attr('id')).toggleClass('checkedClass'); // checkedClass is defined in your CSS
});
You'd need to make sure your checked radio buttons have the correct class on page load as well.
For those who switched to Kotlin just use
string.toLong()
That will call Long.parseLong(string)
under the hood
If you give each of these instances a class you can use
$('.yourClass').upload()
General Query
save the below lines in notepad with name batch.bat and place inside the folder where all your script file are there
for %%G in (*.sql) do sqlcmd /S servername /d databasename -i"%%G"
pause
EXAMPLE
for %%G in (*.sql) do sqlcmd /S NFGDDD23432 /d EMPLYEEDB -i"%%G" pause
sometime if login failed for you please use the below code with username and password
for %%G in (*.sql) do sqlcmd /S SERVERNAME /d DBNAME -U USERNAME -P PASSWORD -i"%%G"
pause
for %%G in (*.sql) do sqlcmd /S NE8148server /d EMPLYEEDB -U Scott -P tiger -i"%%G" pause
After you create the bat file inside the folder in which your Script files are there just click on the bat file your scripts will get executed
You could try either of these. They are not giving me errors.
It is also the suggested method from typescript for array declaration.
By using the Array<Thing>
it is making use of the generics in typescript. It is similar to asking for a List<T>
in c# code.
// Declare with default value
private _possessions: Array<Thing> = new Array<Thing>();
// or
private _possessions: Array<Thing> = [];
// or -> prefered by ts-lint
private _possessions: Thing[] = [];
or
// declare
private _possessions: Array<Thing>;
// or -> preferd by ts-lint
private _possessions: Thing[];
constructor(){
//assign
this._possessions = new Array<Thing>();
//or
this._possessions = [];
}
If the new domain you are redirecting your old site to is on a diffrent host, you can simply use a Redirect
Redirect 301 / http://newdomain.com
This will redirect all requests from olddomain
to the newdomain
.
Redirect
directive will not work or may cause a Redirect loop
if your newdomain and olddomain both are on same host, in that case you'll need to use mod-rewrite
to redirect based on the requested host header.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?olddomain\.com$
RewriteRule ^ http://newdomain.com%{REQUEST_URI} [NE,L,R]
The answer provided by @Jean provides a working but obscure solution (although it doesn't handle trailing spaces)
As an alternative consider a vba user defined function (UDF)
Function RightWord(r As Range) As Variant
Dim s As String
s = Trim(r.Value)
RightWord = Mid(s, InStrRev(s, " ") + 1)
End Function
Use in sheet as
=RightWord(A2)
If you want to delete using line numbers you can use:
:startingline, last line d
Example:
:7,20 d
This example will delete line 7 to 20.
I also had to update the version of Tomcat I was using from Tomcat 7 to Tomcat 8.
I will try to explain you what this error is about.
Starting from MySQL 5.7.5, option ONLY_FULL_GROUP_BY
is enabled by default.
Thus, according to standart SQL92 and earlier:
does not permit queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on (uniquely determined by) GROUP BY columns
So, for example:
SELECT * FROM `users` GROUP BY `name`;
You will get error message after executing query above.
#1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'testsite.user.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
Why?
Because MySQL dont exactly understand, what certain values from grouped records to retrieve, and this is the point.
I.E. lets say you have this records in your users
table:
And you will execute invalid query showen above.
And you will get error shown above, because, there is 3 records with name John
, and it is nice, but, all of them have different email
field values.
So, MySQL simply don't understand which of them to return in resulting grouped record.
You can fix this issue, by simply changing your query like this:
SELECT `name` FROM `users` GROUP BY `name`
Also, you may want to add more fields to SELECT section, but you cant do that, if they are not aggregated, but there is crutch you could use (but highly not reccomended):
SELECT ANY_VALUE(`id`), ANY_VALUE(`email`), `name` FROM `users` GROUP BY `name`
Now, you may ask, why using ANY_VALUE
is highly not recommended?
Because MySQL don't exactly know what value of grouped records to retrieve, and by using this function, you asking it to fetch any of them (in this case, email of first record with name = John was fetched).
Exactly I cant come up with any ideas on why you would want this behaviour to exist.
Please, if you dont understand me, read more about how grouping in MySQL works, it is very simple.
And by the end, here is one more simple, yet valid query.
If you want to query total users count according to available ages, you may want to write down this query
SELECT `age`, COUNT(`age`) FROM `users` GROUP BY `age`;
Which is fully valid, according to MySQL rules.
And so on.
It is important to understand what exactly the problem is and only then write down the solution.
Notice: Trying to get property of non-object in C:\wamp\www\phone\pages\init.php on line 22
@22 is
<?php echo $sidemenu->mname."<br />";?>
$sidemenu
is not an object, and you are trying to access one of its properties.
That is the reason for your error.
This was written quickly, and is neither pretty nor efficient (plus it autoboxes alot, converting between int
and Integer
is annoying!), but it works.
It probably breaks the rules since I'm creating my own objects but hey I'm doing this as a diversion from real work :)
This also assumes that the resultSet/table is completely read into some sort of structure before you start building Nodes, which wouldn't be the best solution if you have hundreds of thousands of rows.
public class Node {
private Node parent = null;
private List<Node> children;
private String name;
private int id = -1;
public Node(Node parent, int id, String name) {
this.parent = parent;
this.children = new ArrayList<Node>();
this.name = name;
this.id = id;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
public void addChild(Node child) {
children.add(child);
}
public List<Node> getChildren() {
return children;
}
public boolean isRoot() {
return (this.parent == null);
}
@Override
public String toString() {
return "id=" + id + ", name=" + name + ", parent=" + parent;
}
}
public class NodeBuilder {
public static Node build(List<Map<String, String>> input) {
// maps id of a node to it's Node object
Map<Integer, Node> nodeMap = new HashMap<Integer, Node>();
// maps id of a node to the id of it's parent
Map<Integer, Integer> childParentMap = new HashMap<Integer, Integer>();
// create special 'root' Node with id=0
Node root = new Node(null, 0, "root");
nodeMap.put(root.getId(), root);
// iterate thru the input
for (Map<String, String> map : input) {
// expect each Map to have keys for "id", "name", "parent" ... a
// real implementation would read from a SQL object or resultset
int id = Integer.parseInt(map.get("id"));
String name = map.get("name");
int parent = Integer.parseInt(map.get("parent"));
Node node = new Node(null, id, name);
nodeMap.put(id, node);
childParentMap.put(id, parent);
}
// now that each Node is created, setup the child-parent relationships
for (Map.Entry<Integer, Integer> entry : childParentMap.entrySet()) {
int nodeId = entry.getKey();
int parentId = entry.getValue();
Node child = nodeMap.get(nodeId);
Node parent = nodeMap.get(parentId);
parent.addChild(child);
}
return root;
}
}
public class NodePrinter {
static void printRootNode(Node root) {
printNodes(root, 0);
}
static void printNodes(Node node, int indentLevel) {
printNode(node, indentLevel);
// recurse
for (Node child : node.getChildren()) {
printNodes(child, indentLevel + 1);
}
}
static void printNode(Node node, int indentLevel) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < indentLevel; i++) {
sb.append("\t");
}
sb.append(node);
System.out.println(sb.toString());
}
public static void main(String[] args) {
// setup dummy data
List<Map<String, String>> resultSet = new ArrayList<Map<String, String>>();
resultSet.add(newMap("1", "Node 1", "0"));
resultSet.add(newMap("2", "Node 1.1", "1"));
resultSet.add(newMap("3", "Node 2", "0"));
resultSet.add(newMap("4", "Node 1.1.1", "2"));
resultSet.add(newMap("5", "Node 2.1", "3"));
resultSet.add(newMap("6", "Node 1.2", "1"));
Node root = NodeBuilder.build(resultSet);
printRootNode(root);
}
//convenience method for creating our dummy data
private static Map<String, String> newMap(String id, String name, String parentId) {
Map<String, String> row = new HashMap<String, String>();
row.put("id", id);
row.put("name", name);
row.put("parent", parentId);
return row;
}
}
These commands will do the work on command prompt without altering any files on local repository
git config --file=.gitmodules submodule.Submod.url https://github.com/username/ABC.git
git config --file=.gitmodules submodule.Submod.branch Development
git submodule sync
git submodule update --init --recursive --remote
Please look at the blog for screenshots: Changing GIT submodules URL/Branch to other URL/branch of same repository
as far as we want to send all the form input fields which have name attribute, you can do this for all forms, regardless of the field names:
First Solution
function submitForm(form){
var url = form.attr("action");
var formData = {};
$(form).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$.post(url, formData).done(function (data) {
alert(data);
});
}
Second Solution: in this solution you can create an array of input values:
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
I also found
/Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist
after using all of the other answers here to uninstall MySQL Community Server 8.0.15 from OS X 10.10.
FIXED!
I've been wrestling with the same issue, and just had a breakthrough! We've established that if you give the image a background color or image, the png displays properly on top of it. The black border is gone, but now you've got an opaque background, and that pretty much defeats the purpose.
Then I remembered a rgba to ie filter converter I came across. (Thanks be to Michael Bester). So I wondered what would happen if I gave my problem pngs an ie filtered background emulating rgba(255,255,255,0), fully expecting it not to work, but lets try it anyway...
.item img {
background: transparent;
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)"; /* IE8 */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF); /* IE6 & 7 */
zoom: 1;
}
Presto! Goodbye black, and hello working alpha channels in ie7 and 8. Fade your pngs in and out, or animate them across the screen - it's all good.
You can try it by adding
If you wanna compare Spring MVC with struts consider below benefit of Spring MVC over Struts.
The :before
pseudo element isn't needed for the clearfix hack itself.
It's just an additional nice feature helping to prevent margin-collapsing of the first child element. Thus the top margin of an child block element of the "clearfixed" element is guaranteed to be positioned below the top border of the clearfixed element.
display:table
is being used because display:block
doesn't do the trick. Using display:block
margins will collapse even with a :before
element.
There is one caveat: if vertical-align:baseline
is used in table cells with clearfixed <div>
elements, Firefox won't align well. Then you might prefer using display:block
despite loosing the anti-collapsing feature. In case of further interest read this article: Clearfix interfering with vertical-align.
For a version with pure Bash and without test
, but really ugly, try:
if ( exit "${s1/*$s2*/0}" )2>/dev/null
then
echo match
fi
Explanation: In ( )
an extra subshell is opened. It exits with 0 if there was a match, and it tries to exit with $s1 if there was no match which raises an error (ugly). This error is directed to /dev/null
.
Ok, this is a very interesting problem I researched a lot and came to a conclusion that private members of a superclass are indeed available (but not accessible) in the subclass's objects. To prove this, here is a sample code with a parent class and a child class and I am writing child class object to a txt file and reading a private member named 'bhavesh' in the file, hence proving it is indeed available in the child class but not accessible due to the access modifier.
import java.io.Serializable;
public class ParentClass implements Serializable {
public ParentClass() {
}
public int a=32131,b,c;
private int bhavesh=5555,rr,weq,refw;
}
import java.io.*;
import java.io.Serializable;
public class ChildClass extends ParentClass{
public ChildClass() {
super();
}
public static void main(String[] args) {
ChildClass childObj = new ChildClass();
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(new FileOutputStream("C:\\MyData1.txt"));
oos.writeObject(childObj); //Writing child class object and not parent class object
System.out.println("Writing complete !");
} catch (IOException e) {
}
}
}
Open MyData1.txt and search for the private member named 'bhavesh'. Please let me know what you guys think.
On Mac:
brew install mysql-client
locate mysql
mdfind mysql | grep bin
then add to path
export PATH=$PATH:/usr/local/Cellar/mysql-client/8.0.23/bin/
or permanently
echo "export PATH=$PATH:/usr/local/Cellar/mysql-client/8.0.23/bin/" >> ~/.zshrc
source ~/.zshrc
SELECT * FROM employees e1, employees e2
WHERE e1.phoneNumber = e2.phoneNumber
AND e1.id != e2.id;
Update : for better performance and faster query its good to add e1
before *
SELECT e1.* FROM employees e1, employees e2
WHERE e1.phoneNumber = e2.phoneNumber
AND e1.id != e2.id;
a:link{
text-decoration: none!important;
}
=> Working with me :) , good luck
JavaScript is case sensitive.
So, if you want to change the font size, you have to go:
span.style.fontSize = "25px";
The schema object naming rules may also be of some use:
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/sql_elements008.htm#sthref723
This question will get moved but you can do the following
which javac
or
cd /
find . -name 'javac'
This in not a perfect answer but will get much better performance.
SELECT *
FROM (
SELECT *
FROM mytable sample (0.01)
ORDER BY
dbms_random.value
)
WHERE rownum <= 1000
Sample will give you a percent of your actual table, if you really wanted a 1000 rows you would need to adjust that number. More often I just need an arbitrary number of rows anyway so I don't limit my results. On my database with 2 million rows I get 2 seconds vs 60 seconds.
select * from mytable sample (0.01)
Here's how i am calling my modal
<a data-toggle="modal" data-id="190" data-target="#modal-popup">Open</a>
Here's how i am obtaining value in the modal
$('#modal-popup').on('show.bs.modal', function(e) {
console.log($(e.relatedTarget).data('id')); // 190 will be printed
});
This work for me
I set style's font before and make rowheader normally then i set in loop for the style with font bolded on each cell of rowhead. Et voilà first row is bolded.
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("FirstSheet");
HSSFRow rowhead = sheet.createRow(0);
HSSFCellStyle style = wb.createCellStyle();
HSSFFont font = wb.createFont();
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short)10);
font.setBold(true);
style.setFont(font);
rowhead.createCell(0).setCellValue("ID");
rowhead.createCell(1).setCellValue("First");
rowhead.createCell(2).setCellValue("Second");
rowhead.createCell(3).setCellValue("Third");
for(int j = 0; j<=3; j++)
rowhead.getCell(j).setCellStyle(style);
just set the hidden field with javascript :
document.getElementById('elementId').value = 'whatever';
or do I miss something?
Try this code in Swift or Objective-C
Swift
self.tabBarController.selectedIndex = 1
Objective-C
[self.tabBarController setSelectedIndex:1];
Make sure you have downloaded the latest 'Command Line Tools' package and run this from a terminal (command line):
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
For some information on Catalina, see Can't compile a C program on a Mac after upgrading to Catalina 10.15.
Extracting a semi-coherent answer from rather extensive comments…
Very often, xcode-select --install
has been the correct solution, but it does not seem to help this time. Have you tried running the main Xcode GUI interface? It may install some extra software for you and clean up. I did that after installing Xcode 10.0, but a week or more ago, long before upgrading to Mojave.
I observe that if your GCC is installed in /usr/local/bin
, you probably aren't using the GCC from Xcode; that's normally installed in /usr/bin
.
I too have updated to macOS 10.14 Mojave and Xcode 10.0. However, both the system /usr/bin/gcc
and system /usr/bin/clang
are working for me (Apple LLVM version 10.0.0 (clang-1000.11.45.2) Target: x86_64-apple-darwin18.0.0
for both.) I have a problem with my home-built GCC 8.2.0 not finding headers in /usr/include
, which is parallel to your problem with /usr/local/bin/gcc
not finding headers either.
I've done a bit of comparison, and my Mojave machine has no /usr/include
at all, yet /usr/bin/clang
is able to compile OK. A header (_stdio.h
, with leading underscore) was in my old /usr/include
; it is missing now (hence my problem with GCC 8.2.0). I ran xcode-select --install
and it said "xcode-select: note: install requested for command line developer tools
" and then ran a GUI installer which showed me a licence which I agreed to, and it downloaded and installed the command line tools — or so it claimed.
I then ran Xcode GUI (command-space, Xcode, return) and it said it needed to install some more software, but still no /usr/include
. But I can compile with /usr/bin/clang
and /usr/bin/gcc
— and the -v
option suggests they're using
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
I've found a way. If we are using Xcode 10, you will notice that if you navigate to the
/usr
in the Finder, you will not see a folder called 'include' any more, which is why the terminal complains of the absence of the header files which is contained inside the 'include' folder. In the Xcode 10.0 Release Notes, it says there is a package:/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
and you should install that package to have the
/usr/include
folder installed. Then you should be good to go.
When all else fails, read the manual or, in this case, the release notes. I'm not dreadfully surprised to find Apple wanting to turn their backs on their Unix heritage, but I am disappointed. If they're careful, they could drive me away. Thank you for the information.
Having installed the package using the following command at the command line, I have /usr/include
again, and my GCC 8.2.0 works once more.
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
As Vesal points out in a valuable comment, you need to download the Command Line Tools package for Xcode 10.1 on Mojave 10.14, and you can do so from:
You need to login with an Apple ID to be able to get the download. When you've done the download, install the Command Line Tools package. Then install the headers as described in the section 'Working Solution'.
This worked for me on Mojave 10.14.1. I must have downloaded this before, but I'd forgotten by the time I was answering this question.
On or about 2019-05-17, I updated to Mojave 10.14.4, and the Xcode 10.2 command line tools were also upgraded (or Xcode 10.1 command line tools were upgraded to 10.2). The open
command shown above fixed the missing headers. There may still be adventures to come with upgrading the main Xcode to 10.2 and then re-reinstalling the command line tools and the headers package.
On 2019-07-22, I got notice via the App Store that the upgrade to Xcode 10.3 is available and that it includes SDKs for iOS 12.4, tvOS 12.4, watchOS 5.3 and macOS Mojave 10.14.6. I installed it one of my 10.14.5 machines, and ran it, and installed extra components as it suggested, and it seems to have left /usr/include
intact.
Later the same day, I discovered that macOS Mojave 10.14.6 was available too (System Preferences ? Software Update), along with a Command Line Utilities package IIRC (it was downloaded and installed automatically). Installing the o/s update did, once more, wipe out /usr/include
, but the open
command at the top of the answer reinstated it again. The date I had on the file for the open
command was 2019-07-15.
The upgrade to XCode 11.0 ("includes Swift 5.1 and SDKs for iOS 13, tvOS 13, watchOS 6 and macOS Catalina 10.15") was released 2019-09-21. I was notified of 'updates available', and downloaded and installed it onto machines running macOS Mojave 10.14.6 via the App Store app (updates tab) without problems, and without having to futz with /usr/include
. Immediately after installation (before having run the application itself), I tried a recompilation and was told:
Agreeing to the Xcode/iOS license requires admin privileges, please run “sudo xcodebuild -license” and then retry this command.
Running that (sudo xcodebuild -license
) allowed me to run the compiler. Since then, I've run the application to install extra components it needs; still no problem. It remains to be seen what happens when I upgrade to Catalina itself — but my macOS Mojave 10.14.6 machines are both OK at the moment (2019-09-24).
If your project has Roslyn references and you are deploying it on an IIS server, you might get unwanted errors on the website as many hosting providers still have not upgraded their servers and hence do not support Roslyn.
To resolve this issue, you will need to remove the Roslyn compiler from the project template. Removing Roslyn shouldn't affect your code's functionality. It worked fine for me and some other projects (C# 4.5.2) on which I worked.
Do the following steps:
Remove from following Nuget Packages using command line shown below (or you can use GUI of Nuget Package manager by Right Clicking on Root Project Solution and removing them).
PM> Uninstall-package Microsoft.CodeDom.Providers.DotNetCompilerPlatform
PM> Uninstall-package Microsoft.Net.Compilers
Remove the following code from your Web.Config file and restart IIS. (Use this method only if step 1 doesn't solve your problem.)
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
I have created fiddle for you.
Take a look at here
<p>
<a class="tooltip" href="#">Tooltip
<span>
<img alt="CSS Tooltip callout"
src="http://www.menucool.com/tooltip/src/callout.gif" class="callout">
<strong>Most Light-weight Tooltip</strong><br>
This is the easy-to-use Tooltip driven purely by CSS.
</span>
</a>
</p>
a.tooltip {
outline: none;
}
a.tooltip strong {
line-height: 30px;
}
a.tooltip:hover {
text-decoration: none;
}
a.tooltip span {
z-index: 10;
display: none;
padding: 14px 20px;
margin-top: -30px;
margin-left: 28px;
width: 240px;
line-height: 16px;
}
a.tooltip:hover span {
display: inline;
position: absolute;
color: #111;
border: 1px solid #DCA;
background: #fffAF0;
}
.callout {
z-index: 20;
position: absolute;
top: 30px;
border: 0;
left: -12px;
}
/*CSS3 extras*/
a.tooltip span {
border-radius: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
-moz-box-shadow: 5px 5px 8px #CCC;
-webkit-box-shadow: 5px 5px 8px #CCC;
box-shadow: 5px 5px 8px #CCC;
}
In the PowerShell ISE editor I found running the following line first allowed scripts.
Set-ExecutionPolicy RemoteSigned -Scope Process
The distribute
package provides a Python 3-compatible version of setuptools
: http://pypi.python.org/pypi/distribute
Also, use pip
to install the modules. It automatically finds dependencies and installs them for you.
It works just fine for me with your package:
[~] pip --version
pip 1.2.1 from /usr/lib/python3.3/site-packages (python 3.3)
[~] sudo pip install ansicolors
Downloading/unpacking ansicolors
Downloading ansicolors-1.0.2.tar.gz
Running setup.py egg_info for package ansicolors
Installing collected packages: ansicolors
Running setup.py install for ansicolors
Successfully installed ansicolors
Cleaning up...
[~]
I just came across this problem when I replaced a failing disk. I had copied over the system files to the new disk, and was good about replacing the old disk's UUID entry with the new disk's UUID in fstab.
However I had not replaced the UUID in the grub.conf (sometimes menu.lst) file in /boot/grub. So check your grub.conf file, and if the "kernel" line has something like
kernel ... root=UUID=906eaa97-f66a-4d39-a39d-5091c7095987
it likely has the old disk's UUID. Replace it with the new disk's UUID and run grub-install (if you're in a live CD rescue you may need to chroot or specify the grub directory).
As strtotime requires specific input format, DateTime::createFromFormat could be used (php 5.3+ is required)
// set timezone to user timezone
date_default_timezone_set($str_user_timezone);
// create date object using any given format
$date = DateTime::createFromFormat($str_user_dateformat, $str_user_datetime);
// convert given datetime to safe format for strtotime
$str_user_datetime = $date->format('Y-m-d H:i:s');
// convert to UTC
$str_UTC_datetime = gmdate($str_server_dateformat, strtotime($str_user_datetime));
// return timezone to server default
date_default_timezone_set($str_server_timezone);
All you need is a ADODB.Connection
Dim cnn As ADODB.Connection ' Requieres reference to the
Dim rs As ADODB.Recordset ' Microsoft ActiveX Data Objects Library
Set cnn = CreateObject("adodb.Connection")
cnn.Open "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Access\webforums\whiteboard2003.mdb;"
Set rs = cnn.Execute(SQLQuery) ' Retrieve the data
pom.xml
as -<project>
....
<build>
<resources>
<resource>
<directory>src/main/config</directory>
</resource>
</resources>
...
</build>
...
</project>
If you only specify either the height or the width, but not both, most browsers will honor the aspect ratio.
Because you are working with an ASP.NET server control, you may consider executing logic on the server side prior to rendering to decide which (height or width) attribute you want to specify; that is, if you want a fixed height under one condition or a fixed width under another.
<table border="1" cellspacing="0" cellpadding= "20">
<tr>
<td id="id1" ></td>
</tr>
</table>
<script>
document.getElementById('id1').style.backgroundColor='#003F87';
</script>
Put id for cell and then change background of the cell.
* * * * * wget --quiet https://example.com/file --output-document=/dev/null
I find --quiet
clearer than -q
, and --output-document=/dev/null
clearer than -O - > /dev/null
Difference between each annotation are :
+-------------------------------------------------------------------------------------------------------+
¦ Feature ¦ Junit 4 ¦ Junit 5 ¦
¦--------------------------------------------------------------------------+--------------+-------------¦
¦ Execute before all test methods of the class are executed. ¦ @BeforeClass ¦ @BeforeAll ¦
¦ Used with static method. ¦ ¦ ¦
¦ For example, This method could contain some initialization code ¦ ¦ ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute after all test methods in the current class. ¦ @AfterClass ¦ @AfterAll ¦
¦ Used with static method. ¦ ¦ ¦
¦ For example, This method could contain some cleanup code. ¦ ¦ ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute before each test method. ¦ @Before ¦ @BeforeEach ¦
¦ Used with non-static method. ¦ ¦ ¦
¦ For example, to reinitialize some class attributes used by the methods. ¦ ¦ ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute after each test method. ¦ @After ¦ @AfterEach ¦
¦ Used with non-static method. ¦ ¦ ¦
¦ For example, to roll back database modifications. ¦ ¦ ¦
+-------------------------------------------------------------------------------------------------------+
Most of annotations in both versions are same, but few differs.
Order of Execution.
Dashed box -> optional annotation.
Argh! From the FAQ:
How do I see a list of all of the ansible_ variables? Ansible by default gathers “facts” about the machines under management, and these facts can be accessed in Playbooks and in templates. To see a list of all of the facts that are available about a machine, you can run the “setup” module as an ad-hoc action:
ansible -m setup hostname
This will print out a dictionary of all of the facts that are available for that particular host.
Here is the output for my vagrant virtual machine called scdev:
scdev | success >> {
"ansible_facts": {
"ansible_all_ipv4_addresses": [
"10.0.2.15",
"192.168.10.10"
],
"ansible_all_ipv6_addresses": [
"fe80::a00:27ff:fe12:9698",
"fe80::a00:27ff:fe74:1330"
],
"ansible_architecture": "i386",
"ansible_bios_date": "12/01/2006",
"ansible_bios_version": "VirtualBox",
"ansible_cmdline": {
"BOOT_IMAGE": "/vmlinuz-3.2.0-23-generic-pae",
"quiet": true,
"ro": true,
"root": "/dev/mapper/precise32-root"
},
"ansible_date_time": {
"date": "2013-09-17",
"day": "17",
"epoch": "1379378304",
"hour": "00",
"iso8601": "2013-09-17T00:38:24Z",
"iso8601_micro": "2013-09-17T00:38:24.425092Z",
"minute": "38",
"month": "09",
"second": "24",
"time": "00:38:24",
"tz": "UTC",
"year": "2013"
},
"ansible_default_ipv4": {
"address": "10.0.2.15",
"alias": "eth0",
"gateway": "10.0.2.2",
"interface": "eth0",
"macaddress": "08:00:27:12:96:98",
"mtu": 1500,
"netmask": "255.255.255.0",
"network": "10.0.2.0",
"type": "ether"
},
"ansible_default_ipv6": {},
"ansible_devices": {
"sda": {
"holders": [],
"host": "SATA controller: Intel Corporation 82801HM/HEM (ICH8M/ICH8M-E) SATA Controller [AHCI mode] (rev 02)",
"model": "VBOX HARDDISK",
"partitions": {
"sda1": {
"sectors": "497664",
"sectorsize": 512,
"size": "243.00 MB",
"start": "2048"
},
"sda2": {
"sectors": "2",
"sectorsize": 512,
"size": "1.00 KB",
"start": "501758"
},
},
"removable": "0",
"rotational": "1",
"scheduler_mode": "cfq",
"sectors": "167772160",
"sectorsize": "512",
"size": "80.00 GB",
"support_discard": "0",
"vendor": "ATA"
},
"sr0": {
"holders": [],
"host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)",
"model": "CD-ROM",
"partitions": {},
"removable": "1",
"rotational": "1",
"scheduler_mode": "cfq",
"sectors": "2097151",
"sectorsize": "512",
"size": "1024.00 MB",
"support_discard": "0",
"vendor": "VBOX"
},
"sr1": {
"holders": [],
"host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)",
"model": "CD-ROM",
"partitions": {},
"removable": "1",
"rotational": "1",
"scheduler_mode": "cfq",
"sectors": "2097151",
"sectorsize": "512",
"size": "1024.00 MB",
"support_discard": "0",
"vendor": "VBOX"
}
},
"ansible_distribution": "Ubuntu",
"ansible_distribution_release": "precise",
"ansible_distribution_version": "12.04",
"ansible_domain": "",
"ansible_eth0": {
"active": true,
"device": "eth0",
"ipv4": {
"address": "10.0.2.15",
"netmask": "255.255.255.0",
"network": "10.0.2.0"
},
"ipv6": [
{
"address": "fe80::a00:27ff:fe12:9698",
"prefix": "64",
"scope": "link"
}
],
"macaddress": "08:00:27:12:96:98",
"module": "e1000",
"mtu": 1500,
"type": "ether"
},
"ansible_eth1": {
"active": true,
"device": "eth1",
"ipv4": {
"address": "192.168.10.10",
"netmask": "255.255.255.0",
"network": "192.168.10.0"
},
"ipv6": [
{
"address": "fe80::a00:27ff:fe74:1330",
"prefix": "64",
"scope": "link"
}
],
"macaddress": "08:00:27:74:13:30",
"module": "e1000",
"mtu": 1500,
"type": "ether"
},
"ansible_form_factor": "Other",
"ansible_fqdn": "scdev",
"ansible_hostname": "scdev",
"ansible_interfaces": [
"lo",
"eth1",
"eth0"
],
"ansible_kernel": "3.2.0-23-generic-pae",
"ansible_lo": {
"active": true,
"device": "lo",
"ipv4": {
"address": "127.0.0.1",
"netmask": "255.0.0.0",
"network": "127.0.0.0"
},
"ipv6": [
{
"address": "::1",
"prefix": "128",
"scope": "host"
}
],
"mtu": 16436,
"type": "loopback"
},
"ansible_lsb": {
"codename": "precise",
"description": "Ubuntu 12.04 LTS",
"id": "Ubuntu",
"major_release": "12",
"release": "12.04"
},
"ansible_machine": "i686",
"ansible_memfree_mb": 23,
"ansible_memtotal_mb": 369,
"ansible_mounts": [
{
"device": "/dev/mapper/precise32-root",
"fstype": "ext4",
"mount": "/",
"options": "rw,errors=remount-ro",
"size_available": 77685088256,
"size_total": 84696281088
},
{
"device": "/dev/sda1",
"fstype": "ext2",
"mount": "/boot",
"options": "rw",
"size_available": 201044992,
"size_total": 238787584
},
{
"device": "/vagrant",
"fstype": "vboxsf",
"mount": "/vagrant",
"options": "uid=1000,gid=1000,rw",
"size_available": 42013151232,
"size_total": 484145360896
}
],
"ansible_os_family": "Debian",
"ansible_pkg_mgr": "apt",
"ansible_processor": [
"Pentium(R) Dual-Core CPU E5300 @ 2.60GHz"
],
"ansible_processor_cores": "NA",
"ansible_processor_count": 1,
"ansible_product_name": "VirtualBox",
"ansible_product_serial": "NA",
"ansible_product_uuid": "NA",
"ansible_product_version": "1.2",
"ansible_python_version": "2.7.3",
"ansible_selinux": false,
"ansible_swapfree_mb": 766,
"ansible_swaptotal_mb": 767,
"ansible_system": "Linux",
"ansible_system_vendor": "innotek GmbH",
"ansible_user_id": "neves",
"ansible_userspace_architecture": "i386",
"ansible_userspace_bits": "32",
"ansible_virtualization_role": "guest",
"ansible_virtualization_type": "virtualbox"
},
"changed": false
}
The current documentation now has a complete chapter listing all Variables and Facts
Both contain the same functionality but the .min.js equivalent has been optimized in size. You can open both files and take a look at them. In the .min.js file you'll notice that all variables names have been reduced to short names and that most whitespace & comments have been taken out.
public async Task<ActionResult> Index()
{
apiTable table = new apiTable();
table.Name = "Asma Nadeem";
table.Roll = "6655";
string str = "";
string str2 = "";
HttpClient client = new HttpClient();
string json = JsonConvert.SerializeObject(table);
StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);
str = "" + response.Content + " : " + response.StatusCode;
if (response.IsSuccessStatusCode)
{
str2 = "Data Posted";
}
return View();
}
islice
has the advantage that it doesn't need to copy part of the list
from itertools import islice
for day in islice(days, 1, None):
...
In C \0
is a character literal constant store into an int
data type that represent the character with value of 0.
Since Objective-C is a strict superset of C this constant is retained.
public static JSONObject doPostRequestWithSingleFile(String url,HashMap<String, String> data, File file,String fileParam) {
try {
final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
RequestBody requestBody;
MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
for (String key : data.keySet()) {
String value = data.get(key);
Utility.printLog("Key Values", key + "-----------------" + value);
mBuilder.addFormDataPart(key, value);
}
if(file!=null) {
Log.e("File Name", file.getName() + "===========");
if (file.exists()) {
mBuilder.addFormDataPart(fileParam, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
}
}
requestBody = mBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
String result=response.body().string();
Utility.printLog("Response",result+"");
return new JSONObject(result);
} catch (UnknownHostException | UnsupportedEncodingException e) {
Log.e(TAG, "Error: " + e.getLocalizedMessage());
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("status","false");
jsonObject.put("message",e.getLocalizedMessage());
} catch (JSONException e1) {
e1.printStackTrace();
}
} catch (Exception e) {
Log.e(TAG, "Other Error: " + e.getMessage());
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("status","false");
jsonObject.put("message",e.getLocalizedMessage());
} catch (JSONException e1) {
e1.printStackTrace();
}
}
return null;
}
public static JSONObject doGetRequest(HashMap<String, String> param,String url) {
JSONObject result = null;
String response;
Set keys = param.keySet();
int count = 0;
for (Iterator i = keys.iterator(); i.hasNext(); ) {
count++;
String key = (String) i.next();
String value = (String) param.get(key);
if (count == param.size()) {
Log.e("Key",key+"");
Log.e("Value",value+"");
url += key + "=" + URLEncoder.encode(value);
} else {
Log.e("Key",key+"");
Log.e("Value",value+"");
url += key + "=" + URLEncoder.encode(value) + "&";
}
}
/*
try {
url= URLEncoder.encode(url, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}*/
Log.e("URL", url);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response responseClient = null;
try {
responseClient = client.newCall(request).execute();
response = responseClient.body().string();
result = new JSONObject(response);
Log.e("response", response+"==============");
} catch (Exception e) {
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("status","false");
jsonObject.put("message",e.getLocalizedMessage());
return jsonObject;
} catch (JSONException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
return result;
}
pyplot
is a sub-module of matplotlib
which doesn't get imported with a simple import matplotlib
.
>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>>
It seems customary to do: import matplotlib.pyplot as plt
at which time you can use the various functions and classes it contains:
p = plt.plot(...)
why not use good old PHP? for example, let us say we receive a GET parameter 'target':
function getTarget() {
var targetParam = "<?php echo $_GET['target']; ?>";
//alert(targetParam);
}
This will work 100%:
<script type="text/javascript">
function calculate() {
var result = document.getElementById('result');
var el, i = 0, total = 0;
while(el = document.getElementById('v'+(i++)) ) {
el.value = el.value.replace(/\\D/,"");
total = total + Number(el.value);
}
result.value = total;
if(document.getElementById('v0').value =="" &&
document.getElementById('v1').value =="" &&
document.getElementById('v2').value =="" ) {
result.value ="";
}
}
}
</script>
Some number:<input type="text" id ="v0" onkeyup="calculate()">
Some number:<input type="text" id ="v1" onkeyup="calculate()">
Some number:<input type="text" id ="v2" onkeyup="calculate()">
Result: <input type="text" id="result" onkeyup="calculate()" readonly>
Use CHAR_LENGTH() instead-of LENGTH() as suggested in: MySQL - length() vs char_length()
SELECT name, CHAR_LENGTH(name) AS mlen FROM mytable ORDER BY mlen DESC LIMIT 1
I would get the part before and after what you want to replace and put them either side.
Like:
var str = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
var matches = str.match(regex);
var result = matches[1] + "1" + matches[2];
// With ES6:
var result = `${matches[1]}1${matches[2]}`;
I tried almost everything but could not help,what helped me was disabling SIP(System Integration Protection) n it works,I do not know what happens when and how but system file get confused somewhere and causes this...though there might be risks to disabling this obviously
here is how
1.Power on your Mac and hold down the [command]+[R] keys to access the Recovery Partition.
2.From the Recovery Partition, click Utilities from the menu bar, and then select Terminal.
3.Enter the following command into Terminal and press Enter to execute it: csrutil disable
4.Once the command has executed, exit the Terminal and reboot the Mac. When you log back into OS X, SIP will be disabled.
Find the index first:
function getIndex(array, key, value) {
var found = false;
var i = 0;
while (i<array.length && !found) {
if (array[i][key]==value) {
found = true;
return i;
}
i++;
}
}
Then:
console.log(getIndex($scope.rides, "_id", id));
Then do what you want with this index, like:
$scope[returnedindex].someKey = "someValue";
Note: please do not use for, since for will check all the array documents, use while with a stopper, so it will stop once it is found, thus faster code.
Here is something cool if you want to go the extra mile with this. in the url, you can use a link or save an image png and use the path. for example:
url('assets/imgs/theGoods.png');
below is the code:
.cursor{
cursor:url(http://www.icon100.com/up/3772/128/425-hand-pointer.png), auto;
}
So this will only work under the size 128 X 128, any bigger and the image wont load. But you can practically use any image you want! This would be consider pure css3, and some html. all you got to do in html is
<div class='cursor'></div>
and only in that div, that cursor will show. So I usually add it to the body tag.
Use this code:
// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();
// Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();
// Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();
It was useful to me to know it.
I also face a situation when I needed to return a top result but also wanted to get the total rows that where matching the query. i finaly get to this solution:
public string Format(SelectQuery selectQuery)
{
string result;
if (string.IsNullOrWhiteSpace(selectQuery.WherePart))
{
result = string.Format(
@"
declare @maxResult int;
set @maxResult = {0};
WITH Total AS
(
SELECT count(*) as [Count] FROM {2}
)
SELECT top (@maxResult) Total.[Count], {1} FROM Total, {2}", m_limit.To, selectQuery.SelectPart, selectQuery.FromPart);
}
else
{
result = string.Format(
@"
declare @maxResult int;
set @maxResult = {0};
WITH Total AS
(
SELECT count(*) as [Count] FROM {2} WHERE {3}
)
SELECT top (@maxResult) Total.[Count], {1} FROM Total, {2} WHERE {3}", m_limit.To, selectQuery.SelectPart, selectQuery.FromPart, selectQuery.WherePart);
}
if (!string.IsNullOrWhiteSpace(selectQuery.OrderPart))
result = string.Format("{0} ORDER BY {1}", result, selectQuery.OrderPart);
return result;
}
Another simple solution (not very elegant, but not too ugly also) is to place a inner div / span
then get his height ($(this).find('span).height()
).
Here is an example of using this strategy:
$(".more").click(function(){_x000D_
if($(this).parent().find('.showMore').length) {_x000D_
$(this).parent().find('.showMore').removeClass('showMore').css('max-height','90px');_x000D_
$(this).parent().find('.more').removeClass('less').text('More');_x000D_
} else {_x000D_
$(this).parent().find('.text').addClass('showMore').css('max-height',$(this).parent().find('span').height());_x000D_
$(this).parent().find('.more').addClass('less').text('Less');_x000D_
}_x000D_
});
_x000D_
* {transition: all 0.5s;}_x000D_
.text {position:relative;width:400px;max-height:90px;overflow:hidden;}_x000D_
.showMore {}_x000D_
.text::after {_x000D_
content: "";_x000D_
position: absolute; bottom: 0; left: 0;_x000D_
box-shadow: inset 0 -26px 22px -17px #fff;_x000D_
height: 39px;_x000D_
z-index:99999;_x000D_
width:100%;_x000D_
opacity:1;_x000D_
}_x000D_
.showMore::after {opacity:0;}_x000D_
.more {border-top:1px solid gray;width:400px;color:blue;cursor:pointer;}_x000D_
.more.less {border-color:#fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<div class="text">_x000D_
<span>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</span></div>_x000D_
<div class="more">More</div>_x000D_
</div>
_x000D_
(This specific example is using this trick to animate the max-height and avoiding animation delay when collapsing (when using high number for the max-height property).
I have the same problem and I solved it by adding package to explore to the Jaxb2marshaller. For spring will be define a bean like this:
@Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
String[] packagesToScan= {"<packcge which contain the department class>"};
marshaller.setPackagesToScan(packagesToScan);
return marshaller;
}
By this way if all your request and response classes are in the same package you do not need to specifically indicate the classes on the JAXBcontext
Add to the PATH, steps below (Windows 10):
One thing to remember (or should I say recall) is that you cannot stack onload
s like you can with ready
. In other words, jQuery magic allows multiple ready
s on the same page, but you can't do that with onload
.
The last onload
will overrule any previous onload
s.
A nice way to deal with that is with a function apparently written by one Simon Willison and described in Using Multiple JavaScript Onload Functions.
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
}
else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
// Example use:
addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
/* More code to run on page load */
});
Because setting the div
's display
style property to ""
doesn't change anything in the CSS rule itself. That basically just creates an "empty," inline CSS rule, which has no effect beyond clearing the same property on that element.
You need to set it to something that has a value:
document.getElementById('mybox').style.display = "block";
What you're doing would work if you were replacing an inline style on the div, like this:
<div id="myBox" style="display: none;"></div>
document.getElementById('mybox').style.display = "";
There is no annotation to set default value.
You can set default value only on java class level:
public class JavaObject
{
public String notNullMember;
public String optionalMember = "Value";
}
Thanks to this question (and answers), I discovered an easy way to get at the exact NumberFormat string for virtually any format that Excel has to offer.
Step 1: In the user interface, set a cell to the NumberFormat you want to use.
In my example, I selected the Chinese (PRC) Currency from the options contained in the "Account Numbers Format" combo box.
Step 2: Expand the Number Format dropdown and select "More Number Formats...".
Step 3: In the Number tab, in Category, click "Custom".
The "Sample" section shows the Chinese (PRC) currency formatting that I applied.
The "Type" input box contains the NumberFormat string that you can use programmatically.
So, in this example, the NumberFormat of my Chinese (PRC) Currency cell is as follows:
_ [$¥-804]* #,##0.00_ ;_ [$¥-804]* -#,##0.00_ ;_ [$¥-804]* "-"??_ ;_ @_
If you do these steps for each NumberFormat that you desire, then the world is yours.
I hope this helps.
In Bash this is easy. Just tie them together with &&
:
command1 && command2 && command3
You can also use the nested if construct:
if command1
then
if command2
then
do_something
else
exit
fi
else
exit
fi
If you want to handle your webapp's timeout with an apache load balancer, you first have to understand the different meaning of timeout
.
I try to condense the discussion I found here: http://apache-http-server.18135.x6.nabble.com/mod-proxy-When-does-a-backend-be-considered-as-failed-td5031316.html :
It appears that
mod_proxy
considers a backend as failed only when the transport layer connection to that backend fails. Unlessfailonstatus/failontimeout
is used. ...
So, setting failontimeout
is necessary for apache to consider a timeout of the webapp (e.g. served by tomcat) as a fail (and consecutively switch to the hot spare server). For the proper configuration, note the following misconfiguration:
ProxyPass / balancer://localbalance/ failontimeout=on timeout=10 failonstatus=50
This is a misconfiguration because:
You are defining a
balancer
here, so thetimeout
parameter relates to thebalancer
(like the two others). However for abalancer
, thetimeout
parameter is not a connection timeout (like the one used withBalancerMember
), but the maximum time to wait for a free worker/member (e.g. when all the workers are busy or in error state, the default being to not wait).
So, a proper configuration is done like this
timeout
at the BalanceMember
level: <Proxy balancer://mycluster>
BalancerMember http://member1:8080/svc timeout=6
... more BalanceMembers here
</Proxy>
failontimeout
on the balancer
ProxyPass /svc balancer://mycluster failontimeout=on
Restart apache.
You need to set M2 and M2_HOME. I was facing same problem and issue was I had put one extra space in PATH variable after semicolon. Just removed space from path and it worked. (Windows 7 machine)
You can use this:
number = 5.55
int(str(number).split('.')[1])
it will work if you put your mOption.check(R.id.option1);
into onAttachedToWindow
method or like this:
view.post(new Runnable()
{
public void run()
{
// TODO Auto-generated method stub
mOption.check(R.id.option1);
}
});
the reason may be that check method will only work when the radiogroup is actually rendered.
evaluate(new File("../tools/Tools.groovy"))
Put that at the top of your script. That will bring in the contents of a groovy file (just replace the file name between the double quotes with your groovy script).
I do this with a class surprisingly called "Tools.groovy".
Try this:
git checkout [revision] .
where [revision]
is the commit hash (for example: 12345678901234567890123456789012345678ab
).
Don't forget the .
at the end, very important. This will apply changes to the whole tree. You should execute this command in the git project root. If you are in any sub directory, then this command only changes the files in the current directory. Then commit and you should be good.
You can undo this by
git reset --hard
that will delete all modifications from the working directory and staging area.
Install Homebrew first :
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Then run this : brew install gdb
Actually, it's easier than you think. In any browsers press F12 to bring up the debug console. This works for IE, Firefox, and Chrome. Not sure about Opera. Then comment out the CSS in the element windows. That's it.
For free private SVN hosting try the following:
Or use BitBucket for free private git/mercurial repositories
customerssalary.Average();
customerssalary.Sum();
foreach (DataRow row in DataRow row in GridView1.Rows)
{
foreach (DataColumn c in GridView1.Columns)
bool ckbVal = (bool)(row[c.ColumnName]);
}
Both
SuperClass.__init__(self, x)
or
super(SubClass,self).__init__( x )
will work (I prefer the 2nd one, as it adheres more to the DRY principle).
See here: http://docs.python.org/reference/datamodel.html#basic-customization
I believe best practice these days is H/5 * * * *
, which means every 5 minutes with a hashing factor to avoid all jobs starting at EXACTLY the same time.
Keep your entitlements file in Target> Build Settings > Code Signing > Code Signing Entitlements.
Go to Target > Capabilities. Toggle On/Off or Off/On one of the capabilities.
Run.
You can use justificationMode as inter_word in xml. You have to remember that this attribute is available for api level 26 and higher. For that you can assign targetApi as o. The full code is given bellow
<com.google.android.material.textview.MaterialTextView
...
android:justificationMode="inter_word"
tools:targetApi="o" />
The protocol is available as req.protocol
. docs here
http
unless you see that req.get('X-Forwarded-Protocol')
is set and has the value https
, in which case you know that's your protocolThe host comes from req.get('host')
as Gopal has indicated
Hopefully you don't need a non-standard port in your URLs, but if you did need to know it you'd have it in your application state because it's whatever you passed to app.listen
at server startup time. However, in the case of local development on a non-standard port, Chrome seems to include the port in the host header so req.get('host')
returns localhost:3000
, for example. So at least for the cases of a production site on a standard port and browsing directly to your express app (without reverse proxy), the host
header seems to do the right thing regarding the port in the URL.
The path comes from req.originalUrl
(thanks @pgrassant). Note this DOES include the query string. docs here on req.url and req.originalUrl. Depending on what you intend to do with the URL, originalUrl
may or may not be the correct value as compared to req.url
.
Combine those all together to reconstruct the absolute URL.
var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
After upgrading the Application. I observed different Cordova versions.
Now i am confused, On which version basis, Google Dev Console is giving warning?
Please migrate your app(s) to Apache Cordova v.4.1.1 or higher as soon as possible and increment the version number of the upgraded APK. Beginning May 9, 2016, Google Play will block publishing of any new apps or updates that use pre-4.1.1 versions of Apache Cordova.
The vulnerabilities were addressed in Apache Cordova 4.1.1. If you’re using a 3rd party library that bundles Apache Cordova, you’ll need to upgrade it to a version that bundles Apache Cordova 4.1.1 or later.
And before upgrading. Our Application versions were these.
Try using 0xFFF000 instead and pass that into the Color.HSVToColor method.
A micro library I wrote: https://github.com/pathikrit/better-files
file.appendLine("Hello", "World")
or
file << "Hello" << "\n" << "World"
Here the solution.
To copy an img from an URL.
this URL: http://url/img.jpg
$image_Url=file_get_contents('http://url/img.jpg');
create the desired path finish the name with .jpg
$file_destino_path="imagenes/my_image.jpg";
file_put_contents($file_destino_path, $image_Url)
For transparency, this is also mandatory: renderer = new THREE.WebGLRenderer( { alpha: true } )
via Transparent background with three.js
1. Approach:
RMI uses an object-oriented paradigm where the user needs to know the object and the method of the object he needs to invoke.
RPC doesn't deal with objects. Rather, it calls specific subroutines that are already established.
2. Working:
With RPC, you get a procedure call that looks pretty much like a local call. RPC handles the complexities involved with passing the call from local to the remote computer.
RMI does the very same thing, but RMI passes a reference to the object and the method that is being called.
RMI = RPC + Object-orientation
3. Better one:
RMI is a better approach compared to RPC, especially with larger programs as it provides a cleaner code that is easier to identify if something goes wrong.
4. System Examples:
RPC Systems: SUN RPC, DCE RPC
RMI Systems: Java RMI, CORBA, Microsoft DCOM/COM+, SOAP(Simple Object Access Protocol)
An other possible solution:
for(Object it : set.toArray()) { /* Create a copy */
Integer element = (Integer)it;
if(element % 2 == 0)
set.remove(element);
}
Or:
Integer[] copy = new Integer[set.size()];
set.toArray(copy);
for(Integer element : copy) {
if(element % 2 == 0)
set.remove(element);
}
8.3.5.8 If the type of a parameter includes a type of the form “pointer to array of unknown bound of T” or “reference to array of unknown bound of T,” the program is ill-formed
Quite an old article on mssqlcity attempts to explain the types of locks:
Shared locks are used for operations that do not change or update data, such as a SELECT statement.
Update locks are used when SQL Server intends to modify a page, and later promotes the update page lock to an exclusive page lock before actually making the changes.
Exclusive locks are used for the data modification operations, such as UPDATE, INSERT, or DELETE.
What it doesn't discuss are Intent (which basically is a modifier for these lock types). Intent (Shared/Exclusive) locks are locks held at a higher level than the real lock. So, for instance, if your transaction has an X lock on a row, it will also have an IX lock at the table level (which stops other transactions from attempting to obtain an incompatible lock at a higher level on the table (e.g. a schema modification lock) until your transaction completes or rolls back).
The concept of "sharing" a lock is quite straightforward - multiple transactions can have a Shared lock for the same resource, whereas only a single transaction may have an Exclusive lock, and an Exclusive lock precludes any transaction from obtaining or holding a Shared lock.
Inside a GitLab CI pipeline the CI_JOB_TOKEN
environment variable works for me:
git clone https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.com/...
Source: Gitlab Docs
BTW, setting this variable in .gitlab-ci.yml
helps to debug errors.
variables:
CI_DEBUG_TRACE: "true"
An excellent 2014 IBM research paper “An Updated Performance Comparison of Virtual Machines and Linux Containers” by Felter et al. provides a comparison between bare metal, KVM, and Docker containers. The general result is: Docker is nearly identical to native performance and faster than KVM in every category.
The exception to this is Docker’s NAT — if you use port mapping (e.g., docker run -p 8080:8080
), then you can expect a minor hit in latency, as shown below. However, you can now use the host network stack (e.g., docker run --net=host
) when launching a Docker container, which will perform identically to the Native column (as shown in the Redis latency results lower down).
They also ran latency tests on a few specific services, such as Redis. You can see that above 20 client threads, highest latency overhead goes Docker NAT, then KVM, then a rough tie between Docker host/native.
Just because it’s a really useful paper, here are some other figures. Please download it for full access.
Taking a look at Disk I/O:
Now looking at CPU overhead:
Now some examples of memory (read the paper for details, memory can be extra tricky):
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] != a[k]) {
System.out.println(a[i] + " not the same with " + a[k + 1] + "\n");
}
}
}
You can start from k=1 & keep "a.length-1" in outer for loop, in order to reduce two comparisions,but that doesnt make any significant difference.