google the javascript same origin policy
in a nutshell, the url you are trying to use must have the same root and protocol. so http://yoursite.com cannot access https://yoursite.com or http://anothersite.com
is you absolutely MUST bypass this protection (which is at the browser level, as galimy pointed out), consider the ProxyPass module for your favorite web server.
First all need to do is start hadoop nodes and Trackers, simply by typing start-all.sh on ur terminal. To check all the trackers and nodes are started write 'jps' command. if everything is fine and working, go to your browser type the following url http://localhost:50070
Can't you surround it with an a tag?
<a href="#"><div id="buttonOne">
<div id="linkedinB">
<img src="img/linkedinB.png" width="40" height="40">
</div>
</div></a>
I hate when sites complicate download so much and use hacks instead of a good old link.
<a href="file.zip">Start automatic download!</a>
It works! In every browser!
If you want to download a file that is usually displayed inline (such as an image) then HTML5 has a download
attribute that forces download of the file. It also allows you to override filename (although there is a better way to do it):
<a href="report-generator.php" download="result.xls">Download</a>
If you want to display "thanks" after download, then use:
<a href="file.zip"
onclick="if (event.button==0)
setTimeout(function(){document.body.innerHTML='thanks!'},500)">
Start automatic download!
</a>
Function in that setTimeout
might be more advanced and e.g. download full page via AJAX (but don't navigate away from the page — don't touch window.location
or activate other links).
The point is that link to download is real, can be copied, dragged, intercepted by download accelerators, gets :visited
color, doesn't re-download if page is left open after browser restart, etc.
There are a many ways to create your objects in JavaScript. Using a constructer function to create an object or object literal notation is using alot in JavaScript. Also creating an instance of Object and then adding properties and methods to it, there are three common ways to do create objects in JavaScript.
Constructer functions
There are built-in constructer functions that we all may use them time to time, like Date(), Number(), Boolean() etc, all constructer functions start with Capital letter, in the meantime we can create custom constructor function in JavaScript like this:
function Box (Width, Height, fill) {
this.width = Width; // The width of the box
this.height = Height; // The height of the box
this.fill = true; // Is it filled or not?
}
and you can invoke it, simply using new(), to create a new instance of the constructor, create something like below and call the constructor function with filled parameters:
var newBox = new Box(8, 12, true);
Object literals
Using object literals are very used case creating object in JavaScript, this an example of creating a simple object, you can assign anything to your object properties as long as they are defined:
var person = {
name: "Alireza",
surname: "Dezfoolian"
nose: 1,
feet: 2,
hands: 2,
cash: null
};
Prototyping
After creating an Object, you can prototype more members to that, for example adding colour to our Box, we can do this:
Box.prototype.colour = 'red';
It basically means that the application wants to perform some "naming operations" (e.g. JNDI or LDAP lookups), and it didn't have sufficient information available to be able to create a connection to the directory server. As the docs for the exception state,
This exception is thrown when no initial context implementation can be created. The policy of how an initial context implementation is selected is described in the documentation of the InitialContext class.
And if you dutifully have a look at the javadocs for InitialContext, they describe quite well how the initial context is constructed, and what your options are for supplying the address/credentials/etc.
If you have a go at creating the context and get stuck somewhere else, please post back explaining what you've done so far and where you're running aground.
Realization single and double click
public abstract class DoubleClickListener implements View.OnClickListener {
private static final long DOUBLE_CLICK_TIME_DELTA = 200;
private long lastClickTime = 0;
private View view;
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
@Override
public void run() {
onSingleClick(view);
}
};
private void runTimer(){
handler.removeCallbacks(runnable);
handler.postDelayed(runnable,DOUBLE_CLICK_TIME_DELTA);
}
@Override
public void onClick(View view) {
this.view = view;
long clickTime = System.currentTimeMillis();
if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA){
handler.removeCallbacks(runnable);
lastClickTime = 0;
onDoubleClick(view);
} else {
runTimer();
lastClickTime = clickTime;
}
}
public abstract void onSingleClick(View v);
public abstract void onDoubleClick(View v);
}
Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) are N-dimensional. Matrix objects are a subclass of ndarray, so they inherit all the attributes and methods of ndarrays.
The main advantage of numpy matrices is that they provide a convenient notation
for matrix multiplication: if a and b are matrices, then a*b
is their matrix
product.
import numpy as np
a = np.mat('4 3; 2 1')
b = np.mat('1 2; 3 4')
print(a)
# [[4 3]
# [2 1]]
print(b)
# [[1 2]
# [3 4]]
print(a*b)
# [[13 20]
# [ 5 8]]
On the other hand, as of Python 3.5, NumPy supports infix matrix multiplication using the @
operator, so you can achieve the same convenience of matrix multiplication with ndarrays in Python >= 3.5.
import numpy as np
a = np.array([[4, 3], [2, 1]])
b = np.array([[1, 2], [3, 4]])
print(a@b)
# [[13 20]
# [ 5 8]]
Both matrix objects and ndarrays have .T
to return the transpose, but matrix
objects also have .H
for the conjugate transpose, and .I
for the inverse.
In contrast, numpy arrays consistently abide by the rule that operations are
applied element-wise (except for the new @
operator). Thus, if a
and b
are numpy arrays, then a*b
is the array
formed by multiplying the components element-wise:
c = np.array([[4, 3], [2, 1]])
d = np.array([[1, 2], [3, 4]])
print(c*d)
# [[4 6]
# [6 4]]
To obtain the result of matrix multiplication, you use np.dot
(or @
in Python >= 3.5, as shown above):
print(np.dot(c,d))
# [[13 20]
# [ 5 8]]
The **
operator also behaves differently:
print(a**2)
# [[22 15]
# [10 7]]
print(c**2)
# [[16 9]
# [ 4 1]]
Since a
is a matrix, a**2
returns the matrix product a*a
.
Since c
is an ndarray, c**2
returns an ndarray with each component squared
element-wise.
There are other technical differences between matrix objects and ndarrays
(having to do with np.ravel
, item selection and sequence behavior).
The main advantage of numpy arrays is that they are more general than 2-dimensional matrices. What happens when you want a 3-dimensional array? Then you have to use an ndarray, not a matrix object. Thus, learning to use matrix objects is more work -- you have to learn matrix object operations, and ndarray operations.
Writing a program that mixes both matrices and arrays makes your life difficult because you have to keep track of what type of object your variables are, lest multiplication return something you don't expect.
In contrast, if you stick solely with ndarrays, then you can do everything matrix objects can do, and more, except with slightly different functions/notation.
If you are willing to give up the visual appeal of NumPy matrix product notation (which can be achieved almost as elegantly with ndarrays in Python >= 3.5), then I think NumPy arrays are definitely the way to go.
PS. Of course, you really don't have to choose one at the expense of the other,
since np.asmatrix
and np.asarray
allow you to convert one to the other (as
long as the array is 2-dimensional).
There is a synopsis of the differences between NumPy arrays
vs NumPy matrix
es here.
None of these did exactly what I needed, to force 2 d.p. and round up as 0.005 -> 0.01
Forcing 2 d.p. requires increasing the precision by 2 d.p. to ensure we have at least 2 d.p.
then rounding to ensure we do not have more than 2 d.p.
Math.Round(exactResult * 1.00m, 2, MidpointRounding.AwayFromZero)
6.665m.ToString() -> "6.67"
6.6m.ToString() -> "6.60"
I had incorrectly typed in the address as
http://addressOfProxy.8080
instead of
http://addressOfProxy:8080
(Notice the colon before the port number 8080.)
Lets consider you have a class name named Products and you have a IsActive field. just you need a create constructor :
Public class Products
{
public Products()
{
IsActive = true;
}
public string Field1 { get; set; }
public string Field2 { get; set; }
public bool IsActive { get; set; }
}
Then your IsActive default value is True!
Edite :
if you want to do this with SQL use this command :
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.IsActive)
.HasDefaultValueSql("true");
}
I tried this:
label1.Content = Directory.GetCurrentDirectory();
and get also the directory.
I've been trying to do something very similar but not using the nodes. However, my xml structure is a little different.
You have it like this:
<Metrics>
<Metric id="TransactionCleanupThread.RefundOldTrans" type="timer" ...>
If it were like this instead:
<Metrics>
<Metric>
<id>TransactionCleanupThread.RefundOldTrans</id>
<type>timer</type>
.
.
.
Then you could simply use this SQL statement.
SELECT
Sqm.SqmId,
Data.value('(/Sqm/Metrics/Metric/id)[1]', 'varchar(max)') as id,
Data.value('(/Sqm/Metrics/Metric/type)[1]', 'varchar(max)') AS type,
Data.value('(/Sqm/Metrics/Metric/unit)[1]', 'varchar(max)') AS unit,
Data.value('(/Sqm/Metrics/Metric/sum)[1]', 'varchar(max)') AS sum,
Data.value('(/Sqm/Metrics/Metric/count)[1]', 'varchar(max)') AS count,
Data.value('(/Sqm/Metrics/Metric/minValue)[1]', 'varchar(max)') AS minValue,
Data.value('(/Sqm/Metrics/Metric/maxValue)[1]', 'varchar(max)') AS maxValue,
Data.value('(/Sqm/Metrics/Metric/stdDeviation)[1]', 'varchar(max)') AS stdDeviation,
FROM Sqm
To me this is much less confusing than using the outer apply or cross apply.
I hope this helps someone else looking for a simpler solution!
This is very simple if you are not using SQLite:
You can delete the SQLite DLLs from your solution's bin folders, then from the folder where you reference ELMAH. Rebuild, and your app won't try to load this DLL that you are not using.
In a new sheet (where you want to create a new pivot table) press the key combination (Alt+D+P). In the list of data source options choose "Microsoft Excel list of database". Click Next and select the pivot table that you want to use as a source (select starting with the actual headers of the fields). I assume that this range is rather static and if you refresh the source pivot and it changes it's size you would have to re-size the range as well. Hope this helps.
This was the only way I could get this to work
add_action('init','add_query_args');
function add_query_args()
{
add_query_arg( 'var1', 'val1' );
}
Check this link for steps on how to install express.js for your application locally.
But, if for some reason you are installing express globally, make sure the directory you are in is the directory where Node is installed. On my Windows 10, package.json is located at
C:\Program Files\nodejs\node_modules\npm
Open command prompt as administrator and change your directory to the location where your package.json is located.
Then issue the install command.
The exact code will vary for each of the columns you want to do, but it's likely you'll want to use the map
and apply
functions. In some cases you can just compute using the existing columns directly, since the columns are Pandas Series objects, which also work as Numpy arrays, which automatically work element-wise for usual mathematical operations.
>>> d
A B C
0 11 13 5
1 6 7 4
2 8 3 6
3 4 8 7
4 0 1 7
>>> (d.A + d.B) / d.C
0 4.800000
1 3.250000
2 1.833333
3 1.714286
4 0.142857
>>> d.A > d.C
0 True
1 True
2 True
3 False
4 False
If you need to use operations like max and min within a row, you can use apply
with axis=1
to apply any function you like to each row. Here's an example that computes min(A, B)-C
, which seems to be like your "lower wick":
>>> d.apply(lambda row: min([row['A'], row['B']])-row['C'], axis=1)
0 6
1 2
2 -3
3 -3
4 -7
Hopefully that gives you some idea of how to proceed.
Edit: to compare rows against neighboring rows, the simplest approach is to slice the columns you want to compare, leaving off the beginning/end, and then compare the resulting slices. For instance, this will tell you for which rows the element in column A is less than the next row's element in column C:
d['A'][:-1] < d['C'][1:]
and this does it the other way, telling you which rows have A less than the preceding row's C:
d['A'][1:] < d['C'][:-1]
Doing ['A"][:-1]
slices off the last element of column A, and doing ['C'][1:]
slices off the first element of column C, so when you line these two up and compare them, you're comparing each element in A with the C from the following row.
The answers as they are require you to add code to the spawned window. That is unnecessary coupling.
// In parent window
var pop = open(url);
pop.onunload = function() {
// Run your code, the popup window is unloading
// Beware though, this will also fire if the user navigates to a different
// page within thepopup. If you need to support that, you will have to play around
// with pop.closed and setTimeouts
}
Although it's not a command line solution, it may help macos
users:
This is because of a higher JDK during compile time and lower JDK during runtime. So you just need to update your JDK version, possible to JDK 7
You may also check Unsupported major.minor version 51.0
I don't know why but for me text-align:center;
only works with:
text-align: grid;
OR
display: inline-grid;
I checked and no one style is overriding.
My structure:
<ul>
<li>
<a>ElementToCenter</a>
</li>
</ul>
The explanation that none of the other answers supplies is that the original arguments are still available, but not in the original position in the arguments
object.
The arguments
object contains one element for each actual parameter provided to the function. When you call a
you supply three arguments: the numbers 1
, 2
, and, 3
. So, arguments
contains [1, 2, 3]
.
function a(args){
console.log(arguments) // [1, 2, 3]
b(arguments);
}
When you call b
, however, you pass exactly one argument: a
's arguments
object. So arguments
contains [[1, 2, 3]]
(i.e. one element, which is a
's arguments
object, which has properties containing the original arguments to a
).
function b(args){
// arguments are lost?
console.log(arguments) // [[1, 2, 3]]
}
a(1,2,3);
As @Nick demonstrated, you can use apply
to provide a set arguments
object in the call.
The following achieves the same result:
function a(args){
b(arguments[0], arguments[1], arguments[2]); // three arguments
}
But apply
is the correct solution in the general case.
This helped and it supports a BLOB/TEXT columns.
CREATE TEMPORARY TABLE temp_table
AS
SELECT * FROM source_table WHERE id=2;
UPDATE temp_table SET id=NULL WHERE id=2;
INSERT INTO source_table SELECT * FROM temp_table;
DROP TEMPORARY TABLE temp_table;
USE source_table;
I normally use another way to do the same
using System.Xml;
using System.Net;
using System.IO;
public static void CallWebService()
{
var _url = "http://xxxxxxxxx/Service1.asmx";
var _action = "http://xxxxxxxx/Service1.asmx?op=HelloWorld";
XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelopeDocument = new XmlDocument();
soapEnvelopeDocument.LoadXml(
@"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/1999/XMLSchema"">
<SOAP-ENV:Body>
<HelloWorld xmlns=""http://tempuri.org/""
SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">
<int1 xsi:type=""xsd:integer"">12</int1>
<int2 xsi:type=""xsd:integer"">32</int2>
</HelloWorld>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>");
return soapEnvelopeDocument;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
It is very simple
public void onClick(View v) {
imgButton.setImageResource(R.drawable.ic_launcher);
}
Using set Background image resource will chanage the background of the button
marshaller.setProperty
only works on the JAX-B marshaller from Sun. The question was regarding the JAX-B marshaller from SpringSource
, which does not support setProperty
.
You can use default primary key (id) which auto increaments.
Note: When you use first design i.e. use default field (id) as a primary key, initialize object by mentioning column names. e.g.
class User(models.Model):
user_name = models.CharField(max_length = 100)
then initialize,
user = User(user_name="XYZ")
if you initialize in following way,
user = User("XYZ")
then python will try to set id = "XYZ" which will give you error on data type.
Assuming your Generic List is of type String:
TextWriter tw = new StreamWriter("SavedList.txt");
foreach (String s in Lists.verbList)
tw.WriteLine(s);
tw.Close();
Alternatively, with the using keyword:
using(TextWriter tw = new StreamWriter("SavedList.txt"))
{
foreach (String s in Lists.verbList)
tw.WriteLine(s);
}
From the grep(1)
man page:
-l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match. (-l is specified by POSIX.)
So to make your expression work, changing &&
for -a
will do the trick.
It is correct like this:
if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
then ....
or like
if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
then ....
or even
if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
then ....
You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.
Paul's answer creates a new repository containing /ABC, but does not remove /ABC from within /XYZ. The following command will remove /ABC from within /XYZ:
git filter-branch --tree-filter "rm -rf ABC" --prune-empty HEAD
Of course, test it in a 'clone --no-hardlinks' repository first, and follow it with the reset, gc and prune commands Paul lists.
# file? will only return true for files
File.file?(filename)
and
# Will also return true for directories - watch out!
File.exist?(filename)
Why are you sending it through a post if you already have it on the server (PHP) side?
Why not just save the array to s $_SESSION
variable so you can use it when the form gets submitted, that might make it more "secure" since then the client cannot change the variables by editing the source.
It all depends on what you really want to do.
This needs bash 4.1 if you use
{fd}
orlocal -n
.The rest should work in bash 3.x I hope. I am not completely sure due to
printf %q
- this might be a bash 4 feature.
Your example can be modified as follows to archive the desired effect:
# Add following 4 lines:
_passback() { while [ 1 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; return $1; }
passback() { _passback "$@" "$?"; }
_capture() { { out="$("${@:2}" 3<&-; "$2_" >&3)"; ret=$?; printf "%q=%q;" "$1" "$out"; } 3>&1; echo "(exit $ret)"; }
capture() { eval "$(_capture "$@")"; }
e=2
# Add following line, called "Annotation"
function test1_() { passback e; }
function test1() {
e=4
echo "hello"
}
# Change following line to:
capture ret test1
echo "$ret"
echo "$e"
prints as desired:
hello
4
Note that this solution:
e=1000
, too.$?
if you need $?
The only bad sideffects are:
bash
._
)_capture
just replace all occurances of 3
with another (higher) number.The following (which is quite long, sorry for that) hopefully explains, how to adpot this recipe to other scripts, too.
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
d1=$(d)
d2=$(d)
d3=$(d)
d4=$(d)
echo $x $d1 $d2 $d3 $d4
outputs
0 20171129-123521 20171129-123521 20171129-123521 20171129-123521
while the wanted output is
4 20171129-123521 20171129-123521 20171129-123521 20171129-123521
Shell variables (or generally speaking, the environment) is passed from parental processes to child processes, but not vice versa.
If you do output capturing, this usually is run in a subshell, so passing back variables is difficult.
Some even tell you, that it is impossible to fix. This is wrong, but it is a long known difficult to solve problem.
There are several ways on how to solve it best, this depends on your needs.
Here is a step by step guide on how to do it.
There is a way to pass back variables to a parental shell. However this is a dangerous path, because this uses eval
. If done improperly, you risk many evil things. But if done properly, this is perfectly safe, provided that there is no bug in bash
.
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
d() { let x++; d=$(date +%Y%m%d-%H%M%S); _passback x d; }
x=0
eval `d`
d1=$d
eval `d`
d2=$d
eval `d`
d3=$d
eval `d`
d4=$d
echo $x $d1 $d2 $d3 $d4
prints
4 20171129-124945 20171129-124945 20171129-124945 20171129-124945
Note that this works for dangerous things, too:
danger() { danger="$*"; passback danger; }
eval `danger '; /bin/echo *'`
echo "$danger"
prints
; /bin/echo *
This is due to printf '%q'
, which quotes everything such, that you can re-use it in a shell context safely.
This does not only look ugly, it also is much to type, so it is error prone. Just one single mistake and you are doomed, right?
Well, we are at shell level, so you can improve it. Just think about an interface you want to see, and then you can implement it.
Let's go a step back and think about some API which allows us to easily express, what we want to do.
Well, what do we want do do with the d()
function?
We want to capture the output into a variable. OK, then let's implement an API for exactly this:
# This needs a modern bash 4.3 (see "help declare" if "-n" is present,
# we get rid of it below anyway).
: capture VARIABLE command args..
capture()
{
local -n output="$1"
shift
output="$("$@")"
}
Now, instead of writing
d1=$(d)
we can write
capture d1 d
Well, this looks like we haven't changed much, as, again, the variables are not passed back from d
into the parent shell, and we need to type a bit more.
However now we can throw the full power of the shell at it, as it is nicely wrapped in a function.
A second thing is, that we want to be DRY (Don't Repeat Yourself). So we definitively do not want to type something like
x=0
capture1 x d1 d
capture1 x d2 d
capture1 x d3 d
capture1 x d4 d
echo $x $d1 $d2 $d3 $d4
The x
here is not only redundant, it's error prone to always repeate in the correct context. What if you use it 1000 times in a script and then add a variable? You definitively do not want to alter all the 1000 locations where a call to d
is involved.
So leave the x
away, so we can write:
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
d() { let x++; output=$(date +%Y%m%d-%H%M%S); _passback output x; }
xcapture() { local -n output="$1"; eval "$("${@:2}")"; }
x=0
xcapture d1 d
xcapture d2 d
xcapture d3 d
xcapture d4 d
echo $x $d1 $d2 $d3 $d4
outputs
4 20171129-132414 20171129-132414 20171129-132414 20171129-132414
This already looks very good. (But there still is the local -n
which does not work in oder common bash
3.x)
d()
The last solution has some big flaws:
d()
needs to be alteredxcapture
to pass the output.
output
,
so we can never pass this one back._passback
Can we get rid of this, too?
Of course, we can! We are in a shell, so there is everything we need to get this done.
If you look a bit closer to the call to eval
you can see, that we have 100% control at this location. "Inside" the eval
we are in a subshell,
so we can do everything we want without fear of doing something bad to the parental shell.
Yeah, nice, so let's add another wrapper, now directly inside the eval
:
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
# !DO NOT USE!
_xcapture() { "${@:2}" > >(printf "%q=%q;" "$1" "$(cat)"); _passback x; } # !DO NOT USE!
# !DO NOT USE!
xcapture() { eval "$(_xcapture "$@")"; }
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
xcapture d1 d
xcapture d2 d
xcapture d3 d
xcapture d4 d
echo $x $d1 $d2 $d3 $d4
prints
4 20171129-132414 20171129-132414 20171129-132414 20171129-132414
However, this, again, has some major drawback:
!DO NOT USE!
markers are there,
because there is a very bad race condition in this,
which you cannot see easily:
>(printf ..)
is a background job. So it might still
execute while the _passback x
is running.sleep 1;
before printf
or _passback
.
_xcapture a d; echo
then outputs x
or a
first, respectively._passback x
should not be part of _xcapture
,
because this makes it difficult to reuse that recipe.$(cat)
),
but as this solution is !DO NOT USE!
I took the shortest route.However, this shows, that we can do it, without modification to d()
(and without local -n
)!
Please note that we not neccessarily need _xcapture
at all,
as we could have written everyting right in the eval
.
However doing this usually isn't very readable. And if you come back to your script in a few years, you probably want to be able to read it again without much trouble.
Now let's fix the race condition.
The trick could be to wait until printf
has closed it's STDOUT, and then output x
.
There are many ways to archive this:
Following the last path could look like (note that it does the printf
last because this works better here):
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
_xcapture() { { printf "%q=%q;" "$1" "$("${@:2}" 3<&-; _passback x >&3)"; } 3>&1; }
xcapture() { eval "$(_xcapture "$@")"; }
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
xcapture d1 d
xcapture d2 d
xcapture d3 d
xcapture d4 d
echo $x $d1 $d2 $d3 $d4
outputs
4 20171129-144845 20171129-144845 20171129-144845 20171129-144845
Why is this correct?
_passback x
directly talks to STDOUT.>&3
.$("${@:2}" 3<&-; _passback x >&3)
finishes after the _passback
,
when the subshell closes STDOUT.printf
cannot happen before the _passback
,
regardless how long _passback
takes.printf
command is not executed before the complete
commandline is assembled, so we cannot see artefacts from printf
,
independently how printf
is implemented.Hence first _passback
executes, then the printf
.
This resolves the race, sacrificing one fixed file descriptor 3. You can, of course, choose another file descriptor in the case, that FD3 is not free in your shellscript.
Please also note the 3<&-
which protects FD3 to be passed to the function.
_capture
contains parts, which belong to d()
, which is bad,
from a reusability perspective. How to solve this?
Well, do it the desparate way by introducing one more thing,
an additional function, which must return the right things,
which is named after the original function with _
attached.
This function is called after the real function, and can augment things. This way, this can be read as some annotation, so it is very readable:
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
_capture() { { printf "%q=%q;" "$1" "$("${@:2}" 3<&-; "$2_" >&3)"; } 3>&1; }
capture() { eval "$(_capture "$@")"; }
d_() { _passback x; }
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
capture d1 d
capture d2 d
capture d3 d
capture d4 d
echo $x $d1 $d2 $d3 $d4
still prints
4 20171129-151954 20171129-151954 20171129-151954 20171129-151954
There is only on bit missing:
v=$(fn)
sets $?
to what fn
returned. So you probably want this, too.
It needs some bigger tweaking, though:
# This is all the interface you need.
# Remember, that this burns FD=3!
_passback() { while [ 1 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; return $1; }
passback() { _passback "$@" "$?"; }
_capture() { { out="$("${@:2}" 3<&-; "$2_" >&3)"; ret=$?; printf "%q=%q;" "$1" "$out"; } 3>&1; echo "(exit $ret)"; }
capture() { eval "$(_capture "$@")"; }
# Here is your function, annotated with which sideffects it has.
fails_() { passback x y; }
fails() { x=$1; y=69; echo FAIL; return 23; }
# And now the code which uses it all
x=0
y=0
capture wtf fails 42
echo $? $x $y $wtf
prints
23 42 69 FAIL
_passback()
can be elmininated with passback() { set -- "$@" "$?"; while [ 1 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; return $1; }
_capture()
can be eliminated with capture() { eval "$({ out="$("${@:2}" 3<&-; "$2_" >&3)"; ret=$?; printf "%q=%q;" "$1" "$out"; } 3>&1; echo "(exit $ret)")"; }
The solution pollutes a file descriptor (here 3) by using it internally.
You need to keep that in mind if you happen to pass FDs.
Note thatbash
4.1 and above has {fd}
to use some unused FD.
(Perhaps I will add a solution here when I come around.)
Note that this is why I use to put it in separate functions like _capture
, because stuffing this all into one line is possible, but makes it increasingly harder to read and understand
Perhaps you want to capture STDERR of the called function, too.
Or you want to even pass in and out more than one filedescriptor
from and to variables.
I have no solution yet, however here is a way to catch more than one FD, so we can probably pass back the variables this way, too.
Also do not forget:
This must call a shell function, not an external command.
There is no easy way to pass environment variables out of external commands. (With
LD_PRELOAD=
it should be possible, though!) But this then is something completely different.
This is not the only possible solution. It is one example to a solution.
As always you have many ways to express things in the shell. So feel free to improve and find something better.
The solution presented here is quite far from being perfect:
bash
, so probably is hard to port to other shells.However I think it is quite easy to use:
It turns out the answer was ridiculously simple, but mystifying as to why it was necessary.
In the IIS Manager on the server, I set the application pool for my web application to not allow 32-bit assemblies.
It seems it assumes, on a 64-bit system, that you must want the 32 bit assembly. Bizarre.
This works best
SELECT RollId, count(*) AS c
FROM `tblstudents`
GROUP BY RollId
HAVING c > 1
ORDER BY c DESC
For python 3.5+ it is recommended that you use the run function from the subprocess module. This returns a CompletedProcess
object, from which you can easily obtain the output as well as return code.
from subprocess import PIPE, run
command = ['echo', 'hello']
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(result.returncode, result.stdout, result.stderr)
Since display
is not one of the animatable CSS properties.
One display:none
fadeOut animation replacement with pure CSS3 animations, just set width:0
and height:0
at last frame, and use animation-fill-mode: forwards
to keep width:0
and height:0
properties.
@-webkit-keyframes fadeOut {
0% { opacity: 1;}
99% { opacity: 0.01;width: 100%; height: 100%;}
100% { opacity: 0;width: 0; height: 0;}
}
@keyframes fadeOut {
0% { opacity: 1;}
99% { opacity: 0.01;width: 100%; height: 100%;}
100% { opacity: 0;width: 0; height: 0;}
}
.display-none.on{
display: block;
-webkit-animation: fadeOut 1s;
animation: fadeOut 1s;
animation-fill-mode: forwards;
}
source_list[::10]
is the most obvious, but this doesn't work for any iterable and is not memory efficient for large lists.itertools.islice(source_sequence, 0, None, 10)
works for any iterable and is memory-efficient, but probably is not the fastest solution for large list and big step.(source_list[i] for i in xrange(0, len(source_list), 10))
From the PHP manual:
This is only called on reading/writing inaccessible properties. Your property however is public, which means it is accessible. Changing the access modifier to protected solves the issue.
In my case the problem was that a method was defined in some Interface A
as default
, while its sub-class overrode it as private. Then when the method was called, the java Runtime realized it was calling a private method.
I am still puzzled as to why the compiler didn't complain about the private override..
public interface A {
default void doStuff() {
// doing stuff
}
}
public class B {
private void doStuff() {
// do other stuff instead
}
}
public static final main(String... args) {
A someB = new B();
someB.doStuff();
}
Regarding the answer from Michael Wyraz, where you use alt*DeploymentRepository
in your settings.xml
or command on the line, be careful if you are using version 3.0.0-M1 of the maven-deploy-plugin (which is the latest version at the time of writing), there is a bug in this version that could cause a server authentication issue.
A workaround is as follows. In the value:
releases::default::https://YOUR_NEXUS_URL/releases
you need to remove the default
section, making it:
releases::https://YOUR_NEXUS_URL/releases
The prior version 2.8.2 does not have this bug.
In order to start a service in its own process, you must specify the following in the xml declaration.
<service
android:name="WordService"
android:process=":my_process"
android:icon="@drawable/icon"
android:label="@string/service_name"
>
</service>
Here you can find a good tutorial that was really useful to me
http://www.vogella.com/articles/AndroidServices/article.html
Hope this helps
Extending from @Chandu, with some UI added:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<style>
button {
background: steelblue;
border-radius: 4px;
height: 40px;
width: 100px;
color: white;
font-size: 20px;
cursor: pointer;
border: none;
}
button:focus {
outline: 0;
}
#minutes, #seconds {
font-size: 40px;
}
.bigger {
font-size: 40px;
}
.button {
box-shadow: 0 9px #999;
}
.button:hover {background-color: hotpink}
.button:active {
background-color: hotpink;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
</style>
<body align='center'>
<button onclick='set_timer()' class='button'>START</button>
<button onclick='stop_timer()' class='button'>STOP</button><br><br>
<label id="minutes">00</label><span class='bigger'>:</span><label id="seconds">00</label>
</body>
</html>
<script>
function pad(val) {
valString = val + "";
if(valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
totalSeconds = 0;
function setTime(minutesLabel, secondsLabel) {
totalSeconds++;
secondsLabel.innerHTML = pad(totalSeconds%60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}
function set_timer() {
minutesLabel = document.getElementById("minutes");
secondsLabel = document.getElementById("seconds");
my_int = setInterval(function() { setTime(minutesLabel, secondsLabel)}, 1000);
}
function stop_timer() {
clearInterval(my_int);
}
</script>
Looks as follows:
According to this post this error message means:
Heap size is larger than your computer's physical memory.
Edit: Heap is not the only memory that is reserved, I suppose. At least there are other JVM settings like PermGenSpace that ask for the memory. With heap size 128M and a PermGenSpace of 64M you already fill the space available.
Why not downsize other memory settings to free up space for the heap?
Well, we can eliminate code error because I tested the code on my own server (PHP 5).
Here's what to check for:
Are you calling session_unset() or session_destroy() anywhere? These functions will delete the session data immediately. If I put these at the end of my script, it begins behaving exactly like you describe.
Does it act the same in all browsers? If it works on one browser and not another, you may have a configuration problem on the nonfunctioning browser (i.e. you turned off cookies and forgot to turn them on, or are blocking cookies by mistake).
Is the session folder writable? You can't test this with is_writable(), so you'll need to go to the folder (from phpinfo() it looks like /var/php_sessions) and make sure sessions are actually getting created.
While using string, the best possible way to print your message is:
#include <iostream>
#include <string>
using namespace std;
int main(){
string newInput;
getline(cin, newInput);
cout<<newInput;
return 0;
}
this can simply do the work instead of doing the method you adopted.
I propose a solution without modules (accumulate modules is never recommended for maintainability especially for small functions that can be written in a few lines...) :
LAST UPDATE :
In v10.12.0, NodeJS impletement recursive options :
// Create recursive folder
fs.mkdir('my/new/folder/create', { recursive: true }, (err) => { if (err) throw err; });
UPDATE :
// Get modules node
const fs = require('fs');
const path = require('path');
// Create
function mkdirpath(dirPath)
{
if(!fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK))
{
try
{
fs.mkdirSync(dirPath);
}
catch(e)
{
mkdirpath(path.dirname(dirPath));
mkdirpath(dirPath);
}
}
}
// Create folder path
mkdirpath('my/new/folder/create');
Why not try to use the Babylonian method for finding a square root.
Here is my code for it:
double sqrt(double number)
{
double error = 0.00001; //define the precision of your result
double s = number;
while ((s - number / s) > error) //loop until precision satisfied
{
s = (s + number / s) / 2;
}
return s;
}
Good luck!
It's possible to view proxy settings in Google Chrome:
chrome://net-internals/#proxy
Enter this in the address bar of Chrome.
It is returning the array, but all returning something (including an Array) does is just what it sounds like: returns the value. In your case, you are getting the value of numbers()
, which happens to be an array (it could be anything and you would still have this issue), and just letting it sit there.
When a function returns anything, it is essentially replacing the line in which it is called (in your case: numbers();
) with the return value. So, what your main
method is really executing is essentially the following:
public static void main(String[] args) {
{1,2,3};
}
Which, of course, will appear to do nothing. If you wanted to do something with the return value, you could do something like this:
public static void main(String[] args){
int[] result = numbers();
for (int i=0; i<result.length; i++) {
System.out.print(result[i]+" ");
}
}
what u can also do i place an extra "dummy" div before your last div.
Make it 1 px heigh and the width as much needed to cover the container div/body
This will make the last div appear under it, starting from the left.
The reason why Python base environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the base environment.
create a new separate environment in Anaconda dedicated to TensorFlow as follows:
conda create -n newenvt anaconda python=python_version
replace python_version by your python version
activate the new environment as follows:
activate newenvt
Then install tensorflow into the new environment (newenvt) as follows:
conda install tensorflow
Now you can check it by issuing the following python code and it will work fine.
import tensorflow
For working with UTC timezones:
time_stamp = calendar.timegm(dt.timetuple())
datetime.utcfromtimestamp(time_stamp)
This is how I login to my servers.
ssp <server_ip>
#!/bin/bash
sshpass -p mypassword ssh root@$1
And therefore...
ssp server_ip
My problem was solved after turning Off Windows Firewall Defender in public network as I was connected with that network.
With C#6.0 you also have a new way of formatting date when using string interpolation e.g.
$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"
Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.
Try this:
nohup python -u <your file name>.py >> <your log file>.log &
You can run above command in screen and come out of screen.
Now you can tail logs of your python script by: tail -f <your log file>.log
To kill you script, you can use ps -aux and kill commands.
I use these two methods depending on the usage. FIDDLE
<div class="img-div">
<img src="http://placekitten.com/g/400/200" />
</div>
<div class="circle-image"></div>
div.img-div{
height:200px;
width:200px;
overflow:hidden;
border-radius:50%;
}
.img-div img{
-webkit-transform:translate(-50%);
margin-left:100px;
}
.circle-image{
width:200px;
height:200px;
border-radius:50%;
background-image:url("http://placekitten.com/g/200/400");
display:block;
background-position-y:25%
}
I would use vbscript (Windows Scripting Host), because in batch I'm sure you cannot tell that a name is a file or a directory.
In vbs, it can be something like this:
Dim fileSystemObject
Set fileSystemObject = CreateObject("Scripting.FileSystemObject")
Dim mainFolder
Set mainFolder = fileSystemObject.GetFolder(myFolder)
Dim files
Set files = mainFolder.Files
For Each file in files
...
Next
Dim subFolders
Set subFolders = mainFolder.SubFolders
For Each folder in subFolders
...
Next
Check FileSystemObject on MSDN.
I'm not sure that I understood your problem, but I think you can divide loop. On the part of the function and the part without it and save the two loops.
You are sending a array of string
var usersRoles = [];
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
So change model type accordingly
public ActionResult AddUser(List<string> model)
{
}
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
I put this right after the onClick(View v)
event.
You need to import android.view.inputmethod.InputMethodManager
;
The keyboard hides when you click the button.
Laravel 5.2 <= 5.5
use Carbon\Carbon; // You need to import Carbon
$current_time = Carbon::now()->toDayDateTimeString(); // Wed, May 17, 2017 10:42 PM
$current_timestamp = Carbon::now()->timestamp; // Unix timestamp 1495062127
In addition, this is how to change datetime format for given date & time, in blade:
{{\Carbon\Carbon::parse($dateTime)->format('D, d M \'y, H:i')}}
Laravel 5.6 <
$current_timestamp = now()->timestamp;
I did it this way (you need to add a class text to <td>
and put the text between a <span>
:
HTML
<td class="text"><span>looooooong teeeeeeeeext</span></td>
SASS
.table td.text {
max-width: 177px;
span {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: inline-block;
max-width: 100%;
}
}
CSS equivalent
.table td.text {
max-width: 177px;
}
.table td.text span {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: inline-block;
max-width: 100%;
}
And it will still be mobile responsive (forget it with layout=fixed) and will keep the original behaviour.
PS: Of course 177px is a custom size (put whatever you need).
I had this code which was causing the error:
for t in dfObj['time']:
if type(t) == str:
the_date = dateutil.parser.parse(t)
loc_dt_int = int(the_date.timestamp())
dfObj.loc[t == dfObj.time, 'time'] = loc_dt_int
I changed it to this:
for t in dfObj['time']:
try:
the_date = dateutil.parser.parse(t)
loc_dt_int = int(the_date.timestamp())
dfObj.loc[t == dfObj.time, 'time'] = loc_dt_int
except Exception as e:
print(e)
continue
to avoid the comparison, which is throwing the warning - as stated above. I only had to avoid the exception because of dfObj.loc
in the for loop, maybe there is a way to tell it not to check the rows it has already changed.
Here's another way -
cat > outfile.txt
>Enter text
>to save press ctrl-d
I used to use the jquery format currency plugin, but it has been very buggy recently. I only need formatting for USD/CAD, so I wrote my own automatic formatting.
$(".currencyMask").change(function () {
if (!$.isNumeric($(this).val()))
$(this).val('0').trigger('change');
$(this).val(parseFloat($(this).val(), 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());
});
Simply set the class of whatever input should be formatted as currency <input type="text" class="currencyMask" />
and it will format it perfectly in any browser.
To complement the answers above, it can be quite useful to use a replacement for NSLog in certain situations, especially when debugging. For example, getting rid of all the date and process name/id information on each line can make output more readable and faster to boot.
The following link provides quite a bit of useful ammo for making simple logging much nicer.
If anyone came here trying to do this with a decimal like me:
myFloat = parseFloat(myString);
If you just need an Int, that's well covered in the other answers.
In Rails 3.2.18, :decimal turns into :integer when using SQLServer, but it works fine in SQLite. Switching to :float solved this issue for us.
The lesson learned is "always use homogeneous development and deployment databases!"
You can use this code to see the last modified date of a file.
DateTime dt = File.GetLastWriteTime(path);
And this code to see the creation time.
DateTime fileCreatedDate = File.GetCreationTime(@"C:\Example\MyTest.txt");
Looking at the edited question, you need to find the number of digits in the largest number to be presented, and then generate the printf()
format using sprintf()
, or using %*d
with the number of digits being passed as an int for the *
and then the value. Once you've got the biggest number (and you have to determine that in advance), you can determine the number of digits with an 'integer logarithm' algorithm (how many times can you divide by 10 before you get to zero), or by using snprintf()
with the buffer length of zero, the format %d
and null for the string; the return value tells you how many characters would have been formatted.
If you don't know and cannot determine the maximum number ahead of its appearance, you are snookered - there is nothing you can do.
The real rule is: Don't throw away exceptions. The objectivity of the author of your quote is questionable, as evidenced by the fact that it ends with
or I will stab you
Of course, be aware that signals (by default) throw exceptions, and normally long-running processes are terminated through a signal, so catching Exception and not terminating on signal exceptions will make your program very hard to stop. So don't do this:
#! /usr/bin/ruby
while true do
begin
line = STDIN.gets
# heavy processing
rescue Exception => e
puts "caught exception #{e}! ohnoes!"
end
end
No, really, don't do it. Don't even run that to see if it works.
However, say you have a threaded server and you want all exceptions to not:
thread.abort_on_exception = true
). Then this is perfectly acceptable in your connection handling thread:
begin
# do stuff
rescue Exception => e
myLogger.error("uncaught #{e} exception while handling connection: #{e.message}")
myLogger.error("Stack trace: #{backtrace.map {|l| " #{l}\n"}.join}")
end
The above works out to a variation of Ruby's default exception handler, with the advantage that it doesn't also kill your program. Rails does this in its request handler.
Signal exceptions are raised in the main thread. Background threads won't get them, so there is no point in trying to catch them there.
This is particularly useful in a production environment, where you do not want your program to simply stop whenever something goes wrong. Then you can take the stack dumps in your logs and add to your code to deal with specific exception further down the call chain and in a more graceful manner.
Note also that there is another Ruby idiom which has much the same effect:
a = do_something rescue "something else"
In this line, if do_something
raises an exception, it is caught by Ruby, thrown away, and a
is assigned "something else"
.
Generally, don't do that, except in special cases where you know you don't need to worry. One example:
debugger rescue nil
The debugger
function is a rather nice way to set a breakpoint in your code, but if running outside a debugger, and Rails, it raises an exception. Now theoretically you shouldn't be leaving debug code lying around in your program (pff! nobody does that!) but you might want to keep it there for a while for some reason, but not continually run your debugger.
Note:
If you've run someone else's program that catches signal exceptions and ignores them, (say the code above) then:
pgrep ruby
, or ps | grep ruby
, look for your offending program's PID, and then run kill -9 <PID>
. If you are working with someone else's program which is, for whatever reason, peppered with these ignore-exception blocks, then putting this at the top of the mainline is one possible cop-out:
%W/INT QUIT TERM/.each { |sig| trap sig,"SYSTEM_DEFAULT" }
This causes the program to respond to the normal termination signals by immediately terminating, bypassing exception handlers, with no cleanup. So it could cause data loss or similar. Be careful!
If you need to do this:
begin
do_something
rescue Exception => e
critical_cleanup
raise
end
you can actually do this:
begin
do_something
ensure
critical_cleanup
end
In the second case, critical cleanup
will be called every time, whether or not an exception is thrown.
You also need to install software-properties-common for add-apt-repository to work. so it will be
sudo apt-get purge nodejs npm
sudo apt-get install -y python-software-properties python g++ make software-properties-common
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs
This is nice but doesn't answer the question:
"A VARCHAR should always be used instead of TINYTEXT." Tinytext is useful if you have wide rows - since the data is stored off the record. There is a performance overhead, but it does have a use.
In some versions, it stores it under
<installed path>\system\oracle.jdeveloper.db.connection.11.1.1.0.11.42.44
\IDEConnections.xml
NodeJS supports http.request as a standard module: http://nodejs.org/docs/v0.4.11/api/http.html#http.request
var http = require('http');
var options = {
host: 'example.com',
port: 80,
path: '/foo.html'
};
http.get(options, function(resp){
resp.on('data', function(chunk){
//do something with chunk
});
}).on("error", function(e){
console.log("Got error: " + e.message);
});
The -std=c++14
flag is not supported on GCC 4.8. If you want to use C++14 features you need to compile with -std=c++1y
. Using godbolt.org it appears that the earilest version to support -std=c++14
is GCC 4.9.0 or Clang 3.5.0
The pattern I generally use is to create the row without the columns that have default constraints, then update the columns to replace the default values with supplied values (if not null).
Assuming col1 is the primary key and col4 and col5 have a default contraint
-- create initial row with default values
insert table1 (col1, col2, col3)
values (@col1, @col2, @col3)
-- update default values, if supplied
update table1
set col4 = isnull(@col4, col4),
col5 = isnull(@col5, col5)
where col1 = @col1
If you want the actual values defaulted into the table ...
-- create initial row with default values
insert table1 (col1, col2, col3)
values (@col1, @col2, @col3)
-- create a container to hold the values actually inserted into the table
declare @inserted table (col4 datetime, col5 varchar(50))
-- update default values, if supplied
update table1
set col4 = isnull(@col4, col4),
col5 = isnull(@col5, col5)
output inserted.col4, inserted.col5 into @inserted (col4, col5)
where col1 = @col1
-- get the values defaulted into the table (optional)
select @col4 = col4, @col5 = col5 from @inserted
Cheers...
You might get the error with the latest android gradle plugin (3.0):
Cannot set the value of read-only property 'outputFile'
According to the migration guide, we should use the following approach now:
applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "${applicationName}_${variant.buildType.name}_${defaultConfig.versionName}.apk"
}
}
Note 2 main changes here:
all
is used now instead of each
to iterate over the variant outputs.outputFileName
property is used instead of mutating a file reference.<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^olddomain.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.olddomain.com$
RewriteRule (.*)$ http://www.newdomain.com/$1 [R=301,L]
</IfModule>
This worked for me
You can append the values in the query string for the next page to see and process. You can wrap them inside the link tags:
<a href="your_page.php?var1=value1&var2=value2">
You separate each of those values with the &
sign.
Or you can create this on a button click like this:
<input type="button" onclick="document.location.href = 'your_page.php?var1=value1&var2=value2';">
It appears to be a known issue.
http://dev.mysql.com/doc/refman/5.1/en/unnamed-views.html
http://bugs.mysql.com/bug.php?id=16757
Many IN queries can be re-written as (left outer) joins and an IS (NOT) NULL of some sort. for example
SELECT * FROM FOO WHERE ID IN (SELECT ID FROM FOO2)
can be re-written as
SELECT FOO.* FROM FOO JOIN FOO2 ON FOO.ID=FOO2.ID
or
SELECT * FROM FOO WHERE ID NOT IN (SELECT ID FROM FOO2)
can be
SELECT FOO.* FROM FOO
LEFT OUTER JOIN FOO2
ON FOO.ID=FOO2.ID WHERE FOO.ID IS NULL
Having the braces right from the first moment should help to prevent you from ever having to debug this:
if (statement)
do this;
else
do this;
do that;
We have the following string which is a valid JSON ...
Clearly the JSON parser disagrees!
However, the exception says that the error is at "line 1: column 9", and there is no "http" token near the beginning of the JSON. So I suspect that the parser is trying to parse something different than this string when the error occurs.
You need to find what JSON is actually being parsed. Run the application within a debugger, set a breakpoint on the relevant constructor for JsonParseException
... then find out what is in the ByteArrayInputStream
that it is attempting to parse.
Inside a module
Option Explicit
dim objExcelApp as Excel.Application
dim wb as Excel.Workbook
sub Initialize()
set objExcelApp = new Excel.Application
end sub
sub ProcessDataWorkbook()
dim ws as Worksheet
set wb = objExcelApp.Workbooks.Open("path to my workbook")
set ws = wb.Sheets(1)
ws.Cells(1,1).Value = "Hello"
ws.Cells(1,2).Value = "World"
'Close the workbook
wb.Close
set wb = Nothing
end sub
sub Release()
set objExcelApp = Nothing
end sub
@Autowired
can be used with setters so you could have a setter modifying an static field.
Just one final suggestion... DON'T
My solution ( may not work for you)
Open the application on a machine that is flagging the error. Change the VB code in some way. ( I added one comment line of code of no consequence into one of the macros)
Sheets(sheetName).Select 'comment of no consequence
and save it. This causes a recompile. Close and re-open - all fixed.
Hope this makes sense and helps
Grant
It can enable some new optimisations. const
traditionally is a hint for the type system, and cannot be used for optimisation (e.g. a const
member function can const_cast
and modify the object anyway, legally, so const
cannot be trusted for optimisation).
constexpr
means the expression really is constant, provided the inputs to the function are const. Consider:
class MyInterface {
public:
int GetNumber() const = 0;
};
If this is exposed in some other module, the compiler can't trust that GetNumber()
won't return different values each time it's called - even consecutively with no non-const calls in between - because const
could have been cast away in the implementation. (Obviously any programmer who did this ought to be shot, but the language permits it, therefore the compiler must abide by the rules.)
Adding constexpr
:
class MyInterface {
public:
constexpr int GetNumber() const = 0;
};
The compiler can now apply an optimisation where the return value of GetNumber()
is cached and eliminate additional calls to GetNumber()
, because constexpr
is a stronger guarantee that the return value won't change.
A pretty nice way to do this is to use SimpleDateFormat
I'll show you how:
SimpleDateFormat sdf = new SimpleDateFormat("d MMMM YYYY");
Date d = new Date();
sdf.format(d);
I see that you have the date in a variable:
sdf.format(variable_name);
Cheers.
Here is a version of the currently accepted answer (from @Trevor) with key instead of keyCode:
document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
// code for enter
}
});
Just wanted to contribute a solution that I used for my app.
It is also based on the OnScrollListener
interface, but I found it to have a much better scrolling performance on low-end devices, since none of the visible/total count calculations are carried out during the scroll operations.
ListFragment
or ListActivity
implement OnScrollListener
Add the following methods to that class:
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//leave this empty
}
@Override
public void onScrollStateChanged(AbsListView listView, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= listView.getCount() - 1 - threshold) {
currentPage++;
//load more list items:
loadElements(currentPage);
}
}
}
where currentPage
is the page of your datasource that should be added to your list, and threshold
is the number of list items (counted from the end) that should, if visible, trigger the loading process. If you set threshold
to 0
, for instance, the user has to scroll to the very end of the list in order to load more items.
(optional) As you can see, the "load-more check" is only called when the user stops scrolling. To improve usability, you may inflate and add a loading indicator to the end of the list via listView.addFooterView(yourFooterView)
. One example for such a footer view:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/footer_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp" >
<ProgressBar
android:id="@+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/progressBar1"
android:padding="5dp"
android:text="@string/loading_text" />
</RelativeLayout>
(optional) Finally, remove that loading indicator by calling listView.removeFooterView(yourFooterView)
if there are no more items or pages.
Yes, you can do this in PHP e.g. in
Silex or Symfony3
using subrequest
$postParams = array(
'email' => $request->get('email'),
'agree_terms' => $request->get('agree_terms'),
);
$subRequest = Request::create('/register', 'POST', $postParams);
return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
For context, I created a project using the ASP.NET Core 2 Web Application template. Then, select the Web Application (MVC) then hit the Change Authentication button and select Individual User accounts.
There is a lot of infrastructure built up for you from this template. Find the ManageController
in the Controllers folder.
This ManageController
class constructor requires this UserManager variable to populated:
private readonly UserManager<ApplicationUser> _userManager;
Then, take a look at the the [HttpPost] Index method in this class. They get the current user in this fashion:
var user = await _userManager.GetUserAsync(User);
As a bonus note, this is where you want to update any custom fields to the user Profile you've added to the AspNetUsers table. Add the fields to the view, then submit those values to the IndexViewModel which is then submitted to this Post method. I added this code after the default logic to set the email address and phone number:
user.FirstName = model.FirstName;
user.LastName = model.LastName;
user.Address1 = model.Address1;
user.Address2 = model.Address2;
user.City = model.City;
user.State = model.State;
user.Zip = model.Zip;
user.Company = model.Company;
user.Country = model.Country;
user.SetDisplayName();
user.SetProfileID();
_dbContext.Attach(user).State = EntityState.Modified;
_dbContext.SaveChanges();
Change:
x.length
to:
x.options.length
Link to fiddle
And I agree with Abraham - you might want to use text
instead of value
Update
The reason your fiddle didn't work was because you chose the option: "onLoad" instead of: "No wrap - in "
To use Subversion in Visual Studio 2008, install TortoiseSVN and AnkhSVN.
TortoiseSVN is a really easy to use Revision control / version control / source control software for Windows. Since it's not an integration for a specific IDE you can use it with whatever development tools you like. TortoiseSVN is free to use. You don't need to get a loan or pay a full years salary to use it.
AnkhSVN is a Subversion SourceControl Provider for Visual Studio. The software allows you to perform the most common version control operations directly from inside the Microsoft Visual Studio IDE. With AnkhSVN you no longer need to leave your IDE to perform tasks like viewing the status of your source code, updating your Subversion working copy and committing changes. You can even browse your repository and you can plug-in your favorite diff tool.
Don't forget nullability.
ALTER TABLE <schemaName>.<tableName>
ALTER COLUMN <columnName> nvarchar(200) [NULL|NOT NULL]
Open the file again using vi. and then press " i " or press insert key ,
For save and quit
Enter Esc
and write the following command
:wq
without save and quit
:q!
Really easy solve. Tested and working. You just need to generate a new url when you update your meta tags. It's as simple as adding a "&cacheBuster=1" to your url. If you change the meta tags, just increment the "&cacheBuster=2"
Orginal URL
www.example.com
URL when og meta tags are updated:
www.example.com?cacheBuster=1
URL when og meta tags are updated again:
www.example.com?cacheBuster=2
Facebook will treat each like a new url and get fresh meta data.
I solve this problem in MvcMusicStore by add this part of code in _Layout.cshtml
@if (IsSectionDefined("scripts"))
{
@RenderSection("scripts", required: false)
}
and remove this code from Edit.cshtml
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Run the program inshallah will work with you.
There are 2 differences:
2 methods creating a user and granting some privileges to him
create user userName identified by password;
grant connect to userName;
and
grant connect to userName identified by password;
do exactly the same. It creates a user and grants him the connect role.
different outcome
resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.
To grant a user all privileges run you first snippet or
grant all privileges to userName identified by password;
This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.
This works in Chrome but not Firefox 3.6 (warning: RickRoll video):
<iframe width="420" height="345" src="http://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1" frameborder="0" allowfullscreen></iframe>
The JavaScript API for iframe embeds exists, but is still posted as an experimental feature.
UPDATE: The iframe API is now fully supported and "Creating YT.Player objects - Example 2" shows how to set "autoplay" in JavaScript.
For a
and b
as two DateTime
types:
DateTime d = DateTime.Now;
DateTime c = DateTime.Now;
c = d.AddDays(145);
string cc;
Console.WriteLine(d);
Console.WriteLine(c);
var t = (c - d).Days;
Console.WriteLine(t);
cc = Console.ReadLine();
IMHO, one point that is missing in this discussion is that whatever variable you use, it is guaranteed to always point at the appropriate folder. This becomes critical in the rare cases where Windows is installed on a drive other than C:\
size_t lf = strlen(first);
size_t ls = strlen(second);
char *both = (char*) malloc((lf + ls + 2) * sizeof(char));
strcpy(both, first);
both[lf] = ' ';
strcpy(&both[lf+1], second);
Well, one classic example is where you wanted to get a list of employees and their immediate managers:
select e.employee as employee, b.employee as boss
from emptable e, emptable b
where e.manager_id = b.empolyee_id
order by 1
It's basically used where there is any relationship between rows stored in the same table.
And so on...
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.vehicals_details_row, parent, false);
Button deleteImageView = (Button) row.findViewById(R.id.DeleteImageView);
deleteImageView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//...
}
});
}
But you can get an issue - listView row not clickable. Solution:
android:focusable="true"
android:focusable="false"
.wrapper{
float: left;
width: 100%;
text-align: center;
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.button{
display:inline-block;
}
<div class="wrapper">
<button class="button">Button1</button>
<button class="button">Button2</button>
</div>
Turned out there was some extra code in the AppModel that was messing things up:
in beforeFind
and afterFind
:
App::Import("Session");
$session = new CakeSession();
$sim_id = $session->read("Simulation.id");
I don't know why, but that was what the problem was. Removing those lines fixed the issue I was having.
Do you mean you only want the alphabetic characters and not the digits? So you want "quality" as a result? You can use Char.IsLetter or Char.IsDigit to filter them out one by one.
string s = "9quali52ty3";
StringBuilder result = new StringBuilder();
foreach(char c in s)
{
if (Char.IsLetter(c))
result.Add(c);
}
Console.WriteLine(result); // quality
I got this error after change a loop in my program, let`s see:
for ...
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:
for ...
x_batch = []
y_batch = []
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
Then, check if you are using np.asarray() or something like that.
I found the correct solution you can use this code
$('.close').click();
Put novalidate="novalidate"
on <form>
tag.
<form novalidate="novalidate">
...
</form>
In XHTML, attribute minimization is forbidden, and the novalidate attribute must be defined as
<form novalidate="novalidate">
.
Using a simple SELECT query is - in my opinion - quite reliable. Most of all it can check table existence in many different database types (SQLite / MySQL).
SELECT 1 FROM table;
It makes sense when you can use other reliable mechanism for determining if the query succeeded (for example, you query a database via QSqlQuery in Qt).
If you did a custom installation you need to add Microsoft Sql Server Data Tools. After that you can add Reportviwer to your webform.
This answer is focused to someone that buy a domain in another site (as GoDaddy) and want to use the Amazon free certificate with Certificate Manager
This answer uses Amazon Classic Load Balancer (paid) see the pricing before using it
Step 1 - Request a certificate with Certificate Manager
Go to Certificate Manager > Request Certificate > Request a public certificate
On Domain name you will add myprojectdomainname.com
and *.myprojectdomainname.com
and go on Next
Chose Email validation and Confirm and Request
Open the email that you have received (on the email account that you have buyed the domain) and aprove the request
After this, check if the validation status of myprojectdomainname.com
and *.myprojectdomainname.com
is sucess, if is sucess you can continue to Step 2
Step 2 - Create a Security Group to a Load Balancer
On EC2 go to Security Groups > and Create a Security Group and add the http and https inbound
Step 3 - Create the Load Balancer
EC2 > Load Balancer > Create Load Balancer > Classic Load Balancer (Third option)
Create LB inside - the vpc of your project On Load Balancer Protocol add Http and Https
Next > Select exiting security group
Choose the security group that you have create in the previous step
Next > Choose certificate from ACM
Select the certificate of the step 1
Next >
on Health check i've used the ping path / (one slash instead of /index.html)
Step 4 - Associate your instance with the security group of load balancer
EC2 > Instances > click on your project > Actions > Networking > Change Security Groups
Add the Security Group of your Load Balancer
Step 5
EC2 > Load Balancer > Click on the load balancer that you have created > copy the DNS Name (A Record), it will be something like myproject-2021611191.us-east-1.elb.amazonaws.com
Go to Route 53 > Routes Zones > click on the domain name > Go to Records Sets
(If you are don't have your domain here, create a hosted zone with Domain Name: myprojectdomainname.com
and Type: Public Hosted Zone
)
Check if you have a record type A (probably not), create/edit record set with name empty, type A, alias Yes and Target the dns that you have copied
Create also a new Record Set of type A, name *.myprojectdomainname.com
, alias Yes and Target your domain (myprojectdomainname.com). This will make possible access your site with www.myprojectdomainname.com and subsite.myprojectdomainname.com. Note: You will need to configure your reverse proxy (Nginx/Apache) to do so.
On NS copy the 4 Name Servers values to use on the next Step, it will be something like:
ns-362.awsdns-45.com
ns-1558.awsdns-02.co.uk
ns-737.awsdns-28.net
ns-1522.awsdns-62.org
Go to EC2 > Instances > And copy the IPv4 Public IP too
Step 6
On the domain register site that you have buyed the domain (in my case GoDaddy)
Change the routing to http : <Your IPv4 Public IP Number>
and select Forward with masking
Change the Name Servers (NS) to the 4 NS that you have copied, this can take 48 hours to make effect
Run this code It will open google print service popup.
function openPrint(x) {
if (x > 0) {
openPrint(--x); print(x); openPrint(--x);
}
}
Try it on console where x is integer .
openPrint(1); // Will open Chrome Print Popup Once
openPrint(2); // Will open Chrome Print Popup Twice after 1st close and so on
Thanks
I just give other option for this question - you need to use '.dt' in your code:
import pandas as pd_x000D_
_x000D_
df.index = pd.to_datetime(df.index)_x000D_
_x000D_
#for get year_x000D_
df.index.dt.year_x000D_
_x000D_
#for get month_x000D_
df.index.dt.month_x000D_
_x000D_
#for get day_x000D_
df.index.dt.day_x000D_
_x000D_
#for get hour_x000D_
df.index.dt.hour_x000D_
_x000D_
#for get minute_x000D_
df.index.dt.minute
_x000D_
I recently ran into the same problem. I had to change my virtual hosts from:
<VirtualHost *:80>
ServerName local.example.com
DocumentRoot /home/example/public
<Directory />
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
To:
<VirtualHost *:80>
ServerName local.example.com
DocumentRoot /home/example/public
<Directory />
Options All
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
I demonstrate how to receive a string, for example "-484876800000" and tryparse the string to make sure it can be assigned to a long. I calculate the Date from universaltime and return a string. When you convert a string to a number, you must decide the numeric type and precision and test if the string data can be parse, otherwise, it will throw and error.
function universalToDate
{
param (
$paramValue
)
$retVal=""
if ($paramValue)
{
$epoch=[datetime]'1/1/1970'
[long]$returnedLong = 0
[bool]$result = [long]::TryParse($paramValue,[ref]$returnedLong)
if ($result -eq 1)
{
$val=$returnedLong/1000.0
$retVal=$epoch.AddSeconds($val).ToString("yyyy-MM-dd")
}
}
else
{
$retVal=$null
}
return($retVal)
}
if ([recognizer state] == UIGestureRecognizerStateChanged)
{
CGPoint translation1 = [recognizer translationInView:main_view];
img12.center=CGPointMake(img12.center.x+translation1.x, img12.center.y+ translation1.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:main_view];
recognizer.view.center=CGPointMake(recognizer.view.center.x+translation1.x, recognizer.view.center.y+ translation1.y);
}
-(void)move:(UIPanGestureRecognizer*)recognizer
{
if ([recognizer state] == UIGestureRecognizerStateChanged)
{
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center=CGPointMake(recognizer.view.center.x+translation.x, recognizer.view.center.y+ translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}
}
Simply add class="img-responsive" to the video tag. I'm doing this on a current project, and it works. It doesn't need to be wrapped in anything.
<video class="img-responsive" src="file.mp4" autoplay loop/>
I used this for radio's:
if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
error.appendTo(element.parent().parent());
}
else if (element.parent(".input-group").length) {
error.insertAfter(element.parent());
}
else {
error.insertAfter(element);
}
this way the error is displayed under last radio option.
You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc()
, the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap()
. Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc()
, it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free()
the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.
If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc()
. Thus, if you make a lot of calls to malloc()
and free()
with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc()
fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.
I prefer to use the HTML5 data API, check this documentation:
$('#some-list li').click(function() {_x000D_
var textLoaded = 'Loading element with id='_x000D_
+ $(this).data('id');_x000D_
$('#loading-content').text(textLoaded);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul id='some-list'>_x000D_
<li data-id='1'>One </li>_x000D_
<li data-id='2'>Two </li>_x000D_
<!-- ... more li -->_x000D_
<li data-id='n'>Other</li>_x000D_
</ul>_x000D_
_x000D_
<h1 id='loading-content'></h1>
_x000D_
You can use the finish
command.
finish
: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated asfin
.
(See 5.2 Continuing and Stepping.)
Here's a variation on ashirazi's answer which doesn't rely on $IFS
. It does have its own issues which I ouline below.
sentence="one;two;three"
sentence=${sentence//;/$'\n'} # change the semicolons to white space
for word in $sentence
do
echo "$word"
done
Here I've used a newline, but you could use a tab "\t
" or a space. However, if any of those characters are in the text it will be split there, too. That's the advantage of $IFS
- it can not only enable a separator, but disable the default ones. Just make sure you save its value before you change it - as others have suggested.
Synalyze It! allows to compare text or bytes in all encodings the ICU library offers. Using that feature you usually see immediately which code page makes sense for your data.
The syntax you have used is incorrect. The query should be something like:
SELECT column_name(s) FROM tablename WHERE id = (SELECT MAX(id) FROM tablename)
You can use Linq to XML to do this:
XDocument doc = XDocument.Load("input.xml");
var q = from node in doc.Descendants("Setting")
let attr = node.Attribute("name")
where attr != null && attr.Value == "File1"
select node;
q.ToList().ForEach(x => x.Remove());
doc.Save("output.xml");
Some RFID chips are read-write, the majority are read-only. You can find out if your chip is read-only by checking the datasheet.
If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.
java -jar myapp.jar --debug
You can also specify debug=true in your application.properties.
When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.
Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html
setInterval(function() {
updatechat();
}, 2000);
function updatechat() {
alert('hello world');
}
Yes the restOfTheUrl
is not returning only required value but we can get the value by using UriTemplate
matching.
I have solved the problem, so here the working solution for the problem:
@RequestMapping("/{id}/**")
public void foo(@PathVariable("id") int id, HttpServletRequest request) {
String restOfTheUrl = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
/*We can use UriTemplate to map the restOfTheUrl*/
UriTemplate template = new UriTemplate("/{id}/{value}");
boolean isTemplateMatched = template.matches(restOfTheUrl);
if(isTemplateMatched) {
Map<String, String> matchTemplate = new HashMap<String, String>();
matchTemplate = template.match(restOfTheUrl);
String value = matchTemplate.get("value");
/*variable `value` will contain the required detail.*/
}
}
The Flexible
does the trick
new Container(
child: Row(
children: <Widget>[
Flexible(
child: new Text("A looooooooooooooooooong text"))
],
));
This is the official doc https://flutter.dev/docs/development/ui/layout#lay-out-multiple-widgets-vertically-and-horizontally on how to arrange widgets.
Remember that Flexible
and also Expanded
, should only be used within a Column
, Row
or Flex
, because of the Incorrect use of ParentDataWidget
.
The solution is not the mere Flexible
Second answer above is the most simple one.
int n = Integer.parseInt(System.console().readLine());
The question is "How to read from standard input".
A console is a device typically associated to the keyboard and display from which a program is launched.
You may wish to test if no Java console device is available, e.g. Java VM not started from a command line or the standard input and output streams are redirected.
Console cons;
if ((cons = System.console()) == null) {
System.err.println("Unable to obtain console");
...
}
Using console is a simple way to input numbers. Combined with parseInt()/Double() etc.
s = cons.readLine("Enter a int: ");
int i = Integer.parseInt(s);
s = cons.readLine("Enter a double: ");
double d = Double.parseDouble(s);
node-dev works great. npm install node-dev
It even gives a desktop notification when the server is reloaded and will give success or errors on the message.
start your app on command line with:
node-dev app.js
Consider using pgrep (if available) rather than ps piped through grep if you're going to go that route. Though, personally, I've got a lot of mileage out of scripts of the form
while(1){
call script_that_must_run
sleep 5
}
Though this can fail and cron jobs are often the best way for essential stuff. Just another alternative.
You can try the below command:
svn info -r 'HEAD' | grep Revision: | awk -F' ' '{print $2}'
Update your version of youtube-dl to the lastest as older version might not support.
pip install --upgrade youtube_dl
Install 'ffmpeg' and 'ffprobe' module
pip install ffmpeg
pip install ffprobe
If you face the same issue, then download ffmpeg builds and put all the .exe files to Script folder($path: "Python\Python38-32\Scripts") (Windows OS only)
In Python 3 this can be done in 2 steps:
datetime
objectdatetime
object by 1000 to convert it to milliseconds.For example like this:
from datetime import datetime
dt_obj = datetime.strptime('20.12.2016 09:38:42,76',
'%d.%m.%Y %H:%M:%S,%f')
millisec = dt_obj.timestamp() * 1000
print(millisec)
Output:
1482223122760.0
strptime
accepts your timestring and a format string as input. The timestring (first argument) specifies what you actually want to convert to a datetime
object. The format string (second argument) specifies the actual format of the string that you have passed.
Here is the explanation of the format specifiers from the official documentation:
%d
- Day of the month as a zero-padded decimal number.%m
- Month as a zero-padded decimal number.%Y
- Year with century as a decimal number%H
- Hour (24-hour clock) as a zero-padded decimal number.%M
- Minute as a zero-padded decimal number.%S
- Second as a zero-padded decimal number.%f
- Microsecond as a decimal number, zero-padded on the left.This is what may be happening, if the value of item.photo
is undefined then item.photo != ''
will always show as true. And if you think logically it actually makes sense, item.photo
is not an empty string (so this condition comes true) since it is undefined
.
Now for people who are trying to check if the value of input is empty or not in Angular 6, can go by this approach.
Lets say this is the input field -
<input type="number" id="myTextBox" name="myTextBox"_x000D_
[(ngModel)]="response.myTextBox"_x000D_
#myTextBox="ngModel">
_x000D_
To check if the field is empty or not this should be the script.
<div *ngIf="!myTextBox.value" style="color:red;">_x000D_
Your field is empty_x000D_
</div>
_x000D_
Do note the subtle difference between the above answer and this answer. I have added an additional attribute .value
after my input name myTextBox
.
I don't know if the above answer worked for above version of Angular, but for Angular 6 this is how it should be done.
this is old but for help :
you can also use the stringReader stream
string str = "asasdkopaksdpoadks";
StringReader TheStream = new StringReader( str );
I found the following solution pretty effective if you need to comment a lot of nested HTML + PHP code.
Wrap all the content in this:
<?php
if(false){
?>
Here goes your PHP + HTML code
<?php
}
?>
As a String
class extension
SWIFT 4
extension String {
func isValidEmail() -> Bool {
// here, `try!` will always succeed because the pattern is valid
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .caseInsensitive)
return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: count)) != nil
}
}
Usage
if "rdfsdsfsdfsd".isValidEmail() {
}
Maybe the anwswers here are obsolete... in any case, for me running Symfony 4, it is easy
Just type symfony -V
from the command line.
The reason why there is no ConcurrentList is because it fundamentally cannot be written. The reason why is that several important operations in IList rely on indices, and that just plain won't work. For example:
int catIndex = list.IndexOf("cat");
list.Insert(catIndex, "dog");
The effect that the author is going after is to insert "dog" before "cat", but in a multithreaded environment, anything can happen to the list between those two lines of code. For example, another thread might do list.RemoveAt(0)
, shifting the entire list to the left, but crucially, catIndex will not change. The impact here is that the Insert
operation will actually put the "dog" after the cat, not before it.
The several implementations that you see offered as "answers" to this question are well-meaning, but as the above shows, they don't offer reliable results. If you really want list-like semantics in a multithreaded environment, you can't get there by putting locks inside the list implementation methods. You have to ensure that any index you use lives entirely inside the context of the lock. The upshot is that you can use a List in a multithreaded environment with the right locking, but the list itself cannot be made to exist in that world.
If you think you need a concurrent list, there are really just two possibilities:
If you have a ConcurrentBag and are in a position where you need to pass it as an IList, then you have a problem, because the method you're calling has specified that they might try to do something like I did above with the cat & dog. In most worlds, what that means is that the method you're calling is simply not built to work in a multi-threaded environment. That means you either refactor it so that it is or, if you can't, you're going to have to handle it very carefully. You you'll almost certainly be required to create your own collection with its own locks, and call the offending method within a lock.
used Martin's suggestion with a little tweak to add time stamp to the file name:
forfiles /p [foldername] /m rsync2.log /c "cmd /c ren @file %DATE:~6,4%%DATE:~3,2%%DATE:~0,2%_%time:~-11,2%-%time:~-8,2%-%time:~-5,2%-@file
For the 10:17:21 23/10/2019 The result is:
20191023_10-17-21-rsync2.log
Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)
Once you've generated your JSON, you can use something like the code below to POST it
StringRequestEntity requestEntity = new StringRequestEntity(
JSON_STRING,
"application/json",
"UTF-8");
PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);
int statusCode = httpClient.executeMethod(postMethod);
Edit
Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:
StringEntity requestEntity = new StringEntity(
JSON_STRING,
ContentType.APPLICATION_JSON);
HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);
HttpResponse rawResponse = httpclient.execute(postMethod);
Another function that would help you look at missing data would be df_status from funModeling library
library(funModeling)
iris.2 is the iris dataset with some added NAs.You can replace this with your dataset.
df_status(iris.2)
This will give you the number and percentage of NAs in each column.
Another way to make objects in Javascript
using JQuery
, getting data from the dom and pass it to the object Box and, for example, store them in an array of Boxes, could be:
var box = {}; // my object
var boxes = []; // my array
$('div.test').each(function (index, value) {
color = $('p', this).attr('color');
box = {
_color: color // being _color a property of `box`
}
boxes.push(box);
});
Hope it helps!
1) you are calling it wrong way try:
$(input[name="searchBar"]).val('hi')
2) if it doesn't work call your .js file at the end of the page or trigger your function on document.ready event
$(document).ready(function() {
$(input[name="searchBar"]).val('hi');
});
A little more elaborate example.
Setup: You have a website at example.com
and you have a web app at example.com/webapp
...
server {
listen 443 ssl;
server_name example.com;
root /usr/share/nginx/html/website_dir;
index index.html index.htm;
try_files $uri $uri/ /index.html;
location /webapp/ {
alias /usr/share/nginx/html/webapp_dir/;
index index.html index.htm;
try_files $uri $uri/ /webapp/index.html;
}
}
...
I've named webapp_dir
and website_dir
on purpose. If you have matching names and folders you can use the root
directive.
This setup works and is tested with Docker.
NB!!! Be careful with the slashes. Put them exactly as in the example.
You can subtract the time zone difference from now.
final Calendar calendar = Calendar.getInstance();
final int utcOffset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
final long tempDate = new Date().getTime();
return new Date(tempDate - utcOffset);
sizeWithFont constrainedToSize:lineBreakMode:
is the method to use. An example of how to use it is below:
//Calculate the expected size based on the font and linebreak mode of your label
// FLT_MAX here simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;
For drawing just the arrow, there is an easier method:-
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")
#draw the arrow
ax.quiver(0,0,0,1,1,1,length=1.0)
plt.show()
quiver can actually be used to plot multiple vectors at one go. The usage is as follows:- [ from http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html?highlight=quiver#mpl_toolkits.mplot3d.Axes3D.quiver]
quiver(X, Y, Z, U, V, W, **kwargs)
Arguments:
X, Y, Z: The x, y and z coordinates of the arrow locations
U, V, W: The x, y and z components of the arrow vectors
The arguments could be array-like or scalars.
Keyword arguments:
length: [1.0 | float] The length of each quiver, default to 1.0, the unit is the same with the axes
arrow_length_ratio: [0.3 | float] The ratio of the arrow head with respect to the quiver, default to 0.3
pivot: [ ‘tail’ | ‘middle’ | ‘tip’ ] The part of the arrow that is at the grid point; the arrow rotates about this point, hence the name pivot. Default is ‘tail’
normalize: [False | True] When True, all of the arrows will be the same length. This defaults to False, where the arrows will be different lengths depending on the values of u,v,w.
try this way
var url_string = window.location;
var url = new URL(url_string);
var name = url.searchParams.get("name");
var tvid = url.searchParams.get("id");
I've never had this problem, but I create a ~/.crontab file and edit that (which allows me to back it up, Time Machine or otherwise), then run
crontab ~/.crontab
Has worked for me for 20+ years across many flavors of unix.
I have tried above with above code but not working ,Here is solution to set current date selected in asp.net calendar control
dtpStartDate.SelectedDate = Convert.ToDateTime(DateTime.Now.Date);
dtpStartDate.VisibleDate = Convert.ToDateTime(DateTime.Now.ToString());
Just becuase your class object has no variables does not mean that it is nothing. Declaring and object and creating an object are two different things. Look and see if you are setting/creating the object.
Take for instance the dictionary object - just because it contains no variables does not mean it has not been created.
Sub test()
Dim dict As Object
Set dict = CreateObject("scripting.dictionary")
If Not dict Is Nothing Then
MsgBox "Dict is something!" '<--- This shows
Else
MsgBox "Dict is nothing!"
End If
End Sub
However if you declare an object but never create it, it's nothing.
Sub test()
Dim temp As Object
If Not temp Is Nothing Then
MsgBox "Temp is something!"
Else
MsgBox "Temp is nothing!" '<---- This shows
End If
End Sub
Please don't use printf("%s", your_string.c_str());
Use cout << your_string;
instead. Short, simple and typesafe. In fact, when you're writing C++, you generally want to avoid printf
entirely -- it's a leftover from C that's rarely needed or useful in C++.
As to why you should use cout
instead of printf
, the reasons are numerous. Here's a sampling of a few of the most obvious:
printf
isn't type-safe. If the type you pass differs from that given in the conversion specifier, printf
will try to use whatever it finds on the stack as if it were the specified type, giving undefined behavior. Some compilers can warn about this under some circumstances, but some compilers can't/won't at all, and none can under all circumstances.printf
isn't extensible. You can only pass primitive types to it. The set of conversion specifiers it understands is hard-coded in its implementation, and there's no way for you to add more/others. Most well-written C++ should use these types primarily to implement types oriented toward the problem being solved.It makes decent formatting much more difficult. For an obvious example, when you're printing numbers for people to read, you typically want to insert thousands separators every few digits. The exact number of digits and the characters used as separators varies, but cout
has that covered as well. For example:
std::locale loc("");
std::cout.imbue(loc);
std::cout << 123456.78;
The nameless locale (the "") picks a locale based on the user's configuration. Therefore, on my machine (configured for US English) this prints out as 123,456.78
. For somebody who has their computer configured for (say) Germany, it would print out something like 123.456,78
. For somebody with it configured for India, it would print out as 1,23,456.78
(and of course there are many others). With printf
I get exactly one result: 123456.78
. It is consistent, but it's consistently wrong for everybody everywhere. Essentially the only way to work around it is to do the formatting separately, then pass the result as a string to printf
, because printf
itself simply will not do the job correctly.
printf
format strings can be quite unreadable. Even among C programmers who use printf
virtually every day, I'd guess at least 99% would need to look things up to be sure what the #
in %#x
means, and how that differs from what the #
in %#f
means (and yes, they mean entirely different things).Search for the "datalist" tag.
<input list="texto_pronto" name="input_normal">
<datalist id="texto_pronto">
<option value="texto A">
<option value="texto B">
</datalist>
The javax.naming
package comprises the JNDI API. Since it's just an API, rather than an implementation, you need to tell it which implementation of JNDI to use. The implementations are typically specific to the server you're trying to talk to.
To specify an implementation, you pass in a Properties
object when you construct the InitialContext
. These properties specify the implementation to use, as well as the location of the server. The default InitialContext
constructor is only useful when there are system properties present, but the properties are the same as if you passed them in manually.
As to which properties you need to set, that depends on your server. You need to hunt those settings down and plug them in.
You must set the height of the container explicitly
#container {
height:100%;
width:100%;
position:absolute;
}
As far as I'm aware in order to format a date value you have to handle it in parameterMap,
$('#listDiv').kendoGrid({
dataSource: {
type: 'json',
serverPaging: true,
pageSize: 10,
transport: {
read: {
url: '@Url.Action("_ListMy", "Placement")',
data: refreshGridParams,
type: 'POST'
},
parameterMap: function (options, operation) {
if (operation != "read") {
var d = new Date(options.StartDate);
options.StartDate = kendo.toString(new Date(d), "dd/MM/yyyy");
return options;
}
else { return options; }
}
},
schema: {
model: {
id: 'Id',
fields: {
Id: { type: 'number' },
StartDate: { type: 'date', format: 'dd/MM/yyyy' },
Area: { type: 'string' },
Length: { type: 'string' },
Display: { type: 'string' },
Status: { type: 'string' },
Edit: { type: 'string' }
}
},
data: "Data",
total: "Count"
}
},
scrollable: false,
columns:
[
{
field: 'StartDate',
title: 'Start Date',
format: '{0:dd/MM/yyyy}',
width: 100
},
If you follow the above example and just renames objects like 'StartDate' then it should work (ignore 'data: refreshGridParams,')
For further details check out below link or just search for kendo grid parameterMap ans see what others have done.
http://docs.kendoui.com/api/framework/datasource#configuration-transport.parameterMap
ASCX files are server-side Web application framework designed for Web development to produce dynamic Web pages.They like DLL codes but you can use there's TAGS You can write them once and use them in any places in your ASP pages.If you have a file named "Controll.ascx" then its code will named "Controll.ascx.cs". You can embed it in a ASP page to use it:
To hide from the UI, use Format > Sheet > Hide
To hide programatically, use the Visible
property of the Worksheet
object. If you do it programatically, you can set the sheet as "very hidden", which means it cannot be unhidden through the UI.
ActiveWorkbook.Sheets("Name").Visible = xlSheetVeryHidden
' or xlSheetHidden or xlSheetVisible
You can also set the Visible property through the properties pane for the worksheet in the VBA IDE (ALT+F11).
Just did this and UrlSearchParams did the trick Here is my code if it helps someone
import 'url-search-params-polyfill';
const userLogsInOptions = (username, password) => {
// const formData = new FormData();
const formData = new URLSearchParams();
formData.append('grant_type', 'password');
formData.append('client_id', 'entrance-app');
formData.append('username', username);
formData.append('password', password);
return (
{
method: 'POST',
headers: {
// "Content-Type": "application/json; charset=utf-8",
"Content-Type": "application/x-www-form-urlencoded",
},
body: formData.toString(),
json: true,
}
);
};
const getUserUnlockToken = async (username, password) => {
const userLoginUri = `${scheme}://${host}/auth/realms/${realm}/protocol/openid-connect/token`;
const response = await fetch(
userLoginUri,
userLogsInOptions(username, password),
);
const responseJson = await response.json();
console.log('acces_token ', responseJson.access_token);
if (responseJson.error) {
console.error('error ', responseJson.error);
}
console.log('json ', responseJson);
return responseJson.access_token;
};
PROJECT eliminates columns while SELECT eliminates rows.
If you really want to use PHP as your backend for socket.io ,here are what I found. Two socket.io php server side alternative.
https://github.com/walkor/phpsocket.io
https://github.com/RickySu/phpsocket.io
Exmaple codes for the first repository like this.
use PHPSocketIO\SocketIO;
// listen port 2021 for socket.io client
$io = new SocketIO(2021);
$io->on('connection', function($socket)use($io){
$socket->on('chat message', function($msg)use($io){
$io->emit('chat message', $msg);
});
});
I guess that you have some value that uniquely identifies a person on which you can base your checks.
This is a tricky one. Assuming you want to keep the structure a tree, I suggest this:
Assume this: A
has kids with his own daughter.
A
adds himself to the program as A
and as B
. Once in the role of father, let's call it boyfriend.
Add a is_same_for_out()
function which tells the output generating part of your program that all links going to B
internally should be going to A
on presentation of data.
This will make some extra work for the user, but I guess IT would be relatively easy to implement and maintain.
Building from that, you could work on code synching A
and B
to avoid inconsistencies.
This solution is surely not perfect, but is a first approach.
Just expose dnozay's answer to a function so that we can import multiple certificates at the same time.
#!/usr/bin/env sh
KEYSTORE_FILE=/path/to/keystore.jks
KEYSTORE_PASS=changeit
import_cert() {
local HOST=$1
local PORT=$2
# get the SSL certificate
openssl s_client -connect ${HOST}:${PORT} </dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ${HOST}.cert
# delete the old alias and then import the new one
keytool -delete -keystore ${KEYSTORE_FILE} -storepass ${KEYSTORE_PASS} -alias ${HOST} &> /dev/null
# create a keystore and import certificate
keytool -import -noprompt -trustcacerts \
-alias ${HOST} -file ${HOST}.cert \
-keystore ${KEYSTORE_FILE} -storepass ${KEYSTORE_PASS}
rm ${HOST}.cert
}
import_cert stackoverflow.com 443
import_cert www.google.com 443
import_cert 172.217.194.104 443 # google
No need for jQuery and lot's of CSS anymore (Note that some browsers need extra CSS)
Kind of what @Abinthaha posted, but pure JS, without the need of jQuery.
let rotateAngle = 90;_x000D_
_x000D_
function rotate(image) {_x000D_
image.setAttribute("style", "transform: rotate(" + rotateAngle + "deg)");_x000D_
rotateAngle = rotateAngle + 90;_x000D_
}
_x000D_
#rotater {_x000D_
transition: all 0.3s ease;_x000D_
border: 0.0625em solid black;_x000D_
border-radius: 3.75em;_x000D_
}
_x000D_
<img id="rotater" onclick="rotate(this)" src="https://upload.wikimedia.org/wikipedia/en/e/e0/Iron_Man_bleeding_edge.jpg"/>
_x000D_
Check if the manifest is a valid xml file. I had the same problem by doing a DOS copy command at the end of the build, and it turns out that for some reason I can not understand "copy" was adding a strange character (->) at the end of the manifest files. The problem was solved by adding "/b" switch to force binary copy.
You can get the icons from the android sdk they are in this folder
$android-sdk\platforms\android-xx\data\res
Recently I faced a similar problem. I was using the sublime editor. it's not an issue with the code but with the editor.
Below change in the preference settings worked for me.
Sublime Text menu -> Preferences -> Settings: Syntax-Specific:
{
"tab_size": 4,
"translate_tabs_to_spaces": true
}
Depending on what exactly you are doing you could make an image and set it as the background programatically.
ActiveX is only supported by IE - the other browsers use a plugin architecture called NPAPI. However, there's a cross-browser plugin framework called Firebreath that you might find useful.
I like Tony approach. It works, but I decided to implement in different way. Here my comments:
1) I did some tests and when using ng-style, Angular evaluates ng-style content, I mean getTableHeight() function more than once. I put a breakpoint into getTableHeight() function to analyze this.
By the way, ui-if was removed. Now you have ng-if build-in.
2) I prefer to write a service like this:
angular.module('angularStart.services').factory('uiGridService', function ($http, $rootScope) {
var factory = {};
factory.getGridHeight = function(gridOptions) {
var length = gridOptions.data.length;
var rowHeight = 30; // your row height
var headerHeight = 40; // your header height
var filterHeight = 40; // your filter height
return length * rowHeight + headerHeight + filterHeight + "px";
}
factory.removeUnit = function(value, unit) {
return value.replace(unit, '');
}
return factory;
});
And then in the controller write the following:
angular.module('app',['ui.grid']).controller('AppController', ['uiGridConstants', function(uiGridConstants) {
...
// Execute this when you have $scope.gridData loaded...
$scope.gridHeight = uiGridService.getGridHeight($scope.gridData);
And at the HTML file:
<div id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize style="height: {{gridHeight}}"></div>
When angular applies the style, it only has to look in the $scope.gridHeight variable and not to evaluate a complete function.
3) If you want to calculate dynamically the height of an expandable grid, it is more complicated. In this case, you can set expandableRowHeight property. This fixes the reserved height for each subgrid.
$scope.gridData = {
enableSorting: true,
multiSelect: false,
enableRowSelection: true,
showFooter: false,
enableFiltering: true,
enableSelectAll: false,
enableRowHeaderSelection: false,
enableGridMenu: true,
noUnselect: true,
expandableRowTemplate: 'subGrid.html',
expandableRowHeight: 380, // 10 rows * 30px + 40px (header) + 40px (filters)
onRegisterApi: function(gridApi) {
gridApi.expandable.on.rowExpandedStateChanged($scope, function(row){
var height = parseInt(uiGridService.removeUnit($scope.jdeNewUserConflictsGridHeight,'px'));
var changedRowHeight = parseInt(uiGridService.getGridHeight(row.entity.subGridNewUserConflictsGrid, true));
if (row.isExpanded)
{
height += changedRowHeight;
}
else
{
height -= changedRowHeight;
}
$scope.jdeNewUserConflictsGridHeight = height + 'px';
});
},
columnDefs : [
{ field: 'GridField1', name: 'GridField1', enableFiltering: true }
]
}
Sharing on Facebook: How to Improve Your Results by Customizing the Image, Title, and Text
From the link above. For the best possible share, you'll want to suggest 3 pieces of data in your HTML:
This accomplished by the following, placed inside the 'head' tag of your HTML:
<title>INSERT POST TITLE</title>
<meta property=og:image content="http://site.com/YOUR_IMAGE.jpg"/>
<meta name=description content="INSERT YOUR SUMMARY TEXT"/>
If you website is static HTML, you'll have to do this for every page using your HTML editor.
If you're using a CMS like Drupal, you can automate a lot of it (see above link). If you use wordpress, you can probably implement something similar using the Drupal example as a guideline. I hope you found these useful.
Finally, you can always manually edit your share posts. See this example with illustrations.
You need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
Then you can use the following in your activity class:
WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
Use the following to check if it's enabled or not
boolean wifiEnabled = wifiManager.isWifiEnabled()
You'll find a nice tutorial on the subject on this site.
For anyone looking to use this and keep the 'click' functionality (as John Landheer mentions in his comment), you can do it with just a couple of modifications:
Add a couple of globals:
var clickms = 100;
var lastTouchDown = -1;
Then modify the switch statement from the original to this:
var d = new Date();
switch(event.type)
{
case "touchstart": type = "mousedown"; lastTouchDown = d.getTime(); break;
case "touchmove": type="mousemove"; lastTouchDown = -1; break;
case "touchend": if(lastTouchDown > -1 && (d.getTime() - lastTouchDown) < clickms){lastTouchDown = -1; type="click"; break;} type="mouseup"; break;
default: return;
}
You may want to adjust 'clickms' to your tastes. Basically it's just watching for a 'touchstart' followed quickly by a 'touchend' to simulate a click.
In this line:
fund = fund * (1 + 0.01 * growthRates) + depositPerYear
growthRates is a sequence ([3,4,5,0,3]
). You can't multiply that sequence by a float (0.1). It looks like what you wanted to put there was i
.
Incidentally, i
is not a great name for that variable. Consider something more descriptive, like growthRate
or rate
.
None of these other answers worked for me. Here's what I had to do to run a procedure in SQL Developer 3.2.20.10:
SET serveroutput on;
DECLARE
testvar varchar(100);
BEGIN
testvar := 'dude';
schema.MY_PROC(testvar);
dbms_output.enable;
dbms_output.put_line(testvar);
END;
And then you'd have to go check the table for whatever your proc was supposed to do with that passed-in variable -- the output will just confirm that the variable received the value (and theoretically, passed it to the proc).
NOTE (differences with mine vs. others):
:
prior to the variable name.package.
or .packages.
between the schema name and the procedure name&
in the variable's value.print
anywherevar
to declare the variableAll of these problems left me scratching my head for the longest and these answers that have these egregious errors out to be taken out and tarred and feathered.
You have to do binding in a directive. Look at this:
angular.module('ng', []).
directive('sliderRange', function($parse, $timeout){
return {
restrict: 'A',
replace: true,
transclude: false,
compile: function(element, attrs) {
var html = '<div class="slider-range"></div>';
var slider = $(html);
element.replaceWith(slider);
var getterLeft = $parse(attrs.ngModelLeft), setterLeft = getterLeft.assign;
var getterRight = $parse(attrs.ngModelRight), setterRight = getterRight.assign;
return function (scope, slider, attrs, controller) {
var vsLeft = getterLeft(scope), vsRight = getterRight(scope), f = vsLeft || 0, t = vsRight || 10;
var processChange = function() {
var vs = slider.slider("values"), f = vs[0], t = vs[1];
setterLeft(scope, f);
setterRight(scope, t);
}
slider.slider({
range: true,
min: 0,
max: 10,
step: 1,
change: function() { setTimeout(function () { scope.$apply(processChange); }, 1) }
}).slider("values", [f, t]);
};
}
};
});
This shows you an example of a slider range, done with jQuery UI. Example usage:
<div slider-range ng-model-left="question.properties.range_from" ng-model-right="question.properties.range_to"></div>
Any color theme can be changed in this settings section on VS Code version 1.12 or higher:
// Overrides colors from the currently selected color theme.
"workbench.colorCustomizations": {}
See https://code.visualstudio.com/docs/getstarted/themes#_customize-a-color-theme
Available values to edit: https://code.visualstudio.com/docs/getstarted/theme-color-reference
EDIT: To change syntax colors, see here: https://code.visualstudio.com/docs/extensions/themes-snippets-colorizers#_syntax-highlighting-colors and here: https://www.sublimetext.com/docs/3/scope_naming.html
In addition to the above, you can do this (where "YourListObjectName" is the name of your table):
Dim LO As ListObject
Set LO = ActiveSheet.ListObjects("YourListObjectName")
But I think that only works if you want to reference a list object that's on the active sheet.
I found your question because I wanted to refer to a list object (a table) on one worksheet that a pivot table on a different worksheet refers to. Since list objects are part of the Worksheets collection, you have to know the name of the worksheet that list object is on in order to refer to it. So to get the name of the worksheet that the list object is on, I got the name of the pivot table's source list object (again, a table) and looped through the worksheets and their list objects until I found the worksheet that contained the list object I was looking for.
Public Sub GetListObjectWorksheet()
' Get the name of the worksheet that contains the data
' that is the pivot table's source data.
Dim WB As Workbook
Set WB = ActiveWorkbook
' Create a PivotTable object and set it to be
' the pivot table in the active cell:
Dim PT As PivotTable
Set PT = ActiveCell.PivotTable
Dim LO As ListObject
Dim LOWS As Worksheet
' Loop through the worksheets and each worksheet's list objects
' to find the name of the worksheet that contains the list object
' that the pivot table uses as its source data:
Dim WS As Worksheet
For Each WS In WB.Worksheets
' Loop through the ListObjects in each workshet:
For Each LO In WS.ListObjects
' If the ListObject's name is the name of the pivot table's soure data,
' set the LOWS to be the worksheet that contains the list object:
If LO.Name = PT.SourceData Then
Set LOWS = WB.Worksheets(LO.Parent.Name)
End If
Next LO
Next WS
Debug.Print LOWS.Name
End Sub
Maybe someone knows a more direct way.
ObjectID
s are objects so if you just compare them with ==
you're comparing their references. If you want to compare their values you need to use the ObjectID.equals
method:
if (results.userId.equals(AnotherMongoDocument._id)) {
...
}
Long.MAX_VALUE
is 9,223,372,036,854,775,807
.
If you were executing your function once per nanosecond, it would still take over 292 years to encounter this situation according to this source.
When that happens, it'll just wrap around to Long.MIN_VALUE
, or -9,223,372,036,854,775,808
as others have said.
http://astutejs.blogspot.in/2015/07/angularjs-what-is-rootscope.html
app.controller('AppCtrl2', function ($scope, $rootScope) {
$scope.msg = 'SCOPE';
$rootScope.name = 'ROOT SCOPE';
});
That's happen usually when you con-cat strings with + sign. In PHP you can make concatenation using dot sign (.) So sometimes I accidentally put + sign between two strings in PHP, and it show me this error, since you can use + sign in numbers only.
Okay, oninvalid works well but it shows error even if user entered valid data. So I have used below to tackle it, hope it will work for you as well,
oninvalid="this.setCustomValidity('Your custom message.')"
onkeyup="setCustomValidity('')"
Old question, but my solution is a bit different.
I was writing a single page web app that was constantly making ajax calls triggered by the user, and to make it even more difficult it required libraries that used methods other than jquery (like dojo, native xhr, etc). I wrote a plugin for one of my own libraries to cache ajax requests as efficiently as possible in a way that would work in all major browsers, regardless of which libraries were being used to make the ajax call.
The solution uses jSQL (written by me - a client-side persistent SQL implementation written in javascript which uses indexeddb and other dom storage methods), and is bundled with another library called XHRCreep (written by me) which is a complete re-write of the native XHR object.
To implement all you need to do is include the plugin in your page, which is here.
There are two options:
jSQL.xhrCache.max_time = 60;
Set the maximum age in minutes. any cached responses that are older than this are re-requested. Default is 1 hour.
jSQL.xhrCache.logging = true;
When set to true, mock XHR calls will be shown in the console for debugging.
You can clear the cache on any given page via
jSQL.tables = {}; jSQL.persist();
A slight modification to @Galwegian's answer - which turns e.g. St Elizabeth's
into St Elizabeth'S
.
This modification keeps apostrophe-s as lowercase where the s comes at the end of the string provided or the s is followed by a space (and only in those circumstances).
create function properCase(@text as varchar(8000))
returns varchar(8000)
as
begin
declare @reset int;
declare @ret varchar(8000);
declare @i int;
declare @c char(1);
declare @d char(1);
if @text is null
return null;
select @reset = 1, @i = 1, @ret = '';
while (@i <= len(@text))
select
@c = substring(@text, @i, 1),
@d = substring(@text, @i+1, 1),
@ret = @ret + case when @reset = 1 or (@reset=-1 and @c!='s') or (@reset=-1 and @c='s' and @d!=' ') then upper(@c) else lower(@c) end,
@reset = case when @c like '[a-za-z]' then 0 when @c='''' then -1 else 1 end,
@i = @i + 1
return @ret
end
It turns:
st elizabeth's
into St Elizabeth's
o'keefe
into O'Keefe
o'sullivan
into O'Sullivan
Others' comments that different solutions are preferable for non-English input remain the case.