The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.
The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
Just use string methods .replace()
if they occur throughout, or .strip()
if they only occur at the start and/or finish:
a = '"sajdkasjdsak" "asdasdasds"'
a = a.replace('"', '')
'sajdkasjdsak asdasdasds'
# or, if they only occur at start and end...
a = a.strip('\"')
'sajdkasjdsak" "asdasdasds'
# or, if they only occur at start...
a = a.lstrip('\"')
# or, if they only occur at end...
a = a.rstrip('\"')
You can simply cast strings to DateTime:
[DateTime]"2020-7-16"
or
[DateTime]"Jul-16"
or
$myDate = [DateTime]"Jul-16";
And you can format the resulting DateTime variable by doing something like this:
'{0:yyyy-MM-dd}' -f [DateTime]'Jul-16'
or
([DateTime]"Jul-16").ToString('yyyy-MM-dd')
or
$myDate = [DateTime]"Jul-16";
'{0:yyyy-MM-dd}' -f $myDate
Use findElement
instead of findElements
driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).sendKeys("your value");
OR
driver.findElement(By.id("invoice_supplier_id")).sendKeys("value", "your value");
OR using JavascriptExecutor
WebElement element = driver.findElement(By.xpath("enter the xpath here")); // you can use any locator
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].value='enter the value here';", element);
OR
(JavascriptExecutor) driver.executeScript("document.evaluate(xpathExpresion, document, null, 9, null).singleNodeValue.innerHTML="+ DesiredText);
OR (in javascript)
driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).setAttribute("value", "your value")
Hope it will help you :)
Use the following JS:
$(document).ready(function () {
$("#btnsubmit").click(function () {
$.ajax({
type: "POST",
url: '/Plan/PlanManage', //your action
data: $('#PlanForm').serialize(), //your form name.it takes all the values of model
dataType: 'json',
success: function (result) {
console.log(result);
}
})
return false;
});
});
and the following code on your controller:
[HttpPost]
public string PlanManage(Plan objplan) //model plan
{
}
In my case, all other solutions didn't work, but this one did:
obj = {...arr}
my arr is in a form: [name: "the name", email: "[email protected]"]
Good news! At the time of writing, this feature has already been implemented in the 0.10.12-insiders release and carried out through 0.10.14-insiders. Hence we are going to have it in the upcoming version 1.0 Release of VS Code.
Implementation Ref: Implement -w/--wait command line arg
$scope.actions.data.concat is not a function
same problem with me but i solve the problem by
$scope.actions.data = [].concat($scope.actions.data , data)
In my case, even though Target Framework of Project was 4.7.1, I was still getting same Error, Solution was to change httpRuntime in web.config under system.web to 4.7.1!
The following does not return a response:
You must return anything like return afunction()
or return 'a string'
.
This can solve the issue
Make sure that...
=
sign before the formula=
sign=A1
, instead of "=A1"
)The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:
RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);
There, &rect
is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.
The code should create a dynamic variable:
RectInvoice *rect = new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);
There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.
Cheers
This should work.
SELECT a.[CUSTOMER ID], a.[NAME], SUM(b.[AMOUNT]) AS [TOTAL AMOUNT]
FROM RES_DATA a INNER JOIN INV_DATA b
ON a.[CUSTOMER ID]=b.[CUSTOMER ID]
GROUP BY a.[CUSTOMER ID], a.[NAME]
I tested it with SQL Fiddle against SQL Server 2008: http://sqlfiddle.com/#!3/1cad5/1
Basically what's happening here is that, because of the join, you are getting the same row on the "left" (i.e. from the RES_DATA
table) for every row on the "right" (i.e. the INV_DATA
table) that has the same [CUSTOMER ID]
value. When you group by just the columns on the left side, and then do a sum of just the [AMOUNT]
column from the right side, it keeps the one row intact from the left side, and sums up the matching values from the right side.
You can sum up the values of a BigDecimal
stream using a reusable Collector named summingUp
:
BigDecimal sum = bigDecimalStream.collect(summingUp());
The Collector
can be implemented like this:
public static Collector<BigDecimal, ?, BigDecimal> summingUp() {
return Collectors.reducing(BigDecimal.ZERO, BigDecimal::add);
}
They can be considered as equivalent. The limits in size are the same:
There is also the DBCLOBs, for double byte characters.
References:
I have same problem and get this error in hostname.err in directory /Applications/XAMPP/xamppfiles/var/mysql
2016-09-06 15:32:45 140735322399488 [Note] Plugin 'FEEDBACK' is disabled. 2016-09-06 15:32:45 140735322399488 [Note] Heuristic crash recovery mode 2016-09-06 15:32:45 140735322399488 [Note] Please restart mysqld without --tc-heuristic-recover 2016-09-06 15:32:45 140735322399488 [ERROR] Can't init tc log 2016-09-06 15:32:45 140735322399488 [ERROR] Aborting
2016-09-06 15:32:48 20004 mysqld_safe mysqld from pid file /Applications/XAMPP/xamppfiles/var/mysql/hostname.pid ended
Then I removed tc.log and It works fine after restart mysql through manager-osx
Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.
I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.
If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.
According to this documentation, starting in MySQL 8.0.13, you will be able to specify:
CREATE TABLE INVOICE(
INVOICEDATE DATE DEFAULT (CURRENT_DATE)
)
Unfortunately, as of today, that version is not yet released. You can check here for the latest updates.
I've used MPDF library. For more information view this tutorial https://arjunphp.com/generating-a-pdf-in-codeigniter-using-mpdf/
Since I didn't see this in any of the other answers, and since it's more efficient (in lines of code and in speed), here's a solution in VB.NET using a stringbuilder and lambda functions with String.Join instead of For loops for the columns.
Dim sb As New StringBuilder
sb.Append("<table>")
sb.Append("<tr>" & String.Join("", dt.Columns.OfType(Of DataColumn)().Select(Function(x) "<th>" & x.ColumnName & "</th>").ToArray()) & "</tr>")
For Each row As DataRow In dt.Rows
sb.Append("<tr>" & String.Join("", row.ItemArray.Select(Function(f) "<td>" & f.ToString() & "</td>")) & "</tr>")
Next
sb.Append("</table>")
You can add your own styles to this pretty easily.
By default the function returns FALSE (boolean) if the segment does not exist. There is an optional second parameter that permits you to set your own default value if the segment is missing. For example, this would tell the function to return the number zero in the event of failure: $product_id = $this->uri->segment(3, 0);
It helps avoid having to write code like this:
[if ($this->uri->segment(3) === FALSE)
{
$product_id = 0;
}
else
{
$product_id = $this->uri->segment(3);
}]
Try below code
I will recommend to use error handler while using vlookup because error might occur when the lookup_value is not found.
Private Sub ComboBox1_Change()
On Error Resume Next
Ret = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
On Error GoTo 0
If Ret <> "" Then MsgBox Ret
End Sub
OR
On Error Resume Next
Result = Application.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
If Result = "Error 2042" Then
'nothing found
ElseIf cell <> Result Then
MsgBox cell.Value
End If
On Error GoTo 0
please set dataType config property in your ajax call and give it another try!
another point is you are using ajax call setup configuration properties as string and it is wrong as reference site
$.ajax({
url : 'http://voicebunny.comeze.com/index.php',
type : 'GET',
data : {
'numberOfWords' : 10
},
dataType:'json',
success : function(data) {
alert('Data: '+data);
},
error : function(request,error)
{
alert("Request: "+JSON.stringify(request));
}
});
I hope be helpful!
Press Alt+shift+R
key and change package name
While reading from the file, your are not terminating your loop. So its read all the values and correctly throws EOFException on the next iteration of the read at line below:
price = in.readDouble();
If you read the documentation, it says:
Throws:
EOFException - if this input stream reaches the end before reading eight bytes.
IOException - the stream has been closed and the contained input stream does not support reading after close, or another I/O error occurs.
Put a proper termination condition in your while loop to resolve the issue e.g. below:
while(in.available() > 0) <--- if there are still bytes to read
As you're using Python 3, there is no urllib module anymore. It has been split into several modules.
This would be equivalent to urlretrieve:
import urllib.request
data = urllib.request.urlretrieve("http://...")
urlretrieve behaves exactly the same way as it did in Python 2.x, so it'll work just fine.
Basically:
urlretrieve
saves the file to a temporary file and returns a tuple (filename, headers)
urlopen
returns a Request
object whose read
method returns a bytestring containing the file contentsA simple and flexible offline recognition on Android is implemented by CMUSphinx, an open source speech recognition toolkit. It works purely offline, fast and configurable It can listen continuously for keyword, for example.
You can find latest code and tutorial here.
Update in 2019: Time goes fast, CMUSphinx is not that accurate anymore. I recommend to try Kaldi toolkit instead. The demo is here.
Last version to support windows XP (SP3) is mono-4.3.2.467-gtksharp-2.12.30.1-win32-0.msi and that doesnot replace .NET 4.5 but could be of interest for some applications.
see there: https://download.mono-project.com/archive/4.3.2/windows-installer/
String dir="/Attendancesystem";
public void displaypdf() {
File file = null;
file = new File(Environment.getExternalStorageDirectory()+dir+ "/sample.pdf");
Toast.makeText(getApplicationContext(), file.toString() , Toast.LENGTH_LONG).show();
if(file.exists()) {
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
}
else
Toast.makeText(getApplicationContext(), "File path is incorrect." , Toast.LENGTH_LONG).show();
}
In ECS6, one may use Array.from()
:
const listItems = document.querySelector('ul').children;
const listArray = Array.from(listItems);
listArray.forEach((item) => {console.log(item)});
try:
gsub('\\$', '', '$5.00$')
For the 24-hour time, you need to use HH24
instead of HH
.
For the 12-hour time, the AM/PM indicator is written as A.M.
(if you want periods in the result) or AM
(if you don't). For example:
SELECT invoice_date,
TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
FROM invoices
;
For more information on the format models you can use with TO_CHAR
on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.
you can do something like
filename = "%s.csv" % name
f = open(filename , 'wb')
or f = open('%s.csv' % name, 'wb')
You cannot directly copy a table into a destination server database from a different database if source db is not in your linked servers. But one way is possible that, generate scripts (schema with data) of the desired table into one table temporarily in the source server DB, then execute the script in the destination server DB to create a table with your data. Finally use INSERT INTO [DESTINATION_TABLE] select * from [TEMPORARY_SOURCE_TABLE]. After getting the data into your destination table drop the temporary one.
I found this solution when I faced the same situation. Hope this helps you too.
I guess the issue here is that you are updating INV_DISCOUNT and the INV_TOTAL uses the INV_DISCOUNT. so that is the issue here. You can use returning clause of update statement to use the new INV_DISCOUNT and use it to update INV_TOTAL.
this is a generic example let me know if this explains the point i mentioned
CREATE OR REPLACE PROCEDURE SingleRowUpdateReturn
IS
empName VARCHAR2(50);
empSalary NUMBER(7,2);
BEGIN
UPDATE emp
SET sal = sal + 1000
WHERE empno = 7499
RETURNING ename, sal
INTO empName, empSalary;
DBMS_OUTPUT.put_line('Name of Employee: ' || empName);
DBMS_OUTPUT.put_line('New Salary: ' || empSalary);
END;
If you use the WEB API with Claims, you can use this:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AutorizeCompanyAttribute: AuthorizationFilterAttribute
{
public string Company { get; set; }
public override void OnAuthorization(HttpActionContext actionContext)
{
var claims = ((ClaimsIdentity)Thread.CurrentPrincipal.Identity);
var claim = claims.Claims.Where(x => x.Type == "Company").FirstOrDefault();
string privilegeLevels = string.Join("", claim.Value);
if (privilegeLevels.Contains(this.Company)==false)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Usuario de Empresa No Autorizado");
}
}
}
[HttpGet]
[AutorizeCompany(Company = "MyCompany")]
[Authorize(Roles ="SuperAdmin")]
public IEnumerable MyAction()
{....
}
Here is how I do this.
Dim TAV() As Variant
Dim ArrayToPreserve() as Variant
TAV = ArrayToPreserve
ReDim ArrayToPreserve(nDim1, nDim2)
For i = 0 To UBound(TAV, 1)
For j = 0 To UBound(TAV, 2)
ArrayToPreserve(i, j) = TAV(i, j)
Next j
Next i
This class was compiled with a JDK more recent than the one used for execution.
The easiest is to install a more recent JRE on the computer where you execute the program. If you think you installed a recent one, check the JAVA_HOME and PATH environment variables.
Version 49 is java 1.5. That means the class was compiled with (or for) a JDK which is yet old. You probably tried to execute the class with JDK 1.4. You really should use one more recent (1.6 or 1.7, see java version history).
it's because some of the fields (specifically InvoiceID on the Invoices table and on the InvoiceLineItems) are present on both table. The way to answer of question is to add an ALIAS
on it.
SELECT
a.VendorName, Invoices.InvoiceID, .. -- or use full tableName
FROM Vendors a -- This is an `ALIAS` of table Vendors
JOIN Invoices ON (Vendors.VendorID = Invoices.VendorID)
JOIN InvoiceLineItems ON (Invoices.InvoiceID = InvoiceLineItems.InvoiceID)
WHERE
Invoices.InvoiceID IN
(SELECT InvoiceSequence
FROM InvoiceLineItems
WHERE InvoiceSequence > 1)
ORDER BY
VendorName, InvoiceID, InvoiceSequence, InvoiceLineItemAmount
Updates you make to the CTE will be cascaded to the source table.
I have had to guess at your schema slightly, but something like this should work.
;WITH T AS
( SELECT InvoiceNumber,
DocTotal,
SUM(Sale + VAT) OVER(PARTITION BY InvoiceNumber) AS NewDocTotal
FROM PEDI_InvoiceDetail
)
UPDATE T
SET DocTotal = NewDocTotal
You can't reference an alias except in ORDER BY because SELECT is the second last clause that's evaluated. Two workarounds:
SELECT BalanceDue FROM (
SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
FROM Invoices
) AS x
WHERE BalanceDue > 0;
Or just repeat the expression:
SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
FROM Invoices
WHERE (InvoiceTotal - PaymentTotal - CreditTotal) > 0;
I prefer the latter. If the expression is extremely complex (or costly to calculate) you should probably consider a computed column (and perhaps persisted) instead, especially if a lot of queries refer to this same expression.
PS your fears seem unfounded. In this simple example at least, SQL Server is smart enough to only perform the calculation once, even though you've referenced it twice. Go ahead and compare the plans; you'll see they're identical. If you have a more complex case where you see the expression evaluated multiple times, please post the more complex query and the plans.
Here are 5 example queries that all yield the exact same execution plan:
SELECT LEN(name) + column_id AS x
FROM sys.all_columns
WHERE LEN(name) + column_id > 30;
SELECT x FROM (
SELECT LEN(name) + column_id AS x
FROM sys.all_columns
) AS x
WHERE x > 30;
SELECT LEN(name) + column_id AS x
FROM sys.all_columns
WHERE column_id + LEN(name) > 30;
SELECT name, column_id, x FROM (
SELECT name, column_id, LEN(name) + column_id AS x
FROM sys.all_columns
) AS x
WHERE x > 30;
SELECT name, column_id, x FROM (
SELECT name, column_id, LEN(name) + column_id AS x
FROM sys.all_columns
) AS x
WHERE LEN(name) + column_id > 30;
Resulting plan for all five queries:
I thought this looked pretty bad - because I was working on a Joomla template recently and I kept getting the template failing W3C because it was using the <i>
tag and that had deprecated, as it's original use was to italicize something, which is now done through CSS not HTML any more.
It does make really bad practice because when I saw it I went through the template and changed all the <i>
tags to <span style="font-style:italic">
instead and then wondered why the entire template looked strange.
This is the main reason it is a bad idea to use the <i>
tag in this way - you never know who is going to look at your work afterwards and "assume" that what you were really trying to do is italicize the text rather than display an icon. I've just put some icons in a website and I did it with the following code
<img class="icon" src="electricity.jpg" alt="Electricity" title="Electricity">
that way I've got all my icons in one class so any changes I make affects all the icons (say I wanted them larger or smaller, or rounded borders, etc), the alt text gives screen readers the chance to tell the person what the icon is rather than possibly getting just "text in italics, end of italics" (I don't exactly know how screen readers read screens but I guess it's something like that), and the title also gives the user a chance to mouse over the image and get a tooltip telling them what the icon is in case they can't figure it out. Much better than using <i>
- and also it passes W3C standard.
We can use $set
operator to update the nested array inside object filed update the value
db.getCollection('geolocations').update(
{
"_id" : ObjectId("5bd3013ac714ea4959f80115"),
"geolocation.country" : "United States of America"
},
{ $set:
{
"geolocation.$.country" : "USA"
}
},
false,
true
);
If the problem is 100% here
EffectSelectorForm effectSelectorForm = new EffectSelectorForm(Effects);
There's only one possible explanation: property/variable "Effects" is not initialized properly... Debug your code to see what you pass to your objects.
EDIT after several hours
There were some problems:
MEF attribute [Import] didn't work as expected, so we replaced it for the time being with a manually populated List<>. While the collection was null, it was causing exceptions later in the code, when the method tried to get the type of the selected item and there was none.
several event handlers weren't wired up to control events
Some problems are still present, but I believe OP's original problem has been fixed. Other problems are not related to this one.
Simple Answer: NO. You cannot help ad hoc queries on a 238 column table with a 50% Fill Factor on the Clustered Index.
Detailed Answer:
As I have stated in other answers on this topic, Index design is both Art and Science and there are so many factors to consider that there are few, if any, hard and fast rules. You need to consider: the volume of DML operations vs SELECTs, disk subsystem, other indexes / triggers on the table, distribution of data within the table, are queries using SARGable WHERE conditions, and several other things that I can't even remember right now.
I can say that no help can be given for questions on this topic without an understanding of the Table itself, its indexes, triggers, etc. Now that you have posted the table definition (still waiting on the Indexes but the Table definition alone points to 99% of the issue) I can offer some suggestions.
First, if the table definition is accurate (238 columns, 50% Fill Factor) then you can pretty much ignore the rest of the answers / advice here ;-). Sorry to be less-than-political here, but seriously, it's a wild goose chase without knowing the specifics. And now that we see the table definition it becomes quite a bit clearer as to why a simple query would take so long, even when the test queries (Update #1) ran so quickly.
The main problem here (and in many poor-performance situations) is bad data modeling. 238 columns is not prohibited just like having 999 indexes is not prohibited, but it is also generally not very wise.
Recommendations:
ANSI_PADDING OFF
is disturbing, not to mention inconsistent within the table due to the various column additions over time. Not sure if you can fix that now, but ideally you would always have ANSI_PADDING ON
, or at the very least have the same setting across all ALTER TABLE
statements.PRIMARY
as that is where SQL SERVER stores all of its data and meta-data about your objects. You create your Table and Clustered Index (as that is the data for the table) on [Tables]
and all Non-Clustered indexes on [Indexes]
WHERE
condition, then consider moving that to the leading column of the clustered index. Assuming that it is used more often than "ER101_ORD_NBR". If "ER101_ORD_NBR" is used more often then keep it. It just seems, assuming that the field names mean "OrganizationCode" and "OrderNumber", that "OrgCode" is a better grouping that might have multiple "OrderNumbers" within it.CHAR(2)
instead of VARCHAR(2)
as it will save a byte in the row header which tracks variable width sizes and adds up over millions of rows.SELECT *
will hurt performance. Not only due to it requiring SQL Server to return all columns and hence be more likely to do a Clustered Index Scan regardless of your other indexes, but it also takes SQL Server time to go to the table definition and translate *
into all of the column names. It should be slightly faster to specify all 238 column names in the SELECT
list though that won't help the Scan issue. But do you ever really need all 238 columns at the same time anyway?Good luck!
UPDATE
For the sake of completeness to the question "how to improve performance on a large table for ad-hoc queries", it should be noted that while it will not help for this specific case, IF someone is using SQL Server 2012 (or newer when that time comes) and IF the table is not being updated, then using Columnstore Indexes is an option. For more details on that new feature, look here:
http://msdn.microsoft.com/en-us/library/gg492088.aspx (I believe these were made to be updateable starting in SQL Server 2014).
UPDATE 2
Additional considerations are:
INT
, BIGINT
, TINYINT
, SMALLINT
, CHAR
, NCHAR
, BINARY
, DATETIME
, SMALLDATETIME
, MONEY
, etc) and well over 50% of the rows are NULL
, then consider enabling the SPARSE
option which became available in SQL Server 2008. Please see the MSDN page for Use Sparse Columns for details.If you set the server output in ON mode before the entire code, it works, otherwise put_line() will not work. Try it!
The code is,
set serveroutput on;
CREATE OR REPLACE PROCEDURE PROC1(invoicenr IN NUMBER, amnt OUT NUMBER)
AS BEGIN
SELECT AMOUNT INTO amnt FROM INVOICE WHERE INVOICE_NR = invoicenr;
END;
And then call the function as it is:
DECLARE
amount NUMBER;
BEGIN
PROC1(1000001, amount);
dbms_output.put_line(amount);
END;
I have a list of positions of array to retrieve ,This worked for me.
public void create_list_to_add_group(ArrayList<Integer> arrayList_loc) {
//In my case arraylist_loc is the list of positions to retrive from
// contact_names
//arraylist and phone_number arraylist
ArrayList<String> group_members_list = new ArrayList<>();
ArrayList<String> group_members_phone_list = new ArrayList<>();
int size = arrayList_loc.size();
for (int i = 0; i < size; i++) {
try {
int loc = arrayList_loc.get(i);
group_members_list.add(contact_names_list.get(loc));
group_members_phone_list.add(phone_num_list.get(loc));
} catch (Exception e) {
e.printStackTrace();
}
}
Log.e("Group memnbers list", " " + group_members_list);
Log.e("Group memnbers num list", " " + group_members_phone_list);
}
You can determine the mean of the signal, and just subtract that value from all the entries. That will give you a zero mean result.
To get unit variance, determine the standard deviation of the signal, and divide all entries by that value.
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
Sample form using PHP for direct payments.
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="upload" value="1">
<input type="hidden" name="business" value="[email protected]">
<input type="hidden" name="item_name_' . $x . '" value="' . $product_name . '">
<input type="hidden" name="amount_' . $x . '" value="' . $price . '">
<input type="hidden" name="quantity_' . $x . '" value="' . $each_item['quantity'] . '">
<input type="hidden" name="custom" value="' . $product_id_array . '">
<input type="hidden" name="notify_url" value="https://www.yoursite.com/my_ipn.php">
<input type="hidden" name="return" value="https://www.yoursite.com/checkout_complete.php">
<input type="hidden" name="rm" value="2">
<input type="hidden" name="cbt" value="Return to The Store">
<input type="hidden" name="cancel_return" value="https://www.yoursite.com/paypal_cancel.php">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="currency_code" value="USD">
<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but01.gif" name="submit" alt="Make payments with PayPal - its fast, free and secure!">
</form>
kindly go through the fields notify_url, return, cancel_return
sample code for handling ipn (my_ipn.php) which is requested by paypal after payment has been made.
For more information on creating a IPN, please refer to this link.
<?php
// Check to see there are posted variables coming into the script
if ($_SERVER['REQUEST_METHOD'] != "POST")
die("No Post Variables");
// Initialize the $req variable and add CMD key value pair
$req = 'cmd=_notify-validate';
// Read the post from PayPal
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
// Now Post all of that back to PayPal's server using curl, and validate everything with PayPal
// We will use CURL instead of PHP for this for a more universally operable script (fsockopen has issues on some environments)
//$url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
$url = "https://www.paypal.com/cgi-bin/webscr";
$curl_result = $curl_err = '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($req)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$curl_result = @curl_exec($ch);
$curl_err = curl_error($ch);
curl_close($ch);
$req = str_replace("&", "\n", $req); // Make it a nice list in case we want to email it to ourselves for reporting
// Check that the result verifies
if (strpos($curl_result, "VERIFIED") !== false) {
$req .= "\n\nPaypal Verified OK";
} else {
$req .= "\n\nData NOT verified from Paypal!";
mail("[email protected]", "IPN interaction not verified", "$req", "From: [email protected]");
exit();
}
/* CHECK THESE 4 THINGS BEFORE PROCESSING THE TRANSACTION, HANDLE THEM AS YOU WISH
1. Make sure that business email returned is your business email
2. Make sure that the transaction?s payment status is ?completed?
3. Make sure there are no duplicate txn_id
4. Make sure the payment amount matches what you charge for items. (Defeat Price-Jacking) */
// Check Number 1 ------------------------------------------------------------------------------------------------------------
$receiver_email = $_POST['receiver_email'];
if ($receiver_email != "[email protected]") {
//handle the wrong business url
exit(); // exit script
}
// Check number 2 ------------------------------------------------------------------------------------------------------------
if ($_POST['payment_status'] != "Completed") {
// Handle how you think you should if a payment is not complete yet, a few scenarios can cause a transaction to be incomplete
}
// Check number 3 ------------------------------------------------------------------------------------------------------------
$this_txn = $_POST['txn_id'];
//check for duplicate txn_ids in the database
// Check number 4 ------------------------------------------------------------------------------------------------------------
$product_id_string = $_POST['custom'];
$product_id_string = rtrim($product_id_string, ","); // remove last comma
// Explode the string, make it an array, then query all the prices out, add them up, and make sure they match the payment_gross amount
// END ALL SECURITY CHECKS NOW IN THE DATABASE IT GOES ------------------------------------
////////////////////////////////////////////////////
// Homework - Examples of assigning local variables from the POST variables
$txn_id = $_POST['txn_id'];
$payer_email = $_POST['payer_email'];
$custom = $_POST['custom'];
// Place the transaction into the database
// Mail yourself the details
mail("[email protected]", "NORMAL IPN RESULT YAY MONEY!", $req, "From: [email protected]");
?>
The below image will help you in understanding the paypal process.
For further reading refer to the following links;
hope this helps you..:)
Following are few libraries to create PDF with Java:
I have used iText for genarating PDF's with a little bit of pain in the past.
Or you can try using FOP: FOP is an XSL formatter written in Java. It is used in conjunction with an XSLT transformation engine to format XML documents into PDF.
All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.
If you have accidentally removed DLL file from php/ext
folder, just add it back (get the copy from XAMPP zip archive - its downloadable).
If you have deleted the accompanying INI configuration line from php.ini
file, add it back as well:
extension=php_mbstring.dll
Also, ensure to restart your webserver (Apache) using XAMPP control panel.
Additional Info on Enabling PHP Extensions
/XAMPP/php/ext
directory)extension_dir = "ext"
)I was getting the same error but solved it finally,actually i was not setting the Object Entity which is already saved to the other entity and hence the Object value it was getting for foreeign key was null.
Two solutions
1. use merge if you want to update the object
2. use save if you want to just save new object (make sure identity is null to let hibernate or database generate it)
3. if you are using mapping like
@OneToOne(fetch = FetchType.EAGER,cascade=CascadeType.ALL)
@JoinColumn(name = "stock_id")
Then use CascadeType.ALL to CascadeType.MERGE
thanks Shahid Abbasi
You can use sessions to save $_POST
data, then retrieve that data and set it to $_POST
on the subsequent request.
User submits request to /dirty-submission-url.php
Do:
if (session_status()!==PHP_SESSION_ACTIVE)session_start();
$_SESSION['POST'] = $_POST;
}
header("Location: /clean-url");
exit;
Then the browser redirects to and requests /clean-submission-url
from your server. You will have some internal routing to figure out what to do with this.
At the beginning of the request, you will do:
if (session_status()!==PHP_SESSION_ACTIVE)session_start();
if (isset($_SESSION['POST'])){
$_POST = $_SESSION['POST'];
unset($_SESSION['POST']);
}
Now, through the rest of your request, you can access $_POST
as you could upon the first request.
It means there's no default document in that directory (index.html, index.php, etc...). On most webservers, that would mean it would show a listing of the directory's contents. But showing that directory is forbidden by server configuration (Options -Indexes
)
One mistake what i did was not including "implements OnClickListener" in the main class declaration. This is a sample code to clearly illustrate the use of switch case during on click. The code changes background colour as per the button pressed. Hope this helps.
public class MainActivity extends Activity implements OnClickListener{
TextView displayText;
Button cred, cblack, cgreen, cyellow, cwhite;
LinearLayout buttonLayout;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cred = (Button) findViewById(R.id.bred);
cblack = (Button) findViewById(R.id.bblack);
cgreen = (Button) findViewById(R.id.bgreen);
cyellow = (Button) findViewById(R.id.byellow);
cwhite = (Button) findViewById(R.id.bwhite);
displayText = (TextView) findViewById(R.id.tvdisplay);
buttonLayout = (LinearLayout) findViewById(R.id.llbuttons);
cred.setOnClickListener(this);
cblack.setOnClickListener(this);
cgreen.setOnClickListener(this);
cyellow.setOnClickListener(this);
cwhite.setOnClickListener(this);
}
@Override
protected void onClick(View V){
int id=V.getId();
switch(id){
case R.id.bred:
displayText.setBackgroundColor(Color.rgb(255, 0, 0));
vanishLayout();
break;
case R.id.bblack:
displayText.setBackgroundColor(Color.rgb(0, 0, 0));
vanishLayout();
break;
case R.id.byellow:
displayText.setBackgroundColor(Color.rgb(255, 255, 0));
vanishLayout();
break;
case R.id.bgreen:
displayText.setBackgroundColor(Color.rgb(0, 255, 0));
vanishLayout();
break;
case R.id.bwhite:
displayText.setBackgroundColor(Color.rgb(255, 255, 255));
vanishLayout();
break;
}
}
Below is how I got this working.
The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.
[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]
[HttpPost]
public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
{
var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
}
The JQuery script used to call this action method:
var requestData = {
InvoiceNumber: $.trim(this.value),
SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
};
$.ajax({
url: '/en/myController/GetDataForInvoiceNumber',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
The solution in simple, but not immediatly.
If you want use this instruction, you must make one change to the db:
ALTER USER user SET search_path to 'name_of_schema';
after these changes "INSERT" will work correctly.
Well maybe a little late after 4 years haha... but I was looking for solution to do OBJECT to CSV, however most solutions here is actually for ARRAY to CSV...
After some tinkering, here is my solution to convert object into CSV, I think is pretty neat. Hope this would help someone else.
$resp = array();
foreach ($entries as $entry) {
$row = array();
foreach ($entry as $key => $value) {
array_push($row, $value);
}
array_push($resp, implode(',', $row));
}
echo implode(PHP_EOL, $resp);
Note that for the $key => $value
to work, your object
's attributes must be public, the private ones will not get fetched.
The end result is that you get something like this:
blah,blah,blah
blah,blah,blah
As others have suggested, the best way to do this is to use a join instead of variable assignment. Re-writing your query to use a join (and using the explicit join syntax instead of the implicit join, which was also suggested--and is the best practice), you would get something like this:
select
OrderDetails.Sku,
OrderDetails.mf_item_number,
OrderDetails.Qty,
OrderDetails.Price,
Supplier.SupplierId,
Supplier.SupplierName,
Supplier.DropShipFees,
Supplier_Item.Price as cost
from
OrderDetails
join Supplier on OrderDetails.Mfr_ID = Supplier.SupplierId
join Group_Master on Group_Master.Sku = OrderDetails.Sku
join Supplier_Item on
Supplier_Item.SKU=OrderDetails.Sku and Supplier_Item.SupplierId=Supplier.SupplierID
where
invoiceid='339740'
If you want to procces an audio block by block, some of the given solutions are quite awful in the sense that they imply loading the whole audio into memory producing many cache misses and slowing down your program. python-wavefile provides some pythonic constructs to do NumPy block-by-block processing using efficient and transparent block management by means of generators. Other pythonic niceties are context manager for files, metadata as properties... and if you want the whole file interface, because you are developing a quick prototype and you don't care about efficency, the whole file interface is still there.
A simple example of processing would be:
import sys
from wavefile import WaveReader, WaveWriter
with WaveReader(sys.argv[1]) as r :
with WaveWriter(
'output.wav',
channels=r.channels,
samplerate=r.samplerate,
) as w :
# Just to set the metadata
w.metadata.title = r.metadata.title + " II"
w.metadata.artist = r.metadata.artist
# This is the prodessing loop
for data in r.read_iter(size=512) :
data[1] *= .8 # lower volume on the second channel
w.write(data)
The example reuses the same block to read the whole file, even in the case of the last block that usually is less than the required size. In this case you get an slice of the block. So trust the returned block length instead of using a hardcoded 512 size for any further processing.
You have an extra double quote at the end, which is adding it back to the end of the string (after removing both quotes from the string).
Input:
set widget="a very useful item"
set widget
set widget=%widget:"=%
set widget
Output:
widget="a very useful item"
widget=a very useful item
Note: To replace Double Quotes " with Single Quotes ' do the following:
set widget=%widget:"='%
Note: To replace the word "World" (not case sensitive) with BobB do the following:
set widget="Hello World!"
set widget=%widget:world=BobB%
set widget
Output:
widget="Hello BobB!"
As far as your initial question goes (save the following code to a batch file .cmd or .bat and run):
@ECHO OFF
ECHO %0
SET BathFileAndPath=%~0
ECHO %BathFileAndPath%
ECHO "%BathFileAndPath%"
ECHO %~0
ECHO %0
PAUSE
Output:
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
Press any key to continue . . .
%0
is the Script Name and Path.
%1
is the first command line argument, and so on.
No, there is no API for Google Voice announced as of 2021.
"pygooglevoice" can perform most of the voice functions from Python. It can send SMS. I've developed code to receive SMS messages, but the overhead is excessive given the current Google Voice interface. Each poll returns over 100K of content, so you'd use a quarter-gigabyte a day just polling every 30 seconds. There's a discussion on Google Code about this.
Private Function addInsert(Media As String, pagesOut As Integer) As Long
Set rst = db.OpenRecordset("tblenccomponent")
With rst
.AddNew
!LeafletCode = LeafletCode
!LeafletName = LeafletName
!UNCPath = "somePath\" + LeafletCode + ".xml"
!Media = Media
!CustomerID = cboCustomerID.Column(0)
!PagesIn = PagesIn
!pagesOut = pagesOut
addInsert = CLng(rst!enclosureID) 'ID is passed back to calling routine
.Update
End With
rst.Close
End Function
I have a tip for those, who want to get various aggregated values from the same table.
Lets say I have table with users and table with points the users acquire. So the connection between them is 1:N (one user, many points records).
Now in the table 'points' I also store the information about for what did the user get the points (login, clicking a banner etc.). And I want to list all users ordered by SUM(points)
AND then by SUM(points WHERE type = x)
. That is to say ordered by all the points user has and then by points the user got for a specific action (eg. login).
The SQL would be:
SELECT SUM(points.points) AS points_all, SUM(points.points * (points.type = 7)) AS points_login
FROM user
LEFT JOIN points ON user.id = points.user_id
GROUP BY user.id
The beauty of this is in the SUM(points.points * (points.type = 7))
where the inner parenthesis evaluates to either 0 or 1 thus multiplying the given points value by 0 or 1, depending on wheteher it equals to the the type of points we want.
Mobile Safari (iPhone & iPod Touch) use the tel:
scheme.
System.out.println(MessageFormat.format("Hello {0}! You have {1} messages", "Join",10L));
Output: Hello Join! You have 10 messages"
I tend to think that people are impressed with stuff that they can relate to or is relevant to their lives. I'd try and base my 10 lines of code around something that they know and understand. Take, for example, Twitter and its API. Why not use this API to build something that's cool. The following 10 lines of code will return the "public timeline" from Twitter and display it in a console application...
using (var xmlr = XmlReader.Create("http://twitter.com/statuses/public_timeline.rss"))
{
SyndicationFeed
.Load(xmlr)
.GetRss20Formatter()
.Feed
.Items
.ToList()
.ForEach( x => Console.WriteLine(x.Title.Text));
}
My code sample might not be the best for your students. It's written in C# and uses .NET 3.5. So if you're going to teach them PHP, Java, or C++ this won't be useful. However, my point is that by associating your 10 lines of code with something "cool, interesting, and relevant to the students your sample also becomes cool, interesting, and relevant.
Good luck!
[Yes, I know that I've missed out a few lines of using statements and the Main method, but I'm guessing that the 10 lines didn't need to be literally 10 lines]
DECLARE @tmp_key int
DECLARE @get_invckey cursor
SET @get_invckey = CURSOR FOR
SELECT invckey FROM tarinvoice WHERE confirmtocntctkey IS NULL AND tranno LIKE '%115876'
OPEN @get_invckey
FETCH NEXT FROM @get_invckey INTO @tmp_key
DECLARE @PrimaryContactKey int --or whatever datatype it is
WHILE (@@FETCH_STATUS = 0)
BEGIN
SELECT @PrimaryContactKey=c.PrimaryCntctKey
FROM tarcustomer c, tarinvoice i
WHERE i.custkey = c.custkey AND i.invckey = @tmp_key
UPDATE tarinvoice SET confirmtocntctkey = @PrimaryContactKey WHERE invckey = @tmp_key
FETCH NEXT FROM @get_invckey INTO @tmp_key
END
CLOSE @get_invckey
DEALLOCATE @get_invckey
EDIT:
This question has gotten a lot more traction than I would have anticipated. Do note that I'm not advocating the use of the cursor in my answer, but rather showing how to assign the value based on the question.
If you wish to create a pdf from php, pdflib will help you (as some others suggested).
Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.
So, the options I know are:
DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.
HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.
Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:
wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.
htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.
You KNOW for sure, that the DUPLICATE KEY will trigger, thus you can select the MAX(ID)+1 beforehand:
INSERT INTO invoices SELECT MAX(ID)+1, ... other fields ... FROM invoices AS iv WHERE iv.ID=XXXXX
Public Sub LinqToSqlJoin07()
Dim q = From e In db.Employees _
Group Join o In db.Orders On e Equals o.Employee Into ords = Group _
From o In ords.DefaultIfEmpty _
Select New With {e.FirstName, e.LastName, .Order = o}
ObjectDumper.Write(q) End Sub
Open Source: CMU Sphinx
Shareware: http://www.e-speaking.com/ (Windows)
Commercial: Dragon NaturallySpeaking (Windows)
you can follow this link to know more about How to convert a string/number into number/float/decimal in PHP. HERE IS WHAT THIS LINK SAYS...
Method 1: Using number_format() Function. The number_format() function is used to convert a string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure.
$num = "1000.314";
//Convert string in number using
//number_format(), function
echo number_format($num), "\n";
//Convert string in number using
//number_format(), function
echo number_format($num, 2);
Method 2: Using type casting: Typecasting can directly convert a string into a float, double, or integer primitive type. This is the best way to convert a string into a number without any function.
// Number in string format
$num = "1000.314";
// Type cast using int
echo (int)$num, "\n";
// Type cast using float
echo (float)$num, "\n";
// Type cast using double
echo (double)$num;
Method 3: Using intval() and floatval() Function. The intval() and floatval() functions can also be used to convert the string into its corresponding integer and float values respectively.
// Number in string format
$num = "1000.314";
// intval() function to convert
// string into integer
echo intval($num), "\n";
// floatval() function to convert
// string to float
echo floatval($num);
Method 4: By adding 0 or by performing mathematical operations. The string number can also be converted into an integer or float by adding 0 with the string. In PHP, performing mathematical operations, the string is converted to an integer or float implicitly.
// Number into string format
$num = "1000.314";
// Performing mathematical operation
// to implicitly type conversion
echo $num + 0, "\n";
// Performing mathematical operation
// to implicitly type conversion
echo $num + 0.0, "\n";
// Performing mathematical operation
// to implicitly type conversion
echo $num + 0.1;
So this isn't what the requester was asking for but it is the answer to "SQL selecting rows by most recent date".
Modified from http://wiki.lessthandot.com/index.php/Returning_The_Maximum_Value_For_A_Row
SELECT t.chargeId, t.chargeType, t.serviceMonth FROM(
SELECT chargeId,MAX(serviceMonth) AS serviceMonth
FROM invoice
GROUP BY chargeId) x
JOIN invoice t ON x.chargeId =t.chargeId
AND x.serviceMonth = t.serviceMonth
Since you added a new property to the model, you must first delete the database. Then manage.py migrations then manage.py migrate.
The time zone is a session parameter. So, you can change the timezone for the current session.
See the doc.
set timezone TO 'GMT';
Or, more closely following the SQL standard, use the SET TIME ZONE
command. Notice two words for "TIME ZONE" where the code above uses a single word "timezone".
SET TIME ZONE 'UTC';
The doc explains the difference:
SET TIME ZONE extends syntax defined in the SQL standard. The standard allows only numeric time zone offsets while PostgreSQL allows more flexible time-zone specifications. All other SET features are PostgreSQL extensions.
If you really need to use a secure foreach interface to iterate an object and make it reusable and clean with a npm module, then use this, https://www.npmjs.com/package/foreach-object
Ex:
import each from 'foreach-object';
const object = {
firstName: 'Arosha',
lastName: 'Sum',
country: 'Australia'
};
each(object, (value, key, object) => {
console.log(key + ': ' + value);
});
// Console log output will be:
// firstName: Arosha
// lastName: Sum
// country: Australia
You can just:
if(variable||variable===0){
//Yes it is set
//do something
}
else {
//No it is not set
//Or its null
//do something else
}
As this helpful article states: On OS X to start/stop MySQL from the command line:
sudo /usr/local/mysql/support-files/mysql.server start
sudo /usr/local/mysql/support-files/mysql.server stop
On Linux start/stop from the command line:
/etc/init.d/mysqld start
/etc/init.d/mysqld stop
/etc/init.d/mysqld restart
Some Linux flavours offer the service command too
# service mysqld start
# service mysqld stop
# service mysqld restart
or
# service mysql start
# service mysql stop
# service mysql restart
You need to implement the equals() method in your MyClass
.
The reason that ==
didn't work is this is checking that they refer to the same instance. Since you did new
for each, each one is a different instance.
The reason that equals()
didn't work is because you didn't implement it yourself yet. I believe it's default behavior is the same thing as ==
.
Note that you should also implement hashcode()
if you're going to implement equals()
because a lot of java.util Collections expect that.
This is pretty must just a copy of that projects demo page and shows uploading a single file on form submit with upload progress.
(function (angular) {
'use strict';
angular.module('uploadModule', [])
.controller('uploadCtrl', [
'$scope',
'$upload',
function ($scope, $upload) {
$scope.model = {};
$scope.selectedFile = [];
$scope.uploadProgress = 0;
$scope.uploadFile = function () {
var file = $scope.selectedFile[0];
$scope.upload = $upload.upload({
url: 'api/upload',
method: 'POST',
data: angular.toJson($scope.model),
file: file
}).progress(function (evt) {
$scope.uploadProgress = parseInt(100.0 * evt.loaded / evt.total, 10);
}).success(function (data) {
//do something
});
};
$scope.onFileSelect = function ($files) {
$scope.uploadProgress = 0;
$scope.selectedFile = $files;
};
}
])
.directive('progressBar', [
function () {
return {
link: function ($scope, el, attrs) {
$scope.$watch(attrs.progressBar, function (newValue) {
el.css('width', newValue.toString() + '%');
});
}
};
}
]);
}(angular));
HTML
<form ng-submit="uploadFile()">
<div class="row">
<div class="col-md-12">
<input type="text" ng-model="model.fileDescription" />
<input type="number" ng-model="model.rating" />
<input type="checkbox" ng-model="model.isAGoodFile" />
<input type="file" ng-file-select="onFileSelect($files)">
<div class="progress" style="margin-top: 20px;">
<div class="progress-bar" progress-bar="uploadProgress" role="progressbar">
<span ng-bind="uploadProgress"></span>
<span>%</span>
</div>
</div>
<button button type="submit" class="btn btn-default btn-lg">
<i class="fa fa-cloud-upload"></i>
<span>Upload File</span>
</button>
</div>
</div>
</form>
EDIT: Added passing a model up to the server in the file post.
The form data in the input elements would be sent in the data property of the post and be available as normal form values.
I have find a solution thanks to Gunter! Here is my whole code if it could help anyone:
<div class="form-group">
<label for="options">Options :</label>
<div *ngFor="#option of options; #i = index">
<label>
<input type="checkbox"
name="options"
value="{{option}}"
[checked]="options.indexOf(option) >= 0"
(change)="updateCheckedOptions(option, $event)"/>
{{option}}
</label>
</div>
</div>
Here are the 3 objects I'm using:
options = ['OptionA', 'OptionB', 'OptionC'];
optionsMap = {
OptionA: false,
OptionB: false,
OptionC: false,
};
optionsChecked = [];
And there are 3 useful methods:
1. To initiate optionsMap
:
initOptionsMap() {
for (var x = 0; x<this.order.options.length; x++) {
this.optionsMap[this.options[x]] = true;
}
}
2. to update the optionsMap
:
updateCheckedOptions(option, event) {
this.optionsMap[option] = event.target.checked;
}
3. to convert optionsMap
into optionsChecked
and store it in options
before sending the POST request:
updateOptions() {
for(var x in this.optionsMap) {
if(this.optionsMap[x]) {
this.optionsChecked.push(x);
}
}
this.options = this.optionsChecked;
this.optionsChecked = [];
}
Byte swapping with ye olde 3-step-xor trick around a pivot in a template function gives a flexible, quick O(ln2) solution that does not require a library, the style here also rejects 1 byte types:
template<typename T>void swap(T &t){
for(uint8_t pivot = 0; pivot < sizeof(t)/2; pivot ++){
*((uint8_t *)&t + pivot) ^= *((uint8_t *)&t+sizeof(t)-1- pivot);
*((uint8_t *)&t+sizeof(t)-1- pivot) ^= *((uint8_t *)&t + pivot);
*((uint8_t *)&t + pivot) ^= *((uint8_t *)&t+sizeof(t)-1- pivot);
}
}
I was facing an issue where Slick carousel wasn't refreshing on new data, it was appending new slides to previous ones, I found an answer which solved my problem, it's very simple.
try unslick, then assign your new data which is being rendered inside slick carousel, and then initialize slick again. these were the steps for me:
jQuery('.class-or-#id').slick('unslick');
myData = my-new-data;
jQuery('.class-or-#id').slick({slick options});
Note: check slick website for syntax just in case. also make sure you are not using unslick before slick is even initialized, what that means is simply initialize (like this jquery('.my-class').slick({options}
); the first ajax call and once it is initialized then follow above steps, you may wanna use if else
You just need to use the Gradle Application plugin:
apply plugin:'application'
mainClassName = "org.gradle.sample.Main"
And then simply gradle run
.
As Teresa points out, you can also configure mainClassName
as a system property and run with a command line argument.
In my experience all the files which i have downloaded from internet,gmail
are stored in
/sdcard/download
on ics
/sdcard/Download
You can access it using
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Try this::
sb_trim = Regex.Replace(stw, @"(\D+)\s+\$([\d,]+)\.\d+\s+(.)",
m => string.Format(
"{0},{1},{2}",
m.Groups[1].Value,
m.Groups[2].Value.Replace(",", string.Empty),
m.Groups[3].Value));
This is about as clean an answer as you'll get, at least with regexes.
(\D+)
: First capture group. One or more non-digit characters.\s+\$
: One or more spacing characters, then a literal dollar sign ($).([\d,]+)
: Second capture group. One or more digits and/or commas.\.\d+
: Decimal point, then at least one digit.\s+
: One or more spacing characters.(.)
: Third capture group. Any non-line-breaking character.The second capture group additionally needs to have its commas stripped. You could do this with another regex, but it's really unnecessary and bad for performance. This is why we need to use a lambda expression and string format to piece together the replacement. If it weren't for that, we could just use this as the replacement, in place of the lambda expression:
"$1,$2,$3"
Using an in
can have a performance impact. Joining two subqueries will not have the same performance impact and can be accomplished like this:
SELECT *
FROM (SELECT msisdn
,callid
,Change_color
,play_file_name
,date_played
FROM insert_log
WHERE play_file_name NOT IN('Prompt1','Conclusion_Prompt_1','silent')
ORDER BY callid ASC) t1
JOIN (SELECT MAX(date_played) AS date_played
FROM insert_log GROUP BY callid) t2
ON t1.date_played = t2.date_played
You can try using StringBuilder
: -
final StringBuilder sb = new StringBuilder();
sb.append("SHOP MA\n");
sb.append("----------------------------\n");
sb.append("Pannampitiya\n");
sb.append("09-10-2012 harsha no: 001\n");
sb.append("No Item Qty Price Amount\n");
sb.append("1 Bread 1 50.00 50.00\n");
sb.append("____________________________\n");
// To use StringBuilder as String.. Use `toString()` method..
System.out.println(sb.toString());
A character set is a subset of all written glyphs. A character encoding specifies how those characters are mapped to numeric values. Some character encodings, like UTF-8 and UTF-16, can encode any character in the Universal Character Set. Others, like US-ASCII or ISO-8859-1 can only encode a small subset, since they use 7 and 8 bits per character, respectively. Because many standards specify both a character set and a character encoding, the term "character set" is often substituted freely for "character encoding".
A collation comprises rules that specify how characters can be compared for sorting. Collations rules can be locale-specific: the proper order of two characters varies from language to language.
Choosing a character set and collation comes down to whether your application is internationalized or not. If not, what locale are you targeting?
In order to choose what character set you want to support, you have to consider your application. If you are storing user-supplied input, it might be hard to foresee all the locales in which your software will eventually be used. To support them all, it might be best to support the UCS (Unicode) from the start. However, there is a cost to this; many western European characters will now require two bytes of storage per character instead of one.
Choosing the right collation can help performance if your database uses the collation to create an index, and later uses that index to provide sorted results. However, since collation rules are often locale-specific, that index will be worthless if you need to sort results according to the rules of another locale.
Other answers have covered pretty much everything about how we can pass model to our layout page. But I have found a way using which you can pass variables to your layout page dynamically without using any model or partial view in your layout. Let us say you have this model -
public class SubLocationsViewModel
{
public string city { get; set; }
public string state { get; set; }
}
And you want to get city and state dynamically. For e.g
in your index.cshtml you can put these two variables in ViewBag
@model MyProject.Models.ViewModel.SubLocationsViewModel
@{
ViewBag.City = Model.city;
ViewBag.State = Model.state;
}
And then in your layout.cshtml you can access those viewbag variables
<div class="text-wrap">
<div class="heading">@ViewBag.City @ViewBag.State</div>
</div>
Find your amended commits by:
git log --reflog
Note: You may add --patch
to see the body of the commits for clarity. Same as git reflog
.
then reset your HEAD to any previous commit at the point it was fine by:
git reset SHA1 --hard
Note: Replace SHA1 with your real commit hash. Also note that this command will lose any uncommitted changes, so you may stash them before. Alternatively, use --soft
instead to retain the latest changes and then commit them.
Then cherry-pick the other commit that you need on top of it:
git cherry-pick SHA1
You can just delete that directory that you cloned the repo into, and re-clone it wherever you'd like.
First page (scroll down to see the second page)_x000D_
<div style="break-after:page"></div>_x000D_
Second page_x000D_
<br>_x000D_
<br>_x000D_
<button onclick="window.print();return false;" />Print (to see the result) </button>
_x000D_
Just add this where you need the page to go to the next one (the text "page 1" will be on page 1 and the text "page 2" will be on the second page).
Page 1
<div style='page-break-after:always'></div>
Page 2
This works too:
First page (there is a break after this)
<div style="break-after:page"></div>
Second page (This will be printed in the second page)
you can declare a Numpy array dynamically for 1 dimension as shown below:
import numpy as np
n = 2
new_table = np.empty(shape=[n,1])
new_table[0,0] = 2
new_table[1,0] = 3
print(new_table)
The above example assumes we know we need to have 1 column but we want to allocate the number of rows dynamically (in this case the number or rows required is equal to 2)
output is shown below:
[[2.] [3.]]
As of Java 1.7, there's a new way: java.nio.file.Files.write
import java.nio.file.Files;
import java.nio.file.Paths;
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
byte[] encoded = key.getEncoded();
Files.write(Paths.get("target-file"), encoded);
Java 1.7 also resolves the embarrassment that Kevin describes: reading a file is now:
byte[] data = Files.readAllBytes(Paths.get("source-file"));
You are trying to call DeckOfCards::shuffle
with a deckOfCards
parameter:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck
But the method takes a vector<Card>&
:
void deckOfCards::shuffle(vector<Card>& deck)
The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.
Error:
[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'
Paraphrased:
Hey, pal. You're trying to call a function called
shuffle
which apparently takes a single parameter of type reference-to-deckOfCards
, but there is no such function.
Error:
[Note] candidate is:
In file included from main.cpp
[Note] void deckOfCards::shuffle(std::vector&)
Paraphrased:
I mean, maybe you meant this other function called
shuffle
, but that one takes a reference-tovector<something>
.
Error:
[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'
Which I'd be happy to call if I knew how to convert from a
deckOfCards
to avector
; but I don't. So I won't.
Binding or setting of default value works only if the value attribute on MatSelect is comparable to value attribute binded to MatOption. If you bind caption
of your item to value attribute of mat-option element you must set the default element on mat-select to caption
of your item too. If you bind Id
of your item to mat-option, you must bind id
to mat-select too, not a whole item, caption or any other, only the same field.
But you need to do it with binding []
The answer is neither.
Docker Compose (herein referred to as compose) will use the Dockerfile if you add the build command to your project's docker-compose.yml
.
Your Docker workflow should be to build a suitable Dockerfile
for each image you wish to create, then use compose to assemble the images using the build
command.
You can specify the path to your individual Dockerfiles using build /path/to/dockerfiles/blah
where /path/to/dockerfiles/blah
is where blah's Dockerfile
lives.
You define an enumeration to restrict the possible values of elements of the type to a limited set. This restriction is to be enforced at compile time.
When forward declaring the fact that you will use a 'limited set' later on doesn't add any value: subsequent code needs to know the possible values in order to benefit from it.
Although the compiler is concerned about the size of the enumerated type, the intent of the enumeration gets lost when you forward declare it.
The increase-memory-limit
module has been deprecated now.
As of Node.js v8.0 shipped August 2017, we can now use the NODE_OPTIONS
env variable to set the max_old_space_size
globally.
export NODE_OPTIONS=--max_old_space_size=4096
I wrote this so I could edit all tables and columns to null at once:
select
case
when sc.max_length = '-1' and st.name in ('char','decimal','nvarchar','varchar')
then
'alter table [' + so.name + '] alter column [' + sc.name + '] ' + st.name + '(MAX) NULL'
when st.name in ('char','decimal','nvarchar','varchar')
then
'alter table [' + so.name + '] alter column [' + sc.name + '] ' + st.name + '(' + cast(sc.max_length as varchar(4)) + ') NULL'
else
'alter table [' + so.name + '] alter column [' + sc.name + '] ' + st.name + ' NULL'
end as query
from sys.columns sc
inner join sys.types st on st.system_type_id = sc.system_type_id
inner join sys.objects so on so.object_id = sc.object_id
where so.type = 'U'
and st.name <> 'timestamp'
order by st.name
There are a couple of variables to set the max number of connections. Most likely, you're running out of file numbers first. Check ulimit -n. After that, there are settings in /proc, but those default to the tens of thousands.
More importantly, it sounds like you're doing something wrong. A single TCP connection ought to be able to use all of the bandwidth between two parties; if it isn't:
ping -s 1472
...)tc
iperf
Possibly I have misunderstood. Maybe you're doing something like Bittorrent, where you need lots of connections. If so, you need to figure out how many connections you're actually using (try netstat
or lsof
). If that number is substantial, you might:
ulimit -n
. Still, ~1000 connections (default on my system) is quite a few.iostat -x
?Also, if you are using a consumer-grade NAT router (Linksys, Netgear, DLink, etc.), beware that you may exceed its abilities with thousands of connections.
I hope this provides some help. You're really asking a networking question.
i know it is a controversial topic, and likely i get burned now. but here are my thoughts.
For myself i figured that it is best to avoid classes as long as possible. If i need a complex datatype I use simple struct (C/C++), dict (python), JSON (js), or similar, i.e. no constructor, no class methods, no operator overloading, no inheritance, etc. When using class, you can get carried away by OOP itself (What Design pattern, what should be private, bla bla), and loose focus on the essential stuff you wanted to code in the first place.
If your project grows big and messy, then OOP starts to make sense because some sort of helicopter-view system architecture is needed. "function vs class" also depends on the task ahead of you.
Edit your php.ini, find allow_url_fopen and set it to allow_url_fopen = 1
The easiest way is using shift()
. If you have an array, the shift
function shifts everything to the left.
var arr = [1, 2, 3, 4];
var theRemovedElement = arr.shift(); // theRemovedElement == 1
console.log(arr); // [2, 3, 4]
I prefer to use DirectoryInfo because I can get FileInfo's, not just strings.
string baseFolder = @"C:\temp";
DirectoryInfo di = new DirectoryInfo(baseFolder);
string searchPattern = "*.xml";
ICollection<FileInfo> matchingFileInfos = di.GetFiles(searchPattern, SearchOption.AllDirectories)
.Select(x => x)
.ToList();
I do this in case in the future I need future filtering..based on the properties of FileInfo.
string baseFolder = @"C:\temp";
DirectoryInfo di = new DirectoryInfo(baseFolder);
string searchPattern = "*.xml";
ICollection<FileInfo> matchingFileInfos = di.GetFiles(searchPattern, SearchOption.AllDirectories)
.Where(x => x.LastWriteTimeUtc < DateTimeOffset.Now)
.Select(x => x)
.ToList();
I can also resort back to strings if need be. (and still am future proofed for filters/where-clause stuff.
string baseFolder = @"C:\temp";
DirectoryInfo di = new DirectoryInfo(baseFolder);
string searchPattern = "*.xml";
ICollection<string> matchingFileNames = di.GetFiles(searchPattern, SearchOption.AllDirectories)
.Select(x => x.FullName)
.ToList();
Note that "." is a valid search pattern if you want to filer by extension.
You need to specify an access modifier for your variable. In this case you want it public.
public class Variables
{
public static string name = "";
}
After this you can use the variable like this.
Variables.name
List<string> animals= new List<string>();
animals.Add("dog");
animals.Add("tiger");
This procedure works even if ADB is not available.
There you go:
<i class="glyphicon glyphicon-search"></i>
More information:
http://getbootstrap.com/components/#glyphicons
Btw. you can use this conversion tool, this will also update the code for the icons:
for me, just press cmd+, then go to account ,chose your developer account refresh(XCODE6) OR download all (XCODE7) will fix.
Yes, this can be done with the UIWebView.
If you are trying to display a PDF file residing on a server somewhere, you can simply load it in your web view directly:
Objective-C
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
NSURL *targetURL = [NSURL URLWithString:@"https://www.example.com/document.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
Swift
let webView = UIWebView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))
let targetURL = NSURL(string: "https://www.example.com/document.pdf")! // This value is force-unwrapped for the sake of a compact example, do not do this in your code
let request = NSURLRequest(URL: targetURL)
webView.loadRequest(request)
view.addSubview(webView)
Or if you have a PDF file bundled with your application (in this example named "document.pdf"):
Objective-C
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
NSURL *targetURL = [[NSBundle mainBundle] URLForResource:@"document" withExtension:@"pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
Swift
let webView = UIWebView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))
let targetURL = NSBundle.mainBundle().URLForResource("document", withExtension: "pdf")! // This value is force-unwrapped for the sake of a compact example, do not do this in your code
let request = NSURLRequest(URL: targetURL)
webView.loadRequest(request)
view.addSubview(webView)
You can find more information here: Technical QA1630: Using UIWebView to display select document types.
Stupid mistake:
make sure you add register(TableViewCell.self, forCellReuseIdentifier: "Cell")
instead of register(TableViewCell.self, forHeaderFooterViewReuseIdentifier: "Cell")
NSString's method is lowercaseString
(0 arguments), not lowercaseString:
(1 argument).
Uncomment IE section in the src/polyfill.js,
/** IE10 and IE11 requires the following for NgClass support on SVG elements*/
import 'classlist.js';
If any build error for missing package then,
npm install classlist.js --save-exact
Make sure to include below line to set the default IE document mode. Other wise it will open in version 7
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
Found out by adding this to your url parameters
approval_prompt=force
Update:
Use access_type=offline&prompt=consent
instead.
approval_prompt=force
no longer works
https://github.com/googleapis/oauth2client/issues/453
first find your binaries file where it is saved. get the path in terminal mine is
C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin
then find your local user data path, it is in mostly
C:\usr\local\pgsql\data
now all we have to hit following command in the binary terminal path:
C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin>pg_ctl -D "C:\usr\local\pgsql\data" start
all done!
autovaccum launcher started! cheers!
The Miro video converter does a beautiful job and is drag-n-drop. http://www.mirovideoconverter.com/
BTW it's FREE and also very good for mobile device encoding.
You can set the index by this code :
sel.selectedIndex = 0;
but remember a caution in this practice, You would not be able to call the server side onclick
method if you select the previous value selected in the drop down..
The simplest way would be to use FOpen or one of FOpen's Wrappers.
$page = file_get_contents("http://www.domain.com/filename");
This does require FOpen which some web hosts disable and some web hosts will allow FOpen, but not allow access to external files. You may want to check where you are going to run the script to see if you have access to External FOpen.
The best way I have found to manage keyboard input on a Windows Forms form is to process it after the keystroke and before the focused control receives the event. Microsoft maintains a built-in Form
-level property named .KeyPreview to facilitate this precise thing:
public frmForm()
{
// ...
frmForm.KeyPreview = true;
// ...
}
Then the form's _KeyDown, _KeyPress, and / or _KeyUp events can be marshaled to access input events before the focused form control ever sees them, and you can apply handler logic to capture the event there or allow it to pass through to the focused form control.
Although not as structurally graceful as XAML's event-routing architecture, it makes management of form-level functions in Winforms far simpler. See the MSDN notes on KeyPreview for caveats.
OpenMP is supported on many platforms (including Visual Studio 2005) and it offers a
int omp_get_num_procs();
function that returns the number of processors/cores available at the time of call.
you can use editor.fontSize
into your setting.json
file of the editor.
for example :
{
"editor.fontSize": 14
}
In-order to make SQL server send email notification you need to create mail profile from Management, database mail.
1) User Right click to get the mail profile menu and choose configure database mail
2)choose the first open (set up a database mail by following the following tasks) and press next Note: if the SMTP is not configured please refer the the URL below
http://www.symantec.com/business/support/index?page=content&id=TECH86263
3) in the second screen fill the the profile name and add SMTP account, then press next
4) choose the type of mail account ( public or private ) then press next
5) change the parameters that related to the sending mail options, and press next 6) press finish
Now to make SQL server send an email if action X happened you can do that via trigger or job ( This is the common ways not the only ones).
1) you can create Job from SQL server agent, then right click on operators and check mails (fill the your email for example) and press OK after that right click Jobs and choose new job and fill the required info as well as the from steps, name, ...etc and from notification tab select the profile you made.
2) from triggers please refer to the example below.
AS
declare @results varchar(max)
declare @subjectText varchar(max)
declare @databaseName VARCHAR(255)
SET @subjectText = 'your subject'
SET @results = 'your results'
-- write the Trigger JOB
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'SQLAlerts',
@recipients = '[email protected]',
@body = @results,
@subject = @subjectText,
@exclude_query_output = 1 --Suppress 'Mail Queued' message
GO
WITH UpdateList_view AS (
SELECT TOP 1 * from TX_Master_PCBA
WHERE SERIAL_NO IN ('0500030309')
ORDER BY TIMESTAMP2 DESC
)
update UpdateList_view
set TIMESTAMP2 = '2013-12-12 15:40:31.593'
I had a similar problem and the reason was that there were two versions of Node installed in my machine: one "global" and another one at the project level. Sass will build correctly only if the Gulp build is running under Node.js 4.x version, so make sure you upgrade the version of Node you are using.
PS: If you completely remove the node_modules folder in your project and re-build from scratch, npm will download the correct dependencies for your current system & node version.
using as will return null if not a valid cast which allows you to do other things besides wrapping the cast in a try/catch. I hate classic cast. I always use as cast if i'm not sure. Plus, exceptions are expensive. Null checks are not.
On recent Ubuntu (12.04 in my case), it's possible for "Segmentation fault (core dumped)" to be printed, but no core file produced where you might expect one (for instance for a locally compiled program).
This can happen if you have a core file size ulimit of 0 (you haven't done ulimit -c unlimited
) -- this is the default on Ubuntu. Normally that would suppress the "(core dumped)", cluing you into your mistake, but on Ubuntu, corefiles are piped to Apport (Ubuntu's crash reporting system) via /proc/sys/kernel/core_pattern
, and this seems to cause the misleading message.
If Apport discovers that the program in question is not one it should be reporting crashes for (which you can see happening in /var/log/apport.log
), it falls back to simulating the default kernel behaviour of putting a core file in the cwd (this is done in the script /usr/share/apport/apport
). This includes honouring ulimit, in which case it does nothing. But (I assume) as far as the kernel is concerned, a corefile was generated (and piped to apport), hence the message "Segmentation fault (core dumped)".
Ultimately PEBKAC for forgetting to set ulimit, but the misleading message had me thinking I was going mad for a while, wondering what was eating my corefiles.
(Also, in general, the core(5) manual page -- man 5 core
-- is a good reference for where your core file ends up and reasons it might not be written.)
Just for the sake of keeping the information up-to-date, with at least JIRA 7.3.0 (maybe older as well) you can explicitly specify the date in multiple formats:
'yyyy/MM/dd HH:mm'
;'yyyy-MM-dd HH:mm'
;'yyyy/MM/dd'
;'yyyy-MM-dd'
;Example:
updatedDate > '2018/06/09 0:00' and updatedDate < '2018/06/10 15:00'
An HttpOnly
cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly
attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly
.
Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly
by just XSS and still have access to the cookie via JS and thus make the HttpOnly
on your cookie completely useless.
JSON.stringify
takes more optional arguments.
Try:
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab
From:
How can I beautify JSON programmatically?
Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre>
tag to get newlines to show.
Look at the traceback:
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
out = iter(out)
TypeError: 'bool' object is not iterable
Your code isn't iterating the value, but the code receiving it is.
The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)
) or enclose it in a tuple ((False,)
).
Always read the traceback: it's correct, and it's helpful.
Instead of switch statements, consider using tables of strings indexed by a small value.
const char * const ones[20] = {"zero", "one", "two", ..., "nineteen"};
const char * const tens[10] = {"", "ten", "twenty", ..., "ninety"};
Now break the problem into small pieces. Write a function that can output a single-digit number. Then write a function that can handle a two-digit number (which will probably use the previous function). Continue building up the functions as necessary.
Create a list of test cases with expected output, and write code to call your functions and check the output, so that, as you fix problems for the more complicated cases, you can be sure that the simpler cases continue to work.
use MM
(months) instead of mm
(minutes) :
DateTime.Now.ToString("dd/MM/yyyy");
check here for more format options.
found
will be npos
in case of failure to find the substring in the search string.
Use a for
loop instead of .forEach()
var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false
for(var call of myObj) {
console.log(call)
var a = call['a'], b = call['b']
if(a == null || b == null) {
result = false
break
}
}
To expand on the above and make a quick reference:
ALTER USER username WITH SUPERUSER;
ALTER USER username WITH NOSUPERUSER;
ALTER USER username CREATEDB;
You can also use CREATEROLE
and CREATEUSER
to allow a user privileges without making them a superuser.
With this method you can set font size, font style and Header background also. there are have 2 method for this
First Method
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
header.backgroundView.backgroundColor = [UIColor darkGrayColor];
header.textLabel.font=[UIFont fontWithName:@"Open Sans-Regular" size:12];
[header.textLabel setTextColor:[UIColor whiteColor]];
}
Second Method
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)];
// myLabel.frame = CGRectMake(20, 8, 320, 20);
myLabel.font = [UIFont fontWithName:@"Open Sans-Regular" size:12];
myLabel.text = [NSString stringWithFormat:@" %@",[self tableView:FilterSearchTable titleForHeaderInSection:section]];
myLabel.backgroundColor=[UIColor blueColor];
myLabel.textColor=[UIColor whiteColor];
UIView *headerView = [[UIView alloc] init];
[headerView addSubview:myLabel];
return headerView;
}
For AWS users who work with Amazon SES in conjunction with PHPMailer, this error also appears when your "from" mail sender isn't a verified sender.
To add a verified sender:
Log in to your Amazon AWS console: https://console.aws.amazon.com
Select "Amazon SES" from your list of available AWS applications
Select, under "Verified Senders", the "Email Addresses" --> "Verify a new email address"
Navigate to that new sender's email, click the confirmation e-mail's link.
And you're all set.
In Build: v22.6.2-1085508 ADT you need to add(select Android 4.4.2)
Goto project --> properties --> Android(This is second in listed item order leftPanel) and in the RightPanel Project Build Target, select Android 4.4.2 as Target name and apply changes It will rebuild the workspace.
In my case unable to resolve target 'android-17' eclipse was being shown as compile error and in code: import java.util.HashMap was not being referenced.
I used this:
myElement = document.getElemenById("xyz");
Get_Offset_From_Start ( myElement ); // returns positions from website's start position
Get_Offset_From_CurrentView ( myElement ); // returns positions from current scrolled view's TOP and LEFT
code:
function Get_Offset_From_Start (object, offset) {
offset = offset || {x : 0, y : 0};
offset.x += object.offsetLeft; offset.y += object.offsetTop;
if(object.offsetParent) {
offset = Get_Offset_From_Start (object.offsetParent, offset);
}
return offset;
}
function Get_Offset_From_CurrentView (myElement) {
if (!myElement) return;
var offset = Get_Offset_From_Start (myElement);
var scrolled = GetScrolled (myElement.parentNode);
var posX = offset.x - scrolled.x; var posY = offset.y - scrolled.y;
return {lefttt: posX , toppp: posY };
}
//helper
function GetScrolled (object, scrolled) {
scrolled = scrolled || {x : 0, y : 0};
scrolled.x += object.scrollLeft; scrolled.y += object.scrollTop;
if (object.tagName.toLowerCase () != "html" && object.parentNode) { scrolled=GetScrolled (object.parentNode, scrolled); }
return scrolled;
}
/*
// live monitoring
window.addEventListener('scroll', function (evt) {
var Positionsss = Get_Offset_From_CurrentView(myElement);
console.log(Positionsss);
});
*/
Using this Function u can define your won position
setBounds(500, 200, 647, 418);
Converting a varchar
value into an int
fails when the value includes a decimal point to prevent loss of data.
If you convert to a decimal
or float
value first, then convert to int
, the conversion works.
Either example below will return 7082:
SELECT CONVERT(int, CONVERT(decimal(12,7), '7082.7758172'));
SELECT CAST(CAST('7082.7758172' as float) as int);
Be aware that converting to a float
value may result, in rare circumstances, in a loss of precision. I would tend towards using a decimal
value, however you'll need to specify precision and scale values that make sense for the varchar
data you're converting.
That is SQL Server syntax for converting a date to a string. In MySQL you can use the DATE function to extract the date from a datetime:
SELECT *
FROM players
WHERE DATE(us_reg_date) BETWEEN '2000-07-05' AND '2011-11-10'
But if you want to take advantage of an index on the column us_reg_date
you might want to try this instead:
SELECT *
FROM players
WHERE us_reg_date >= '2000-07-05'
AND us_reg_date < '2011-11-10' + interval 1 day
Your tables should have as immediate children just tbody
and thead
elements, with the rows within*. So, amend the HTML to be:
<table border="1" width="100%" id="test">
<tbody>
<tr>
<td>
<table border="1" width="100%">
<tbody>
<tr>
<td>table 2</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
</tbody>
</table>
Then amend your selector slightly to this:
#test > tbody > tr:last-child { background:#ff0000; }
See it in action here. That makes use of the child selector, which:
...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.
So, you are targeting only direct children of tbody
elements that are themselves direct children of your #test
table.
The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:
#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }
* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:
...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.
Since switch case
always returns a single object, we can directly print its result:
puts case a
when 0
"It's zero"
when 1
"It's one"
end
There is a method object_of_ViewPager.getCurrentItem()
which returns the position of currently Viewed page of view pager
As an aside to those that stumble along across this, one nice way to run test level on using the HostingEnvironment call, is if accessing say a UNC share: \example\ that is mapped to ~/example/ you could execute this to get around IIS-Express issues:
#if DEBUG
var fs = new FileStream(@"\\example\file",FileMode.Open, FileAccess.Read);
#else
var fs = new FileStream(HostingEnvironment.MapPath("~/example/file"), FileMode.Open, FileAccess.Read);
#endif
I find that helpful in case you have rights to locally test on a file, but need the env mapping once in production.
I usually execute following command in cmd prompt to check if my program.exe is running or not:
tasklist | grep program
As of Ubuntu 12.04 (Precise Pangolin) (and perhaps a release or two before) simply installing apache2
and mod-perl
via Synaptic and placing your CGI scripts in /usr/lib/cgi-bin is really all you need to do.
Use keydown
, not keypress
for non-printable keys such as arrow keys:
function checkKey(e) {
e = e || window.event;
alert(e.keyCode);
}
document.onkeydown = checkKey;
The best JavaScript key event reference I've found (beating the pants off quirksmode, for example) is here: http://unixpapa.com/js/key.html
If you look at the methods AtomicInteger has, you'll notice that they tend to correspond to common operations on ints. For instance:
static AtomicInteger i;
// Later, in a thread
int current = i.incrementAndGet();
is the thread-safe version of this:
static int i;
// Later, in a thread
int current = ++i;
The methods map like this:
++i
is i.incrementAndGet()
i++
is i.getAndIncrement()
--i
is i.decrementAndGet()
i--
is i.getAndDecrement()
i = x
is i.set(x)
x = i
is x = i.get()
There are other convenience methods as well, like compareAndSet
or addAndGet
'lines' term from your snippet consists of set of strings.
lines = f.readlines()
match = re.findall('[A-Z]+', lines)
You cannot send entire lines into the re.findall('pattern',<string>)
You can try to send line by line
for i in lines:
match = re.findall('[A-Z]+', i)
print match
or to convert the entire lines collection into single line (each line seperated by space)
NEW_LIST=' '.join(lines)
match=re.findall('[A-Z]+' ,NEW_LIST)
print match
This might help you
DST aware solution:
Manipulating the Timezone is possible for changing the clock some hours. Due to the daylight saving time, 24 hours ago can be today or the day before yesterday.
You are sure that yesterday is 20 or 30 hours ago. Which one? Well, the most recent one that is not today.
echo -e "$(TZ=GMT+30 date +%Y-%m-%d)\n$(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1
The -e parameter used in the echo command is needed with bash, but will not work with ksh. In ksh you can use the same command without the -e flag.
When your script will be used in different environments, you can start the script with #!/bin/ksh or #!/bin/bash. You could also replace the \n by a newline:
echo "$(TZ=GMT+30 date +%Y-%m-%d)
$(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1
Here are some supplemental examples to see the raw text that Postman passes in the request. You can see this by opening the Postman console:
Header
content-type: multipart/form-data; boundary=--------------------------590299136414163472038474
Body
key1=value1key2=value2
Header
Content-Type: application/x-www-form-urlencoded
Body
key1=value1&key2=value2
Header
Content-Type: text/plain
Body
This is some text.
Header
Content-Type: application/json
Body
{"key1":"value1","key2":"value2"}
I just had a similar issue, but it didn't error immediately, so it may have not been the same issue.
I'm behind a firewall and changed my proxy settings (TortoiseSVN->Settings->Network) to access an open source repo yesterday. I received the error this morning trying to checkout a repo in the local domain behind the firewall. I just had to remove the proxy settting in TortoiseSVN->Settings->Network to get it work locally again.
I make sure that I add the Style of the Image. It worked for me
style= "width:320; height:240"
I am using Microsoft's Visual Code for resolving conflicts. Its very simple to use. I keep my project open in the workspace. It detects and highlights conflicts, moreover give GUI options to select whatever change I want to keep from HEAD or incoming.
I'm not sure what you're trying to achieve, but you may want to consider using jQuery, which allows you to put your code in the head tag or a separate script file and still have the code executed after the DOM has loaded.
You can then do something like:
$(document).ready(function() {
$(document).remove();
});
as well as selectively removing elements (all DIVs, only DIVs with certain classes, etc.)
I've added to /etc/sysconfig/jenkins (CentOS):
# Options to pass to java when running Jenkins.
#
JENKINS_JAVA_OPTIONS="-Djava.awt.headless=true -Xmx1024m -XX:MaxPermSize=512m"
For ubuntu the same config should be located in /etc/default
If you are running out of heap space during the surefire (or failsafe) JUnit testing run, changing MAVEN_OPTS may not help you. I kept trying different configurations in MAVEN_OPTS with no luck until I found this post that fixed the problem.
Basically the JUnits fork off into their own environment and ignore the settings in MAVEN_OPTS. You need to configure surefire in your pom to add more memory for the JUnits.
Hopefully this can save someone else some time!
Edit: Copying solution from Keith Chapman's blog just in case the link breaks some day:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkMode>pertest</forkMode>
<argLine>-Xms256m -Xmx512m</argLine>
<testFailureIgnore>false</testFailureIgnore>
<skip>false</skip>
<includes>
<include>**/*IntegrationTestSuite.java</include>
</includes>
</configuration>
</plugin>
Update (5/31/2017): Thanks to @johnstosh for pointing this out - surefire has evolved a bit since I put this answer out there. Here is a link to their documentation and an updated code sample (arg line is still the important part for this question):
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20</version>
<configuration>
<forkCount>3</forkCount>
<reuseForks>true</reuseForks>
<argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
<systemPropertyVariables>
<databaseSchema>MY_TEST_SCHEMA_${surefire.forkNumber}</databaseSchema>
</systemPropertyVariables>
<workingDirectory>FORK_DIRECTORY_${surefire.forkNumber}</workingDirectory>
</configuration>
</plugin>
You forgot to reset the position of the memory stream:
private void Test()
{
System.IO.MemoryStream data = new System.IO.MemoryStream();
System.IO.Stream str = TestStream();
str.CopyTo(data);
// Reset memory stream
data.Seek(0, SeekOrigin.Begin);
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);
}
Update:
There is one more thing to note: It usually pays not to ignore the return values of methods. A more robust implementation should check how many bytes have been read after the call returns:
private void Test()
{
using(MemoryStream data = new MemoryStream())
{
using(Stream str = TestStream())
{
str.CopyTo(data);
}
// Reset memory stream
data.Seek(0, SeekOrigin.Begin);
byte[] buf = new byte[data.Length];
int bytesRead = data.Read(buf, 0, buf.Length);
Debug.Assert(bytesRead == data.Length,
String.Format("Expected to read {0} bytes, but read {1}.",
data.Length, bytesRead));
}
}
For jQuery 1.6+ :
.attr() is deprecated for properties; use the new .prop() function instead as:
$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it
For jQuery < 1.6:
To check/uncheck a checkbox, use the attribute checked
and alter that. With jQuery you can do:
$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it
Cause you know, in HTML, it would look something like:
<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->
However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.
Python treats comma on the left hand side of equal sign ( =
) as an input splitter,
Very useful for functions that return a tuple.
e.g,
x,y = (5,2)
What you want to do is:
grade_1 = grade_2 = grade_3 = average = 0.0
though that might not be the most clear way to write it.
It's obvious, but the App Theme
selection in design is just for display a draft during layout edition, is not related to real app looking in cell phone.
Just change the manifest file (AndroidManifest.xml
) is not enough because the style need to be predefined is styles.xml
. Also is useless change the layout files.
All proposed solution in Java
or Kotlin
has failed for me. Some of them crash the app. And if one never (like me) uses the title bar in app, the static solution is cleaner.
For me the only solution that works in 2019 (Android Studio 3.4.1) is:
in styles.xml
(under app/res/values) add the lines:
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
After in AndroidManifest.xml
(under app/manifests)
Replace
android:theme="@style/AppTheme">
by
android:theme="@style/AppTheme.NoActionBar">
This is exactly what you need. See it in action here 8FydL/445
Example's Code below:
$(".dropdown img.flag").addClass("flagvisibility");_x000D_
$(".dropdown dt a").click(function() {_x000D_
$(".dropdown dd ul").toggle();_x000D_
});_x000D_
_x000D_
$(".dropdown dd ul li a").click(function() {_x000D_
var text = $(this).html();_x000D_
$(".dropdown dt a span").html(text);_x000D_
$(".dropdown dd ul").hide();_x000D_
$("#result").html("Selected value is: " + getSelectedValue("sample"));_x000D_
});_x000D_
_x000D_
function getSelectedValue(id) {_x000D_
return $("#" + id).find("dt a span.value").html();_x000D_
}_x000D_
_x000D_
$(document).bind('click', function(e) {_x000D_
var $clicked = $(e.target);_x000D_
if (! $clicked.parents().hasClass("dropdown"))_x000D_
$(".dropdown dd ul").hide();_x000D_
});_x000D_
_x000D_
$(".dropdown img.flag").toggleClass("flagvisibility");
_x000D_
.desc { color:#6b6b6b;}_x000D_
.desc a {color:#0092dd;}_x000D_
_x000D_
.dropdown dd, .dropdown dt, .dropdown ul { margin:0px; padding:0px; }_x000D_
.dropdown dd { position:relative; }_x000D_
.dropdown a, .dropdown a:visited { color:#816c5b; text-decoration:none; outline:none;}_x000D_
.dropdown a:hover { color:#5d4617;}_x000D_
.dropdown dt a:hover { color:#5d4617; border: 1px solid #d0c9af;}_x000D_
.dropdown dt a {background:#e4dfcb url('http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/arrow.png') no-repeat scroll right center; display:block; padding-right:20px;_x000D_
border:1px solid #d4ca9a; width:150px;}_x000D_
.dropdown dt a span {cursor:pointer; display:block; padding:5px;}_x000D_
.dropdown dd ul { background:#e4dfcb none repeat scroll 0 0; border:1px solid #d4ca9a; color:#C5C0B0; display:none;_x000D_
left:0px; padding:5px 0px; position:absolute; top:2px; width:auto; min-width:170px; list-style:none;}_x000D_
.dropdown span.value { display:none;}_x000D_
.dropdown dd ul li a { padding:5px; display:block;}_x000D_
.dropdown dd ul li a:hover { background-color:#d0c9af;}_x000D_
_x000D_
.dropdown img.flag { border:none; vertical-align:middle; margin-left:10px; }_x000D_
.flagvisibility { display:none;}
_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>_x000D_
<dl id="sample" class="dropdown">_x000D_
<dt><a href="#"><span>Please select the country</span></a></dt>_x000D_
<dd>_x000D_
<ul>_x000D_
<li><a href="#">Brazil<img class="flag" src="http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/br.png" alt="" /><span class="value">BR</span></a></li>_x000D_
<li><a href="#">France<img class="flag" src="http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/fr.png" alt="" /><span class="value">FR</span></a></li>_x000D_
_x000D_
</ul>_x000D_
</dd>_x000D_
</dl>_x000D_
<span id="result"></span>
_x000D_
You can make:
$values = array_values($array);
echo $values[0];
This one is just extension of article you found.
public class WebClientEx : WebClient
{
public WebClientEx(CookieContainer container)
{
this.container = container;
}
public CookieContainer CookieContainer
{
get { return container; }
set { container= value; }
}
private CookieContainer container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest r = base.GetWebRequest(address);
var request = r as HttpWebRequest;
if (request != null)
{
request.CookieContainer = container;
}
return r;
}
protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
{
WebResponse response = base.GetWebResponse(request, result);
ReadCookies(response);
return response;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse response = base.GetWebResponse(request);
ReadCookies(response);
return response;
}
private void ReadCookies(WebResponse r)
{
var response = r as HttpWebResponse;
if (response != null)
{
CookieCollection cookies = response.Cookies;
container.Add(cookies);
}
}
}
How about writing out some HTML tags and some CSS if you're outputting this to the browser?
echo '<span style="color:#AFA;text-align:center;">Request has been sent. Please wait for my reply!</span>';
Won't work from console though, only through browser.
I implemented this a while back, to some extent. It is impossible to know whether or not a user has rated an app, to prevent ratings from becoming a currency (some developers might add an option like "Rate this app and get so and so in the app for free").
The class I wrote provides three buttons, and configures the dialog so that it is only shown after the app has been launched n
times (users have a higher chance of rating the app if they've used it a bit before. Most of them are unlikely to even know what it does on the first run):
public class AppRater {
private final static String APP_TITLE = "App Name";// App Name
private final static String APP_PNAME = "com.example.name";// Package Name
private final static int DAYS_UNTIL_PROMPT = 3;//Min number of days
private final static int LAUNCHES_UNTIL_PROMPT = 3;//Min number of launches
public static void app_launched(Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
if (prefs.getBoolean("dontshowagain", false)) { return ; }
SharedPreferences.Editor editor = prefs.edit();
// Increment launch counter
long launch_count = prefs.getLong("launch_count", 0) + 1;
editor.putLong("launch_count", launch_count);
// Get date of first launch
Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0);
if (date_firstLaunch == 0) {
date_firstLaunch = System.currentTimeMillis();
editor.putLong("date_firstlaunch", date_firstLaunch);
}
// Wait at least n days before opening
if (launch_count >= LAUNCHES_UNTIL_PROMPT) {
if (System.currentTimeMillis() >= date_firstLaunch +
(DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) {
showRateDialog(mContext, editor);
}
}
editor.commit();
}
public static void showRateDialog(final Context mContext, final SharedPreferences.Editor editor) {
final Dialog dialog = new Dialog(mContext);
dialog.setTitle("Rate " + APP_TITLE);
LinearLayout ll = new LinearLayout(mContext);
ll.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(mContext);
tv.setText("If you enjoy using " + APP_TITLE + ", please take a moment to rate it. Thanks for your support!");
tv.setWidth(240);
tv.setPadding(4, 0, 4, 10);
ll.addView(tv);
Button b1 = new Button(mContext);
b1.setText("Rate " + APP_TITLE);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME)));
dialog.dismiss();
}
});
ll.addView(b1);
Button b2 = new Button(mContext);
b2.setText("Remind me later");
b2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
ll.addView(b2);
Button b3 = new Button(mContext);
b3.setText("No, thanks");
b3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (editor != null) {
editor.putBoolean("dontshowagain", true);
editor.commit();
}
dialog.dismiss();
}
});
ll.addView(b3);
dialog.setContentView(ll);
dialog.show();
}
}
Integrating the class is as simple as adding:
AppRater.app_launched(this);
To your Activity. It only needs to be added to one Activity in the entire app.
How I would start emulation.
1.Get books based around low level programming, you'll need it for the "pretend" operating system of the Nintendo...game boy...
2.Get books on emulation specifically, and maybe os development. (you won't be making an os, but the closest to it.
3.look at some open source emulators, especially ones of the system you want to make an emulator for.
4.copy snippets of the more complex code into your IDE/compliler. This will save you writing out long code. This is what I do for os development, use a district of linux
Besides the most commonly known registry key for installed programs:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall
wmic command and the add/remove programs also query another registry key:
HKEY_CLASSES_ROOT\Installer\Products
Software name shown in the list is read from the Value of a Data entry within this key called: ProductName
Removing the registry key for a certain product from both of the above locations will keep it from showing in the add/remove programs list. This is not a method to uninstall programs, it will just remove the entry from what's known to windows as installed software.
Since, by using this method you would lose the chance of using the Remove button from the add/remove list to cleanly remove the software from your system; it's recommended to export registry keys to a file before you delete them. In future, if you decided to bring that item back to the list, you would simply run the registry file you stored.
One can use regular expressions, too:
var thingToTest = "B";_x000D_
if (/A|B/.test(thingToTest)) alert("Do something!")
_x000D_
Here's an example of regular expressions in general:
var myString = "This is my search subject"_x000D_
if (/my/.test(myString)) alert("Do something here!")
_x000D_
This will look for "my" within the variable "myString". You can substitute a string directly in place of the "myString" variable.
As an added bonus you can add the case insensitive "i" and the global "g" to the search as well.
var myString = "This is my search subject"_x000D_
if (/my/ig.test(myString)) alert("Do something here");
_x000D_
Yes. It is possible to draw text in pygame:
# initialize font; must be called after 'pygame.init()' to avoid 'Font not Initialized' error
myfont = pygame.font.SysFont("monospace", 15)
# render text
label = myfont.render("Some text!", 1, (255,255,0))
screen.blit(label, (100, 100))
ListaServizi = ListaServizi.OrderBy(q => q).ToList();
This error also may occur if you're trying to profile an app where the device is not included in the provisioning profile.
Make sure your device is included in the dev provisioning profile you want to use. Somehow the error message is misleading. My entitlements were actually ok.
You Just execute the following commands in your command prompt,
For 32 bit machine,
cd C:\Windows\System32
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb
For 64 bit machine,
cd C:\Windows\SysWOW64
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb
Here is a method, which does not use jQuery. I used it to create a bookmarklet, which checks the current page on w3-html-validator.
var f = document.createElement('form');
f.action='http://validator.w3.org/check';
f.method='POST';
f.target='_blank';
var i=document.createElement('input');
i.type='hidden';
i.name='fragment';
i.value='<!DOCTYPE html>'+document.documentElement.outerHTML;
f.appendChild(i);
document.body.appendChild(f);
f.submit();
If you use multiple node_modules
(yarn workspace etc), tell webpack where they are:
externals: [nodeExternals({
modulesDir: path.resolve(__dirname, '../node_modules'),
}), nodeExternals()],
var date1 = new Date("7/11/2010");
var date2 = new Date("8/11/2010");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24), 10);
alert(diffDays )
If you are using Vim, hit escape and then type
gg=G
This auto indents everything and will clear up any spaces you have thrown in.
I also had the same problem. In starting, it was working fine then, but sometime later I uninstalled my application completely from my device (I was running it on my mobile) and ran it again, and it shows me the same error.
I had all lib and resources included as it was working, but still I was getting this error so I removed all references and lib from my project build, updated google service play to revision 10, uninstalled application completely from the device and then again added all resources and libs and ran it and it started working again.
One thing to note here is while running I am still seeing this error message in my LogCat, but on my device it is working fine now.
var datatoday = new Date();
var datatodays = datatoday.setDate(new Date(datatoday).getDate() + 1);
todate = new Date(datatodays);
console.log(todate);
This will help you...
Use java.util.TreeSet
as the actual object. When you iterate over this collection, the values come back in a well-defined order.
If you use java.util.HashSet
then the order depends on an internal hash function which is almost certainly not lexicographic (based on content).
In config.inc.php
in the top-level directory, set
$cfg['DefaultLang'] = 'en-utf-8'; // Language if no other language is recognized
// or
$cfg['Lang'] = 'en-utf-8'; // Force this language for all users
If Lang
isn't set, you should be able to select the language in the initial welcome screen, and the language your browser prefers should be preselected there.
Download https://github.com/douglascrockford/JSON-js/blob/master/json2.js
, include it and do
var json_data = JSON.stringify(obj);
I believe this will solve the issue
var z = '[{"name":"1","age":"2"},{"name":"1","age":"3"}]';
z = JSON.stringify(JSON.parse(z));
$.ajax({
url: "/setTest",
data: z,
type: "POST",
dataType:"json",
contentType:'application/json'
});
Unfortunately, there is no good, portable way to do this that I know of. If you attempt to parse /etc/group, as others are suggesting, you will miss users who have that group as their primary group and anyone who has been added to that group via a mechanism other than UNIX flat files (i.e. LDAP, NIS, pam-pgsql, etc.).
If I absolutely had to do this myself, I'd probably do it in reverse: use id
to get the groups of every user on the system (which will pull all sources visible to NSS), and use Perl or something similar to maintain a hash table for each group discovered noting the membership of that user.
Edit: Of course, this leaves you with a similar problem: how to get a list of every user on the system. Since my location uses only flat files and LDAP, I can just get a list from both locations, but that may or may not be true for your environment.
Edit 2: Someone in passing reminded me that getent passwd
will return a list of all users on the system including ones from LDAP/NIS/etc., but getent group
still will still miss users that are members only via the default group entry, so that inspired me to write this quick hack.
#!/usr/bin/perl -T
#
# Lists members of all groups, or optionally just the group
# specified on the command line
#
# Copyright © 2010-2013 by Zed Pobre ([email protected] or [email protected])
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
use strict; use warnings;
$ENV{"PATH"} = "/usr/bin:/bin";
my $wantedgroup = shift;
my %groupmembers;
my $usertext = `getent passwd`;
my @users = $usertext =~ /^([a-zA-Z0-9_-]+):/gm;
foreach my $userid (@users)
{
my $usergrouptext = `id -Gn $userid`;
my @grouplist = split(' ',$usergrouptext);
foreach my $group (@grouplist)
{
$groupmembers{$group}->{$userid} = 1;
}
}
if($wantedgroup)
{
print_group_members($wantedgroup);
}
else
{
foreach my $group (sort keys %groupmembers)
{
print "Group ",$group," has the following members:\n";
print_group_members($group);
print "\n";
}
}
sub print_group_members
{
my ($group) = @_;
return unless $group;
foreach my $member (sort keys %{$groupmembers{$group}})
{
print $member,"\n";
}
}
Summary:
PagingAndSortingRepository extends CrudRepository
JpaRepository extends PagingAndSortingRepository
The CrudRepository interface provides methods for CRUD operations, so it allows you to create, read, update and delete records without having to define your own methods.
The PagingAndSortingRepository provides additional methods to retrieve entities using pagination and sorting.
Finally the JpaRepository add some more functionality that is specific to JPA.
Wanted to add my solution here as well. This is similar to Ravindu's answer above.
I added width: 'resolve',
as a property within the select2:
$('#searchFilter').select2({
width: 'resolve',
});
Then I added a min-width
property to select2-container
with !important
:
.select2-container {
min-width: 100% !important;
}
On the select element, the style='100px !important;'
attribute needed !important
to work:
<select class="form-control" style="width: 160px;" id="searchFilter" name="searchfilter[]">
URL url = new URL(yourUrl, "/api/v1/status.xml");
According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:
URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");
Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html
Technically, the Integrity attribute helps with just that - it enables the proper verification of the data source. That is, it merely allows the browser to verify the numbers in the right source file with the amounts requested by the source file located on the CDN server.
Going a bit deeper, in case of the established encrypted hash value of this source and its checked compliance with a predefined value in the browser - the code executes, and the user request is successfully processed.
Crossorigin attribute helps developers optimize the rates of CDN performance, at the same time, protecting the website code from malicious scripts.
In particular, Crossorigin downloads the program code of the site in anonymous mode, without downloading cookies or performing the authentication procedure. This way, it prevents the leak of user data when you first load the site on a specific CDN server, which network fraudsters can easily replace addresses.
Source: https://yon.fun/what-is-link-integrity-and-crossorigin/
With jQuery, you can try to call trigger:
$(window).trigger('resize');
Use port number 22 (for sftp) instead of 21 (normal ftp). Solved this problem for me.
When I look at this description, I have a feeling, that this xdr integer is just a big-endian "standard" integer, but it's expressed in the most obfuscated way. Two's complement notation is better know as U2, and it's what we are using on today's processors. The byte order indicates that it's a big-endian notation.
So, answering your question, you should inverse elements in your array (0 <--> 3, 1 <-->2), as they are encoded in little-endian. Just to make sure, you should first check BitConverter.IsLittleEndian
to see on what machine you are running.
This is probably considered dirty by some, but a very practical solution in case of github repositories is just to make a script, e.g. "git-ls":
#!/bin/sh
remote_url=${1:? "$0 requires URL as argument"}
curl -s $remote_url | grep js-directory-link | sed "s/.* title=\"\(.*\)\".*/\1/"
Make it executable and reachable of course: chmod a+x git-ls; sudo cp git-ls /usr/local/bin
. Now, you just run it as you wish:
git-ls https://github.com/mrquincle/aim-bzr
git-ls https://github.com/mrquincle/aim-bzr/tree/master/aim_modules
Also know that there is a git instaweb
utility for your local files. To have the ability to show files and have a server like that does in my opinion not destroy any of the inherent decentralized characteristics of git.
Yep, you can use border: 1px solid transparent
Another solution is to use outline
on hover (and set the border to 0) which doesn't affect the document flow:
li{
display:inline-block;
padding:5px;
border:0;
}
li:hover{
outline:1px solid #FC0;
}
NB. You can only set the outline as a sharthand property, not for individual sides. It's only meant to be used for debugging but it works nicely.
I was trying to add List to existing key in dictionary and reached the following solution:
Dictionary<string,List<string>> NewParent = new Dictionary<string,List<string>>();
child = new List<string> ();
child.Add('SomeData');
NewParent["item1"].AddRange(child);
It will not show any exception and won't replace previous values.
local_settings.py, for django projects.
*~ for all projects.
In Apache Maven 3.5.4, I had to add double quotation. Without double quotation it wasn't worked for me.
example: mvn install:install-file "-Dfile=location to the jar file" "-DgroupId=group id" "-DartifactId=artifact id" "-Dversion=version" "-Dpackaging=package type"
the following can be used:
install.packages("data.table")
library(data.table)
On Windows 2012 R2, you can't install Visual Studio or SDK. You can use powershell to register assemblies into GAC. It didn't need any special installation for me.
Set-location "C:\Temp"
[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$publish = New-Object System.EnterpriseServices.Internal.Publish
$publish.GacInstall("C:\Temp\myGacLibrary.dll")
If you need to get the name and PublicKeyToken see this question.
While you can't write macros, when it comes to simplifying things like your example, C# 6.0 now offers static usings. Here's the example Martin Pernica gave on his Medium article:
using static System.Console; // Note the static keyword
namespace CoolCSharp6Features
{
public class Program
{
public static int Main(string[] args)
{
WriteLine("Hellow World without Console class name prefix!");
return 0;
}
}
}
The properties that can be set for a figure
is referenced here.
You could then use:
figure_number = 1;
x = 0; % Screen position
y = 0; % Screen position
width = 600; % Width of figure
height = 400; % Height of figure (by default in pixels)
figure(figure_number, 'Position', [x y width height]);
An integer starting with 0 will cause fatal error as of PHP 7, because it might interpret it as an octal character.
Invalid octal literals
Previously, octal literals that contained invalid numbers were silently truncated (0128 was taken as 012). Now, an invalid octal literal will cause a parse error.
So you might want to remove leading zeros from your integer, first:
$var = ltrim($var, 0);
Added another case to Michal Górny's answer:
Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__
", modules intended for use as the main module of a Python application must always use absolute imports.
I'm assuming you figured this out already but:
Technical Reference for Log Files in Configuration Manager
That's a list of client-side logs and what they do. They are located in Windows\CCM\Logs
AppEnforce.log
will show you the actual command-line executed and the resulting exit code for each Deployment Type (only for the new style ConfigMgr Applications)
This is my go-to for troubleshooting apps. Haven't really found any other logs that are exceedingly useful.
I think this might work a little cleaner/better (though I haven't test it's performance):
String.prototype.stripAccents = function() {
var translate_re = /[àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ]/g;
var translate = 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY';
return (this.replace(translate_re, function(match){
return translate.substr(translate_re.source.indexOf(match)-1, 1); })
);
};
Or if you are still too worried about performance, let's get the best of both worlds:
String.prototype.stripAccents = function() {
var in_chrs = 'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ',
out_chrs = 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY',
transl = {};
eval('var chars_rgx = /['+in_chrs+']/g');
for(var i = 0; i < in_chrs.length; i++){ transl[in_chrs.charAt(i)] = out_chrs.charAt(i); }
return this.replace(chars_rgx, function(match){
return transl[match]; });
};
EDIT (by @Tomalak)
I appreciate the idea. However, there are several things wrong with the implementation, as outlined in the comment below.
Here is how I would implement it.
var stripAccents = (function () {
var in_chrs = 'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ',
out_chrs = 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY',
chars_rgx = new RegExp('[' + in_chrs + ']', 'g'),
transl = {}, i,
lookup = function (m) { return transl[m] || m; };
for (i=0; i<in_chrs.length; i++) {
transl[ in_chrs[i] ] = out_chrs[i];
}
return function (s) { return s.replace(chars_rgx, lookup); }
})();
Just a minor addition: if you add the -c
flag to ps, you don't need to remove the line containing the grep process with grep -v
afterwards. I.e.
ps acux | grep cron
is all the typing you'll need on a bsd-ish system (this includes MacOSX) You can leave the -u
away if you need less information.
On a system where the genetics of the native ps
command point back to SysV, you'd use
ps -e |grep cron
or
ps -el |grep cron
for a listing containing more than just pid and process name. Of course you could select the specific fields to print out using the -o <field,field,...>
option.
Code coverage has been explained well in the previous answers. So this is more of an answer to the second part of the question.
We've used three tools to determine code coverage.
We use these tools to
To get the value of a pointer, just de-reference the pointer.
int *ptr;
int value;
*ptr = 9;
value = *ptr;
value is now 9.
I suggest you read more about pointers, this is their base functionality.
you can use like this situation:
for example, you have a page: http://www.example.com/page.php
then in that page.php, insert this code:
if (!empty($_GET['doaction']) && $_GET['doaction'] == blabla ){
echo '<script>alert("hello");</script>';
}
then, whenever you visit this url: http://www.example.com/page.php?doaction=blabla
then the alert will be automatically called.
The volatile
keyword is used:
long
and double
. (all other, primitive accesses are already guaranteed to be atomic!)The java.util.concurrent.atomic.*
classes are, according to the java docs:
A small toolkit of classes that support lock-free thread-safe programming on single variables. In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form:
boolean compareAndSet(expectedValue, updateValue);
The atomic classes are built around the atomic compareAndSet(...)
function that maps to an atomic CPU instruction. The atomic classes introduce the happen-before ordering as the volatile
variables do. (with one exception: weakCompareAndSet(...)
).
From the java docs:
When a thread sees an update to an atomic variable caused by a weakCompareAndSet, it does not necessarily see updates to any other variables that occurred before the weakCompareAndSet.
To your question:
Does this mean that whosoever takes lock on it, that will be setting its value first. And in if meantime, some other thread comes up and read old value while first thread was changing its value, then doesn't new thread will read its old value?
You don't lock anything, what you are describing is a typical race condition that will happen eventually if threads access shared data without proper synchronization. As already mentioned declaring a variable volatile
in this case will only ensure that other threads will see the change of the variable (the value will not be cached in a register of some cache that is only seen by one thread).
What is the difference between
AtomicInteger
andvolatile int
?
AtomicInteger
provides atomic operations on an int
with proper synchronization (eg. incrementAndGet()
, getAndAdd(...)
, ...), volatile int
will just ensure the visibility of the int
to other threads.
// iterate over the map
for(Entry<String, ArrayList<String>> entry : test1.entrySet()){
// iterate over each entry
for(String item : entry.getValue()){
// print the map's key with each value in the ArrayList
System.out.println(entry.getKey() + ": " + item);
}
}
Tested in Android Studio 0.8.14:
I was able to get a standard project running with minimal steps in this way:
You can then add your code, and choose Build > Run 'YourClassName'. Presto, your code is running with no Android device!
BigDecimal decPrec = (BigDecimal)yo.get("Avg");
decPrec = decPrec.setScale(5, RoundingMode.CEILING);
String value= String.valueOf(decPrec);
This way you can set specific precision of a BigDecimal
.
The value of decPrec was 1.5726903423607562595809913132345426
which is rounded off to 1.57267
.
Unless you're trying to upload the file using ajax, just submit the form to /upload/image
.
<form enctype="multipart/form-data" action="/upload/image" method="post">
<input id="image-file" type="file" />
</form>
If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:
time.monotonic() (basically your computer's uptime in seconds) is guarranteed to not misbehave when your computer's clock is adjusted (such as when transitioning to/from daylight saving time).
>>> import time
>>>
>>> time.monotonic()
452782.067158593
>>>
>>> a = time.monotonic()
>>> time.sleep(1)
>>> b = time.monotonic()
>>> print(b-a)
1.001658110995777
Use the SingleOrDefault() instead of FirstOrDefault().
Make sure all services windows are closed before starting install/uninstall
You can put an apostrophe in a single quoted JavaScript string by escaping it with a backslash, like so:
theAnchorText = 'I\'m home';
This is a really old question, and thus, has many outdated answers. As of 2020 all major browsers have adhered to the standard.
Answer for 2020:
document.body.scrollHeight
Edit: the above doesn't take margins on the <body>
tag into account. If your body has margins, use:
document.documentElement.scrollHeight
In the .service file under the [Unit] section:
[Unit]
Description=My Website
After=syslog.target network.target mongodb.service
The important part is the mongodb.service
The manpage describes it however due to formatting it's not as clear on first sight
I was looking for a way to get the event type when jQuery listens for several events at once, and Google put me here.
So, for those interested, event.type
is my answer :
$('#element').on('keyup keypress blur change', function(event) {
alert(event.type); // keyup OR keypress OR blur OR change
});
More info in the jQuery doc.
I prefer to use the ngModel and ngChange directives when dealing with checkboxes. ngModel allows you to bind the checked/unchecked state of the checkbox to a property on the entity:
<input type="checkbox" ng-model="entity.isChecked">
Whenever the user checks or unchecks the checkbox the entity.isChecked
value will change too.
If this is all you need then you don't even need the ngClick or ngChange directives. Since you have the "Check All" checkbox, you obviously need to do more than just set the value of the property when someone checks a checkbox.
When using ngModel with a checkbox, it's best to use ngChange rather than ngClick for handling checked and unchecked events. ngChange is made for just this kind of scenario. It makes use of the ngModelController for data-binding (it adds a listener to the ngModelController's $viewChangeListeners
array. The listeners in this array get called after the model value has been set, avoiding this problem).
<input type="checkbox" ng-model="entity.isChecked" ng-change="selectEntity()">
... and in the controller ...
var model = {};
$scope.model = model;
// This property is bound to the checkbox in the table header
model.allItemsSelected = false;
// Fired when an entity in the table is checked
$scope.selectEntity = function () {
// If any entity is not checked, then uncheck the "allItemsSelected" checkbox
for (var i = 0; i < model.entities.length; i++) {
if (!model.entities[i].isChecked) {
model.allItemsSelected = false;
return;
}
}
// ... otherwise ensure that the "allItemsSelected" checkbox is checked
model.allItemsSelected = true;
};
Similarly, the "Check All" checkbox in the header:
<th>
<input type="checkbox" ng-model="model.allItemsSelected" ng-change="selectAll()">
</th>
... and ...
// Fired when the checkbox in the table header is checked
$scope.selectAll = function () {
// Loop through all the entities and set their isChecked property
for (var i = 0; i < model.entities.length; i++) {
model.entities[i].isChecked = model.allItemsSelected;
}
};
CSS
What is the best way to... add a CSS class to the
<tr>
containing the entity to reflect its selected state?
If you use the ngModel approach for the data-binding, all you need to do is add the ngClass directive to the <tr>
element to dynamically add or remove the class whenever the entity property changes:
<tr ng-repeat="entity in model.entities" ng-class="{selected: entity.isChecked}">
See the full Plunker here.
if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
"nd"
else
totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')
The above logic should be what you are looking for.
As it may happens that the default branch of your submodules are not master
(which happens a lot in my case), this is how I automate the full Git submodules upgrades:
git submodule init
git submodule update
git submodule foreach 'git fetch origin; git checkout $(git rev-parse --abbrev-ref HEAD); git reset --hard origin/$(git rev-parse --abbrev-ref HEAD); git submodule update --recursive; git clean -dfx'
For those of you who have tried all the above mentioned methods including Windows system env. variables, .bashrc, .bashprofile, etc. AND can see the correct path in 'echo $PATH' ... I may have a solution for you.
suppress the errors using exec 2> /dev/null
My script runs fine but was throwing 'command not found' or 'No directory found' errors even though, as far as I can tell, the paths were flush. So, if you suppress those errors (might have to also add 'set +e'), than it works properly.
Here's a mmap example:
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
/*
* pvtmMmapAlloc - creates a memory mapped file area.
* The return value is a page-aligned memory value, or NULL if there is a failure.
* Here's the list of arguments:
* @mmapFileName - the name of the memory mapped file
* @size - the size of the memory mapped file (should be a multiple of the system page for best performance)
* @create - determines whether or not the area should be created.
*/
void* pvtmMmapAlloc (char * mmapFileName, size_t size, char create)
{
void * retv = NULL;
if (create)
{
mode_t origMask = umask(0);
int mmapFd = open(mmapFileName, O_CREAT|O_RDWR, 00666);
umask(origMask);
if (mmapFd < 0)
{
perror("open mmapFd failed");
return NULL;
}
if ((ftruncate(mmapFd, size) == 0))
{
int result = lseek(mmapFd, size - 1, SEEK_SET);
if (result == -1)
{
perror("lseek mmapFd failed");
close(mmapFd);
return NULL;
}
/* Something needs to be written at the end of the file to
* have the file actually have the new size.
* Just writing an empty string at the current file position will do.
* Note:
* - The current position in the file is at the end of the stretched
* file due to the call to lseek().
* - The current position in the file is at the end of the stretched
* file due to the call to lseek().
* - An empty string is actually a single '\0' character, so a zero-byte
* will be written at the last byte of the file.
*/
result = write(mmapFd, "", 1);
if (result != 1)
{
perror("write mmapFd failed");
close(mmapFd);
return NULL;
}
retv = mmap(NULL, size,
PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);
if (retv == MAP_FAILED || retv == NULL)
{
perror("mmap");
close(mmapFd);
return NULL;
}
}
}
else
{
int mmapFd = open(mmapFileName, O_RDWR, 00666);
if (mmapFd < 0)
{
return NULL;
}
int result = lseek(mmapFd, 0, SEEK_END);
if (result == -1)
{
perror("lseek mmapFd failed");
close(mmapFd);
return NULL;
}
if (result == 0)
{
perror("The file has 0 bytes");
close(mmapFd);
return NULL;
}
retv = mmap(NULL, size,
PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);
if (retv == MAP_FAILED || retv == NULL)
{
perror("mmap");
close(mmapFd);
return NULL;
}
close(mmapFd);
}
return retv;
}
According to the article Chris Corio: Teach Your Apps To Play Nicely With Windows Vista User Account Control, MSDN Magazine, Jan. 2007, only ShellExecute
checks the embedded manifest and prompts the user for elevation if needed, while CreateProcess
and other APIs don't. Hope it helps.
See also: same article as .chm.
Linux manual said:
EPIPE The local end has been shut down on a connection oriented socket. In this case the process will also receive a SIGPIPE unless MSG_NOSIGNAL is set.
But for Ubuntu 12.04 it isn't right. I wrote a test for that case and I always receive EPIPE withot SIGPIPE. SIGPIPE is genereated if I try to write to the same broken socket second time. So you don't need to ignore SIGPIPE if this signal happens it means logic error in your program.
<form id="uploadbanner" enctype="multipart/form-data" method="post" action="#">
<input id="fileupload" name="myfile" type="file" />
<input type="submit" value="submit" id="submit" />
</form>
To upload a file, it is essential to set enctype="multipart/form-data"
on your form
You need that form type and then some php to process the file :)
You should probably check out Uploadify if you want something very customisable out of the box.
I think throw a new error is good approach to stop execution rather than just return or return false. For ex. I am validating a number of files that I only allow max five files for upload in separate function.
validateMaxNumber: function(length) {
if (5 >= length) {
// Continue execution
}
// Flash error message and stop execution
// Can't stop execution by return or return false statement;
let message = "No more than " + this.maxNumber + " File is allowed";
throw new Error(message);
}
But I am calling this function from main flow function as
handleFilesUpload() {
let files = document.getElementById("myFile").files;
this.validateMaxNumber(files.length);
}
In the above example I can't stop execution unless I throw new Error.Just return or return false only works if you are in main function of execution otherwise it doesn't work.
A cleaner approach in ES6 is the following solution.
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
a2.filter(d => !a1.includes(d)) // gives ["c", "d"]
a2.filter(d => a1.includes(d)) // gives ["a", "b"]
[ ...a2.filter(d => !a1.includes(d)),
...a1.filter(d => !a2.includes(d)) ]
I thought I'd add another perspective here. The answer depends on whether the question is assuming weak scaling or strong scaling.
From Wikipedia:
Weak scaling: how the solution time varies with the number of processors for a fixed problem size per processor.
Strong scaling: how the solution time varies with the number of processors for a fixed total problem size.
If the question is assuming weak scaling then @Gonzalo's answer suffices. However if the question is assuming strong scaling, there's something more to add. In strong scaling you're assuming a fixed workload size so if you increase the number of threads, the size of the data that each thread needs to work on decreases. On modern CPUs memory accesses are expensive and would be preferable to maintain locality by keeping the data in caches. Therefore, the likely optimal number of threads can be found when the dataset of each thread fits in each core's cache (I'm not going into the details of discussing whether it's L1/L2/L3 cache(s) of the system).
This holds true even when the number of threads exceeds the number of cores. For example assume there's 8 arbitrary unit (or AU) of work in the program which will be executed on a 4 core machine.
Case 1: run with four threads where each thread needs to complete 2AU. Each thread takes 10s to complete (with a lot of cache misses). With four cores the total amount of time will be 10s (10s * 4 threads / 4 cores).
Case 2: run with eight threads where each thread needs to complete 1AU. Each thread takes only 2s (instead of 5s because of the reduced amount of cache misses). With four cores the total amount of time will be 4s (2s * 8 threads / 4 cores).
I've simplified the problem and ignored overheads mentioned in other answers (e.g., context switches) but hope you get the point that it might be beneficial to have more number of threads than the available number of cores, depending on the data size you're dealing with.
Static methods use the class as the object for locking, which is Utils.class for your example. So yes, it is OK.
Old question, but if you want to do locale-aware sorting without setting locale.LC_ALL
you can do so by using the PyICU library as suggested by this answer:
import icu # PyICU
def sorted_strings(strings, locale=None):
if locale is None:
return sorted(strings)
collator = icu.Collator.createInstance(icu.Locale(locale))
return sorted(strings, key=collator.getSortKey)
Then call with e.g.:
new_list = sorted_strings(list_of_strings, "de_DE.utf8")
This worked for me without installing any locales or changing other system settings.
(This was already suggested in a comment above, but I wanted to give it more prominence, because I missed it myself at first.)
Logger log = Logger.getLogger("myApp");
log.setLevel(Level.ALL);
log.info("initializing - trying to load configuration file ...");
//Properties preferences = new Properties();
try {
//FileInputStream configFile = new //FileInputStream("/path/to/app.properties");
//preferences.load(configFile);
InputStream configFile = myApp.class.getResourceAsStream("app.properties");
LogManager.getLogManager().readConfiguration(configFile);
} catch (IOException ex)
{
System.out.println("WARNING: Could not open configuration file");
System.out.println("WARNING: Logging not configured (console output only)");
}
log.info("starting myApp");
this is working..:) you have to pass InputStream in readConfiguration().
DateTime? MyDateTime{get;set;}
MyDateTime = (dr["f1"] == DBNull.Value) ? (DateTime?)null : ((DateTime)dr["f1"]);
You may call U.difference(lists)
method in underscore-java library. I am the maintainer of the project. Live example
import com.github.underscore.U;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(1, 2);
List<Integer> list3 = U.difference(list1, list2);
System.out.println(list3);
// [3]
}
}
I had this problem also. The issue was because I was running an old version of PHP (5.6) and once I upgraded to PHP 7.4 the errors went away.
This was on Amazon Linux 2 for me and the command to upgrade was:
amazon-linux-extras install php7.4
Other flavors of *nix might have it in their repositories otherwise if you're on a flavor of Linux then Remi might have it for you here: https://rpms.remirepo.net/
this works wonders - no its turn to call this procedure form code with DataTable with schema exactly matching the custType create table customer ( id int identity(1,1) primary key, name varchar(50), cnt varchar(10) )
create type custType as table
(
ctId int,
ctName varchar(20)
)
insert into customer values('y1', 'c1')
insert into customer values('y2', 'c2')
insert into customer values('y3', 'c3')
insert into customer values('y4', 'c4')
insert into customer values('y5', 'c5')
declare @ct as custType
insert @ct (ctid, ctName) values(3, 'y33'), (4, 'y44')
exec multiUpdate @ct
create Proc multiUpdate (@ct custType readonly) as begin
update customer set Name = t.ctName from @ct t where t.ctId = customer.id
end
public DataTable UpdateLevels(DataTable dt)
{
DataTable dtRet = new DataTable();
using (SqlConnection con = new SqlConnection(datalayer.bimCS))
{
SqlCommand command = new SqlCommand();
command.CommandText = "UpdateLevels";
command.Parameters.Clear();
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@ct", dt).SqlDbType = SqlDbType.Structured;
command.Connection = con;
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{
dataAdapter.SelectCommand = command;
dataAdapter.Fill(dtRet);
}
}
}
What the browser does when you've got
<a onclick="alert('Hi');" ... >
is to set the actual value of "onclick" to something effectively like:
new Function("event", "alert('Hi');");
That is, it creates a function that expects an "event" parameter. (Well, IE doesn't; it's more like a plain simple anonymous function.)
Go to command prompt and enter the command,
net user <username>
Will show your local group memberships.
If you're on a domain, use localgroup instead:
net localgroup Administrators or net localgroup [Admin group name]
Check the list of local groups with localgroup on its own.
net localgroup
Using TortoiseSVN worked easily on Windows for me.
Right click file -> TortoiseSVN menu -> Repo-browser -> right click file in repository -> rename -> press Enter -> click Ok
Using SVN 1.8.8 TortoiseSVN version 1.8.5
Starting in NumPy version 1.10, we have the method stack. It can stack arrays of any dimension (all equal):
# List of arrays.
L = [np.random.randn(5,4,2,5,1,2) for i in range(10)]
# Stack them using axis=0.
M = np.stack(L)
M.shape # == (10,5,4,2,5,1,2)
np.all(M == L) # == True
M = np.stack(L, axis=1)
M.shape # == (5,10,4,2,5,1,2)
np.all(M == L) # == False (Don't Panic)
# This are all true
np.all(M[:,0,:] == L[0]) # == True
all(np.all(M[:,i,:] == L[i]) for i in range(10)) # == True
Enjoy,
The first option's text will always display as default title.
<select>
<option value ="">What is the name of your city?</option>
<option value ="sydney">Sydney</option>
<option value ="melbourne">Melbourne</option>
<option value ="cromwell">Cromwell</option>
<option value ="queenstown">Queenstown</option>
</select>
import pandas as pd
header=['a','b','v']
df=pd.DataFrame(columns=header)
for i in range(len(doc_list)):
d_id=(test_data.filenames[i]).split('\\')
doc_id.append(d_id[len(d_id)-1])
df['a']=doc_id
print(df.head())
df[column_names_to_be_updated]=np.asanyarray(data)
print(df.head())
df.to_csv('output.csv')
Using pandas dataframe,we can write to csv. First create a dataframe as per the your needs for storing in csv. Then create csv of the dataframe using pd.DataFrame.to_csv() API.
If you used...
$(function(){
function myFunc() {
// ... do something ...
};
$('#saveBtn').click(myFunc);
});
... then it will be easier to unbind later.
I display images in windows forms when I put it in Load event like this:
private void Form1_Load( object sender , EventArgs e )
{
pictureBox1.ImageLocation = "./image.png"; //path to image
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
}
In Spark 2.4
To compare with one value:
df.filter(lower(trim($"col_name")) === "<value>").show()
To compare with collection of value:
df.filter($"col_name".isInCollection(new HashSet<>(Arrays.asList("value1", "value2")))).show()
Just add the line below to the <TextInput>
secureTextEntry={true}
So my question is: Is there a way to tell the compiler that a long long int is the also a int64_t, just like long int is?
This is a good question or problem, but I suspect the answer is NO.
Also, a long int
may not be a long long int
.
# if __WORDSIZE == 64 typedef long int int64_t; # else __extension__ typedef long long int int64_t; # endif
I believe this is libc. I suspect you want to go deeper.
In both 32-bit compile with GCC (and with 32- and 64-bit MSVC), the output of the program will be:
int: 0 int64_t: 1 long int: 0 long long int: 1
32-bit Linux uses the ILP32 data model. Integers, longs and pointers are 32-bit. The 64-bit type is a long long
.
Microsoft documents the ranges at Data Type Ranges. The say the long long
is equivalent to __int64
.
However, the program resulting from a 64-bit GCC compile will output:
int: 0 int64_t: 1 long int: 1 long long int: 0
64-bit Linux uses the LP64
data model. Longs are 64-bit and long long
are 64-bit. As with 32-bit, Microsoft documents the ranges at Data Type Ranges and long long is still __int64
.
There's a ILP64
data model where everything is 64-bit. You have to do some extra work to get a definition for your word32
type. Also see papers like 64-Bit Programming Models: Why LP64?
But this is horribly hackish and does not scale well (actual functions of substance, uint64_t, etc)...
Yeah, it gets even better. GCC mixes and matches declarations that are supposed to take 64 bit types, so its easy to get into trouble even though you follow a particular data model. For example, the following causes a compile error and tells you to use -fpermissive
:
#if __LP64__
typedef unsigned long word64;
#else
typedef unsigned long long word64;
#endif
// intel definition of rdrand64_step (http://software.intel.com/en-us/node/523864)
// extern int _rdrand64_step(unsigned __int64 *random_val);
// Try it:
word64 val;
int res = rdrand64_step(&val);
It results in:
error: invalid conversion from `word64* {aka long unsigned int*}' to `long long unsigned int*'
So, ignore LP64
and change it to:
typedef unsigned long long word64;
Then, wander over to a 64-bit ARM IoT gadget that defines LP64
and use NEON:
error: invalid conversion from `word64* {aka long long unsigned int*}' to `uint64_t*'
If you are producing the entire output yourself, you can use sprintf()
, e.g.
> sprintf("%.10f",0.25)
[1] "0.2500000000"
specifies that you want to format a floating point number with ten decimal points (in %.10f
the f
is for float and the .10
specifies ten decimal points).
I don't know of any way of forcing R's higher level functions to print an exact number of digits.
Displaying 100 digits does not make sense if you are printing R's usual numbers, since the best accuracy you can get using 64-bit doubles is around 16 decimal digits (look at .Machine$double.eps on your system). The remaining digits will just be junk.
DSM's solution works, but if you wanted a direct equivalent to which
you could do (df.columns == name).nonzero()
Here's an option using a JQuery extension I made based on the code by waspinator in the comments of the accepted answer:
jQuery.fn.extend({
printElem: function() {
var cloned = this.clone();
var printSection = $('#printSection');
if (printSection.length == 0) {
printSection = $('<div id="printSection"></div>')
$('body').append(printSection);
}
printSection.append(cloned);
var toggleBody = $('body *:visible');
toggleBody.hide();
$('#printSection, #printSection *').show();
window.print();
printSection.remove();
toggleBody.show();
}
});
$(document).ready(function(){
$(document).on('click', '#btnPrint', function(){
$('.printMe').printElem();
});
});
JSFiddle: http://jsfiddle.net/95ezN/1227/
This can be useful if you don't want to have this applied to every single print and just do it on your custom print button (which was my case).
See also a lot of general hints and useful links at the regex tag details page.
Online tutorials
Quantifiers
*
:greedy, *?
:reluctant, *+
:possessive+
:greedy, +?
:reluctant, ++
:possessive?
:optional (zero-or-one){n,m}
:between n & m, {n,}
:n-or-more, {n}
:exactly n{n}
and {n}?
Character Classes
[...]
: any one character, [^...]
: negated/any character but[^]
matches any one character including newlines javascript[\w-[\d]]
/ [a-z-[qz]]
: set subtraction .net, xml-schema, xpath, JGSoft[\w&&[^\d]]
: set intersection java, ruby 1.9+[[:alpha:]]
:POSIX character classes[^\\D2]
, [^[^0-9]2]
, [^2[^0-9]]
get different results in Java? java\d
:digit, \D
:non-digit\w
:word character, \W
:non-word character\s
:whitespace, \S
:non-whitespace\p{L}, \P{L}
, etc.)Escape Sequences
\h
:space-or-tab, \t
:tab\H
:Non horizontal whitespace character, \V
:Non vertical whitespace character, \N
:Non line feed character pcre php5 java-8\v
:vertical tab, \e
:the escape characterAnchors
^
:start of line/input, \b
:word boundary, and \B
:non-word boundary, $
:end of line/input\A
:start of input, \Z
:end of input php, perl, ruby\z
:the very end of input (\Z
in Python) .net, php, pcre, java, ruby, icu, swift, objective-c\G
:start of match php, perl, ruby(Also see "Flavor-Specific Information ? Java ? The functions in Matcher
")
Groups
(...)
:capture group, (?:)
:non-capture group
\1
:backreference and capture-group reference, $1
:capture group reference
(?i:regex)
mean?(?P<group_name>regexp)
mean?(?>)
:atomic group or independent group, (?|)
:branch reset
regular-expressions.info
(?<groupname>regex)
: Overview and naming rules (Non-Stack Overflow links)(?P<groupname>regex)
python, (?<groupname>regex)
.net, (?<groupname>regex)
perl, (?P<groupname>regex)
and (?<groupname>regex)
phpLookarounds
(?=...)
:positive, (?!...)
:negative(?<=...)
:positive, (?<!...)
:negative (not supported by javascript)Modifiers
flag | modifier | flavors |
---|---|---|
c |
current position | perl |
e |
expression | php perl |
g |
global | most |
i |
case-insensitive | most |
m |
multiline | php perl python javascript .net java |
m |
(non)multiline | ruby |
o |
once | perl ruby |
S |
study | php |
s |
single line | unsupported: javascript (workaround) | ruby |
U |
ungreedy | php r |
u |
unicode | most |
x |
whitespace-extended | most |
y |
sticky ? | javascript |
Other:
|
:alternation (OR) operator, .
:any character, [.]
:literal dot character(*PRUNE)
, (*SKIP)
, (*FAIL)
and (*F)
(*BSR_ANYCRLF)
(?R)
, (?0)
and (?1)
, (?-1)
, (?&groupname)
Common Tasks
{...}
Advanced Regex-Fu
(?!a)a
this
except in contexts A, B and CFlavor-Specific Information
(Except for those marked with *
, this section contains non-Stack Overflow links.)
java.util.regex.Matcher
:
matches()
): The match must be anchored to both input-start and -endfind()
): A match may be anywhere in the input string (substrings)lookingAt()
: The match must be anchored to input-start onlyjava.lang.String
functions that accept regular expressions: matches(s)
, replaceAll(s,s)
, replaceFirst(s,s)
, split(s)
, split(s,i)
java.util.regex
preg_match
search
vs match
, how-toregex
, struct regex::Regex
regexp
commandGeneral information
(Links marked with *
are non-Stack Overflow links.)
Examples of regex that can cause regex engine to fail
Tools: Testers and Explainers
(This section contains non-Stack Overflow links.)
switch(this.dealer) {
case 1:
case 2:
case 3:
case 4:
// Do something.
break;
case 5:
case 6:
case 7:
case 8:
// Do something.
break;
default:
break;
}
If you don't like the succession of cases, simply go for if/else if/else
statements.
Try this:
function btnClick() {
var x = document.getElementById("mytable").getElementsByTagName("td");
x[0].innerHTML = "i want to change my cell color";
x[0].style.backgroundColor = "yellow";
}
Set from JS, backgroundColor
is the equivalent of background-color
in your style-sheet.
Note also that the .cells
collection belongs to a table row, not to the table itself. To get all the cells from all rows you can instead use getElementsByTagName()
.
In addition to kus answer.
There are some changes in Xcode 8.0
Step 1:
Change scheme destination to Generic IOS device
.
Step 2:
Click Product
> Archive
> once this is complete open up the Organiser and click the latest version.
Step 3:
Click on Export...
option from right side of organiser window.
Step 4: Select a method for export > Choose correct signing > Save to Destination.
Xcode 10.0
Step 3: From Right Side Panel Click on Distribute App.
Step 4: Select Method of distribution and click next.
Step 5: It Opens up distribution option window. Select All compatible device variants and click next.
Step 6: Choose signing certificate.
Step 7: It will open up Preparing archive for distribution window. it takes few min.
Step 8: It will open up Archives window. Click on export and save it.
The easiest would be to locate the bootstrap file (bootstrap.css OR bootstrap.min.css) and read through the docblock, you'll see something like this
Bootstrap v3.3.6 (http://getbootstrap.com)
Maybe you should try it with -quality 100 -size "1024x1024", because resize often gives results that are ugly to view.
You need use patches.
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig2 = plt.figure()
ax2 = fig2.add_subplot(111, aspect='equal')
ax2.add_patch(
patches.Rectangle(
(0.1, 0.1),
0.5,
0.5,
fill=False # remove background
) )
fig2.savefig('rect2.png', dpi=90, bbox_inches='tight')
As mentioned earlier, you can use the grid system to layout your inputs and labels anyway that you want. The trick is to remember that you can use rows within your columns to break them into twelfths as well.
The example below is one possible way to accomplish your goal and will put the two text boxes near Label3 on the same line when the screen is small or larger.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->_x000D_
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
<!--[if lt IE 9]>_x000D_
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>_x000D_
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>_x000D_
<![endif]-->_x000D_
</head>_x000D_
<body>_x000D_
<div class="row">_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label1</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label2</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-6">_x000D_
<div class="row">_x000D_
<label class="col-xs-12">Label3</label>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-xs-12 col-sm-6">_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
<div class="col-xs-12 col-sm-6">_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-xs-6 form-group">_x000D_
<label>Label4</label>_x000D_
<input class="form-control" type="text"/>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
</body>_x000D_
</html>
_x000D_
Redirection of program output is performed by the shell.
grep ... > output.txt
grep
has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1)
man page for details, specifically the -C
and --color
options.
Simply type "node NodeJsProject/app.js"
Your program will run :)
To remove the variable from the current command session without removing it permanently, use the regular built-in set
command - just put nothing after the equals sign:
set FOOBAR=
To confirm, run set
with no arguments and check the current environment. The variable should be missing from the list entirely.
Note: this will only remove the variable from the current environment - it will not persist the change to the registry. When a new command process is started, the variable will be back.
You can use float on that particular div, e.g.
<div style="float:right;">
Float the div you want more space to have to the left as well:
<div style="float:left;">
If all else fails give the div on the right position:absolute and then move it as right as you want it to be.
<div style="position:absolute; left:-500px; top:30px;">
etc. Obviously put the style in a seperate stylesheet but this is just a quicker example.
Just to be sure that this is really the "conversion" you need, please note that jks
files are keystores, a file format used to store more than one certificate and allows you to retrieve them programmatically using the Java security API, it's not a one-to-one conversion between equivalent formats.
So, if you just want to import that certificate in a new ad-hoc keystore you can do it with Keystore Explorer, a graphical tool. You'll be able to modify the keystore and the certificates contained therein like you would have done with the java terminal utilities like keytool
(but in a more accessible way).