I had to make the entry in the [project].vs\config\applicationhost.config file.
Prior to this, it worked from deployment but not from code.
You can use this aproach:
Response.Clear();
StringBuilder sb = new StringBuilder();
sb.Append("<html>");
sb.AppendFormat(@"<body onload='document.forms[""form""].submit()'>");
sb.AppendFormat("<form name='form' action='{0}' method='post'>",postbackUrl);
sb.AppendFormat("<input type='hidden' name='id' value='{0}'>", id);
// Other params go here
sb.Append("</form>");
sb.Append("</body>");
sb.Append("</html>");
Response.Write(sb.ToString());
Response.End();
As result right after client will get all html from server the event onload take place that triggers form submit and post all data to defined postbackUrl.
This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....
To cover the identities listed:
IIS_IUSRS:
This is analogous to the old IIS6 IIS_WPG
group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.
IUSR:
This account is analogous to the old IUSR_<MACHINE_NAME>
local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).
For more information about IIS_IUSRS
and IUSR
see:
DefaultAppPool:
If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name>
will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool
created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>
. You also won't see these pool accounts in your computers User Manager. See the following for more information:
ASP.NET v4.0:
-
This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool
above.
NETWORK SERVICE:
-
The NETWORK SERVICE
account is a built-in identity introduced on Windows 2003. NETWORK SERVICE
is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).
In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE
). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" />
setting in web.config
file locally (if that setting is locked then it would need to be done by an admin in the machine.config
file).
Setting <identity impersonate="true">
is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).
In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR
or a specific custom anonymous account.
LOCAL SERVICE:
The LOCAL SERVICE
account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:
LOCAL SYSTEM:
You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.
In Practice:
In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity
. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity
:
In the website you should then configure the Authentication feature:
Right click and edit the Anonymous Authentication entry:
Ensure that "Application pool identity" is selected:
When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0
pool permissions then you can either do this via Explorer:
Click the "Check Names" button:
Or you can do this using the ICACLS.EXE
utility:
icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)
...or...if you site's application pool is called BobsCatPicBlog
then:
icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)
I hope this helps clear things up.
Update:
I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:
The difference between the 'Local System' account and the 'Network Service' account?
You can install nano in powershell via choco - It's a low friction way to get text editing capabilities into powershell:
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
choco install nano
nano myfile.txt
Best part is it becomes part of the path, and stays working across reboots etc :)
Are you looking for the code to do it or understanding the algorithm?
Does this do what you need? Specifically a2b_uu
and b2a_uu
? There are LOTS of other options in there in case those aren't what you want.
(NOTE: Not a Python guy but this seemed like an obvious answer)
Thanks everybody for your help. Piecing together what I found here and elsewhere I came up with this:
command="php $INSTALL/indefero/scripts/gitcron.php"
job="0 0 * * 0 $command"
cat <(fgrep -i -v "$command" <(crontab -l)) <(echo "$job") | crontab -
I couldn't figure out how to eliminate the need for the two variables without repeating myself.
command
is obviously the command I want to schedule. job
takes $command
and adds the scheduling data. I needed both variables separately in the line of code that does the work.
<(*command*)
) to turn the output of crontab -l
into input for the fgrep
command.fgrep
then filters out any matches of $command
(-v
option), case-insensitive (-i
option).<(*command*)
) is used to turn the result back into input for the cat
command.cat
command also receives echo "$job"
(self explanatory), again, through use of the redirect thingy (<(*command*)
).crontab -l
and the simple echo "$job"
, combined, are piped ('|') over to crontab -
to finally be written.This line of code filters out any cron jobs that match the command, then writes out the remaining cron jobs with the new one, effectively acting like an "add" or "update" function.
To use this, all you have to do is swap out the values for the command
and job
variables.
I had the same problem, however all popular answers - to change .tooltip-inner{width}
for my task failed to do the job right. As for other (i.e. shorter) tooltips fixed width was too big. I was lazy to write separate html templates/classes for zilions of tooltips, so I just replaced all spaces between words with
in each text line.
You will need Javascript to do this:
HTML
<input id="datefield" type='date' min='1899-01-01' max='2000-13-13'></input>
JS
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
today = yyyy+'-'+mm+'-'+dd;
document.getElementById("datefield").setAttribute("max", today);
The openssl
documentation says that file supplied as the -in
argument must be in PEM format.
Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer
is not PEM format rather it is PKCS7.
In order to create my .p12
, I had to first convert the certificate to PEM:
openssl pkcs7 -in myCert.cer -print_certs -out certs.pem
and then execute
openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem
php_value memory_limit 30M
php_value post_max_size 100M
php_value upload_max_filesize 30M
Use all 3 in .htaccess
after everything at last line. php_value post_max_size
must be more than than the remaining two.
I found a way to do it without replacing the slashes
select CONVERT(VARCHAR(10), GETDATE(), 112)
This would return: "YYYYMMDD"
I use the Description
attribute from the System.ComponentModel namespace. Simply decorate the enum:
private enum PublishStatusValue
{
[Description("Not Completed")]
NotCompleted,
Completed,
Error
};
Then use this code to retrieve it:
public static string GetDescription<T>(this T enumerationValue)
where T : struct
{
Type type = enumerationValue.GetType();
if (!type.IsEnum)
{
throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
}
//Tries to find a DescriptionAttribute for a potential friendly name
//for the enum
MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
if (memberInfo != null && memberInfo.Length > 0)
{
object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
{
//Pull out the description value
return ((DescriptionAttribute)attrs[0]).Description;
}
}
//If we have no description attribute, just return the ToString of the enum
return enumerationValue.ToString();
}
Your website folder needs network service security. Especially the web.config. It uses this account to access your registry for the certificates. This will stop the need to add a hack to your code.
Those won't necessarily give the same result: find()
will get you any descendant node, whereas children()
will only get you immediate children that match.
At one point, find()
was a lot slower since it had to search for every descendant node that could be a match, and not just immediate children. However, this is no longer true; find()
is much quicker due to using native browser methods.
Write the code using ASyncTask
for http handling.
Bitmap b;
ImageView img;
......
try
{
URL url = new URL("http://10.119.120.10:80/img.jpg");
InputStream is = new BufferedInputStream(url.openStream());
b = BitmapFactory.decodeStream(is);
} catch(Exception e){}
......
img.setImageBitmap(b);
Swift3:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController("LoginViewController") as UIViewController
self.navigationController?.pushViewController(vc, animated: true)
Try this out. You just confused nib with storyboard representation.
$bucket = '$node->' . $fieldname . "['und'][0]['value'] = " . '$form_state' . "['values']['" . $fieldname . "']";
print $bucket;
yields:
$node->mindd_2_study_status['und'][0]['value'] = $form_state['values']
['mindd_2_study_status']
In addition to @Cristian's answer above, I had to do two more steps to get it working correctly. I will sum all of it here:
R.java
class and the press F6
(Refactor->Move...). It will allow you to move the class to another package, and all references to that class will be updated.build.gradle
file : android / defaultconfig / application ID [source].You can check in windows services if tomcat is installed it will be listed in windows services.
To check the windows service list of services installed on windows machine use
WINDOWS KEY + R and type services.msc
There you can find all the services related with Jasperreport server like Tomcat and MySQL with name starting Jasperreport server Tomcat and MySQL only if these services are installed and its need to be started by selecting the option.Then you can access it through browser using this link :-
http://localhost:8080
default port for tomcat is 8080.
In my situation, I was comparing table schema column count for 2 identical tables in 2 databases; one is the main database and the other is the archival database. I did this (SQL 2012+):
DECLARE @colCount1 INT;
DECLARE @colCount2 INT;
SELECT @colCount1 = COUNT(COLUMN_NAME) FROM MainDB.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'SomeTable';
SELECT @colCount2 = COUNT(COLUMN_NAME) FROM ArchiveDB.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'SomeTable';
IF (@colCount1 != @colCount2) THROW 5000, 'Number of columns in both tables are not equal. The archive schema may need to be updated.', 16;
The important thing to notice here is qualifying the database name before INFORMATION_SCHEMA
(which is a schema, like dbo
). This will allow the code to break, in case columns were added to the main database and not to the archival database, in which if the procedure were allowed to run, data loss would almost certainly occur.
Try adding parentheses around the row in table1
e.g.
DELETE
FROM table1
WHERE (stn, year(datum)) IN (SELECT stn, jaar FROM table2);
The above is Standard SQL-92 code. If that doesn't work, it could be that your SQL product of choice doesn't support it.
Here's another Standard SQL approach that is more widely implemented among vendors e.g. tested on SQL Server 2008:
MERGE INTO table1 AS t1
USING table2 AS s1
ON t1.stn = s1.stn
AND s1.jaar = YEAR(t1.datum)
WHEN MATCHED THEN DELETE;
For me, adding Trusted_Connection=True to the connection string helped.
Use .map without return in simple way. Also start using let and const instead of var because let and const is more recommended
const rockets = [_x000D_
{ country:'Russia', launches:32 },_x000D_
{ country:'US', launches:23 },_x000D_
{ country:'China', launches:16 },_x000D_
{ country:'Europe(ESA)', launches:7 },_x000D_
{ country:'India', launches:4 },_x000D_
{ country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
const launchOptimistic = rockets.map(elem => (_x000D_
{_x000D_
country: elem.country,_x000D_
launches: elem.launches+10_x000D_
} _x000D_
));_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
I am using Protractor with directConnect. Disabling the "--no-sandbox" option fixed the issue for me.
// Capabilities to be passed to the webdriver instance.
capabilities: {
'directConnect': true,
'browserName': 'chrome',
chromeOptions: {
args: [
//"--headless",
//"--hide-scrollbars",
"--disable-software-rasterizer",
'--disable-dev-shm-usage',
//"--no-sandbox",
"incognito",
"--disable-gpu",
"--window-size=1920x1080"]
}
},
Thanks to both Tony and Paul for the quick feedback, its very helpful. I actually figure out a solution through POJO. Here it is:
if (cell_value.indexOf("\"") != -1 || cell_value.indexOf(",") != -1) {
cell_value = cell_value.replaceAll("\"", "\"\"");
row.append("\"");
row.append(cell_value);
row.append("\"");
} else {
row.append(cell_value);
}
in short if there is special character like comma or double quote within the string in side the cell, then first escape the double quote("\""
) by adding additional double quote (like "\"\""
), then put the whole thing into a double quote (like "\""+theWholeThing+"\""
)
This worked for me Visual C++ Redistributable Packages
I'm using python 3.4, requests 2.19.1:
'urllib3' is the logger to get now (no longer 'requests.packages.urllib3'). Basic logging will still happen without setting http.client.HTTPConnection.debuglevel
Len(word)
Although that's not what your question title asks =)
I think everything that you need is array_key_exists:
if (!array_key_exists('id', $access_data['Privilege'])) {
$this->Session->setFlash(__('Access Denied! You are not eligible to access this.'), 'flash_custom_success');
return $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
}
In my case same error is there , I am using Asyanc / Await functions , for this needs to add AWAIT for findOne
Ex:const foundUser = User.findOne ({ "email" : req.body.email });
above , foundUser always contains Object value in both cases either user found or not because it's returning values before finishing findOne .
const foundUser = await User.findOne ({ "email" : req.body.email });
above , foundUser returns null if user is not there in collection with provided condition . If user found returns user document.
In my case the problem was that one of the queries included in the transaction was raising an exception, and even though the exception was "gracefully" handled, it still managed to roll back the entire transaction.
My pseudo-code was like:
var transaction = connection.BeginTransaction();
for(all the lines in a file)
{
try{
InsertLineInTable(); // INSERT statement might fail and throw an exception
}
catch {
// notify the user about the error on line x and continue
}
}
// Commit and Rollback will fail if one of the queries
// in InsertLineInTable threw an exception
if(CheckTableForErrors())
{
transaction.Commit();
}
else
{
transaction.Rollback();
}
If you don't need to keep the order, and consider 45
and "45"
to be the same:
function union_arrays (x, y) {_x000D_
var obj = {};_x000D_
for (var i = x.length-1; i >= 0; -- i)_x000D_
obj[x[i]] = x[i];_x000D_
for (var i = y.length-1; i >= 0; -- i)_x000D_
obj[y[i]] = y[i];_x000D_
var res = []_x000D_
for (var k in obj) {_x000D_
if (obj.hasOwnProperty(k)) // <-- optional_x000D_
res.push(obj[k]);_x000D_
}_x000D_
return res;_x000D_
}_x000D_
_x000D_
console.log(union_arrays([34,35,45,48,49], [44,55]));
_x000D_
I saw the answers here and although helpful, they weren't exactly what I wanted since I had to alter a lot of my code.
What worked out for me, was doing something like this:
function isSession(selector) {
//line added for the var that will have the result
var result = false;
$.ajax({
type: "POST",
url: '/order.html',
data: ({ issession : 1, selector: selector }),
dataType: "html",
//line added to get ajax response in sync
async: false,
success: function(data) {
//line added to save ajax response in var result
result = data;
},
error: function() {
alert('Error occured');
}
});
//line added to return ajax response
return result;
}
Hope helps someone
anakin
You can do it via FileInfo or DirectoryInfo:
DirectoryInfo di = new DirectoryInfo("TempDir");
di.Delete(true);
And then recreate the directory
A lot of the answers here apply to older versions of Visual Studio. What worked for me, if using Visual Studio 2017 Community version, was setting an environment variable called VCTargetsPath
and giving it a value of
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets
If using Visual Studio 2019 Community version,
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VC\v160
Other answers here set this variable to c:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\v140
but I noticed in my visual studio installation, there was no folder called Microsoft.Cpp in my MSBuild folder. So keep this in mind as well as the fact that the path above is for the Community version of Visual Studio 2017.
Also, make sure that your MSBuild path in your environment variables points to the correct version of MSBuild if you're using Visual Studio 2017 Community version,
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin
If you're using Visual Studio 2019 Community version,
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin
I have done this way:
Add this method to replace fragments with Animations:
public void replaceFragmentWithAnimation(android.support.v4.app.Fragment fragment, String tag){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left);
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(tag);
transaction.commit();
}
You have to add four animations in anim folder which is associate with resource:
enter_from_left.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate
android:fromXDelta="-100%" android:toXDelta="0%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="700"/>
</set>
exit_to_right.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate
android:fromXDelta="0%" android:toXDelta="100%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="700" />
</set>
enter_from_right.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate
android:fromXDelta="100%" android:toXDelta="0%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="700" />
</set>
exit_to_left.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<translate
android:fromXDelta="0%" android:toXDelta="-100%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="700"/>
</set>
Output:
Its Done.
ggplot 3.3.0
fixes this by providing guide_axis(angle = 90)
(as guide
argument to scale_..
or as x
argument to guides
):
library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper", as.character(diamonds$cut))
ggplot(diamonds, aes(cut, carat)) +
geom_boxplot() +
scale_x_discrete(guide = guide_axis(angle = 90)) +
# ... or, equivalently:
# guides(x = guide_axis(angle = 90)) +
NULL
From the documentation of the angle
argument:
Compared to setting the angle in theme() / element_text(), this also uses some heuristics to automatically pick the hjust and vjust that you probably want.
Alternatively, it also provides guide_axis(n.dodge = 2)
(as guide
argument to scale_..
or as x
argument to guides
) to overcome the over-plotting problem by dodging the labels vertically. It works quite well in this case:
library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
ggplot(diamonds, aes(cut, carat)) +
geom_boxplot() +
scale_x_discrete(guide = guide_axis(n.dodge = 2)) +
NULL
If you only want to install the latest official JRE from Oracle, you can get it there, install it, and export the new JAVA_HOME in the terminal.
java -version
gives you an error and a popupexport JAVA_HOME="/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home"
java -version
now gives you java version "1.7.0_45"
That's the cleanest way I found to install the latest JRE.
You can add the export JAVA_HOME
line in your .bashrc
to have java
permanently in your Terminal:
echo export JAVA_HOME=\"/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home\" >> ~/.bashrc
If jQuery
is loading asynchronously, you can wait till it is defined, checking for it every period of time:
(function() {
var a = setInterval( function() {
if ( typeof window.jQuery === 'undefined' ) {
return;
}
clearInterval( a );
console.log( 'jQuery is loaded' ); // call your function with jQuery instead of this
}, 500 );
})();
This method can be used for any variable, you are waiting to appear.
On my machine this only works in bin/idea.vmoptions
, adding the setting in ~/Library/Preferences/IntelliJIdea12/idea.vmoptions
causes the IDEA to hang during startup.
The following code with Python 2.6 and above ONLY
First, import itertools
:
import itertools
print list(itertools.permutations([1,2,3,4], 2))
[(1, 2), (1, 3), (1, 4),
(2, 1), (2, 3), (2, 4),
(3, 1), (3, 2), (3, 4),
(4, 1), (4, 2), (4, 3)]
print list(itertools.combinations('123', 2))
[('1', '2'), ('1', '3'), ('2', '3')]
print list(itertools.product([1,2,3], [4,5,6]))
[(1, 4), (1, 5), (1, 6),
(2, 4), (2, 5), (2, 6),
(3, 4), (3, 5), (3, 6)]
print list(itertools.product([1,2], repeat=3))
[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
(2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
This solution is only for components
If we toggle(show/hide) components using booleans then data is also removed. No need to clean the form fields.
I usually make components and initialize them using booleans. e.g.
<template>
<button @click="show_create_form = true">Add New Record</button
<create-form v-if="show_create_form" />
</template>
<script>
...
data(){
return{
show_create_form:false //making it false by default
}
},
methods:{
submitForm(){
//...
this.axios.post('/submit-form-url',data,config)
.then((response) => {
this.show_create_form= false; //hide it again after success.
//if you now click on add new record button then it will show you empty form
}).catch((error) => {
//
})
}
}
...
</script>
When use clicks on edit button then this boolean becomes true and after successful submit I change it to false again.
You want the (standard) POSIXt
type from base R that can be had in 'compact form' as a POSIXct
(which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt
(which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)
Quick example:
R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10 # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79
$min
[1] 39
$hour
[1] 18
$mday
[1] 25
$mon
[1] 11
$year
[1] 109
$wday
[1] 5
$yday
[1] 358
$isdst
[1] 0
attr(,"tzone")
[1] "America/Chicago" "CST" "CDT"
R>
As for reading them in, see help(strptime)
As for difference, easy too:
R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R>
Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.
Use the new jQuery on function in 1.7.1 -
I always initialise them as NULL
.
I always use string.IsNullOrEmpty(someString)
to check it's value.
Simple.
Not sure if this is what you want but this is what I do sometimes in a pinch when certain websites are not saving right.
I just print them to PDF and I get a PDF file of the 'print output'. There's an Microsoft XPS Document writer under my list of printers as well, but I don't use it.
Hope this helps! =)
It is very important to set a default timezone to get the correct result
<?php
// set default timezone
date_default_timezone_set('Europe/Berlin');
// timestamp
$timestamp = 1307595105;
// output
echo date('d M Y H:i:s Z',$timestamp);
echo date('c',$timestamp);
?>
Online conversion help: http://freeonlinetools24.com/timestamp
As a general rule of thumb, I use 1 cm margins when producing pdfs. I work in the geospatial industry and produce pdf maps that reference a specific geographic scale. Therefore, I do not have the option to 'fit document to printable area,' because this would make the reference scale inaccurate. You must also realize that when you fit to printable area, you are fitting your already existing margins inside the printer margins, so you end up with double margins. Make your margins the right size and your documents will print perfectly. Many modern printers can print with margins less than 3 mm, so 1 cm as a general rule should be sufficient. However, if it is a high profile job, get the specs of the printer you will be printing with and ensure that your margins are adequate. All you need is the brand and model number and you can find spec sheets through a google search.
In general this error message means that you have tried to use indexing on a function. You can reproduce this error message with, for example
mean[1]
## Error in mean[1] : object of type 'closure' is not subsettable
mean[[1]]
## Error in mean[[1]] : object of type 'closure' is not subsettable
mean$a
## Error in mean$a : object of type 'closure' is not subsettable
The closure mentioned in the error message is (loosely) the function and the environment that stores the variables when the function is called.
In this specific case, as Joshua mentioned, you are trying to access the url
function as a variable. If you define a variable named url
, then the error goes away.
As a matter of good practise, you should usually avoid naming variables after base-R functions. (Calling variables data
is a common source of this error.)
There are several related errors for trying to subset operators or keywords.
`+`[1]
## Error in `+`[1] : object of type 'builtin' is not subsettable
`if`[1]
## Error in `if`[1] : object of type 'special' is not subsettable
If you're running into this problem in shiny
, the most likely cause is that you're trying to work with a reactive
expression without calling it as a function using parentheses.
library(shiny)
reactive_df <- reactive({
data.frame(col1 = c(1,2,3),
col2 = c(4,5,6))
})
While we often work with reactive expressions in shiny as if they were data frames, they are actually functions that return data frames (or other objects).
isolate({
print(reactive_df())
print(reactive_df()$col1)
})
col1 col2
1 1 4
2 2 5
3 3 6
[1] 1 2 3
But if we try to subset it without parentheses, then we're actually trying to index a function, and we get an error:
isolate(
reactive_df$col1
)
Error in reactive_df$col1 : object of type 'closure' is not subsettable
<form method="post" action="servletName">
<input type="submit" id="btn1" name="btn1"/>
<input type="submit" id="btn2" name="btn2"/>
</form>
on pressing it request will go to servlet on the servlet page check which button is pressed and then accordingly call the needed method as objectName.method
For me running these three commands fix the issue on my Mac:
export ANDROID_HOME=~/Library/Android/sdk
export PATH=${PATH}:${ANDROID_HOME}/tools
export PATH=${PATH}:${ANDROID_HOME}/platform-tools
For ease of copying here's one-liner
export ANDROID_HOME=~/Library/Android/sdk && export PATH=${PATH}:${ANDROID_HOME}/tools && export PATH=${PATH}:${ANDROID_HOME}/platform-tools
To add Permanently
Follow these steps:
export PATH="The above exports here"
to the last line of the file, where your-dir is the directory you want to add.This misled me a bit - it should be setImageResource
instead of setBackgroundResource
:) !!
The following works fine :
ImageButton btn = (ImageButton)findViewById(R.id.imageButton1);
btn.setImageResource(R.drawable.actions_record);
while when using the setBackgroundResource
the actual imagebutton's image
stays while the background image is changed which leads to a ugly looking imageButton object
Thanks.
I used this to allow the user to enter the currency and to convert it from string into int to store in db and to change back from int into string again
Hi as @andrew mentioned make cellpadding = 0
, you still might have some space as you are using table border=1
.
JSON (= JavaScript Object Notation), is a lightweight and fast mechanism to convert Javascript objects into a string and vice versa.
Since Javascripts objects consists of key/value
pairs its very easy to use and access JSON that way.
So if we have an object:
var myObj = {
foo: 'bar',
base: 'ball',
deep: {
java: 'script'
}
};
We can convert that into a string by calling window.JSON.stringify(myObj);
with the result of "{"foo":"bar","base":"ball","deep":{"java":"script"}}"
.
The other way around, we would call window.JSON.parse("a json string like the above");
.
JSON.parse()
returns a javascript object/array on success.
alert(myObj.deep.java); // 'script'
window.JSON
is not natively available in all browser. Some "older" browser need a little javascript plugin which offers the above mentioned functionality. Check http://www.json.org for further information.
Cygwin's setup accepts command-line arguments to install packages from the command-line.
e.g. setup-x86.exe -q -P packagename1,packagename2
to install packages without any GUI interaction ('unattended setup mode').
(Note that you need to use setup-x86.exe
or setup-x86_64.exe
as appropriate.)
See http://cygwin.com/packages/ for the package list.
I'm not sure you can exclude packages explicitly with an <exclude-filter>, but I bet using a regex filter would effectively get you there:
<context:component-scan base-package="com.example">
<context:exclude-filter type="regex" expression="com\.example\.ignore\..*"/>
</context:component-scan>
To make it annotation-based, you'd annotate each class you wanted excluded for integration tests with something like @com.example.annotation.ExcludedFromITests. Then the component-scan would look like:
<context:component-scan base-package="com.example">
<context:exclude-filter type="annotation" expression="com.example.annotation.ExcludedFromITests"/>
</context:component-scan>
That's clearer because now you've documented in the source code itself that the class is not intended to be included in an application context for integration tests.
In my case, I was mistaken the function parameters, which are:
context.drawImage(image, left, top);
context.drawImage(image, left, top, width, height);
If you expect them to be
context.drawImage(image, width, height);
you will place the image just outside the canvas with the same effects as described in the question.
Any input from a client are ways to be vulnerable. Including all forms and the query string. This includes all HTTP verbs.
There are 3rd party solutions that can crawl an application and detect when an injection could happen.
Also, You can write all inline, direct at html code:
<input type="file" id="imgupload">
<a href="#" onclick="$('#imgupload').trigger('click'); return false;">Upload file</a>
return false; - will be useful to decline anchor action after link was clicked.
Try position:fixed; bottom:0;
. This will make your div to stay fixed at the bottom.
The HTML:
<div id="bottom-stuff">
<div id="search"> MY DIV </div>
</div>
<div id="bottom"> MY DIV </div>
The CSS:
#bottom-stuff {
position: relative;
}
#bottom{
position: fixed;
background:gray;
width:100%;
bottom:0;
}
#search{height:5000px; overflow-y:scroll;}
Hope this helps.
Once instanciated, cannot be altered. Consider a class that an instance of might be used as the key for a hashtable or similar. Check out Java best practices.
Within the class you can call function by using :
$this->filter();
Outside of the class
you have to create an object of a class
ex: $obj = new Functions();
$obj->filter($param);
for more about OOPs in php
this example:
class test {
public function newTest(){
$this->bigTest();// we don't need to create an object we can call simply using $this
$this->smallTest();
}
private function bigTest(){
//Big Test Here
}
private function smallTest(){
//Small Test Here
}
public function scoreTest(){
//Scoring code here;
}
}
$testObject = new test();
$testObject->newTest();
$testObject->scoreTest();
hope it will help!
Add this at the start of main
ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml");
JobLauncher launcher=(JobLauncher)context.getBean("launcher");
Job job=(Job)context.getBean("job");
//Get as many beans you want
//Now do the thing you were doing inside test method
StopWatch sw = new StopWatch();
sw.start();
launcher.run(job, jobParameters);
sw.stop();
//initialize the log same way inside main
logger.info(">>> TIME ELAPSED:" + sw.prettyPrint());
For Python, I haven't found an OpenCV function that provides contrast. As others have suggested, there are some techniques to automatically increase contrast using a very simple formula.
In the official OpenCV docs, it is suggested that this equation can be used to apply both contrast and brightness at the same time:
new_img = alpha*old_img + beta
where alpha corresponds to a contrast and beta is brightness. Different cases
alpha 1 beta 0 --> no change
0 < alpha < 1 --> lower contrast
alpha > 1 --> higher contrast
-127 < beta < +127 --> good range for brightness values
In C/C++, you can implement this equation using cv::Mat::convertTo, but we don't have access to that part of the library from Python. To do it in Python, I would recommend using the cv::addWeighted function, because it is quick and it automatically forces the output to be in the range 0 to 255 (e.g. for a 24 bit color image, 8 bits per channel). You could also use convertScaleAbs
as suggested by @nathancy.
import cv2
img = cv2.imread('input.png')
# call addWeighted function. use beta = 0 to effectively only operate one one image
out = cv2.addWeighted( img, contrast, img, 0, brightness)
output = cv2.addWeighted
The above formula and code is quick to write and will make changes to brightness and contrast. But they yield results that are significantly different than photo editing programs. The rest of this answer will yield a result that will reproduce the behavior in the GIMP and also LibreOffice brightness and contrast. It's more lines of code, but it gives a nice result.
In the GIMP, contrast levels go from -127 to +127. I adapted the formulas from here to fit in that range.
f = 131*(contrast + 127)/(127*(131-contrast))
new_image = f*(old_image - 127) + 127 = f*(old_image) + 127*(1-f)
To figure out brightness, I figured out the relationship between brightness and levels and used information in this levels post to arrive at a solution.
#pseudo code
if brightness > 0
shadow = brightness
highlight = 255
else:
shadow = 0
highlight = 255 + brightness
new_img = ((highlight - shadow)/255)*old_img + shadow
Putting it all together and adding using the reference "mandrill" image from USC SIPI:
import cv2
import numpy as np
# Open a typical 24 bit color image. For this kind of image there are
# 8 bits (0 to 255) per color channel
img = cv2.imread('mandrill.png') # mandrill reference image from USC SIPI
s = 128
img = cv2.resize(img, (s,s), 0, 0, cv2.INTER_AREA)
def apply_brightness_contrast(input_img, brightness = 0, contrast = 0):
if brightness != 0:
if brightness > 0:
shadow = brightness
highlight = 255
else:
shadow = 0
highlight = 255 + brightness
alpha_b = (highlight - shadow)/255
gamma_b = shadow
buf = cv2.addWeighted(input_img, alpha_b, input_img, 0, gamma_b)
else:
buf = input_img.copy()
if contrast != 0:
f = 131*(contrast + 127)/(127*(131-contrast))
alpha_c = f
gamma_c = 127*(1-f)
buf = cv2.addWeighted(buf, alpha_c, buf, 0, gamma_c)
return buf
font = cv2.FONT_HERSHEY_SIMPLEX
fcolor = (0,0,0)
blist = [0, -127, 127, 0, 0, 64] # list of brightness values
clist = [0, 0, 0, -64, 64, 64] # list of contrast values
out = np.zeros((s*2, s*3, 3), dtype = np.uint8)
for i, b in enumerate(blist):
c = clist[i]
print('b, c: ', b,', ',c)
row = s*int(i/3)
col = s*(i%3)
print('row, col: ', row, ', ', col)
out[row:row+s, col:col+s] = apply_brightness_contrast(img, b, c)
msg = 'b %d' % b
cv2.putText(out,msg,(col,row+s-22), font, .7, fcolor,1,cv2.LINE_AA)
msg = 'c %d' % c
cv2.putText(out,msg,(col,row+s-4), font, .7, fcolor,1,cv2.LINE_AA)
cv2.putText(out, 'OpenCV',(260,30), font, 1.0, fcolor,2,cv2.LINE_AA)
cv2.imwrite('out.png', out)
I manually processed the images in the GIMP and added text tags in Python/OpenCV:
Note: @UtkarshBhardwaj has suggested that Python 2.x users must cast the contrast correction calculation code into float for getting floating result, like so:
...
if contrast != 0:
f = float(131*(contrast + 127))/(127*(131-contrast))
...
In the Divi Theme Documentation, it says that the theme comes with access to 'ePanel' which also has an 'Integration' section.
You should be able to add this code:
<script>
$( ".et-pb-icon" ).click(function() {
$( this ).toggleClass( "active" );
});
</script>
into the the box that says 'Add code to the head of your blog' under the 'Integration' tab, which should get the jQuery working.
Then, you should be able to style your class to what ever you need.
I used PDFiumSharp and ImageSharp in a .NET Standard 2.1 class library.
/// <summary>
/// Saves a thumbnail (jpg) to the same folder as the PDF file, using dimensions 300x423,
/// which corresponds to the aspect ratio of 'A' paper sizes like A4 (ratio h/w=sqrt(2))
/// </summary>
/// <param name="pdfPath">Source path of the pdf file.</param>
/// <param name="thumbnailPath">Target path of the thumbnail file.</param>
/// <param name="width"></param>
/// <param name="height"></param>
public static void SaveThumbnail(string pdfPath, string thumbnailPath = "", int width = 300, int height = 423)
{
using var pdfDocument = new PdfDocument(pdfPath);
var firstPage = pdfDocument.Pages[0];
using var pageBitmap = new PDFiumBitmap(width, height, true);
firstPage.Render(pageBitmap);
var imageJpgPath = string.IsNullOrWhiteSpace(thumbnailPath)
? Path.ChangeExtension(pdfPath, "jpg")
: thumbnailPath;
var image = Image.Load(pageBitmap.AsBmpStream());
// Set the background to white, otherwise it's black. https://github.com/SixLabors/ImageSharp/issues/355#issuecomment-333133991
image.Mutate(x => x.BackgroundColor(Rgba32.White));
image.Save(imageJpgPath, new JpegEncoder());
}
int x;
ifile >> x
while (!iFile.eof())
{
cerr << x << endl;
iFile >> x;
}
Set args = Wscript.Arguments
For Each arg In args
Wscript.Echo arg
Next
From a command prompt, run the script like this:
CSCRIPT MyScript.vbs 1 2 A B "Arg with spaces"
Will give results like this:
1
2
A
B
Arg with spaces
This is what I've been using for development:
<?xml version="1.0" ?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>
This is a very liberal approach, but is fine for my application.
As others have pointed out below, beware the risks of this.
I'd like to add the following to Shay Levy's correct answer:
You can make your life easier if you create a little batch script run.cmd
to launch your powershell script:
@echo off & setlocal
set batchPath=%~dp0
powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" "MY-PC"
Put it in the same path as SQLExecutor.ps1
and from now on you can run it by simply double-clicking on run.cmd
.
Note:
If you require command line arguments inside the run.cmd batch, simply pass them as %1
... %9
(or use %*
to pass all parameters) to the powershell script, i.e.
powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" %*
The variable batchPath
contains the executing path of the batch file itself (this is what the expression %~dp0
is used for). So you just put the powershell script in the same path as the calling batch file.
...
<div class="img_file" style="background-image: url('/upload/test/14120330.jpg')" data-img="/upload/test/14120330.jpg"></div>
<div class="img_file" style="background-image: url('/upload/test/14120330.jpg')" data-img="/upload/test/14120330.jpg"></div>
...
if($(".img_file[data-img]").length) {
var imgs_slider_img = [];
$(".img_file[data-img]").each(function(i) {
imgs_slider_img.push({
href:$(this).attr('data-img')
});
$(this).attr('data-index-img', i);
}).on("click", function(e) {
e.preventDefault();
$.fancybox.open(imgs_slider_img, {
index: $(this).attr('data-index-img'),
padding: 0,
margin: 0,
prevEffect: 'elastic',
nextEffect: 'elastic',
maxWidth: '90%',
maxHeight: '90%',
autoWidth: true,
autoHeight: true
});
});
}
...
I think blog post How to fetch & show SQL Server database data in ASP.NET page using Ajax (jQuery) will help you.
JavaScript Code
<script src="http://code.jquery.com/jquery-3.3.1.js" />
<script language="javascript" type="text/javascript">
function GetCompanies() {
$("#UpdatePanel").html("<div style='text-align:center; background-color:yellow; border:1px solid red; padding:3px; width:200px'>Please Wait...</div>");
$.ajax({
type: "POST",
url: "Default.aspx/GetCompanies",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: OnError
});
}
function OnSuccess(data) {
var TableContent = "<table border='0'>" +
"<tr>" +
"<td>Rank</td>" +
"<td>Company Name</td>" +
"<td>Revenue</td>" +
"<td>Industry</td>" +
"</tr>";
for (var i = 0; i < data.d.length; i++) {
TableContent += "<tr>" +
"<td>"+ data.d[i].Rank +"</td>" +
"<td>"+data.d[i].CompanyName+"</td>" +
"<td>"+data.d[i].Revenue+"</td>" +
"<td>"+data.d[i].Industry+"</td>" +
"</tr>";
}
TableContent += "</table>";
$("#UpdatePanel").html(TableContent);
}
function OnError(data) {
}
</script>
ASP.NET Server Side Function
[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json)]
public static List<TopCompany> GetCompanies()
{
System.Threading.Thread.Sleep(5000);
List<TopCompany> allCompany = new List<TopCompany>();
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
allCompany = dc.TopCompanies.ToList();
}
return allCompany;
}
This answers the 'best random' request:
Adi's answer1 from Security.StackExchange has a solution for this:
Make sure you have OpenSSL support, and you'll never go wrong with this one-liner
$token = bin2hex(openssl_random_pseudo_bytes(16));
1. Adi, Mon Nov 12 2018, Celeritas, "Generating an unguessable token for confirmation e-mails", Sep 20 '13 at 7:06, https://security.stackexchange.com/a/40314/
This is what I would do:
// num is your number
// amount is your percentage
function per(num, amount){
return num*amount/100;
}
...
<html goes here>
...
alert(per(10000, 35.8));
Use float() in place of int() so that your program can handle decimal points. Also, don't use next
as it's a built-in Python function, next().
Also you code as posted is missing import sys
and the definition for dead
Necroing this question but there's an explanation that no-one seems to have considered.
STATISTICS - Statistics are not available or misleading
If all of the following are true:
Then sql server may be incorrectly assuming that the columns are uncorrelated, leading to lower than expected cardinality estimates for applying both restrictions and a poor execution plan being selected. The fix in this case would be to create a statistics object linking the two columns, which is not an expensive operation.
since df.save(path, source, mode)
is deprecated, (http://spark.apache.org/docs/1.5.0/api/scala/index.html#org.apache.spark.sql.DataFrame)
use df.write.format(source).mode("overwrite").save(path)
where df.write is DataFrameWriter
'source' can be ("com.databricks.spark.avro" | "parquet" | "json")
Since strings are immutable, both versions are safe. The latter, however, is less efficient (it creates an extra object and in some cases copies the character data).
With this in mind, the first version should be preferred.
The suggested answer no longer works after 2014. Now you have to use Google Maps Embed API for loading into iframe.
Here is the link for the question and solution.
If you are using Angular like me you won't be able to load the google maps in iframe because of XSS security issue. For that you need to sanitise the URL with Pipe from angular.
Here is the link to do so.
All the suggestions are tested and works 100% as of today.
Update
I found another simple way
simply declare a property :-
@property( strong , nonatomic) UITextfield *currentTextfield;
and a Tap Gesture Gecognizer:-
@property (strong , nonatomic) UITapGestureRecognizer *resignTextField;
In ViewDidLoad
_currentTextfield=[[UITextField alloc]init];
_resignTextField=[[UITapGestureRecognizer alloc]initWithTarget:@selector(tapMethod:)];
[self.view addGestureRecognizer:_resignTextField];
Implement the textfield delegate method didBeginEditing
-(void)textFieldDidBeginEditing:(UITextField *)textField{
_currentTextfield=textField;
}
Implement Your Tap Gesture Method (_resignTextField)
-(void)tapMethod:(UITapGestureRecognizer *)Gesture{
[_currentTextfield resignFirstResponder];
}
The file is truncated, so you can call read()
(no exceptions raised, unlike when opened using 'w') but you'll get an empty string.
You are catching the error but then you are re throwing it. You should try and handle it more gracefully, otherwise your user is going to see 500, internal server, errors.
You may want to send back a response telling the user what went wrong as well as logging the error on your server.
I am not sure exactly what errors the request might return, you may want to return something like.
router.get("/emailfetch", authCheck, async (req, res) => {
try {
let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
emailFetch = emailFetch.data
res.send(emailFetch)
} catch(error) {
res.status(error.response.status)
return res.send(error.message);
})
})
This code will need to be adapted to match the errors that you get from the axios call.
I have also converted the code to use the try and catch syntax since you are already using async.
I had a similar issue with MySQL 5.7 with the following code:
`update_date` TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
I fixed by using this instead:
`update_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
Python's standard out is buffered (meaning that it collects some of the data "written" to standard out before it writes it to the terminal). Calling sys.stdout.flush()
forces it to "flush" the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so.
Here's some good information about (un)buffered I/O and why it's useful:
http://en.wikipedia.org/wiki/Data_buffer
Buffered vs unbuffered IO
This is a optimized version of the function which removes dependency on BitConverter function and makes it compatible with NETMF (.NET Micro Framework)
public static DateTime GetNetworkTime()
{
const string ntpServer = "pool.ntp.org";
var ntpData = new byte[48];
ntpData[0] = 0x1B; //LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)
var addresses = Dns.GetHostEntry(ntpServer).AddressList;
var ipEndPoint = new IPEndPoint(addresses[0], 123);
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(ipEndPoint);
socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close();
ulong intPart = (ulong)ntpData[40] << 24 | (ulong)ntpData[41] << 16 | (ulong)ntpData[42] << 8 | (ulong)ntpData[43];
ulong fractPart = (ulong)ntpData[44] << 24 | (ulong)ntpData[45] << 16 | (ulong)ntpData[46] << 8 | (ulong)ntpData[47];
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
var networkDateTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long)milliseconds);
return networkDateTime;
}
The accepted solution wont work in case you are working with an anchor tag. In this case you wont be able to click the link again after calling e.preventDefault()
. Thats because the click event generated by jQuery is just layer on top of native browser events. So triggering a 'click' event on an anchor tag wont follow the link. Instead you could use a library like jquery-simulate that will allow you to launch native browser events.
More details about this can be found in this link
Just because you're in PowerShell don't forgot about good ol' exes. Sometimes they can provide the easiest solution e.g.:
icacls.exe $folder /grant 'domain\user:(OI)(CI)(M)'
Not sure if this matters to anyone else, but I prefer the id for the table to be the first column in the database. The syntax for that is:
ALTER TABLE your_db.your_table ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT FIRST;
Which is just a slight improvement over the first answer. If you wanted it to be in a different position, then
ALTER TABLE unique_address ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT AFTER some_other_column;
HTH, -ft
SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d')
FROM users
WHERE DATE(signup_date) = CURDATE()
$query->num_rows()
The number of rows returned by the query. Note: In this example, $query is the variable that the query result object is assigned to:
$query = $this->db->query('SELECT * FROM my_table');
echo $query->num_rows();
Use Jquery for append the value for creating dynamically
eg:
var user_image1='<img src="{@user_image}" class="img-thumbnail" alt="Thumbnail Image"
style="width:125px; height:125px">';
$("#userphoto").append(user_image1.replace("{@user_image}","http://127.0.0.1:50075/webhdfs/v1/PATH/"+user_image+"?op=OPEN"));
HTML :
<div id="userphoto">
Since you say you're using Java 5, you can use setInt
with an Integer
due to autounboxing: pstmt.setInt(1, tempID)
should work just fine. In earlier versions of Java, you would have had to call .intValue()
yourself.
The opposite works as well... assigning an int
to an Integer
will automatically cause the int
to be autoboxed using Integer.valueOf(int)
.
I disagree that .form-group should be within .col-*-n elements. In my experience, all the appropriate padding happens automatically when you use .form-group like .row within a form.
<div class="form-group">
<div class="col-sm-12">
<label for="user_login">Username</label>
<input class="form-control" id="user_login" name="user[login]" required="true" size="30" type="text" />
</div>
</div>
Check out this demo.
Altering the demo slightly by adding .form-horizontal to the form tag changes some of that padding.
<form action="#" method="post" class="form-horizontal">
Check out this demo.
When in doubt, inspect in Chrome or use Firebug in Firefox to figure out things like padding and margins. Using .row within the form fails in edsioufi's fiddle because .row uses negative left and right margins thereby drawing the horizontal bounds of the divs classed .row beyond the bounds of the containing fieldsets.
Hibernate has a built-in "yes_no" type that would do what you want. It maps to a CHAR(1) column in the database.
Basic mapping: <property name="some_flag" type="yes_no"/>
Annotation mapping (Hibernate extensions):
@Type(type="yes_no")
public boolean getFlag();
You stated you want circular crops from recangles. This may not be able to be done with the 3 popular bootstrap classes (img-rounded; img-circle; img-polaroid)
You may want to write a custom CSS class using border-radius where you have more control. If you want it more circular just increase the radius.
.CattoBorderRadius_x000D_
{_x000D_
border-radius: 25px;_x000D_
}
_x000D_
<img class="img-responsive CattoBorderRadius" src="http://placekitten.com/g/200/200" />
_x000D_
Fiddle URL: http://jsfiddle.net/ccatto/LyxEb/
I know this may not be the perfect radius but I think your answer will use a custom css class. Hope this helps.
I beleive I'm little late here. But I think this would help for the new peeps! If you're using smtp.gmail.com , then you have to do the following:
Turn on the less secure apps
You'll get the security mail in your gmail inbox, Click Yes,it's me in that.
float
Or if you want to go old-school:
real
You can also use float(53), but it means the same thing as float.
("real" is equivalent to float(24), not float/float(53).)
The decimal(x,y) SQL Server type is for when you want exact decimal numbers rather than floating point (which can be approximations). This is in contrast to the C# "decimal" data type, which is more like a 128-bit floating point number.
MSSQL's float type is equivalent to the 64-bit double type in .NET. (My original answer from 2011 said there could be a slight difference in mantissa, but I've tested this in 2020 and they appear to be 100% compatible in their binary representation of both very small and very large numbers -- see https://dotnetfiddle.net/wLX5Ox for my test).
To make things more confusing, a "float" in C# is only 32-bit, so it would be more equivalent in SQL to the real/float(24) type in MSSQL than float/float(53).
In your specific use case... All you need is 5 places after the decimal point to represent latitude and longitude within about one-meter precision, and you only need up to three digits before the decimal point for the degrees. Float(24) or decimal(8,5) will best fit your needs in MSSQL, and using float in C# is good enough, you don't need double. In fact, your users will probably thank you for rounding to 5 decimal places rather than having a bunch of insignificant digits coming along for the ride.
OS X tends to prefix the system account names with "_"; you don't say what version of OS X you're using, but at least in 10.8 and 10.9 the _postgres user exists in a default install. Note that you won't be able to su
to this account (except as root), since it doesn't have a password. sudo -u _postgres
, on the other hand, should work fine.
In the CMakeLists.txt file, create a cache variable, as documented here:
SET(FAB "po" CACHE STRING "Some user-specified option")
Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#command:set
Then, either use the GUI (ccmake or cmake-gui) to set the cache variable, or specify the value of the variable on the cmake command line:
cmake -DFAB:STRING=po
Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#opt:-Dvar:typevalue
Modify your cache variable to a boolean if, in fact, your option is boolean.
Use the following
<div style="max-width:980px; overflow-x: scroll; white-space: nowrap;">
<table border="1" style="cellpadding:0; cellspacing:0; border:0; width=:100%;" >
this is what it worked for me:
select * from table
where column
BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
AND STR_TO_DATE('07/10/15', '%d/%m/%Y')
Please, note that I had to change STR_TO_DATE(column, '%d/%m/%Y') from previous solutions, as it was taking ages to load
I think the easiest is to simply open the file in write mode and then close it. For example, if your file myfile.dat
contains:
"This is the original content"
Then you can simply write:
f = open('myfile.dat', 'w')
f.close()
This would erase all the content. Then you can write the new content to the file:
f = open('myfile.dat', 'w')
f.write('This is the new content!')
f.close()
Try double-clicking on the bottom right hand corner of the cell (ie on the box that you would otherwise drag).
This can work too:
chmod -R 755 * // All files and folders to 755.
chmod -R 644 *.* // All files will be 644.
OS: Windows 7
Steps which worked for me:
npm config get proxy
npm config get https-proxy
Comments: I executed this command to know my proxy settings
npm config rm proxy
npm config rm https-proxy
npm config set registry=http://registry.npmjs.org/
npm install
<input type="checkbox" checked="checked" onclick="this.checked=true" />
I started from the problem: "how to POST/Submit an Input Checkbox that is disabled?" and in my answer I skipped the comment: "If we want to disable a checkbox we surely need to keep a prefixed value (checked or unchecked) and also we want that the user be aware of it (otherwise we should use a hidden type and not a checkbox)". In my answer I supposed that we want to keep always a checkbox checked and that code works in this way. If we click on that ckeckbox it will be forever checked and its value will be POSTED/Submitted! In the same way if I write onclick="this.checked=false" without checked="checked" (note: default is unchecked) it will be forever unchecked and its value will be not POSTED/Submitted!.
For those trouble shooting, it is important to know that ng-include requires the url path to be from the app root directory and not from the same directory where the partial.html lives. (whereas partial.html is the view file that the inline ng-include markup tag can be found).
For example:
Correct: div ng-include src=" '/views/partials/tabSlides/add-more.html' ">
Incorrect: div ng-include src=" 'add-more.html' ">
I had a similar problem (detailed explanation below), and I solved it (in jasmine-core: 2.52
) by using the tick
function with the same (or greater) amount of milliseconds as in original setTimeout
call.
For example, if I had a setTimeout(() => {...}, 2500);
(so it will trigger after 2500 ms), I would call tick(2500)
, and that would solve the problem.
What I had in my component, as a reaction on a Delete button click:
delete() {
this.myService.delete(this.id)
.subscribe(
response => {
this.message = 'Successfully deleted! Redirecting...';
setTimeout(() => {
this.router.navigate(['/home']);
}, 2500); // I wait for 2.5 seconds before redirect
});
}
Her is my working test:
it('should delete the entity', fakeAsync(() => {
component.id = 1; // preparations..
component.getEntity(); // this one loads up the entity to my component
tick(); // make sure that everything that is async is resolved/completed
expect(myService.getMyThing).toHaveBeenCalledWith(1);
// more expects here..
fixture.detectChanges();
tick();
fixture.detectChanges();
const deleteButton = fixture.debugElement.query(By.css('.btn-danger')).nativeElement;
deleteButton.click(); // I've clicked the button, and now the delete function is called...
tick(2501); // timeout for redirect is 2500 ms :) <-- solution
expect(myService.delete).toHaveBeenCalledWith(1);
// more expects here..
}));
P.S. Great explanation on fakeAsync
and general asyncs in testing can be found here: a video on Testing strategies with Angular 2 - Julie Ralph, starting from 8:10, lasting 4 minutes :)
With a = subprocess.Popen("cdrecord --help",stdout = subprocess.PIPE)
, you need to either use a list or use shell=True
;
Either of these will work. The former is preferable.
a = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE)
a = subprocess.Popen('cdrecord --help', shell=True, stdout=subprocess.PIPE)
Also, instead of using Popen.stdout.read
/Popen.stderr.read
, you should use .communicate()
(refer to the subprocess documentation for why).
proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
I started using mocks with EasyMock. Easy enough to understand, but the replay step was kinda annoying. Mockito removes this, also has a cleaner syntax as it looks like readability was one of its primary goals. I cannot stress enough how important this is, since most of developers will spend their time reading and maintaining existing code, not creating it.
Another nice thing is that interfaces and implementation classes are handled in the same way, unlike in EasyMock where still you need to remember (and check) to use an EasyMock Class Extension.
I've taken a quick look at JMockit recently, and while the laundry list of features is pretty comprehensive, I think the price of this is legibility of resulting code, and having to write more.
For me, Mockito hits the sweet spot, being easy to write and read, and dealing with majority of the situations most code will require. Using Mockito with PowerMock would be my choice.
One thing to consider is that the tool you would choose if you were developing by yourself, or in a small tight-knit team, might not be the best to get for a large company with developers of varying skill levels. Readability, ease of use and simplicity would need more consideration in the latter case. No sense in getting the ultimate mocking framework if a lot of people end up not using it or not maintaining the tests.
select right(rtrim('94342KMR'),3)
This will fetch the last 3 right string.
select substring(rtrim('94342KMR'),1,len('94342KMR')-3)
This will fetch the remaining Characters.
Here's a way to get dimensions of a png file without needing a third-party module. From http://coreygoldberg.blogspot.com/2013/01/python-verify-png-file-and-get-image.html
import struct
def get_image_info(data):
if is_png(data):
w, h = struct.unpack('>LL', data[16:24])
width = int(w)
height = int(h)
else:
raise Exception('not a png image')
return width, height
def is_png(data):
return (data[:8] == '\211PNG\r\n\032\n'and (data[12:16] == 'IHDR'))
if __name__ == '__main__':
with open('foo.png', 'rb') as f:
data = f.read()
print is_png(data)
print get_image_info(data)
When you run this, it will return:
True
(x, y)
And another example that includes handling of JPEGs as well: http://markasread.net/post/17551554979/get-image-size-info-using-pure-python-code
Implement INotifyPropertyChanged
in your class.
Specify a callback in the property metadata when you register the dependency property.
In the callback, raise the PropertyChanged
event.
Adding the callback:
public static DependencyProperty FirstProperty = DependencyProperty.Register(
"First",
typeof(string),
typeof(MyType),
new FrameworkPropertyMetadata(
false,
new PropertyChangedCallback(OnFirstPropertyChanged)));
Raising PropertyChanged
in the callback:
private static void OnFirstPropertyChanged(
DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
PropertyChangedEventHandler h = PropertyChanged;
if (h != null)
{
h(sender, new PropertyChangedEventArgs("Second"));
}
}
Are you using the @ symbol anywhere?
If you have something like:
@include('page_with_error.php');
You will get a blank page.
If you're on Windows, you can use kbhit()
which is part of the Microsoft run-time library. If you're on Linux, you can implement kbhit
thus (source):
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
int kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF)
{
ungetc(ch, stdin);
return 1;
}
return 0;
}
Update: The above function works on OS X (at least, on OS X 10.5.8 - Leopard, so I would expect it to work on more recent versions of OS X). This gist can be saved as kbhit.c
and compiled on both Linux and OS X with
gcc -o kbhit kbhit.c
When run with
./kbhit
It prompts you for a keypress, and exits when you hit a key (not limited to Enter or printable keys).
@Johnsyweb - please elaborate what you mean by "detailed canonical answer" and "all the concerns". Also, re "cross-platform": With this implementation of kbhit()
you can have the same functionality in a C++ program on Linux/Unix/OS X/Windows - which other platforms might you be referring to?
Further update for @Johnsyweb: C++ applications do not live in a hermetically sealed C++ environment. A big reason for C++'s success is interoperability with C. All mainstream platforms are implemented with C interfaces (even if internal implementation is using C++) so your talk of "legacy" seems out of place. Plus, as we are talking about a single function, why do you need C++ for this ("C with classes")? As I pointed out, you can write in C++ and access this functionality easily, and your application's users are unlikely to care how you implemented it.
Use the Tortoise SVN copy functionality to revert commited changes:
Hope that helps
SELECT *
FROM tbl_name
WHERE coalesce(id_field,'unik_null_value')
IN ('value1', 'value2', 'value3', 'unik_null_value')
So that you eliminate the null from the check. Given a null value in id_field, the coalesce function would instead of null return 'unik_null_value', and by adding 'unik_null_value to the IN-list, the query would return posts where id_field is value1-3 or null.
export a=$(script.sh)
Hope this helps. Note there are no spaces between variable and =. To echo the output
echo $a
a bit more smart (python 3) way:
def printvars():
tmp = globals().copy()
[print(k,' : ',v,' type:' , type(v)) for k,v in tmp.items() if not k.startswith('_') and k!='tmp' and k!='In' and k!='Out' and not hasattr(v, '__call__')]
To follow @modocache's recommendation to avoid calling view.endEditing()
, you could keep track of the text field that became first responder, but that is messy and error-prone.
An alternative is to call resignFirstResponder()
on all text fields in the viewcontroller. Here's an example of creating a collection of all text fields (which in my case was needed for validation code anyway):
@IBOutlet weak var firstName: UITextField!
@IBOutlet weak var lastName: UITextField!
@IBOutlet weak var email: UITextField!
var allTextFields: Array<UITextField>! // Forced unwrapping so it must be initialized in viewDidLoad
override func viewDidLoad()
{
super.viewDidLoad()
self.allTextFields = [self.firstName, self.lastName, self.email]
}
With the collection available, it's a simple matter to iterate through all of them:
private func dismissKeyboard()
{
for textField in allTextFields
{
textField.resignFirstResponder()
}
}
So now you can call dismissKeyboard()
in your gesture recognizer (or wherever is appropriate for you). Drawback is that you must maintain the list of UITextField
s when you add or remove fields.
Comments welcome. If there is a problem with calling resignFirstResponder()
on controls that aren't first responder, or if there's an easy and guaranteed non-buggy way to track the current first responder, I'd love to hear about it!
i have this error using datatables.net
i fixed changing the default ajax Get to POST in te properties of the DataTable()
"ajax": {
"url": "../ControllerName/MethodJson",
"type": "POST"
},
Here's a demo of the above:https://jsfiddle.net/sajadweb/mjnyLm0q/11
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
users: [{ name: 'sajadweb',email:'[email protected]' }] _x000D_
},_x000D_
methods: {_x000D_
addUser: function () {_x000D_
this.users.push({ name: '',email:'' });_x000D_
},_x000D_
deleteUser: function (index) {_x000D_
console.log(index);_x000D_
console.log(this.finds);_x000D_
this.users.splice(index, 1);_x000D_
if(index===0)_x000D_
this.addUser()_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://unpkg.com/vue/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
<h1>Add user</h1>_x000D_
<div v-for="(user, index) in users">_x000D_
<input v-model="user.name">_x000D_
<input v-model="user.email">_x000D_
<button @click="deleteUser(index)">_x000D_
delete_x000D_
</button>_x000D_
</div>_x000D_
_x000D_
<button @click="addUser">_x000D_
New User_x000D_
</button>_x000D_
_x000D_
<pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
You can use this simple code for rate your app in your activity.
try {
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
You're looking for the Skip
and Take
extension methods. Skip
moves past the first N elements in the result, returning the remainder; Take
returns the first N elements in the result, dropping any remaining elements.
See MSDN for more information on how to use these methods: http://msdn.microsoft.com/en-us/library/bb386988.aspx
Assuming you are already taking into account that the pageNumber should start at 0 (decrease per 1 as suggested in the comments) You could do it like this:
int numberOfObjectsPerPage = 10;
var queryResultPage = queryResult
.Skip(numberOfObjectsPerPage * pageNumber)
.Take(numberOfObjectsPerPage);
Otherwise as suggested by @Alvin
int numberOfObjectsPerPage = 10;
var queryResultPage = queryResult
.Skip(numberOfObjectsPerPage * (pageNumber - 1))
.Take(numberOfObjectsPerPage);
The heading looks bold because of its large size, if you have applied bold or want to change behaviour, you can do:
h1 { font-weight:normal; }
Starting in Python 2.6, there is an alternative: the str.format()
method. Here are some examples using the existing string format operator (%
):
>>> "Name: %s, age: %d" % ('John', 35)
'Name: John, age: 35'
>>> i = 45
>>> 'dec: %d/oct: %#o/hex: %#X' % (i, i, i)
'dec: 45/oct: 055/hex: 0X2D'
>>> "MM/DD/YY = %02d/%02d/%02d" % (12, 7, 41)
'MM/DD/YY = 12/07/41'
>>> 'Total with tax: $%.2f' % (13.00 * 1.0825)
'Total with tax: $14.07'
>>> d = {'web': 'user', 'page': 42}
>>> 'http://xxx.yyy.zzz/%(web)s/%(page)d.html' % d
'http://xxx.yyy.zzz/user/42.html'
Here are the equivalent snippets but using str.format()
:
>>> "Name: {0}, age: {1}".format('John', 35)
'Name: John, age: 35'
>>> i = 45
>>> 'dec: {0}/oct: {0:#o}/hex: {0:#X}'.format(i)
'dec: 45/oct: 0o55/hex: 0X2D'
>>> "MM/DD/YY = {0:02d}/{1:02d}/{2:02d}".format(12, 7, 41)
'MM/DD/YY = 12/07/41'
>>> 'Total with tax: ${0:.2f}'.format(13.00 * 1.0825)
'Total with tax: $14.07'
>>> d = {'web': 'user', 'page': 42}
>>> 'http://xxx.yyy.zzz/{web}/{page}.html'.format(**d)
'http://xxx.yyy.zzz/user/42.html'
Like Python 2.6+, all Python 3 releases (so far) understand how to do both. I shamelessly ripped this stuff straight out of my hardcore Python intro book and the slides for the Intro+Intermediate Python courses I offer from time-to-time. :-)
Aug 2018 UPDATE: Of course, now that we have the f-string feature in 3.6, we need the equivalent examples of that, yes another alternative:
>>> name, age = 'John', 35
>>> f'Name: {name}, age: {age}'
'Name: John, age: 35'
>>> i = 45
>>> f'dec: {i}/oct: {i:#o}/hex: {i:#X}'
'dec: 45/oct: 0o55/hex: 0X2D'
>>> m, d, y = 12, 7, 41
>>> f"MM/DD/YY = {m:02d}/{d:02d}/{y:02d}"
'MM/DD/YY = 12/07/41'
>>> f'Total with tax: ${13.00 * 1.0825:.2f}'
'Total with tax: $14.07'
>>> d = {'web': 'user', 'page': 42}
>>> f"http://xxx.yyy.zzz/{d['web']}/{d['page']}.html"
'http://xxx.yyy.zzz/user/42.html'
android:inputMethod
is deprecated, instead use inputType
:
android:inputType="numberPassword"
You could try looping until the line you want, not the EOF, and resetting the variable to the line each time (not adding to it). In your case, the 2nd line is the EOF. (A for loop is probably more appropriate in my code below).
This way the entire file is not in the memory; the drawback is it takes time to go through the file up to the point you want.
<?php
$myFile = "4-24-11.txt";
$fh = fopen($myFile, 'r');
$i = 0;
while ($i < 2)
{
$theData = fgets($fh);
$i++
}
fclose($fh);
echo $theData;
?>
In case you are using Typescript, I'd like to add that you can use the "type predicate" feature. Just should wrap the logical verification in a function that returns x is Promise<any>
and you won't need to do typecasts. Below on my example, c
is either a promise or one of my types which I want to convert into a promise by calling the c.fetch()
method.
export function toPromise(c: Container<any> | Promise<any>): Promise<any> {
if (c == null) return Promise.resolve();
return isContainer(c) ? c.fetch() : c;
}
export function isContainer(val: Container<any> | Promise<any>): val is Container<any> {
return val && (<Container<any>>val).fetch !== undefined;
}
export function isPromise(val: Container<any> | Promise<any>): val is Promise<any> {
return val && (<Promise<any>>val).then !== undefined;
}
More info: https://www.typescriptlang.org/docs/handbook/advanced-types.html
Most answers are surprisingly complicated or erroneous. However simple and robust examples have been posted elsewhere [codereview]. Admittedly the options provided by the gnu preprocessor are a bit confusing. However, the removal of all directories from the build target with -MM
is documented and not a bug [gpp]:
By default CPP takes the name of the main input file, deletes any directory components and any file suffix such as ‘.c’, and appends the platform's usual object suffix.
The (somewhat newer) -MMD
option is probably what you want. For completeness an example of a makefile that supports multiple src dirs and build dirs with some comments. For a simple version without build dirs see [codereview].
CXX = clang++
CXX_FLAGS = -Wfatal-errors -Wall -Wextra -Wpedantic -Wconversion -Wshadow
# Final binary
BIN = mybin
# Put all auto generated stuff to this build dir.
BUILD_DIR = ./build
# List of all .cpp source files.
CPP = main.cpp $(wildcard dir1/*.cpp) $(wildcard dir2/*.cpp)
# All .o files go to build dir.
OBJ = $(CPP:%.cpp=$(BUILD_DIR)/%.o)
# Gcc/Clang will create these .d files containing dependencies.
DEP = $(OBJ:%.o=%.d)
# Default target named after the binary.
$(BIN) : $(BUILD_DIR)/$(BIN)
# Actual target of the binary - depends on all .o files.
$(BUILD_DIR)/$(BIN) : $(OBJ)
# Create build directories - same structure as sources.
mkdir -p $(@D)
# Just link all the object files.
$(CXX) $(CXX_FLAGS) $^ -o $@
# Include all .d files
-include $(DEP)
# Build target for every single object file.
# The potential dependency on header files is covered
# by calling `-include $(DEP)`.
$(BUILD_DIR)/%.o : %.cpp
mkdir -p $(@D)
# The -MMD flags additionaly creates a .d file with
# the same name as the .o file.
$(CXX) $(CXX_FLAGS) -MMD -c $< -o $@
.PHONY : clean
clean :
# This should remove all generated files.
-rm $(BUILD_DIR)/$(BIN) $(OBJ) $(DEP)
This method works because if there are multiple dependency lines for a single target, the dependencies are simply joined, e.g.:
a.o: a.h
a.o: a.c
./cmd
is equivalent to:
a.o: a.c a.h
./cmd
as mentioned at: Makefile multiple dependency lines for a single target?
Thanks to @LyphTEC that gave a very interesting way to open an Office file in edit mode!
It gave me the idea to change the function _DispEx
that is called when the user clicks on a file into a document library. By hacking the original function we can them be able to open a dialog (for Firefox/Chrome) and ask the user if he/she wants to readonly or edit the file:
See below the JavaScript code I used. My code is for Excel files, but it could be modified to work with Word documents too:
/**
* fix problem with Excel documents on Firefox/Chrome (see https://blog.kodono.info/wordpress/2017/02/09/how-to-open-an-excel-document-from-sharepoint-files-into-chromefirefox-in-readonlyedit-mode/)
* @param {HTMLElement} p the <A> element
* @param {HTMLEvent} a the click event
* @param {Boolean} h TRUE
* @param {Boolean} e FALSE
* @param {Boolean} g FALSE
* @param {Strin} k the ActiveX command (e.g. "SharePoint.OpenDocuments.3")
* @param {Number} c 0
* @param {String} o the activeX command, here we look at "SharePoint.OpenDocuments"
* @param {String} m
* @param {String} b the replacement URL to the xslviewer
*/
var bak_DispEx;
var modalOpenDocument; // it will be use with the modal
SP.SOD.executeOrDelayUntilEventNotified(function() {
bak_DispEx = _DispEx;
_DispEx=function(p, a, h, e, g, k, c, o, m, b, j, l, i, f, d) {
// if o==="SharePoint.OpenDocuments" && !IsClientAppInstalled(o)
// in that case we want to open ask the user if he/she wants to readonly or edit the file
var fileURL = b.replace(/.*_layouts\/xlviewer\.aspx\?id=(.*)/, "$1");
if (o === "SharePoint.OpenDocuments" && !IsClientAppInstalled(o) && /\.xlsx?$/.test(fileURL)) {
// if the URL doesn't start with http
if (!/^http/.test(fileURL)) {
fileURL = window.location.protocol + "//" + window.location.host + fileURL;
}
var ohtml = document.createElement('div');
ohtml.style.padding = "10px";
ohtml.style.display = "inline-block";
ohtml.style.width = "200px";
ohtml.style.width = "200px";
ohtml.innerHTML = '<style>'
+ '.opendocument_button { background-color:#fdfdfd; border:1px solid #ababab; color:#444; display:inline-block; padding: 7px 10px; }'
+ '.opendocument_button:hover { box-shadow: none }'
+ '#opendocument_readonly,#opendocument_edit { float:none; font-size: 100%; line-height: 1.15; margin: 0; overflow: visible; box-sizing: border-box; padding: 0; height:auto }'
+ '.opendocument_ul { list-style-type:none;margin-top:10px;margin-bottom:10px;padding-top:0;padding-bottom:0 }'
+ '</style>'
+ 'You are about to open:'
+ '<ul class="opendocument_ul">'
+ ' <li>Name: <b>'+fileURL.split("/").slice(-1)+'</b></li>'
+ ' <li>From: <b>'+window.location.hostname+'</b></li>'
+ '</ul>'
+ 'How would like to open this file?'
+ '<ul class="opendocument_ul">'
+ ' <li><label><input type="radio" name="opendocument_choices" id="opendocument_readonly" checked> Read Only</label></li>'
+ ' <li><label><input type="radio" name="opendocument_choices" id="opendocument_edit"> Edit</label></li>'
+ '</ul>'
+ '<div style="text-align: center;margin-top: 20px;"><button type="button" class="opendocument_button" style="background-color: #2d9f2d;color: #fff;" onclick="modalOpenDocument.close(document.getElementById(\'opendocument_edit\').checked)">Open</button> <button type="button" class="opendocument_button" style="margin-left:10px" onclick="modalOpenDocument.close(-1)">Cancel</button></div>';
// show the modal
modalOpenDocument=SP.UI.ModalDialog.showModalDialog({
html:ohtml,
dialogReturnValueCallback:function(ret) {
if (ret!==-1) {
if (ret === true) { // edit
// reformat the fileURL
var ext;
if (/\.xlsx?$/.test(b)) ext = "ms-excel";
if (/\.docx?$/.test(b)) ext = "ms-word"; // not currently supported
fileURL = ext + ":ofe|u|" + fileURL;
}
window.location.href = fileURL; // open the file
}
}
});
a.preventDefault();
a.stopImmediatePropagation()
a.cancelBubble = true;
a.returnValue = false;
return false;
}
return bak_DispEx.apply(this, arguments);
}
}, "sp.scriptloaded-core.js")
I use SP.SOD.executeOrDelayUntilEventNotified
to make sure the function will be executed when core.js
is loaded.
They're called favicons, and are quite easy to make/use. Have a read of http://www.favicon.com/ for help.
PowerShell 3 has the $PSScriptRoot
automatic variable:
Contains the directory from which a script is being run.
In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.
Don't be fooled by the poor wording. PSScriptRoot
is the directory of the current file.
In PowerShell 2, you can calculate the value of $PSScriptRoot
yourself:
# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
The answer below is apparently obsolete now, but works with older drivers. See comments.
If you have the connection string you could also use MongoDatabase directly:
var db = MongoDatabase.Create(connectionString);
var coll = db.GetCollection("MyCollection");
It doesn't do anything -- the under/overflow just happens.
A "-1" that is the result of a computation that overflowed is no different from the "-1" that resulted from any other information. So you can't tell via some status or by inspecting just a value whether it's overflowed.
But you can be smart about your computations in order to avoid overflow, if it matters, or at least know when it will happen. What's your situation?
You can supply your own class to the nav-pills
container with your custom color for your active link, that way you can create as many colors as you like without modifying the bootstrap default colors in other sections of your page. Try this:
Markup
<ul class="nav nav-pills red">
<li class="active"><a href="#tab1" data-toggle="tab">Overview</a></li>
<li><a href="#tab2" data-toggle="tab">Sample</a></li>
<li><a href="#tab3" data-toggle="tab">Sample</a></li>
</ul>
And here is the CSS for your custom color:
.red .active a,
.red .active a:hover {
background-color: red;
}
Also, if you prefer to replace the default color for the .active
item in your nav-pills
you can modify the original like so:
.nav-pills > .active > a, .nav-pills > .active > a:hover {
background-color: red;
}
If you are using Reactive form you can set it to default like this:
In the form model, set the value to false. So if it's checked its value will be true else false
let form = this.formBuilder.group({
is_known: [false]
})
//In HTML
<mat-checkbox matInput formControlName="is_known">Known</mat-checkbox>
For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.
$s = '1234.13';
$double = bcadd($s,'0',2);
To copy conditional formatting from google spreadsheet (doc1) to another (doc2) you need to do the following:
According to w3.org (note that this link is in the long-expired draft HTML 3.0 spec):
An unordered list typically is a bulleted list of items. HTML 3.0 gives you the ability to customise the bullets, to do without bullets and to wrap list items horizontally or vertically for multicolumn lists.
The opening list tag must be
<UL>
. It is followed by an optional list header (<LH>
caption</LH>
) and then by the first list item (<LI>
). For example:<UL> <LH>Table Fruit</LH> <LI>apples <LI>oranges <LI>bananas </UL>
which could be rendered as:
Table Fruit
- apples
- oranges
- bananas
Note: Some legacy documents may include headers or plain text before the first LI element. Implementors of HTML 3.0 user agents are advised to cater for this possibility in order to handle badly formed legacy documents.
The most effective solution that I found is to define the parent element with display:flex
and align-items:center
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.myclass{
display:flex;
align-items:center;
background-color:grey;
color:#fff;
height:50px;
}
</style>
</head>
<body>
<div class="myclass">
<input type="checkbox">
<label>do you love Ananas?
</label>
</div>
</body>
</html>
OUTPUT:
You can just call the Execute command.
EXEC spDoSomthing @myDate
Edit:
Since you want to return data..that's a little harder. You can use user defined functions instead that return data.
The best way to do this is to have your files zipped and link to that:
The other solution can be found here: How to make a link open multiple pages when clicked
Which states the following:
HTML:
<a href="#" class="yourlink">Download</a>
JS:
$('a.yourlink').click(function(e) {
e.preventDefault();
window.open('mysite.com/file1');
window.open('mysite.com/file2');
window.open('mysite.com/file3');
});
Having said this, I would still go with zipping the file, as this implementation requires JavaScript and can also sometimes be blocked as popups.
In Java side, the date is usually represented by the (poorly designed, but that aside) java.util.Date
. It is basically backed by the Epoch time in flavor of a long
, also known as a timestamp. It contains information about both the date and time parts. In Java, the precision is in milliseconds.
In SQL side, there are several standard date and time types, DATE
, TIME
and TIMESTAMP
(at some DB's also called DATETIME
), which are represented in JDBC as java.sql.Date
, java.sql.Time
and java.sql.Timestamp
, all subclasses of java.util.Date
. The precision is DB dependent, often in milliseconds like Java, but it can also be in seconds.
In contrary to java.util.Date
, the java.sql.Date
contains only information about the date part (year, month, day). The Time
contains only information about the time part (hours, minutes, seconds) and the Timestamp
contains information about the both parts, like as java.util.Date
does.
The normal practice to store a timestamp in the DB (thus, java.util.Date
in Java side and java.sql.Timestamp
in JDBC side) is to use PreparedStatement#setTimestamp()
.
java.util.Date date = getItSomehow();
Timestamp timestamp = new Timestamp(date.getTime());
preparedStatement = connection.prepareStatement("SELECT * FROM tbl WHERE ts > ?");
preparedStatement.setTimestamp(1, timestamp);
The normal practice to obtain a timestamp from the DB is to use ResultSet#getTimestamp()
.
Timestamp timestamp = resultSet.getTimestamp("ts");
java.util.Date date = timestamp; // You can just upcast.
If you are using qmake, the standard Qt build system, just add a line to the .pro
file as documented in the qmake Variable Reference:
INCLUDEPATH += <your path>
If you are using your own build system, you create a project by selecting "Import of Makefile-based project". This will create some files in your project directory including a file named <your project name>.includes
. In that file, simply list the paths you want to include, one per line. Really all this does is tell Qt Creator where to look for files to index for auto completion. Your own build system will have to handle the include paths in its own way.
As explained in the Qt Creator Manual, <your path>
must be an absolute path, but you can avoid OS-, host- or user-specific entries in your .pro
file by using $$PWD
which refers to the folder that contains your .pro
file, e.g.
INCLUDEPATH += $$PWD/code/include
Just change your syntax ever so slightly:
CASE WHEN STATE = 2 AND RetailerProcessType = 1 THEN '"AUTHORISED"'
WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
WHEN STATE = 2 AND RetailerProcessType = 2 THEN '"AUTHORISED"'
ELSE '"DECLINED"'
END
If you don't put the field expression before the CASE
statement, you can put pretty much any fields and comparisons in there that you want. It's a more flexible method but has slightly more verbose syntax.
I had these choices:
-----------------------------------------------
* 1 /usr/lib/jvm/jre-1.6.0-openjdk.x86_64/bin/java
+ 2 /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
3 /home/ec2-user/local/java/jre1.7.0_25/bin/java
When I chose 3, it didn't work. When I chose 2, it did work.
What you show, ('A','B','C','D','E')
, is not a list
, it's a tuple
(the round parentheses instead of square brackets show that). Nevertheless, whether it to index a list or a tuple (for getting one item at an index), in either case you append the index in square brackets.
So:
thetuple = ('A','B','C','D','E')
print thetuple[0]
prints A
, and so forth.
Tuples (differently from lists) are immutable, so you couldn't assign to thetuple[0]
etc (as you could assign to an indexing of a list). However you can definitely just access ("get") the item by indexing in either case.
The template it is referring to is the Html helper DisplayFor
.
DisplayFor expects to be given an expression that conforms to the rules as specified in the error message.
You are trying to pass in a method chain to be executed and it doesn't like it.
This is a perfect example of where the MVVM (Model-View-ViewModel) pattern comes in handy.
You could wrap up your Trainer
model class in another class called TrainerViewModel
that could work something like this:
class TrainerViewModel
{
private Trainer _trainer;
public string ShortDescription
{
get
{
return _trainer.Description.ToString().Substring(0, 100);
}
}
public TrainerViewModel(Trainer trainer)
{
_trainer = trainer;
}
}
You would modify your view model class to contain all the properties needed to display that data in the view, hence the name ViewModel.
Then you would modify your controller to return a TrainerViewModel
object rather than a Trainer
object and change your model type declaration in your view file to TrainerViewModel
too.
You could just simply write but you have to use JavaScript regardless.
Page.ClientScript.RegisterStartupScript(Page.GetType(), "Message Box", "<script language = 'javascript'>alert('dd')</script>");
You can match those three groups separately, and make sure that they all present. Also, [^\w]
seems a bit too broad, but if that's what you want you might want to replace it with \W
.
For some instrutions, like ALTER TABLE, this is not possible with MySQL, even with transactions (1 and 2).
What I did was;
1 - I first find out what version of PHP I am using thru the function phpinfo()
<?php
phpinfo();
?>
2 - From there you will find the location of your configuration(php.ini) file
3 - Open that file
4 - Comment out the line similar to the image below
This might be a different value but it should be related to extension. I am no expert but this process helped me solved similar problem.
You could also disable the cascade delete convention in global scope of your application by doing this:
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>()
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>()
Actually is quite easy with this option at the end:
c:\start BATCH.bat -WindowStyle Hidden
If your computer is on a domain, you can see Windows Password Rescuer Advanced, http://www.daossoft.com/documents/how-to-reset-windows-domian-account-password.html
You can do this:
class MyStudentDetails{
public static void main (String args[]){
Scanner s = new Scanner(System.in);
System.out.println("Enter Your Name: ");
String name = s.nextLine();
System.out.println("Enter Your Age: ");
String age = s.nextLine();
System.out.println("Enter Your E-mail: ");
String email = s.nextLine();
System.out.println("Enter Your Address: ");
String address = s.nextLine();
System.out.println("Name: "+name);
System.out.println("Age: "+age);
System.out.println("E-mail: "+email);
System.out.println("Address: "+address);
}
}
Here is my 2 cents. Create an empty invisible div. Fill it with the input content and return the width to the input field. Match text styles between each box.
$(".answers_number").keyup(function(){_x000D_
$( "#number_box" ).html( $( this ).val() );_x000D_
$( this ).animate({_x000D_
width: $( "#number_box" ).width()+20_x000D_
}, 300, function() {_x000D_
});_x000D_
});
_x000D_
#number_box {_x000D_
position: absolute;_x000D_
visibility: hidden;_x000D_
height: auto;_x000D_
width: auto;_x000D_
white-space: nowrap;_x000D_
padding:0 4px;_x000D_
/*Your font styles to match input*/_x000D_
font-family:Arial;_x000D_
font-size: 30px; _x000D_
}_x000D_
_x000D_
.answers_number {_x000D_
font-size: 30px; _x000D_
font-family:Arial;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="number" class="answers_number" />_x000D_
<div id="number_box">_x000D_
</div>
_x000D_
I think there is a simpler way:
public async Task<string> CreateSoapEnvelope()
{
string soapString = @"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
<soap:Body>
<HelloWorld xmlns=""http://tempuri.org/"" />
</soap:Body>
</soap:Envelope>";
HttpResponseMessage response = await PostXmlRequest("your_url_here", soapString);
string content = await response.Content.ReadAsStringAsync();
return content;
}
public static async Task<HttpResponseMessage> PostXmlRequest(string baseUrl, string xmlString)
{
using (var httpClient = new HttpClient())
{
var httpContent = new StringContent(xmlString, Encoding.UTF8, "text/xml");
httpContent.Headers.Add("SOAPAction", "http://tempuri.org/HelloWorld");
return await httpClient.PostAsync(baseUrl, httpContent);
}
}
TLDR; The best I can come up with is this: (Depending on your use case, there are a number of ways to optimize this function.)
function arrayIndexExists(array, index){
if ( typeof index !== 'number' && index === parseInt(index).toString()) {
index = parseInt(index);
} else {
return false;//to avoid checking typeof again
}
return typeof index === 'number' && index % 1===0 && index >= 0 && array.hasOwnKey(index);
}
The other answer's examples get close and will work for some (probably most) purposes, but are technically quite incorrect for reasons I explain below.
Javascript arrays only use 'numerical' keys. When you set an "associative key" on an array, you are actually setting a property on that array object, not an element of that array. For example, this means that the "associative key" will not be iterated over when using Array.forEach() and will not be included when calculating Array.length. (The exception for this is strings like '0' will resolve to an element of the array, but strings like ' 0' won't.)
Additionally, checking array element or object property that doesn't exist does evaluate as undefined, but that doesn't actually tell you that the array element or object property hasn't been set yet. For example, undefined is also the result you get by calling a function that doesn't terminate with a return statement. This could lead to some strange errors and difficulty debugging code.
This can be confusing, but can be explored very easily using your browser's javascript console. (I used chrome, each comment indicates the evaluated value of the line before it.);
var foo = new Array();
foo;
//[]
foo.length;
//0
foo['bar'] = 'bar';
//"bar"
foo;
//[]
foo.length;
//0
foo.bar;
//"bar"
This shows that associative keys are not used to access elements in the array, but for properties of the object.
foo[0] = 0;
//0
foo;
//[0]
foo.length;
//1
foo[2] = undefined
//undefined
typeof foo[2]
//"undefined"
foo.length
//3
This shows that checking typeof doesn't allow you to see if an element has been set.
var foo = new Array();
//undefined
foo;
//[]
foo[0] = 0;
//0
foo['0']
//0
foo[' 0']
//undefined
This shows the exception I mentioned above and why you can't just use parseInt();
If you want to use associative arrays, you are better off using simple objects as other answers have recommended.
In the interest of providing a different answer from the ones above; you could check it with Object.hasOwnProperty(...)
like this:
if( $("#dataTable").data().hasOwnProperty("timer") ){
// the data-time property exists, now do you business! .....
}
alternatively, if you have multiple data elements you want to iterate over you can variablize the .data()
object and iterate over it like this:
var objData = $("#dataTable").data();
for ( data in objData ){
if( data == 'timer' ){
//...do the do
}
}
Not saying this solution is better than any of the other ones in here, but at least it's another approach...
You have to execute your query and add single quote to $email in the query beacuse it's a string, and remove the is_resource($query)
$query is a string, the $result will be the resource
$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($link,$query); //$link is the connection
if(mysqli_num_rows($result) > 0 ){....}
UPDATE
Base in your edit just change:
if(is_resource($query) && mysqli_num_rows($query) > 0 ){
$query = mysqli_fetch_assoc($query);
echo $email . " email exists " . $query["email"] . "\n";
By
if(is_resource($result) && mysqli_num_rows($result) == 1 ){
$row = mysqli_fetch_assoc($result);
echo $email . " email exists " . $row["email"] . "\n";
and you will be fine
UPDATE 2
A better way should be have a Store Procedure that execute the following SQL passing the Email as Parameter
SELECT IF( EXISTS (
SELECT *
FROM `Table`
WHERE `email` = @Email)
, 1, 0) as `Exist`
and retrieve the value in php
Pseudocodigo:
$query = Call MYSQL_SP($EMAIL);
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result)
$exist = ($row['Exist']==1)? 'the email exist' : 'the email doesnt exist';
Here is what you do in Excel 2003:
Here is what you do in Excel 2007:
Once this is done, the sheet is hidden and cannot be unhidden without the password. Make sense?
If you really need to keep some calculations secret, try this: use Access (or another Excel workbook or some other DB of your choice) to calculate what you need calculated, and export only the "unclassified" results to your Excel workbook.
Function-instantiation is allowed inside and outside of functions. Inside those functions, just like variables, the nested functions are local and therefore cannot be obtained from the outside scope.
function foo() {
function bar() {
return 1;
}
return bar();
}
foo
manipulates bar
within itself. bar
cannot be touched from the outer scope unless it is defined in the outer scope.
So this will not work:
function foo() {
function bar() {
return 1;
}
}
bar(); // throws error: bar is not defined
To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.
class YourClass():
def your_function(self, *args):
self.callable_function(param) # if you need to pass any parameter
def callable_function(self, *params):
print('Your param:', param)
With quotes around the date:
mysql> CALL insertEvent('2012.01.01 12:12:12');
All you have to do to run a js file via bash is type:
$ node filename.js
This is similar to in python, when you do:
$ python filename.py
Just for fun, I wanted to build off of Ian Henry's answer.
Of course var array = new Array(N);
will give you an array of size N
, but the keys and values will be identical.... then to shorten the array to size M
, use array.length = M
.... but for some added functionality try:
function range()
{
// This function takes optional arguments:
// start, end, increment
// start may be larger or smaller than end
// Example: range(null, null, 2);
var array = []; // Create empty array
// Get arguments or set default values:
var start = (arguments[0] ? arguments[0] : 0);
var end = (arguments[1] ? arguments[1] : 9);
// If start == end return array of size 1
if (start == end) { array.push(start); return array; }
var inc = (arguments[2] ? Math.abs(arguments[2]) : 1);
inc *= (start > end ? -1 : 1); // Figure out which direction to increment.
// Loop ending condition depends on relative sizes of start and end
for (var i = start; (start < end ? i <= end : i >= end) ; i += inc)
array.push(i);
return array;
}
var foo = range(1, -100, 8.5)
for(var i=0;i<foo.length;i++){
document.write(foo[i] + ' is item: ' + (i+1) + ' of ' + foo.length + '<br/>');
}?
Output of the above:
1 is item: 1 of 12
-7.5 is item: 2 of 12
-16 is item: 3 of 12
-24.5 is item: 4 of 12
-33 is item: 5 of 12
-41.5 is item: 6 of 12
-50 is item: 7 of 12
-58.5 is item: 8 of 12
-67 is item: 9 of 12
-75.5 is item: 10 of 12
-84 is item: 11 of 12
-92.5 is item: 12 of 12
This function makes use of the automatically generated arguments
array.
The function creates an array filled with values beginning at start
and ending at end
with increments of size increment
, where
range(start, end, increment);
Each value has a default and the sign of the increment doesn't matter, since the direction of incrementation depends on the relative sizes of start and end.
I would advise against using """
for multi line comments!
Here is a simple example to highlight what might be considered an unexpected behavior:
print('{}\n{}'.format(
'I am a string',
"""
Some people consider me a
multi-line comment, but
"""
'clearly I am also a string'
)
)
Now have a look at the output:
I am a string
Some people consider me a
multi-line comment, but
clearly I am also a string
The multi line string was not treated as comment, but it was concatenated with 'clearly I'm also a string'
to form a single string.
If you want to comment multiple lines do so according to PEP 8 guidelines:
print('{}\n{}'.format(
'I am a string',
# Some people consider me a
# multi-line comment, but
'clearly I am also a string'
)
)
Output:
I am a string
clearly I am also a string
Please be careful not to overwrite the ";secure" cookie flag in https-sessions. This flag prevents the browser from sending the cookie over an unencrypted http connection, basically rendering the use of https for legit requests pointless.
private void rewriteCookieToHeader(HttpServletRequest request, HttpServletResponse response) {
if (response.containsHeader("SET-COOKIE")) {
String sessionid = request.getSession().getId();
String contextPath = request.getContextPath();
String secure = "";
if (request.isSecure()) {
secure = "; Secure";
}
response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid
+ "; Path=" + contextPath + "; HttpOnly" + secure);
}
}
If you need to update a property in the request, I recommend you to use the replace method from Request class used by Laravel
$request->replace(['property to update' => $newValue]);
If you are trying to login with SQL credentials, you can also try changing the LoginMode for SQL Server in the registry to allow both SQL Server and Windows Authentication.
I know this is an old post but just for reference. Here is how to append without the special case check for an empty list, although at the expense of more complex looking code.
void Append(List * l, Node * n)
{
Node ** next = &list->Head;
while (*next != NULL) next = &(*next)->Next;
*next = n;
n->Next = NULL;
}
You can do it in this way
private EditText nameEdit;
private EditText emailEdit;
private String nameDefaultValue = "Your Name";
private String emailDefaultValue = "[email protected]";
and inside onCreate method
nameEdit = (EditText) findViewById(R.id.name);
nameEdit.setText(nameDefaultValue);
nameEdit.setOnTouchListener( new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (nameEdit.getText().toString().equals(nameDefaultValue)){
nameEdit.setText("");
}
return false;
}
});
nameEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus && TextUtils.isEmpty(nameEdit.getText().toString())){
nameEdit.setText(nameDefaultValue);
} else if (hasFocus && nameEdit.getText().toString().equals(nameDefaultValue)){
nameEdit.setText("");
}
}
});
emailEdit = (EditText)findViewById(R.id.email);
emailEdit.setText(emailDefaultValue);
emailEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus && TextUtils.isEmpty(emailEdit.getText().toString())){
emailEdit.setText(emailDefaultValue);
} else if (hasFocus && emailEdit.getText().toString().equals(emailDefaultValue)){
emailEdit.setText("");
}
}
});
Instead of using the "c" tags, you could also do the following:
<h:outputLink value="Images/thumb_02.jpg" target="_blank" rendered="#{not empty user or user.userId eq 0}" />
<h:graphicImage value="Images/thumb_02.jpg" rendered="#{not empty user or user.userId eq 0}" />
<h:outputLink value="/DisplayBlobExample?userId=#{user.userId}" target="_blank" rendered="#{not empty user and user.userId neq 0}" />
<h:graphicImage value="/DisplayBlobExample?userId=#{user.userId}" rendered="#{not empty user and user.userId neq 0}"/>
I think that's a little more readable alternative to skuntsel's alternative answer and is utilizing the JSF rendered attribute instead of nesting a ternary operator. And off the answer, did you possibly mean to put your image in between the anchor tags so the image is clickable?
You can use CURL for this purpose see the example code:
$url = "your url";
$content = json_encode("your data to be sent");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
Observations:
#include <cstring>
should introduce std::strcpy().using namespace std;
(as written in medico.h) introduces any identifiers from std::
into the global namespace.Aside from using namespace std;
being somewhat clumsy once the application grows larger (as it introduces one hell of a lot of identifiers into the global namespace), and that you should never use using
in a header file (see below!), using namespace
does not affect identifiers introduced after the statement.
(using namespace std
is written in the header, which is included in medico.cpp, but #include <cstring>
comes after that.)
My advice: Put the using namespace std;
(if you insist on using it at all) into medico.cpp, after any includes, and use explicit std::
in medico.h.
strcmpi()
is not a standard function at all; while being defined on Windows, you have to solve case-insensitive compares differently on Linux.
(On general terms, I would like to point to this answer with regards to "proper" string handling in C and C++ that takes Unicode into account, as every application should. Summary: The standard cannot handle these things correctly; do use ICU.)
warning: deprecated conversion from string constant to ‘char*’
A "string constant" is when you write a string literal (e.g. "Hello"
) in your code. Its type is const char[]
, i.e. array of constant characters (as you cannot change the characters). You can assign an array to a pointer, but assigning to char *
, i.e. removing the const
qualifier, generates the warning you are seeing.
OT clarification: using
in a header file changes visibility of identifiers for anyone including that header, which is usually not what the user of your header file wants. For example, I could use std::string
and a self-written ::string
just perfectly in my code, unless I include your medico.h, because then the two classes will clash.
Don't use using
in header files.
And even in implementation files, it can introduce lots of ambiguity. There is a case to be made to use explicit namespacing in implementation files as well.
Blockquote
Using concatenation in Oracle SQL is very easy and interesting. But don't know much about MS-SQL.
Blockquote
Here we go for Oracle :
Syntax:
SQL> select First_name||Last_Name as Employee
from employees;
EllenAbel SundarAnde MozheAtkinson
Here AS: keyword used as alias. We can concatenate with NULL values. e.g. : columnm1||Null
Suppose any of your columns contains a NULL value then the result will show only the value of that column which has value.
You can also use literal character string in concatenation.
e.g.
select column1||' is a '||column2
from tableName;
Result: column1 is a column2.
in between literal should be encolsed in single quotation. you cna exclude numbers.
NOTE: This is only for oracle server//SQL.
Here is my solution:
DataTable datatable = (DataTable)dataset.datatablename;
I followed the most of the answers which was recommended here. First I got the following error:
fatal: unable to access 'https://github.com/folder/sample.git/': schannel: next InitializeSecurityContext failed: Unknown error (0x80092012) - The revocation function was unable to check revocation for the certificate.
Then I have tried the following command by @Salim Hamidi
git config --global http.proxy http://proxyuser:[email protected]:8080
But I got the following error:
fatal: unable to access 'https://github.com/folder/sample.git/': Received HTTP code 407 from proxy after CONNECT
This could happen if the proxy server can't verify the SSL certificate. So we want to make sure that the ssl verification is off (not recommended for non trusted sites), so I have done the following steps which was recommended by @Arpit but with slight changes:
1.First make sure to remove any previous proxy settings:
git config --global --unset http.proxy
2.Then list and get the gitconfig content
git config --list --show-origin
3.Last update the content of the gitconfig file as below:
[http]
sslCAInfo = C:/yourfolder/AppData/Local/Programs/Git/mingw64/ssl/certs/ca-bundle.crt
sslBackend = schannel
proxy = http://proxyuser:[email protected]:8080
sslverify = false
[https]
proxy = http://proxyuser:[email protected]:8080
sslverify = false
Here's your problem:
int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
Latitude and Longitude are double
-values, because they represent the location in degrees.
By casting them to int
, you're discarding everything behind the comma, which makes a big difference. See "Decimal Degrees - Wiki"
It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.
<input id="myFileInput" type="file" accept="image/*;capture=camera">
var myInput = document.getElementById('myFileInput');
function sendPic() {
var file = myInput.files[0];
// Send file here either by adding it to a `FormData` object
// and sending that via XHR, or by simply passing the file into
// the `send` method of an XHR instance.
}
myInput.addEventListener('change', sendPic, false);
shouldn't you use "file://C:/localfile.jpg" instead of "C:/localfile.jpg"?
Great answers here. If you're looking for the default view "Store Name" set in the Magento configuration:
Mage::app()->getStore()->getFrontendName()
Okay, oninvalid works well but it shows error even if user entered valid data. So I have used below to tackle it, hope it will work for you as well,
oninvalid="this.setCustomValidity('Your custom message.')"
onkeyup="setCustomValidity('')"
It would be much better to realize that talking of physical lines of code is pretty meaningless. The number of physical Lines of Code (LoC) is so dependent on the coding style that it can vary of an order of magnitude from one developer to another one.
In the .NET world there are a convenient way to count the LoC. Sequence point. A sequence point is a unit of debugging, it is the code portion highlighted in dark-red when putting a break point. With sequence point we can talk of logical LoC, and this metric can be compared across various .NET languages. The logical LoC code metric is supported by most .NET tools including VisualStudio code metric, NDepend or NCover.
For example, here is a 8 LoC method (beginning and ending brackets sequence points are not taken account):
The production of LoC must be counted in the long term. Some days you'll spit more than 200 LoC, some others days you'll spend 8 hours fixing a bug by not even adding a single LoC. Some days you'll clean dead code and will remove LoC, some days you'll spend all your time refactoring existing code and not adding any new LoC to the total.
Personally, I count a single LoC in my own productivity score only when:
In this condition, my personal score over the last 5 years coding the NDepend tool for .NET developers is an average of 80 physical LoC per day without sacrificing by any mean the code quality. The rhythm is sustained and I don't see it decreased any time soon. All in all, NDepend is a C# code base that currently weights around 115K physical LoC
For those who hates counting LoC (I saw many of them in comments here), I attest that once adequately calibrated, counting LoC is an excellent estimation tool. After coding and measuring dozens of features achieved in my particular context of development, I reached the point where I can estimate precisely the size of any TODO feature in LoC, and the time it'll take me to deliver it to production.
I had a similar problem and it was caused by the placement of the Timer initialisation.
It was placed in a method that was invoked oftener.
Try this:
Timer waitTimer;
void exampleMethod() {
if (waitTimer == null ) {
//initialize your Timer here
...
}
The "cancel()" method only canceled the latest Timer. The older ones were ignored an didn't stop running.
So after a long time of playing around with AccessibilityServices, window insets, screen height detection, etc, I think I found a way to do this.
Disclaimer: it uses a hidden method in Android, meaning it might not be consistent. However, in my testing, it seems to work.
The method is InputMethodManager#getInputMethodWindowVisibleHeight(), and it's existed since Lollipop (5.0).
Calling that returns the height, in pixels, of the current keyboard. In theory, a keyboard shouldn't be 0 pixels tall, so I did a simple height check (in Kotlin):
val imm by lazy { context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager }
if (imm.inputMethodWindowVisibleHeight > 0) {
//keyboard is shown
else {
//keyboard is hidden
}
I use Android Hidden API to avoid reflection when I call hidden methods (I do that a lot for the apps I develop, which are mostly hacky/tuner apps), but this should be possible with reflection as well:
val imm by lazy { context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager }
val windowHeightMethod = InputMethodManager::class.java.getMethod("getInputMethodWindowVisibleHeight")
val height = windowHeightMethod.invoke(imm) as Int
//use the height val in your logic
Take a look at the Cursor.Position
Property. It should get you started.
private void MoveCursor()
{
// Set the Current cursor, move the cursor's Position,
// and set its clipping rectangle to the form.
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
Cursor.Clip = new Rectangle(this.Location, this.Size);
}
Looking again at your question, I think I see what's wrong with your conf file. You set:
fullresolution=1366x768 windowresolution=1366x768
That's why you're getting the letterboxing (black on either side). You've essentially told Dosbox that your screen is the same size as your window, but your screen is actually bigger, 1600x900 (or higher) per the Googled specs for that computer. So the 'difference' shows up in black. So you either should change fullresolution to your actual screen resolution, or revert to fullresolution=original default, and only specify the window resolution.
So now I wonder if you really want fullscreen, though your question asks about only a window. For you are getting a window, but you sized it short of your screen, hence the two black stripes (letterboxing). If you really want fullscreen, then you need to specify the actual resolution of your screen. 1366x768 is not big enough.
The next issue is, what's the resolution of the program itself? It won't go past its own resolution. So if the program/game is (natively) say 1280x720 (HD), then your window resolution setting shouldn't be bigger than that (remember, it's fixed not dynamic when you use AxB as windowresolution).
Example: DOS Lotus 123 will only extend eight columns and 20 rows. The bigger the Dosbox, the bigger the text, but not more columns and rows. So setting a higher windowresolution for that, only results in bigger text, not more columns and rows. After that you'll have letterboxing.
Hope this helps you better.
from datetime import date,timedelta
delta = timedelta(days=1)
start = date(2020,1,1)
end=date(2020,9,1)
loop_date = start
while loop_date<=end:
print(loop_date)
loop_date+=delta
You can use lambda expressions
private void MyMethod(string param1,int param2)
{
//do stuff
}
Thread myNewThread = new Thread(() => MyMethod("param1",5));
myNewThread.Start();
this is so far the best answer i could find, it's fast and easy.
Start by turning the text into a list of lists. That will take care of the parsing part:
lol = list(csv.reader(open('text.txt', 'rb'), delimiter='\t'))
The rest can be done with indexed lookups:
d = dict()
key = lol[6][0] # cell A7
value = lol[6][3] # cell D7
d[key] = value # add the entry to the dictionary
...
I think the key is to copy the module to the standard paths.
Once that is done, modprobe only accepts the module name, so leave off the path and ".ko" extension.
Symmetric Encryption:
Symmetric encryption may also be referred to as shared key or shared secret encryption. In symmetric encryption, a single key is used both to encrypt and decrypt traffic.
Asymmetric Encryption:
Asymmetric encryption is also known as public-key cryptography. Asymmetric encryption differs from symmetric encryption primarily in that two keys are used: one for encryption and one for decryption. The most common asymmetric encryption algorithm is RSA
.
Compared to symmetric encryption, asymmetric encryption imposes a high computational burden, and tends to be much slower. Thus, it isn't typically employed to protect payload data. Instead, its major strength is its ability to establish a secure channel over a nonsecure medium (for example, the Internet). This is accomplished by the exchange of public keys, which can only be used to encrypt data. The complementary private key, which is never shared, is used to decrypt.
Hashing:
Finally, hashing is a form of cryptographic security which differs from encryption. Whereas encryption is a two step process used to first encrypt and then decrypt a message, hashing condenses a message into an irreversible fixed-length value, or hash. Two of the most common hashing algorithms seen in networking are MD5
and SHA-1
.
Read more here:http://packetlife.net/blog/2010/nov/23/symmetric-asymmetric-encryption-hashing/
Inside <td>
, use style="border-left:1px solid #colour;"
I'd do it like this jsFiddle example.
JavaScript:
function check(elem) {
document.getElementById('mySelect1').disabled = !elem.selectedIndex;
}
HTML:
<form>
<select id="mySelect" onChange="check(this);">
<option>No</option>
<option>Yes</option>
</select>
<select id="mySelect1" disabled="disabled" >
<option>Dep1</option>
<option>Dep2</option>
<option>Dep3</option>
<option>Dep4</option>
</select>
</form>
I solved this issue on PHP 7.0.22-0ubuntu0.16.04.1 nginx
sudo apt-get install php7.0-soap
sudo systemctl restart php7.0-fpm
sudo systemctl restart nginx
I had to use
HTML:
<img id="loading" src="~/Images/spinner.gif" alt="Updating ..." style="display: none;" />
In script file:
// invoked when sending ajax request
$(document).ajaxSend(function () {
$("#loading").show();
});
// invoked when sending ajax completed
$(document).ajaxComplete(function () {
$("#loading").hide();
});