What about thinking the following way:
So when you have an abstract class Mammals, a subclass Human, and an interface Driving, then you can say
My suggestion is that the book knowledge phrase indicates that he wanted to hear the semantic difference between both (like others here already suggested).
Try this, at the end of the each loop, ids array will contain all the hexcodes.
var ids = [];
$(document).ready(function($) {
var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
$(".color_cell").each(function() {
code = $(this).attr('id');
ids.push(code);
$div.append(code + "<br />");
});
});
Try this it will list all the tags along with annotations & 9 lines of message for every tag:
git tag -n9
can also use
git tag -l -n9
if specific tags are to list:
git tag -l -n9 v3.*
(e.g, above command will only display tags starting with "v3.")
-l , --list List tags with names that match the given pattern (or all if no pattern is given). Running "git tag" without arguments also lists all tags. The pattern is a shell wildcard (i.e., matched using fnmatch(3)). Multiple patterns may be given; if any of them matches, the tag is shown.
You can also use $("ul li:first-child")
to only get the direct children of the UL.
I agree though, you need an ID or something else to identify the main UL otherwise it will just select them all. If you had a div with an ID around the UL the easiest thing to do would be$("#someDiv > ul > li")
I prefer using the value returned by System.currentTimeMillis()
for all kinds of calculations and only use Calendar
or Date
if I need to really display a value that is read by humans. This will also prevent 99% of your daylight-saving-time bugs. :)
I know I'm a little late to the party, but I did want to throw some interjections. (I would have commented but not enough reputation points yet, so, here's a full answer).
This requires the latest version of VS Code, Azure Repo Extention, and Git to be installed.
Anyone looking to use the new VS Code (or using the preview like myself), when you go to the Settings (Still File -> Preferences -> Settings or CTRL+, ) you'll be looking under User Settings -> Extensions -> Azure Repos.
Then under Tfvc: Location you can paste the location of the executable.
For 2017 it'll be
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe
Or for 2019 (Preview)
C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe
After adding the location, I closed my VS Code (not sure if this was needed) and went my git repo to copy the git URL.
After that, went back into VS Code went to the Command Palette (View -> Command Palette or CTRL+Shift+P) typed Git: Clone
pasted my repo:
Selected the location for the repo to be stored. Next was an error that popped up. I proceeded to follow this video which walked me through clicking on the Team button with the exclamation mark on the bottom of your VS Code Screen
Then chose the new method of authentication
Copy by using CTRL+C and then press enter. Your browser will launch a page where you'll enter the code you copied (CTRL+V).
Click Continue
Log in with your Microsoft Credentials and you should see a change on the bottom bar of VS Code.
Cheers!
First, you need to allocate array of pointers like char **c = malloc( N * sizeof( char* ))
, then allocate each row with a separate call to malloc
, probably in the loop:
/* N is the number of rows */
/* note: c is char** */
if (( c = malloc( N*sizeof( char* ))) == NULL )
{ /* error */ }
for ( i = 0; i < N; i++ )
{
/* x_i here is the size of given row, no need to
* multiply by sizeof( char ), it's always 1
*/
if (( c[i] = malloc( x_i )) == NULL )
{ /* error */ }
/* probably init the row here */
}
/* access matrix elements: c[i] give you a pointer
* to the row array, c[i][j] indexes an element
*/
c[i][j] = 'a';
If you know the total number of elements (e.g. N*M
) you can do this in a single allocation.
Only change the DOM once...
var listitems = '';
$.each(temp, function(key, value){
listitems += '<option value=' + key + '>' + value + '</option>';
});
$select.append(listitems);
->
is used to call a method, or access a property, on the object of a class
=>
is used to assign values to the keys of an array
E.g.:
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34, 1=>2);
And since PHP 7.4+ the operator =>
is used too for the added arrow functions, a more concise syntax for anonymous functions.
This is the complete answer (GitBash + color scheme + icon + context menu)
1) Set default profile:
"globals" :
{
"defaultProfile" : "{00000000-0000-0000-0000-000000000001}",
...
2) Add GitBash profile
"profiles" :
[
{
"guid": "{00000000-0000-0000-0000-000000000001}",
"acrylicOpacity" : 0.75,
"closeOnExit" : true,
"colorScheme" : "GitBash",
"commandline" : "\"%PROGRAMFILES%\\Git\\usr\\bin\\bash.exe\" --login -i -l",
"cursorColor" : "#FFFFFF",
"cursorShape" : "bar",
"fontFace" : "Consolas",
"fontSize" : 10,
"historySize" : 9001,
"icon" : "%PROGRAMFILES%\\Git\\mingw64\\share\\git\\git-for-windows.ico",
"name" : "GitBash",
"padding" : "0, 0, 0, 0",
"snapOnInput" : true,
"startingDirectory" : "%USERPROFILE%",
"useAcrylic" : false
},
3) Add GitBash color scheme
"schemes" :
[
{
"background" : "#000000",
"black" : "#0C0C0C",
"blue" : "#6060ff",
"brightBlack" : "#767676",
"brightBlue" : "#3B78FF",
"brightCyan" : "#61D6D6",
"brightGreen" : "#16C60C",
"brightPurple" : "#B4009E",
"brightRed" : "#E74856",
"brightWhite" : "#F2F2F2",
"brightYellow" : "#F9F1A5",
"cyan" : "#3A96DD",
"foreground" : "#bfbfbf",
"green" : "#00a400",
"name" : "GitBash",
"purple" : "#bf00bf",
"red" : "#bf0000",
"white" : "#ffffff",
"yellow" : "#bfbf00",
"grey" : "#bfbfbf"
},
4) To add a right-click context menu "Windows Terminal Here"
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Directory\Background\shell\wt]
@="Windows terminal here"
"Icon"="C:\\Users\\{YOUR_WINDOWS_USERNAME}\\AppData\\Local\\Microsoft\\WindowsApps\\{YOUR_ICONS_FOLDER}\\icon.ico"
[HKEY_CLASSES_ROOT\Directory\Background\shell\wt\command]
@="\"C:\\Users\\{YOUR_WINDOWS_USERNAME}\\AppData\\Local\\Microsoft\\WindowsApps\\wt.exe\""
The only option I have found to do this is find some exact wording and put that under the "Has the words" option. Its not the best option, but it works.
I'm using different ports then standard and copy files between files like this:
scp -P 1234 user@[ip address or host name]:/var/www/mywebsite/dumps/* /var/www/myNewPathOnCurrentLocalMachine
This is only for occasional use, if it repeats itself based on a schedule you should use rsync and cron job to do it.
Simple javascript document navigation to "#" will do it.
window.onload = function()
{
document.location.href = "#";
}
This will force the navigation bar to remove itself on load.
I use <span>
in the first column header:
<span> |
--- | ---
Value | Value
Value | Value
It creates an empty header with border, but with 1/2 the size.
Go to this link ... https://github.com/bsodmike/android-avd-profiles-2016/blob/master/Samsung%20Galaxy%20Tab%20A%2010.1%20(2016).xml
Save as xml file in your computer. Go on Android Studio => Tools => AVD Manager => + Create Virtual Device => Import Hardware Profiles ... choose the saved file and the device will be available on the tablet's section.
Happy Android developments guys!!!
Referring to Gamaliel 's answer: $args is an array of the arguments that are passed into a script at runtime - as such cannot be used the way Gamaliel is using it. This is actually working:
$myPath = 'C:\whatever.file'
# get actual Acl entry
$myAcl = Get-Acl "$myPath"
$myAclEntry = "Domain\User","FullControl","Allow"
$myAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($myAclEntry)
# prepare new Acl
$myAcl.SetAccessRule($myAccessRule)
$myAcl | Set-Acl "$MyPath"
# check if added entry present
Get-Acl "$myPath" | fl
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
With this you can remove the column
and store variable
into another variable
.
df = subset(data, select = -c(genome) )
UDP is slightly quicker in my experience, but not by much. The choice shouldn't be made on performance but on the message content and compression techniques.
If it's a protocol with message exchange, I'd suggest that the very slight performance hit you take with TCP is more than worth it. You're given a connection between two end points that will give you everything you need. Don't try and manufacture your own reliable two-way protocol on top of UDP unless you're really, really confident in what you're undertaking.
you may check this http://coenraets.org/blog/2011/10/sample-application-with-jquery-mobile-and-phonegap/ and you can also check http://mobile.tutsplus.com/category/tutorials/phonegap/ which provide you with a good sample
The JavaScript Object()
constructor makes an Object that you can assign members to.
myObj = new Object()
myObj.key = value;
myObj[key2] = value2; // Alternative
>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:
sub(pattern, repl, string, count=0)
Return the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in string by the
replacement repl. repl can be either a string or a callable;
if a callable, it's passed the match object and must return
a replacement string to be used.
After trying and searching different solutions, I think the most safest way is adding the following code at the end of the Podfile
post_install do |pi|
pi.pods_project.targets.each do |t|
t.build_configurations.each do |bc|
bc.build_settings['ARCHS[sdk=iphonesimulator*]'] = `uname -m`
end
end
end
This way you only override the iOS simulator's compiler architecture as your current cpu's architecture. Compared to others, this solution will also work on computers with Apple Silicon.
No, you can't break from a closure in Groovy without throwing an exception. Also, you shouldn't use exceptions for control flow.
If you find yourself wanting to break out of a closure you should probably first think about why you want to do this and not how to do it. The first thing to consider could be the substitution of the closure in question with one of Groovy's (conceptual) higher order functions. The following example:
for ( i in 1..10) { if (i < 5) println i; else return}
becomes
(1..10).each{if (it < 5) println it}
becomes
(1..10).findAll{it < 5}.each{println it}
which also helps clarity. It states the intent of your code much better.
The potential drawback in the shown examples is that iteration only stops early in the first example. If you have performance considerations you might want to stop it right then and there.
However, for most use cases that involve iterations you can usually resort to one of Groovy's find, grep, collect, inject, etc. methods. They usually take some "configuration" and then "know" how to do the iteration for you, so that you can actually avoid imperative looping wherever possible.
Return a FileContentResult
. The last line in your controller action would be something like:
return File("Chap0101.pdf", "application/pdf");
If you are generating this PDF dynamically, it may be better to use a MemoryStream
, and create the document in memory instead of saving to file. The code would be something like:
Document document = new Document();
MemoryStream stream = new MemoryStream();
try
{
PdfWriter pdfWriter = PdfWriter.GetInstance(document, stream);
pdfWriter.CloseStream = false;
document.Open();
document.Add(new Paragraph("Hello World"));
}
catch (DocumentException de)
{
Console.Error.WriteLine(de.Message);
}
catch (IOException ioe)
{
Console.Error.WriteLine(ioe.Message);
}
document.Close();
stream.Flush(); //Always catches me out
stream.Position = 0; //Not sure if this is required
return File(stream, "application/pdf", "DownloadName.pdf");
The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.
If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)
You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.
In mathematics the result of the modulo operation is the remainder of the Euclidean division. However, other conventions are possible. Computers and calculators have various ways of storing and representing numbers; thus their definition of the modulo operation depends on the programming language and/or the underlying hardware.
7 modulo 3 --> 1
7 modulo -3 --> -2
-7 modulo 3 --> 2
-7 modulo -3 --> -1
Just type ctrl+shift+I in google chrome & you will land in an isolated developer window.
You can use:
print (1==2 and "only if condition true" or "in case condition is false")
Just as well you can keep going like:
print 1==2 and "aa" or ((2==3) and "bb" or "cc")
Real world example:
>>> print "%d item%s found." % (count, (count>1 and 's' or ''))
1 item found.
>>> count = 2
>>> print "%d item%s found." % (count, (count>1 and 's' or ''))
2 items found.
The hamcrest-core-1.3.jar available on maven repository is deprecated.
Download working hamcrest-core-1.3.jar
from official Junit4 github link .
If you want to download from maven repository, use latest hamcrest-XX.jar
.
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
If it is a valid answer
boolean IsNegative(char[] v) throws NullPointerException, ArrayIndexOutOfBoundException
{
return v[0]=='-';
}
You are missing the ?
in the second URL (Also, it should be URL-encoded to be %3F
).
Also, I believe that the remaining &
need to be URL, not HTML-encoded. Change &second=12&third=5
to %26second=12%26third=5
and everything should just work.
This:
&u=http://www.foobar.com/first=12&sec=25&position=2
should be:
&u=http://www.foobar.com/%3Ffirst=12%26sec=25%26position=2
If you want the fastest way for numpy arrays, use numba, which if you use conda should be already installed
The code will be fast because it will be compiled by numba
import numba
@numba.jit
def issorted(vec, ascending=True):
if len(vec) < 2:
return True
if ascending:
for i in range(1, len(vec)):
if vec[i-1] > vec[i]:
return False
return True
else:
for i in range(1, len(vec)):
if vec[i-1] < vec[i]:
return False
return True
and then:
>>> issorted(array([4,9,100]))
>>> True
The usual approach is to download the source and build and install locally (but not directly in virtualenv), and then create a new virtualenv using that local Python install. On some systems, it may be possible to download and install a prebuilt python, rather than building from source.
Based on Ben's answer you you could do the following when running apache on Linux (Debian in my case).
First create the file rewrite-log.load
/etc/apache2/mods-availabe/rewrite-log.load
RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3
Then enter
$ a2enmod rewrite-log
followed by
$ service apache2 restart
And when you finished with debuging your rewrite rules
$ a2dismod rewrite-log && service apache2 restart
Go to properties of your project ( with Alt+Enter or righ-click )
check on Apache Tomcat v7.0 under Targeted Runtime and it works.
My case was that i was using RDS (mysql db verion 8) of AWS and was connecting my application through EC2 (my php code 5.6 was in EC2).
Here in this case since it is RDS there is no my.cnf the parameters are maintained by PARAMETER Group of AWS. Refer: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html
so what i did was:
Created a new Parameter group and then edited them.
Searched all character-set parameters. These are blank by default. edit them individually and select utf8 from drop down list.
character_set_client, character_set_connection, character_set_database, character_set_server
And then most important, Rebooted RDS instance.
This has solved my problem and connection from php5.6 to mysql 8.x was working great.
hope this helps.
Please view this image for better understanding. enter image description here
I advise you to go with Scanner
instead of DataInputStream
. Scanner
is specifically designed for this purpose and introduced in Java 5. See the following links to know how to use Scanner
.
Example
Scanner s = new Scanner(System.in);
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
if you are running nvm you might want to run nvm use <desired-node-version>
This keeps node consistent with npm
Try writing all the errors to a file.
error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
Something like that.
shift column gdp up:
df.gdp = df.gdp.shift(-1)
and then remove the last row
Use strstr(const char *s , const char *t)
and include<string.h>
You can write your own function which behaves same as strstr
and you can modify according to your requirement also
char * str_str(const char *s, const char *t)
{
int i, j, k;
for (i = 0; s[i] != '\0'; i++)
{
for (j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++);
if (k > 0 && t[k] == '\0')
return (&s[i]);
}
return NULL;
}
If you want to list only methods of a python class
import numpy as np
print(np.random.__all__)
You might try searching the internet for ".htaccess Options not allowed here".
A suggestion I found (using google) is:
Check to make sure that your httpd.conf file has AllowOverride All.
A .htaccess file that works for me on Mint Linux (placed in the Laravel /public folder):
# Apache configuration file
# http://httpd.apache.org/docs/2.2/mod/quickreference.html
# Turning on the rewrite engine is necessary for the following rules and
# features. "+FollowSymLinks" must be enabled for this to work symbolically.
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
</IfModule>
# For all files not found in the file system, reroute the request to the
# "index.php" front controller, keeping the query string intact
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
Hope this helps you. Otherwise you could ask a question on the Laravel forum (http://forums.laravel.com/), there are some really helpful people hanging around there.
I had also similar problem. In my case brokerUrl was not configured properly. So that's way I received following Error:
Cause: Error While attempting to add new Connection to the pool: nested exception is javax.jms.JMSException: Could not connect to broker URL : tcp://localhost:61616. Reason: java.net.ConnectException: Connection refused
& I resolved it following way.
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
connectionFactory.setBrokerURL("tcp://hostname:61616");
connectionFactory.setUserName("admin");
connectionFactory.setPassword("admin");
Here's a function to see what the effective SQL will be, adpated from a comment by "Mark" at php.net:
function sql_debug($sql_string, array $params = null) {
if (!empty($params)) {
$indexed = $params == array_values($params);
foreach($params as $k=>$v) {
if (is_object($v)) {
if ($v instanceof \DateTime) $v = $v->format('Y-m-d H:i:s');
else continue;
}
elseif (is_string($v)) $v="'$v'";
elseif ($v === null) $v='NULL';
elseif (is_array($v)) $v = implode(',', $v);
if ($indexed) {
$sql_string = preg_replace('/\?/', $v, $sql_string, 1);
}
else {
if ($k[0] != ':') $k = ':'.$k; //add leading colon if it was left out
$sql_string = str_replace($k,$v,$sql_string);
}
}
}
return $sql_string;
}
How about this, a quick solution.
import requests
url = "http://craphound.com/images/1006884_2adf8fc7.jpg"
response = requests.get(url)
if response.status_code == 200:
with open("/Users/apple/Desktop/sample.jpg", 'wb') as f:
f.write(response.content)
You made the error, for the second call, to set the size of source to the size of the target.
Anyway i bet that you want the same aspect ratio for the scaled image, so you need to compute it :
var hRatio = canvas.width / img.width ;
var vRatio = canvas.height / img.height ;
var ratio = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);
i also suppose you want to center the image, so the code would be :
function drawImageScaled(img, ctx) {
var canvas = ctx.canvas ;
var hRatio = canvas.width / img.width ;
var vRatio = canvas.height / img.height ;
var ratio = Math.min ( hRatio, vRatio );
var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
var centerShift_y = ( canvas.height - img.height*ratio ) / 2;
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.drawImage(img, 0,0, img.width, img.height,
centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);
}
you can see it in a jsbin here : http://jsbin.com/funewofu/1/edit?js,output
If you want to bypass that restriction when fetching the contents with fetch API or XMLHttpRequest in javascript, you can use a proxy server so that it sets the header Access-Control-Allow-Origin
to *
.
const express = require('express');
const request = require('request');
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.get('/fetch', (req, res) => {
request(
{ url: req.query.url },
(error, response, body) => {
if (error || response.statusCode !== 200) {
return res.status(500).send('error');
}
res.send(body);
}
)
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));
Above is a sample code( node Js required ) which can act as a proxy server. For eg: If I want to fetch https://www.google.com
normally a CORS error is thrown, but now since the request is sent through the proxy server hosted locally at port 3000, the proxy server adds the Access-Control-Allow-Origin
header in the response and there wont be any issue.
Send a GET request to http://localhost:3000/fetch?url=Your URL here
, instead of directly sending the request to the URl you want to fetch.
Your URL here
stands for the URL you wish to fetch eg: https://www.google.com
I have been able to work around this bug by setting a unique name
attribute on the iframe - for whatever reason, this seems to bust the cache. You can use whatever dynamic data you have as the name
attribute - or simply the current ms or ns time in whatever templating language you're using. This is a nicer solution than those above because it does not directly require JS.
In my particular case, the iframe is being built via JS (but you could do the same via PHP, Ruby, whatever), so I simply use Date.now()
:
return '<iframe src="' + src + '" name="' + Date.now() + '" />';
This fixes the bug in my testing; probably because the window.name
in the inner window changes.
I think the best way to do this is to use event.preventDefault()
because if some exception is raised in the handler, then the return false
statement will be skipped and the behavior will be opposite to what you want.
But if you are sure that the code won't trigger any exceptions, then you can go with any of the method you wish.
If you still want to go with the return false
, then you can put your entire handler code in a try catch block like below:
$('a').click(function (e) {
try{
your code here.........
}
catch(e){}
return false;
});
This works when I try it. I double-checked with two sample programs:
using System;
using System.Diagnostics;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
Process.Start("ConsoleApplication2.exe");
}
}
}
using System;
using System.IO;
namespace ConsoleApplication2 {
class Program {
static void Main(string[] args) {
try {
File.WriteAllText(@"c:\program files\test.txt", "hello world");
}
catch (Exception ex) {
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
}
}
}
First verified that I get the UAC bomb:
System.UnauthorizedAccessException: Access to the path 'c:\program files\test.txt' is denied.
// etc..
Then added a manifest to ConsoleApplication1 with the phrase:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
No bomb. And a file I can't easily delete :) This is consistent with several previous tests on various machines running Vista and Win7. The started program inherits the security token from the starter program. If the starter has acquired admin privileges, the started program has them as well.
There is an official documentation page about this as well.
Examples from that page include:
mongo server:27017/dbname --quiet my_commands.js
mongo test --eval "printjson(db.getCollectionNames())"
According to the release-notes, Java 11 removed the Java EE modules:
java.xml.bind (JAXB) - REMOVED
See JEP 320 for more info.
You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.3</version>
<scope>runtime</scope>
</dependency>
Use latest release of Eclipse Implementation of JAXB 3.0.0:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>3.0.0</version>
<scope>runtime</scope>
</dependency>
Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*
, so update import statements:
javax.xml.bind -> jakarta.xml.bind
If you are not limited to just a camera which wasn't in one of your constraints perhaps you can move to using a range sensor like the Xbox Kinect. With this you can perform depth and colour based matched segmentation of the image. This allows for faster separation of objects in the image. You can then use ICP matching or similar techniques to even match the shape of the can rather then just its outline or colour and given that it is cylindrical this may be a valid option for any orientation if you have a previous 3D scan of the target. These techniques are often quite quick especially when used for such a specific purpose which should solve your speed problem.
Also I could suggest, not necessarily for accuracy or speed but for fun you could use a trained neural network on your hue segmented image to identify the shape of the can. These are very fast and can often be up to 80/90% accurate. Training would be a little bit of a long process though as you would have to manually identify the can in each image.
Sadly, this is not possible by default to use section
as another user suggested, since a section
is only available to the immediate child
of a View
.
What works however is implementing and redefining the section
in every view, meaning:
section Head
{
@RenderSection("Head", false)
}
This way every view can implement a head section, not just the immediate children. This only works partly though, especially with multiple partials the troubles begin (as you have mentioned in your question).
So the only real solution to your problem is using the ViewBag
. The best would probably be a seperate collection (list) for CSS and scripts. For this to work, you need to ensure that the List
used is initialized before any of the views are executed. Then you can can do things like this in the top of every view/partial (without caring if the Scripts
or Styles
value is null:
ViewBag.Scripts.Add("myscript.js");
ViewBag.Styles.Add("mystyle.css");
In the layout you can then loop through the collections and add the styles based on the values in the List
.
@foreach (var script in ViewBag.Scripts)
{
<script type="text/javascript" src="@script"></script>
}
@foreach (var style in ViewBag.Styles)
{
<link href="@style" rel="stylesheet" type="text/css" />
}
I think it's ugly, but it's the only thing that works.
******UPDATE****
Since it starts executing the inner views first and working its way out to the layout and CSS styles are cascading, it would probably make sense to reverse the style list via ViewBag.Styles.Reverse()
.
This way the most outer style is added first, which is inline with how CSS style sheets work anyway.
If the value type is already double, then update the value with $set command can not change the value type double to int when using NumberInt() or NumberLong() function. So, to Change the value type, it must update the whole record.
var re = db.data.find({"name": "zero"})
re['value']=NumberInt(0)
db.data.update({"name": "zero"}, re)
You could use one of the below solutions:
$items = Item::whereIn('id', [1,2,..])->get();
or:
$items = DB::table('items')->whereIn('id',[1,2,..])->get();
While there is no functional difference between os.environ.get
and os.getenv
, there is a massive difference between os.putenv
and setting entries on os.environ
. os.putenv
is broken, so you should default to os.environ.get
simply to avoid the way os.getenv
encourages you to use os.putenv
for symmetry.
os.putenv
changes the actual OS-level environment variables, but in a way that doesn't show up through os.getenv
, os.environ
, or any other stdlib way of inspecting environment variables:
>>> import os
>>> os.environ['asdf'] = 'fdsa'
>>> os.environ['asdf']
'fdsa'
>>> os.putenv('aaaa', 'bbbb')
>>> os.getenv('aaaa')
>>> os.environ.get('aaaa')
You'd probably have to make a ctypes call to the C-level getenv
to see the real environment variables after calling os.putenv
. (Launching a shell subprocess and asking it for its environment variables might work too, if you're very careful about escaping and --norc
/--noprofile
/anything else you need to do to avoid startup configuration, but it seems a lot harder to get right.)
REST vs. SOAP
SOAP:
? SOAP is simple object access protocol that run on TCP/UDP/SMTP.
? SOAP read and write request response messages in XML format.
? SOAP uses interface in order to define the services.
? SOAP is more secure as it has its own security and well defined standards.
? SOAP follows RPC and Document style to define web services.
? SOAP uses SOAP-UI as client tools for testing.
REST
? REST is representational state transfer that uses underlying HTTP protocols.
? REST is stateless.
? REST is an architectural style that is used to describe and define web services.
? REST can read and write request response messages in JSON/XML/Plain HTML.
? REST uses URI for each resource that is used in web service.A resource can be image text method etc.
? REST uses set of verbs, like HTTP's GET, POST, PUT, DELETE.
? REST is easy to develop and easy to manage as compared to SOAP UI.
? REST has light-weight client tools or plugins that can easily be integrated inside a browser.
? REST services are cacheable.
For me it work fine
&:not(:last-child){
text-transform: uppercase;
}
The Newline in T-SQL is represented by CHAR(13) & CHAR(10) (Carriage return + Line Feed). Accordingly, you can create a REPLACE statement with the text you want to replace the newline with.
REPLACE(MyField, CHAR(13) + CHAR(10), 'something else')
2019 modern browsers update
This is the approach I'd now recommend with a few caveats:
fetch('https://jsonplaceholder.typicode.com/todos/1')_x000D_
.then(resp => resp.blob())_x000D_
.then(blob => {_x000D_
const url = window.URL.createObjectURL(blob);_x000D_
const a = document.createElement('a');_x000D_
a.style.display = 'none';_x000D_
a.href = url;_x000D_
// the filename you want_x000D_
a.download = 'todo-1.json';_x000D_
document.body.appendChild(a);_x000D_
a.click();_x000D_
window.URL.revokeObjectURL(url);_x000D_
alert('your file has downloaded!'); // or you know, something with better UX..._x000D_
})_x000D_
.catch(() => alert('oh no!'));
_x000D_
2012 original jQuery/iframe/cookie based approach
I have created the jQuery File Download plugin (Demo) (GitHub) which could also help with your situation. It works pretty similarly with an iframe but has some cool features that I have found quite handy:
Very easy to setup with nice visuals (jQuery UI Dialog, but not required), everything is tested too
User never leaves the same page they initiated a file download from. This feature is becoming crucial for modern web applications
successCallback and failCallback functions allow for you to be explicit about what the user sees in either situation
In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demo for an example of this. Hope this helps someone!
Here is a simple use case demo using the plugin source with promises. The demo page includes many other, 'better UX' examples as well.
$.fileDownload('some/file.pdf')
.done(function () { alert('File download a success!'); })
.fail(function () { alert('File download failed!'); });
var item = (from something in someList
select x).firstordefault();
Would get the item
, and then you could do item.prop1=5;
to change the specific property.
Or are you wanting to get a list of items from the db and have it change the property prop1
on each item in that returned list to a specified value?
If so you could do this (I'm doing it in VB because I know it better):
dim list = from something in someList select x
for each item in list
item.prop1=5
next
(list
will contain all the items returned with your changes)
Change column type to LONGTEXT
As already mentioned, you can get a performance increase from having your python code compiled into bytecode. This is usually handled by python itself, for imported scripts only.
Another reason you might want to compile your python code, could be to protect your intellectual property from being copied and/or modified.
You can read more about this in the Python documentation.
Check
man paste
possible followed by some command like untabify
or tabs2spaces
This function do the truncate space and words parts also.(ex: Mother into Moth...)
String.prototype.truc= function (length) {
return this.length>length ? this.substring(0, length) + '…' : this;
};
usage:
"this is long length text".trunc(10);
"1234567890".trunc(5);
output:
this is lo...
12345...
For the lazy and the learning, to put it into your theme, Rfvgyhn's full code
<?php $category = get_the_category();
$firstCategory = $category[0]->cat_name; echo $firstCategory;?>
The proposed solutions are perfect to download the images and if it is enough for you to save all the files in the directory you are using. But if you want to save all the images in a specified directory without reproducing the entire hierarchical tree of the site, try to add "cut-dirs" to the line proposed by Jon.
wget -r -P /save/location -A jpeg,jpg,bmp,gif,png http://www.boia.de --cut-dirs=1 --cut-dirs=2 --cut-dirs=3
in this case cut-dirs will prevent wget from creating sub-directories until the 3th level of depth in the website hierarchical tree, saving all the files in the directory you specified.You can add more 'cut-dirs' with higher numbers if you are dealing with sites with a deep structure.
You can use ng-show on every div element in the loop. Is this what you've wanted: http://jsfiddle.net/pGwRu/2/ ?
<div class="from" ng-show="message.from">From: {{message.from.name}}</div>
Just in case, you might have had unbalanced brackets, you can likely design some expression with recursion similar to,
\[(([^\]\[]+)|(?R))*+\]
which of course, it would relate to the language or RegEx engine that you might be using.
Other than that,
\[([^\]\[\r\n]*)\]
or,
(?<=\[)[^\]\[\r\n]*(?=\])
are good options to explore.
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
jex.im visualizes regular expressions:
const regex = /\[([^\]\[\r\n]*)\]/gm;_x000D_
const str = `This is a [sample] string with [some] special words. [another one]_x000D_
This is a [sample string with [some special words. [another one_x000D_
This is a [sample[sample]] string with [[some][some]] special words. [[another one]]`;_x000D_
let m;_x000D_
_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
// This is necessary to avoid infinite loops with zero-width matches_x000D_
if (m.index === regex.lastIndex) {_x000D_
regex.lastIndex++;_x000D_
}_x000D_
_x000D_
// The result can be accessed through the `m`-variable._x000D_
m.forEach((match, groupIndex) => {_x000D_
console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_
});_x000D_
}
_x000D_
If it is not necessary turn off 'Enable 32-bit Applications' from your respective application pool of your website.
This worked for me on my local machine
add a div to the cells that you would like to add some extra spacing:
<tr class="highlight">
<td><div>Value1</div></td>
<td><div>Value2</div></td>
</tr>
tr.highlight td div {
margin-top: 10px;
}
Try using the overflow
CSS property. There are also separate properties to define the behaviour of just horizontal overflow (overflow-x
) and vertical overflow (overflow-y
).
Since you only want the vertical scroll, try this:
table {
height: 500px;
overflow-y: scroll;
}
EDIT:
Apparently <table>
elements don't respect the overflow
property. This appears to be because <table>
elements are not rendered as display: block
by default (they actually have their own display type). You can force the overflow
property to work by setting the <table>
element to be a block type:
table {
display: block;
height: 500px;
overflow-y: scroll;
}
Note that this will cause the element to have 100% width, so if you don't want it to take up the entire horizontal width of the page, you need to specify an explicit width for the element as well.
window.open('https://support.wwf.org.uk', '_blank');
The second parameter is what makes it open in a new window. Don't forget to read Jakob Nielsen's informative article :)
To actually do it in HTML with inline CSS (not with an external CSS style sheet)
<input type="text" style="font-size: 44pt">
A lot of people would consider putting the style right into the html like this to be poor form. However, I frequently make extreeemly simple web pages for my own use that don't even have a <html>
or <body>
tag, and such is appropriate there.
<div>
with some proportions
div {
position: relative;
width: 100%;
height: 100%;
}
<img>
's with their own proportions
img {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: auto; /* to keep proportions */
height: auto; /* to keep proportions */
max-width: 100%; /* not to stand out from div */
max-height: 100%; /* not to stand out from div */
margin: auto auto 0; /* position to bottom and center */
}
I was having a hell of a time with this as well. I didn't realize that beyond the extra permission you need to append "tel:" onto the string that has the number in it. This is what mine looks like after getting it functional. Hope this helps.
@Override_x000D_
public void onClick(View v) {_x000D_
Intent intent = new Intent(Intent.ACTION_DIAL);_x000D_
String temp = "tel:" + phone;_x000D_
intent.setData(Uri.parse(temp));_x000D_
_x000D_
startActivity(intent);_x000D_
}
_x000D_
The C++ standard requires a definition for your static const member if the definition is somehow needed.
The definition is required, for example if it's address is used. push_back
takes its parameter by const reference, and so strictly the compiler needs the address of your member and you need to define it in the namespace.
When you explicitly cast the constant, you're creating a temporary and it's this temporary which is bound to the reference (under special rules in the standard).
This is a really interesting case, and I actually think it's worth raising an issue so that the std be changed to have the same behaviour for your constant member!
Although, in a weird kind of way this could be seen as a legitimate use of the unary '+' operator. Basically the result of the unary +
is an rvalue and so the rules for binding of rvalues to const references apply and we don't use the address of our static const member:
v.push_back( +Foo::MEMBER );
You could use multiple approaches and see if they converge to the same answer. Or grab some from the 'net. The Chudnovsky algorithm is usually used as a very fast method of calculating pi. http://www.craig-wood.com/nick/articles/pi-chudnovsky/
I found your question looking for a solution to the same problem; and what other answers fail to point is a way to use a variable to change the name of the table for every execution of your procedure in a permanent form, not temporary.
So far what I do is concatenate the entire SQL code with the variables to use. Like this:
declare @table_name as varchar(30)
select @table_name = CONVERT(varchar(30), getdate(), 112)
set @table_name = 'DAILY_SNAPSHOT_' + @table_name
EXEC('
SELECT var1, var2, var3
INTO '+@table_name+'
FROM my_view
WHERE string = ''Strings must use double apostrophe''
');
I hope it helps, but it could be cumbersome if the code is too large, so if you've found a better way, please share!
Maybe someone will find this solution useful:
void print_binary(int number, int num_digits) {
int digit;
for(digit = num_digits - 1; digit >= 0; digit--) {
printf("%c", number & (1 << digit) ? '1' : '0');
}
}
This error also occurs if you try to add ngModel to the non-input elements like <option>
HTML tags. Make sure you add ngModel only to the <input>
tags.
In my case, I have added a ngModel to the <ion-select-option>
instead of <ion-select>
.
you can try this.
data_you_need=pd.DataFrame()
for infile in glob.glob("*.xlsx"):
data = pandas.read_excel(infile)
data_you_need=data_you_need.append(data,ignore_index=True)
I hope it can help.
In addition to xzyfer's answer
The function
function custom_unset(&$array=array(), $key=0) {
if(isset($array[$key])){
// remove item at index
unset($array[$key]);
// 'reindex' array
$array = array_values($array);
//alternatively
//$array = array_merge($array);
}
return $array;
}
Use
$my_array=array(
0=>'test0',
1=>'test1',
2=>'test2'
);
custom_unset($my_array, 1);
Result
array(2) {
[0]=>
string(5) "test0"
[1]=>
string(5) "test2"
}
You probably want something like this:
Collections.sort(students, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
if(s1.getName() != null && s2.getName() != null && s1.getName().comareTo(s1.getName()) != 0) {
return s1.getName().compareTo(s2.getName());
} else {
return s1.getAge().compareTo(s2.getAge());
}
}
);
This sorts the students first by name. If a name is missing, or two students have the same name, they are sorted by their age.
Try :
SET @num := 0;
UPDATE your_table SET id = @num := (@num+1);
ALTER TABLE
tableName
AUTO_INCREMENT = 1;
That'll reset the autoincremented value, and then count every row while a new value is created for it.
example : before
so the table will display the array : 1,2,4,5
Example : AFTER (if you use this command you will obtain)
No trace of the deleted value, and the rest of the incremented continues with this new count.
BUT
I had the same problem
Here is the Solution that might work for you. It worked for me
GridView1.DataBind();
if (GridView1.Columns.Count > 0)
GridView1.Columns[0].Visible = false;
else
{
GridView1.HeaderRow.Cells[0].Visible = false;
foreach (GridViewRow gvr in GridView1.Rows)
{
gvr.Cells[0].Visible = false;
}
}
Be forwarned... I am using jQuery Mobile 1.0b2 with PhoneGap 1.0.0 on an Android 2.2 (Cyanogen 7.0.1) phone (T-Mobile G2) and could not get the .append() method to work at all. I had to use .html() like follows:
var options;
$.each(data, function(index, object) {
options += '<option value="' + object.id + '">' + object.stop + '</option>';
});
$('#selectMenu').html(options);
If you are getting an error like the one below:
OperationalError: FATAL: no pg_hba.conf entry for host "your ipv6",
user "username", database "postgres", SSL off
then add an entry like the following, with your mac address.
host all all [your ipv6]/128 md5
My ls sorts by name by default. What are you seeing?
man ls
states:
List information about the FILEs (the current directory by default). Sort entries alpha-betically if none of -cftuvSUX nor --sort is specified.
:
It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress
and the relative URI passed to the GetAsync
method -- or whichever other method of HttpClient
-- only one permutation works. You must place a slash at the end of the BaseAddress
, and you must not place a slash at the beginning of your relative URI, as in the following example.
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://something.com/api/");
var response = await client.GetAsync("resource/7");
}
Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient
.
var $whatever = $('#whatever');
var ending_right = ($(window).width() - ($whatever.offset().left + $whatever.outerWidth()));
Reference: .outerWidth()
What you've written actually almost works (it would work if all the variables were numbers), but it's not an idiomatic way at all.
(…)
parentheses indicate a subshell. What's inside them isn't an expression like in many other languages. It's a list of commands (just like outside parentheses). These commands are executed in a separate subprocess, so any redirection, assignment, etc. performed inside the parentheses has no effect outside the parentheses.
$(…)
is a command substitution: there is a command inside the parentheses, and the output from the command is used as part of the command line (after extra expansions unless the substitution is between double quotes, but that's another story).{ … }
braces are like parentheses in that they group commands, but they only influence parsing, not grouping. The program x=2; { x=4; }; echo $x
prints 4, whereas x=2; (x=4); echo $x
prints 2. (Also braces require spaces around them and a semicolon before closing, whereas parentheses don't. That's just a syntax quirk.)
${VAR}
is a parameter expansion, expanding to the value of a variable, with possible extra transformations.((…))
double parentheses surround an arithmetic instruction, that is, a computation on integers, with a syntax resembling other programming languages. This syntax is mostly used for assignments and in conditionals.
$((…))
, which expand to the integer value of the expression.[[ … ]]
double brackets surround conditional expressions. Conditional expressions are mostly built on operators such as -n $variable
to test if a variable is empty and -e $file
to test if a file exists. There are also string equality operators: "$string1" == "$string2"
(beware that the right-hand side is a pattern, e.g. [[ $foo == a* ]]
tests if $foo
starts with a
while [[ $foo == "a*" ]]
tests if $foo
is exactly a*
), and the familiar !
, &&
and ||
operators for negation, conjunction and disjunction as well as parentheses for grouping. Note that you need a space around each operator (e.g. [[ "$x" == "$y" ]]
, not [[ "$x"=="$y" ]]
;
both inside and outside the brackets (e.g. [[ -n $foo ]]
, not [[-n $foo]]
[ … ]
single brackets are an alternate form of conditional expressions with more quirks (but older and more portable). Don't write any for now; start worrying about them when you find scripts that contain them.This is the idiomatic way to write your test in bash:
if [[ $varA == 1 && ($varB == "t1" || $varC == "t2") ]]; then
If you need portability to other shells, this would be the way (note the additional quoting and the separate sets of brackets around each individual test, and the use of the traditional =
operator rather than the ksh/bash/zsh ==
variant):
if [ "$varA" = 1 ] && { [ "$varB" = "t1" ] || [ "$varC" = "t2" ]; }; then
The code formatting is available in Visual Studio Code through the following shortcuts:
Alternatively, you can find the shortcut, as well as other shortcuts, through the 'Command Palette' provided in the editor with Ctrl +Shift+ P (or Command + Shift + P on Mac), and then searching for format document.
Open command palette (Win: F1 or Ctrt+Shift+P)
Find 'Change Language Model'
Select language e.g. json
. By now syntax should be highlighted.
Format document (e.g. Open Command Palette -> 'Format Document')
By entering $PATH
on its own at the command prompt, you're trying to run it. This isn't like Windows where you can get your path output by simply typing path
.
If you want to see what the path is, simply echo it:
echo $PATH
I used the display:inline-block property: the solution consist in use a wrapper with fixed width. Inside, the ul block with the inline-block for display. Using this, the ul just take the width for the real content! and finally margin: 0 auto, to center this inline-block =)
/*ul wrapper*/
.gallery_wrapper{
width: 958px;
margin: 0 auto;
}
/*ul list*/
ul.gallery_carrousel{
display: inline-block;
margin: 0 auto;
}
.contenido_secundario li{
float: left;
}
I've managed to find a CSS workaround to preventing bouncing of the viewport. The key was to wrap the content in 3 divs with -webkit-touch-overflow:scroll applied to them. The final div should have a min-height of 101%. In addition, you should explicitly set fixed widths/heights on the body tag representing the size of your device. I've added a red background on the body to demonstrate that it is the content that is now bouncing and not the mobile safari viewport.
Source code below and here is a plunker (this has been tested on iOS7 GM too). http://embed.plnkr.co/NCOFoY/preview
If you intend to run this as a full-screen app on iPhone 5, modify the height to 1136px (when apple-mobile-web-app-status-bar-style is set to 'black-translucent' or 1096px when set to 'black'). 920x is the height of the viewport once the chrome of mobile safari has been taken into account).
<!doctype html>
<html>
<head>
<meta name="viewport" content="initial-scale=0.5,maximum-scale=0.5,minimum-scale=0.5,user-scalable=no" />
<style>
body { width: 640px; height: 920px; overflow: hidden; margin: 0; padding: 0; background: red; }
.no-bounce { width: 100%; height: 100%; overflow-y: scroll; -webkit-overflow-scrolling: touch; }
.no-bounce > div { width: 100%; height: 100%; overflow-y: scroll; -webkit-overflow-scrolling: touch; }
.no-bounce > div > div { width: 100%; min-height: 101%; font-size: 30px; }
p { display: block; height: 50px; }
</style>
</head>
<body>
<div class="no-bounce">
<div>
<div>
<h1>Some title</h1>
<p>item 1</p>
<p>item 2</p>
<p>item 3</p>
<p>item 4</p>
<p>item 5</p>
<p>item 6</p>
<p>item 7</p>
<p>item 8</p>
<p>item 9</p>
<p>item 10</p>
<p>item 11</p>
<p>item 12</p>
<p>item 13</p>
<p>item 14</p>
<p>item 15</p>
<p>item 16</p>
<p>item 17</p>
<p>item 18</p>
<p>item 19</p>
<p>item 20</p>
</div>
</div>
</div>
</body>
</html>
"." | "!" | "~" | "*" | "'" | "(" | ")"
are also acceptable [RFC2396]. Really, anything can be in a GET parameter if it is properly encoded.
Right-click on the table in SSMS, 'Design' it, and click on the id column. In the properties, set the identity to be seeded @ e.g. 1 and to have increment of 1 - save and you're done.
I had the same problem but got it working by changing enable-oslogin from TRUE to FALSE in google cloud.
Missing ;
after var_dump($row)
The more general answer to this question involves shadowed variables and how they are accessed.
In the following example (from Oracle), the variable x in main() is shadowing Test.x:
class Test {
static int x = 1;
public static void main(String[] args) {
InnerClass innerClassInstance = new InnerClass()
{
public void printX()
{
System.out.print("x=" + x);
System.out.println(", Test.this.x=" + Test.this.x);
}
}
innerClassInstance.printX();
}
public abstract static class InnerClass
{
int x = 0;
public InnerClass() { }
public abstract void printX();
}
}
Running this program will print:
x=0, Test.this.x=1
More at: http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6
on windows invoke "cmd /k start http://www.example.com" Infact you can always invoke "default" programs using the start command. For ex start abc.mp3 will invoke the default mp3 player and load the requested mp3 file.
This answer is similar to Alexander Ukhov's answer, except that it uses touch events rather than click events. Those event allow the parent to display the proper pressed states (e.g., ripple effect). This answer is also in Kotlin instead of Java.
view.setOnTouchListener { view, motionEvent ->
(view.parent as View).onTouchEvent(motionEvent)
}
Have a look at the class
org.joda.time.DateTime
This allows you to do things like:
old = new DateTime();
new = old.plusSeconds(500000);
System.out.println("Hours: " + (new.Hours() - old.Hours()));
However, your solution probably can be simpler:
You need to work out how many seconds in a day, divide your input by the result to get the days, and subtract it from the input to keep the remainder. You then need to work out how many hours in the remainder, followed by the minutes, and the final remainder is the seconds.
This is the analysis done for you, now you can focus on the code.
You need to ask what s/he means by "no hard coding", generally it means pass parameters, rather than fixing the input values. There are many ways to do this, depending on how you run your code. Properties are a common way in java.
From what I understand of your request, this should work:
<script>
// var status = document.getElementsByID("uniqueID"); // this works too
var status = document.getElementsByName("status")[0];
var jsonArr = [];
for (var i = 0; i < status.options.length; i++) {
jsonArr.push({
id: status.options[i].text,
optionValue: status.options[i].value
});
}
</script>
You can set left margins for li
tags in percents and set the same negative left margin on parent:
ul {margin-left:-5%;}_x000D_
li {width:20%;margin-left:5%;float:left;}
_x000D_
<ul>_x000D_
<li>A_x000D_
<li>B_x000D_
<li>C_x000D_
<li>D_x000D_
</ul>
_x000D_
The value of the match
attribute of the <xsl:template>
instruction must be a match pattern.
Match patterns form a subset of the set of all possible XPath expressions. The first, natural, limitation is that a match pattern must select a set of nodes. There are also other limitations. In particular, reverse axes are not allowed in the location steps (but can be specified within the predicates). Also, no variable or parameter references are allowed in XSLT 1.0, but using these is legal in XSLT 2.x.
/
in XPath denotes the root or document node. In XPath 2.0 (and hence XSLT 2.x) this can also be written as document-node()
.
A match pattern can contain the //
abbreviation.
Examples of match patterns:
<xsl:template match="table">
can be applied on any element named table
.
<xsl:template match="x/y">
can be applied on any element named y
whose parent is an element named x
.
<xsl:template match="*">
can be applied to any element.
<xsl:template match="/*">
can be applied only to the top element of an XML document.
<xsl:template match="@*">
can be applied to any attribute.
<xsl:template match="text()">
can be applied to any text node.
<xsl:template match="comment()">
can be applied to any comment node.
<xsl:template match="processing-instruction()">
can be applied to any processing instruction node.
<xsl:template match="node()">
can be applied to any node: element, text, comment or processing instructon.
I faced the same problem once. THe reason for this is that even though the server is available, the config files are missing. You can see the server at Windows -> Show view -> Servers. Their configuration files can be seen at Project Explorer -> Servers. For some reason this second mentioned config files were missing.
I simply deleted the existing server and created a new one with this the config files were also created and the problem was solved!
Similar solution is given at here by Emertana EM java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory
One way I like to use is:
select ,COUNT()as VAR1 from Table_Name
group by
order by VAR1 desc
limit 1
It turns out the compiler version I was using did not match the compiled version done with the coreset.o.
One was 32bit the other was 64bit. I'll leave this up in case anyone else runs into a similar problem.
Now with new JavaScript version (ECMAScript 6 http://es6-features.org/#ClassDefinition) there is a better way to submit requests using nodejs and Promise request (http://www.wintellect.com/devcenter/nstieglitz/5-great-features-in-es6-harmony)
Using library: https://github.com/request/request-promise
npm install --save request
npm install --save request-promise
client:
//Sequential execution for node.js using ES6 ECMAScript
var rp = require('request-promise');
rp({
method: 'POST',
uri: 'http://localhost:3000/',
body: {
val1 : 1,
val2 : 2
},
json: true // Automatically stringifies the body to JSON
}).then(function (parsedBody) {
console.log(parsedBody);
// POST succeeded...
})
.catch(function (err) {
console.log(parsedBody);
// POST failed...
});
server:
var express = require('express')
, bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/', function(request, response){
console.log(request.body); // your JSON
var jsonRequest = request.body;
var jsonResponse = {};
jsonResponse.result = jsonRequest.val1 + jsonRequest.val2;
response.send(jsonResponse);
});
app.listen(3000);
Although the each function probably isn't necessary ...
$('select').each(function(){
$(this).find('option:first').prop('selected', 'selected');
});
works for me.
Just cast the entire sockaddr
structure to a sockaddr_in. Then you can use:
char *ip = inet_ntoa(their_addr.sin_addr)
To retrieve the standard ip representation.
I too had the same issue. I changed the codec to H264-MPEG-4 AVC and the videos started working in HTML5/Chrome.
Option selected in converter: H264-MPEG-4 AVC, Codec visible in VLC player: H264-MPEG-4 AVC (part 10) (avc1)
Hope it helps...
Initially I too faced this same problem, I installed python and when I run pip
command it used to throw me an error like shown in pic below.
Make Sure pip path is added in environmental variables. For me, the python and pip installation path is::
Python: C:\Users\fhhz\AppData\Local\Programs\Python\Python38\
pip: C:\Users\fhhz\AppData\Local\Programs\Python\Python38\Scripts
Both these paths were added to path in environmental variables.
Now Open a new cmd window and type pip, you should be seeing a screen as below.
Now type pip install <<package-name>>
. Here I'm installing package spyder so my command line statement will be as pip install spyder
and here goes my running screen..
and I hope we are done with this!!
I like Daniel Cerecedo's answer using toJSON()
and regex. An even simpler form would be:
var now = new Date();
var regex = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).*$/;
var token_array = regex.exec(now.toJSON());
// [ "2017-10-31T02:24:45.868Z", "2017", "10", "31", "02", "24", "45" ]
var myFormat = token_array.slice(1).join('');
// "20171031022445"
You're correct, length
is a data member, not a method.
From the Arrays tutorial:
The length of an array is established when the array is created. After creation, its length is fixed.
rather than extension methods, just try a couple of static methods
public static class Utility
{
public static string GetDescriptionFromEnumValue(Enum value)
{
DescriptionAttribute attribute = value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(typeof (DescriptionAttribute), false)
.SingleOrDefault() as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
public static T GetEnumValueFromDescription<T>(string description)
{
var type = typeof(T);
if (!type.IsEnum)
throw new ArgumentException();
FieldInfo[] fields = type.GetFields();
var field = fields
.SelectMany(f => f.GetCustomAttributes(
typeof(DescriptionAttribute), false), (
f, a) => new { Field = f, Att = a })
.Where(a => ((DescriptionAttribute)a.Att)
.Description == description).SingleOrDefault();
return field == null ? default(T) : (T)field.Field.GetRawConstantValue();
}
}
and use here
var result1 = Utility.GetDescriptionFromEnumValue(
Animal.GiantPanda);
var result2 = Utility.GetEnumValueFromDescription<Animal>(
"Lesser Spotted Anteater");
One other point that I didn't see anyone make:
If you don't do anything in your catch {} block, having a try...catch is pointless. I see this all the time:
try
{
//Code here
}
catch
{
throw;
}
Or worse:
try
{
//Code here
}
catch(Exception ex)
{
throw ex;
}
Worst yet:
try
{
//Code here
}
catch(Exception ex)
{
throw new System.Exception(ex.Message);
}
The trick is that the DOM Element.children
attribute is not an array but an array-like collection which has length and can be indexed like an array, but it is not an array:
var children = tableFields.children;
for (var i = 0; i < children.length; i++) {
var tableChild = children[i];
// Do stuff
}
Incidentally, in general it is a better practice to iterate over an array using a basic for-loop instead of a for-in-loop.
The option that I tend to use, mostly because it's simple and I don't have to think, is using Write-Output as below. Write-Output will put an EOL marker in the string for you and you can simply output the finished string.
Write-Output $stringThatNeedsEOLMarker | Out-File -FilePath PathToFile -Append
Alternatively, you could also just build the entire string using Write-Output and then push the finished string into Out-File.
Have you tried using the WebClient class?
you should be able to use
string result = "";
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);
Documentation at
http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspx
http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx
Use "php -l <filename>" (that's an 'L') from the command line to output the syntax error that could be causing PHP to throw the status 500 error. It'll output something like:
PHP Parse error: syntax error, unexpected '}' in <filename> on line 18
// I used VS2012 to write below code-- convert_system_string to Standard_Sting
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace System;
using namespace Runtime::InteropServices;
void MarshalString ( String^ s, std::string& outputstring )
{
const char* kPtoC = (const char*) (Marshal::StringToHGlobalAnsi(s)).ToPointer();
outputstring = kPtoC;
Marshal::FreeHGlobal(IntPtr((void*)kPtoC));
}
int _tmain(int argc, _TCHAR* argv[])
{
std::string strNativeString;
String ^ strManagedString = "Temp";
MarshalString(strManagedString, strNativeString);
std::cout << strNativeString << std::endl;
return 0;
}
System Preferences => Keyboard => Key Repeat Rate
Here's another way of getting a Bash array with the example JSON given by @anubhava in his answer:
arr=($(jq --raw-output 'keys_unsorted | @sh' file.json))
echo ${arr[0]} # 'Archiver-Version'
echo ${arr[1]} # 'Build-Id'
echo ${arr[2]} # 'Build-Jdk'
This may help : Hide the element by positioning it on far most left position and then check the offsetLeft property. If you want to use jQuery you can simply check the :visible selector and get the visibility state of the element.
HTML :
<div id="myDiv">Hello</div>
CSS :
<!-- for javaScript-->
#myDiv{
position:absolute;
left : -2000px;
}
<!-- for jQuery -->
#myDiv{
visibility:hidden;
}
javaScript :
var myStyle = document.getElementById("myDiv").offsetLeft;
if(myStyle < 0){
alert("Div is hidden!!");
}
jQuery :
if( $("#MyElement").is(":visible") == true )
{
alert("Div is visible!!");
}
I had the same problem. The thing is. The selected item doesnt know which object it should use from the collection. So you have to say to the selected item to use the item from the collection.
public MyObject SelectedObject
{
get
{
Objects.find(x => x.id == _selectedObject.id)
return _selectedObject;
}
set
{
_selectedObject = value;
}
}
I hope this helps.
Although >1 year later, I share a slightly different solution. Hope this is useful for somebody.
Yesterday I found myself with the question: "How to share the clipboard between different user sessions?". When switching between sessions with ctrlaltF7 - ctrlaltF8, in fact, you can't paste what you copied.
I came up with the following quick & dirty solution, based on a named pipe. It is surely quite bare and raw, but I found it functional:
user1@host:~$ mkfifo /tmp/sharedClip
then in the sending terminal
user1@host:~$ cat > /tmp/sharedClip
last, in the receiving terminal:
user2@host:~$ cat /tmp/sharedClip
Now, you type or paste anything in the first terminal, and (after hitting return), it will appear immediately in the receiving terminal, from where you can Copy/Paste again anywhere you like.
Of course this doesn't just strictly take the content from user1's clipboard to make it available in user2's clipboard, but rather it requires an additional pair of Paste & Copy clicks.
One way is to associating unique properties with your file while creation.
properties = "{ \
key='somekey' and \
value='somevalue'
}"
then create a query.
query = "title = " + "\'" + title + "\'" + \
AND + "mimeType = " + "\'" + mimeType + "\'" + \
AND + "trashed = false" + \
AND + "properties has " + properties
All the file properties(title, etc) already known to you can go here + properties.
I used this way, and kind liked it , it validates the form before submit also is compatible with safari/google. no jquery n.n.
<module-body>
<form id="testform" method="post">
<label>Input Title</label>
<input name="named1" placeholder="Placeholder" title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
<alert>No Alerts!</alert>
<label>Input Title</label>
<input placeholder="Placeholder" title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
<alert>No Alerts!</alert>
<label>Input Title</label>
<input placeholder="Placeholder" title="Please enter only alphanumeric characters." required="required" pattern="[A-Za-z0-9]{1,20}" />
<alert>No Alerts!</alert>
</form>
</module-body>
<module-footer>
<input type="button" onclick='if (document.querySelector("#testform").reportValidity()) { document.querySelector("#testform").submit(); }' value="Submit">
<input type="button" value="Reset">
</module-footer>
Private Sub Click_Click()
Dim vaFiles As Variant
Dim i As Long
For j = 1 To 2
vaFiles = Application.GetOpenFilename _
(FileFilter:="Excel Filer (*.xlsx),*.xlsx", _
Title:="Open File(s)", MultiSelect:=True)
If Not IsArray(vaFiles) Then Exit Sub
With Application
.ScreenUpdating = False
For i = 1 To UBound(vaFiles)
Workbooks.Open vaFiles(i)
wrkbk_name = vaFiles(i)
Next i
.ScreenUpdating = True
End With
If j = 1 Then
work1 = Right(wrkbk_name, Len(wrkbk_name) - InStrRev(wrkbk_name, "\"))
Else: work2 = Right(wrkbk_name, Len(wrkbk_name) - InStrRev(wrkbk_name, "\"))
End If
Next j
'Filling the values of the group name
'check = Application.WorksheetFunction.Search(Name, work1)
check = InStr(UCase("Qoute Request"), work1)
If check = 1 Then
Application.Workbooks(work1).Activate
Else
Application.Workbooks(work2).Activate
End If
ActiveWorkbook.Sheets("GI Quote Request").Select
ActiveSheet.Range("B4:C12").Copy
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Range("K3").Select
ActiveSheet.Paste
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
Range("D3").Value = Range("L3").Value
Range("D7").Value = Range("L9").Value
Range("D11").Value = Range("L7").Value
For i = 4 To 5
If i = 5 Then
GoTo NextIteration
End If
If Left(ActiveSheet.Range("B" & i).Value, Len(ActiveSheet.Range("B" & i).Value) - 1) = Range("K" & i).Value Then
ActiveSheet.Range("D" & i).Value = Range("L" & i).Value
End If
NextIteration:
Next i
'eligibles part
Count = Range("D11").Value
For i = 27 To Count + 24
Range("C" & i).EntireRow.Offset(1, 0).Insert
Next i
check = Left(work1, InStrRev(work1, ".") - 1)
'check = InStr("Census", work1)
If check = "Census" Then
workbk = work1
Application.Workbooks(work1).Activate
Else
Application.Workbooks(work2).Activate
workbk = work2
End If
'DOB
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("D2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
ActiveSheet.Range("C27").Select
ActiveSheet.Paste
'Gender
Application.Workbooks(workbk).Activate
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("C2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
'Application.CutCopyMode = False
ActiveSheet.Range("k27").Select
ActiveSheet.Paste
For i = 27 To Count + 27
ActiveSheet.Range("E" & i).Value = Left(ActiveSheet.Range("k" & i).Value, 1)
Next i
'Salary
Application.Workbooks(workbk).Activate
ActiveWorkbook.Sheets("Sheet1").Select
ActiveSheet.Range("N2").Select
ActiveSheet.Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Application.Workbooks("Model").Activate
ActiveWorkbook.Sheets("Request").Select
'Application.CutCopyMode = False
ActiveSheet.Range("F27").Select
ActiveSheet.Paste
ActiveSheet.Range("K3:L" & Count).Select
selction.ClearContents
End Sub
For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
While this will not (note the leading space before the opening <?
tag)
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
Also, this will not work either (the echo
will break it):
<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.
add ob_start ();
at the top and at the end add ob_end_flush();
<?php
ob_start();
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
ob_end_flush();
?>
give me an error as below:
FPDF error: Some data has already been output, can't send PDF
to over come this error:
go to fpdf.php
in that,goto line number 996
function Output($name='', $dest='')
after that make changes like this:
function Output($name='', $dest='') {
ob_clean(); //Output PDF to so
Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.
<?
while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);
?>
cheers :-)
In my case i had set:
ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);
When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off
the display_errors
option, the report was generated successfully.
try it.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
In the CSS all you have to do is put url(logical path to the image file)
You can use RoundingMode.#UNNECESSARY if you want/accept exception thrown otherwise
new BigDecimal(value).setScale(2, RoundingMode.UNNECESSARY);
If this rounding mode is specified on an operation that yields an inexact result, an ArithmeticException is thrown.
Exception if not integer value:
java.lang.ArithmeticException: Rounding necessary
I don't know what you are going to use it for, but I needed .doc support for search indexing; What I did was use a little commandline tool called "catdoc"; This transfers the contents of the Word document to plain text so it can be indexed. If you need to keep formatting and stuff this is not your tool.
A little bit simpler and more effective variation of @yannis solution:
SELECT
title,
description,
CHAR_LENGTH(description) - CHAR_LENGTH( REPLACE ( description, 'value', '1234') )
AS `count`
FROM <table>
The difference is that I replace the "value" string with a 1-char shorter string ("1234" in this case). This way you don't need to divide and round to get an integer value.
Generalized version (works for every needle string):
SET @needle = 'value';
SELECT
description,
CHAR_LENGTH(description) - CHAR_LENGTH(REPLACE(description, @needle, SPACE(LENGTH(@needle)-1)))
AS `count`
FROM <table>
In one bizarre case this
contentView.translatesAutoresizingMaskIntoConstraints = false
would not work. Added four explicit anchors to the contentView and it worked.
class AnnoyingCell: UICollectionViewCell {
@IBOutlet var word: UILabel!
override init(frame: CGRect) {
super.init(frame: frame); common() }
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder); common() }
private func common() {
contentView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
contentView.leftAnchor.constraint(equalTo: leftAnchor),
contentView.rightAnchor.constraint(equalTo: rightAnchor),
contentView.topAnchor.constraint(equalTo: topAnchor),
contentView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
}
and as usual
estimatedItemSize = UICollectionViewFlowLayout.automaticSize
in YourLayout: UICollectionViewFlowLayout
Who knows? Might help someone.
https://www.vadimbulavin.com/collection-view-cells-self-sizing/
stumbled on to the tip there - never saw it anywhere else in all the 1000s articles on this.
You need the ?Rscript
command to run an R script from the terminal.
Check out http://stat.ethz.ch/R-manual/R-devel/library/utils/html/Rscript.html
Example
## example #! script for a Unix-alike
#! /path/to/Rscript --vanilla --default-packages=utils
args <- commandArgs(TRUE)
res <- try(install.packages(args))
if(inherits(res, "try-error")) q(status=1) else q()
Method can not return anonymous type. It has to be same as the type defined in method return type. Check the signature of GetProjectForCombo and see what return type you have specified.
Create a class ProjectInfo with required properties and then in new expression create object of ProjectInfo type.
class ProjectInfo
{
public string Name {get; set; }
public long Id {get; set; }
}
public List<ProjectInfo> GetProjectForCombo()
{
using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
{
var query = from pro in db.Projects
select new ProjectInfo(){ Name = pro.ProjectName, Id = pro.ProjectId };
return query.ToList();
}
}
I may have missed something here, but why can't you just declare your string with the desired size? For example, in my VBA code I often use something like:
Dim AString As String * 1024
which provides for a 1k string. Obviously, you can use whatever declaration you like within the larger limits of Excel and available memory etc.
This may be a little inefficient in some cases, and you will probably wish to use Trim(AString) like constructs to obviate any superfluous trailing blanks. Still, it easily exceeds 256 chars.
For faster and short solution you can use HashSet
instead of List
.
a.Overlaps(b);
This method is an O(n) instead of O(n^2) with two lists.
If someone is using column names like "key"
or "value"
, then you still see the same error that your mysql query syntax is bad. This should fix:
.where("`key` LIKE ?", "%#{key}%")
Here is the PHP implementation:
// https://stackoverflow.com/q/12412782/1066234
function math_gcd($a,$b)
{
$a = abs($a);
$b = abs($b);
if($a < $b)
{
list($b,$a) = array($a,$b);
}
if($b == 0)
{
return $a;
}
$r = $a % $b;
while($r > 0)
{
$a = $b;
$b = $r;
$r = $a % $b;
}
return $b;
}
function math_lcm($a, $b)
{
return ($a * $b / math_gcd($a, $b));
}
// https://stackoverflow.com/a/2641293/1066234
function math_lcmm($args)
{
// Recursively iterate through pairs of arguments
// i.e. lcm(args[0], lcm(args[1], lcm(args[2], args[3])))
if(count($args) == 2)
{
return math_lcm($args[0], $args[1]);
}
else
{
$arg0 = $args[0];
array_shift($args);
return math_lcm($arg0, math_lcmm($args));
}
}
// fraction bonus
function math_fraction_simplify($num, $den)
{
$g = math_gcd($num, $den);
return array($num/$g, $den/$g);
}
var_dump( math_lcmm( array(4, 7) ) ); // 28
var_dump( math_lcmm( array(5, 25) ) ); // 25
var_dump( math_lcmm( array(3, 4, 12, 36) ) ); // 36
var_dump( math_lcmm( array(3, 4, 7, 12, 36) ) ); // 252
Credits go to @T3db0t with his answer above (ECMA-style code).
You must override EventTarget.prototype.addEventListener to build an trap function for logging all 'add listener' calls. Something like this:
var _listeners = [];
EventTarget.prototype.addEventListenerBase = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(type, listener)
{
_listeners.push({target: this, type: type, listener: listener});
this.addEventListenerBase(type, listener);
};
Then you can build an EventTarget.prototype.removeEventListeners:
EventTarget.prototype.removeEventListeners = function(targetType)
{
for(var index = 0; index != _listeners.length; index++)
{
var item = _listeners[index];
var target = item.target;
var type = item.type;
var listener = item.listener;
if(target == this && type == targetType)
{
this.removeEventListener(type, listener);
}
}
}
In ES6 you can use a Symbol, to hide the original function and the list of all added listener directly in the instantiated object self.
(function()
{
let target = EventTarget.prototype;
let functionName = 'addEventListener';
let func = target[functionName];
let symbolHidden = Symbol('hidden');
function hidden(instance)
{
if(instance[symbolHidden] === undefined)
{
let area = {};
instance[symbolHidden] = area;
return area;
}
return instance[symbolHidden];
}
function listenersFrom(instance)
{
let area = hidden(instance);
if(!area.listeners) { area.listeners = []; }
return area.listeners;
}
target[functionName] = function(type, listener)
{
let listeners = listenersFrom(this);
listeners.push({ type, listener });
func.apply(this, [type, listener]);
};
target['removeEventListeners'] = function(targetType)
{
let self = this;
let listeners = listenersFrom(this);
let removed = [];
listeners.forEach(item =>
{
let type = item.type;
let listener = item.listener;
if(type == targetType)
{
self.removeEventListener(type, listener);
}
});
};
})();
You can test this code with this little snipper:
document.addEventListener("DOMContentLoaded", event => { console.log('event 1'); });
document.addEventListener("DOMContentLoaded", event => { console.log('event 2'); });
document.addEventListener("click", event => { console.log('click event'); });
document.dispatchEvent(new Event('DOMContentLoaded'));
document.removeEventListeners('DOMContentLoaded');
document.dispatchEvent(new Event('DOMContentLoaded'));
// click event still works, just do a click in the browser
You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:
/**
* Used to stitch together functional operators into a chain.
* @method pipe
* @return {Observable} the Observable result of all of the operators having
* been called in the order they were passed in.
*
* @example
*
* import { map, filter, scan } from 'rxjs/operators';
*
* Rx.Observable.interval(1000)
* .pipe(
* filter(x => x % 2 === 0),
* map(x => x + x),
* scan((acc, x) => acc + x)
* )
* .subscribe(x => console.log(x))
*/
Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan()
, but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe()
to make a chain of those operators (see example above).
Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do()
. You can think of it as if observable was an array over time, then tap()
would be an equivalent to Array.forEach()
.
Just use the crossOrigin
attribute and pass 'anonymous'
as the second parameter
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
The <ul>
is by default a block element, make it inline-block
instead:
.navigation-bar ul {
padding: 0px;
margin: 0px;
text-align: center;
display:inline-block;
vertical-align:top;
}
You may make a computed property and enable/disable any form type according to its value.
<template>
<button class="btn btn-default" :disabled="clickable">Click me</button>
</template>
<script>
export default{
computed: {
clickable() {
// if something
return true;
}
}
}
</script>
None of those work for me.
.fa-volume-down {
color: white;
width: 50% !important;
height: 50% !important;
margin-top: 8%;
margin-left: 7.5%;
font-size: 1em;
background-size: 120%;
}
You cannot start a container from a Dockerfile.
The process goes like this:
Dockerfile =[
docker build
]=> Docker image =[docker run
]=> Docker container
To start (or run) a container you need an image. To create an image you need to build the Dockerfile[1].
[1]: you can also docker import
an image from a tarball or again docker load
.
Try this:
// MockHttpSession Setup
var session = new MockHttpSession();
// MockHttpRequest Setup - mock AJAX request
var httpRequest = new Mock<HttpRequestBase>();
// Setup this part of the HTTP request for AJAX calls
httpRequest.Setup(req => req["X-Requested-With"]).Returns("XMLHttpRequest");
// MockHttpContextBase Setup - mock request, cache, and session
var httpContext = new Mock<HttpContextBase>();
httpContext.Setup(ctx => ctx.Request).Returns(httpRequest.Object);
httpContext.Setup(ctx => ctx.Cache).Returns(HttpRuntime.Cache);
httpContext.Setup(ctx => ctx.Session).Returns(session);
// MockHttpContext for cache
var contextRequest = new HttpRequest("", "http://localhost/", "");
var contextResponse = new HttpResponse(new StringWriter());
HttpContext.Current = new HttpContext(contextRequest, contextResponse);
// MockControllerContext Setup
var context = new Mock<ControllerContext>();
context.Setup(ctx => ctx.HttpContext).Returns(httpContext.Object);
//TODO: Create new controller here
// Set controller's ControllerContext to context.Object
And Add the class:
public class MockHttpSession : HttpSessionStateBase
{
Dictionary<string, object> _sessionDictionary = new Dictionary<string, object>();
public override object this[string name]
{
get
{
return _sessionDictionary.ContainsKey(name) ? _sessionDictionary[name] : null;
}
set
{
_sessionDictionary[name] = value;
}
}
public override void Abandon()
{
var keys = new List<string>();
foreach (var kvp in _sessionDictionary)
{
keys.Add(kvp.Key);
}
foreach (var key in keys)
{
_sessionDictionary.Remove(key);
}
}
public override void Clear()
{
var keys = new List<string>();
foreach (var kvp in _sessionDictionary)
{
keys.Add(kvp.Key);
}
foreach(var key in keys)
{
_sessionDictionary.Remove(key);
}
}
}
This will allow you to test with both session and cache.
I found the solution in this topic and I code this:
$cards = DB::select("SELECT
cards.id_card,
cards.hash_card,
cards.`table`,
users.name,
0 as total,
cards.card_status,
cards.created_at as last_update
FROM cards
LEFT JOIN users
ON users.id_user = cards.id_user
WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
UNION
SELECT
cards.id_card,
orders.hash_card,
cards.`table`,
users.name,
sum(orders.quantity*orders.product_price) as total,
cards.card_status,
max(orders.created_at) last_update
FROM menu.orders
LEFT JOIN cards
ON cards.hash_card = orders.hash_card
LEFT JOIN users
ON users.id_user = cards.id_user
GROUP BY hash_card
ORDER BY id_card ASC");
- Each time you append or do any modification with it, it creates a new String
object.
- So use append()
method of StringBuilder
(If thread safety is not important), else use StringBuffer
(If thread safety is important.), that will be efficient way to do it.
If you're using jQuery and want to keep using indexOf without worrying about compatibility issues, you can do this :
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(val) {
return jQuery.inArray(val, this);
};
}
This is helpful when you want to keep using indexOf
but provide a fallback when it's not available.
It is bounded on the lower end by 2^(n/2)
and on the upper end by 2^n (as noted in other comments). And an interesting fact of that recursive implementation is that it has a tight asymptotic bound of Fib(n) itself. These facts can be summarized:
T(n) = O(2^(n/2)) (lower bound)
T(n) = O(2^n) (upper bound)
T(n) = T(Fib(n)) (tight bound)
The tight bound can be reduced further using its closed form if you like.
Here is a much shorter way:
defaultConfig {
...
applicationId "com.blahblah.example"
versionCode 1
versionName "1.0"
setProperty("archivesBaseName", applicationId + "-v" + versionCode + "(" + versionName + ")")
//or so
archivesBaseName = "$applicationId-v$versionCode($versionName)"
}
It gives you name com.blahblah.example-v1(1.0)-debug.apk (in debug mode)
Android Studio add versionNameSuffix by build type name by default, if you want override this, do next:
buildTypes {
debug {
...
versionNameSuffix "-MyNiceDebugModeName"
}
release {
...
}
}
Output in debug mode: com.blahblah.example-v1(1.0)-MyNiceDebugModeName.apk
I tried all the solutions listed and none of them worked. I ended up having to do a sp_detach_db, then deleting the ldf file and re-attaching the database forcing it to create a new ldf file. That worked.
If we need only one column to be numeric
yyz$b <- as.numeric(as.character(yyz$b))
But, if all the columns needs to changed to numeric
, use lapply
to loop over the columns and convert to numeric
by first converting it to character
class as the columns were factor
.
yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))
Both the columns in the OP's post are factor
because of the string "n/a"
. This could be easily avoided while reading the file using na.strings = "n/a"
in the read.table/read.csv
or if we are using data.frame
, we can have character
columns with stringsAsFactors=FALSE
(the default is stringsAsFactors=TRUE
)
Regarding the usage of apply
, it converts the dataset to matrix
and matrix
can hold only a single class. To check the class
, we need
lapply(yyz, class)
Or
sapply(yyz, class)
Or check
str(yyz)
You can open the file again using vi helloworld.txt
and then use cat /path/your_file
to view it.
The argument order seems to matter... to exclude subdirectories, I used
robocopy \\source\folder C:\destinationfolder /XD * /MIR
...and that works for me (Windows 10 copy from Windows Server 2016)
I tried doing a SELECT DATE(ColumnName)
, however this does not work for TIMESTAMP
columns† because they are stored in UTC and the UTC date is used instead of converting to the local date. I needed to select rows that were on a specific date in my time zone, so combining my answer to this other question with Balaswamy Vaddeman's answer to this question, this is what I did:
DATETIME
Just do SELECT DATE(ColumnName)
TIMESTAMP
Load the time zone data into MySQL if you haven't done so already. For Windows servers see the previous link. For Linux, FreeBSD, Solaris, and OS X servers you would do:
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
Then format your query like this:
SELECT DATE(CONVERT_TZ(`ColumnName`, 'UTC', 'America/New_York'))
You can also put this in the WHERE
part of the query like this (but note that indexes on that column will not work):
SELECT * FROM tableName
WHERE DATE(CONVERT_TZ(`ColumnName`, 'UTC', 'America/New_York')) >= '2015-02-04'
(Obviously substitute America/New_York
for your local time zone.)
† The only exception to this is if your local time zone is GMT and you don't do daylight savings because your local time is the same as UTC.
The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).
Define a Java class that resembles the JSON you will be expecting.
e.g. this JSON:
{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}
could be mapped to this class:
public class Fizzle{
private List<String> foo;
private boolean bar;
private int baz;
// getters and setters omitted
}
Now if you have a Controller method like this:
@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
return new Fozzle(input);
}
and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json
.
For a full working example see this previous answer of mine.
If you already have the databinding in place John Myczek answer is complete.
If not you have at least 2 options I know of if you want to specify the source of your data. (However I am not sure whether or not this is in
line with most guidelines, like MVVM)
option 1: like JohnB said. But I think you should use your own defined collection instead of a weakly typed DataTable (no offense, but you can't tell from the code what each column represents)
xaml.cs
DataContext = myCollection;
//myCollection is a `ICollection<YourType>` preferably
`ObservableCollection<YourType>
- option 2) Declare the name of the Datagrid in xaml
<WpfToolkit:DataGrid Name=dataGrid}>
in xaml.cs
CollectionView myCollectionView =
(CollectionView)CollectionViewSource.GetDefaultView(yourCollection);
dataGrid.ItemsSource = myCollectionView;
If your type has a property FirstName defined, you can then do what John Myczek pointed out.
DataGridTextColumn textColumn = new DataGridTextColumn();
dataColumn.Header = "First Name";
dataColumn.Binding = new Binding("FirstName");
dataGrid.Columns.Add(textColumn);
This obviously doesn't work if you don't know properties you will need to show in your dataGrid, but if that is the case you will have more problems to deal with, and I believe that's out of scope here.
Given your simple question: "In javascript, when would you want to use this:..."
I like @ken_browning and @sean_holding's answers, but here's another use-case that I don't see mentioned:
let red_tree = new Node(10);
(async function () {
for (let i = 0; i < 1000; i++) {
await red_tree.insert(i);
}
})();
console.log('----->red_tree.printInOrder():', red_tree.printInOrder());
where Node.insert is some asynchronous action.
I can't just call await without the async keyword at the declaration of my function, and i don't need a named function for later use, but need to await that insert call or i need some other richer features (who knows?).
This gives the value if it exists, and returns an error code ERROR_FILE_NOT_FOUND if the key doesn't exist.
(I can't tell if my link is working or not, but if you just google for "RegQueryValueEx" the first hit is the msdn documentation.)
i have a very simple function:
function busca(busca){
$("#listagem tr:not(contains('"+busca+"'))").css("display", "none");
$("#listagem tr:contains('"+busca+"')").css("display", "");
}
I'd actually suggest using a solid open-source library as an http client. If you take a look at http client by ASF you'll find life a lot easier. It is an easy-to-use,scalable and robust client for http.
Using constants allows to combine multiple fields for verification:
class LoginFrm extends React.Component {_x000D_
constructor() {_x000D_
super();_x000D_
this.state = {_x000D_
email: '',_x000D_
password: '',_x000D_
};_x000D_
}_x000D_
_x000D_
handleEmailChange = (evt) => {_x000D_
this.setState({ email: evt.target.value });_x000D_
}_x000D_
_x000D_
handlePasswordChange = (evt) => {_x000D_
this.setState({ password: evt.target.value });_x000D_
}_x000D_
_x000D_
handleSubmit = () => {_x000D_
const { email, password } = this.state;_x000D_
alert(`Welcome ${email} password: ${password}`);_x000D_
}_x000D_
_x000D_
render() {_x000D_
const { email, password } = this.state;_x000D_
const enabled =_x000D_
email.length > 0 &&_x000D_
password.length > 0;_x000D_
return (_x000D_
<form onSubmit={this.handleSubmit}>_x000D_
<input_x000D_
type="text"_x000D_
placeholder="Email"_x000D_
value={this.state.email}_x000D_
onChange={this.handleEmailChange}_x000D_
/>_x000D_
_x000D_
<input_x000D_
type="password"_x000D_
placeholder="Password"_x000D_
value={this.state.password}_x000D_
onChange={this.handlePasswordChange}_x000D_
/>_x000D_
<button disabled={!enabled}>Login</button>_x000D_
</form>_x000D_
)_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<LoginFrm />, document.body);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<body>_x000D_
_x000D_
_x000D_
</body>
_x000D_
From R 3.0.0 onwards mean(<data.frame>)
is defunct (and passing a data.frame to mean
will give the error you state)
A data frame is a list of variables of the same number of rows with unique row names, given class "data.frame".
In your case, result has two variables (if your description is correct) . You could obtain the column means by using any of the following
lapply(results, mean, na.rm = TRUE)
sapply(results, mean, na.rm = TRUE)
colMeans(results, na.rm = TRUE)
You can also use interface builder if you don't want to make the adjustments in code. Here I left align the text and also indent it some:
Don't forget you can also align an image in the button too.:
You can also override onContentChanged()
which is among others fired when setContentView()
has been called.
If your arrays are not string arrays, use:
memcpy(array2, array1, sizeof(array2));
<button style="position: absolute; left: 20%; right: 20%; bottom: 5%;"> Button </button>
log in as root user:
sudo su
password:
then go and do what you want to do in var/www
First check if the user has granted the permission:
if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED)
Then, you could use this to request to the user:
ActivityCompat.requestPermissions(activity, new String[] {Manifest.permission.CAMERA}, requestCode);
And in Marshmallow, it will appear in a dialog
You can try this.
// Author: Hannad Rehman Sat Jun 03 2017 12:59:09 GMT+0530 (India Standard Time)
import React from 'react';
import RippleButton from '../../Components/RippleButton/rippleButton.jsx';
class HtmlComponents extends React.Component {
constructor(props){
super(props);
this.rippleClickFunction=this.rippleClickFunction.bind(this);
}
rippleClickFunction(){
//do stuff.
// foo==bar
}
render() {
return (
<article>
<h1>React Components</h1>
<RippleButton onClick={this.rippleClickFunction}/>
</article>
);
}
}
export default HtmlComponents;
Yhe only concern is you have to bind the context to the function
After formatting the previous answer to my own code, I have found an efficient way to copy all necessary data if you are attempting to paste the values returned via AutoFilter
to a separate sheet.
With .Range("A1:A" & LastRow)
.Autofilter Field:=1, Criteria1:="=*" & strSearch & "*"
.Offset(1,0).SpecialCells(xlCellTypeVisible).Cells.Copy
Sheets("Sheet2").activate
DestinationRange.PasteSpecial
End With
In this block, the AutoFilter
finds all of the rows that contain the value of strSearch
and filters out all of the other values. It then copies the cells (using offset in case there is a header), opens the destination sheet and pastes the values to the specified range on the destination sheet.
let us see the below source code. Here fragment name is DirectoryOfEbooks. After completion of the background task, i am the replacing the frame with current fragment. so the fragment gets refreshed and reloads its data
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.github.mikephil.charting.data.LineRadarDataSet;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class DirectoryOfEbooks extends Fragment {
RecyclerView recyclerView;
branchesAdapter adapter;
LinearLayoutManager linearLayoutManager;
Cursor c;
FragmentTransaction fragmentTransaction;
SQLiteDatabase db;
List<branch_sync> directoryarraylist;
public DirectoryOfEbooks() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_directory_of_ebooks, container, false);
directoryarraylist = new ArrayList<>();
db = getActivity().openOrCreateDatabase("notify", android.content.Context.MODE_PRIVATE, null);
c = db.rawQuery("select * FROM branch; ", null);
if (c.getCount() != 0) {
c.moveToFirst();
while (true) {
//String ISBN = c.getString(c.getColumnIndex("ISBN"));
String branch = c.getString(c.getColumnIndex("branch"));
branch_sync branchSync = new branch_sync(branch);
directoryarraylist.add(branchSync);
if (c.isLast())
break;
else
c.moveToNext();
}
recyclerView = (RecyclerView) view.findViewById(R.id.directoryOfEbooks);
adapter = new branchesAdapter(directoryarraylist, this.getContext());
adapter.setHasStableIds(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
System.out.println("ebooks");
recyclerView.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(this.getContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
System.out.println(adapter.getItemCount()+"adpater count");
}
// Inflate the layout for this fragment
return view;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.fragment_books);
setHasOptionsMenu(true);
}
public void onPrepareOptionsMenu(Menu menu) {
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.refresh, menu);
MenuItem menuItem = menu.findItem(R.id.refresh1);
menuItem.setVisible(true);
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.refresh1) {
new AlertDialog.Builder(getContext()).setMessage("Refresh takes more than a Minute").setPositiveButton("Refresh Now", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new refreshebooks().execute();
}
}).setNegativeButton("Refresh Later", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).setCancelable(false).show();
}
return super.onOptionsItemSelected(item);
}
public class refreshebooks extends AsyncTask<String,String,String>{
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog=new ProgressDialog(getContext());
progressDialog.setMessage("\tRefreshing Ebooks .....");
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected String doInBackground(String... params) {
Ebooksync syncEbooks=new Ebooksync();
String status=syncEbooks.syncdata(getContext());
return status;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s.equals("error")){
progressDialog.dismiss();
Toast.makeText(getContext(),"Refresh Failed",Toast.LENGTH_SHORT).show();
}
else{
fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.mainframe, new DirectoryOfEbooks());
fragmentTransaction.commit();
progressDialog.dismiss();
adapter.notifyDataSetChanged();
Toast.makeText(getContext(),"Refresh Successfull",Toast.LENGTH_SHORT).show();
}
}
}
}
The statement def foo(client_id: str) -> list or bool:
when evaluated is equivalent to
def foo(client_id: str) -> list:
and will therefore not do what you want.
The native way to describe a "either A or B" type hint is Union (thanks to Bhargav Rao):
def foo(client_id: str) -> Union[list, bool]:
I do not want to be the "Why do you want to do this anyway" guy, but maybe having 2 return types isn't what you want:
If you want to return a bool to indicate some type of special error-case, consider using Exceptions instead. If you want to return a bool as some special value, maybe an empty list would be a good representation.
You can also indicate that None
could be returned with Optional[list]
Neither of them worked for me for some reason.
I figured it out that for some reason python doesn't read %s. So use (?) instead of %S in you SQL Code.
And finally this worked for me.
cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4"))
connect.commit()
Try this, sudo service mysql stop it will stop any other mysql services and then restart xampp
My experience in this matter tells me , most of these software work good with small projects .
But what about big projects? e.g: Zend Framework 2 and some things like that.
Some of them need browser to run and this is difficult to tell customer "please type http://localhost/
" in your browser address bar !!
I create a simple project to do this : PHPPy
This is not complete way for create stand alone executable file for running php projects but helps you to do this.
I couldn't compile python file with PyInstaller or Py2exe to .exe file , hope you can.
You don't need uniformserver executable files.
You could do this
Assembly asm = Assembly.GetExecutingAssembly();
string path = System.IO.Path.GetDirectoryName(asm.Location);
The short answer is: don't. If you want code that reads linearly, use a library like seq. But just don't expect synchronous. You really can't. And that's a good thing.
There's little or nothing that can't be put in a callback. If they depend on common variables, create a closure to contain them. What's the actual task at hand?
You'd want to have a counter, and only call the callback when the data is there:
var waiting = 2;
request( {url: base + u_ext}, function( err, res, body ) {
var split1 = body.split("\n");
var split2 = split1[1].split(", ");
ucomp = split2[1];
if(--waiting == 0) callback();
});
request( {url: base + v_ext}, function( err, res, body ) {
var split1 = body.split("\n");
var split2 = split1[1].split(", ");
vcomp = split2[1];
if(--waiting == 0) callback();
});
function callback() {
// do math here.
}
Update 2018: node.js supports async/await keywords in recent editions, and with libraries that represent asynchronous processes as promises, you can await them. You get linear, sequential flow through your program, and other work can progress while you await. It's pretty well built and worth a try.
That's not the behavior I'm seeing:
irb(main):001:0> metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" =>
10 }
=> {"siteb.com"=>9, "sitec.com"=>10, "sitea.com"=>745}
irb(main):002:0> metrics.sort {|a1,a2| a2[1]<=>a1[1]}
=> [["sitea.com", 745], ["sitec.com", 10], ["siteb.com", 9]]
Is it possible that somewhere along the line your numbers are being converted to strings? Is there more code you're not posting?
Binary floating-point numbers have interesting precision characteristics, since the value is stored as a binary integer raised to a binary power. When dealing with sub-integer values (that is, values between 0 and 1), negative powers of two "round off" very differently than negative powers of ten.
For example, the number 0.1 can be represented by 1 x 10-1, but there is no combination of base-2 exponent and mantissa that can precisely represent 0.1 -- the closest you get is 0.10000000000000001.
So if you have an application where you are working with values like 0.1 or 0.01 a great deal, but where small (less than 0.000000000000001%) errors cannot be tolerated, then binary floating-point numbers are not for you.
Conversely, if powers of ten are not "special" to your application (powers of ten are important in currency calculations, but not in, say, most applications of physics), then you are actually better off using binary floating-point, since it's usually at least an order of magnitude faster, and it is much more memory efficient.
The article from the Python documentation on floating point issues and limitations does an excellent job of explaining this issue in an easy to understand form. Wikipedia also has a good article on floating point that explains the math behind the representation.
You're not running a module -- you're running subroutines/functions that happen to be stored in modules.
If you put the code in a standalone module and don't specify scope in the definitions of your subroutines/functions, they will be public by default, and callable from anywhere within your application. This means that you can call them with RunCode in a macro, from the class modules of forms/reports, from standalone class modules, or for the functions, from SQL (with some caveats).
Given that you were trying to implement in VBA something that you felt was too complicated for SQL, SQL is the likely context in which you want to execute the code. So, you should just be able to call your function within the SQL statement:
SELECT MyTable.PersonID, MyTable.FirstName, MyTable.LastName, FormatAddress([Address], [City], [State], [Zip], [Country]) As Address
FROM MyTable;
That SQL calls a public function called FormatAddress() that takes as arguments the components of an address and formats them appropriately. It's a trivial example as you likely would not need a VBA function for that purpose, but the point is that this is how you call functions from within a SQL statement.
Subroutines (i.e., code that returns no value) are not callable from within SQL statements.
One way would be:
while read NAME
do
echo "$NAME"
done < names.txt
EDIT:
Note that the loop gets executed in a sub-shell, so any modified variables will be local, except if you declare them with declare
outside the loop.
Dennis Williamson is right. Sorry, must have used piped constructs too often and got confused.
Your onCreate()
method has several huge flaws:
1) onCreate
prepares your Activity - so nothing that you do here will be made visible to the user until this method finishes! For example - you will never be able to alter a TextView
's text here more than ONE time as only the last change will be drawn and thus visible to the user!
2) Keep in mind that an Android program will - by default - run in ONE thread only! Thus: never use Thread.sleep()
or Thread.wait()
in your main thread which is responsible for your UI! (read "Keep your App Responsive" for further information!)
What your initialization of your Activity does is:
TextView
object t
!TextView
in the variable t
later.t
(but keep in mind: it will be displayed only after onCreate()
finishes and the main event loop of your application runs!)onCreate
method - this must never be done as it stops all UI activity and will definitely force an ANR (Application Not Responding, see link above!)onCreate()
method finishes and several other Activity lifecycle methods have been processed!The solution:
Set text only once in onCreate()
- this must be the first text that should be visible.
Create a Runnable
and a Handler
private final Runnable mUpdateUITimerTask = new Runnable() {
public void run() {
// do whatever you want to change here, like:
t.setText("Second text to display!");
}
};
private final Handler mHandler = new Handler();
install this runnable as a handler, possible in onCreate()
(but read my advice below):
// run the mUpdateUITimerTask's run() method in 10 seconds from now
mHandler.postDelayed(mUpdateUITimerTask, 10 * 1000);
Advice: be sure you know an Activity
's lifecycle! If you do stuff like that in onCreate()
this will only happen when your Activity
is created the first time! Android will possibly keep your Activity
alive for a longer period of time, even if it's not visible!
When a user "starts" it again - and it is still existing - you will not see your first text anymore!
=> Always install handlers in onResume()
and disable them in onPause()
! Otherwise you will get "updates" when your Activity
is not visible at all!
In your case, if you want to see your first text again when it is re-activated, you must set it in onResume()
, not onCreate()
!
Try on this..
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
For those who are looking for pure javascript solution
document.getElementById(location.hash.substring(1)).style.display = 'block'
Hope this saves you some time.
Mysqldump isn't bad solution. Simplest way to duplicate database:
mysqldump -uusername -ppass dbname1 | mysql -uusername -ppass dbname2
Also, you can change storage engine by this way:
mysqldump -uusername -ppass dbname1 | sed 's/InnoDB/RocksDB/' | mysql -uusername -ppass dbname2