You simply need to remove v-bind (:) from selected and required attributes. Like this :-
<template>_x000D_
<select class="form-control" v-model="selected" required @change="changeLocation">_x000D_
<option selected>Choose Province</option>_x000D_
<option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>_x000D_
</select>_x000D_
</template>
_x000D_
You are not binding anything to the vue instance through these attributes thats why it is giving error.
Since react-router v5.1 with hooks:
import { useParams } from 'react-router';
export default function DetailsPage() {
const { id } = useParams();
}
I would avoid the use of a mega api like apache commons. This is a simplistic operation and its built into the JDK in the new NIO package. It was kind of already linked to in a previous answer, but the key method in the NIO api are the new functions "transferTo" and "transferFrom".
One of the linked articles shows a great way on how to integrate this function into your code, using the transferFrom:
public static void copyFile(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
}
Learning NIO can be a little tricky, so you might want to just trust in this mechanic before going off and trying to learn NIO overnight. From personal experience it can be a very hard thing to learn if you don't have the experience and were introduced to IO via the java.io streams.
You just need to provide an alias for your aggregate columns in the CTE
d as (SELECT
duration,
sum(totalitems) as sumtotalitems
FROM
[DrySoftBranch].[dbo].[mnthItemWiseTotalQty] ('1') AS BkdQty
group by duration
)
You could use the DirectoryInfo and FileInfo classes.
//GetFiles on DirectoryInfo returns a FileInfo object.
var pdfFiles = new DirectoryInfo("C:\\Documents").GetFiles("*.pdf");
//FileInfo has a Name property that only contains the filename part.
var firstPdfFilename = pdfFiles[0].Name;
In XML 1.0, the XML Declaration is optional. See section 2.8 of the XML 1.0 Recommendation, where it says it "should" be used -- which means it is recommended, but not mandatory. In XML 1.1, however, the declaration is mandatory. See section 2.8 of the XML 1.1 Recommendation, where it says "MUST" be used. It even goes on to state that if the declaration is absent, that automatically implies the document is an XML 1.0 document.
Note that in an XML Declaration the encoding
and standalone
are both optional. Only the version
is mandatory. Also, these are not attributes, so if they are present they must be in that order: version
, followed by any encoding
, followed by any standalone
.
<?xml version="1.0"?>
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" standalone="yes"?>
<?xml version="1.0" encoding="UTF-16" standalone="yes"?>
If you don't specify the encoding in this way, XML parsers try to guess what encoding is being used. The XML 1.0 Recommendation describes one possible way character encoding can be autodetected. In practice, this is not much of a problem if the input is encoded as UTF-8, UTF-16 or US-ASCII. Autodetection doesn't work when it encounters 8-bit encodings that use characters outside the US-ASCII range (e.g. ISO 8859-1) -- avoid creating these if you can.
The standalone
indicates whether the XML document can be correctly processed without the DTD or not. People rarely use it. These days, it is a bad to design an XML format that is missing information without its DTD.
Update:
A "prolog error/invalid utf-8 encoding" error indicates that the actual data the parser found inside the file did not match the encoding that the XML declaration says it is. Or in some cases the data inside the file did not match the autodetected encoding.
Since your file contains a byte-order-mark (BOM) it should be in UTF-16 encoding. I suspect that your declaration says <?xml version="1.0" encoding="UTF-8"?>
which is obviously incorrect when the file has been changed into UTF-16 by NotePad. The simple solution is to remove the encoding
and simply say <?xml version="1.0"?>
. You could also edit it to say encoding="UTF-16"
but that would be wrong for the original file (which wasn't in UTF-16) or if the file somehow gets changed back to UTF-8 or some other encoding.
Don't bother trying to remove the BOM -- that's not the cause of the problem. Using NotePad or WordPad to edit XML is the real problem!
Web servers respond with a HTTP status code indicating the outcome of the request e.g. 200 (sometimes 202) means success, 404 - not found etc (see here). Assuming the server address part of the URL is correct and you are not getting a socket timeout, the exception is most likely telling you the HTTP status code was other than 200. I would suggest checking the class of the exception and seeing if the exception carries the HTTP status code.
IIRC - The call in question throws a WebException or a descendant. Check the class name to see which one and wrap the call in a try block to trap the condition.
Yes, that is possible. At its lowest level Bluetooth allows you to connect up to 7 devices to one master device. I have done this and it has worked well for me, but only on other platforms (linux) where I had lots of manual control - I've never tried that on Android and there are some possible complications so you will need to do some testing to be certain.
One of the issues is that you need the tablet to the master and Android doesn't give you any explicit control of this. It is likely that this won't be a problem because * the tablet will automatically become the master when you try to connect a second device to it, or * you will be able to control the master/slave roles by how you setup your socket connection
I will caution though that most apps using Bluetooth on mobile are not attempting many simultaneous connections and Bluetooth can be a bit fragile, e.g. what if two devices already have a Bluetooth connection for some other app - how might that affect the roles?
For reference, here's complete code for how to send json from a Python client:
import requests
res = requests.post('http://localhost:5000/api/add_message/1234', json={"mytext":"lalala"})
if res.ok:
print res.json()
The "json=" input will automatically set the content-type, as discussed here: Post JSON using Python Requests
And the above client will work with this server-side code:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.json
print content['mytext']
return jsonify({"uuid":uuid})
if __name__ == '__main__':
app.run(host= '0.0.0.0',debug=True)
If you want to split a string into more than two columns based on a delimiter you can omit the 'maximum splits' parameter.
You can use:
df['column_name'].str.split('/', expand=True)
This will automatically create as many columns as the maximum number of fields included in any of your initial strings.
REST is somewhat of a revival of old-school HTTP, where the actual HTTP verbs (commands) have semantic meaning. Til recently, apps that wanted to update stuff on the server would supply a form containing an 'action' variable and a bunch of data. The HTTP command would almost always be GET
or POST
, and would be almost irrelevant. (Though there's almost always been a proscription against using GET for operations that have side effects, in reality a lot of apps don't care about the command used.)
With REST, you might instead PUT /profiles/cHao
and send an XML or JSON representation of the profile info. (Or rather, I would -- you would have to update your own profile. :) That'd involve logging in, usually through HTTP's built-in authentication mechanisms.) In the latter case, what you want to do is specified by the URL, and the request body is just the guts of the resource involved.
http://en.wikipedia.org/wiki/Representational_State_Transfer has some details.
A sha256 is 256 bits long -- as its name indicates.
Since sha256 returns a hexadecimal representation, 4 bits are enough to encode each character (instead of 8, like for ASCII), so 256 bits would represent 64 hex characters, therefore you need a varchar(64)
, or even a char(64)
, as the length is always the same, not varying at all.
And the demo :
$hash = hash('sha256', 'hello, world!');
var_dump($hash);
Will give you :
$ php temp.php
string(64) "68e656b251e67e8358bef8483ab0d51c6619f3e7a1a9f0e75838d41ff368f728"
i.e. a string with 64 characters.
In case you need more shorting your code, you can creating new type for helper
type Strings []string
func (ss Strings) ToInterfaceSlice() []interface{} {
iface := make([]interface{}, len(ss))
for i := range ss {
iface[i] = ss[i]
}
return iface
}
then
a := []strings{"a", "b", "c", "d"}
sliceIFace := Strings(a).ToInterfaceSlice()
You can use the following attributes for webkit, which reach into the shadow DOM:
::-webkit-scrollbar { /* 1 */ }
::-webkit-scrollbar-button { /* 2 */ }
::-webkit-scrollbar-track { /* 3 */ }
::-webkit-scrollbar-track-piece { /* 4 */ }
::-webkit-scrollbar-thumb { /* 5 */ }
::-webkit-scrollbar-corner { /* 6 */ }
::-webkit-resizer { /* 7 */ }
Here's a working fiddle with a red scrollbar, based on code from this page explaining the issues.
http://jsfiddle.net/hmartiro/Xck2A/1/
Using this and your solution, you can handle all browsers except Firefox, which at this point I think still requires a javascript solution.
In C11(ISO/IEC 9899:201x), gets()
has been removed. (It's deprecated in ISO/IEC 9899:1999/Cor.3:2007(E))
In addition to fgets()
, C11 introduces a new safe alternative gets_s()
:
C11 K.3.5.4.1 The
gets_s
function#define __STDC_WANT_LIB_EXT1__ 1 #include <stdio.h> char *gets_s(char *s, rsize_t n);
However, in the Recommended practice section, fgets()
is still preferred.
The
fgets
function allows properly-written programs to safely process input lines too long to store in the result array. In general this requires that callers offgets
pay attention to the presence or absence of a new-line character in the result array. Consider usingfgets
(along with any needed processing based on new-line characters) instead ofgets_s
.
You don't add columns between other columns in SQL, you just add them. Where they're put is totally up to the DBMS. The right place to ensure that columns come out in the correct order is when you select
them.
In other words, if you want them in the order {name,colnew,qty,rate}
, you use:
select name, colnew, qty, rate from ...
With SQLite, you need to use alter table
, an example being:
alter table mytable add column colnew char(50)
Here is an ES6 method chain using .map()
and .includes()
:
const arr = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
const checkForUser = (newUsername) => {
arr.map(user => {
return user.username
}).includes(newUsername)
}
if (!checkForUser('fred')){
// add fred
}
The idiom (shared by quite a few other languages) for an unused variable is a single underscore _
. Code analysers typically won't complain about _
being unused, and programmers will instantly know it's a shortcut for i_dont_care_wtf_you_put_here
. There is no way to iterate without having an item variable - as the Zen of Python puts it, "special cases aren't special enough to break the rules".
I found this:
<embed type="application/x-vlc-plugin"
pluginspage="http://www.videolan.org"version="VideoLAN.VLCPlugin.2" width="100%"
height="100%" id="vlc" loop="yes"autoplay="yes" target="http://10.1.2.201:8000/"></embed>
I don't see that in your code anywhere.... I think that's all you need and the target would be the location of your video...
and here is more info on the vlc plugin:
http://wiki.videolan.org/Documentation%3aWebPlugin#Input_object
Another thing to check is that the address for the video file is correct....
I approached the same problem yesterday and found a module called [natsort][1], which solves your problem. Use:
from natsort import natsorted # pip install natsort
# Example list of strings
a = ['1', '10', '2', '3', '11']
[In] sorted(a)
[Out] ['1', '10', '11', '2', '3']
[In] natsorted(a)
[Out] ['1', '2', '3', '10', '11']
# Your array may contain strings
[In] natsorted(['string11', 'string3', 'string1', 'string10', 'string100'])
[Out] ['string1', 'string3', 'string10', 'string11', 'string100']
It also works for dictionaries as an equivalent of sorted
.
[1]: https://pypi.org/project/natsort/
The problem with most of these solutions is that you either have your local settings applied before the common ones, or after them.
So it's impossible to override things like
at the same time.
One solution can be implemented using "ini"-style config files with the ConfigParser class. It supports multiple files, lazy string interpolation, default values and a lot of other goodies. Once a number of files have been loaded, more files can be loaded and their values will override the previous ones, if any.
You load one or more config files, depending on the machine address, environment variables and even values in previously loaded config files. Then you just use the parsed values to populate the settings.
One strategy I have successfully used has been:
defaults.ini
filenet.ini
, then net.domain.ini
, then net.domain.webserver01.ini
, each one possibly overriding values of the previous). This account also for developers' machines, so each one could set up its preferred database driver, etc. for local developmentcluster.cluster_name.ini
, which can define things like database and cache IPsAs an example of something you can achieve with this, you can define a "subdomain" value per-env, which is then used in the default settings (as hostname: %(subdomain).whatever.net
) to define all the necessary hostnames and cookie things django needs to work.
This is as DRY I could get, most (existing) files had just 3 or 4 settings. On top of this I had to manage customer configuration, so an additional set of configuration files (with things like database names, users and passwords, assigned subdomain etc) existed, one or more per customer.
One can scale this as low or as high as necessary, you just put in the config file the keys you want to configure per-environment, and once there's need for a new config, put the previous value in the default config, and override it where necessary.
This system has proven reliable and works well with version control. It has been used for long time managing two separate clusters of applications (15 or more separate instances of the django site per machine), with more than 50 customers, where the clusters were changing size and members depending on the mood of the sysadmin...
You can't do exactly what you want in Python (if I read you correctly). You need to put values in for each element of the list (or as you called it, array).
But, try this:
a = [0 for x in range(N)] # N = size of list you want
a[i] = 5 # as long as i < N, you're okay
For lists of other types, use something besides 0. None
is often a good choice as well.
Based on the 5.10.1 version.
My solution (locally):
If you're using "fontawesome.css" or "fontawesome.min.css", try using "all.css" instead (located in the css folder).
The "css" folder and the "webfonts" folder from the fontawesome package that you downloaded must be in the same level as each other.
In my case, I already had a css folder so I just renamed the fontawesome css folder to "css-fa".
With both "css-fa" and "webfonts" in my css folder, simply link it correctly in your text editor and it should work.
Ex: link rel="stylesheet" href="css/css-fa/all.css"
I needed to add an additional Maven dependency:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
Rather than creating empty directories in source to exclude, you can supply the full destination path to the /XD switch to have the destination directories untouched
robocopy "%SOURCE_PATH%" "%DEST_PATH%" /MIR /XD "%DEST_PATH%"\hq04s2dba301
A scan of the @SpringBootApplication
show that it includes the following annotations:
@Configuration
@ComponentScan
@EnableAutoConfiguration
So you could do this too:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(ScheduledTasks.class, args);
}
}
something like this:
List<string> test1 = new List<string> { "@bob.com", "@tom.com" };
List<string> test2 = new List<string> { "[email protected]", "[email protected]" };
var res = test2.Where(f => test1.Count(z => f.Contains(z)) == 0)
Live example: here
Try adding this at the end of your code:
import matplotlib.pyplot as plt
plt.title('add title here')
I think easy way to disable button is :data => { disable_with: "Saving.." }
This will submit a form and then make a button disable, Also it won't disable button if you have any validations like required = 'required'.
You can use the regex
(\s)\1
and
replace it with $1
.
Java code:
str = str.replaceAll("(\\s)\\1","$1");
If the input is "foo\t\tbar "
you'll get "foo\tbar "
as output
But if the input is "foo\t bar"
it will remain unchanged because it does not have any consecutive whitespace characters.
If you treat all the whitespace characters(space, vertical tab, horizontal tab, carriage return, form feed, new line) as space then you can use the following regex to replace any number of consecutive white space with a single space:
str = str.replaceAll("\\s+"," ");
But if you want to replace two consecutive white space with a single space you should do:
str = str.replaceAll("\\s{2}"," ");
In IIS 7 and beyond:
web.config file:
<system.webServer>
<security >
<requestFiltering>
<requestLimits maxAllowedContentLength="[Size In Bytes]" />
</requestFiltering>
</security>
</system.webServer>
You can then check in code behind, like so:
If FileUpload1.PostedFile.ContentLength > 2097152 Then ' (2097152 = 2 Mb)
' Exceeded the 2 Mb limit
' Do something
End If
Just make sure the [Size In Bytes] in the web.config is greater than the size of the file you wish to upload then you won't get the 404 error. You can then check the file size in code behind using the ContentLength which would be much better
I found this (WPF Multithreading: Using the BackgroundWorker and Reporting the Progress to the UI. link) to contain the rest of the details which are missing from @Andrew's answer.
The one thing I found very useful was that the worker thread couldn't access the MainWindow's controls (in it's own method), however when using a delegate inside the main windows event handler it was possible.
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
pd.Close();
// Get a result from the asynchronous worker
T t = (t)args.Result
this.ExampleControl.Text = t.BlaBla;
};
In my case installing a new virtual device helped. Now I am using 1 device per app.
Note that for me to get this working (RVM install on CentOS 5.6), I had to run the following:
export GIT_SSL_NO_VERIFY=true
and after that, the standard install procedure for curling the RVM installer into bash worked a treat :)
jobs -l should give you the pid for the list of nohup processes. kill (-9) them gently. ;)
<application android:icon="drawable resource">
....
</application>
https://developer.android.com/guide/topics/manifest/application-element.html
You should create separate icons for all generalized screen densities, including low-, medium-, high-, and extra-high-density screens. This ensures that your icons will display properly across the range of devices on which your application can be installed...
Launcher icons should be 32-bit PNGs with an alpha channel for transparency. The finished launcher icon dimensions corresponding to a given generalized screen density are shown in the table below.
android:icon="@drawable/icon_name"
or android:icon="@mipmap/icon_name"
developer.android.com/guide says,
This attribute must be set as a reference to a drawable resource containing the image (for example "@drawable/icon").
about launcher icons android-developers.googleblog.com says,
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density. For example, an xxxhdpi app icon can be used on the launcher for an xxhdpi device.
Dianne Hackborn from Google (Android Framework) says,
If you are building different versions of your app for different densities, you should know about the "mipmap" resource directory. This is exactly like "drawable" resources, except it does not participate in density stripping when creating the different apk targets.
<application android:name="ApplicationTitle"
android:label="@string/app_label"
android:icon="@mipmap/ic_launcher" >
Little bit more quoting this
You want to load an image for your device density and you are going to use it "as is", without changing its actual size. In this case you should work with drawables and Android will give you the best fitting image.
You want to load an image for your device density, but this image is going to be scaled up or down. For instance this is needed when you want to show a bigger launcher icon, or you have an animation, which increases image's size. In such cases, to ensure best image quality, you should put your image into mipmap folder. What Android will do is, it will try to pick up the image from a higher density bucket instead of scaling it up. This will increase sharpness (quality) of the image.
Fore more you can read mipmap vs drawable folders
Read more : https://developer.android.com/guide/practices/ui_guidelines/icon_design_launcher.html
the xcode UI has changed a bit from one version to the next so here is where you update the plist for 9.0 beta 4 if it helps Project ->Target ->Info
SELECT SUM(No), HOUR(dateofissue)
FROM tablename
WHERE dateofissue>='2011-07-30'
GROUP BY HOUR(dateofissue)
It will give the hour by sum from a particular day!
Whoa whoa whoa. Is there a specific reason you're using floating-point for currency, or would things be better off with an arbitrary-precision, fixed-point number format? I have no idea what the specific problem that you're trying to solve is, but you should think about whether or not half a cent is really something you want to work with, or if it's just an artifact of using an imprecise number format.
I know this is an old post but I would like share my solution. I spent several hours trying to make a justified navigation menu. You do not really need to modify anything in bootstrap css. Just need to add the correct class in the html.
<nav class="nav navbar-default navbar-fixed-top">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#collapsable-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#top">Brand Name</a>
</div>
<div class="collapse navbar-collapse" id="collapsable-1">
<ul class="nav nav-justified">
<li><a href="#about-me">About Me</a></li>
<li><a href="#skills">Skills</a></li>
<li><a href="#projects">Projects</a></li>
<li><a href="#contact-me">Contact Me</a></li>
</ul>
</div>
</nav>
This CSS code will simply remove the navbar-brand class when the screen reaches 768px.
media@(min-width: 768px){
.navbar-brand{
display: none;
}
}
I was getting the same error. I was using Intellij IDEA and I wanted to run Spring boot application. So, solution from my side is as follow.
Go to Run menu -> Run configuration -> Click on Add button from the left panel and select maven -> In parameters add this text -> spring-boot:run
Now press Ok and Run.
function XLExport() {
try {
var i;
var j;
var mycell;
var tableID = "tblInnerHTML";
var objXL = new ActiveXObject("Excel.Application");
var objWB = objXL.Workbooks.Add();
var objWS = objWB.ActiveSheet;
for (i = 0; i < document.getElementById('<%= tblAuditReport.ClientID %>').rows.length; i++) {
for (j = 0; j < document.getElementById('<%= tblAuditReport.ClientID %>').rows(i).cells.length; j++) {
mycell = document.getElementById('<%= tblAuditReport.ClientID %>').rows(i).cells(j);
objWS.Cells(i + 1, j + 1).Value = mycell.innerText;
}
}
//objWS.Range("A1", "L1").Font.Bold = true;
objWS.Range("A1", "Z1").EntireColumn.AutoFit();
//objWS.Range("C1", "C1").ColumnWidth = 50;
objXL.Visible = true;
}
catch (err) {
}
}
Try the following parameter:
-nc
,--no-clobber
: skip downloads that would download to existing files.
Sample usage:
wget -nc http://example.com/pic.png
The Scanner class may simplify this.
StringBuilder sb=new StringBuilder();
Scanner scanner=null;
try {
scanner=new Scanner(getAssets().open("text.txt"));
while(scanner.hasNextLine()){
sb.append(scanner.nextLine());
sb.append('\n');
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(scanner!=null){try{scanner.close();}catch (Exception e){}}
}
mTextView.setText(sb.toString());
I use following code for get different result from condition That worked for me.
Select A.column, B.column
FROM TABLE1 A
INNER JOIN
TABLE2 B
ON A.Id = (case when (your condition) then b.Id else (something) END)
This is the pattern you are looking for
/^[\w-_.]*$/
What this means:
^
Start of string[...]
Match characters inside\w
Any word character so 0-9
a-z
A-Z
-_.
Match -
and _
and .
*
Zero or more of pattern or unlimited $
End of stringIf you want to limit the amount of characters:
/^[\w-_.]{0,5}$/
{0,5}
Means 0-5
characters
Go to keycloak admin console > SpringBootKeycloak> Cients>login-app page. Here in valid-redirect uris section add http://localhost:8080/sso/login
This will help resolve indirect-uri problem
There are lots of suggestions to remove
dataType: "json"
While I grant that this works it's ignoring the underlying issue. If you're confident the return string really is JSON then look for errant whitespace at the start of the response. Consider having a look at it in fiddler. Mine looked like this:
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8
{"type":"scan","data":{"image":".\/output\/ou...
In my case this was a problem with PHP spewing out unwanted characters (in this case UTF file BOMs). Once I removed these it fixed the problem while also keeping
dataType: json
Here's a hack (updated with entire .html file):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
<script type="text/javascript">
$(function() {
$('.date-picker').datepicker( {
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy',
onClose: function(dateText, inst) {
$(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
}
});
});
</script>
<style>
.ui-datepicker-calendar {
display: none;
}
</style>
</head>
<body>
<label for="startDate">Date :</label>
<input name="startDate" id="startDate" class="date-picker" />
</body>
</html>
EDIT jsfiddle for the above example: http://jsfiddle.net/DBpJe/7755/
EDIT 2 Adds the month year value to input box only on clicking of Done button. Also allows to delete input box values, which isn't possible in above field http://jsfiddle.net/DBpJe/5103/
EDIT 3
updated Better Solution based on rexwolf's solution down.
http://jsfiddle.net/DBpJe/5106
There is no "absolute path for a file existing in the asset folder". The content of your project's assets/
folder are packaged in the APK file. Use an AssetManager
object to get an InputStream
on an asset.
For WebView
, you can use the file
Uri
scheme in much the same way you would use a URL. The syntax for assets is file:///android_asset/...
(note: three slashes) where the ellipsis is the path of the file from within the assets/
folder.
PROBLEM:
I had a problem with ConstraintLayout and ScrollView when i wanted to include it in another layout.
DECISION:
The solution to my problem was to use dataBinding.
You are trying to link objects compiled by different versions of the compiler. That's not supported in modern versions of VS, at least not if you are using the C++ standard library. Different versions of the standard library are binary incompatible and so you need all the inputs to the linker to be compiled with the same version. Make sure you re-compile all the objects that are to be linked.
The compiler error names the objects involved so the information the the question already has the answer you are looking for. Specifically it seems that the static library that you are linking needs to be re-compiled.
So the solution is to recompile Projectname1.lib with VS2012.
Please try this which it works for me.
return [] as Criminal[];
In crystal report formulafield date function aavailable there pass your date-time format in that You Will get the Date only here
Example: Date({MyTable.dte_QDate})
//lat=3434&lon=yy38&rd=1.0&|
in that format o/p is displaying
public class ReadText {
public static void main(String[] args) throws Exception {
FileInputStream f= new FileInputStream("D:/workplace/sample/bookstore.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(f));
String strline;
StringBuffer sb = new StringBuffer();
while ((strline = br.readLine()) != null)
{
String[] arraylist=StringUtils.split(strline, ",");
if(arraylist.length == 2){
sb.append("lat=").append(StringUtils.trim(arraylist[0])).append("&lon=").append(StringUtils.trim(arraylist[1])).append("&rt=1.0&|");
} else {
System.out.println("Error: "+strline);
}
}
System.out.println("Data: "+sb.toString());
}
}
Did you import the packages for the file reading stuff.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
also here
cfiltering(numberOfUsers, numberOfMovies);
Are you trying to create an object or calling a method?
also another thing:
user_movie_matrix[userNo][movieNo]=rating;
you are assigning a value to a member of an instance as if it was a static variable
also remove the Th
in
private int user_movie_matrix[][];Th
Hope this helps.
The IEnumerable<T>
interface does not include an indexer, you're probably confusing it with IList<T>
If the object really is an IList<T>
(e.g. List<T>
or an array T[]
), try making the reference to it of type IList<T>
too.
Otherwise, you can use myEnumerable.ElementAt(index)
which uses the Enumerable.ElementAt extension method. This should work for all IEnumerable<T>
s .
Note that unless the (run-time) object implements IList<T>
, this will cause all of the first index + 1
items to be enumerated, with all but the last being discarded.
EDIT:
As an explanation, IEnumerable<T>
is simply an interface that represents "that which exposes an enumerator." A concrete implementation may well be some sort of in-memory list that does allow fast-access by index, or it may not. For instance, it could be a collection that cannot efficiently satisfy such a query, such as a linked-list (as mentioned by James Curran). It may even be no sort of in-memory data-structure at all, such as an iterator, where items are generated ('yielded') on demand, or by an enumerator that fetches the items from some remote data-source. Because IEnumerable<T>
must support all these cases, indexers are excluded from its definition.
If you're using Python < 3, you'll need to tell the interpreter that your string literal is Unicode by prefixing it with a u
:
Python 2.7.2 (default, Jan 14 2012, 23:14:09)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> "??".encode("utf8")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
>>> u"??".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'
Further reading: Unicode HOWTO.
No, they are the same. But there is a difference between:
Test t; // create a Test called t
and
Test t(); // declare a function called t which returns a Test
This is because of the basic C++ (and C) rule: If something can possibly be a declaration, then it is a declaration.
Edit: Re the initialisation issues regarding POD and non-POD data, while I agree with everything that has been said, I would just like to point out that these issues only apply if the thing being new'd or otherwise constructed does not have a user-defined constructor. If there is such a constructor it will be used. For 99.99% of sensibly designed classes there will be such a constructor, and so the issues can be ignored.
Supopose you want to copy oldList into a new ArrayList object called newList
ArrayList<Object> newList = new ArrayList<>() ;
for (int i = 0 ; i<oldList.size();i++){
newList.add(oldList.get(i)) ;
}
These two lists are indepedant, changes to one are not reflected to the other one.
You would need to always consider the state of all checkboxes!
You could increase or decrease a number on checking or unchecking, but imagine the site loads with three of them checked.
So you always need to check all of them:
<script type="text/javascript">
<!--
function showMe (it, box) {
// consider all checkboxes with same name
var checked = amountChecked(box.name);
var vis = (checked >= 3) ? "block" : "none";
document.getElementById(it).style.display = vis;
}
function amountChecked(name) {
var all = document.getElementsByName(name);
// count checked
var result = 0;
all.forEach(function(el) {
if (el.checked) result++;
});
return result;
}
//-->
</script>
<div>
<div class="a">
A
</div>
</div>?
$(window).scroll(function() {
if ($(this).scrollTop() > 0) {
$('.a').fadeOut();
} else {
$('.a').fadeIn();
}
});
I wanted a simple example of the use of case that I could play with, this doesn't even need a table. This returns odd or even depending whether seconds is odd or even
SELECT CASE MOD(SECOND(NOW()),2) WHEN 0 THEN 'odd' WHEN 1 THEN 'even' END;
We can adjust the factor levels based on target
and use it in arrange
library(dplyr)
df %>% arrange(factor(name, levels = target))
# name value
#1 b TRUE
#2 c FALSE
#3 a TRUE
#4 d FALSE
Or order
it and use it in slice
df %>% slice(order(factor(name, levels = target)))
My common approach to get date without the time part..
SELECT CONVERT(VARCHAR(MAX),GETDATE(),103)
SELECT CAST(GETDATE() AS DATE)
The only time to use java.sql.Date
is in a PreparedStatement.setDate
. Otherwise, use java.util.Date
. It's telling that ResultSet.getDate
returns a java.sql.Date
but it can be assigned directly to a java.util.Date
.
Using DataTable is valid as user927524 stated. You can also do it by adding rows manually, which will not require to add a specific wrapping class:
List<string> filenamesList = ...;
foreach(string filename in filenamesList)
gvFilesOnServer.Rows.Add(new object[]{filename});
In any case, thanks user927524 for clearing this weird behavior!!
Use with:
{% with "shop/"|add:shop_name|add:"/base.html" as template %}
{% include template %}
{% endwith %}
Access contentResolver in Kotlin , inside activities, Object classes &... :
Application().contentResolver
I personally would just use the JavaScript code to switch between 2 classes.
Have the CSS outline everything you need on your div MINUS the background rule, then add two classes (e.g: expanded & collapsed) as rules each with the correct background image (or background position if using a sprite).
CSS with different images
.div {
/* button size etc properties */
}
.expanded {background: url(img/x.gif) no-repeat left top;}
.collapsed {background: url(img/y.gif) no-repeat left top;}
Or CSS with image sprite
.div {
background: url(img/sprite.gif) no-repeat left top;
/* Other styles */
}
.expanded {background-position: left bottom;}
Then...
JavaScript code with images
$(function){
$('#button').click(function(){
if($(this).hasClass('expanded'))
{
$(this).addClass('collapsed').removeClass('expanded');
}
else
{
$(this).addClass('expanded').removeClass('collapsed');
}
});
}
JavaScript with sprite
Note: the elegant toggleClass does not work in Internet Explorer 6, but the below addClass
/removeClass
method will work fine in this situation as well
The most elegant solution (unfortunately not Internet Explorer 6 friendly)
$(function){
$('#button').click(function(){
$(this).toggleClass('expanded');
});
}
$(function){
$('#button').click(function(){
if($(this).hasClass('expanded'))
{
$(this).removeClass('expanded');
}
else
{
$(this).addClass('expanded');
}
});
}
As far as I know this method will work accross browsers, and I would feel much more comfortable playing with CSS and classes than with URL changes in the script.
Try:
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'Pa55w0rd' WITH GRANT OPTION;
Delete the line "/*# sourceMappingURL=bootstrap.min.css.map */ "
in following files.
To fetch the file path in Linux use the command find / -name "\*bootstrap\*"
Well, if all you're wanting to do is put text from a separate file into your page (tags in the text should work, too), you can do this (your text styles on the main page—test.html
—should still work):
test.html
<html>
<body>
<p>Start</p>
<p>Beginning</p>
<div>
<script language="JavaScript" src="sample.js"></script>
</div>
<p>End</p>
</body>
</html>
sample.js
var data="Here is the imported text!";
document.write(data);
You can always recreate the HTML tags you want yourself, after all. There's need for server-side scripting just to grab text from another file, unless you want to do something more.
Anyway, what I'm starting to use this for is to make it so if I update a description common among lots of HTML files, I only need to update one file to do it (the .js
file) instead of every single HTML file that contains the text.
So, in summary, instead of importing an .html
file, a simpler solution is to import a .js
file with the content of the .html
file in a variable (and write the contents to the screen where you call the script).
Thanks for the question.
You may try this method:
private bool ValidatePassword(string password, out string ErrorMessage)
{
var input = password;
ErrorMessage = string.Empty;
if (string.IsNullOrWhiteSpace(input))
{
throw new Exception("Password should not be empty");
}
var hasNumber = new Regex(@"[0-9]+");
var hasUpperChar = new Regex(@"[A-Z]+");
var hasMiniMaxChars = new Regex(@".{8,15}");
var hasLowerChar = new Regex(@"[a-z]+");
var hasSymbols = new Regex(@"[!@#$%^&*()_+=\[{\]};:<>|./?,-]");
if (!hasLowerChar.IsMatch(input))
{
ErrorMessage = "Password should contain at least one lower case letter.";
return false;
}
else if (!hasUpperChar.IsMatch(input))
{
ErrorMessage = "Password should contain at least one upper case letter.";
return false;
}
else if (!hasMiniMaxChars.IsMatch(input))
{
ErrorMessage = "Password should not be lesser than 8 or greater than 15 characters.";
return false;
}
else if (!hasNumber.IsMatch(input))
{
ErrorMessage = "Password should contain at least one numeric value.";
return false;
}
else if (!hasSymbols.IsMatch(input))
{
ErrorMessage = "Password should contain at least one special case character.";
return false;
}
else
{
return true;
}
}
You can install cygwin, which has rm
as well as ls
etc.
As Requested By User Erickson, I Post My comment As Answer:
I have done some more testing with IE8, IE9, FF14, Opera11, Chrome20 and Tomcat 6.0.32 (fresh installation), Jersey 1.13 on the server side. I used the jQuery function $.getJson and JSONP. Results: All Browsers allowed up to around 5400 chars. FF and IE9 did up to around 6200 chars. Everything above returned "400 Bad request". I did not further investigate what was responsible for the 400. I was fine with the maximum I found, because I needed around 2000 chars in my case.
You first have to tell Gnuplot to use a style that uses points, e.g. with points
or with linespoints
. Try for example:
plot sin(x) with points
Output:
Now try:
plot sin(x) with points pointtype 5
Output:
You may also want to look at the output from the test
command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:
Do you need to do it from mgmt studio? Here's how we do it from cmd line:
"C:\Program Files\Microsoft SQL Server\MSSQL\Binn\TEXTCOPY.exe" /S < Server> /D < DataBase> /T mytable /C mypictureblob /F "C:\picture.png" /W"where RecId=" /I
Below code works for me
public static void sftpsript(String filepath) {
try {
String user ="demouser"; // username for remote host
String password ="demo123"; // password of the remote host
String host = "demo.net"; // remote host address
JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
sftpChannel.disconnect();
session.disconnect();
}catch(Exception ex){
ex.printStackTrace();
}
}
OR using StrictHostKeyChecking as "NO" (security consequences)
public static void sftpsript(String filepath) {
try {
String user ="demouser"; // username for remote host
String password ="demo123"; // password of the remote host
String host = "demo.net"; // remote host address
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);;
session.setPassword(password);
System.out.println("user=="+user+"\n host=="+host);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
sftpChannel.disconnect();
session.disconnect();
}catch(Exception ex){
ex.printStackTrace();
}
}
As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.
This is some pseudocodish JavaScript:
Client:
var websocket = new WebSocket("server address");
websocket.onmessage = function(str) {
console.log("Someone sent: ", str);
};
// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
id: "client1"
}));
// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
to: "client2",
data: "foo"
}));
Server:
var clients = {};
server.on("data", function(client, str) {
var obj = JSON.parse(str);
if("id" in obj) {
// New client, add it to the id/client object
clients[obj.id] = client;
} else {
// Send data to the client requested
clients[obj.to].send(obj.data);
}
});
In case, you would like to collect bitstamp trade data form their websocket in higher resolution over longer time period you could use script log_bitstamp_trades.py below.
The script uses python websocket-client and pusher_client_python libraries, so install them.
#!/usr/bin/python
import pusherclient
import time
import logging
import sys
import datetime
import signal
import os
logging.basicConfig()
log_file_fd = None
def sigint_and_sigterm_handler(signal, frame):
global log_file_fd
log_file_fd.close()
sys.exit(0)
class BitstampLogger:
def __init__(self, log_file_path, log_file_reload_path, pusher_key, channel, event):
self.channel = channel
self.event = event
self.log_file_fd = open(log_file_path, "a")
self.log_file_reload_path = log_file_reload_path
self.pusher = pusherclient.Pusher(pusher_key)
self.pusher.connection.logger.setLevel(logging.WARNING)
self.pusher.connection.bind('pusher:connection_established', self.connect_handler)
self.pusher.connect()
def callback(self, data):
utc_timestamp = time.mktime(datetime.datetime.utcnow().timetuple())
line = str(utc_timestamp) + " " + data + "\n"
if os.path.exists(self.log_file_reload_path):
os.remove(self.log_file_reload_path)
self.log_file_fd.close()
self.log_file_fd = open(log_file_path, "a")
self.log_file_fd.write(line)
def connect_handler(self, data):
channel = self.pusher.subscribe(self.channel)
channel.bind(self.event, self.callback)
def main(log_file_path, log_file_reload_path):
global log_file_fd
bitstamp_logger = BitstampLogger(
log_file_path,
log_file_reload_path,
"de504dc5763aeef9ff52",
"live_trades",
"trade")
log_file_fd = bitstamp_logger.log_file_fd
signal.signal(signal.SIGINT, sigint_and_sigterm_handler)
signal.signal(signal.SIGTERM, sigint_and_sigterm_handler)
while True:
time.sleep(1)
if __name__ == '__main__':
log_file_path = sys.argv[1]
log_file_reload_path = sys.argv[2]
main(log_file_path, log_file_reload_path
and logrotate file config
/mnt/data/bitstamp_logs/bitstamp-trade.log
{
rotate 10000000000
minsize 10M
copytruncate
missingok
compress
postrotate
touch /mnt/data/bitstamp_logs/reload_log > /dev/null
endscript
}
then you can run it on background
nohup ./log_bitstamp_trades.py /mnt/data/bitstamp_logs/bitstamp-trade.log /mnt/data/bitstamp_logs/reload_log &
If you want to preserve the order of the element with the same length as the original array, use bubble sort.
Input = ["ab","cdc","abcd","de"];
Output = ["ab","cd","cdc","abcd"]
Function:
function bubbleSort(strArray){
const arrayLength = Object.keys(strArray).length;
var swapp;
var newLen = arrayLength-1;
var sortedStrArrByLenght=strArray;
do {
swapp = false;
for (var i=0; i < newLen; i++)
{
if (sortedStrArrByLenght[i].length > sortedStrArrByLenght[i+1].length)
{
var temp = sortedStrArrByLenght[i];
sortedStrArrByLenght[i] = sortedStrArrByLenght[i+1];
sortedStrArrByLenght[i+1] = temp;
swapp = true;
}
}
newLen--;
} while (swap);
return sortedStrArrByLenght;
}
use below command to turn off the safe mode
$> hdfs dfsadmin -safemode leave
There's the global attribute called hidden
. But I'm green to all this and maybe there was a reason it wasn't mentioned yet?
var someCondition = true;_x000D_
_x000D_
if (someCondition == true){_x000D_
document.getElementById('hidden div').hidden = false;_x000D_
}
_x000D_
<div id="hidden div" hidden>_x000D_
stuff hidden by default_x000D_
</div>
_x000D_
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidden
Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.
set nocount on
create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)
insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)
declare @PersonID int
set @PersonID = 1
IF EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Posted_Flag = 1
AND Staff_Id = @PersonID
)
BEGIN
RAISERROR('Timesheets have already been posted!', 16, 1)
ROLLBACK TRAN
END
ELSE
IF NOT EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Staff_Id = @PersonID
)
BEGIN
RAISERROR('Default list has not been loaded!', 16, 1)
ROLLBACK TRAN
END
ELSE
print 'No problems here'
drop table Timesheet_Hours
JSON (= JavaScript Object Notation), is a lightweight and fast mechanism to convert Javascript objects into a string and vice versa.
Since Javascripts objects consists of key/value
pairs its very easy to use and access JSON that way.
So if we have an object:
var myObj = {
foo: 'bar',
base: 'ball',
deep: {
java: 'script'
}
};
We can convert that into a string by calling window.JSON.stringify(myObj);
with the result of "{"foo":"bar","base":"ball","deep":{"java":"script"}}"
.
The other way around, we would call window.JSON.parse("a json string like the above");
.
JSON.parse()
returns a javascript object/array on success.
alert(myObj.deep.java); // 'script'
window.JSON
is not natively available in all browser. Some "older" browser need a little javascript plugin which offers the above mentioned functionality. Check http://www.json.org for further information.
Your question is pretty hard to decode, but I'll try taking a stab at it.
You say:
I want to create a json object having two fields
uniqueIDofSelect
andoptionValue
in javascript.
And then you say:
I need output like
[{"selectID":2,"optionValue":"2"}, {"selectID":4,"optionvalue":"1"}]
Well, this example output doesn't have the field named uniqueIDofSelect
, it only has optionValue
.
Anyway, you are asking for array of objects...
Then in the comment to michaels answer you say:
It creates json object array. but I need only one json object.
So you don't want an array of objects?
What do you want then?
Please make up your mind.
if you're using .Net earlier than 4.5 you wont have Tls12 in the enum so state is explicitly mentioned here
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
I tried putting a getchar()
function at the end. But it didn't work. So what I did was add two getchar()
functions one after another. I think the first getchar()
absorbs the Enter key you press after the last data input. So try adding two getchar()
functions instead of one
Just an update to above answers :
If you want to have see changes in the click event, i.e. Color of your UIVIew shud change whenever user clicks the UIView then make changes as below...
class ClickableUIView: UIView {
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let currentPoint = touch.locationInView(self)
// do something with your currentPoint
}
self.backgroundColor = UIColor.magentaColor()//Color when UIView is clicked.
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let currentPoint = touch.locationInView(self)
// do something with your currentPoint
}
self.backgroundColor = UIColor.magentaColor()//Color when UIView is clicked.
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let currentPoint = touch.locationInView(self)
// do something with your currentPoint
}
self.backgroundColor = UIColor.whiteColor()//Color when UIView is not clicked.
}//class closes here
Also, call this Class from Storyboard & ViewController as:
@IBOutlet weak var panVerificationUIView:ClickableUIView!
The problem is that your regex is a string, but html
is bytes:
>>> type(html)
<class 'bytes'>
Since python doesn't know how those bytes are encoded, it throws an exception when you try to use a string regex on them.
You can either decode
the bytes to a string:
html = html.decode('ISO-8859-1') # encoding may vary!
title = re.findall(pattern, html) # no more error
Or use a bytes regex:
regex = rb'<title>(,+?)</title>'
# ^
In this particular context, you can get the encoding from the response headers:
with urllib.request.urlopen(url) as response:
encoding = response.info().get_param('charset', 'utf8')
html = response.read().decode(encoding)
See the urlopen
documentation for more details.
You can do something like
$(this).unbind('click').click();
hello you can try this bellow :
char arr[nb_of_string][max_string_length];
strcpy(arr[0], "word");
a nice example of using, array of strings in c if you want it
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]){
int i, j, k;
// to set you array
//const arr[nb_of_string][max_string_length]
char array[3][100];
char temp[100];
char word[100];
for (i = 0; i < 3; i++){
printf("type word %d : ",i+1);
scanf("%s", word);
strcpy(array[i], word);
}
for (k=0; k<3-1; k++){
for (i=0; i<3-1; i++)
{
for (j=0; j<strlen(array[i]); j++)
{
// if a letter ascii code is bigger we swap values
if (array[i][j] > array[i+1][j])
{
strcpy(temp, array[i+1]);
strcpy(array[i+1], array[i]);
strcpy(array[i], temp);
j = 999;
}
// if a letter ascii code is smaller we stop
if (array[i][j] < array[i+1][j])
{
j = 999;
}
}
}
}
for (i=0; i<3; i++)
{
printf("%s\n",array[i]);
}
return 0;
}
The outcome can be summarized as
LinqToSql for small sites, and prototypes. It really saves time for Prototyping.
Sps : Universal. I can fine tune my queries and always check ActualExecutionPlan / EstimatedExecutionPlan.
I already had python3 installed(via miniconda3) and needed to install python2 alongside in that case brew install python
won't install python2, so you would need
brew install python@2
.
Now alias python2
refers to python2.x from /usr/bin/python
and alias python3
refers to python3.x from /Users/ishandutta2007/miniconda3/bin/python
and alias python
refers to python3 by default.
Now to use python
as alias for python2, I added the following to .bashrc
file
alias python='/usr/bin/python'
.
To go back to python3 as default just remove this line when required.
First we should know that regular expression can separately be used. Here is an example:
import scala.util.matching.Regex
val pattern = "Scala".r // <=> val pattern = new Regex("Scala")
val str = "Scala is very cool"
val result = pattern findFirstIn str
result match {
case Some(v) => println(v)
case _ =>
} // output: Scala
Second we should notice that combining regular expression with pattern matching would be very powerful. Here is a simple example.
val date = """(\d\d\d\d)-(\d\d)-(\d\d)""".r
"2014-11-20" match {
case date(year, month, day) => "hello"
} // output: hello
In fact, regular expression itself is already very powerful; the only thing we need to do is to make it more powerful by Scala. Here are more examples in Scala Document: http://www.scala-lang.org/files/archive/api/current/index.html#scala.util.matching.Regex
If you want to open Form2
modally (meaning you can't click on Form1 while Form2 is open), you can do this:
using (Form2 f2 = new Form2())
{
f2.ShowDialog(this);
}
If you want to open Form2 non-modally (meaning you can still click on Form1 while Form2 is open), you can create a form-level reference to Form2 like this:
private Form2 _f2;
public void openForm2()
{
_f2 = new Form2();
_f2.Show(this); // the "this" is important, as this will keep Form2 open above
// Form1.
}
public void closeForm2()
{
_f2.Close();
_f2.Dispose();
}
You can also pass events down into child components with something like this:
<CustomComponent
@keyup.enter="handleKeyUp"
/>
...
<template>
<div>
<input
type="text"
v-on="$listeners"
>
</div>
</template>
<script>
export default {
name: 'CustomComponent',
mounted() {
console.log('listeners', this.$listeners)
},
}
</script>
That works well if you have a pass-through component and want the listeners to go onto a specific element.
I believe you intended it more this way:
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());
TaskStart.ToString("dd-MMMM-yyyy");
rpt.SetParameterValue("TaskStartDate", TaskStart);
}
}
You always accessed your first row in your dataset.
For those who stumble upon this from a search (Google) and are trying to translate to .NET and MVC code. (as in my case)
@using (Html.BeginForm("RemoveLostRolls", "Process", FormMethod.Get)) {
<input type="submit" value="Process" />
}
This will show a button labeled "Process" and take you to "/Process/RemoveLostRolls". Without "FormMethod.Get" it worked, but was seen as a "post".
You can use the below query to remove all the rows from the table, also you should keep it in mind that it will reset the Identity too.
TRUNCATE TABLE table_name
This worked nicely for my needs ;) Hope someone can use it....
public static Color FromName(String name)
{
var color_props= typeof(Colors).GetProperties();
foreach (var c in color_props)
if (name.Equals(c.Name, StringComparison.OrdinalIgnoreCase))
return (Color)c.GetValue(new Color(), null);
return Colors.Transparent;
}
There are different regex engines but I think most of them will work with this:
apple|banana
How malloc() and free() works depends on the runtime library used. Generally, malloc() allocates a heap (a block of memory) from the operating system. Each request to malloc() then allocates a small chunk of this memory be returning a pointer to the caller. The memory allocation routines will have to store some extra information about the block of memory allocated to be able to keep track of used and free memory on the heap. This information is often stored in a few bytes just before the pointer returned by malloc() and it can be a linked list of memory blocks.
By writing past the block of memory allocated by malloc() you will most likely destroy some of the book-keeping information of the next block which may be the remaining unused block of memory.
One place where you program may also crash is when copying too many characters into the buffer. If the extra characters are located outside the heap you may get an access violation as you are trying to write to non-existing memory.
I was able to fix this error by simply initializing a variable that was being used later in my program. At the time, I wasn't using Option Explicit in my class/module.
You can also use -match against a Regular expression. Ex:
if ($dbUserName -match ".{8}" )
{
Write-Output " Please enter more than 8 characters "
$dbUserName=read-host " Re-enter database user name"
}
Also if you're like me and like your curly braces to be in the same horizontal position for your code blocks, you can put that on a new line, since it's expecting a code block it will look on next line. In some commands where the first curly brace has to be in-line with your command, you can use a grave accent marker (`) to tell powershell to treat the next line as a continuation.
@Manuel was part way there. You can add the compiler option as well, like this:
If you have CMake 3.1.0+, this becomes even easier:
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app PRIVATE Threads::Threads)
If you are using CMake 2.8.12+, you can simplify this to:
find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
target_compile_options(my_app PUBLIC "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()
Older CMake versions may require:
find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
set_property(TARGET my_app PROPERTY COMPILE_OPTIONS "-pthread")
set_property(TARGET my_app PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()
If you want to use one of the first two methods with CMake 3.1+, you will need set(THREADS_PREFER_PTHREAD_FLAG ON)
there too.
Linq to sql has no support for Count(Distinct ...). You therefore have to map a .NET method in code onto a Sql server function (thus Count(distinct.. )) and use that.
btw, it doesn't help if you post pseudo code copied from a toolkit in a format that's neither VB.NET nor C#.
In keyboard (Spanish), SO: Win7.
Go into Preferences->Key Bindings - Default,
replace..."ctrl+/"]...
by "ctrl+7"...
And don't use the numpad, it doesn't work. Just use the numbers above the letters
Stop using the TEXT
data type in SQL Server!
It's been deprecated since the 2005 version. Use VARCHAR(MAX)
instead, if you need more than 8000 characters.
The TEXT
data type doesn't support the normal string functions, while VARCHAR(MAX)
does - your statement would work just fine, if you'd be using just VARCHAR types.
for (int i = 0; i < list.size(); i++) {
if (i < list.size() - 1) {
if (list.get(i) > list.get(i + 1)) {
int j = list.get(i);
list.remove(i);
list.add(i, list.get(i));
list.remove(i + 1);
list.add(j);
i = -1;
}
}
}
org.openqa.selenium.remote.DesiredCapabilities
package.Example:
WebDriver driver;
String baseUrl , nodeUrl;
baseUrl = "https://www.facebook.com";
nodeUrl = "http://192.168.10.21:5568/wd/hub";
DesiredCapabilities capability = DesiredCapabilities.firefox();
capability.setBrowserName("firefox");
capability.setPlatform(Platform.WIN8_1);
driver = new RemoteWebDriver(new URL(nodeUrl),capability);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);
Kibana is also a good solution. It is a data visualization platform for Elastic.If installed it runs by default on port 5601.
Out of the many things it provides. It has "Dev Tools" where we can do your debugging.
For example you can check your available indexes here using the command
GET /_cat/indices
You can combine both in the same date function call
date("d-m-Y H:i:s");
You can try using the WebDriver.Support SelectElement found in OpenQA.Selenium.Support.UI.Selected namespace to access the option list of a select list:
IWebElement elem = driver.FindElement(By.XPath("//select[@name='time_zone']"));
SelectElement selectList = new SelectElement(elem);
IList<IWebElement> options = selectList.Options;
You can then access each option as an IWebElement, such as:
IWebElement firstOption = options[0];
Assert.AreEqual(firstOption.GetAttribute("value"), "-09:00");
I think it actually depends on what are you going to do inside your doSomething
function. If you are going to access MyObject
properties using this keyword then you have to use that. But I think that the following code fragment will also work if you are not doing any special things using object(MyObject)
properties.
function doSomething(){
.........
}
$("#foobar").ready('click', function(){
});
You ask specifically about map()
, filter()
and reduce()
, but I assume you want to know about functional programming in general. Having tested this myself on the problem of computing distances between all points within a set of points, functional programming (using the starmap
function from the built-in itertools
module) turned out to be slightly slower than for-loops (taking 1.25 times as long, in fact). Here is the sample code I used:
import itertools, time, math, random
class Point:
def __init__(self,x,y):
self.x, self.y = x, y
point_set = (Point(0, 0), Point(0, 1), Point(0, 2), Point(0, 3))
n_points = 100
pick_val = lambda : 10 * random.random() - 5
large_set = [Point(pick_val(), pick_val()) for _ in range(n_points)]
# the distance function
f_dist = lambda x0, x1, y0, y1: math.sqrt((x0 - x1) ** 2 + (y0 - y1) ** 2)
# go through each point, get its distance from all remaining points
f_pos = lambda p1, p2: (p1.x, p2.x, p1.y, p2.y)
extract_dists = lambda x: itertools.starmap(f_dist,
itertools.starmap(f_pos,
itertools.combinations(x, 2)))
print('Distances:', list(extract_dists(point_set)))
t0_f = time.time()
list(extract_dists(large_set))
dt_f = time.time() - t0_f
Is the functional version faster than the procedural version?
def extract_dists_procedural(pts):
n_pts = len(pts)
l = []
for k_p1 in range(n_pts - 1):
for k_p2 in range(k_p1, n_pts):
l.append((pts[k_p1].x - pts[k_p2].x) ** 2 +
(pts[k_p1].y - pts[k_p2].y) ** 2)
return l
t0_p = time.time()
list(extract_dists_procedural(large_set))
# using list() on the assumption that
# it eats up as much time as in the functional version
dt_p = time.time() - t0_p
f_vs_p = dt_p / dt_f
if f_vs_p >= 1.0:
print('Time benefit of functional progamming:', f_vs_p,
'times as fast for', n_points, 'points')
else:
print('Time penalty of functional programming:', 1 / f_vs_p,
'times as slow for', n_points, 'points')
I've been using this function in my project.
function changeViewPort(key, val) {
var reg = new RegExp(key, "i"), oldval = document.querySelector('meta[name="viewport"]').content;
var newval = reg.test(oldval) ? oldval.split(/,\s*/).map(function(v){ return reg.test(v) ? key+"="+val : v; }).join(", ") : oldval+= ", "+key+"="+val ;
document.querySelector('meta[name="viewport"]').content = newval;
}
so just addEventListener:
if( /iPad|iPhone|iPod|Android/i.test(navigator.userAgent) ){
window.addEventListener("orientationchange", function() {
changeViewPort("maximum-scale", 1);
changeViewPort("maximum-scale", 10);
}
}
If you want to remove the default value constraint, you can do:
ALTER TABLE <table> ALTER COLUMN <column> DROP DEFAULT;
This is a quick hack: just assign the scroll value to a very large number. This will ensure that the page is scrolled to the bottom. Using plain javascript:
document.body.scrollTop = 100000;
Also it's important to pay attention if the property android:inputType is textMultiLine. If so, the properties android:singleLine, android:imeOptions, android:ellipsize and android maxLines will be ignored and your EditText will accepted MultiLines anyway.
Generally, there are two ways to list out installed packages - through the Command Line Interface (CLI) or in your application using the API.
Both commands will print to stdout
all the versions of packages that are installed, as well as their dependencies, in a tree-structure.
npm list
Use the -g
(global) flag to list out all globally-installed packages. Use the --depth=0
flag to list out only the top packages and not their dependencies.
In your case, you want to run this within your script, so you'd need to use the API. From the docs:
npm.commands.ls(args, [silent,] callback)
In addition to printing to stdout
, the data will also be passed into the callback.
This code works
BufferedReader bR = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
StringBuilder responseStrBuilder = new StringBuilder();
while((line = bR.readLine()) != null){
responseStrBuilder.append(line);
}
inputStream.close();
JSONObject result= new JSONObject(responseStrBuilder.toString());
You can use the "system( string $command[, int &$return_var] ) : string" function. For Windows system( "time" );, system( "time > output.txt" ); to put the response in the output.txt file. If you plan on deploying your website on someone else's server, then you may not want to hardcode the server time, as the server may move to an unknown timezone. Then it may be best to set the default time zone in the php.ini file. I use Hostinger and they allow you to configure that php.ini value.
I have same error. Problem was that branch was deleted, released. But in PhpStorm I still could see it in remote branches. I could checkout as local branch. And then doing git pull was giving this error.
So need to check if this brnach really exists remotely.
To make your formula more readable, you could assign a Name to cell A0, and then use that name in the formula.
The easiest way to define a Name is to highlight the cell or range, then click on the Name box in the formula bar.
Then, if you named A0 "Rate" you can use that name like this:
=(B0+4)/(Rate)
See, much easier to read.
If you want to find Rate, click F5 and it appears in the GoTo list.
Unsorted vector:
if (std::find(v.begin(), v.end(),value)!=v.end())
...
Sorted vector:
if (std::binary_search(v.begin(), v.end(), value)
...
P.S. may need to include <algorithm>
header
Since the method NetworkInfo.isConnected() is now deprecated in API-23, here is a method which detects if the Wi-Fi adapter is on and also connected to an access point using WifiManager instead:
private boolean checkWifiOnAndConnected() {
WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (wifiMgr.isWifiEnabled()) { // Wi-Fi adapter is ON
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
if( wifiInfo.getNetworkId() == -1 ){
return false; // Not connected to an access point
}
return true; // Connected to an access point
}
else {
return false; // Wi-Fi adapter is OFF
}
}
You can use below code for h2 and MySQl
@Query(value = "SELECT req.CREATED_AT createdAt, req.CREATED_BY createdBy,req.APP_ID appId,req.NOTE_ID noteId,req.MODEL model FROM SUMBITED_REQUESTS req inner join NOTE note where req.NOTE_ID=note.ID and note.CREATED_BY= :userId "
,
countQuery = "SELECT count(*) FROM SUMBITED_REQUESTS req inner join NOTE note WHERE req.NOTE_ID=note.ID and note.CREATED_BY=:userId",
nativeQuery = true)
Page<UserRequestsDataMapper> getAllRequestForCreator(@Param("userId") String userId,Pageable pageable);
Here's how to do it inside ViewModel
and FusedLocationProviderClient
, code in Kotlin
locationClient.lastLocation.addOnSuccessListener { location: Location? ->
location?.let {
val position = CameraPosition.Builder()
.target(LatLng(it.latitude, it.longitude))
.zoom(15.0f)
.build()
map.animateCamera(CameraUpdateFactory.newCameraPosition(position))
}
}
You can try like below
DECLARE @sqlCommand NVARCHAR(4000)
DECLARE @ID INT
DECLARE @Name NVARCHAR(100)
SET @ID = 4
SET @sqlCommand = 'SELECT @Name = [Name]
FROM [AdventureWorks2014].[HumanResources].[Department]
WHERE DepartmentID = @ID'
EXEC sp_executesql @sqlCommand, N'@ID INT, @Name NVARCHAR(100) OUTPUT',
@ID = @ID, @Name = @Name OUTPUT
SELECT @Name ReturnedName
Source : blog.sqlauthority.com
The solution is just 3 lines:
@media only screen and (max-width: 479px) {
.nav-tabs > li {
width: 100%;
}
}
..but you have to accept the idea of tabs that wrap to more lines in other dimensions.
Of course you can achieve a horizontal scrolling area with white-space: nowrap
trick but the scrollbars look ugly on desktops so you have to write js code and the whole thing starts becoming no trivial at all!
get page content by page name:
<?php
$page = get_page_by_title( 'page-name' );
$content = apply_filters('the_content', $page->post_content);
echo $content;
?>
As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.
Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.
With the repository pattern, you would only need to change one object and one repository. The impact is very small.
Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:
You have a single place to make changes to your data access
You have a single place responsible for a set of tables (usually)
It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests
There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!
Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.
If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like
double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);
(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)
I'm no expert with DOM or Javascript/Typescript but I think that the DOM-Tags can't handle real javascript object somehow. But putting the whole object in as a string and parsing it back to an Object/JSON worked for me:
interface TestObject {
name:string;
value:number;
}
@Component({
selector: 'app',
template: `
<h4>Select Object via 2-way binding</h4>
<select [ngModel]="selectedObject | json" (ngModelChange)="updateSelectedValue($event)">
<option *ngFor="#o of objArray" [value]="o | json" >{{o.name}}</option>
</select>
<h4>You selected:</h4> {{selectedObject }}
`,
directives: [FORM_DIRECTIVES]
})
export class App {
objArray:TestObject[];
selectedObject:TestObject;
constructor(){
this.objArray = [{name: 'foo', value: 1}, {name: 'bar', value: 1}];
this.selectedObject = this.objArray[1];
}
updateSelectedValue(event:string): void{
this.selectedObject = JSON.parse(event);
}
}
I know this question is very old, but I would like to add a few points, strangely omitted:
It's a bit sad that no product (I know of) documents these query fields descriptions and expressions.
after going through the HTML 5.1 ducumentation (1 November 2016):
part 4 (The elements of HTML)
chapter 2 (Document metadata)
section 4 (The link element) states that:
The destination of the link(s) is given by the
href
attribute, which must be present and must contain a valid non-empty URL potentially surrounded by spaces. If thehref
attribute is absent, then the element does not define a link.
does not contain the src
attribute ...
witch is logical because it is a link .
chapter 12 (Scripting)
section 1 (The script element) states that:
Classic scripts may either be embedded inline or may be imported from an external file using the
src
attribute, which if specified gives the URL of the external script resource to use. Ifsrc
is specified, it must be a valid non-empty URL potentially surrounded by spaces. The contents of inline script elements, or the external script resource, must conform with the requirements of the JavaScript specification’s Script production for classic scripts.
it doesn't even mention the href
attribute ...
this indicates that while using script tags always use the src
attribute !!!
chapter 7 (Embedded content)
section 5 (The img element)
The image given by the
src
andsrcset
attributes, and any previous sibling source element'ssrcset
attributes if the parent is apicture
element, is the embedded content.
also doesn't mention the href
attribute ...
this indicates that when using img
tags the src
attribute should be used aswell ...
Found one solution for WIFI (works for Android 4.3, 4.4):
Use the .date()
method to convert a datetime to a date:
if item_date.date() > from_date:
Alternatively, you could use datetime.today()
instead of date.today()
. You could use
from_date = from_date.replace(hour=0, minute=0, second=0, microsecond=0)
to eliminate the time part afterwards.
Paul Irish has a way to do this that covers most of the common problems. See his bullet-proof @font-face article:
The final variant, which stops unnecessary data from being downloaded by IE, and works in IE8, Firefox, Opera, Safari, and Chrome looks like this:
@font-face {
font-family: 'Graublau Web';
src: url('GraublauWeb.eot');
src: local('Graublau Web Regular'), local('Graublau Web'),
url("GraublauWeb.woff") format("woff"),
url("GraublauWeb.otf") format("opentype"),
url("GraublauWeb.svg#grablau") format("svg");
}
He also links to a generator that will translate the fonts into all the formats you need.
As others have already specified, this will only work in the latest generation of browsers. Your best bet is to use this in conjunction with something like Cufon, and only load Cufon if the browser doesn't support @font-face
.
The errors EXC_BAD_INSTRUCTION
and fatal error: unexpectedly found nil while implicitly unwrapping an Optional value
appears the most when you have declared an @IBOutlet
, but not connected to the storyboard.
You should also learn about how Optionals work, mentioned in other answers, but this is the only time that mostly appears to me.
Your $GOROOT
should not be set up.
You $GOPATH
should be set to $HOME/go
by typing export $GOPATH=$HOME/go
Please type export GOROOT=""
to fix your problem.
update
update
ngComponentOutlet
was added to 4.0.0-beta.3
update
There is a NgComponentOutlet
work in progress that does something similar https://github.com/angular/angular/pull/11235
RC.7
// Helper component to add dynamic components
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef;
@Input() type: Type<Component>;
cmpRef: ComponentRef<Component>;
private isViewInitialized:boolean = false;
constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler) {}
updateComponent() {
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
// when the `type` input changes we destroy a previously
// created component before creating the new one
this.cmpRef.destroy();
}
let factory = this.componentFactoryResolver.resolveComponentFactory(this.type);
this.cmpRef = this.target.createComponent(factory)
// to access the created instance use
// this.compRef.instance.someProperty = 'someValue';
// this.compRef.instance.someOutput.subscribe(val => doSomething());
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
Usage example
// Use dcl-wrapper component
@Component({
selector: 'my-tabs',
template: `
<h2>Tabs</h2>
<div *ngFor="let tab of tabs">
<dcl-wrapper [type]="tab"></dcl-wrapper>
</div>
`
})
export class Tabs {
@Input() tabs;
}
@Component({
selector: 'my-app',
template: `
<h2>Hello {{name}}</h2>
<my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
// The list of components to create tabs from
types = [C3, C1, C2, C3, C3, C1, C1];
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, DclWrapper, Tabs, C1, C2, C3],
entryComponents: [C1, C2, C3],
bootstrap: [ App ]
})
export class AppModule {}
See also angular.io DYNAMIC COMPONENT LOADER
older versions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
This changed again in Angular2 RC.5
I will update the example below but it's the last day before vacation.
This Plunker example demonstrates how to dynamically create components in RC.5
Update - use ViewContainerRef.createComponent()
Because DynamicComponentLoader
is deprecated, the approach needs to be update again.
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target;
@Input() type;
cmpRef:ComponentRef;
private isViewInitialized:boolean = false;
constructor(private resolver: ComponentResolver) {}
updateComponent() {
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
this.cmpRef.destroy();
}
this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
this.cmpRef = this.target.createComponent(factory)
// to access the created instance use
// this.compRef.instance.someProperty = 'someValue';
// this.compRef.instance.someOutput.subscribe(val => doSomething());
});
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
Plunker example RC.4
Plunker example beta.17
Update - use loadNextToLocation
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target;
@Input() type;
cmpRef:ComponentRef;
private isViewInitialized:boolean = false;
constructor(private dcl:DynamicComponentLoader) {}
updateComponent() {
// should be executed every time `type` changes but not before `ngAfterViewInit()` was called
// to have `target` initialized
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
this.cmpRef.destroy();
}
this.dcl.loadNextToLocation(this.type, this.target).then((cmpRef) => {
this.cmpRef = cmpRef;
});
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}
original
Not entirely sure from your question what your requirements are but I think this should do what you want.
The Tabs
component gets an array of types passed and it creates "tabs" for each item in the array.
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
constructor(private elRef:ElementRef, private dcl:DynamicComponentLoader) {}
@Input() type;
ngOnChanges() {
if(this.cmpRef) {
this.cmpRef.dispose();
}
this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
this.cmpRef = cmpRef;
});
}
}
@Component({
selector: 'c1',
template: `<h2>c1</h2>`
})
export class C1 {
}
@Component({
selector: 'c2',
template: `<h2>c2</h2>`
})
export class C2 {
}
@Component({
selector: 'c3',
template: `<h2>c3</h2>`
})
export class C3 {
}
@Component({
selector: 'my-tabs',
directives: [DclWrapper],
template: `
<h2>Tabs</h2>
<div *ngFor="let tab of tabs">
<dcl-wrapper [type]="tab"></dcl-wrapper>
</div>
`
})
export class Tabs {
@Input() tabs;
}
@Component({
selector: 'my-app',
directives: [Tabs]
template: `
<h2>Hello {{name}}</h2>
<my-tabs [tabs]="types"></my-tabs>
`
})
export class App {
types = [C3, C1, C2, C3, C3, C1, C1];
}
Plunker example beta.15 (not based on your Plunker)
There is also a way to pass data along that can be passed to the dynamically created component like (someData
would need to be passed like type
)
this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {
cmpRef.instance.someProperty = someData;
this.cmpRef = cmpRef;
});
There is also some support to use dependency injection with shared services.
For more details see https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html
Example for insert into values in One database table into another database table
insert into dbo.onedatabase.FolderStatus
(
[FolderStatusId],
[code],
[title],
[last_modified]
)
select [FolderStatusId], [code], [title], [last_modified]
from dbo.Twodatabase.f_file_stat
You can use SELECT @@IDENTITY as well
Use x.fullNameMethod()
to call the method.
/**
* Usage "foo baz".insertInside(4, 0, "bar ") ==> "foo bar baz"
*/
String.prototype.insertInside = function(start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
$('textarea').bind("keydown keypress", function (event) {
var val = $(this).val();
var indexOf = $(this).prop('selectionStart');
if(event.which === 13) {
val = val.insertInside(indexOf, 0, "<br>\n");
$(this).val(val);
$(this).focus();
}
})
I have a file that I need to act differently when it's included vs when it's accessed directly (mainly a print()
vs return()
) Here's some modified code:
if(count(get_included_files()) ==1) exit("Direct access not permitted.");
The file being accessed is always an included file, hence the == 1.
You could store the data in an array of strings of some large fixed size. It should be efficient to access any particular character in that array of strings, and to treat that character as a byte.
It would be interesting to see the operations you want to support, perhaps expressed as an interface, to make the question more concrete.
Use one of the the StringUtils.join methods in Apache Commons Lang.
import org.apache.commons.lang3.StringUtils;
String result = StringUtils.join(list, ", ");
If you are fortunate enough to be using Java 8, then it's even easier...just use String.join
String result = String.join(", ", list);
I had this problem because I was calling a method
await myClass.myStaticMethod(myString);
but I was setting myString with
var myString = String.Format({some dynamic-type values})
which resulted in a dynamic
type, not a string
, thus when I tried to await on myClass.myStaticMethod(myString)
, the compiler thought I meant to call myClass.myStaticMethod(dynamic myString)
. This compiled fine because, again, in a dynamic context, it's all good until it blows up at run-time, which is what happened because there is no implementation of the dynamic version of myStaticMethod
, and this error message didn't help whatsoever, and the fact that Intellisense would take me to the correct definition didn't help either.
Tricky!
However, by forcing the result type to string, like:
var myString = String.Format({some dynamic-type values})
to
string myString = String.Format({some dynamic-type values})
my call to myStaticMethod
routed properly
You can use Func<T, TResult>
generic delegate. (See MSDN)
Func<MyType, ReturnType> func = (db) => { return new MyType(); }
Also there are useful generic delegates which considers a return value:
Method:
public MyType SimpleUsing.DoUsing<MyType>(Func<TInput, MyType> myTypeFactory)
Generic delegate:
Func<InputArgumentType, MyType> createInstance = db => return new MyType();
Execute:
MyType myTypeInstance = SimpleUsing.DoUsing(
createInstance(new InputArgumentType()));
OR explicitly:
MyType myTypeInstance = SimpleUsing.DoUsing(db => return new MyType());
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
Double d = scan.nextDouble();
String newStr = "";
Scanner charScanner = new Scanner( System.in ).useDelimiter( "(\\b|\\B)" ) ;
while( charScanner.hasNext() ) {
String c = charScanner.next();
if (c.equalsIgnoreCase("\r")) {
break;
}
else {
newStr += c;
}
}
System.out.println("String: " + newStr);
System.out.println("Int: " + i);
System.out.println("Double: " + d);
This code works fine
I was inserting script
tags dynamically with this usual alternative to eval
and simply set a global property currentComponentScript
right before adding to the DOM.
const old = el.querySelector("script")[0];
const replacement = document.createElement("script");
replacement.setAttribute("type", "module");
replacement.appendChild(document.createTextNode(old.innerHTML));
window.currentComponentScript = replacement;
old.replaceWith(replacement);
Doesn't work in a loop though. The DOM doesn't run the scripts until the next macrotask so a batch of them will only see the last value set. You'd have to setTimeout
the whole paragraph, and then setTimeout
the next one after the previous finishes. I.e. chain the setTimeouts, not just call setTimeout
multiple times in a row from a loop.
String.Format("0,###.###"); also works with decimal places
Moving tables:
First run:
SELECT 'ALTER TABLE <schema_name>.' || OBJECT_NAME ||' MOVE TABLESPACE '||' <tablespace_name>; '
FROM ALL_OBJECTS
WHERE OWNER = '<schema_name>'
AND OBJECT_TYPE = 'TABLE' <> '<TABLESPACE_NAME>';
-- Or suggested in the comments (did not test it myself)
SELECT 'ALTER TABLE <SCHEMA>.' || TABLE_NAME ||' MOVE TABLESPACE '||' TABLESPACE_NAME>; '
FROM dba_tables
WHERE OWNER = '<SCHEMA>'
AND TABLESPACE_NAME <> '<TABLESPACE_NAME>
Where <schema_name>
is the name of the user.
And <tablespace_name>
is the destination tablespace.
As a result you get lines like:
ALTER TABLE SCOT.PARTS MOVE TABLESPACE USERS;
Paste the results in a script or in a oracle sql developer like application and run it.
Moving indexes:
First run:
SELECT 'ALTER INDEX <schema_name>.'||INDEX_NAME||' REBUILD TABLESPACE <tablespace_name>;'
FROM ALL_INDEXES
WHERE OWNER = '<schema_name>'
AND TABLESPACE_NAME NOT LIKE '<tablespace_name>';
The last line in this code could save you a lot of time because it filters out the indexes which are already in the correct tablespace.
As a result you should get something like:
ALTER INDEX SCOT.PARTS_NO_PK REBUILD TABLESPACE USERS;
Paste the results in a script or in a oracle sql developer like application and run it.
Last but not least, moving LOBs:
First run:
SELECT 'ALTER TABLE <schema_name>.'||LOWER(TABLE_NAME)||' MOVE LOB('||LOWER(COLUMN_NAME)||') STORE AS (TABLESPACE <table_space>);'
FROM DBA_TAB_COLS
WHERE OWNER = '<schema_name>' AND DATA_TYPE like '%LOB%';
This moves the LOB objects to the other tablespace.
As a result you should get something like:
ALTER TABLE SCOT.bin$6t926o3phqjgqkjabaetqg==$0 MOVE LOB(calendar) STORE AS (TABLESPACE USERS);
Paste the results in a script or in a oracle sql developer like application and run it.
O and there is one more thing:
For some reason I wasn't able to move 'DOMAIN' type indexes. As a work around I dropped the index. changed the default tablespace of the user into de desired tablespace. and then recreate the index again. There is propably a better way but it worked for me.
If you want a quick demo how you check for empty divs I'd suggest you to try this link:
http://html-tuts.com/check-if-html-element-is-empty-or-has-children-tags/
Below you have some short examples:
Using CSS
If your div is empty without anything even no white-space, you can use CSS:
.someDiv:empty {
display: none;
}
Unfortunately there is no CSS selector that selects the previous sibling element. There is only for the next sibling element: x ~ y
.someDiv:empty ~ .anotherDiv {
display: none;
}
Using jQuery
Checking text length of element with text() function
if ( $('#leftmenu').text().length == 0 ) {
// length of text is 0
}
Check if element has any children tags inside
if ( $('#leftmenu').children().length == 0 ) {
// div has no other tags inside it
}
Check for empty elements if they have white-space
if ( $.trim( $('.someDiv').text() ).length == 0 ) {
// white-space trimmed, div is empty
}
Three ways:
1.
int main ()
{
for (int i=2; i<100; i++)
for (int j=2; j*j<=i; j++)
{
if (i % j == 0)
break;
else if (j+1 > sqrt(i)) {
cout << i << " ";
}
}
return 0;
}
2.
int main ()
{
for (int i=2; i<100; i++)
{
bool prime=true;
for (int j=2; j*j<=i; j++)
{
if (i % j == 0)
{
prime=false;
break;
}
}
if(prime) cout << i << " ";
}
return 0;
}
3.
#include <vector>
int main()
{
std::vector<int> primes;
primes.push_back(2);
for(int i=3; i < 100; i++)
{
bool prime=true;
for(int j=0;j<primes.size() && primes[j]*primes[j] <= i;j++)
{
if(i % primes[j] == 0)
{
prime=false;
break;
}
}
if(prime)
{
primes.push_back(i);
cout << i << " ";
}
}
return 0;
}
Edit: In the third example, we keep track of all of our previously calculated primes. If a number is divisible by a non-prime number, there is also some prime <= that divisor which it is also divisble by. This reduces computation by a factor of primes_in_range/total_range.
I agree with MarsPeople regarding loading libraries in the wrong order. My example is from working with owl.carousel.
I got the same error when importing jquery after owl.carousel:
<script src="owl.carousel.js"></script>
<script src="jquery-3.1.1.min.js"></script>
and fixed it by importing jquery before owl.carousel:
<script src="jquery-3.1.1.min.js"></script>
<script src="owl.carousel.js"></script>
You can use the test construct, [[ ]]
, along with the regular expression match operator, =~
, to check if a string matches a regex pattern.
For your specific case, you can write:
[[ $date =~ ^[0-9]{8}$ ]] && echo "yes"
Or more a accurate test:
[[ $date =~ ^[0-9]{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])$ ]] && echo "yes"
# |^^^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^^^^^ ^^^^^^ |
# | | ^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^ |
# | | | | |
# | | \ | |
# | --year-- --month-- --day-- |
# | either 01...09 either 01..09 end of line
# start of line or 10,11,12 or 10..29
# or 30, 31
That is, you can define a regex in Bash matching the format you want. This way you can do:
[[ $date =~ ^regex$ ]] && echo "matched" || echo "did not match"
where commands after &&
are executed if the test is successful, and commands after ||
are executed if the test is unsuccessful.
Note this is based on the solution by Aleks-Daniel Jakimenko in User input date format verification in bash.
In other shells you can use grep. If your shell is POSIX compliant, do
(echo "$date" | grep -Eq ^regex$) && echo "matched" || echo "did not match"
In fish, which is not POSIX-compliant, you can do
echo "$date" | grep -Eq "^regex\$"; and echo "matched"; or echo "did not match"
In clausule if, use ()
.
For example:
stringtorray = "xxxx,yyyyy,zzzzz";
if (xxx && (stringtoarray.split(',') + "")) { ...
Why don't you strip out the <div>
element and replace it with an <a>
instead? Just because the anchor tag isn't a div doesn't mean you can't style it with display:block
, a height, width, background, border, etc. You can make it look like a div but still act like a link. Then you're not relying on invalid code or JavaScript that may not be enabled for some users.
You can use the Like
operator with a wildcard to determine whether a given substring exists in a string, for example:
If cell.Value Like "*Word1*" Then
'...
ElseIf cell.Value Like "*Word2*" Then
'...
End If
In this example the *
character in "*Word1*"
is a wildcard character which matches zero or more characters.
NOTE: The Like
operator is case-sensitive, so "Word1" Like "word1"
is false, more information can be found on this MSDN page.
The Best solution is this badass one-liner:
String hex=DatatypeConverter.printHexBinary(byte[] b);
as mentioned here
Ermh... Came along here with exactly the same problem: Test a simple, but pivotal private method. After reading this thread, it appears to be like "I want to drill this simple hole in this simple piece of metal, and I want to make sure the quality meets the specs", and then comes "Okay, this is not to easy. First of all, there is no proper tool to do so, but you could build a gravitational-wave observatory in your garden. Read my article at http://foobar.brigther-than-einstein.org/ First, of course, you have to attend some advanced quantum physics courses, then you need tons of ultra-cool nitrogenium, and then, of course, my book available at Amazon"...
In other words...
No, first things first.
Each and every method, may it private, internal, protected, public has to be testable. There has to be a way to implement such tests without such ado as was presented here.
Why? Exactly because of the architectural mentions done so far by some contributors. Perhaps a simple reiteration of software principles may clear up some missunderstandings.
In this case, the usual suspects are: OCP, SRP, and, as always, KIS.
But wait a minute. The idea of making everything publicly available is more of less political and a kind of an attitude. But. When it comes to code, even in then Open Source Community, this is no dogma. Instead, "hiding" something is good practice to make it easier to come familiar with a certain API. You would hide, for example, the very core calculations of your new-to-market digital thermometer building block--not to hide the maths behind the real measured curve to curious code readers, but to prevent your code from becoming dependent on some, perhaps suddenly important users who could not resist using your formerly private, internal, protected code to implement their own ideas.
What am I talking about?
private double TranslateMeasurementIntoLinear(double actualMeasurement);
It's easy to proclaim the Age of Aquarius or what is is been called nowadays, but if my piece of sensor gets from 1.0 to 2.0, the implementation of Translate... might change from a simple linear equation that is easily understandable and "re-usable" for everybody, to a pretty sophisticated calculation that uses analysis or whatever, and so I would break other's code. Why? Because they didn't understand the very priciples of software coding, not even KIS.
To make this fairy tale short: We need a simple way to test private methods--without ado.
First: Happy new year everyone!
Second: Rehearse your architect lessons.
Third: The "public" modifier is religion, not a solution.
You'll need to also set the height of the element to 0 when it's hidden. I ran into this problem while using jQuery, my solution was to set the height and opacity to 0 when it's hidden, then change height to auto and opacity to 1 when it's un-hidden.
I'd recommend looking at jQuery. It's pretty easy to pick up and will allow you to do things like this a lot more easily.
$('#yesCheck').click(function() {
$('#ifYes').slideDown();
});
$('#noCheck').click(function() {
$('#ifYes').slideUp();
});
It's slightly better for performance to change the CSS with jQuery and use CSS3 animations to do the dropdown, but that's also more complex. The example above should work, but I haven't tested it.
if (empty($_FILES['cover_image']['name']))
This work for me.
Syntax : ssh -i pemfile.pem user_name@ip_address 'command_1 ; command 2; command 3'
#! /bin/bash
echo "########### connecting to server and run commands in sequence ###########"
ssh -i ~/.ssh/ec2_instance.pem ubuntu@ip_address 'touch a.txt; touch b.txt; sudo systemctl status tomcat.service'
JavaScript code using ng-controller:
$scope.checkkey = function (event) {
alert(event.keyCode); //this will show the ASCII value of the key pressed
}
In HTML:
<input type="text" ng-keypress="checkkey($event)" />
You can now place your checks and other conditions using the keyCode method.
recently I needed such functionality, I was porting Zend Framework Credit Card Validator to ruby. ruby gem: https://github.com/Fivell/credit_card_validations zend framework: https://github.com/zendframework/zf2/blob/master/library/Zend/Validator/CreditCard.php
They both use INN ranges for detecting type. Here you can read about INN
According to this you can detect credit card alternatively (without regexps,but declaring some rules about prefixes and possible length)
So we have next rules for most used cards
######## most used brands #########
visa: [
{length: [13, 16], prefixes: ['4']}
],
mastercard: [
{length: [16], prefixes: ['51', '52', '53', '54', '55']}
],
amex: [
{length: [15], prefixes: ['34', '37']}
],
######## other brands ########
diners: [
{length: [14], prefixes: ['300', '301', '302', '303', '304', '305', '36', '38']},
],
#There are Diners Club (North America) cards that begin with 5. These are a joint venture between Diners Club and MasterCard, and are processed like a MasterCard
# will be removed in next major version
diners_us: [
{length: [16], prefixes: ['54', '55']}
],
discover: [
{length: [16], prefixes: ['6011', '644', '645', '646', '647', '648',
'649', '65']}
],
jcb: [
{length: [16], prefixes: ['3528', '3529', '353', '354', '355', '356', '357', '358', '1800', '2131']}
],
laser: [
{length: [16, 17, 18, 19], prefixes: ['6304', '6706', '6771']}
],
solo: [
{length: [16, 18, 19], prefixes: ['6334', '6767']}
],
switch: [
{length: [16, 18, 19], prefixes: ['633110', '633312', '633304', '633303', '633301', '633300']}
],
maestro: [
{length: [12, 13, 14, 15, 16, 17, 18, 19], prefixes: ['5010', '5011', '5012', '5013', '5014', '5015', '5016', '5017', '5018',
'502', '503', '504', '505', '506', '507', '508',
'6012', '6013', '6014', '6015', '6016', '6017', '6018', '6019',
'602', '603', '604', '605', '6060',
'677', '675', '674', '673', '672', '671', '670',
'6760', '6761', '6762', '6763', '6764', '6765', '6766', '6768', '6769']}
],
# Luhn validation are skipped for union pay cards because they have unknown generation algoritm
unionpay: [
{length: [16, 17, 18, 19], prefixes: ['622', '624', '625', '626', '628'], skip_luhn: true}
],
dankrot: [
{length: [16], prefixes: ['5019']}
],
rupay: [
{length: [16], prefixes: ['6061', '6062', '6063', '6064', '6065', '6066', '6067', '6068', '6069', '607', '608'], skip_luhn: true}
]
}
Then by searching prefix and comparing length you can detect credit card brand. Also don't forget about luhn algoritm (it is descibed here http://en.wikipedia.org/wiki/Luhn).
UPDATE
updated list of rules can be found here https://raw.githubusercontent.com/Fivell/credit_card_validations/master/lib/data/brands.yaml
We faced the same problem:
ORA-29913: error in executing ODCIEXTTABLEOPEN callout
ORA-29400: data cartridge error error opening file /fs01/app/rms01/external/logs/SH_EXT_TAB_VGAG_DELIV_SCHED.log
In our case we had a RAC with 2 nodes. After giving write permission on the log directory, on both sides, everything worked fine.
Ideone supports Python 2.6 and Python 3
Both the data import function (here: read.csv()
) as well as a global option offer you to say stringsAsFactors=FALSE
which should fix this.
I had lots of duplicate column names, and once I ran
df = df.loc[:,~df.columns.duplicated()]
I was able to see the full list of columns
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
xlWorkSheet.Cells(1, 1).Borders(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlDataBarBorderType.xlDataBarBorderSolid
There are several ways to use gitignore git
just create a .gitignore file and write in whatever you want to ignore a sample gitignore file would be:
# NPM packages folder.
node_modules
# Build files
dist/
# lock files
yarn.lock
package-lock.json
# Logs
logs
*.log
npm-debug.log*
# node-waf configuration
.lock-wscript
# Optional npm cache directory
.npm
# Optional REPL history
.node_repl_history
# Jest Coverage
coverage
.history/
You can find more on git documentation gitignore
If you see this error when running tests, make sure you have imported the module the pipe belongs to, e.g.:
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [CustomPipeModule],
declarations: [...],
providers: [...],
...
}).compileComponents();
}));
You can factor out your common logic to a private method, for example called Initialize
that gets called from both constructors.
Due to the fact that you want to perform argument validation you cannot resort to constructor chaining.
Example:
public Point2D(double x, double y)
{
// Contracts
Initialize(x, y);
}
public Point2D(Point2D point)
{
if (point == null)
throw new ArgumentNullException("point");
// Contracts
Initialize(point.X, point.Y);
}
private void Initialize(double x, double y)
{
X = x;
Y = y;
}
You are debugging two or more times. so the application may run more at a time. Then only this issue will occur. You should close all debugging applications using task-manager, Then debug again.
This jQuery plugin (jQuery File Upload Demo) does it without flash, in the form it's using:
<input type='file' name='files[]' multiple />
The following will work for a DateTime that has fractional milliseconds, and also preserves the Kind property (Local, Utc or Undefined).
DateTime dateTime = ... anything ...
dateTime = new DateTime(
dateTime.Ticks - (dateTime.Ticks % TimeSpan.TicksPerSecond),
dateTime.Kind
);
or the equivalent and shorter:
dateTime = dateTime.AddTicks( - (dateTime.Ticks % TimeSpan.TicksPerSecond));
This could be generalized into an extension method:
public static DateTime Truncate(this DateTime dateTime, TimeSpan timeSpan)
{
if (timeSpan == TimeSpan.Zero) return dateTime; // Or could throw an ArgumentException
if (dateTime == DateTime.MinValue || dateTime == DateTime.MaxValue) return dateTime; // do not modify "guard" values
return dateTime.AddTicks(-(dateTime.Ticks % timeSpan.Ticks));
}
which is used as follows:
dateTime = dateTime.Truncate(TimeSpan.FromMilliseconds(1)); // Truncate to whole ms
dateTime = dateTime.Truncate(TimeSpan.FromSeconds(1)); // Truncate to whole second
dateTime = dateTime.Truncate(TimeSpan.FromMinutes(1)); // Truncate to whole minute
...
In case you want to format number for view rather than for calculation you can use this
function numberFormat( number ){
var digitCount = (number+"").length;
var formatedNumber = number+"";
var ind = digitCount%3 || 3;
var temparr = formatedNumber.split('');
if( digitCount > 3 && digitCount <= 6 ){
temparr.splice(ind,0,',');
formatedNumber = temparr.join('');
}else if (digitCount >= 7 && digitCount <= 15) {
var temparr2 = temparr.slice(0, ind);
temparr2.push(',');
temparr2.push(temparr[ind]);
temparr2.push(temparr[ind + 1]);
// temparr2.push( temparr[ind + 2] );
if (digitCount >= 7 && digitCount <= 9) {
temparr2.push(" million");
} else if (digitCount >= 10 && digitCount <= 12) {
temparr2.push(" billion");
} else if (digitCount >= 13 && digitCount <= 15) {
temparr2.push(" trillion");
}
formatedNumber = temparr2.join('');
}
return formatedNumber;
}
Input: {Integer} Number
Outputs: {String} Number
22,870 => if number 22870
22,87 million => if number 2287xxxx (x can be whatever)
22,87 billion => if number 2287xxxxxxx
22,87 trillion => if number 2287xxxxxxxxxx
You get the idea
and just FYI, in case you do all of your data reference checks and find no bad data...apparently it is not possible to create a foreign key constraint between two tables and fields where those fields are the primary key in both tables! Do not ask me how I know this.
This is microsoft's page on the location
tag: http://msdn.microsoft.com/en-us/library/b6x6shw7%28v=vs.100%29.aspx
It may be helpful to some folks.
You don't need to store the column to reference it that way. Try this:
To set up:
CREATE TABLE tbl
(zipcode text NOT NULL, city text NOT NULL, state text NOT NULL);
INSERT INTO tbl VALUES ('10954', 'Nanuet', 'NY');
We can see we have "the right stuff":
\pset border 2
SELECT * FROM tbl;
+---------+--------+-------+ | zipcode | city | state | +---------+--------+-------+ | 10954 | Nanuet | NY | +---------+--------+-------+
Now add a function with the desired "column name" which takes the record type of the table as its only parameter:
CREATE FUNCTION combined(rec tbl)
RETURNS text
LANGUAGE SQL
AS $$
SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
$$;
This creates a function which can be used as if it were a column of the table, as long as the table name or alias is specified, like this:
SELECT *, tbl.combined FROM tbl;
Which displays like this:
+---------+--------+-------+--------------------+ | zipcode | city | state | combined | +---------+--------+-------+--------------------+ | 10954 | Nanuet | NY | 10954 - Nanuet, NY | +---------+--------+-------+--------------------+
This works because PostgreSQL checks first for an actual column, but if one is not found, and the identifier is qualified with a relation name or alias, it looks for a function like the above, and runs it with the row as its argument, returning the result as if it were a column. You can even index on such a "generated column" if you want to do so.
Because you're not using extra space in each row for the duplicated data, or firing triggers on all inserts and updates, this can often be faster than the alternatives.
How to convert date to string and to date again?
LocalDate.now().toString()
2017-01-23
…and…
LocalDate.parse( "2017-01-23" )
The Question uses troublesome old date-time classes bundled with the earliest versions of Java. Those classes are now legacy, supplanted by the java.time classes built into Java 8, Java 9, and later.
Determining today’s date requires a time zone. For any given moment the date varies around the globe by zone.
If not supplied by you, your JVM’s current default time zone is applied. That default can change at any moment during runtime, and so is unreliable. I suggest you always specify your desired/expected time zone.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate ld = LocalDate.now( z ) ;
Your desired format of YYYY-MM-DD happens to comply with the ISO 8601 standard.
That standard happens to be used by default by the java.time classes when parsing/generating strings. So you can simply call LocalDate::parse
and LocalDate::toString
without specifying a formatting pattern.
String s = ld.toString() ;
To parse:
LocalDate ld = LocalDate.parse( s ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
You can achieve this with the display
property:
html, body {
height:100%;
margin:0;
padding:0;
}
#section1 {
width:100%; /*full width*/
min-height:90%;
text-align:center;
display:table; /*acts like a table*/
}
h1{
margin:0;
padding:0;
vertical-align:middle; /*middle centred*/
display:table-cell; /*acts like a table cell*/
}
Had a similar question and had difficulty finding an answer. The following function allows you to paste an image with a transparency parameter over another image at a specific offset.
import Image
def trans_paste(fg_img,bg_img,alpha=1.0,box=(0,0)):
fg_img_trans = Image.new("RGBA",fg_img.size)
fg_img_trans = Image.blend(fg_img_trans,fg_img,alpha)
bg_img.paste(fg_img_trans,box,fg_img_trans)
return bg_img
bg_img = Image.open("bg.png")
fg_img = Image.open("fg.png")
p = trans_paste(fg_img,bg_img,.7,(250,100))
p.show()
Check out this GitHub repository that describes best practices for AngularJS apps. It has naming conventions for different components. It is not complete, but it is community-driven so everyone can contribute.
There's a shorthand-type way to do this that I have been using recently. This might need to be configured, but it should work in most mainline PHP installations. If you're storing the link in a PHP variable, you can do it in the following manner based off the OP:
<html>
<body>
<?php
$link = "http://www.google.com";
?>
<a href="<?= $link ?>">Click here to go to Google.</a>
</body>
</html>
This will evaluate the variable as a string, in essence shorthand for echo $link;
You can avoid compilation errors if you remove the method definitions from the header files and let the classes contain only the method declarations and variable declarations/definitions. The method definitions should be placed in a .cpp file (just like a best practice guideline says).
The down side of the following solution is (assuming that you had placed the methods in the header file to inline them) that the methods are no longer inlined by the compiler and trying to use the inline keyword produces linker errors.
//A.h
#ifndef A_H
#define A_H
class B;
class A
{
int _val;
B* _b;
public:
A(int val);
void SetB(B *b);
void Print();
};
#endif
//B.h
#ifndef B_H
#define B_H
class A;
class B
{
double _val;
A* _a;
public:
B(double val);
void SetA(A *a);
void Print();
};
#endif
//A.cpp
#include "A.h"
#include "B.h"
#include <iostream>
using namespace std;
A::A(int val)
:_val(val)
{
}
void A::SetB(B *b)
{
_b = b;
cout<<"Inside SetB()"<<endl;
_b->Print();
}
void A::Print()
{
cout<<"Type:A val="<<_val<<endl;
}
//B.cpp
#include "B.h"
#include "A.h"
#include <iostream>
using namespace std;
B::B(double val)
:_val(val)
{
}
void B::SetA(A *a)
{
_a = a;
cout<<"Inside SetA()"<<endl;
_a->Print();
}
void B::Print()
{
cout<<"Type:B val="<<_val<<endl;
}
//main.cpp
#include "A.h"
#include "B.h"
int main(int argc, char* argv[])
{
A a(10);
B b(3.14);
a.Print();
a.SetB(&b);
b.Print();
b.SetA(&a);
return 0;
}
The XML declaration in the document map consists of the following:
The version number, ?xml version="1.0"?.
This is mandatory. Although the number might change for future versions of XML, 1.0 is the current version.
The encoding declaration,
encoding="UTF-8"?
This is optional. If used, the encoding declaration must appear immediately after the version information in the XML declaration, and must contain a value representing an existing character encoding.
If you use Python from MacPorts, it has it's own easy_install located at: /opt/local/bin/easy_install-2.6 (for py26, that is). It's not the same one as simply calling easy_install directly, even if you used python_select to change your default python command.