Example query:
SELECT TO_CHAR(TO_DATE('2017-08-23','YYYY-MM-DD'), 'MM/DD/YYYY') FROM dual;
You guessed right, HTTP Headers are not part of the URL.
And when you type a URL in the browser the request will be issued with standard headers. Anyway REST Apis are not meant to be consumed by typing the endpoint in the address bar of a browser.
The most common scenario is that your server consumes a third party REST Api.
To do so your server-side code forges a proper GET (/PUT/POST/DELETE) request pointing to a given endpoint (URL) setting (when needed, like your case) some headers and finally (maybe) sending some data (as typically occurrs in a POST request for example).
The code to forge the request, send it and finally get the response back depends on your server side language.
If you want to test a REST Api you may use curl
tool from the command line.
curl
makes a request and outputs the response to stdout (unless otherwise instructed).
In your case the test request would be issued like this:
$curl -H "Accept: application/json" 'http://localhost:8080/otp/routers/default/plan?fromPlace=52.5895,13.2836&toPlace=52.5461,13.3588&date=2017/04/04&time=12:00:00'
The H
or --header
directive sets a header and its value.
You should make sure your test case function is public rather than private to make it accessible by Test Runner.
@Test
private void testmethod(){}
to
@Test
public void testmethod(){}
The $ sign is an identifier for variables and functions.
That has a clear explanation of what the dollar sign is for.
Here's an alternative explanation: http://www.vcarrer.com/2010/10/about-dollar-sign-in-javascript.html
I have this solution working for me:
Create a file named dayOfWeek.vbs in the same dir where the cmd file will go.
dayOfWeek.vbs contains a single line:
wscript.stdout.write weekdayname(weekday(date))
or, if you want day number instead of name:
wscript.stdout.write weekday(date)
The cmd file will have this line:
For /F %%A In ('CScript dayOfWeek.vbs //NoLogo') Do Set dayName=%%A
Now you can use variable dayName like:
robocopy c:\inetpub \\DCStorage1\Share1\WebServer\InetPub_%dayName% /S /XD history logs
To answer the question more generally, the answer is:
select: function( event , ui ) {
alert( "You selected: " + ui.item.label );
}
Complete example :
$('#test').each(function(i, el) {_x000D_
var that = $(el);_x000D_
that.autocomplete({_x000D_
source: ['apple','banana','orange'],_x000D_
select: function( event , ui ) {_x000D_
alert( "You selected: " + ui.item.label );_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>_x000D_
_x000D_
Type a fruit here: <input type="text" id="test" />
_x000D_
.schema TableName
Where TableName is the name of the Table
I recently found this App called Icon Set Creator in the App Store which is free, without ads, updated on new changes, straight forward and works just fine for every possible icon size in OSX, iOS and WatchOS:
$dateTime = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
echo $dateTime->modify("+10 minutes")->format("H:i:s A");
Funnily enough, adjusting the padding seems to do it.
.arrow {
border: solid rgb(2, 0, 0);
border-width: 0 3px 3px 0;
display: inline-block;
}
.first{
padding: 2vh;
}
.second{
padding: 4vh;
}
.left {
transform: rotate(135deg);
-webkit-transform: rotate(135deg);
}
_x000D_
<i class="arrow first left"></i>
<i class="arrow second left"></i>
_x000D_
i was trying trying to GRANT read-only privileges to a particular table to a user called walters-ro. So when i ran the sql command # GRANT SELECT ON table_name TO walters-ro; --- i got the following error..`syntax error at or near “-”
The solution to this was basically putting the user_name into double quotes since there is a dash(-) between the name.
# GRANT SELECT ON table_name TO "walters-ro";
That solved the problem.
You just have to remove dataType: 'json'
from your header if your implemented Web service method is void.
In this case, the Ajax call don't expect to have a JSON return datatype.
You could use scipy.interpolate.spline
to smooth out your data yourself:
from scipy.interpolate import spline
# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300)
power_smooth = spline(T, power, xnew)
plt.plot(xnew,power_smooth)
plt.show()
spline is deprecated in scipy 0.19.0, use BSpline class instead.
Switching from spline
to BSpline
isn't a straightforward copy/paste and requires a little tweaking:
from scipy.interpolate import make_interp_spline, BSpline
# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300)
spl = make_interp_spline(T, power, k=3) # type: BSpline
power_smooth = spl(xnew)
plt.plot(xnew, power_smooth)
plt.show()
To add to the other answers, instead of assigning to a differently named variable inside of an if
condition:
var a: Int? = 5
if let b = a {
// do something
}
you can reuse the same variable name like this:
var a: Int? = 5
if let a = a {
// do something
}
This might help you avoid running out of creative variable names...
This takes advantage of variable shadowing that is supported in Swift.
From the MDN docs for the :-webkit-autofill CSS pseudo-class:
The :-webkit-autofill CSS pseudo-class matches when an element has its value autofilled by the browser
We can define a void transition css rule on the desired <input>
element once it is :-webkit-autofill
ed. JS will then be able to hook onto the animationstart
event.
Credits to the Klarna UI team. See their nice implementation here:
First create an object of class2 in class1 and then use that object to call any function of class2 for example write this in class1
class2 obj= new class2();
obj.thefunctioname(args);
You can try settings of code::block
, there is a complier..., then you select in C mode.
Use:
document.location.href = "http://yoursite.com" + document.getElementById('somefield');
That would get the value of some text field or hidden field, and add it to your site URL to get a new URL (href). You can modify this to suit your needs.
In Visual Studio:
Properties ->
Advanced ->
Entry Point ->
write just the name of the function you want the program to begin running from, case sensitive, without any brackets and command line arguments.
You can see all the version of a module with npm view
.
eg: To list all versions of bootstrap including beta.
npm view bootstrap versions
But if the version list is very big it will truncate. An --json
option will print all version including beta versions as well.
npm view bootstrap versions --json
If you want to list only the stable versions not the beta then use singular version
npm view bootstrap@* versions
Or
npm view bootstrap@* versions --json
And, if you want to see only latest version then here you go.
npm view bootstrap version
Hope it might help someone instantly.
In Python 2.7: By default, division operator will return integer output.
to get the result in double multiple 1.0 to "dividend or divisor"
100/35 => 2 #(Expected is 2.857142857142857)
(100*1.0)/35 => 2.857142857142857
100/(35*1.0) => 2.857142857142857
In Python 3
// => used for integer output
/ => used for double output
100/35 => 2.857142857142857
100//35 => 2
100.//35 => 2.0 # floating-point result if divsor or dividend real
check out csvreader/writer library at http://www.codeproject.com/KB/cs/CsvReaderAndWriter.aspx
I used to try this method
_.filter(data, function(d) { return d.name != 'a' });
There might be better methods too like the above solutions provided by users
I landed here with the same issue, then figured it out on my own. This weird character was appearing with my HTML.
The issue is most likely your code editor. I use Espresso and sometimes run into issues like this.
To fix it, simply highlight the affected code, then go to the menu and click "convert to numeric entities". You'll see the numeric value of this character appear; simply delete it and it's gone forever.
To your secondary question
var elem1 = $('#elem1'),
elem2 = $('#elem2'),
elem3 = $('#elem3');
You can use the variable as the replacement of selector.
elem1.css({'display':'none'}); //will work
In the below case selector is already stored in a variable.
$(elem1,elem2,elem3).css({'display':'none'}); // will not work
You can use the Java enum TimeUnit
to perform your math and avoid any hard coded values. Then we can use String.format(String, Object...)
and a pair of StringBuilder
(s) as well as a DecimalFormat
to build the requested output. Something like,
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number of seconds:");
String str = scanner.nextLine().replace("\\,", "").trim();
long secondsIn = Long.parseLong(str);
long dayCount = TimeUnit.SECONDS.toDays(secondsIn);
long secondsCount = secondsIn - TimeUnit.DAYS.toSeconds(dayCount);
long hourCount = TimeUnit.SECONDS.toHours(secondsCount);
secondsCount -= TimeUnit.HOURS.toSeconds(hourCount);
long minutesCount = TimeUnit.SECONDS.toMinutes(secondsCount);
secondsCount -= TimeUnit.MINUTES.toSeconds(minutesCount);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%d %s, ", dayCount, (dayCount == 1) ? "day"
: "days"));
StringBuilder sb2 = new StringBuilder();
sb2.append(sb.toString());
sb2.append(String.format("%02d:%02d:%02d %s", hourCount, minutesCount,
secondsCount, (hourCount == 1) ? "hour" : "hours"));
sb.append(String.format("%d %s, ", hourCount, (hourCount == 1) ? "hour"
: "hours"));
sb.append(String.format("%d %s and ", minutesCount,
(minutesCount == 1) ? "minute" : "minutes"));
sb.append(String.format("%d %s.", secondsCount,
(secondsCount == 1) ? "second" : "seconds"));
System.out.printf("You entered %s seconds, which is %s (%s)%n",
new DecimalFormat("#,###").format(secondsIn), sb, sb2);
Which, when I enter 500000
outputs the requested (manual line break added for post) -
You entered 500,000 seconds, which is 5 days, 18 hours,
53 minutes and 20 seconds. (5 days, 18:53:20 hours)
insertAdjacentHTML
+ outerHTML
elementBefore.insertAdjacentHTML('afterEnd', elementAfter.outerHTML)
Upsides:
insertBefore
(break even if the existing node variable name is 3 chars long)Downsides:
outerHTML
converts the element to a string. We need it because insertAdjacentHTML
adds content from strings rather than elements.To make it do nothing at all, use this:
<a href="javascript:void(0)"> ... </a>
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
This code works very well
function isUndefined(array, index) {
return ((String(array[index]) == "undefined") ? "Yes" : "No");
}
I had a similar problem using Flask, but I did not have to resort to JSON. I just passed a list letters = ['a','b','c']
with render_template('show_entries.html', letters=letters)
, and set
var letters = {{ letters|safe }}
in my javascript code. Jinja2 replaced {{ letters }}
with ['a','b','c']
, which javascript interpreted as an array of strings.
This is the first example in the manual page for mysql_query
:
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
If you wish to use something other than die
, then I'd suggest trigger_error
.
The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo
ls
show the right files?git init
? (git-init documentation)Either of those would cause your error.
My experience with larger files sizes has been that java.nio
is faster than java.io
. Solidly faster. Like in the >250% range. That said, I am eliminating obvious bottlenecks, which I suggest your micro-benchmark might suffer from. Potential areas for investigating:
The buffer size. The algorithm you basically have is
My own experience has been that this buffer size is ripe for tuning. I've settled on 4KB for one part of my application, 256KB for another. I suspect your code is suffering with such a large buffer. Run some benchmarks with buffers of 1KB, 2KB, 4KB, 8KB, 16KB, 32KB and 64KB to prove it to yourself.
Don't perform java benchmarks that read and write to the same disk.
If you do, then you are really benchmarking the disk, and not Java. I would also suggest that if your CPU is not busy, then you are probably experiencing some other bottleneck.
Don't use a buffer if you don't need to.
Why copy to memory if your target is another disk or a NIC? With larger files, the latency incured is non-trivial.
Like other have said, use FileChannel.transferTo()
or FileChannel.transferFrom()
. The key advantage here is that the JVM uses the OS's access to DMA (Direct Memory Access), if present. (This is implementation dependent, but modern Sun and IBM versions on general purpose CPUs are good to go.) What happens is the data goes straight to/from disc, to the bus, and then to the destination... bypassing any circuit through RAM or the CPU.
The web app I spent my days and night working on is very IO heavy. I've done micro benchmarks and real-world benchmarks too. And the results are up on my blog, have a look-see:
Use production data and environments
Micro-benchmarks are prone to distortion. If you can, make the effort to gather data from exactly what you plan to do, with the load you expect, on the hardware you expect.
My benchmarks are solid and reliable because they took place on a production system, a beefy system, a system under load, gathered in logs. Not my notebook's 7200 RPM 2.5" SATA drive while I watched intensely as the JVM work my hard disc.
What are you running on? It matters.
Note a similar error such as:
standard_init_linux.go:211: exec user process caused "no such file or directory"
can happen if the architecture an image was built for does not match the one of your system. For instance, trying to run an image built for arm64
on a x86_64
machine can generate this error.
This is to do with JavaScript's +
in operator - if a number and a string are "added" up, the number is converted into a string:
0 + 1; //1
'0' + 1; // '01'
To solve this, use the +
unary operator, or use parseInt()
:
+'0' + 1; // 1
parseInt('0', 10) + 1; // 1
The unary +
operator converts it into a number (however if it's a decimal it will retain the decimal places), and parseInt()
is self-explanatory (converts into number, ignoring decimal places).
The second argument is necessary for parseInt()
to use the correct base when leading 0s are placed:
parseInt('010'); // 8 in older browsers, 10 in newer browsers
parseInt('010', 10); // always 10 no matter what
There's also parseFloat()
if you need to convert decimals in strings to their numeric value - +
can do that too but it behaves slightly differently: that's another story though.
For Visual Studio Code v1.31.1, you can toggle the panel session via the View menu.
Toggle Panel Position
Any class which extends Exception
class will be a user defined Checked exception class where as any class which extends RuntimeException
will be Unchecked exception class.
as mentioned in User defined exception are checked or unchecked exceptions
So, not throwing the checked exception(be it user-defined or built-in exception) gives compile time error.
Checked exception are the exceptions that are checked at compile time.
Unchecked exception are the exceptions that are not checked at compiled time
What you are looking for is this:
SHOW VARIABLES;
You can modify it further like any query:
SHOW VARIABLES LIKE '%max%';
Just remove your "classpath" from you environment variable. Then try running:
java HelloWorld
This should work fine.
In Swift use this,
If you wants to have pull to refresh in WebView,
So try this code:
override func viewDidLoad() {
super.viewDidLoad()
addPullToRefreshToWebView()
}
func addPullToRefreshToWebView(){
var refreshController:UIRefreshControl = UIRefreshControl()
refreshController.bounds = CGRectMake(0, 50, refreshController.bounds.size.width, refreshController.bounds.size.height) // Change position of refresh view
refreshController.addTarget(self, action: Selector("refreshWebView:"), forControlEvents: UIControlEvents.ValueChanged)
refreshController.attributedTitle = NSAttributedString(string: "Pull down to refresh...")
YourWebView.scrollView.addSubview(refreshController)
}
func refreshWebView(refresh:UIRefreshControl){
YourWebView.reload()
refresh.endRefreshing()
}
If you only want to change the route for picture.php
then adding rewrite rule in .htaccess
will serve your needs, but, if you want the URL rewriting as in Wordpress then PHP is the way. Here is simple example to begin with.
Folder structure
There are two files that are needed in the root folder, .htaccess
and index.php
, and it would be good to place the rest of the .php
files in separate folder, like inc/
.
root/
inc/
.htaccess
index.php
.htaccess
RewriteEngine On
RewriteRule ^inc/.*$ index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
This file has four directives:
RewriteEngine
- enable the rewriting engineRewriteRule
- deny access to all files in inc/
folder, redirect any call to that folder to index.php
RewriteCond
- allow direct access to all other files ( like images, css or scripts )RewriteRule
- redirect anything else to index.php
index.php
Because everything is now redirected to index.php, there will be determined if the url is correct, all parameters are present, and if the type of parameters are correct.
To test the url we need to have a set of rules, and the best tool for that is a regular expression. By using regular expressions we will kill two flies with one blow. Url, to pass this test must have all the required parameters that are tested on allowed characters. Here are some examples of rules.
$rules = array(
'picture' => "/picture/(?'text'[^/]+)/(?'id'\d+)", // '/picture/some-text/51'
'album' => "/album/(?'album'[\w\-]+)", // '/album/album-slug'
'category' => "/category/(?'category'[\w\-]+)", // '/category/category-slug'
'page' => "/page/(?'page'about|contact)", // '/page/about', '/page/contact'
'post' => "/(?'post'[\w\-]+)", // '/post-slug'
'home' => "/" // '/'
);
Next is to prepare the request uri.
$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );
Now that we have the request uri, the final step is to test uri on regular expression rules.
foreach ( $rules as $action => $rule ) {
if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
/* now you know the action and parameters so you can
* include appropriate template file ( or proceed in some other way )
*/
}
}
Successful match will, since we use named subpatterns in regex, fill the $params
array almost the same as PHP fills the $_GET
array. However, when using a dynamic url, $_GET
array is populated without any checks of the parameters.
/picture/some+text/51 Array ( [0] => /picture/some text/51 [text] => some text [1] => some text [id] => 51 [2] => 51 ) picture.php?text=some+text&id=51 Array ( [text] => some text [id] => 51 )
These few lines of code and a basic knowing of regular expressions is enough to start building a solid routing system.
Complete source
define( 'INCLUDE_DIR', dirname( __FILE__ ) . '/inc/' );
$rules = array(
'picture' => "/picture/(?'text'[^/]+)/(?'id'\d+)", // '/picture/some-text/51'
'album' => "/album/(?'album'[\w\-]+)", // '/album/album-slug'
'category' => "/category/(?'category'[\w\-]+)", // '/category/category-slug'
'page' => "/page/(?'page'about|contact)", // '/page/about', '/page/contact'
'post' => "/(?'post'[\w\-]+)", // '/post-slug'
'home' => "/" // '/'
);
$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );
foreach ( $rules as $action => $rule ) {
if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
/* now you know the action and parameters so you can
* include appropriate template file ( or proceed in some other way )
*/
include( INCLUDE_DIR . $action . '.php' );
// exit to avoid the 404 message
exit();
}
}
// nothing is found so handle the 404 error
include( INCLUDE_DIR . '404.php' );
If you want to use a js variable in a php script you MUST pass it within a HTTP request.
There are basically two ways:
A basic example can be:
var profile_viewer_uid = 1;
$.ajax({
url: "serverScript.php",
method: "POST",
data: { "profile_viewer_uid": profile_viewer_uid }
})
And in the serverScript.php
file, you can do:
$profile_viewer_uid = $_POST['profile_viewer_uid'];
echo($profile_viewer_uid);
// prints 1
Note: in this example I used jQuery AJAX, which is quicker to implement. You can do it in pure js as well.
G++ does support C++14 both via -std=c++14
and -std=c++1y
. The latter was the common name for the standard before it was known in which year it would be released. In older versions (including yours) only the latter is accepted as the release year wasn't known yet when those versions were released.
I used "sudo apt-get install g++" which should automatically retrieve the latest version, is that correct?
It installs the latest version available in the Ubuntu repositories, not the latest version that exists.
The latest GCC version is 5.2.
Most devices have some form of emulated storage. if they support sd cards they are usually mounted to /sdcard
(or some variation of that name) which is usually symlinked to to a directory in /storage
like /storage/sdcard0
or /storage/0
sometimes the emulated storage is mounted to /sdcard
and the actual path is something like /storage/emulated/legacy. You should be able to use to get the downloads directory. You are best off using the api calls to get directories.
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Since the filesystems and sdcard support varies among devices.
see similar question for more info how to access downloads folder in android?
Usually the DownloadManager handles downloads and the files are then accessed by requesting the file's uri fromthe download manager using a file id to get where file was places which would usually be somewhere in the sdcard/ real or emulated since apps can only read data from certain places on the filesystem outside of their data directory like the sdcard
Using true
/false
as the value will have the field pre-filled if the model passed to the form has this attribute already filled:
= f.radio_button(:public?, true)
= f.label(:public?, "yes", value: true)
= f.radio_button(:public?, false)
= f.label(:public?, "no", value: false)
or this example, just to make it more visible:
public class CustomerListList : List<CustomerList> { }
public class CustomerList : List<Customer> { }
public class Customer
{
public int ID { get; set; }
public string SomethingWithText { get; set; }
}
and you can keep it going. to the infinity and beyond !
Just in case if .dt doesn't work for you. Trying .DatetimeIndex might help. Hope the code and our test result here help you fix it. Regards,
import pandas as pd
import datetime
df = pd.DataFrame({'Date':['2015-01-01','2015-01-02','2015-01-03'],'Number':[1,2,3]})
df['Day'] = pd.DatetimeIndex(df['Date']).day_name() # week day name
df.head()
By catching Throwable
it includes things that subclass Error
. You should generally not do that, except perhaps at the very highest "catch all" level of a thread where you want to log or otherwise handle absolutely everything that can go wrong. It would be more typical in a framework type application (for example an application server or a testing framework) where it can be running unknown code and should not be affected by anything that goes wrong with that code, as much as possible.
I don't believe there's currently any way to do this. The Razor engine does not parse Javascript files, only Razor views. However, you can accomplish what you want by setting the variables inside your Razor view:
<script>
var someStringValue = '@(ViewBag.someStringValue)';
var someNumericValue = @(ViewBag.someNumericValue);
</script>
<!-- "someStringValue" and "someNumericValue" will be available in script -->
<script src="js/myscript.js"></script>
As Joe points out in the comments, the string value above will break if there's a single quote in it. If you want to make this completely iron-clad, you'll have to replace all single quotes with escaped single quotes. The problem there is that all of the sudden slashes become an issue. For example, if your string is "foo \' bar
", and you replace the single quote, what will come out is "foo \\' bar
", and you're right back to the same problem. (This is the age old difficulty of chained encoding.) The best way to handle this is to treat backslashes and quotes as special and make sure they're all escaped:
@{
var safeStringValue = ViewBag.someStringValue
.Replace("\\", "\\\\")
.Replace("'", "\\'");
}
var someStringValue = '@(safeStringValue)';
If you don't want to change anything in your php.ini file, according to PHP documentation, you can do this.
error_log("Error message\n", 3, "/mypath/php.log");
The first parameter is the string to be sent to the log. The second parameter 3
means expect a file destination. The third parameter is the log file path.
While this will render in a web browser, beware that:
??Nesting an html button
in an html a
(or vice-versa) is not valid html ??.
If you want to keep your html semantic to screen readers, use another approach.
Do wrapping in the reverse way and you get the original button with the Link attached. No CSS changes required.
<Link to="/dashboard">
<button type="button">
Click Me!
</button>
</Link>
Here button is HTML button. It is also applicable to the components imported from third party libraries like Semantic-UI-React.
import { Button } from 'semantic-ui-react'
...
<Link to="/dashboard">
<Button style={myStyle}>
<p>Click Me!</p>
</Button>
</Link>
at the first create a kotlin file and add these methods:
fun Activity.getRootView(): View {
return findViewById<View>(android.R.id.content)
}
fun Context.convertDpToPx(dp: Float): Float {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp,
this.resources.displayMetrics
)
}
fun Activity.isKeyboardOpen(): Boolean {
val visibleBounds = Rect()
this.getRootView().getWindowVisibleDisplayFrame(visibleBounds)
val heightDiff = getRootView().height - visibleBounds.height()
val marginOfError = Math.round(this.convertDpToPx(50F))
return heightDiff > marginOfError
}
fun Activity.isKeyboardClosed(): Boolean {
return !this.isKeyboardOpen()
}
then create a listener class for checking the keyboard is open or not :
class KeyboardEventListener(
private val activity: AppCompatActivity,
private val callback: (isOpen: Boolean) -> Unit
) : LifecycleObserver {
private val listener = object : ViewTreeObserver.OnGlobalLayoutListener {
private var lastState: Boolean = activity.isKeyboardOpen()
override fun onGlobalLayout() {
val isOpen = activity.isKeyboardOpen()
if (isOpen == lastState) {
return
} else {
dispatchKeyboardEvent(isOpen)
lastState = isOpen
}
}
}
init {
// Dispatch the current state of the keyboard
dispatchKeyboardEvent(activity.isKeyboardOpen())
// Make the component lifecycle aware
activity.lifecycle.addObserver(this)
registerKeyboardListener()
}
private fun registerKeyboardListener() {
activity.getRootView().viewTreeObserver.addOnGlobalLayoutListener(listener)
}
private fun dispatchKeyboardEvent(isOpen: Boolean) {
when {
isOpen -> callback(true)
!isOpen -> callback(false)
}
}
@OnLifecycleEvent(value = Lifecycle.Event.ON_PAUSE)
@CallSuper
fun onLifecyclePause() {
unregisterKeyboardListener()
}
private fun unregisterKeyboardListener() {
activity.getRootView().viewTreeObserver.removeOnGlobalLayoutListener(listener)
}
}
and use it like this :
override fun onResume() {
super.onResume()
KeyboardEventListener(this) { isOpen -> // handle event }
}
I hope you find it useful.
Faster :
String date = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis( ));
You can take using the following method
mysqldump -d <database name> > <filename.sql> // -d : without data
Hope it will helps you
Other way is using short-circuit:
x = (typeof y !== 'undefined') && y || 1
Although I myself think that ternary is more readable.
Start by registering your custom browser/uploader when you instantiate CKEditor.
<script type="text/javascript">
CKEDITOR.replace('content', {
filebrowserUploadUrl: "Upload File Url",//http://localhost/phpwork/test/ckFileUpload.php
filebrowserWindowWidth : 800,
filebrowserWindowHeight : 500
});
</script>
Code for upload file(ckFileUpload.php) & put the upload file on root dir of your project.
// HERE SET THE PATH TO THE FOLDERS FOR IMAGES AND AUDIO ON YOUR SERVER (RELATIVE TO THE ROOT OF YOUR WEBSITE ON SERVER)
$upload_dir = array(
'img'=> '/phpwork/test/uploads/editor-images/',
'audio'=> '/phpwork/ezcore_v1/uploads/editor-images/'
);
// HERE PERMISSIONS FOR IMAGE
$imgset = array(
'maxsize' => 2000, // maximum file size, in KiloBytes (2 MB)
'maxwidth' => 900, // maximum allowed width, in pixels
'maxheight' => 800, // maximum allowed height, in pixels
'minwidth' => 10, // minimum allowed width, in pixels
'minheight' => 10, // minimum allowed height, in pixels
'type' => array('bmp', 'gif', 'jpg', 'jpeg', 'png'), // allowed extensions
);
// HERE PERMISSIONS FOR AUDIO
$audioset = array(
'maxsize' => 20000, // maximum file size, in KiloBytes (20 MB)
'type' => array('mp3', 'ogg', 'wav'), // allowed extensions
);
// If 1 and filename exists, RENAME file, adding "_NR" to the end of filename (name_1.ext, name_2.ext, ..)
// If 0, will OVERWRITE the existing file
define('RENAME_F', 1);
$re = '';
if(isset($_FILES['upload']) && strlen($_FILES['upload']['name']) >1) {
define('F_NAME', preg_replace('/\.(.+?)$/i', '', basename($_FILES['upload']['name']))); //get filename without extension
// get protocol and host name to send the absolute image path to CKEditor
$protocol = !empty($_SERVER['HTTPS']) ? 'https://' : 'http://';
$site = $protocol. $_SERVER['SERVER_NAME'] .'/';
$sepext = explode('.', strtolower($_FILES['upload']['name']));
$type = end($sepext); // gets extension
$upload_dir = in_array($type, $imgset['type']) ? $upload_dir['img'] : $upload_dir['audio'];
$upload_dir = trim($upload_dir, '/') .'/';
//checkings for image or audio
if(in_array($type, $imgset['type'])){
list($width, $height) = getimagesize($_FILES['upload']['tmp_name']); // image width and height
if(isset($width) && isset($height)) {
if($width > $imgset['maxwidth'] || $height > $imgset['maxheight']) $re .= '\\n Width x Height = '. $width .' x '. $height .' \\n The maximum Width x Height must be: '. $imgset['maxwidth']. ' x '. $imgset['maxheight'];
if($width < $imgset['minwidth'] || $height < $imgset['minheight']) $re .= '\\n Width x Height = '. $width .' x '. $height .'\\n The minimum Width x Height must be: '. $imgset['minwidth']. ' x '. $imgset['minheight'];
if($_FILES['upload']['size'] > $imgset['maxsize']*1000) $re .= '\\n Maximum file size must be: '. $imgset['maxsize']. ' KB.';
}
}
else if(in_array($type, $audioset['type'])){
if($_FILES['upload']['size'] > $audioset['maxsize']*1000) $re .= '\\n Maximum file size must be: '. $audioset['maxsize']. ' KB.';
}
else $re .= 'The file: '. $_FILES['upload']['name']. ' has not the allowed extension type.';
//set filename; if file exists, and RENAME_F is 1, set "img_name_I"
// $p = dir-path, $fn=filename to check, $ex=extension $i=index to rename
function setFName($p, $fn, $ex, $i){
if(RENAME_F ==1 && file_exists($p .$fn .$ex)) return setFName($p, F_NAME .'_'. ($i +1), $ex, ($i +1));
else return $fn .$ex;
}
$f_name = setFName($_SERVER['DOCUMENT_ROOT'] .'/'. $upload_dir, F_NAME, ".$type", 0);
$uploadpath = $_SERVER['DOCUMENT_ROOT'] .'/'. $upload_dir . $f_name; // full file path
// If no errors, upload the image, else, output the errors
if($re == '') {
if(move_uploaded_file($_FILES['upload']['tmp_name'], $uploadpath)) {
$CKEditorFuncNum = $_GET['CKEditorFuncNum'];
$url = $site. $upload_dir . $f_name;
$msg = F_NAME .'.'. $type .' successfully uploaded: \\n- Size: '. number_format($_FILES['upload']['size']/1024, 2, '.', '') .' KB';
$re = in_array($type, $imgset['type']) ? "window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')" //for img
: 'var cke_ob = window.parent.CKEDITOR; for(var ckid in cke_ob.instances) { if(cke_ob.instances[ckid].focusManager.hasFocus) break;} cke_ob.instances[ckid].insertHtml(\'<audio src="'. $url .'" controls></audio>\', \'unfiltered_html\'); alert("'. $msg .'"); var dialog = cke_ob.dialog.getCurrent(); dialog.hide();';
}
else $re = 'alert("Unable to upload the file")';
}
else $re = 'alert("'. $re .'")';
}
@header('Content-type: text/html; charset=utf-8');
echo '<script>'. $re .';</script>';
Ck-editor documentation is not clear after doing alot of R&D for custom file upload finally i have found this solution. It work for me and i hope it will helpful to others as well.
This is how I made it without extra css or jquery:
<div class="form-group">
<div class="input-group">
<label class="sr-only" for="extra3">Extra name 3</label>
<input type="text" id="extra3" class="form-control" placeholder="Extra name">
<span class="input-group-addon">
<label class="checkbox-inline">
Mandatory? <input type="checkbox" id="inlineCheckbox5" value="option1">
</label>
</span>
<span class="input-group-addon">
<label class="checkbox-inline">
Per person? <input type="checkbox" id="inlineCheckbox6" value="option2">
</label>
</span>
<span class="input-group-addon">
To be paid?
<select>
<option value="online">Online</option>
<option value="on spot">On Spot</option>
</select>
</span>
</div>
</div>
If you're using executeScalar:
cmd.ExecuteScalar();
result_id=cmd.LastInsertedId.ToString();
Well, to use it i dont think matters (similar to disabled and readonly), personally i use checked="checked" but if you are trying to manipulate them with JavaScript, you use true/false
You can do
int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(o -> o.getField()).sum();
or (using Method reference)
int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(Obj::getField).sum();
You can specify multiple patterns in an array.
select-string VendorEnquiry,Failed C:\Logs
This works with -notmatch as well:
select-string -notmatch VendorEnquiry,Failed C:\Logs
Whenever I have a task like this I end up falling back to
$ man strftime
to remind myself of all the possibilities for time formatting options.
The API appears to have changed (or at least, it doesn't work for me).
Running the following in the Package Manager Console works as expected:
Update-Database -Script -SourceMigration:0
for me this error was actually caused by a field falsely declared as public instead of private.
public static void printPyramid(int number) {
int size = 5;
for (int k = 1; k <= size; k++) {
for (int i = (size+2); i > k; i--) {
System.out.print(" ");
}
for (int j = 1; j <= k; j++) {
System.out.print(" *");
}
System.out.println();
}
}
First of all you cannot change the memory settings only for a tomcat application but rather for all tomcat instance.
If you are running tomcat from console (using startup.bat) you'll need to edit catalina.bat and play around with CATALINA_OPTS. For example:
set CATALINA_OPTS=-Xms512m -Xmx512m
Restarting tomcat will apply the new settings.
If you are still getting OutOfMemoryError you need to know how much memory does your application need at that particular moment (nom.tam.util.ArrayFuncs...). You'll either have to optimize the application or simply increase the memory provided to tomcat.
Calling /search/
should result in "you submitted nothing", but calling /search/?q=
on the other hand should result in "you submitted u''"
Browsers have to add the q=
even when it's empty, because they have to include all fields which are part of the form. Only if you do some DOM manipulation in Javascript (or a custom javascript submit action), you might get such a behavior, but only if the user has javascript enabled. So you should probably simply test for non-empty strings, e.g:
if request.GET.get('q'):
message = 'You submitted: %r' % request.GET['q']
else:
message = 'You submitted nothing!'
Unfortunately DEBUG
is overloaded heavily. For instance, it's recommended to always generate and save a pdb file for RELEASE builds. Which means one of the -Zx
flags, and -DEBUG
linker option. While _DEBUG
relates to special debug versions of runtime library such as calls to malloc
and free
. Then NDEBUG
will disable assertions.
Is this what you're looking for?
#include <chrono>
#include <iostream>
int main()
{
typedef std::chrono::high_resolution_clock Time;
typedef std::chrono::milliseconds ms;
typedef std::chrono::duration<float> fsec;
auto t0 = Time::now();
auto t1 = Time::now();
fsec fs = t1 - t0;
ms d = std::chrono::duration_cast<ms>(fs);
std::cout << fs.count() << "s\n";
std::cout << d.count() << "ms\n";
}
which for me prints out:
6.5e-08s
0ms
var values = [];
var count = 0;
$("#tblName").on("click", "tbody tr", function (event) {
$(this).find("td").each(function () {
values[count] = $(this).text();
count++;
});
});
Now values array contain all the cell values of that row can be used like values[0] first cell value of clicked row
You need
str.CopyTo(data);
data.Position = 0; // reset to beginning
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);
And since your Test()
method is imitating the client it ought to Close()
or Dispose()
the str
Stream. And the memoryStream too, just out of principal.
Probably because you forgot to implement the solution in the accepted answer. That's the code that makes trim()
work.
update
This answer only applies to older browsers. Newer browsers apparently support trim()
natively.
You must use a .ts
file - e.g. test.ts
to get Typescript validation, intellisense typing
of vars, return types, as well as "typed" error checking (e.g. passing a string
to a method that expects an number
param will error out).
It will be transpiled into (standard) .js
via tsc
.
Clarification needed based on down-votes, very helpful comments and other answers.
types
Yes, you can do type
checking in VS Code in .js
files with @ts-check
- as shown in the animation
What I originally was referring to for Typescript types
is something like this in .ts
which isn't quite the same thing:
hello-world.ts
function hello(str: string): string {
return 1;
}
function foo(str:string):void{
console.log(str);
}
This will not compile. Error: Type "1" is not assignable to String
if you tried this syntax in a Javascript hello-world.js
file:
//@ts-check
function hello(str: string): string {
return 1;
}
function foo(str:string):void{
console.log(str);
}
The error message referenced by OP is shown: [js] 'types' can only be used in a .ts file
If there's something I missed that covers this as well as the OP's context, please add. Let's all learn.
Several answers are here but nobody has posted usefull code.
Here is my code that detects all encodings that Microsoft detects in Framework 4 in the StreamReader class.
Obviously you must call this function immediately after opening the stream before reading anything else from the stream because the BOM are the first bytes in the stream.
This function requires a Stream that can seek (for example a FileStream). If you have a Stream that cannot seek you must write a more complicated code that returns a Byte buffer with the bytes that have already been read but that are not BOM.
/// <summary>
/// UTF8 : EF BB BF
/// UTF16 BE: FE FF
/// UTF16 LE: FF FE
/// UTF32 BE: 00 00 FE FF
/// UTF32 LE: FF FE 00 00
/// </summary>
public static Encoding DetectEncoding(Stream i_Stream)
{
if (!i_Stream.CanSeek || !i_Stream.CanRead)
throw new Exception("DetectEncoding() requires a seekable and readable Stream");
// Try to read 4 bytes. If the stream is shorter, less bytes will be read.
Byte[] u8_Buf = new Byte[4];
int s32_Count = i_Stream.Read(u8_Buf, 0, 4);
if (s32_Count >= 2)
{
if (u8_Buf[0] == 0xFE && u8_Buf[1] == 0xFF)
{
i_Stream.Position = 2;
return new UnicodeEncoding(true, true);
}
if (u8_Buf[0] == 0xFF && u8_Buf[1] == 0xFE)
{
if (s32_Count >= 4 && u8_Buf[2] == 0 && u8_Buf[3] == 0)
{
i_Stream.Position = 4;
return new UTF32Encoding(false, true);
}
else
{
i_Stream.Position = 2;
return new UnicodeEncoding(false, true);
}
}
if (s32_Count >= 3 && u8_Buf[0] == 0xEF && u8_Buf[1] == 0xBB && u8_Buf[2] == 0xBF)
{
i_Stream.Position = 3;
return Encoding.UTF8;
}
if (s32_Count >= 4 && u8_Buf[0] == 0 && u8_Buf[1] == 0 && u8_Buf[2] == 0xFE && u8_Buf[3] == 0xFF)
{
i_Stream.Position = 4;
return new UTF32Encoding(true, true);
}
}
i_Stream.Position = 0;
return Encoding.Default;
}
My solution to this is pretty unbelievable.
<script type="text/javascript" src="/js/dataLayer.js?v=1"></script>
The filename in the src attribute needed to be lowercase:
<script type="text/javascript" src="/js/datalayer.js?v=1"></script>
and that somewhat inexplicably fixed the problem.
In both cases the reference was returning 404 for testing.
You need to change from queue import Queue
to from multiprocessing import Queue
.
The root reason is the former Queue is designed for threading module Queue while the latter is for multiprocessing.Process module.
For details, you can read some source code or contact me!
In fact the "[" square opening bracket is just an internal shell alias for the test command.
So you can say:
test -f "/bin/bash" && echo "This system has a bash shell"
or
[ -f "/bin/bash" ] && echo "This system has a bash shell"
... they are equivalent in either sh or bash. Note the requirement to have a closing "]" bracket on the "[" command but other than that "[" is the same as "test". "man test" is a good thing to read.
Have you tried url-encoding the data ? cURL can take care of that for you :
curl -H "Content-type: text/xml" --data-urlencode "<XmlContainer xmlns='sads'..." http://myapiurl.com/service.svc/
This is my way to do that:
int digitcount(int n)
{
int count = 1;
int temp = n;
while (true)
{
temp /= 10;
if (temp != 0) ++count;
if (temp == 0) break;
}
return count;
}
if you want to pull from a specific branch all you have to do is
git pull 'remote_name' 'branch_name'
NOTE: Make sure you commit your code first.
After trying the options described here, I found this post from Forester in r-bloggers . I think it is a clean option to consider.
I put his code here:
From command line
$ R CMD BATCH --no-save --no-restore '--args a=1 b=c(2,5,6)' test.R test.out &
Test.R
##First read in the arguments listed at the command line
args=(commandArgs(TRUE))
##args is now a list of character vectors
## First check to see if arguments are passed.
## Then cycle through each element of the list and evaluate the expressions.
if(length(args)==0){
print("No arguments supplied.")
##supply default values
a = 1
b = c(1,1,1)
}else{
for(i in 1:length(args)){
eval(parse(text=args[[i]]))
}
}
print(a*2)
print(b*3)
In test.out
> print(a*2)
[1] 2
> print(b*3)
[1] 6 15 18
Thanks to Forester!
one obvious solution is to run 2 separate queries, first select all items that have count=1 and run your insert, then select the items with count>1 and run the second insert.
as a second step if the two inserts are similar you can probably combine them into one query.
another possibility is to use a cursor to loop thru your recordset and do whatever logic you need for each line.
I have recently evaluated and picked a persistence framework for a java project and my findings are as follows:
What I am seeing is that the support in favour of JDO is primarily:
and the support in favour of JPA is primarily:
I am seeing a lot of pro-JPA posts from JPA developers who have clearly not used JDO/Datanucleus offering weak arguments for not using JDO.
I am also seeing a lot of posts from JDO users who have migrated to JDO and are much happier as a result.
In respect of JPA being more popular, it seems that this is due in part due to RDBMS vendor support rather than it being technically superior. (Sounds like VHS/Betamax to me).
JDO and it's reference implementation Datanucleus is clearly not dead, as shown by Google's adoption of it for GAE and active development on the source-code (http://sourceforge.net/projects/datanucleus/).
I have seen a number of complaints about JDO due to bytecode enhancement, but no explanation yet for why it is bad.
In fact, in a world that is becoming more and more obsessed by NoSQL solutions, JDO (and the datanucleus implementation) seems a much safer bet.
I have just started using JDO/Datanucleus and have it set up so that I can switch easily between using db4o and mysql. It's helpful for rapid development to use db4o and not have to worry too much about the DB schema and then, once the schema is stabilised to deploy to a database. I also feel confident that later on, I could deploy all/part of my application to GAE or take advantage of distributed storage/map-reduce a la hbase /hadoop / cassandra without too much refactoring.
I found the initial hurdle of getting started with Datanucleus a little tricky - The documentation on the datanucleus website is a little hard to get into - the tutorials are not as easily to follow as I would have liked. Having said that, the more detailed documentation on the API and mapping is very good once you get past the initial learning curve.
The answer is, it depends what you want. I would rather have cleaner code, no-vendor-lock-in, more pojo-orientated, nosql options verses more-popular.
If you want the warm fussy feeling that you are doing the same as the majority of other developers/sheep, choose JPA/hibernate. If you want to lead in your field, test drive JDO/Datanucleus and make your own mind up.
This can be done in a more portable way:
$ nproc --all
32
Compatible with macOS and Linux.
Failure [INSTALL_FAILED_USER_RESTRICTED: Install canceled by user]:
Go to Settings->Additional Settings->Developer options->Developer Option(Need to enable)->USB debugging(Need to enable)->Install via USB (Need to enable)->USB debugging (Security settings)(Need to enable)
Perfectly working in the above steps.
Enjoy your coding...
You can create an alias in .bashrc file as follows
alias vg='valgrind --leak-check=full -v --track-origins=yes --log-file=vg_logfile.out'
So whenever you want to check memory leaks, just do simply
vg ./<name of your executable> <command line parameters to your executable>
This will generate a Valgrind log file in the current directory.
Both or
and ||
evaluate to true if either operand is true. They evaluate their second operand only if the first is false.
As with and
, the only difference between or
and ||
is their precedence.
Just to make life interesting, and
and or
have the same precedence, while &&
has a higher precedence than ||
.
There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here. Here is an example for gcc:
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
//define something for Windows (32-bit and 64-bit, this part is common)
#ifdef _WIN64
//define something for Windows (64-bit only)
#else
//define something for Windows (32-bit only)
#endif
#elif __APPLE__
#include <TargetConditionals.h>
#if TARGET_IPHONE_SIMULATOR
// iOS Simulator
#elif TARGET_OS_IPHONE
// iOS device
#elif TARGET_OS_MAC
// Other kinds of Mac OS
#else
# error "Unknown Apple platform"
#endif
#elif __linux__
// linux
#elif __unix__ // all unices not caught above
// Unix
#elif defined(_POSIX_VERSION)
// POSIX
#else
# error "Unknown compiler"
#endif
The defined macros depend on the compiler that you are going to use.
The _WIN64
#ifdef
can be nested into the _WIN32
#ifdef
because _WIN32
is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both
(also WIN32
without underscore allows IDE to highlight the right partition of code).
Maybe you find this simpler
select * from (
select ssn, sum(time) from downloads
group by ssn
order by sum(time) desc
) where rownum <= 10 --top 10 downloaders
Regards
K
Got the same issue, turned out that the private key to the certificate had no permission.
To fix - open the certifacte management, find your certificate, right click -> Manage Private Keys and then in security on top be sure that your user is added and given permissions, that fixed it for me.
I would guess your query isn't running as expected and you are getting to the return line with undefined variables.
Also, the way you are doing the variable assignment, you would be overwriting the same variable with each loop iteration, so you wouldn't return the entire result set.
Finally, it seems odd to return a numerically-keyed result set instead of an associatively-keyed one. Consider naming only the fields needed in the SELECT and keeping the key assignments. So something like this:
Function ShowDataPatient($idURL){
$query =" select * from cmu_list_insurance,cmu_home,cmu_patient where cmu_home.home_id = (select home_id from cmu_patient where patient_hn like '%$idURL%')
AND cmu_patient.patient_hn like '%$idURL%'
AND cmu_list_insurance.patient_id like (select patient_id from cmu_patient where patient_hn like '%$idURL%') ";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
$return = array();
while ($row = pg_fetch_array($result)){
$return[] = $row;
}
return $return;
}
You might also consider opening a question about how to improve your query, is it is pretty heinous as it stands now.
iloc
df1 = datasX.iloc[:, :72]
df2 = datasX.iloc[:, 72:]
Use this line of codes inside the Column.
For wrap_content : mainAxisSize: MainAxisSize.min
For match_parent : mainAxisSize: MainAxisSize.max
You can use the following code:
var d1 = Dictionary<Int, Int>()
var d2 = [Int: Int]()
var d3: Dictionary<Int, Int> = [Int : Int]()
var d4: [Int : Int] = [:]
I think by using the content"."; The dot becomes too squared if made too big, thus I believe that this is a better solution, here you can decide the size of the "disc" without affecting the font size.
li {_x000D_
list-style: none;_x000D_
display: list-item;_x000D_
margin-left: 50px;_x000D_
}_x000D_
_x000D_
li:before {_x000D_
content: "";_x000D_
border: 5px #000 solid !important;_x000D_
border-radius: 50px;_x000D_
margin-top: 5px;_x000D_
margin-left: -20px;_x000D_
position: absolute;_x000D_
}
_x000D_
<h2>Look at these examples!</h2>_x000D_
<li>This is an example</li>_x000D_
<li>This is another example</li>
_x000D_
You edit the size of the disk by editing the size of the border px. and you can adjust the distance to the text by how much - margin left you give it. As well as adjust the y position by editing the margin top.
Depending on your needs, an approximation like:
[0-9a-f:]+
may be enough (as with simple log file grepping, for example.)
I faced the same issue recently and I created a small github project that contains a new mysql function UNIX_TIMESTAMP_MS()
that returns the current timestamp in milliseconds.
Also you can do the following :
SELECT UNIX_TIMESTAMP_MS(NOW(3))
or SELECT UNIX_TIMESTAMP_MS(DateTimeField)
The project is located here : https://github.com/silviucpp/unix_timestamp_ms
To compile you need to Just run make compile
in the project root.
Then you need to only copy the shared library in the /usr/lib/mysql/plugin/
(or whatever the plugin folder is on your machine.)
After this just open a mysql console and run :
CREATE FUNCTION UNIX_TIMESTAMP_MS RETURNS INT SONAME 'unix_timestamp_ms.so';
I hope this will help, Silviu
Just simply add or die(mysqli_error($db));
at the end of your query, this will print the mysqli error.
mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));
As a side note I'd say you are at risk of mysql injection
, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.
You need a table variable:
declare @values table
(
Value varchar(1000)
)
insert into @values values ('A')
insert into @values values ('B')
insert into @values values ('C')
select blah
from foo
where myField in (select value from @values)
You haven't mentioned the DBMS. Assuming you are using MS SQL-Server, I've found a T-SQL Error message that is self-explanatory:
"An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference"
http://www.sql-server-performance.com/
And an example that it is possible in a subquery.
Show all customers and smallest order for those who have 5 or more orders (and NULL for others):
SELECT a.lastname
, a.firstname
, ( SELECT MIN( o.amount )
FROM orders o
WHERE a.customerid = o.customerid
AND COUNT( a.customerid ) >= 5
)
AS smallestOrderAmount
FROM account a
GROUP BY a.customerid
, a.lastname
, a.firstname ;
UPDATE.
The above runs in both SQL-Server and MySQL but it doesn't return the result I expected. The next one is more close. I guess it has to do with that the field customerid
, GROUPed BY and used in the query-subquery join is in the first case PRIMARY KEY of the outer table and in the second case it's not.
Show all customer ids and number of orders for those who have 5 or more orders (and NULL for others):
SELECT o.customerid
, ( SELECT COUNT( o.customerid )
FROM account a
WHERE a.customerid = o.customerid
AND COUNT( o.customerid ) >= 5
)
AS cnt
FROM orders o
GROUP BY o.customerid ;
A third option, for a pipelined one-liner is to nest the -replaces:
PS> ("ABC" -replace "B","C") -replace "C","D"
ADD
And:
PS> ("ABC" -replace "C","D") -replace "B","C"
ACD
This preserves execution order, is easy to read, and fits neatly into a pipeline. I prefer to use parentheses for explicit control, self-documentation, etc. It works without them, but how far do you trust that?
-Replace is a Comparison Operator, which accepts an object and returns a presumably modified object. This is why you can stack or nest them as shown above.
Please see:
help about_operators
Upcasting is casting to a supertype, while downcasting is casting to a subtype. Upcasting is always allowed, but downcasting involves a type check and can throw a ClassCastException
.
In your case, a cast from a Dog
to an Animal
is an upcast, because a Dog
is-a Animal
. In general, you can upcast whenever there is an is-a relationship between two classes.
Downcasting would be something like this:
Animal animal = new Dog();
Dog castedDog = (Dog) animal;
Basically what you're doing is telling the compiler that you know what the runtime type of the object really is. The compiler will allow the conversion, but will still insert a runtime sanity check to make sure that the conversion makes sense. In this case, the cast is possible because at runtime animal
is actually a Dog
even though the static type of animal
is Animal
.
However, if you were to do this:
Animal animal = new Animal();
Dog notADog = (Dog) animal;
You'd get a ClassCastException
. The reason why is because animal
's runtime type is Animal
, and so when you tell the runtime to perform the cast it sees that animal
isn't really a Dog
and so throws a ClassCastException
.
To call a superclass's method you can do super.method()
or by performing the upcast.
To call a subclass's method you have to do a downcast. As shown above, you normally risk a ClassCastException
by doing this; however, you can use the instanceof
operator to check the runtime type of the object before performing the cast, which allows you to prevent ClassCastException
s:
Animal animal = getAnimal(); // Maybe a Dog? Maybe a Cat? Maybe an Animal?
if (animal instanceof Dog) {
// Guaranteed to succeed, barring classloader shenanigans
Dog castedDog = (Dog) animal;
}
Another oneliner using basic command line functions handling multiple occurences per line.
cat * |sed s/string/\\\nstring\ /g |grep string |wc -l
Set also android:gravity
parameter in TextView
to center
.
For testing the effects of different layout parameters I recommend to use different background color for every element, so you can see how your layout changes with parameters like gravity, layout_gravity or others.
If you work in MS Visual Studio just do following
Correct WSDL file like this YourSchemeFile.xsd
Use visual Studio using this great example How to generate service reference with only physical wsdl file
Notice that you have to put the path to your WSDL file manually. There is no way to use Open File dialog box out there.
Html.DisplayFor()
will render the DisplayTemplate that matches the property's type.
If it can't find any, I suppose it invokes .ToString()
.
If you don't know about display templates, they're partial views that can be put in a DisplayTemplates
folder inside the view folder associated to a controller.
Example:
If you create a view named String.cshtml
inside the DisplayTemplates
folder of your views folder (e.g Home
, or Shared
) with the following code:
@model string
@if (string.IsNullOrEmpty(Model)) {
<strong>Null string</strong>
}
else {
@Model
}
Then @Html.DisplayFor(model => model.Title)
(assuming that Title
is a string) will use the template and display <strong>Null string</strong>
if the string is null, or empty.
for nested arrays you can use:
$data = [
'name[0]' = 'value 1',
'name[1]' = 'value 2',
'name[2]' = 'value 3',
'id' = 'value 4',
....
];
The following MySQL statement should modify your column to accept NULLs.
ALTER TABLE `MyTable`
ALTER COLUMN `Col3` varchar(20) DEFAULT NULL
You probably want git checkout master
, or git checkout [branchname]
.
document.getElementById("theForm").submit();
It works perfect in my case.
you can use it in function also like,
function submitForm()
{
document.getElementById("theForm").submit();
}
Set "theForm" as your form ID. It's done.
Just in case, anyone's visiting this question in 2017 or later and looking for an easy-to-remember way, here's an elaborate blog post on Accessing Nested Objects in JavaScript without being bamboozled by
Cannot read property 'foo' of undefined error
Let's take this example structure
const user = {
id: 101,
email: '[email protected]',
personalInfo: {
name: 'Jack',
address: [{
line1: 'westwish st',
line2: 'washmasher',
city: 'wallas',
state: 'WX'
}]
}
}
To be able to access nested arrays, you can write your own array reduce util.
const getNestedObject = (nestedObj, pathArr) => {
return pathArr.reduce((obj, key) =>
(obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
}
// pass in your object structure as array elements
const name = getNestedObject(user, ['personalInfo', 'name']);
// to access nested array, just pass in array index as an element the path array.
const city = getNestedObject(user, ['personalInfo', 'address', 0, 'city']);
// this will return the city from the first address item.
There is also an excellent type handling minimal library typy that does all this for you.
With typy, your code will look like this
const city = t(user, 'personalInfo.address[0].city').safeObject;
Disclaimer: I am the author of this package.
Seems like var ctx = $('#myChart');
is returning a list of elements. You would need to reference the first by using ctx[0]
.
Also height is a property, not a function.
I did it this way in my code:
var ctx = document.getElementById("myChart");
ctx.height = 500;
One way to solve this problem, specialization of member functions is to put the specialization into another class, then inherit from that class. You may have to change the order of inheritence to get access to all of the other underlying data but this technique does work.
template< class T, bool condition> struct FooImpl;
template<class T> struct FooImpl<T, true> {
T foo() { return 10; }
};
template<class T> struct FoolImpl<T,false> {
T foo() { return 5; }
};
template< class T >
class Y : public FooImpl<T, boost::is_integer<T> > // whatever your test is goes here.
{
public:
typedef FooImpl<T, boost::is_integer<T> > inherited;
// you will need to use "inherited::" if you want to name any of the
// members of those inherited classes.
};
The disadvantage of this technique is that if you need to test a lot of different things for different member functions you'll have to make a class for each one, and chain it in the inheritence tree. This is true for accessing common data members.
Ex:
template<class T, bool condition> class Goo;
// repeat pattern above.
template<class T, bool condition>
class Foo<T, true> : public Goo<T, boost::test<T> > {
public:
typedef Goo<T, boost::test<T> > inherited:
// etc. etc.
};
Place your scripts in this order:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
If you're just after console logging here's what I'd do:
export default class App extends Component {
componentDidMount() {
console.log('I was triggered during componentDidMount')
}
render() {
console.log('I was triggered during render')
return (
<div> I am the App component </div>
)
}
}
Shouldn't be any need for those packages just to do console logging.
I would add an android:onClick
to the layout and then change the layout in the activity.
So in the layout
<ImageView
(Other things like source etc.)
android:onClick="changelayout"
/>
Then in the activity add the following:
public void changelayout(View view){
setContentView(R.layout.second_layout);
}
When using SASS
I use the following 2 @media queries
to target IE 6-10 & EDGE.
@media screen\9
@import ie_styles
@media screen\0
@import ie_styles
http://keithclark.co.uk/articles/moving-ie-specific-css-into-media-blocks/
Edit
I also target later versions of EDGE using @support queries
(add as many as you need)
@supports (-ms-ime-align:auto)
@import ie_styles
@supports (-ms-accelerator:auto)
@import ie_styles
https://jeffclayton.wordpress.com/2015/04/07/css-hacks-for-windows-10-and-spartan-browser-preview/
Dirk has explained how to plot the density function over the histogram. But sometimes you might want to go with the stronger assumption of a skewed normal distribution and plot that instead of density. You can estimate the parameters of the distribution and plot it using the sn package:
> sn.mle(y=c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
$call
sn.mle(y = c(rep(65, times = 5), rep(25, times = 5), rep(35,
times = 10), rep(45, times = 4)))
$cp
mean s.d. skewness
41.46228 12.47892 0.99527
This probably works better on data that is more skew-normal:
Forward Slash is special character so,you have to add a backslash before forward slash to make it work
$patterm = "/[0-9]{2}+(?:-|.|\/)+[a-zA-Z]{3}+(?:-|.|\/)+[0-9]{4}/";
where / represents search for / In this way you
I stumbled over this as chocolatey sets M2_HOME
. I wanted to locate settings.xml
.
The current way for settings.xml
is to go to %USERPROFILE%
. There, a directory .m2
is contained, where one finds settings.xml
.
Never use M2_HOME
. It is unsupported since Apache Maven 3.5.0.
Details:
Based on problems in using
M2_HOME
related to different Maven versions installed and to simplify things, the usage ofM2_HOME
has been removed and is not supported any more MNG-5823, MNG-5836, MNG-5607.Important change for windows users: The usage of
%HOME%
has been replaced with%USERPROFILE%
MNG-6001
Source: https://maven.apache.org/docs/3.5.0/release-notes.html#overview-about-the-changes
The spelling?
Seriously though - they're both BS job title fluffing. "Programmer" not good enough for you? Become an "Architect"!
Really... What is the world coming to?!
Edit: I clearly hurt some "architects'" feelings!
Edit 2: Though I agree with the sentiments that the phrasing can be interpreted to mean some people deal with the whole problem domain (eg hardware, software, deployment, maintaining), most people who want to satisfy a client (and make more money) will provide a full service, if required, regardless of their title.
In real life, it's just marketing fluff.
kind of an old thread, but.. i do this:
$file = 'http://www.google.com';
$file_headers = @get_headers($file);
if ($file_headers) {
$exists = true;
} else {
$exists = false;
}
I made adb working on Android 4.4.2 with GT-N8010 (Samsung tablet) after setting device in authorized mode once upgraded adb to SDK version.
~/local/opt/Android/Sdk/platform-tools/adb
Android Debug Bridge version 1.0.32
While It did not work using :
adb version
Android Debug Bridge version 1.0.31
Shiped in Ubuntu LTS version :
apt-cache show android-tools-adb | grep Version
Version: 4.2.2+git20130218-3ubuntu23
This link may help then
You can use addBatch and executeBatch for batch insert in java See the Example : Batch Insert In Java
[Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:
extension=php_ldap.dll
Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin Restart Apache. You can now use functions of the LDAP Module!
Check out the instanceof operator.
var isJqueryObject = obj instanceof jQuery
Like the other posters have suggested, it sounds like you have a lock contention issue. We faced a similar issue a few weeks back; however, ours was much more intermittent, and often cleared up before we could get a DBA onto the server to run sp_who2 to trace down the issue.
What we ended up doing was implement an e-mail notification if a lock exceeded a certain threshold. Once we put this in place, we were able to identify the processes that were locking, and change the isolation level to read uncommitted where appropriate to fix the issue.
Here's an article that provides an overview of how to configure this type of notification.
If locking turns out to be the issue, and if you're not already doing so, I would suggest looking into configuring row versioning-based isolation levels.
Following steps helped me solve the issue.
i.ToString("0000");
Developing from Hugues BR answer but using method swizzling I've arrived to a solution that is successfully changing all the fonts to a desired font in my app.
An approach with Dynamic Type should be what you should look for on iOS 7. The following solution is not using Dynamic Type.
Notes:
- initWithCoder:
override. However that won't cover all the cases;This solution uses two different methods to achieve the final result. The first is override the UIFont class methods + systemFontWithSize:
and similar with ones that use my alternatives (here I use "Zapfino" to leave no doubts that the replacement was successful).
The other method is to override - initWithCoder:
method on UIFont to replace any occurrence of CTFontRegularUsage
and similar by my alternatives.
This last method was necessary because I've found that UILabel
objects encoded in NIB files don't check the + systemFontWithSize:
methods to get their system font and instead encode them as UICTFontDescriptor
objects.
I've tried to override - awakeAfterUsingCoder:
but somehow it was getting called for every encoded object in my storyboard and causing crashes. Overriding - awakeFromNib
wouldn't allow me to read the NSCoder
object.
#import <objc/runtime.h>
NSString *const FORegularFontName = @"Zapfino";
NSString *const FOBoldFontName = @"Zapfino";
NSString *const FOItalicFontName = @"Zapfino";
#pragma mark - UIFont category
@implementation UIFont (CustomFonts)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
+ (void)replaceClassSelector:(SEL)originalSelector withSelector:(SEL)modifiedSelector {
Method originalMethod = class_getClassMethod(self, originalSelector);
Method modifiedMethod = class_getClassMethod(self, modifiedSelector);
method_exchangeImplementations(originalMethod, modifiedMethod);
}
+ (void)replaceInstanceSelector:(SEL)originalSelector withSelector:(SEL)modifiedSelector {
Method originalDecoderMethod = class_getInstanceMethod(self, originalSelector);
Method modifiedDecoderMethod = class_getInstanceMethod(self, modifiedSelector);
method_exchangeImplementations(originalDecoderMethod, modifiedDecoderMethod);
}
+ (UIFont *)regularFontWithSize:(CGFloat)size
{
return [UIFont fontWithName:FORegularFontName size:size];
}
+ (UIFont *)boldFontWithSize:(CGFloat)size
{
return [UIFont fontWithName:FOBoldFontName size:size];
}
+ (UIFont *)italicFontOfSize:(CGFloat)fontSize
{
return [UIFont fontWithName:FOItalicFontName size:fontSize];
}
- (id)initCustomWithCoder:(NSCoder *)aDecoder {
BOOL result = [aDecoder containsValueForKey:@"UIFontDescriptor"];
if (result) {
UIFontDescriptor *descriptor = [aDecoder decodeObjectForKey:@"UIFontDescriptor"];
NSString *fontName;
if ([descriptor.fontAttributes[@"NSCTFontUIUsageAttribute"] isEqualToString:@"CTFontRegularUsage"]) {
fontName = FORegularFontName;
}
else if ([descriptor.fontAttributes[@"NSCTFontUIUsageAttribute"] isEqualToString:@"CTFontEmphasizedUsage"]) {
fontName = FOBoldFontName;
}
else if ([descriptor.fontAttributes[@"NSCTFontUIUsageAttribute"] isEqualToString:@"CTFontObliqueUsage"]) {
fontName = FOItalicFontName;
}
else {
fontName = descriptor.fontAttributes[@"NSFontNameAttribute"];
}
return [UIFont fontWithName:fontName size:descriptor.pointSize];
}
self = [self initCustomWithCoder:aDecoder];
return self;
}
+ (void)load
{
[self replaceClassSelector:@selector(systemFontOfSize:) withSelector:@selector(regularFontWithSize:)];
[self replaceClassSelector:@selector(boldSystemFontOfSize:) withSelector:@selector(boldFontWithSize:)];
[self replaceClassSelector:@selector(italicSystemFontOfSize:) withSelector:@selector(italicFontOfSize:)];
[self replaceInstanceSelector:@selector(initWithCoder:) withSelector:@selector(initCustomWithCoder:)];
}
#pragma clang diagnostic pop
@end
[UPDATE]
As per March 7, 2017, Visual Studio 2017
was released for general availability.
You can refer to Mehdi Dehghani answer for the direct download links
or the old-fashioned ways using the website, vibs2006 answer
And you can also combine it with ray pixar answer to make it a complete full standalone offline installer.
Note:
I don't condone any illegal use of the offline installer.
Please stop piracy and follow the EULA.The community edition is free even for commercial use, under some condition.
You can see the EULA in this link below.
https://www.visualstudio.com/support/legal/mt171547
Thank you.
Instruction for official offline installer:
Open this link
Scroll Down (DO NOT FORGET!)
These menu should be available in that panel:
- Community 2015
- Enterprise 2015
- Professional 2015
- Enterprise 2015
- Visual Studio 2015 Update
- Visual Studio 2015 Language Pack
- Visual Studio Test Professional 2015 Language Pack
- Test Professional 2015
- Express 2015 for Desktop
- Express 2015 for Windows 10
The language drop-down menu should be like this:
- English for English
- Deutsch for German
- Español for Spanish
- Français for French
- Italiano for Italian
- ??????? for Russian
- ??? for Japanese
- ???? for Chinese (Simplified)
- ???? for Chinese (Traditional)
- ??? for Korean
Check on "ISO" in radio-button menu (on the left side of the Download button)
The radio-button menu should be like this:
- Web installer
- ISO
Click the Download button
I honestly thought that the casting method would work fine. Since it doesn't you can try stringstream. An example is below:
#include <sstream>
#include <string>
std::stringstream ss;
std::string target;
char mychar = 'a';
ss << mychar;
ss >> target;
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = <sql server name>;
builder.UserID = <user id>; //User id used to login into SQL
builder.Password = <password>; //password used to login into SQL
builder.InitialCatalog = <database name>; //Name of Database
DataTable orderTable = new DataTable();
//<sp name> stored procedute name which you want to exceute
using (var con = new SqlConnection(builder.ConnectionString))
using (SqlCommand cmd = new SqlCommand(<sp name>, con))
using (var da = new SqlDataAdapter(cmd))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//Data adapter(da) fills the data retuned from stored procedure
//into orderTable
da.Fill(orderTable);
}
You cannot calculate the differences separately ... what difference would that yield for 7:59 and 8:00 o'clock? Try
import time
time.time()
which gives you the seconds since the start of the epoch.
You can then get the intermediate time with something like
timestamp1 = time.time()
# Your code here
timestamp2 = time.time()
print "This took %.2f seconds" % (timestamp2 - timestamp1)
Use:
num_lines = sum(1 for line in open('data.txt'))
print(num_lines)
That will work.
Error: listen EADDRINUSE to solve it in Ubuntu run in terminal netstat -nptl
and after this kill -9 {process-number}
this command is to kill node process and now you can try to run again node server.js command
Ex
listen EADDRINUSE :::8080
netstat -nptl
tcp6 0 0 :::9000 :::* LISTEN 9660/java
tcp6 0 0 :::5800 :::* LISTEN -
tcp6 0 0 :::5900 :::* LISTEN -
tcp6 0 0 :::8080 :::* LISTEN 10401/node
tcp6 0 0 :::20080 :::* LISTEN 9660/java
tcp6 0 0 :::80 :::* LISTEN -
tcp6 0 0 :::22 :::* LISTEN -
tcp6 0 0 :::10137 :::* LISTEN 9660/java
kill -9 10401
Click on the arrow near by start button there you will get list of browser. Select the browser you want your application to be run with and click on "Set as Default" Click ok and you are done with this.
which(df==my.val, arr.ind=TRUE)
you have an type error in example of code. You forget curlybracket after success
$.ajax({
type: "POST",
url: '@Url.Action("Search","Controller")',
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.d.toString());
}
})
;
I discovered that FF triggers the focus event for iframe.contentWindow but not for iframe.contentWindow.document. Chrome for example can handle both cases. so, I just needed to bind my event handlers to iframe.contentWindow in order to get things working. Maybe this helps somebody ...
For Angular 5
app.module.ts
import {DatePipe} from '@angular/common';
.
.
.
providers: [DatePipe]
demo.component.ts
import { DatePipe } from '@angular/common';
.
.
constructor(private datePipe: DatePipe) {}
ngOnInit() {
var date = new Date();
console.log(this.datePipe.transform(date,"yyyy-MM-dd")); //output : 2018-02-13
}
more information angular/datePipe
e.preventDefault() works fine only if you dont have problem on your javascripts, check your javascripts if e.preventDefault() doesn't work chances are some other parts of your JS doesn't work also
As a workaround to this limitation, I use two rules to cover all the cases.
For example, if I want to allow or deny these 18 ports:
465,110,995,587,143,11025,20,21,22,26,80,443,3000,10000,7080,8080,3000,5666
I use the below rules:
iptables -A INPUT -p tcp -i eth0 -m multiport --dports 465,110,995,587,143,11025,20,21,22,26,80,443 -j ACCEPT
iptables -A INPUT -p tcp -i eth0 -m multiport --dports 3000,10000,7080,8080,3000,5666 -j ACCEPT
The above rules should work for your scenario also. You can create another rule if you hit 15 ports limit on both first and second rule.
Here's a helpful article on long polling (long-held HTTP request) using jQuery. A code snippet derived from this article:
(function poll() {
setTimeout(function() {
$.ajax({
url: "/server/api/function",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json",
complete: poll,
timeout: 2000
})
}, 5000);
})();
This will make the next request only after the ajax request has completed.
A variation on the above that will execute immediately the first time it is called before honouring the wait/timeout interval.
(function poll() {
$.ajax({
url: "/server/api/function",
type: "GET",
success: function(data) {
console.log("polling");
},
dataType: "json",
complete: setTimeout(function() {poll()}, 5000),
timeout: 2000
})
})();
If anyone else stumbles onto this page from google like I did:
use putty (putty.exe) to sign into your server and install curl using this command :
sudo apt-get install php5-curl
Make sure curl is enabled in the php.ini file. For me it's in /etc/php5/apache2/php.ini, if you can't find it, this line might be in /etc/php5/conf.d/curl.ini. Make sure the line :
extension=curl.so
is not commented out then restart apache, so type this into putty:
sudo /etc/init.d/apache2 restart
Info for install from https://askubuntu.com/questions/9293/how-do-i-install-curl-in-php5, to check if it works this stack overflow might help you: Detect if cURL works?
You can compile your code as Objective-C++ - the simplest way is to rename your .cpp as .mm. It will then compile properly if you include EAGLView.h
(you were getting so many errors because the C++ compiler didn't understand any of the Objective-C specific keywords), and you can (for the most part) mix Objective-C and C++ however you like.
Check if you are implementing the code inside a could drive like box, dropbox etc. If you copy the files you are trying to implement to a local folder on your machine you should be able to get rid of the error.
You can use groupBy of angular.filter module.
so you can do something like this:
JS:
$scope.players = [
{name: 'Gene', team: 'alpha'},
{name: 'George', team: 'beta'},
{name: 'Steve', team: 'gamma'},
{name: 'Paula', team: 'beta'},
{name: 'Scruath', team: 'gamma'}
];
HTML:
<ul ng-repeat="(key, value) in players | groupBy: 'team'">
Group name: {{ key }}
<li ng-repeat="player in value">
player: {{ player.name }}
</li>
</ul>
RESULT:
Group name: alpha
* player: Gene
Group name: beta
* player: George
* player: Paula
Group name: gamma
* player: Steve
* player: Scruath
UPDATE: jsbin Remember the basic requirements to use angular.filter
, specifically note you must add it to your module's dependencies:
(1) You can install angular-filter using 4 different methods:
- clone & build this repository
- via Bower: by running $ bower install angular-filter from your terminal
- via npm: by running $ npm install angular-filter from your terminal
- via cdnjs http://www.cdnjs.com/libraries/angular-filter
(2) Include angular-filter.js (or angular-filter.min.js) in your index.html, after including Angular itself.
(3) Add 'angular.filter' to your main module's list of dependencies.
You can try setting the target attribute of your form to a hidden iframe, so the page containing the form won't get reloaded.
I tried it with file uploads (which we know can't be done via AJAX), and it worked beautifully.
If you git stash pop
(with no conflicts) it will remove the stash after it is applied. But if you git stash apply
it will apply the patch without removing it from the stash list. Then you can revert the unwanted changes with git checkout -- files...
Answer is NO. You might have seen an example where somebody would have set something like :
-DArguments=a=1,b=2,c=3,d=4,e=cow
Then the application would parse value of Arguments
property string to get individual values.
In your main
you can get the key values as(Assuming input format is guaranteed):
String line = System.getProperty("Arguments");
if(line != null) {
String str[] = line.split(",");
for(int i=1;i<str.length;i++){
String arr[] = str[i].split("=");
System.out.println("Key = " + arr[0]);
System.out.println("Value = " + arr[1]);
}
}
Also, the -D
should be before the main class or the jar
file in the java command line. Example : java -DArguments=a=1,b=2,c=3,d=4,e=cow MainClass
We can checked a particulate checkbox as,
$('id of the checkbox')[0].checked = true
and uncheck by ,
$('id of the checkbox')[0].checked = false
An example based on Chuck's answer:
myIntToStr :: Int -> String
myIntToStr x
| x < 3 = show x ++ " is less than three"
| otherwise = "normal"
Note that without the show
the third line will not compile.
It might also make sense to add a call to clearNotifications in applicationDidBecomeActive so that in case the application is in the background and comes back it will also clear the notifications.
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[self clearNotifications];
}
Your datatype is wrong, change datatype for dataType.
If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection
.
using (ExcelPackage package = new ExcelPackage(file))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");
worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);
package.Save();
}
Simple way is to convert into column
SELECT COLUMN_VALUE FROM TABLE (SPLIT ('19869,19572,19223,18898,10155,'))
CREATE TYPE split_tbl as TABLE OF VARCHAR2(32767);
CREATE OR REPLACE FUNCTION split (p_list VARCHAR2, p_del VARCHAR2 := ',')
RETURN split_tbl
PIPELINED IS
l_idx PLS_INTEGER;
l_list VARCHAR2 (32767) := p_list;
l_value VARCHAR2 (32767);
BEGIN
LOOP
l_idx := INSTR (l_list, p_del);
IF l_idx > 0 THEN
PIPE ROW (SUBSTR (l_list, 1, l_idx - 1));
l_list := SUBSTR (l_list, l_idx + LENGTH (p_del));
ELSE
PIPE ROW (l_list);
EXIT;
END IF;
END LOOP;
RETURN;
END split;
An alternative approach with vue-cli
version 3 is to add a .env
file in the root project directory (along side package.json
) with the contents:
PORT=3000
Running npm run serve
will now indicate the app is running on port 3000.
You can use the rpad
and lpad
functions to pad numbers to the right or to the left, respectively. Note that this does not work directly on numbers, so you'll have to use ::char
or ::text
to cast them:
SELECT RPAD(numcol::text, 3, '0'), -- Zero-pads to the right up to the length of 3
LPAD(numcol::text, 3, '0'), -- Zero-pads to the left up to the length of 3
FROM my_table
There is a Hidden
helper alongside HiddenFor
which lets you set the value.
@Html.Hidden("RequiredProperty", "default")
EDIT Based on the edit you've made to the question, you could do this, but I believe you're moving into territory where it will be cheaper and more effective, in the long run, to fight for making the code change. As has been said, even by yourself, the controller or view model should be setting the default.
This code:
<ul>
@{
var stacks = new System.Diagnostics.StackTrace().GetFrames();
foreach (var frame in stacks)
{
<li>@frame.GetMethod().Name - @frame.GetMethod().DeclaringType</li>
}
}
</ul>
Will give output like this:
Execute - ASP._Page_Views_ViewDirectoryX__SubView_cshtml
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
ExecutePageHierarchy - System.Web.Mvc.WebViewPage
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
RenderView - System.Web.Mvc.RazorView
Render - System.Web.Mvc.BuildManagerCompiledView
RenderPartialInternal - System.Web.Mvc.HtmlHelper
RenderPartial - System.Web.Mvc.Html.RenderPartialExtensions
Execute - ASP._Page_Views_ViewDirectoryY__MainView_cshtml
So assuming the MVC framework will always go through the same stack, you can grab var frame = stacks[8];
and use the declaring type to determine who your parent view is, and then use that determination to set (or not) the default value. You could also walk the stack instead of directly grabbing [8]
which would be safer but even less efficient.
On Windows:-
Go to File -> Settings.
And open the 'Build,Execution,Deployment'
. Then open the
Build Tools -> Gradle
Then uncheck -> Offline work on the right.
Click the OK button.
Then Rebuild the Project.
On Mac OS:-
go to Android Studio -> Preferences, and the rest is the same. OR follow steps given in the image
[
For me what worked was:
Uninstall and then reinstall the referenced Nuget package that has the error.
I found a short solution for it.
No extra code is needed just trigger the changeDate event. E.g.
$('.datepicker').datepicker().trigger('changeDate');
Sounds like you want temp tables. http://www.sqlteam.com/article/temporary-tables
Note that #TempTable is available throughout your SP.
Note the ##TempTable is available to all.
This code works for me just fine as of mongoDB v4.2 and mongoose 5.9.9:
const Ids = ['id1','id2','id3']
const results = await Model.find({ _id: Ids})
and the Ids can be of type ObjectId
or String
I had the same problem with Visio 2016. I have the standard license. I think it is very strange that you can select a "UML Sequence" template when you search for it but it then opens a blank canvas without shapes. So you don't see anything and can't select the shapes under the "More Shapes" window on the side.
So I searched the shapes in the installation directory of Visio. I found in the directory C:\Program Files\Microsoft Office\Office16\Visio Content\1033
a couple of Sequence diagram templates (ie: BASIC_UMLSEQUENCE_M.VSTX). They are using the stencil USEQME_M.vssx
. I found that out by right clicking the shapes in the left window and select "Save as". I saved them in "My Documents" under "My Shapes" just like custom shapes. I can than use them in any new document that I want.
Note the capital M
or U
in the name of the template or stencil for US Units
or Metric Units
. I'm from the Netherlands so I'm using the M
version.
A not really friendly way to get the shapes. But it works.
It's a hexadecimal number.
0x6400 translates to 4*16^2 + 6*16^3 = 25600
Typically, I'll set the line-height
to be 200px. Usually does the trick.
Here is a successful example of an implementation of the same thing, on a device which supported lower screen brightness values (I tested on an Allwinner Chinese 7" tablet running API15).
WindowManager.LayoutParams params = this.getWindow().getAttributes();
/** Turn off: */
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
//TODO Store original brightness value
params.screenBrightness = 0.1f;
this.getWindow().setAttributes(params);
/** Turn on: */
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
//TODO restoring from original value
params.screenBrightness = 0.9f;
this.getWindow().setAttributes(params);
If someone else tries this out, pls comment below if it worked/didn't work and the device, Android API.
Actually, this is not specific to display:inline-block
, but also applies to display:inline
. Thus, in addition to David Horák's solution, this also works:
ul {
font-size: 0;
}
ul li {
font-size: 14px;
display: inline;
}
I think you want this:
select *
from dbo.table
where DATALENGTH(column_name) = 3
If your end goal is to add elements to your page, just manipulate the DOM directly. Don't use string concatenation to try to create HTML - what a pain! See how much more straightforward it is to just create your element, instead of the HTML that represents your element:
var x = document.createElement("option");
x.value = col;
x.text = "Very roomy";
x.selected = col == "screwdriver";
Then, later when you put the element in your page, instead of setting the innerHTML
of the parent element, call appendChild()
:
mySelectElement.appendChild(x);
This worked for me
yum install mysql
It will install mysql client and then
pip install mysqlclient
you can't use aliases from select list inside the WHERE clause (because of the Order of Evaluation of a SELECT statement)
also you cannot use OVER
clause inside WHERE clause - "You can specify analytic functions with this clause in the select list or ORDER BY clause." (citation from docs.oracle.com)
select *
from (select
staff_id, site_id, pay_level, date,
max(date) over (partition by staff_id) max_date
from owner.table
where end_enrollment_date is null
)
where date = max_date
++i
will increment the value of i
, and then return the incremented value.
i = 1;
j = ++i;
(i is 2, j is 2)
i++
will increment the value of i
, but return the original value that i
held before being incremented.
i = 1;
j = i++;
(i is 2, j is 1)
For a for
loop, either works. ++i
seems more common, perhaps because that is what is used in K&R.
In any case, follow the guideline "prefer ++i
over i++
" and you won't go wrong.
There's a couple of comments regarding the efficiency of ++i
and i++
. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical.
The efficiency question is interesting... here's my attempt at an answer: Is there a performance difference between i++ and ++i in C?
As @OnFreund notes, it's different for a C++ object, since operator++()
is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value.
To be clear and answer @Dean's question: EBS-type root storage doesn't seem to be ephemeral. Data is persistent across reboots and actually it doesn't make any sense to use ebs-backed root volume which is 'ephemeral'. This wouldn't be different from image-based root volume.
Thing's to be Consider While Designing the Elevator System,
Elevator
Floor/Location Identifier
Number of steps
Rotation speed
Daterange
InstallationDate
MaintainenceDate
Department Identifier
AllowedWeight
Detail / Description
Poison Ratio (Statistics)
Start
Stop
SetDirection
SetRotationSpeed
EmergencyStop = Stop + Alert
EmergencyAccidentSenser Handler
Each button press results in an elevator request which has to be served. Each of these requests is tracked at a global place
The number of elevators in the building will be determined by the user. The building will contain a fixed number of floors. The number of passengers that can fit into the elevator will be fixed. The passengers will be counted as they leave the elevator at their destination floor. The destination floor will be determined using a "random" Poisson interval. When all of the passengers in the elevator have reached their destination floors, the elevator will return to the lobby to pickup more passengers
There are several ways I can think of to do this.
Use a callback:
function FunctInit(someVarible){
//init and fill screen
AndroidCallGetResult(); // Enables Android button.
}
function getResult(){ // Called from Android button only after button is enabled
//return some variables
}
Use a Timeout (this would probably be my preference):
var inited = false;
function FunctInit(someVarible){
//init and fill screen
inited = true;
}
function getResult(){
if (inited) {
//return some variables
} else {
setTimeout(getResult, 250);
}
}
Wait for the initialization to occur:
var inited = false;
function FunctInit(someVarible){
//init and fill screen
inited = true;
}
function getResult(){
var a = 1;
do { a=1; }
while(!inited);
//return some variables
}
One alternative is to change up your module. Generally if you are exporting an object with a bunch of functions on it, it's easier to export a bunch of named functions, e.g.
export function foo() { console.log('foo') },
export function bar() { console.log('bar') },
export function baz() { foo(); bar() }
In this case you are export all of the functions with names, so you could do
import * as fns from './foo';
to get an object with properties for each function instead of the import you'd use for your first example:
import fns from './foo';
Are you calling getWidth()
before the view is actually laid out on the screen?
A common mistake made by new Android developers is to use the width and height of a view inside its constructor. When a view’s constructor is called, Android doesn’t know yet how big the view will be, so the sizes are set to zero. The real sizes are calculated during the layout stage, which occurs after construction but before anything is drawn. You can use the
onSizeChanged()
method to be notified of the values when they are known, or you can use thegetWidth()
andgetHeight()
methods later, such as in theonDraw()
method.
Alternative syntax:
INSERT tbl (Col1, Col2, ..., ColN)
SELECT Col1, Col2, ..., ColN
FROM Tbl2
WHERE ...
The select query can (of course) include expressions, case statements, constants/literals, etc.
You are improperly declaring your main module, it requires a second dependencies array argument when creating a module, otherwise it is a reference to an existing module
Change:
var app = angular.module("MesaViewer");
To:
var app = angular.module("MesaViewer",[]);
They are names for the same standard from two different industries with different naming methods, the guys who make & sell movies and the guys who transfer the movies over the internet. Since 2003: "MPEG 4 Part 10" = "H.264" = "AVC". Before that the relationship was a little looser in that they are not equal but an "MPEG 4 Part 2" decoder can render a stream that's "H.263". The Next standard is "MPEG H Part 2" = "H.265" = "HEVC"
There are some excellent points here and I'm going to add another one in case someones' path crosses here.
Thrift gives you an option to choose between thrift-binary and thrift-compact (de)serializer, thrift-binary will have an excellent performance but bigger packet size, while thrift-compact will give you good compression but needs more processing power. This is handy because you can always switch between these two modes as easily as changing a line of code (heck, even make it configurable). So if you are not sure how much your application should be optimized for packet size or in processing power, thrift can be an interesting choice.
PS: See this excellent benchmark project by thekvs
which compares many serializers including thrift-binary, thrift-compact, and protobuf: https://github.com/thekvs/cpp-serializers
PS: There is another serializer named YAS
which gives this option too but it is schema-less see the link above.
I solve the same problem with this SO answer.
Basically it binds the radio button to a boolean property of a Strongly Typed Model.
@Html.RadioButton("blah", !Model.blah) Yes
@Html.RadioButton("blah", Model.blah) No
Hope it helps!
I'm still going suggest the 2 map solution, but with a tweest
Map<K2, K1> m2;
Map<K1, V> m1;
This scheme lets you have an arbitrary number of key "aliases".
It also lets you update the value through any key without the maps getting out of sync.
Use DATESTR
>> datestr(40189)
ans =
12-Jan-0110
Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM
>> datenum(2010,1,11)
ans =
734149
>> datenum(2010,1,11)-40189
ans =
693960
>> datestr(40189+693960)
ans =
11-Jan-2010
In other words, to convert any serial Excel date, call
datestr(excelSerialDate + 693960)
EDIT
To get the date in mm/dd/yyyy format, call datestr
with the specified format
excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010
Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things
excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010
1. Authorization
You have received access data like this:
Username: johndoe
Password: zznAQOoWyj8uuAgq
Consumer Key: ggczWttBWlTjXCEtk3Yie_WJGEIa
Consumer Secret: uuzPjjJykiuuLfHkfgSdXLV98Ciga
Which you can call in cURL like this:
curl -k -d "grant_type=password&username=Username&password=Password" \
-H "Authorization: Basic Base64(consumer-key:consumer-secret)" \
https://somedomain.test.com/token
or for this case it would be:
curl -k -d "grant_type=password&username=johndoe&password=zznAQOoWyj8uuAgq" \
-H "Authorization: Basic zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh" \
https://somedomain.test.com/token
Answer would be something like:
{
"access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
"refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
"scope": "default",
"token_type": "Bearer",
"expires_in": 3600
}
2. Calling API
Here is how you call some API that uses authentication from above. Limit
and offset
are just examples of 2 parameters that API could implement.
You need access_token
from above inserted after "Bearer "
.So here is how you call some API with authentication data from above:
curl -k -X GET "https://somedomain.test.com/api/Users/Year/2020/Workers?offset=1&limit=100" -H "accept: application/json" -H "Authorization: Bearer zz8d62zz-56zz-34zz-9zzf-azze1b8057f8"
Same thing from above implemented in Python. I've put text in comments so code could be copy-pasted.
# Authorization data
import base64
import requests
username = 'johndoe'
password= 'zznAQOoWyj8uuAgq'
consumer_key = 'ggczWttBWlTjXCEtk3Yie_WJGEIa'
consumer_secret = 'uuzPjjJykiuuLfHkfgSdXLV98Ciga'
consumer_key_secret = consumer_key+":"+consumer_secret
consumer_key_secret_enc = base64.b64encode(consumer_key_secret.encode()).decode()
# Your decoded key will be something like:
#zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh
headersAuth = {
'Authorization': 'Basic '+ str(consumer_key_secret_enc),
}
data = {
'grant_type': 'password',
'username': username,
'password': password
}
## Authentication request
response = requests.post('https://somedomain.test.com/token', headers=headersAuth, data=data, verify=True)
j = response.json()
# When you print that response you will get dictionary like this:
{
"access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
"refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
"scope": "default",
"token_type": "Bearer",
"expires_in": 3600
}
# You have to use `access_token` in API calls explained bellow.
# You can get `access_token` with j['access_token'].
# Using authentication to make API calls
## Define header for making API calls that will hold authentication data
headersAPI = {
'accept': 'application/json',
'Authorization': 'Bearer '+j['access_token'],
}
### Usage of parameters defined in your API
params = (
('offset', '0'),
('limit', '20'),
)
# Making sample API call with authentication and API parameters data
response = requests.get('https://somedomain.test.com/api/Users/Year/2020/Workers', headers=headersAPI, params=params, verify=True)
api_response = response.json()
Run the following command on the terminal:
sudo apt-get autoremove ruby
Actually if you create func:
create function p1() returns INTEGER DETERMINISTIC NO SQL return @p1;
and view:
create view h_parm as
select * from sw_hardware_big where unit_id = p1() ;
Then you can call a view with a parameter:
select s.* from (select @p1:=12 p) parm , h_parm s;
I hope it helps.
Why PendingIntent is required ? I was thinking like
Intent
orIntent
for the same purpose.E.g.Intent bluetoothIntent= new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
If I send bluetoothIntent
to another application, which doesn't have permission android.permission.BLUETOOTH_ADMIN
, that receiving application cannot enable Bluetooth with startActivity(bluetoothIntent)
.
The limitation is overcome using PendingIntent
. With PendingIntent
the receiving application, doesn't need to have android.permission.BLUETOOTH_ADMIN
for enabling Bluetooth. Source.
It is possible that you have multiple versions of the dll(s) on your system. You can search your system to find out. The issue may be solved by simply changing the order of the directories in your path. This was my issue. (Cannot run Qt Creator GUI outside of Qt. "The application was unable to start correctly (0xc000007b)" error)
Don't forget to generate a second password for your Gmail account. You will use this new password in your code. Read this:
https://support.google.com/accounts/answer/185833
Under the section "How to generate an App password" click on "App passwords", then under "Select app" choose "Mail", select your device and click "Generate". Your second password will be printed on the screen.
Using the minus
operator was working but also it was taking more time to execute which was not acceptable.
I have a similar kind of requirement for data migration and I used the NOT IN
operator for that.
The modified query is :
select *
from A
where (emp_id,emp_name) not in
(select emp_id,emp_name from B)
union all
select * from B
where (emp_id,emp_name) not in
(select emp_id,emp_name from A);
This query executed fast. Also you can add any number of columns in the select query. Only catch is that both tables should have the exact same table structure for this to be executed.
As akjoshi and Julio say this is about dispatching an Action to update the GUI on the same thread as the GUI item but from the method that is handling the background data. You can see this code in specific form in akjoshi's answer above. This is a general version.
myTextBlock.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(delegate()
{
myTextBlock.Text = Convert.ToString(myDataObject.getMeData());
}));
The critical part is to call the dispatcher of your UI object - that ensures you have the correct thread.
From personal experience it seems much easier to create and use the Action inline like this. Declaring it at class level gave me lots of problems with static/non-static contexts.
You could use DOM4j doing that.