Actually you must make sure that the IIS Management Console feature is explicitly checked. On my win 10 pro I had to do it manually, checking the root only was not enough!
I had the same problem. my problem was that the version of the dependency had conflict with the elasticsearch version. check the version in ip:9200 and use the dependency version that match it
This is sonxurxo's solution in Kotlin, if anyone needs it.
private fun getUnsafeOkHttpClient(): OkHttpClient {
// Create a trust manager that does not validate certificate chains
val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
}
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
}
override fun getAcceptedIssuers() = arrayOf<X509Certificate>()
})
// Install the all-trusting trust manager
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, java.security.SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory = sslContext.socketFactory
return OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
.hostnameVerifier { _, _ -> true }.build()
}
I faced the same issue once. I think its because of the URL
String xmlServerURL = "https://example.com/soap/WsRouter";
Check whether its a proper one or not ??
javax.net.ssl.SSLHandshakeException
is because the server not able to connect to the specified URL because of following reason-
Issue is with remote server, can you login to the remote server and check if "scp" works
probable causes: - scp is not in path - openssh client not installed correctly
for more details http://www.linuxquestions.org/questions/linux-newbie-8/bash-scp-command-not-found-920513/
<location path="ForAll/Demo.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
In Addition: If you want to write something on that folder through website , you have to give IIS_User permission to the folder
If you get the above problem on windows server 2008 you may need to enable ASP. To do so, follow these steps:
Add an 'Application Server' role:
Then, add a 'Web Server' role:
w3wp.exe is a process associated with the application pool in IIS. If you have more than one application pool, you will have more than one instance of w3wp.exe running. This process usually allocates large amounts of resources. It is important for the stable and secure running of your computer and should not be terminated.
You can get more information on w3wp.exe here
http://www.processlibrary.com/en/directory/files/w3wp/25761/
Try downloading "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files" from the Java download site and replacing the files in your JRE.
This worked for me and I didn't even need to use BouncyCastle - the standard Sun JCE was able to connect to the server.
PS. I got the same error (ArrayIndexOutOfBoundsException: 64) when I tried using BouncyCastle before changing the policy files, so it seems our situation is very similar.
I just ran into this on .NET 4.6.1 and it ultimately had a simple solution - I removed (actually commented out) the section in the web.config and the web forms application came back to life. See what-exactly-does-system-codedom-compilers-do-in-web-config-in-mvc-5 for more info.
It worked for me.
If you're working with an asp.net application and you want to locate assemblies when using the debugger, they are usually put into some temp directory. I wrote the this method to help with that scenario.
private string[] GetAssembly(string[] assemblyNames)
{
string [] locations = new string[assemblyNames.Length];
for (int loop = 0; loop <= assemblyNames.Length - 1; loop++)
{
locations[loop] = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic && a.ManifestModule.Name == assemblyNames[loop]).Select(a => a.Location).FirstOrDefault();
}
return locations;
}
For more details see this blog post http://nodogmablog.bryanhogan.net/2015/05/finding-the-location-of-a-running-assembly-in-net/
If you can't change the source code, or redeploy, but you can examine the running processes on the computer use Process Explorer. I written a detailed description here.
It will list all executing dlls on the system, you may need to determine the process id of your running application, but that is usually not too difficult.
I've written a full description of how do this for a dll inside IIS - http://nodogmablog.bryanhogan.net/2016/09/locating-and-checking-an-executing-dll-on-a-running-web-server/
If you still need to use the HTTP Module you need to configure it (.NET 4.0 framework) as follows:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="MyModule" type="[Namespace].[Class], [assembly]"/>
</modules>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
The solution is:
$(document).ready(function(){
$("#date_pretty").datepicker({
});
var myDate = new Date();
var month = myDate.getMonth() + 1;
var prettyDate = month + '/' + myDate.getDate() + '/' + myDate.getFullYear();
$("#date_pretty").val(prettyDate);
});
Thanks grayghost!
You may also consider the following solution:
let sum = options.set0.concat(options.set1);
const codeHTML = '<ol>' + sum.reduce((html, item) => {
return html + "<li>" + item + "</li>";
}, "") + '</ol>';
document.querySelector("#list").innerHTML = codeHTML;
I have a hard time remember the char to int conversions so this could be optimized
def decryptCaesar(encrypted, shift):
minRange = ord('a')
decrypted = ""
for char in encrypted:
decrypted += chr(((ord(char) - minRange + shift) % 26) + minRange)
return decrypted
Assuming you actually mean timestamp
because there is no datetime
in Postgres
Cast the timestamp column to a date, that will remove the time part:
select *
from the_table
where the_timestamp_column::date = date '2015-07-15';
This will return all rows from July, 15th.
Note that the above will not use an index on the_timestamp_column
. If performance is critical, you need to either create an index on that expression or use a range condition:
select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
and the_timestamp_column < timestamp '2015-07-16 00:00:00';
I recently ran into this problem and discovered that it was caused by the "Adblock" extension (my best guess is that it's because I had the words "banner" and "ad" in the filename).
As a quick test to see if that's your problem, start Chrome in incognito mode with extensions disabled (ctrl+shift+n) and see if your page works now. Note that by default all extensions will be already disabled in incognito mode unless you've specifically set them to run (via chrome://extensions
).
@if($errors->any())
{!! implode('', $errors->all('<div class="alert alert-danger">:message</div>')) !!}
@endif
We can format tag as per requirements.
None is a special value in Python which usually designates an uninitialized variable. To test whether A does not have this particular value you use:
if A is not None
Falsey values are a special class of objects in Python (e.g. false, []). To test whether A is falsey use:
if not A
Thus, the two expressions are not the same And you'd better not treat them as synonyms.
P.S. None is also falsey, so the first expression implies the second. But the second covers other falsey values besides None. Now... if you can be sure that you can't have other falsey values besides None in A, then you can replace the first expression with the second.
In simple terms, you just need to edit the .gitmodules file, then resync and update:
Edit the file, either via a git command or directly:
git config --file=.gitmodules -e
or just:
vim .gitmodules
then resync and update:
git submodule sync
git submodule update --init --recursive --remote
If you like getting random Command Timeout errors in SQLServer then leave off the semi-colon at the end of your CommandText strings.
I don't know if this is documented anywhere or if it is a bug, but it does happen and I have learnt this from bitter experience.
I have verifiable and reproducible examples using SQLServer 2008.
aka -> In practice, always include the terminator even if you're just sending one statement to the database.
You can also reference the obj
once you are inside the function instead of this
.
var obj = {
key1: "it",
key2: function(){return obj.key1 + " works!"}
};
alert(obj.key2());
try
<div style="width:100%;">
<div style="width:50px; float: left;"><img src="myleftimage" /></div>
<div style="width:50px; float: right;"><img src="myrightimage" /></div>
<div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
</div>
or
<div style="width:100%; border:2px solid #dadada;">
<div style="width:50px; float: left;"><img src="myleftimage" /></div>
<div style="width:50px; float: right;"><img src="myrightimage" /></div>
<div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
<div style="clear:both"></div>
</div>
setup.py
is Python's answer to a multi-platform installer and make
file.
If you’re familiar with command line installations, then make && make install
translates to python setup.py build && python setup.py install
.
Some packages are pure Python, and are only byte compiled. Others may contain native code, which will require a native compiler (like gcc
or cl
) and a Python interfacing module (like swig
or pyrex
).
All you have to do is use the value attribute of input tags:
<input type="text" value="Your Value" />
Or, in the case of a textarea:
<textarea>Your Value</textarea>
If order is preserved between files you might also prefer difflib
. Although Rob?'s result is the bona-fide standard for intersections you might actually be looking for a rough diff-like:
from difflib import Differ
with open('cfg1.txt') as f1, open('cfg2.txt') as f2:
differ = Differ()
for line in differ.compare(f1.readlines(), f2.readlines()):
if line.startswith(" "):
print(line[2:], end="")
That said, this has a different behaviour to what you asked for (order is important) even though in this instance the same output is produced.
Curtis's answer was very close to what I needed, but I changed it up a little.
Where he used:
$options['inputs']['name'][] = $new_input['name'];
I used:
$options[]['inputs']['name'] = $new_input['name'];
Here's my actual code using a query from a DB:
while($row=mysql_fetch_array($result)){
$dtlg_array[]['dt'] = $row['dt'];
$dtlg_array[]['lat'] = $row['lat'];
$dtlg_array[]['lng'] = $row['lng'];
}
Thanks!
You need to go into the developer console and set
http://localhost:8080/WEBAPP/youtube-callback.html
as your callback URL.
This video is slightly outdated, as it shows the older Developer Console instead of the new one, however, the concepts should still apply. You need to find your project in the developer console and register a callback URL.
When jumi (joomla plugin for PHP) compiles your code for some reason it removes all backslashes from your code. Such that something like $csv_output .= "\n";
becomes $csv_output .= "n";
Very annoying bug!
Use PHP_EOL instead to get the result you were after.
You can add extra data with form data
use serializeArray and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'tienn2t', value: 'love'});
$.ajax({
type: "POST",
url: "your url.php",
data: data,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
<table>
<tbody>
<tr>
<td>
<select name="test" style="color: red;">
<option value="Basic">Basic : $30.00 USD - yearly</option>
<option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
<option value="Supporting">Supporting : $120.00 USD - yearly</option>
</select>
</td>
</tr>
</tbody>
</table>
Be aware that the NuGet PM breaks the Rosalyn behavior. Click Tools > NuGet Package Manager > Manage NuGet Packages for Solution
If an update Exists for Microsoft.CodeDom.Providers.DotNetCompilerPlatform
, Microsoft.Net.Compilers
, or Microsoft.Net.Compilers.netcore
, update them and the Solution will break! This occurs because the ASP Sites templates are set to use specific versions at project creation. To See the problem, click Show All Files in the Solution Explorer.
At project creation the $(WebProjectOutputDir)\bin
doesn't exist, therefore when Rosalyn is added as a dependency by NuGet it installs it properly. After Updating the Solution Packages, the $(WebProjectOutputDir)\bin
directory looks like so:
$(WebProjectOutputDir)\bin\bin\rosalyn
The easiest fix is to Cut & Paste rosalyn to the proper location, and then delete the extra bin
folder. You can now Refresh the page and the site will load.
(this question is a duplicate of In chart.js, Is it possible to hide x-axis label/text of bar chart if accessing from mobile?) They added the option, 2.1.4 (and maybe a little earlier) has it
var myLineChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
xAxes: [{
ticks: {
display: false
}
}]
}
}
}
When dealing with mocking lists and iterating them, I always use something like:
@Spy
private List<Object> parts = new ArrayList<>();
The whole thing to em is, that the size is relative to the base. So I would say you could keep the font sizes by altering the base.
Example: If you base is 16px, and p is .75em (which is 12px) you would have to raise the base to about 20px. In this case p would then equal about 15px which is the minimum I personally require for mobile phones.
I just set the timezone with Matthias Bauch answer And it worked for me. else it was adding 18:30 min more.
let cal: NSCalendar = NSCalendar.currentCalendar()
cal.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let newDate: NSDate = cal.dateBySettingHour(1, minute: 0, second: 0, ofDate: NSDate(), options: NSCalendarOptions())!
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
Why you didn`t use
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
?
Or you can use this
-(void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
Or this
-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
Hope it owl be useful )
You just have to set UIFileSharingEnabled
(Application Supports iTunes file sharing
) key in the info plist of your app. Here's a link for the documentation. Scroll down to the file sharing support part.
In the past, it was also necessary to define CFBundleDisplayName
(Bundle Display Name
), if it wasn't already there. More details here.
try
{
// your code
}
catch (Exception w)
{
MessageDialog msgDialog = new MessageDialog(w.ToString());
}
Express 4.x
To get a URL parameter's value, use req.params
app.get('/p/:tagId', function(req, res) {
res.send("tagId is set to " + req.params.tagId);
});
// GET /p/5
// tagId is set to 5
If you want to get a query parameter ?tagId=5
, then use req.query
app.get('/p', function(req, res) {
res.send("tagId is set to " + req.query.tagId);
});
// GET /p?tagId=5
// tagId is set to 5
Express 3.x
URL parameter
app.get('/p/:tagId', function(req, res) {
res.send("tagId is set to " + req.param("tagId"));
});
// GET /p/5
// tagId is set to 5
Query parameter
app.get('/p', function(req, res) {
res.send("tagId is set to " + req.query("tagId"));
});
// GET /p?tagId=5
// tagId is set to 5
To access any element of a list in a YAML file like this:
global:
registry:
url: dtr-:5000/
repoPath:
dbConnectionString: jdbc:oracle:thin:@x.x.x.x:1521:abcd
You can use following python script:
import yaml
with open("/some/path/to/yaml.file", 'r') as f:
valuesYaml = yaml.load(f, Loader=yaml.FullLoader)
print(valuesYaml['global']['dbConnectionString'])
Besides CMAKE_GENERATOR_PLATFORM
variable, there is also the -A
switch
cmake -G "Visual Studio 16 2019" -A Win32
cmake -G "Visual Studio 16 2019" -A x64
https://cmake.org/cmake/help/v3.16/generator/Visual%20Studio%2016%202019.html#platform-selection
-A <platform-name> = Specify platform name if supported by
generator.
UPDATE FOR NEW VERSION
Glide.with(context.applicationContext)
.load(url)
.listener(object : RequestListener<Drawable> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Drawable>?,
isFirstResource: Boolean
): Boolean {
listener?.onLoadFailed(e)
return false
}
override fun onResourceReady(
resource: Drawable?,
model: Any?,
target: com.bumptech.glide.request.target.Target<Drawable>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
listener?.onLoadSuccess(resource)
return false
}
})
.into(this)
OLD ANSWER
@outlyer's answer is correct, but there're some changes in new Glide version
My version: 4.7.1
Code:
Glide.with(context.applicationContext)
.asBitmap()
.load(iconUrl)
.into(object : SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
override fun onResourceReady(resource: Bitmap, transition: com.bumptech.glide.request.transition.Transition<in Bitmap>?) {
callback.onReady(createMarkerIcon(resource, iconId))
}
})
Note: this code run in UI Thread, thus you can use AsyncTask, Executor or somethings else for concurrency (like @outlyer's code) If you want to get original size, put Target.SIZE_ORIGINA as my code. Don't use -1, -1
FWIW, here is a sort method for showing which processes are using the most virt memory.
memstat | sort -k 1 -t':' -g -r | less
Sort options are set to first column, using : as column seperator, numeric sort and sort in reverse.
This isn't too difficult with a little CSS, and is much better than using an image for the bullet since you can scale it and colour it and it will keep sharp at all resolutions.
Find the character code of the glyphicon by opening the Bootstrap docs and inspecting the character you want to use.
Use that character code in the following CSS
li {
display: block;
}
li:before {
/*Using a Bootstrap glyphicon as the bullet point*/
content: "\e080";
font-family: 'Glyphicons Halflings';
font-size: 9px;
float: left;
margin-top: 4px;
margin-left: -17px;
color: #CCCCCC;
}
You may like to tweak the colour and margins to suit your font size and taste.
Related with the answer by @DanielSerrano, I've been recently bit by localization of the sc.exe
command, namely in Spanish. My proposal is to pin-point the line and token which holds numerical service state and interpret it, which should be much more robust:
@echo off
rem TODO: change to the desired service name
set TARGET_SERVICE=w32time
set SERVICE_STATE=
rem Surgically target third line, as some locales (such as Spanish) translated the utility's output
for /F "skip=3 tokens=3" %%i in ('""%windir%\system32\sc.exe" query "%TARGET_SERVICE%" 2>nul"') do (
if not defined SERVICE_STATE set SERVICE_STATE=%%i
)
rem Process result
if not defined SERVICE_STATE (
echo ERROR: could not obtain service state!
) else (
rem NOTE: values correspond to "SERVICE_STATUS.dwCurrentState"
rem https://msdn.microsoft.com/en-us/library/windows/desktop/ms685996(v=vs.85).aspx
if not %SERVICE_STATE%==4 (
echo WARNING: service is not running
rem TODO: perform desired operation
rem net start "%TARGET_SERVICE%"
) else (
echo INFORMATION: service is running
)
)
Tested with:
Your fundamental problem is that grep
works one line at a time - so it cannot find a SELECT statement spread across lines.
Your second problem is that the regex you are using doesn't deal with the complexity of what can appear between SELECT and FROM - in particular, it omits commas, full stops (periods) and blanks, but also quotes and anything that can be inside a quoted string.
I would likely go with a Perl-based solution, having Perl read 'paragraphs' at a time and applying a regex to that. The downside is having to deal with the recursive search - there are modules to do that, of course, including the core module File::Find.
In outline, for a single file:
$/ = "\n\n"; # Paragraphs
while (<>)
{
if ($_ =~ m/SELECT.*customerName.*FROM/mi)
{
printf file name
go to next file
}
}
That needs to be wrapped into a sub that is then invoked by the methods of File::Find.
If you really need then you can use i.e.
entity to do that, but remember that fonts used to render your page are usually proportional, so "aligning" with spaces does not really work and looks ugly.
I know, you ask for Eloquent but you can do it with Fluent Query Builder
$data = DB::table('themes')
->join('users', 'users.id', '=', 'themes.user_id')
->get(array('themes.*', 'users.username'));
You can directly show image from web without downloading it. Please check the below function . It will show the images from the web into your image view.
public static Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
then set image to imageview using code in your activity.
As per the Django Project Skeleton, the proper directory structure that could be followed is :
[projectname]/ <- project root
+-- [projectname]/ <- Django root
¦ +-- __init__.py
¦ +-- settings/
¦ ¦ +-- common.py
¦ ¦ +-- development.py
¦ ¦ +-- i18n.py
¦ ¦ +-- __init__.py
¦ ¦ +-- production.py
¦ +-- urls.py
¦ +-- wsgi.py
+-- apps/
¦ +-- __init__.py
+-- configs/
¦ +-- apache2_vhost.sample
¦ +-- README
+-- doc/
¦ +-- Makefile
¦ +-- source/
¦ +-- *snap*
+-- manage.py
+-- README.rst
+-- run/
¦ +-- media/
¦ ¦ +-- README
¦ +-- README
¦ +-- static/
¦ +-- README
+-- static/
¦ +-- README
+-- templates/
+-- base.html
+-- core
¦ +-- login.html
+-- README
Refer https://django-project-skeleton.readthedocs.io/en/latest/structure.html for the latest directory structure.
selection opertion is used to select a subset of tuple from the relation that satisfied selection condition It filter out those tuple that satisfied the condition .Selection opertion can be visualized as horizontal partition into two set of tuple - those tuple satisfied the condition are selected and those tuple do not select the condition are discarded sigma (R) projection opertion is used to select a attribute from the relation that satisfied selection condition . It filter out only those tuple that satisfied the condition . The projection opertion can be visualized as a vertically partition into two part -are those satisfied the condition are selected other discarded ?(R) attribute list is a num of attribute
I experienced the same as above after removing signing of assemblies in the solution. The projects would not build.
I found that one of the projects referenced the StrongNamer NuGet package, which modifies the build process and tries to sign non-signed Nuget packages.
After removing the StrongNamer package I was able to build the project again without signing/strong-naming the assemblies.
I would suggest you read this article and focus more on how to optimize the overall response to the user request (either a page, a search result etc.)
A good argument for this is the example they give about using gzip to compress the page. Even though ttfb is faster when you do not compress, the overall experience of the user is worst because it takes longer to download content that is not zipped.
Please find the code in jsFiddle. It uses jQuery to modify the href of the link. You can use any other library in its place. It should work.
HTML
<a id="emailLnk" href="#">
<img src="http://ssl.gstatic.com/gb/images/j_e6a6aca6.png">
</a>
JS
$(document).ready(function() {
$("#emailLnk").attr('href',"mailto:[email protected]");
});?
UPDATE
Another code sample, if the id is known only during the click event
$(document).ready(function() {
$("#emailLnk").click(function()
{
window.location.href = "mailto:[email protected]";
});
});?
I know this question already have been answer but I have made some update to the GD function :
### COST FUNCTION
def cost(theta,X,y):
### Evaluate half MSE (Mean square error)
m = len(y)
error = np.dot(X,theta) - y
J = np.sum(error ** 2)/(2*m)
return J
cost(theta,X,y)
def GD(X,y,theta,alpha):
cost_histo = [0]
theta_histo = [0]
# an arbitrary gradient, to pass the initial while() check
delta = [np.repeat(1,len(X))]
# Initial theta
old_cost = cost(theta,X,y)
while (np.max(np.abs(delta)) > 1e-6):
error = np.dot(X,theta) - y
delta = np.dot(np.transpose(X),error)/len(y)
trial_theta = theta - alpha * delta
trial_cost = cost(trial_theta,X,y)
while (trial_cost >= old_cost):
trial_theta = (theta +trial_theta)/2
trial_cost = cost(trial_theta,X,y)
cost_histo = cost_histo + trial_cost
theta_histo = theta_histo + trial_theta
old_cost = trial_cost
theta = trial_theta
Intercept = theta[0]
Slope = theta[1]
return [Intercept,Slope]
res = GD(X,y,theta,alpha)
This function reduce the alpha over the iteration making the function too converge faster see Estimating linear regression with Gradient Descent (Steepest Descent) for an example in R. I apply the same logic but in Python.
Double brace initialization is an option:
List<String> symbolsPresent = new ArrayList<String>() {{
add("ONE");
add("TWO");
add("THREE");
add("FOUR");
}};
Note that the String
generic type argument is necessary in the assigned expression as indicated by JLS §15.9
It is a compile-time error if a class instance creation expression declares an anonymous class using the "<>" form for the class's type arguments.
You can utilize the dependency management mechanism.
If you create entries in the <dependencyManagement> section of your pom for spring-security-web and spring-web with the desired 3.1.0 version set the managed version of the artifact will override those specified in the transitive dependency tree.
I'm not sure if that really saves you any code, but it is a cleaner solution IMO.
go get
will install the package in the first directory listed at GOPATH
(an environment variable which might contain a colon separated list of directories). You can use go get -u
to update existing packages.
You can also use go get -u all
to update all packages in your GOPATH
For larger projects, it might be reasonable to create different GOPATHs for each project, so that updating a library in project A wont cause issues in project B.
Type go help gopath
to find out more about the GOPATH
environment variable.
In bash script I do this to check if image exists by tag :
IMAGE_NAME="mysql:5.6"
if docker image ls -a "$IMAGE_NAME" | grep -Fq "$IMAGE_NAME" 1>/dev/null; then
echo "could found image $IMAGE_NAME..."
fi
Example script above checks if mysql image with 5.6 tag exists. If you want just check if any mysql image exists without specific version then just pass repository name without tag as this :
IMAGE_NAME="mysql"
Note that "number of cores" might not be a particularly useful number, you might have to qualify it a bit more. How do you want to count multi-threaded CPUs such as Intel HT, IBM Power5 and Power6, and most famously, Sun's Niagara/UltraSparc T1 and T2? Or even more interesting, the MIPS 1004k with its two levels of hardware threading (supervisor AND user-level)... Not to mention what happens when you move into hypervisor-supported systems where the hardware might have tens of CPUs but your particular OS only sees a few.
The best you can hope for is to tell the number of logical processing units that you have in your local OS partition. Forget about seeing the true machine unless you are a hypervisor. The only exception to this rule today is in x86 land, but the end of non-virtual machines is coming fast...
You have number of ways doing it on Windows:
Press CTRL + L
import os
cls = lambda: os.system('cls')
cls()
cls = lambda: print('\n'*100)
cls()
This is a REALLY old thread, but it was still the first thing to pop up when I googled the issue. So I just wanted to add this:
InputStream inputStream = conn.getInputStream();
int length = inputStream.available();
Worked for me. And MUCH simpler than the other answers here.
Warning This solution does not provide reliable results regarding the total size of a stream. Except from the JavaDoc:
Note that while some implementations of {@code InputStream} will return * the total number of bytes in the stream, many will not.
I solved this issue by updating my settings.xml file with correct mirror config, seems that intellij will try to download meta-data from repository every time the maven module imported.
Using JavaScript and jQuery:
<script src="js/jquery.js"></script>
...
<video id="vid" width="1280" height="720" src="v/myvideo01.mp4" controls autoplay></video>
...
function chVid(vid) {
$("#vid").attr("src",vid);
}
...
<div onclick="chVid('v/myvideo02.mp4')">See my video #2!</div>
Maybe too late :))) but there is another solution that you can find the key and value of structs and iterate over that
package main
import (
"fmt"
"reflect"
)
type person struct {
firsName string
lastName string
iceCream []string
}
func main() {
u := struct {
myMap map[int]int
mySlice []string
myPerson person
}{
myMap: map[int]int{1: 10, 2: 20},
mySlice: []string{"red", "green"},
myPerson: person{
firsName: "Esmaeil",
lastName: "Abedi",
iceCream: []string{"Vanilla", "chocolate"},
},
}
v := reflect.ValueOf(u)
for i := 0; i < v.NumField(); i++ {
fmt.Println(v.Type().Field(i).Name)
fmt.Println("\t", v.Field(i))
}
}
and there is no *panic* for v.Field(i)
DateFormat = DD.MM.YYYY or D.M.YYYY
function dateValidate(val){
var dateStr = val.split('.');
var date = new Date(dateStr[2], dateStr[1]-1, dateStr[0]);
if(date.getDate() == dateStr[0] && date.getMonth()+1 == dateStr[1] && date.getFullYear() == dateStr[2])
{ return date; }
else{ return 'NotValid';}
}
In SQL Server Management Studio (SSMS):
You can also right click your database in the Object Explorer and go to Properties. From there, go to Options. Scroll all the way down and set Restrict Access to SINGLE_USER. Change your database name, then go back in and set it back to MULTI_USER.
You cannot create a process in linux that cannot be killed. The root user (uid=0) can send a signal to a process, and there are two signals which cannot be caught, SIGKILL=9, SIGSTOP=19. And other signals (when uncaught) can also result in process termination.
You may want a more general daemonize function, where you can specify a name for your program/daemon, and a path to run your program (perhaps "/" or "/tmp"). You may also want to provide file(s) for stderr and stdout (and possibly a control path using stdin).
Here are the necessary includes:
#include <stdio.h> //printf(3)
#include <stdlib.h> //exit(3)
#include <unistd.h> //fork(3), chdir(3), sysconf(3)
#include <signal.h> //signal(3)
#include <sys/stat.h> //umask(3)
#include <syslog.h> //syslog(3), openlog(3), closelog(3)
And here is a more general function,
int
daemonize(char* name, char* path, char* outfile, char* errfile, char* infile )
{
if(!path) { path="/"; }
if(!name) { name="medaemon"; }
if(!infile) { infile="/dev/null"; }
if(!outfile) { outfile="/dev/null"; }
if(!errfile) { errfile="/dev/null"; }
//printf("%s %s %s %s\n",name,path,outfile,infile);
pid_t child;
//fork, detach from process group leader
if( (child=fork())<0 ) { //failed fork
fprintf(stderr,"error: failed fork\n");
exit(EXIT_FAILURE);
}
if (child>0) { //parent
exit(EXIT_SUCCESS);
}
if( setsid()<0 ) { //failed to become session leader
fprintf(stderr,"error: failed setsid\n");
exit(EXIT_FAILURE);
}
//catch/ignore signals
signal(SIGCHLD,SIG_IGN);
signal(SIGHUP,SIG_IGN);
//fork second time
if ( (child=fork())<0) { //failed fork
fprintf(stderr,"error: failed fork\n");
exit(EXIT_FAILURE);
}
if( child>0 ) { //parent
exit(EXIT_SUCCESS);
}
//new file permissions
umask(0);
//change to path directory
chdir(path);
//Close all open file descriptors
int fd;
for( fd=sysconf(_SC_OPEN_MAX); fd>0; --fd )
{
close(fd);
}
//reopen stdin, stdout, stderr
stdin=fopen(infile,"r"); //fd=0
stdout=fopen(outfile,"w+"); //fd=1
stderr=fopen(errfile,"w+"); //fd=2
//open syslog
openlog(name,LOG_PID,LOG_DAEMON);
return(0);
}
Here is a sample program, which becomes a daemon, hangs around, and then leaves.
int
main()
{
int res;
int ttl=120;
int delay=5;
if( (res=daemonize("mydaemon","/tmp",NULL,NULL,NULL)) != 0 ) {
fprintf(stderr,"error: daemonize failed\n");
exit(EXIT_FAILURE);
}
while( ttl>0 ) {
//daemon code here
syslog(LOG_NOTICE,"daemon ttl %d",ttl);
sleep(delay);
ttl-=delay;
}
syslog(LOG_NOTICE,"daemon ttl expired");
closelog();
return(EXIT_SUCCESS);
}
Note that SIG_IGN indicates to catch and ignore the signal. You could build a signal handler that can log signal receipt, and set flags (such as a flag to indicate graceful shutdown).
I don't believe this is a good pattern to use in general. Link will run your onClick event and then navigate to the route, so there will be a slight delay navigating to the new route. A better strategy is to navigate to the new route with the 'to' prop as you have done, and in the new component's componentDidMount() function you can fire your hello function or any other function. It will give you the same result, but with a much smoother transition between routes.
For context, I noticed this while updating my redux store with an onClick event on Link like you have here, and it caused a ~.3 second blank-white-screen delay before mounting the new route's component. There was no api call involved, so I was surprised the delay was so big. However, if you're just console logging 'hello' the delay might not be noticeable.
I had a similar issue with Angular and IIS throwing a 404 status code on manual refresh and tried the most voted solution but that did not work for me. Also tried a bunch of other solutions having to deal with WebDAV and changing handlers and none worked.
Luckily I found this solution and it worked (took out parts I didn't need). So if none of the above works for you or even before trying them, try this and see if that fixes your angular deployment on iis issue.
Add the snippet to your webconfig in the root directory of your site. From my understanding, it removes the 404 status code from any inheritance (applicationhost.config, machine.config), then creates a 404 status code at the site level and redirects back to the home page as a custom 404 page.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<httpErrors errorMode="Custom">
<remove statusCode="404"/>
<error statusCode="404" path="/index.html" responseMode="ExecuteURL"/>
</httpErrors>
</system.webServer>
</configuration>
$('input[type=checkbox]').change(function () {
alert('changed');
});
An important comment from tmoschou:
As of Ansible 2.10, The documentation for ansible.builtin.copy says:
If you need variable interpolation in copied files, use the
ansible.builtin.template module. Using a variable in the content
field will result in unpredictable output.
For more details see this and an explanation
Original answer:
You could use the copy
module, with the content
parameter:
- copy: content="{{ your_json_feed }}" dest=/path/to/destination/file
The docs here: copy module
I know this has plenty of answers but since most of them are old (well, older), none is mentioning approach I grow very fond of really quick. In short:
Use functional components and hooks.
In longer:
Try to use as much functional components instead class ones especially for rendering, AND try to keep them as pure as possible (yes, data is dirty by default I know).
Two bluntly obvious benefits of functional components (there are more):
Quick proof for 2nd point - Isn't this absolutely disgusting?
constructor(props) {
super(props);
this.toggle= this.toggle.bind(this);
this.state = {
details: false
}
}
If you are using functional components for more then rendering you are gonna need the second part of great duo - hooks. Why are they better then lifecycle methods, what else can they do and much more would take me a lot of space to cover so I recommend you to listen to the man himself: Dan preaching the hooks
In this case you need only two hooks:
A callback hook conveniently named useCallback
. This way you are preventing the binding the function over and over when you re-render.
A state hook, called useState
, for keeping the state despite entire component being function and executing in its entirety (yes, this is possible due to magic of hooks). Within that hook you will store the value of toggle.
If you read to this part you probably wanna see all I have talked about in action and applied to original problem. Here you go: Demo
For those of you that want only to glance the component and WTF is this about, here you are:
const Item = () => {
// HOOKZ
const [isVisible, setIsVisible] = React.useState('hidden');
const toggle = React.useCallback(() => {
setIsVisible(isVisible === 'visible' ? 'hidden': 'visible');
}, [isVisible, setIsVisible]);
// RENDER
return (
<React.Fragment>
<div style={{visibility: isVisible}}>
PLACEHOLDER MORE INFO
</div>
<button onClick={toggle}>Details</button>
</React.Fragment>
)
};
PS: I wrote this in case many people land here with similar problem. Hopefully, they will like what I have shown here, at least well enough to google it a bit more. This is NOT me saying other answers are wrong, this is me saying that since the time they have been written, there is another way (IMHO, a better one) of dealing with this.
If you are using Eclipse with the yedit plugin (an editor for .yaml files), you can comment-out multiple lines by:
And to un-comment, follow the same steps.
SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.
Let's suppose you have two databases on the same server - Db1
and Db2
. Db1
has a table called Clients
with a column ClientId
and Db2
has a table called Messages
with a column ClientId
(let's leave asside why those tables are in different databases).
Now, to perform a join on the above-mentioned tables you will be using this query:
select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId
Delete every things (jar, pom.xml, etc) under your local ~/.m2/repository/phonegap/1.1.0/
directory if you are using a linux OS.
I had the same issue as all of our servers run older versions of MySQL. This can be solved by running a PHP script. Save this code to a file and run it entering the database name, user and password and it'll change the collation from utf8mb4/utf8mb4_unicode_ci
to utf8/utf8_general_ci
<!DOCTYPE html>
<html>
<head>
<title>DB-Convert</title>
<style>
body { font-family:"Courier New", Courier, monospace; }
</style>
</head>
<body>
<h1>Convert your Database to utf8_general_ci!</h1>
<form action="db-convert.php" method="post">
dbname: <input type="text" name="dbname"><br>
dbuser: <input type="text" name="dbuser"><br>
dbpass: <input type="text" name="dbpassword"><br>
<input type="submit">
</form>
</body>
</html>
<?php
if ($_POST) {
$dbname = $_POST['dbname'];
$dbuser = $_POST['dbuser'];
$dbpassword = $_POST['dbpassword'];
$con = mysql_connect('localhost',$dbuser,$dbpassword);
if(!$con) { echo "Cannot connect to the database ";die();}
mysql_select_db($dbname);
$result=mysql_query('show tables');
while($tables = mysql_fetch_array($result)) {
foreach ($tables as $key => $value) {
mysql_query("ALTER TABLE $value CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
}}
echo "<script>alert('The collation of your database has been successfully changed!');</script>";
}
?>
I store my data this way:
accountsTable ->
key1 -> account1
key2 -> account2
in order to get object data:
accountsDb = mDatabase.child("accountsTable");
accountsDb.child("some key").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
try{
Account account = snapshot.getChildren().iterator().next()
.getValue(Account.class);
} catch (Throwable e) {
MyLogger.error(this, "onCreate eror", e);
}
}
@Override public void onCancelled(DatabaseError error) { }
});
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
I thought by setting the first element to a null would clear the entire contents of a char array.
That is not correct as you discovered
However, this only sets the first element to null.
Exactly!
You need to use memset to clear all the data, it is not sufficient to set one of the entries to null.
However, if setting an element of the array to null means something special (for example when using a null terminating string in) it might be sufficient to set the first element to null. That way any user of the array will understand that it is empty even though the array still includes the old chars in memory
There is, indeed, prevision for such feature, look http://www.w3.org/TR/css3-values/#attr-notation
This fiddle should work like what you need, but will not for now.
Unfortunately, it's still a draft, and isn't fully implemented on major browsers.
It does work for content
on pseudo-elements, though.
No one says that you need to modify the .htacces and add the directory in the rewrite condition. I've created a directory "public" in the root directory alongside with "system", "application", "index.php". and edited the .htaccess file like this:
RewriteCond $1 !^(index\.php|public|robots\.txt)
Now you have to just call <?php echo base_url()."/public/yourdirectory/yuorfile";?>
You can add subdirectory inside "public" dir as you like.
One approach is to build the image locally and then do:
docker save imageNameGoesHere | pv | (eval $(minikube docker-env) && docker load)
minikube docker-env
might not return the correct info running under a different user / sudo. Instead you can run sudo -u yourUsername minikube docker-env
.
It should return something like:
export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://192.168.99.100:2376"
export DOCKER_CERT_PATH="/home/chris/.minikube/certs"
export DOCKER_API_VERSION="1.23"
# Run this command to configure your shell:
# eval $(minikube docker-env)
Strongly typed enums aiming to solve multiple problems and not only scoping problem as you mentioned in your question:
Thus, it is impossible to implicitly convert a strongly typed enum to integers, or even its underlying type - that's the idea. So you have to use static_cast
to make conversion explicit.
If your only problem is scoping and you really want to have implicit promotion to integers, then you better off using not strongly typed enum with the scope of the structure it is declared in.
You can try with method select
DataRow[] rows = table.Select("ID = 7");
If you have query like:
SELECT * FROM user WHERE id IN (1, 2, 3, 4 -- and thousands of another keys)
you may increase performace if rewrite your query like:
SELECT * FROM user WHERE id = ANY(VALUES (1), (2), (3), (4) -- and thousands of another keys)
You could directly inject the values into JavaScript:
//View.cshtml
<script type="text/javascript">
var arrayOfArrays = JSON.parse('@Html.Raw(Model.Addresses)');
</script>
See JSON.parse
, Html.Raw
Alternatively you can get the values via Ajax:
public ActionResult GetValues()
{
// logic
// Edit you don't need to serialize it just return the object
return Json(new { Addresses: lAddressGeocodeModel });
}
<script type="text/javascript">
$(function() {
$.ajax({
type: 'POST',
url: '@Url.Action("GetValues")',
success: function(result) {
// do something with result
}
});
});
</script>
See jQuery.ajax
Better one: Instead of using extra span tags in html and increasing html code, you can do as below:
<div id="sc-nav-display">
<table class="sc-nav-table">
<tr>
<th class="nav-invent-head">Inventory</th>
<th class="nav-orders-head">Orders</th>
</tr>
</table>
</div>
Here, you can use CSS as below:
#sc-nav-display th{
font-weight: normal;
}
You just need to use ID assigned to the respected div tag of table. I used "#sc-nav-display" with "th" in CSS, so that, every other table headings will remain BOLD until and unless you do the same to all others table head as I said.
swift 4
==> Getting iOS device current time:-
print(" ---> ",(Calendar.current.component(.hour, from: Date())),":",
(Calendar.current.component(.minute, from: Date())),":",
(Calendar.current.component(.second, from: Date())))
output: ---> 10 : 11: 34
Use the class
function
>> b = 2
b =
2
>> a = 'Hi'
a =
Hi
>> class(b)
ans =
double
>> class(a)
ans =
char
In the Script Editor:
do shell script "/full/path/to/your/script -with 'all desired args'
"
Save as an application bundle.
As long as all you want to do is get the effect of the script, this will work fine. You won't see STDOUT or STDERR.
Path is a new feature of Django 2.0. Explained here : https://docs.djangoproject.com/en/2.0/releases/2.0/#whats-new-2-0
Look like more pythonic way, and enable to not use regular expression in argument you pass to view... you can ue int() function for exemple.
Same issue as in Error in launching AVD:
1) Install the Intel x86 Emulator Accelerator (HAXM installer) from the Android SDK Manager;
2) Run (for Windows):
{SDK_FOLDER}\extras\intel\Hardware_Accelerated_Execution_Manager\intelhaxm.exe
or (for OSX):
{SDK_FOLDER}\extras\intel\Hardware_Accelerated_Execution_Manager\IntelHAXM_1.1.1_for_10_9_and_above.dmg
3) Start the emulator.
<script>
function getSummary(id)
{
$.ajax({
type: "GET",//post
url: 'Your URL',
data: "id="+id, // appears as $_GET['id'] @ ur backend side
success: function(data) {
// data is ur summary
$('#summary').html(data);
}
});
}
</script>
If you just need to await
to avoid nesting code:
let json;
await new Promise(done => $.getJSON('https://***', async function (data) {
json = data;
done();
}));
For use the syntax like return Post::getAll();
you should have a magic function __callStatic
in your class where handle all static calls:
public static function __callStatic($method, $parameters)
{
return (new static)->$method(...$parameters);
}
For me this was thrown when running unit tests under MSTest
(VS2015). Had to add
<startup useLegacyV2RuntimeActivationPolicy="true">
</startup>
in
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\TE.ProcessHost.Managed.exe.config
First of all use
mysqli_connect($dbhost,$dbuser,$dbpass,$dbname)
Second - put mysqli_
everywhere instead of mysql_
Third - use this
$sql = "UPDATE anstalld SET mandag = '.$mandag.', tisdag = '.$tisdag.', onsdag = '.$onsdag.', torsdag = '.$torsdag.', fredag = '.$fredag.' WHERE namn = '.$namn.'";
$retval = mysqli_query( $conn, $sql ); //execute your query
if Your data is being updated in your database but not in your table its because when you will click on update button, the request is made to the same file. It first selects the data from the database when it is not updated prints it in the table and then update it according to the flow. If you have to update it as you click on update button then put this section
<?php
if(isset($_POST['update']))
{
$namn = $_POST['namnid'];
$mandag = $_POST['mandagid'];
$tisdag = $_POST['tisdagid'];
$onsdag = $_POST['onsdagid'];
$torsdag = $_POST['torsdagid'];
$fredag = $_POST['fredagid'];
$sql = mysql_query("UPDATE anstalld SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn'");
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
}
?>`
after connecting with database.
Below is a minimal code to achieve the effect.
This also works responsively since the border-radius
is in percentage.
.semi-circle{_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
border-radius: 50% 50% 0 0 / 100% 100% 0 0;_x000D_
border: 10px solid #000;_x000D_
border-bottom: 0;_x000D_
}
_x000D_
<div class="semi-circle"></div>
_x000D_
In my case, I had to open up
Documents\IISExpress\config
folder and rename or delete existing config files. After this step, I ran the application and IISExpress generated new config files and the error was gone.
To do this for a specific target, you can do the following:
target_compile_definitions(my_target PRIVATE FOO=1 BAR=1)
You should do this if you have more than one target that you're building and you don't want them all to use the same flags. Also see the official documentation on target_compile_definitions.
Felipsmartins is correct.
It is worth mentioning that it is because you cannot really use the -d/--data option if this is not a POST request. But this is still possible if you use the -G option.
Which means you can do this:
curl -X DELETE -G 'http://localhost:5000/locations' -d 'id=3'
Here it is a bit silly but when you are on the command line and you have a lot of parameters, it is a lot tidier.
I am saying this because cURL commands are usually quite long, so it is worth making it on more than one line escaping the line breaks.
curl -X DELETE -G \
'http://localhost:5000/locations' \
-d id=3 \
-d name=Mario \
-d surname=Bros
This is obviously a lot more comfortable if you use zsh. I mean when you need to re-edit the previous command because zsh lets you go line by line. (just saying)
Hope it helps.
Yes, each package must be defined in its own directory.
The source structure is defined in How to Write Go Code.
A package is a component that you can use in more than one program, that you can publish, import, get from an URL, etc. So it makes sense for it to have its own directory as much as a program can have a directory.
It is not planned for IE8. See the CSS Compatibility page.
Beyond that no plans have been released. Rumors exist that IE8 will be the last version for Windows XP
Install sshpass, then launch the command:
sshpass -p "yourpassword" ssh -o StrictHostKeyChecking=no yourusername@hostname
It's not possible to run a java class from a WAR file. WAR files have a different structure to Jar files.
To find the related java classes, export (preferred way to use ant) them as Jar put it in your web app lib.
Then you can use the jar file as normal to run java program. The same jar was also referred in web app (if you put this jar in web app lib)
Using CMD you can run your python scripts as long as the installed python is added to the path with the following line:
C: \ Python27;
The (27) is example referring to version 2.7, add as per your version.
Path to system path:
Control Panel => System and Security => System => Advanced Settings => Advanced => Environment Variables.
Under "User Variables," append the PATH variable to the path of the Python installation directory (As above).
Once this is done, you can open a CMD where your scripts are saved, or manually navigate through the CMD.
To run the script enter:
C: \ User \ X \ MyScripts> python ScriptName.py
Yes, you will need to specify the width for each cell, otherwise they will try to be "intelligent" about it and divide the 100% between whichever cells think they need it most. Cells with more content will take up more width than those with less.
To make sure you get equal width for each cell you need to make it clear. Either do it as you already have, or use CSS.
table.className td { width: 25%; }
<div onmouseover='alert("welcome")' id="sub1 sub2 sub3">some text</div>
Or something like this
you can't force refresh but you can forward all old ip requests to new one. for a website:
replace [OLD_IP] with old server's ip
replace [NEW_IP] with new server's ip
run & win.
echo "1" > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A PREROUTING -d [OLD_IP] -p tcp --dport 80 -j DNAT --to-destination [NEW_IP]:80
iptables -t nat -A PREROUTING -d [OLD_IP] -p tcp --dport 443 -j DNAT --to-destination [NEW_IP]:443
iptables -t nat -A POSTROUTING -j MASQUERADE
If you are on Ubuntu,
sudo su postgres
pg_dump -d <database_name> -t <table_name> > file.sql
Make sure that you are executing the command where the postgres
user have write permissions (Example: /tmp
)
Edit
If you want to dump the .sql in another computer, you may need to consider skipping the owner information getting saved into the .sql file.
You can use pg_dump --no-owner -d <database_name> -t <table_name> > file.sql
I don't see why you couldn't do it. I am a book person, so pick a book and run through it. Set up some small projects and finish them. 10 weeks is longer then I usually get to learn a new language.
Have fun and hope you learn a lot.
I would post the books I learned java with but they are at home and I ain't.
Try this
df.drop(df.iloc[:, 1:69], inplace=True, axis=1)
This works for me
You could just declare a DBMS_SQL.VARCHAR2_TABLE to hold an in-memory variable length array indexed by a BINARY_INTEGER:
DECLARE
name_array dbms_sql.varchar2_table;
BEGIN
name_array(1) := 'Tim';
name_array(2) := 'Daisy';
name_array(3) := 'Mike';
name_array(4) := 'Marsha';
--
FOR i IN name_array.FIRST .. name_array.LAST
LOOP
-- Do something
END LOOP;
END;
You could use an associative array (used to be called PL/SQL tables) as they are an in-memory array.
DECLARE
TYPE employee_arraytype IS TABLE OF employee%ROWTYPE
INDEX BY PLS_INTEGER;
employee_array employee_arraytype;
BEGIN
SELECT *
BULK COLLECT INTO employee_array
FROM employee
WHERE department = 10;
--
FOR i IN employee_array.FIRST .. employee_array.LAST
LOOP
-- Do something
END LOOP;
END;
The associative array can hold any make up of record types.
Hope it helps, Ollie.
// looking for that last hex?
org.joda.DateTime@57110da6
If you're looking into the hashcode
Java types when you do a .toString()
on an object the underlying code is this:
Integer.toHexString(hashCode())
I want to refine this a little bit because down-votes indicate to me that people don't understand that these suggestions are like "last hope" approach for someone who got into the state described in the question.
Check your console input history and/or ant scripts you have been using if you have them. Keep in mind that the console history will not be saved if you were promoted for password but if you entered it within for example signing command you can find it.
You mentioned you have a zip with a password in which your certificate file is stored, you could try just brute force opening that with many tools available. People will say "Yea but what if you used strong password, you should bla,bla,bla..." Unfortunately in that case tough-luck. But people are people and they sometimes use simple passwords. For you any tool that can provide dictionary attacks in which you can enter your own words and set them to some passwords you suspect might help you. Also if password is short enough with today CPUs even regular brute force guessing might work since your zip file does not have any limitation on number of guesses so you will not get blocked as if you tried to brute force some account on a website.
use the below pattern to get content between element. Replace [tag]
with the actual element you wish to extract the content from.
<[tag]>(.+?)</[tag]>
Sometime tags will have attributes, like anchor
tag having href
, then use the below pattern.
<[tag][^>]*>(.+?)</[tag]>
As Davide Gualano has been told. This one
$("#myDiv").load("myScript.php?var=x&var2=y&var3=z")
use GET method for sending the request, and this one
$("#myDiv").load("myScript.php", {var:x, var2:y, var3:z})
use POST method for sending the request. But any limitation that is applied to each method (post/get) is applied to the alternative usages that has been mentioned in the question.
For example: url length limits the amount of sending data in GET method.
pathToShell="/home/praveen/"
chmod a+x $pathToShell"myShell.sh"
sh $pathToShell"myShell.sh"
This is a security update. If an attacker can modify some file in the web server (the JS one, for example), he can make every loaded pages to download another script (for example to keylog your password or steal your SessionID and send it to his own server).
To avoid it, the browser check the Same-origin policy
Your problem is that the browser is trying to load something with your script (with an Ajax request) that is on another domain (or subdomain). To avoid it (if it is on your own website) you can:
As stated by @Dugini, some config entries have been removed. Maximal:
webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
"httpProxy":PROXY,
"ftpProxy":PROXY,
"sslProxy":PROXY,
"noProxy":[],
"proxyType":"MANUAL"
}
The only real use case for GROUP BY without aggregation is when you GROUP BY more columns than are selected, in which case the selected columns might be repeated. Otherwise you might as well use a DISTINCT.
It's worth noting that other RDBMS's do not require that all non-aggregated columns be included in the GROUP BY. For example in PostgreSQL if the primary key columns of a table are included in the GROUP BY then other columns of that table need not be as they are guaranteed to be distinct for every distinct primary key column. I've wished in the past that Oracle did the same as it would have made for more compact SQL in many cases.
I had the same requirement for a project I am doing. But none of the answers came elegant to my requirement. Here is something which finally helped me, and might be useful for this case:
from bokeh.io import export_png, export_svgs
from bokeh.models import ColumnDataSource, DataTable, TableColumn
def save_df_as_image(df, path):
source = ColumnDataSource(df)
df_columns = [df.index.name]
df_columns.extend(df.columns.values)
columns_for_table=[]
for column in df_columns:
columns_for_table.append(TableColumn(field=column, title=column))
data_table = DataTable(source=source, columns=columns_for_table,height_policy="auto",width_policy="auto",index_position=None)
export_png(data_table, filename = path)
9Rays used to have a decompiler, but I haven't checked in a while. It was not free, I remember...
There is also a new one (at least for me) named Dis#.
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
try this :
driver = webdriver.Chrome(ChromeDriverManager().install())
Don't know if this will be everybody's answer, but after some digging, here's what we came up with.
The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)? The key to the issue wasn't that we couldn't connect, but that it was intermittent
After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went. Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).
The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.
So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak. Hope that helps.
Short answer:
myView.layer.cornerRadius = 8
myView.layer.masksToBounds = true // optional
If you have come to this answer, you have probably already seen enough to solve your problem. I'm adding this answer to give a bit more visual explanation for why things do what they do.
If you start with a regular UIView
it has square corners.
let blueView = UIView()
blueView.frame = CGRect(x: 100, y: 100, width: 100, height: 50)
blueView.backgroundColor = UIColor.blueColor()
view.addSubview(blueView)
You can give it round corners by changing the cornerRadius
property of the view's layer
.
blueView.layer.cornerRadius = 8
Larger radius values give more rounded corners
blueView.layer.cornerRadius = 25
and smaller values give less rounded corners.
blueView.layer.cornerRadius = 3
This might be enough to solve your problem right there. However, sometimes a view can have a subview or a sublayer that goes outside of the view's bounds. For example, if I were to add a subview like this
let mySubView = UIView()
mySubView.frame = CGRect(x: 20, y: 20, width: 100, height: 100)
mySubView.backgroundColor = UIColor.redColor()
blueView.addSubview(mySubView)
or if I were to add a sublayer like this
let mySubLayer = CALayer()
mySubLayer.frame = CGRect(x: 20, y: 20, width: 100, height: 100)
mySubLayer.backgroundColor = UIColor.redColor().CGColor
blueView.layer.addSublayer(mySubLayer)
Then I would end up with
Now, if I don't want things hanging outside of the bounds, I can do this
blueView.clipsToBounds = true
or this
blueView.layer.masksToBounds = true
which gives this result:
Both clipsToBounds
and masksToBounds
are equivalent. It is just that the first is used with UIView
and the second is used with CALayer
.
I found a very easy solution to this problem.
python.exe
C:\xxx\...\python.exe your_script.py
I'm not sure whether the spells of these options are right, since I'm using Chinese version of Windows.
So my question is: Is there a way to tell the compiler that a long long int is the also a int64_t, just like long int is?
This is a good question or problem, but I suspect the answer is NO.
Also, a long int
may not be a long long int
.
# if __WORDSIZE == 64 typedef long int int64_t; # else __extension__ typedef long long int int64_t; # endif
I believe this is libc. I suspect you want to go deeper.
In both 32-bit compile with GCC (and with 32- and 64-bit MSVC), the output of the program will be:
int: 0 int64_t: 1 long int: 0 long long int: 1
32-bit Linux uses the ILP32 data model. Integers, longs and pointers are 32-bit. The 64-bit type is a long long
.
Microsoft documents the ranges at Data Type Ranges. The say the long long
is equivalent to __int64
.
However, the program resulting from a 64-bit GCC compile will output:
int: 0 int64_t: 1 long int: 1 long long int: 0
64-bit Linux uses the LP64
data model. Longs are 64-bit and long long
are 64-bit. As with 32-bit, Microsoft documents the ranges at Data Type Ranges and long long is still __int64
.
There's a ILP64
data model where everything is 64-bit. You have to do some extra work to get a definition for your word32
type. Also see papers like 64-Bit Programming Models: Why LP64?
But this is horribly hackish and does not scale well (actual functions of substance, uint64_t, etc)...
Yeah, it gets even better. GCC mixes and matches declarations that are supposed to take 64 bit types, so its easy to get into trouble even though you follow a particular data model. For example, the following causes a compile error and tells you to use -fpermissive
:
#if __LP64__
typedef unsigned long word64;
#else
typedef unsigned long long word64;
#endif
// intel definition of rdrand64_step (http://software.intel.com/en-us/node/523864)
// extern int _rdrand64_step(unsigned __int64 *random_val);
// Try it:
word64 val;
int res = rdrand64_step(&val);
It results in:
error: invalid conversion from `word64* {aka long unsigned int*}' to `long long unsigned int*'
So, ignore LP64
and change it to:
typedef unsigned long long word64;
Then, wander over to a 64-bit ARM IoT gadget that defines LP64
and use NEON:
error: invalid conversion from `word64* {aka long long unsigned int*}' to `uint64_t*'
If you would like to get GMT time only with intiger: var currentTime = new Date(); var currentYear ='2010' var currentMonth = 10; var currentDay ='30' var currentHours ='20' var currentMinutes ='20' var currentSeconds ='00' var currentMilliseconds ='00'
currentTime.setFullYear(currentYear);
currentTime.setMonth((currentMonth-1)); //0is January
currentTime.setDate(currentDay);
currentTime.setHours(currentHours);
currentTime.setMinutes(currentMinutes);
currentTime.setSeconds(currentSeconds);
currentTime.setMilliseconds(currentMilliseconds);
var currentTimezone = currentTime.getTimezoneOffset();
currentTimezone = (currentTimezone/60) * -1;
var gmt ="";
if (currentTimezone !== 0) {
gmt += currentTimezone > 0 ? ' +' : ' ';
gmt += currentTimezone;
}
alert(gmt)
This works for me, I only need first numbers in string:
TO_NUMBER(regexp_substr(h.HIST_OBSE, '\.*[[:digit:]]+\.*[[:digit:]]*'))
the field had the following string: "(43 Paginas) REGLAS DE PARTICIPACION"
.
result field: 43
Could the Barcode Rendering Framework at Codeplex GitHub be of help?
This Worked for me
Actually error is a array which contain error message and other values for elements we pass, you can console.log(error); and see. Inside if condition "error.appendTo($(element).parents('div').find($('.errorEmail')));" Is nothing but finding html element in code and passing the error message.
$("form[name='contactUs']").validate({
rules: {
message: 'required',
name: "required",
phone_number: {
required: true,
minlength: 10,
maxlength: 10,
number: false
},
email: {
required: true,
email: true
}
},
messages: {
name: "Please enter your name",
email: "Please enter a valid email address",
message: "Please enter your message",
phone_number: "Please enter a valid mobile number"
},
errorPlacement: function(error, element) {
$("#errorText").empty();
if(error[0].htmlFor == 'name')
{
error.appendTo($(element).parents('div').find($('.errorName')));
}
if(error[0].htmlFor == 'email')
{
error.appendTo($(element).parents('div').find($('.errorEmail')));
}
if(error[0].htmlFor == 'phone_number')
{
error.appendTo($(element).parents('div').find($('.errorMobile')));
}
if(error[0].htmlFor == 'message')
{
error.appendTo($(element).parents('div').find($('.errorMessage')));
}
}
});
For me doesnt put jars to lib directory and set to Build path enought.
The right thing was add it to Deployment Assembly.
Like This:
<?= $form->field($model, 'hidden')->hiddenInput(['class' => 'form-control', 'maxlength' => true,])->label(false) ?>
SQL is primarily a set-orientated language - it's generally a bad idea to use a loop in it.
In this case, a similar result could be achieved using a recursive CTE:
with cte as
(select 1 i union all
select i+1 i from cte where i < 5)
select dateadd(d, i-1, '2010-01-01') from cte
You can use relative positioning to overlap your elements. However, the space they would normally occupy will still be reserved for the element:
<div style="background-color:#f00;width:200px;height:100px;">
DEFAULT POSITIONED
</div>
<div style="background-color:#0f0;width:200px;height:100px;position:relative;top:-50px;left:50px;">
RELATIVE POSITIONED
</div>
<div style="background-color:#00f;width:200px;height:100px;">
DEFAULT POSITIONED
</div>
In the example above, there will be a block of white space between the two 'DEFAULT POSITIONED' elements. This is caused, because the 'RELATIVE POSITIONED' element still has it's space reserved.
If you use absolute positioning, your elements will not have any space reserved, so your element will actually overlap, without breaking your document:
<div style="background-color:#f00;width:200px;height:100px;">
DEFAULT POSITIONED
</div>
<div style="background-color:#0f0;width:200px;height:100px;position:absolute;top:50px;left:50px;">
ABSOLUTE POSITIONED
</div>
<div style="background-color:#00f;width:200px;height:100px;">
DEFAULT POSITIONED
</div>
Finally, you can control which elements are on top of the others by using z-index:
<div style="z-index:10;background-color:#f00;width:200px;height:100px;">
DEFAULT POSITIONED
</div>
<div style="z-index:5;background-color:#0f0;width:200px;height:100px;position:absolute;top:50px;left:50px;">
ABSOLUTE POSITIONED
</div>
<div style="z-index:0;background-color:#00f;width:200px;height:100px;">
DEFAULT POSITIONED
</div>
I find this image very meaningful :
(from : Oliver Steele -My Git Workflow (2008) )
Building on the answer of JMax, use this formula for the dynamic named range to make the solution work for multiple rows:
=OFFSET(Sheet2!$A$1,MATCH(INDIRECT("Sheet1!"&ADDRESS(ROW(),COLUMN(),4))&"*",Sheet2!$A$1:$A$300,0)-1,0,COUNTA(Sheet2!$A:$A))
\D
is a non-digit, and so then \D*
is any number of non-digits in a row. So your whole string should match ^\D*$
.
Check on http://rubular.com/r/AoWBmrbUkN it works perfectly.
You can also try on http://regexpal.com/ OR http://www.regextester.com/
I had similar problem before. But this was resolved when I started using hostname instead of IP address in my connection string.
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
switch( keyCode ) {
case KeyEvent.VK_UP:
// handle up
break;
case KeyEvent.VK_DOWN:
// handle down
break;
case KeyEvent.VK_LEFT:
// handle left
break;
case KeyEvent.VK_RIGHT :
// handle right
break;
}
}
Simple explanation:
foo = "BEST DAY EVER" #assign a string to variable foo.
=> foo.downcase #call method downcase, this is without any exclamation.
"best day ever" #returns the result in downcase, but no change in value of foo.
=> foo #call the variable foo now.
"BEST DAY EVER" #variable is unchanged.
=> foo.downcase! #call destructive version.
=> foo #call the variable foo now.
"best day ever" #variable has been mutated in place.
But if you ever called a method downcase!
in the explanation above, foo
would change to downcase permanently. downcase!
would not return a new string object but replace the string in place, totally changing the foo
to downcase.
I suggest you don't use downcase!
unless it is totally necessary.
The following code should work. It takes every filename in the current directory, if the filename contains the pattern CHEESE_CHEESE_
then it is renamed. If not nothing is done to the filename.
import os
for fileName in os.listdir("."):
os.rename(fileName, fileName.replace("CHEESE_CHEESE_", "CHEESE_"))
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv
:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv
and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
Unfortunately, there doesn't appear to be a magic bullet. Bottom line up front: "context".
Google indeed ignores most punctuation, with the following exceptions:
As such, it is not well suited for these types of searchs. Google Code however does have syntax for searching through their code projects, that includes a robust language/syntax for dealing with "special characters". If looking at someone else's code could help solve a problem, this may be an option.
Unfortunately, this is not a limitation unique to google. You may find that your best successes hinge on providing as much 'context' to the problem as possible. If you are searching to find what $- means, providing information about the problem's domain may yield good results.
For example, searching "special perl variables" quickly yields your answer in the first entry on the results page.
try
netstat -a -t -n | grep 3306
to see any one listening to the 3306 port then kill it
I was having this problem for 2 days. Trying out the solutions posted on forums I accidentally ran into a situation where my log was getting this error
check that you do not already have another mysqld process
If, in addition to automatic two-way binding, you want to call a function when a value changes, you can break the two-way binding shortcut syntax to the more verbose version.
<input [(ngModel)]="yourVar"></input>
is shorthand for
<input [ngModel]="yourVar" (ngModelChange)="yourVar=$event"></input>
(see e.g. http://victorsavkin.com/post/119943127151/angular-2-template-syntax)
You could do something like this:
<input [(ngModel)]="yourVar" (ngModelChange)="changedExtraHandler($event)"></input>
Of course you can, just add the url localhost (without "http") in your app_domain and then add in your site_url http://localhost
(with http)
Update
Facebook change the things a little now, just go to the app settings and in the site url just add http: //localhost
and leave the App Domain empty
$('.class[value=3]').prop('checked', true);
I would say:
#mybox{_x000D_
background:green; _x000D_
}_x000D_
_x000D_
#mybox:hover{_x000D_
color:transparent;_x000D_
}
_x000D_
<div id="mybox">_x000D_
This text will disappear on hover _x000D_
</div>
_x000D_
This will hide text, but of course, it still contains the text, but it is a tricky way to hide the text (make in invisible), but it will work well
if you want saturday or sunday or any day of week but not exceeding current week(Sat-Sun) I got you covered with this piece of code.
public static DateTime GetDateInCurrentWeek(this DateTime date, DayOfWeek day)
{
var temp = date;
var limit = (int)date.DayOfWeek;
var returnDate = DateTime.MinValue;
if (date.DayOfWeek == day) return date;
for (int i = limit; i < 6; i++)
{
temp = temp.AddDays(1);
if (day == temp.DayOfWeek)
{
returnDate = temp;
break;
}
}
if (returnDate == DateTime.MinValue)
{
for (int i = limit; i > -1; i++)
{
date = date.AddDays(-1);
if (day == date.DayOfWeek)
{
returnDate = date;
break;
}
}
}
return returnDate;
}
If Maven update snapshot doesn't work and if you have Spring Tooling, one interesting way is to remove
Note: Maven update snapshot sometimes stops working if you use anything else i.e. eclipse:eclipse or Spring Tooling
Here is the code to base64 encode directly to byte array (tested to be performing +-10% of .Net Implementation, but allocates half the memory):
static public void testBase64EncodeToBuffer()
{
for (int i = 1; i < 200; ++i)
{
// prep test data
byte[] testData = new byte[i];
for (int j = 0; j < i; ++j)
testData[j] = (byte)(j ^ i);
// test
testBase64(testData);
}
}
static void testBase64(byte[] data)
{
if (!appendBase64(data, 0, data.Length, false).SequenceEqual(System.Text.Encoding.ASCII.GetBytes(Convert.ToBase64String(data)))) throw new Exception("Base 64 encoding failed");
}
static public byte[] appendBase64(byte[] data
, int offset
, int size
, bool addLineBreaks = false)
{
byte[] buffer;
int bufferPos = 0;
int requiredSize = (4 * ((size + 2) / 3));
// size/76*2 for 2 line break characters
if (addLineBreaks) requiredSize += requiredSize + (requiredSize / 38);
buffer = new byte[requiredSize];
UInt32 octet_a;
UInt32 octet_b;
UInt32 octet_c;
UInt32 triple;
int lineCount = 0;
int sizeMod = size - (size % 3);
// adding all data triplets
for (; offset < sizeMod;)
{
octet_a = data[offset++];
octet_b = data[offset++];
octet_c = data[offset++];
triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
buffer[bufferPos++] = base64EncodingTable[(triple >> 3 * 6) & 0x3F];
buffer[bufferPos++] = base64EncodingTable[(triple >> 2 * 6) & 0x3F];
buffer[bufferPos++] = base64EncodingTable[(triple >> 1 * 6) & 0x3F];
buffer[bufferPos++] = base64EncodingTable[(triple >> 0 * 6) & 0x3F];
if (addLineBreaks)
{
if (++lineCount == 19)
{
buffer[bufferPos++] = 13;
buffer[bufferPos++] = 10;
lineCount = 0;
}
}
}
// last bytes
if (sizeMod < size)
{
octet_a = offset < size ? data[offset++] : (UInt32)0;
octet_b = offset < size ? data[offset++] : (UInt32)0;
octet_c = (UInt32)0; // last character is definitely padded
triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
buffer[bufferPos++] = base64EncodingTable[(triple >> 3 * 6) & 0x3F];
buffer[bufferPos++] = base64EncodingTable[(triple >> 2 * 6) & 0x3F];
buffer[bufferPos++] = base64EncodingTable[(triple >> 1 * 6) & 0x3F];
buffer[bufferPos++] = base64EncodingTable[(triple >> 0 * 6) & 0x3F];
// add padding '='
sizeMod = size % 3;
// last character is definitely padded
buffer[bufferPos - 1] = (byte)'=';
if (sizeMod == 1) buffer[bufferPos - 2] = (byte)'=';
}
return buffer;
}
Since the question is How to generate random colors in matplotlib?
and as I was searching for an answer concerning pie plots
, I think it is worth to put an answer here (for pies
)
import numpy as np
from random import sample
import matplotlib.pyplot as plt
import matplotlib.colors as pltc
all_colors = [k for k,v in pltc.cnames.items()]
fracs = np.array([600, 179, 154, 139, 126, 1185])
labels = ["label1", "label2", "label3", "label4", "label5", "label6"]
explode = ((fracs == max(fracs)).astype(int) / 20).tolist()
for val in range(2):
colors = sample(all_colors, len(fracs))
plt.figure(figsize=(8,8))
plt.pie(fracs, labels=labels, autopct='%1.1f%%',
shadow=True, explode=explode, colors=colors)
plt.legend(labels, loc=(1.05, 0.7), shadow=True)
plt.show()
Output
Per Byron's answer, you can't set networkaddress.cache.ttl
or networkaddress.cache.negative.ttl
as System Properties by using the -D
flag or calling System.setProperty
because these are not System properties - they are Security properties.
If you want to use a System property to trigger this behavior (so you can use the -D
flag or call System.setProperty
), you will want to set the following System property:
-Dsun.net.inetaddr.ttl=0
This system property will enable the desired effect.
But be aware: if you don't use the -D
flag when starting the JVM process and elect to call this from code instead:
java.security.Security.setProperty("networkaddress.cache.ttl" , "0")
This code must execute before any other code in the JVM attempts to perform networking operations.
This is important because, for example, if you called Security.setProperty
in a .war file and deployed that .war to Tomcat, this wouldn't work: Tomcat uses the Java networking stack to initialize itself much earlier than your .war's code is executed. Because of this 'race condition', it is usually more convenient to use the -D
flag when starting the JVM process.
If you don't use -Dsun.net.inetaddr.ttl=0
or call Security.setProperty
, you will need to edit $JRE_HOME/lib/security/java.security
and set those security properties in that file, e.g.
networkaddress.cache.ttl = 0
networkaddress.cache.negative.ttl = 0
But pay attention to the security warnings in the comments surrounding those properties. Only do this if you are reasonably confident that you are not susceptible to DNS spoofing attacks.
Yes to the first question and no to the second question; it's a virtual machine. Your problems are probably related to unspecified changes in library implementation between versions. Although it could be, say, a race condition.
There are some hoops the VM has to go through. Notably references are treated in class files as if they took the same space as int
s on the stack. double
and long
take up two reference slots. For instance fields, there's some rearrangement the VM usually goes through anyway. This is all done (relatively) transparently.
Also some 64-bit JVMs use "compressed oops". Because data is aligned to around every 8 or 16 bytes, three or four bits of the address are useless (although a "mark" bit may be stolen for some algorithms). This allows 32-bit address data (therefore using half as much bandwidth, and therefore faster) to use heap sizes of 35- or 36-bits on a 64-bit platform.
A custom map seems appropriate in this case. This is what I use to paste yanked items in insert mode:
inoremap <Leader>p <ESC>pa
My Leader
key here is \
; this means hitting \p
in insert mode would paste the previously yanked items/lines.
The reason it exits is because the shell script is run first as PID 1 and when that's complete, PID 1 is gone, and docker only runs while PID 1 is.
You can use supervisor to do everything, if run with the "-n" flag it's told not to daemonize, so it will stay as the first process:
CMD ["/usr/bin/supervisord", "-n"]
And your supervisord.conf:
[supervisord]
nodaemon=true
[program:startup]
priority=1
command=/root/credentialize_and_run.sh
stdout_logfile=/var/log/supervisor/%(program_name)s.log
stderr_logfile=/var/log/supervisor/%(program_name)s.log
autorestart=false
startsecs=0
[program:nginx]
priority=10
command=nginx -g "daemon off;"
stdout_logfile=/var/log/supervisor/nginx.log
stderr_logfile=/var/log/supervisor/nginx.log
autorestart=true
Then you can have as many other processes as you want and supervisor will handle the restarting of them if needed.
That way you could use supervisord in cases where you might need nginx and php5-fpm and it doesn't make much sense to have them apart.
There are few mistakes you are doing:
addRow
methodsplice
method to remove an element from an array at particular index.my-item
component, where this can be modified.You can see working code here.
addRow(){
this.rows.push({description: '', unitprice: '' , code: ''}); // what to push unto the rows array?
},
removeRow(index){
this. itemList.splice(index, 1)
}
You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);
, you just need to get rid of default sum(max_count)
. No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL
as the value for every cell in that column.
So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.
You also have the option to always COALESCE
the column to your desired default and leave it NULL
for now. This option fails when you want NULL
to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE
.
If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.
See the docs about querying.
It would be:
$or: [{a: 5}, {a: 6}] // (a = 5 OR a = 6)
Use Manatee.Json https://github.com/gregsdennis/Manatee.Json/wiki/Usage
And you can convert the entire object to a string, filename.json is expected to be located in documents folder.
var text = File.ReadAllText("filename.json");
var json = JsonValue.Parse(text);
while (JsonValue.Null != null)
{
Console.WriteLine(json.ToString());
}
Console.ReadLine();
To avoid common mistakes when using exclude
, remember:
You can not add multiple conditions into an exclude() block like filter
.
To exclude multiple conditions, you must use multiple exclude()
Example
Incorrect:
User.objects.filter(email='[email protected]').exclude(profile__nick_name='', profile__avt='')
Correct:
User.objects.filter(email='[email protected]').exclude(profile__nick_name='').exclude(profile__avt='')
Tomalak already gave you a correct answer, but I would like to add that most of the times when you would like to know the VBA code needed to do a certain action in the user interface it is a good idea to record a macro.
In this case click Record Macro on the developer tab of the Ribbon, freeze the top row and then stop recording. Excel will have the following macro recorded for you which also does the job:
With ActiveWindow
.SplitColumn = 0
.SplitRow = 1
End With
ActiveWindow.FreezePanes = True
If file size is still too large it could help using ps2pdf to downscale the resolution of the produced pdf file:
pdf2ps input.pdf tmp.ps
ps2pdf -dPDFSETTINGS=/screen -dDownsampleColorImages=true -dColorImageResolution=200 -dColorImageDownsampleType=/Bicubic tmp.ps output.pdf
Adjust the value of the -dColorImageResolution option to achieve a result that fits your needs (the value describes the image resolution in DPIs). If your input file is in grayscale, replacing Color through Gray or using both options in the above command could also help. Further fine-tuning is possible by changing the -dPDFSETTINGS option to /default or /printer. For explanations of the all possible options consult the ps2pdf manual.
For all docker users, just run docker-php-ext-install mysqli
from inside your php container.
Update: More information on https://hub.docker.com/_/php in the section "How to install more PHP extensions".
"
is shown as \"
in the debugger, but the data is correct in the string, and you don't need to replace anything. Try to dump your string to a file and you will note that the string is correct.
SQL stands for Structured Query Language, and is the basis for which all Relational Database Management Systems allow the user to add, remove, update, or select records. Things like MySQ are the actual Management Systems which allow you to store and retrieve your data, whereas SQL is the actual language to do so.
The basic SQL is somewhat universal - Selects usually look the same, Inserts, Updates, Deletes, etc. Once you get beyond the basics, the commands and abilities of your individual Databases vary, and this is where you get people who are Oracle experts, MySQL, SQL Server, etc.
Basically, MySQL is one of many books holding everything, and SQL is how you go about reading that book.
ES-6 way to get title case of a word or entire line.
ex. input = 'hEllo' --> result = 'Hello'
ex. input = 'heLLo woRLd' --> result = 'Hello World'
const getTitleCase = (str) => {
if(str.toLowerCase().indexOf(' ') > 0) {
return str.toLowerCase().split(' ').map((word) => {
return word.replace(word[0], word[0].toUpperCase());
}).join(' ');
}
else {
return str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase();
}
}
The problem is that unless your tables are related you can't determine how to join them, so you'd have to arbitrarily join them, resulting in a cartesian product:
select Table1.col1, Table1.col2, Table2.col3, Table2.col4
from Table1
cross join Table2
If you had, for example, the following data:
col1 col2
a 1
b 2
col3 col4
y 98
z 99
You would end up with the following:
col1 col2 col3 col4
a 1 y 98
a 1 z 99
b 2 y 98
b 2 z 99
Is this what you're looking for? If not, and you have some means of relating the tables, then you'd need to include that in joining the two tables together, e.g.:
select Table1.col1, Table1.col2, Table2.col3, Table2.col4
from Table1
inner join Table2
on Table1.JoiningField = Table2.JoiningField
That would pull things together for you into however the data is related, giving you your result.
To do this with user input:
public static void getPow(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter first integer: "); // 3
int first = sc.nextInt();
System.out.println("Enter second integer: "); // 2
int second = sc.nextInt();
System.out.println(first + " to the power of " + second + " is " +
(int) Math.pow(first, second)); // outputs 9
Modify Mysql encryption
ALTER USER 'lcherukuri'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
Simply call list
on the generator.
lst = list(gen)
lst
Be aware that this affects the generator which will not return any further items.
You also cannot directly call list
in IPython, as it conflicts with a command for listing lines of code.
Tested on this file:
def gen():
yield 1
yield 2
yield 3
yield 4
yield 5
import ipdb
ipdb.set_trace()
g1 = gen()
text = "aha" + "bebe"
mylst = range(10, 20)
which when run:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.
There are debugger commands p
and pp
that will print
and prettyprint
any expression following them.
So you could use it as follows:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c
There is also an exec
command, called by prefixing your expression with !
, which forces debugger to take your expression as Python one.
ipdb> !list(g1)
[]
For more details see help p
, help pp
and help exec
when in debugger.
ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']
Use Boost asynchronous input/output threads, sleep for x milliseconds;
#include <boost/thread.hpp>
#include <boost/asio.hpp>
boost::thread::sleep(boost::get_system_time() + boost::posix_time::millisec(1000));
Suppose your screen id has a pattern. Then you can use the following code to kill all the attached screen at once.
result=$(screen -ls | grep 'pattern_of_screen_id' -o)
for i in $result;
do
`screen -X -S $i quit`;
done
...and to prepend (add the beginning of) each line with *,
%s/^/*/g
You should include "bPaginate": false,
into the configuration object you pass to your constructor parameters. As seen here: http://datatables.net/release-datatables/examples/basic_init/filter_only.html
As I understand you use ASP.NET authentication and to set cookies persistent you need to set FormsAuthenticationTicket.IsPersistent = true It is the main idea.
bool isPersisted = true;
var authTicket = new FormsAuthenticationTicket(
1,
user_name,
DateTime.Now,
DateTime.Now.AddYears(1),//Expiration (you can set it to 1 year)
isPersisted,//THIS IS THE MAIN FLAG
addition_data);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket );
if (isPersisted)
authCookie.Expires = authTicket.Expiration;
HttpContext.Current.Response.Cookies.Add(authCookie);
After 2 hours of searching, I found a way to fix it with just one line of command. You need to know the version of the package (Just search up PACKAGE version).
Command:
python3 -m pip install --pre --upgrade PACKAGE==VERSION.VERSION.VERSION
Paths specified with a .
are relative to the current working directory, not relative to the script file. So the file might be found if you run node app.js
but not if you run node folder/app.js
. The only exception to this is require('./file')
and that is only possible because require
exists per-module and thus knows what module it is being called from.
To make a path relative to the script, you must use the __dirname
variable.
var path = require('path');
path.join(__dirname, 'path/to/file')
or potentially
path.join(__dirname, 'path', 'to', 'file')
You want to convert it to an object first and then access normally making sure to cast it.
JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];
Just one thing to add to this (although I do think you have already had your question answered by others). In the interests of extensibility (since we all know it will happen at some point) you may want to check out the Composite Pattern This is ideal for working with "Tree-Like Structures"..
Like I said, I know you are only expecting one sub-level, but this could really be useful for you if you later need to extend ^_^
If boolean() is not available (the tool I'm using does not) one way to achieve it is:
//SELECT[@id='xpto']/OPTION[not(not(@selected))]
In this case, within the /OPTION, one of the options is the selected one. The "selected" does not have a value... it just exists, while the other OPTION do not have "selected". This achieves the objective.
First off, RangeToHTML
. The script calls it like a method, but it isn't. It's a popular function by MVP Ron de Bruin. Coincidentally, that links points to the exact source of the script you posted, before those few lines got b?u?t?c?h?e?r?e?d? modified.
On with Range.SpecialCells. This method operates on a range and returns only those cells that match the given criteria. In your case, you seem to be only interested in the visible text cells. Importantly, it operates on a Range, not on HTML text.
For completeness sake, I'll post a working version of the script below. I'd certainly advise to disregard it and revisit the excellent original by Ron the Bruin.
Sub Mail_Selection_Range_Outlook_Body()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set rng = Nothing
' Only send the visible cells in the selection.
Set rng = Sheets("Sheet1").Range("D4:D12").SpecialCells(xlCellTypeVisible)
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected. " & _
vbNewLine & "Please correct and try again.", vbOKOnly
Exit Sub
End If
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = ThisWorkbook.Sheets("Sheet2").Range("C1").Value
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.HTMLBody = RangetoHTML(rng)
' In place of the following statement, you can use ".Display" to
' display the e-mail message.
.Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Function RangetoHTML(rng As Range)
' By Ron de Bruin.
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
http://en.wikipedia.org/wiki/Division_by_zero
http://en.wikipedia.org/wiki/Unix_signal#SIGFPE
This should give you a really good idea. Since a modulus is, in its basic sense, division with a remainder, something % 0
IS division by zero and as such, will trigger a SIGFPE being thrown.
Router Link
routerLink with brackets and none - simple explanation.
The difference between routerLink= and [routerLink] is mostly like relative and absolute path.
Similar to a href you may want to navigate to ./about.html or https://your-site.com/about.html.
When you use without brackets then you navigate relative and without params;
my-app.com/dashboard/client
"jumping" from my-app.com/dashboard to my-app.com/dashboard/client
<a routerLink="client/{{ client.id }}" .... rest the same
When you use routerLink with brackets then you execute app to navigate absolute and you can add params how is the puzzle of your new link
first of all it will not include the "jump" from dashboard/ to dashboard/client/client-id and bring you data of client/client-id which is more helpful for EDIT CLIENT
<a [routerLink]="['/client', client.id]" ... rest the same
The absolute way or brackets routerLink require additional set up of you components and app.routing.module.ts
The code without error will "tell you more/what is the purpose of []" when you make the test. Just check this with or without []. Than you may experiments with selectors which - as mention above - helps with dynamics routing.
See whats the routerLink construct
You declared the constructor blowfish as this:
Blowfish(BlowfishAlgorithm algorithm);
So this line cannot exist (without further initialization later):
Blowfish _blowfish;
since you passed no parameter. It does not understand how to handle a parameter-less declaration of object "BlowFish" - you need to create another constructor for that.
I ran into this issue as well. I don't know the technical details of what was actually happening. However, in my situation, the root cause was that there was cascading deletes setup in the Oracle database and my JPA/Hibernate code was also trying to do the cascading delete calls. So my advice is to make sure that you know exactly what is happening.
Another reason to use merge is when using custom viewgroups in ListViews or GridViews. Instead of using the viewHolder pattern in a list adapter, you can use a custom view. The custom view would inflate an xml whose root is a merge tag. Code for adapter:
public class GridViewAdapter extends BaseAdapter {
// ... typical Adapter class methods
@Override
public View getView(int position, View convertView, ViewGroup parent) {
WallpaperView wallpaperView;
if (convertView == null)
wallpaperView = new WallpaperView(activity);
else
wallpaperView = (WallpaperView) convertView;
wallpaperView.loadWallpaper(wallpapers.get(position), imageWidth);
return wallpaperView;
}
}
here is the custom viewgroup:
public class WallpaperView extends RelativeLayout {
public WallpaperView(Context context) {
super(context);
init(context);
}
// ... typical constructors
private void init(Context context) {
View.inflate(context, R.layout.wallpaper_item, this);
imageLoader = AppController.getInstance().getImageLoader();
imagePlaceHolder = (ImageView) findViewById(R.id.imgLoader2);
thumbnail = (NetworkImageView) findViewById(R.id.thumbnail2);
thumbnail.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
public void loadWallpaper(Wallpaper wallpaper, int imageWidth) {
// ...some logic that sets the views
}
}
and here is the XML:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="@+id/imgLoader"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerInParent="true"
android:src="@drawable/ico_loader" />
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</merge>
<form method="post" action="">
<table>
<tr><td><input name="Submit" type="submit" value="refresh"></td></tr>
</table>
</form>
<?php
if(isset($_POST['Submit']))
{
header("Location: http://yourpagehere.com");
}
?>
If you are using brew with python, unfortunately, pip/pip3 ships with very limited options. You do not have --install-option, --target, --user options as mentioned above.
Note on pip install --user
The normal pip install --user is disabled for brewed Python. This is because of a bug in distutils, because Homebrew writes a distutils.cfg which sets the package prefix. A possible workaround (which puts executable scripts in ~/Library/Python/./bin) is:python -m pip install --user --install-option="--prefix=" <package-name>
You might find this line very cumbersome. I suggest use pyenv for management. If you are using
brew upgrade python python3
Ironically you are actually downgrade pip functionality.
(I post this answer, simply because pip in my mac osx does not have --target option, and I have spent hours fixing it)
What argument does Init
take? What is the new error message?
Method pointers in C++ are a bit difficult to use. Besides the method pointer itself, you also need to provide an instance pointer (in your case this
). Maybe Init
expects it as a separate argument?
background-image
takes multiple values.
so a combination of just 1 color linear-gradient and css blend modes
will do the trick.
.testclass {
background-image: url("../images/image.jpg"), linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5));
background-blend-mode: overlay;
}
note that there is no support on IE/Edge for CSS blend-modes at all.
If you're ever dynamically generating page content or loading content through AJAX, the following example is really the way you should go:
body
of the document, so regardless of what elements are added, moved, removed and re-added, all descendants of body
matching the selector specified will retain proper binding.The Code:
// Define the element we wish to bind to.
var bind_to = ':input';
// Prevent double-binding.
$(document.body).off('change', bind_to);
// Bind the event to all body descendants matching the "bind_to" selector.
$(document.body).on('change keyup', bind_to, function(event) {
alert('something happened!');
});
Please notice! I'm making use of $.on()
and $.off()
rather than other methods for several reasons:
$.live()
and $.die()
are deprecated and have been omitted from more recent versions of jQuery.$.change()
and $.keyup()
separately, or pass the same function declaration to each function called; Duplicating logic... Which is absolutely unacceptable.$.bind()
does not dynamically bind to elements as they are created. Therefore if you bind to :input
and then add an input to the DOM, that bind method is not attached to the new input. You'd then need to explicitly un-bind and then re-bind to all elements in the DOM (otherwise you'll end up with binds being duplicated). This process would need to be repeated each time an input was added to the DOM.Try to bind to the DOMSubtreeModified
event seeign as test is also just part of the DOM.
see this post here on SO:
Something like this should do the trick
function array_max_key($array) {
$max_key = -1;
$max_val = -1;
foreach ($array as $key => $value) {
if ($value > $max_val) {
$max_key = $key;
$max_val = $value;
}
}
return $max_key;
}
there is another technique
use
background-size:cover
That is it full set of css is
body {
background: url('images/body-bg.jpg') no-repeat center center fixed;
-moz-background-size: cover;
-webkit-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Latest browsers support the default property.
In my case the device date and time was changed manually .To solve the problem set the date and time to automatic .
<parent>
<groupId>com.test.vaquar.khan</groupId>
<artifactId>vk-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../projectname/pom.xml</relativePath>
</parent>
Add following line in parent
<relativePath>../projectname/pom.xml</relativePath>
You need relative path if you are building from local parent pom not available in nexsus, add pom in nexus then no need this path
If you just need to insert a new row with a data from another row,
insert into ORDER_ITEM select * from ORDER_ITEM where ITEM_NUMBER =123;
This one also works for nullable bools.
[ValueConversion(typeof(bool?), typeof(bool))]
public class InverseBooleanConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType != typeof(bool?))
{
throw new InvalidOperationException("The target must be a nullable boolean");
}
bool? b = (bool?)value;
return b.HasValue && !b.Value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return !(value as bool?);
}
#endregion
}
Overwriting the getRegister and postRegister is tricky - if you are using git there is a high possibility that .gitignore
is set to ignore framework files which will lead to the outcome that registration will still be possible in your production environment (if laravel is installed via composer for example)
Another possibility is using routes.php and adding this line:
Route::any('/auth/register','HomeController@index');
This way the framework files are left alone and any request will still be redirected away from the Frameworks register module.
@PostConstruct is run ONCE in first when Bean Created. the solution is create a Unused property and Do your Action in Getter method of this property and add this property to your .xhtml file like this :
<h:inputHidden value="#{loginBean.loginStatus}"/>
and in your bean code:
public void setLoginStatus(String loginStatus) {
this.loginStatus = loginStatus;
}
public String getLoginStatus() {
// Do your stuff here.
return loginStatus;
}
Somebody posted quite a few form fields to your page. The new default max introduced by the recent security update is 1000.
Try adding the following setting in your web.config's <appsettings>
block. in this block you are maximizing the MaxHttpCollection values this will override the defaults set by .net Framework. you can change the value accordingly as per your form needs
<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="2001" />
</appSettings>
For more information please read this post. For more insight into the security patch by microsoft you can read this Knowledge base article
The combo you need is
white-space: nowrap
on the parent and
display: inline-block; // or inline
on the children
I think you can't call
androidHttpTransport.call(SOAP_ACTION, envelope);
on main Thread.
Network operations should be done on different Thread.
Create another Thread or AsyncTask to call the method.