Use "in" or "where".
Its gonna be something like this:
db.mycollection.find( { $where : function() {
return ( this.startTime < Now() && this.expireTime > Now() || this.expireTime == null ); } } );
In addition to what people wrote years ago:
main.c:30:3: warning: unknown conversion type character 'l' in format [-Wformat=]
printf("%llu\n", k);
Then your version of mingw does not default to c99. Add this compiler flag: -std=c99
.
You can do this in two ways:
f.write("text to write\n")
or, depending on your Python version (2 or 3):
print >>f, "text to write" # Python 2.x
print("text to write", file=f) # Python 3.x
Create New User Environment Variables:
MAVEN_HOME=D:\apache-maven-3.5.3
MAVEN=D:\apache-maven-3.5.3\bin
MAVEN_OPTS=-Xms256m -Xmx512m
Appened below in Path variable (System Variable):
;D:\apache-maven-3.5.3\bin;
I did find this somewhere. Can't remember where though... probably on StackOverflow :)
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
SELECT p.LastName, p.FirstName, o.OrderNo
FROM persons AS p
LEFT JOIN
orders AS o
ON o.orderNo = p.p_id
UNION ALL
SELECT NULL, NULL, orderNo
FROM orders
WHERE orderNo NOT IN
(
SELECT p_id
FROM persons
)
You can also use hostbinding:
import { HostBinding } from '@angular/core';
export class HomeComponent {
@HostBinding('style.width') width: Number;
@HostBinding('style.height') height: Number;
}
Now when you change the width or height property from within the HomeComponent, this should affect the style attributes.
@echo off cls echo press any key to continue backup ! pause xcopy c:\users\file*.* e:\backup*.* /s /e echo backup complete pause
file = name of file your wanting to copy
Hope this helps
Sure. I suppose that you have already installed TensorFlow for GPU.
You need to add the following block after importing keras. I am working on a machine which have 56 core cpu, and a gpu.
import keras
import tensorflow as tf
config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 56} )
sess = tf.Session(config=config)
keras.backend.set_session(sess)
Of course, this usage enforces my machines maximum limits. You can decrease cpu and gpu consumption values.
Try this
#include <stdio.h>
struct context;
struct funcptrs{
void (*func0)(struct context *ctx);
void (*func1)(void);
};
struct context{
struct funcptrs fps;
};
void func1 (void) { printf( "1\n" ); }
void func0 (struct context *ctx) { printf( "0\n" ); }
void getContext(struct context *con){
con->fps.func0 = func0;
con->fps.func1 = func1;
}
int main(int argc, char *argv[]){
struct context c;
c.fps.func0 = func0;
c.fps.func1 = func1;
getContext(&c);
c.fps.func0(&c);
getchar();
return 0;
}
Have you tried JMX?
http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html
(source: sun.com)
I am assuming that you need the JDK itself. If so you can accomplish this with:
sudo add-apt-repository ppa:sun-java-community-team/sun-java6
sudo apt-get update
sudo apt-get install sun-java6-jdk
You don't really need to go around editing sources or anything along those lines.
One way to block commenting in YAML is by using a text editor like Notepad++ to add a # (comment) tag to multiple lines at once.
In Notepad++ you can do that using the "Block Comment" right-click option for selected text.
pgAdmin has GUI for data import since 1.16. You have to create your table first and then you can import data easily - just right-click on the table name and click on Import.
Simply you could use:
PartialView("../ABC/XXX")
Use it to access class in Javascript.
<script type="text/javascript">
var var_name = document.getElementsByClassName("class_name")[0];
</script>
If you don't mind mutating x
,
x.update(y) or x
Simple, readable, performant. You know update()
always returns None
, which is a false value. So the above expression will always evaluate to x
, after updating it.
Most mutating methods in the standard library (like .update()
) return None
by convention, so this kind of pattern will work on those too. However, if you're using a dict subclass or some other method that doesn't follow this convention, then or
may return its left operand, which may not be what you want. Instead, you can use a tuple display and index, which works regardless of what the first element evaluates to (although it's not quite as pretty):
(x.update(y), x)[-1]
If you don't have x
in a variable yet, you can use lambda
to make a local without using an assignment statement. This amounts to using lambda
as a let expression, which is a common technique in functional languages, but maybe unpythonic.
(lambda x: x.update(y) or x)({'a': 1, 'b': 2})
Although it's not that different from the following use of the new walrus operator (Python 3.8+ only):
(x := {'a': 1, 'b': 2}).update(y) or x
If you do want a copy, PEP 584 style x | y
is the most Pythonic on 3.9+. If you must support older versions, PEP 448 style {**x, **y}
is easiest for 3.5+. But if that's not available in your (even older) Python version, the let pattern works here too.
(lambda z: z.update(y) or z)(x.copy())
(That is, of course, nearly equivalent to (z := x.copy()).update(y) or z
, but if your Python version is new enough for that, then the PEP 448 style will be available.)
Use slideToggle(500) function with a duration in milliseconds for getting a better effect.
Sample Html
<body>
<div class="growth-step js--growth-step">
<div class="step-title">
<div class="num">2.</div>
<h3>How Can Aria Help Your Business</h3>
</div>
<div class="step-details ">
<p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
management organization with expertise. </p>
</div>
</div>
<div class="growth-step js--growth-step">
<div class="step-title">
<div class="num">3.</div>
<h3>How Can Aria Help Your Business</h3>
</div>
<div class="step-details">
<p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
management organization with expertise. </p>
</div>
</div>
</body>
In your js file, if you need child propagation for the animation then remove the second click event function and its codes.
$(document).ready(function(){
$(".js--growth-step").click(function(event){
$(this).children(".step-details").slideToggle(500);
return false;
});
//for stoping child to manipulate the animation
$(".js--growth-step .step-details").click(function(event) {
event.stopPropagation();
});
});
Also, be sure, that two-factor authentication is off, otherwise use personal access tokens
Details here : Can I use GitHub's 2-Factor Authentication with TortoiseGit?
Short answer:
Remove (from list results
)
results.RemoveAll(r => r.ID == 2);
will remove the item with ID 2 in results
(in place).
Filter (without removing from original list results
):
var filtered = result.Where(f => f.ID != 2);
returns all items except the one with ID 2
Detailed answer:
I think .RemoveAll()
is very flexible, because you can have a list of item IDs which you want to remove - please regard the following example.
If you have:
class myClass {
public int ID; public string FirstName; public string LastName;
}
and assigned some values to results
as follows:
var results = new List<myClass> {
new myClass { ID=1, FirstName="Bill", LastName="Smith" }, // results[0]
new myClass { ID=2, FirstName="John", LastName="Wilson" }, // results[1]
new myClass { ID=3, FirstName="Doug", LastName="Berg" }, // results[2]
new myClass { ID=4, FirstName="Bill", LastName="Wilson" } // results[3]
};
Then you can define a list of IDs to remove:
var removeList = new List<int>() { 2, 3 };
And simply use this to remove them:
results.RemoveAll(r => removeList.Any(a => a==r.ID));
It will remove the items 2 and 3 and keep the items 1 and 4 - as specified by the removeList
. Note that this happens in place, so there is no additional assigment required.
Of course, you can also use it on single items like:
results.RemoveAll(r => r.ID==4);
where it will remove Bill with ID 4 in our example.
A last thing to mention is that lists have an indexer, that is, they can also be accessed like a dynamic array, i.e. results[3]
will give you the 4th element in the results list (because the first element has the index 0, the 2nd has index 1 etc).
So if you want to remove all entries where the first name is the same as in the 4th element of the results list, you can simply do it this way:
results.RemoveAll(r => results[3].FirstName == r.FirstName);
Note that afterwards, only John and Doug will remain in the list, Bill is removed (the first and last element in the example). Important is that the list will shrink automatically, so it has only 2 elements left - and hence the largest allowed index after executing RemoveAll in this example is 1
(which is results.Count() - 1
).
Some Trivia: You can use this knowledge and create a local function
void myRemove() { var last = results.Count() - 1;
results.RemoveAll(r => results[last].FirstName == r.FirstName); }
What do you think will happen, if you call this function twice? Like
myRemove(); myRemove();
The first call will remove Bill at the first and last position, the second call will remove Doug and only John Wilson remains in the list.
DotNetFiddle: Run the demo
Note: Since C# Version 8, you can as well write results[^1]
instead of var last = results.Count() - 1;
and results[last]
:
void myRemove() { results.RemoveAll(r => results[^1].FirstName == r.FirstName); }
So you would not need the local variable last
anymore (see indices and ranges. For a list of all the new features in C#, look here).
cd <your project folder>
(where your angularjs's deployable code is there)
sudo npm install serve -g
serve
You can hit your page at
localhost:3000 or IPaddress:3000
git rebase -i HEAD~<quantity of your commits>
(i.e. git rebase -i HEAD~5
)txt
file change pick
keyword to squash
for all commits, except first commit (which is on the top). For top one change it to reword
(which means you will provide a new comment for this commit in the next step) and click SAVE! If in vim, press esc
then save by entering wq!
and press enter.Done
I had the same problem. But I also had to perform additional steps. Here is what I did.
Perform the following steps (Only 64bit version of SQL Server 2005 Developer Edition tested on Windows 8 Pro 64bit)
For STEP 5 above: Although I didn't try looking into SP4 / SP3 setup for SQLSERVR.EXE and SQLOS.DLL but if you don't have an existing installation of SQL Server 2005 SP3/SP4 then maybe try looking into the SP3/SP4 EXE (Compressed file). I am not sure if this may help. In any case you can create a VM and install SQL Server 2005 with SP3/Sp4 to copy the files for Windows 8
Following class implements fast method described in this article and contains all you need: readPixel
, putPixel
, get width/height
. Class update canvas after calling refresh()
method. Example solve simple case of 2d wave equation
class Screen{
constructor(canvasSelector) {
this.canvas = document.querySelector(canvasSelector);
this.width = this.canvas.width;
this.height = this.canvas.height;
this.ctx = this.canvas.getContext('2d');
this.imageData = this.ctx.getImageData(0, 0, this.width, this.height);
this.buf = new ArrayBuffer(this.imageData.data.length);
this.buf8 = new Uint8ClampedArray(this.buf);
this.data = new Uint32Array(this.buf);
}
// r,g,b,a - red, gren, blue, alpha components in range 0-255
putPixel(x,y,r,g,b,a=255) {
this.data[y * this.width + x] = (a<<24) | (b<<16) | (g<<8) | r;
}
readPixel(x,y) {
let p= this.data[y * this.width + x]
return [p&0xff, p>>8&0xff, p>>16&0xff, p>>>24];
}
refresh() {
this.imageData.data.set(this.buf8);
this.ctx.putImageData(this.imageData, 0, 0);
}
}
// --------
// TEST
// --------
let s= new Screen('#canvas'); // initialise
function draw() {
for (var y = 1; y < s.height-1; ++y) {
for (var x = 1; x < s.width-1; ++x) {
let a = [[1,0],[-1,0],[0,1],[0,-1]].reduce((a,[xp,yp])=>
a+= s.readPixel(x+xp,y+yp)[0] // read pixel
,0);
let v= a/1.99446-tmp[x][y];
tmp[x][y]=v<0 ? 0:v;
}
}
for (var y = 1; y < s.height-1; ++y) {
for (var x = 1; x < s.width-1; ++x) {
let v=tmp[x][y];
tmp[x][y]= s.readPixel(x,y)[0]; // read pixel
s.putPixel(x,y, v,0,0); // put pixel
}
}
s.refresh();
frame++;
window.requestAnimationFrame(draw)
}
// temporary 2d buffer ()for solving wave equation)
let tmp = [...Array(s.width)].map(x => Array(s.height).fill(0));
function move(e) { s.putPixel(e.x-10, e.y-10, 255,255,255);}
draw();
_x000D_
<canvas id="canvas" height="150" width="512" onmousemove="move(event)"></canvas>
<div>Move mouse on black square</div>
_x000D_
Dude,
lets say you're a very lucky guy just like I've been, go back to your editor and do an undo(command + Z for mac), you should see your lost content in the file. Hope it helped you. Of course, this will work only for existing files.
Test Data
DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)
Query
SELECT ID
,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
FROM @Table1
WHERE ID = t.ID
FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
SQL Server 2017 and Later Versions
If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:
DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);
SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
No difference here, but it matters when you have a type that has a constructor.
struct S {
constexpr S(int);
};
const S s0(0);
constexpr S s1(1);
s0
is a constant, but it does not promise to be initialized at compile-time. s1
is marked constexpr
, so it is a constant and, because S
's constructor is also marked constexpr
, it will be initialized at compile-time.
Mostly this matters when initialization at runtime would be time-consuming and you want to push that work off onto the compiler, where it's also time-consuming, but doesn't slow down execution time of the compiled program
I inherited a bunch of .JAVA files from elsewhere and couldn't figure out how to get them to work in any IDE. Ultimately I had to go to the command line where the Main.JAVA file was and run javac Main.java
. This created a bunch of .CLASS files. The IDE's were then able to figure out what to do.
This also handles the keyboard activation.
private void dgvApps_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if(dgvApps.CurrentCell.GetType() == typeof(DataGridViewCheckBoxCell))
{
if (dgvApps.CurrentCell.IsInEditMode)
{
if (dgvApps.IsCurrentCellDirty)
{
dgvApps.EndEdit();
}
}
}
}
private void dgvApps_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
// handle value changed.....
}
There is an easier solution to this problem.
You just need to add a t
to the mode so it becomes wt
. This causes Python to open the file as a text file and not binary. Then everything will just work.
The complete program becomes this:
plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wt") as outfile:
outfile.write(plaintext)
Try this :
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Test {
public static void main(String[] args) {
JFrame f = new JFrame();
try {
f.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("test.jpg")))));
} catch (IOException e) {
e.printStackTrace();
}
f.pack();
f.setVisible(true);
}
}
By the way, this will result in the content pane not being a container. If you want to add things to it you have to subclass a JPanel and override the paintComponent method.
That's an Object and you want to count the properties of it.
Object.keys(jsonArray).length
References:
Offical plugins
You can use the output callback plugins. For example, starting in Ansible 2.4, you can use the debug output callback plugin:
# In ansible.cfg:
[defaults]
stdout_callback = debug
(Altervatively, run export ANSIBLE_STDOUT_CALLBACK=debug
before running your playbook)
Important: you must run ansible-playbook
with the -v
(--verbose
) option to see the effect. With stdout_callback = debug
set, the output should now look something like this:
TASK [Say Hello] ********************************
changed: [192.168.1.2] => {
"changed": true,
"rc": 0
}
STDOUT:
Hello!
STDERR:
Shared connection to 192.168.1.2 closed.
There are other modules besides the debug
module if you want the output to be formatted differently. There's json
, yaml
, unixy
, dense
, minimal
, etc. (full list).
For example, with stdout_callback = yaml
, the output will look something like this:
TASK [Say Hello] **********************************
changed: [192.168.1.2] => changed=true
rc: 0
stderr: |-
Shared connection to 192.168.1.2 closed.
stderr_lines:
- Shared connection to 192.168.1.2 closed.
stdout: |2-
Hello!
stdout_lines: <omitted>
Third-party plugins
If none of the official plugins are satisfactory, you can try the human_log
plugin. There are a few versions:
HTML
<input type="text" name="number" only-digits>
// Just type 123
.directive('onlyDigits', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var digits = val.replace(/[^0-9]/g, '');
if (digits !== val) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseInt(digits,10);
}
return undefined;
}
ctrl.$parsers.push(inputValue);
}
};
// type: 123 or 123.45
.directive('onlyDigits', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var digits = val.replace(/[^0-9.]/g, '');
if (digits !== val) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseFloat(digits);
}
return undefined;
}
ctrl.$parsers.push(inputValue);
}
};
You can use recyclerView.getChildAt()
to get each visible child, and setting some tag convertview.setTag(index)
on these view in adapter code will help you to relate it with adapter data.
You also can do theCallback
using the Delegate
pattern:
Callback.java
public interface Callback {
void onItemSelected(int position);
}
PagerActivity.java
public class PagerActivity implements Callback {
CustomPagerAdapter mPagerAdapter;
public PagerActivity() {
mPagerAdapter = new CustomPagerAdapter(this);
}
@Override
public void onItemSelected(int position) {
// Do something
System.out.println("Item " + postion + " selected")
}
}
CustomPagerAdapter.java
public class CustomPagerAdapter {
private static final int DEFAULT_POSITION = 1;
public CustomPagerAdapter(Callback callback) {
callback.onItemSelected(DEFAULT_POSITION);
}
}
Steps:
1 - Right click on your task bar -->Start Task Manager
2 - Click on Services button (at bottom).
3 - Search for MYSQL57
4 - Right Click on MYSQL57 --> Start
Now again start your mysql-cmd-prompt or MYSQL WorkBench
This answer is based on Eclipse 3.4, but should work in older versions of Eclipse.
When selecting Run As..., go into the run configurations.
On the Arguments tab of your Java run configuration, configure the variable ${string_prompt} to appear (you can click variables to get it, or copy that to set it directly).
Every time you use that run configuration (name it well so you have it for later), you will be prompted for the command line arguments.
Another trick for getting sequential pieces (beyond the seq solution already mentioned) is to use a short logical vector and use vector recycling:
foo[ c( rep(FALSE, 5), TRUE ) ]
By default EC2 is secured by AWS Security Group (A service found in EC2 and VPC). Security Group by default are disallowing Any ICMP request which includes the ping. To allow it:
Goto: AWS EC2 Instance Locate: The Security Group bind to that instance (It's possible to have multiple security group) Check: Inbound Rules for Protocol (ICMP) Port (0 - 65535) if it's not present you can add it and allow it on your specified source IP or Another Security Group.
Just add this code, And it will work like charm:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST}#%{HTTPS}s ^www\.([^#]+)#(?:off|on(s)) [NC]
RewriteRule ^ http%2://%1%{REQUEST_URI} [R=301,L]
</IfModule>
Just had a similar issue
Resolved it by checking in httpd.conf
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All <--- make sure this is not set to "None"
It is worth bearing in mind I tried (from Mark's answer) the "put garbage in the .htaccess" which did give a server error - but even though it was being read, it wasn't being acted on due to no overrides allowed.
The two answers did not solve my issue but combining them, I was able to solve the problem. My situation was I was trying to install and run Docker on a Windows 7 pc and kept getting an error: "Looks like something went wrong... Press any key to continue..."
After much digging, I was able to relate the issue to the host network adapter that was created by Docker. I had the NDIS6 driver installed but it was enabled. I tried to uncheck, disable, recheck, enable etc but it did not help.
I then uninstalled VB and reinstalled as per the first answer to get the NDIS5 driver. This was unchecked, so checking it I was able to move past this issue.
.map files allow a browser to download a full version of the minified JS. It is really for debugging purposes.
In effect, the .map missing isn't a problem. You only know it is missing, as the browser has had its Developer tools opened, detected a minified file and is just informing you that the JS debugging won't be as good as it could be.
This is why libraries like jQuery have the full, the minified and the map file too.
See this article for a full explanation of .map files:
You can invoke private method with reflection. Modifying the last bit of the posted code:
Method method = object.getClass().getDeclaredMethod(methodName);
method.setAccessible(true);
Object r = method.invoke(object);
There are a couple of caveats. First, getDeclaredMethod
will only find method declared in the current Class
, not inherited from supertypes. So, traverse up the concrete class hierarchy if necessary. Second, a SecurityManager
can prevent use of the setAccessible
method. So, it may need to run as a PrivilegedAction
(using AccessController
or Subject
).
I have to point that out as a lot of people can struggle into that without knowing the problem.
If you want the kb to hide when clicking Done
, and you set android:imeOptions="actionDone"
& android:maxLines="1"
without setting your EditText inputType
it will NOT work as the default inputType
for the EditText is not "text"
as a lot of people think.
so, setting only inputType
will give you the results you desire whatever what you are setting it to like "text"
, "number"
, ...etc.
Cloud: the hardware running the application scales to meet the demand (potentially crossing multiple machines, networks, etc).
Grid: the application scales to take as much hardware as possible (for example in the hope of finding extra-terrestrial intelligence).
Cluster: this is an old term referring to one OS instance or one DB instance installed across multiple machines. It was done with special OS handling, proprietary drivers, low latency network cards with fat cables, and various hardware bedfellows.
(We love you SGI, but notice that "Cloud" and "Grid" are available to the little guy and your NUMAlink never has been...)
Just Check your webconfig file and remove this code :-
<dependentAssembly>
<assemblyIdentity name="itextsharp" publicKeyToken="8354ae6d2174ddca" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.5.13.0" newVersion="5.5.13.0" />
</dependentAssembly>
docker run -it -name YOUR_NAME IMAGE_ID /bin/bash
$>vi path_to_file
If you have to work with file-stream (so no physically saved PDF) like we do and you want to download the PDF without page-reload, the following function works for us:
HTML
<div id="download-helper-hidden-container" style="display:none">
<form id="download-helper-form" target="pdf-download-output" method="post">
<input type="hidden" name="downloadHelperTransferData" id="downloadHelperTransferData" />
</form>
<iframe id="pdf-helper-output" name="pdf-download-output"></iframe>
</div>
Javascript
var form = document.getElementById('download-helper-form');
$("#downloadHelperTransferData").val(transferData);
form.action = "ServerSideFunctionWhichWritesPdfBytesToResponse";
form.submit();
Due to the target="pdf-download-output", the response is written into the iframe and therefore no page reload is executed, but the pdf-response-stream is output in the browser as a download.
=TEXT(A1,"0000")
However the TEXT function is able to do other fancy stuff like date formating, aswell.
if you have a fixed height footer (for example 712px) you can do this with js like so:
var bgTop = 0;
window.addEventListener("resize",theResize);
function theResize(){
bgTop = winHeight - 712;
document.getElementById("bg").style.marginTop = bgTop+"px";
}
After data-binding, do this:
ddlColor.Items.Insert(0, new ListItem("Select","NA")); //updated code
Or follow Brian's second suggestion if you want to do it in markup.
You should probably add a RequiredFieldValidator control and set its InitialValue to "NA".
<asp:RequiredFieldValidator .. ControlToValidate="ddlColor" InitialValue="NA" />
A small word of caution, if "do some stuff" means updating the value of the actual property that you visit AND if there is a struct type property along the path from root object to the visited property, the change you made on the property will not be reflected on the root object.
Robert Love's book LINUX System Programming 2nd Edition, specifically addresses your question at the beginning of Chapter 11, pg 363:
The important aspect of a monotonic time source is NOT the current value, but the guarantee that the time source is strictly linearly increasing, and thus useful for calculating the difference in time between two samplings
That said, I believe he is assuming the processes are running on the same instance of an OS, so you might want to have a periodic calibration running to be able to estimate drift.
When you directly run the rake task or execute any binary file of a gem, there is no guarantee that the command will behave as expected. Because it might happen that you already have the same gem installed on your system which have a version say 1.0 but in your project you have higher version say 2.0. In this case you can not predict which one will be used.
To enforce the desired gem version you take the help of bundle exec
command which would execute the binary in context of current bundle. That means when you use bundle exec, bundler checks the gem version configured for the current project and use that to perform the task.
I have also written a post about it which also shows how we can avoid using it using bin stubs.
just give elem.fadeOut(10).fadeIn(10);
I know than it's a really old question, but if someone is interested in this feature, can check this code http://vim.wikia.com/wiki/Auto_highlight_current_word_when_idle
" Highlight all instances of word under cursor, when idle.
" Useful when studying strange source code.
" Type z/ to toggle highlighting on/off.
nnoremap z/ :if AutoHighlightToggle()<Bar>set hls<Bar>endif<CR>
function! AutoHighlightToggle()
let @/ = ''
if exists('#auto_highlight')
au! auto_highlight
augroup! auto_highlight
setl updatetime=4000
echo 'Highlight current word: off'
return 0
else
augroup auto_highlight
au!
au CursorHold * let @/ = '\V\<'.escape(expand('<cword>'), '\').'\>'
augroup end
setl updatetime=500
echo 'Highlight current word: ON'
return 1
endif
endfunction
In my case it was a duplicate Swift Flag
entry inside my Target's Build Settings > Other Swift Flags. I had two -Xfrontend
entries in it.
pip uninstall pip
will work
Use these animations:
bottom_up.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="75%p" android:toYDelta="0%p"
android:fillAfter="true"
android:duration="500"/>
</set>
bottom_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="0%p" android:toYDelta="100%p" android:fillAfter="true"
android:interpolator="@android:anim/linear_interpolator"
android:duration="500" />
</set>
Use this code in your activity for hiding/animating your view:
Animation bottomUp = AnimationUtils.loadAnimation(getContext(),
R.anim.bottom_up);
ViewGroup hiddenPanel = (ViewGroup)findViewById(R.id.hidden_panel);
hiddenPanel.startAnimation(bottomUp);
hiddenPanel.setVisibility(View.VISIBLE);
Assuming alphanumeric words, you can use:
Search = ^([A-Za-z0-9]+)$
Replace = able:"\1"
Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):
Search = ^(.+)$
^
points to the start of the line.
$
points to the end of the line.
\1
will be the source match within the parentheses.
You can escape the quotes with a backslash:
"I asked my son's teacher, \"How is my son doing now?\""
Here it is:
.background {
background:url('../img/bg/diagonalnoise.png');
position: relative;
}
.layer {
background-color: rgba(248, 247, 216, 0.7);
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
HTML for this:
<div class="background">
<div class="layer">
</div>
</div>
Of course you need to define a width and height to the .background
class, if there are no other elements inside of it
One minor thing, which wasted my time.
Put the conditions(if comparing using " = ", " != ") in parenthesis, failing to do so also raises this exception. This will work
df[(some condition) conditional operator (some conditions)]
This will not
df[some condition conditional-operator some condition]
I wrote an npm module to solve this problem. It's available here:
object-types
: a module for finding what literal types underly objects
npm install --save object-types
const objectTypes = require('object-types');
objectTypes({});
//=> 'object'
objectTypes([]);
//=> 'array'
objectTypes(new Object(true));
//=> 'boolean'
Take a look, it should solve your exact problem. Let me know if you have any questions! https://github.com/dawsonbotsford/object-types
I got over this issue by using git merge command with the --no-commit
option and then explicitly removed the staged file and ignore the changes to the file.
E.g.: say I want to ignore any changes to myfile.txt
I proceed as follows:
git merge --no-ff --no-commit <merge-branch>
git reset HEAD myfile.txt
git checkout -- myfile.txt
git commit -m "merged <merge-branch>"
You can put statements 2 & 3 in a for loop, if you have a list of files to skip.
For Java 8 and higher:
String[] test = {"1", "2", "3", "4", "5"};
int[] ints = Arrays.stream(test).mapToInt(Integer::parseInt).toArray();
After insuring that the string "strOutput" has a correct XML structure, you can do this:
Matcher junkMatcher = (Pattern.compile("^([\\W]+)<")).matcher(strOutput);
strOutput = junkMatcher.replaceFirst("<");
Here's a solution using simpler functions and no hacks:
all.equal(a, as.integer(a))
What's more, you can test a whole vector at once, if you wish. Here's a function:
testInteger <- function(x){
test <- all.equal(x, as.integer(x), check.attributes = FALSE)
if(test == TRUE){ return(TRUE) }
else { return(FALSE) }
}
You can change it to use *apply
in the case of vectors, matrices, etc.
I purpose to you a very simple method who use String.contains
:
public static boolean containWhitespace(String value) {
return value.contains(" ");
}
A little usage example:
public static void main(String[] args) {
System.out.println(containWhitespace("i love potatoes"));
System.out.println(containWhitespace("butihatewhitespaces"));
}
Output:
true
false
Using Tyler Dodge's excellent answer kept lagging on my iPad, so I added some throttling code, now it's quite smooth. There is some minimal skipping sometimes while scrolling.
// Uses document because document will be topmost level in bubbling
$(document).on('touchmove',function(e){
e.preventDefault();
});
var scrolling = false;
// Uses body because jquery on events are called off of the element they are
// added to, so bubbling would not work if we used document instead.
$('body').on('touchstart','.scrollable',function(e) {
// Only execute the below code once at a time
if (!scrolling) {
scrolling = true;
if (e.currentTarget.scrollTop === 0) {
e.currentTarget.scrollTop = 1;
} else if (e.currentTarget.scrollHeight === e.currentTarget.scrollTop + e.currentTarget.offsetHeight) {
e.currentTarget.scrollTop -= 1;
}
scrolling = false;
}
});
// Prevents preventDefault from being called on document if it sees a scrollable div
$('body').on('touchmove','.scrollable',function(e) {
e.stopPropagation();
});
Also, adding the following CSS fixes some rendering glitches (source):
.scrollable {
overflow: auto;
overflow-x: hidden;
-webkit-overflow-scrolling: touch;
}
.scrollable * {
-webkit-transform: translate3d(0,0,0);
}
Try this; bear in mind that JavaScript months are 0-indexed, whilst days are 1-indexed.
var date = new Date('2010-10-11T00:00:00+05:30');_x000D_
alert(((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '/' + date.getFullYear());
_x000D_
You can use std::find
to get an iterator to a value:
#include <algorithm>
std::vector<int>::iterator position = std::find(myVector.begin(), myVector.end(), 8);
if (position != myVector.end()) // == myVector.end() means the element was not found
myVector.erase(position);
I was able to resolve the shared issue by following below steps:
I strongly recommend you to use virtual environments for python package installation. With virtualenv, you prevent any package conflict and total isolation from your python related userland commands.
To delete all your package follow this;
It's possible to uninstall packages installed with --user
flag. This one worked for me;
pip freeze --user | xargs pip uninstall -y
For python 3;
pip3 freeze --user | xargs pip3 uninstall -y
But somehow these commands don't uninstall setuptools and pip. After those commands (if you really want clean python) you may delete them with;
pip uninstall setuptools && pip uninstall pip
This code works for me:
Dim script As String = "<script type=""text/javascript"">window.open('" & URL.ToString & "');</script>"
ClientScript.RegisterStartupScript(Me.GetType, "openWindow", script)
Here is working code for all android versions as of API LEVEL 26+ with backward compatibility.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext(), "M_CH_ID");
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Hearty365")
.setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
.setContentTitle("Default notification")
.setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
.setContentInfo("Info");
NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());
UPDATE for API 26 to set Max priority
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Hearty365")
// .setPriority(Notification.PRIORITY_MAX)
.setContentTitle("Default notification")
.setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
.setContentInfo("Info");
notificationManager.notify(/*notification id*/1, notificationBuilder.build());
I have a simple script I use for this:
me@mycomputer:~$ cat /usr/local/bin/c
#!/bin/sh
echo "$*" | sed 's/x/\*/g' | bc -l
It changes x
to *
since *
is a special character in the shell. Use it as follows:
c 5x5
c 5-4.2 + 1
c '(5 + 5) * 30'
(you still have to use quotes if the expression contains any parentheses).C# version of Jules' answer:
public static double CalcDistanceBetween2Points(double x1, double y1, double x2, double y2)
{
return Math.Sqrt(Math.Pow (x1-x2, 2) + Math.Pow (y1-y2, 2));
}
public static bool PointLinesOnLine (double x, double y, double x1, double y1, double x2, double y2, double allowedDistanceDifference)
{
double dist1 = CalcDistanceBetween2Points(x, y, x1, y1);
double dist2 = CalcDistanceBetween2Points(x, y, x2, y2);
double dist3 = CalcDistanceBetween2Points(x1, y1, x2, y2);
return Math.Abs(dist3 - (dist1 + dist2)) <= allowedDistanceDifference;
}
Oauth is definitely gaining momentum and becoming popular among enterprise APIs as well. In the app and data driven world, Enterprises are exposing APIs more and more to the outer world in line with Google, Facebook, twitter. With this development a 3 way triangle of authentication gets formed
1) API provider- Any enterprise which exposes their assets by API, say Amazon,Target etc 2) Developer - The one who build mobile/other apps over this APIs 3) The end user- The end user of the service provided by the - say registered/guest users of Amazon
Now this develops a situation related to security - (I am listing few of these complexities) 1) You as an end user wants to allow the developer to access APIs on behalf of you. 2) The API provider has to authenticate the developer and the end user 3) The end user should be able to grant and revoke the permissions for the consent they have given 4) The developer can have varying level of trust with the API provider, in which the level of permissions given to her is different
The Oauth is an authorization framework which tries to solve the above mentioned problem in a standard way. With the prominence of APIs and Apps this problem will become more and more relevant and any standard which tries to solve it - be it ouath or any other - will be something to care about as an API provider/developer and even end user!
It seems to me you are using the wrong version...
TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!
this works with most types of elements:
$('selector').on('click',function(e){
log(e.currentTarget.id);
});
A good information: you don't need to check whether the Bundle object is null into the onCreate() method. Use the onRestoreInstanceState() method, which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null
If Python3 is your cup of tea, you can do this (but please explain why you would?):
ls -1 | python -c "import sys; print(','.join(sys.stdin.read().splitlines()))"
This is the simplest way
np.random.uniform(start,stop,(rows,columns))
You can also force flush the buffer to a file programmatically with the flush()
method.
with open('out.log', 'w+') as f:
f.write('output is ')
# some work
s = 'OK.'
f.write(s)
f.write('\n')
f.flush()
# some other work
f.write('done\n')
f.flush()
I have found this useful when tailing an output file with tail -f
.
XMLHttpRequest
is a standard object in the JavaScript Object model.
According to Wikipedia, XMLHttpRequest
first appeared in Internet Explorer 5 as an ActiveX object, but has since been made into a standard and has been included for use in JavaScript in the Mozilla family since 1.0, Apple Safari 1.2, Opera 7.60-p1, and IE 7.0.
The open()
method on the object takes the HTTP Method as an argument - and is specified as taking any valid HTTP method (see the item number 5 of the link) - including GET
, POST
, HEAD
, PUT
and DELETE
, as specified by RFC 2616.
Note: The following only works for the next line of code, and only due to a coincidence.
With Lodash,
require('lodash');
_.isArray([]); // true
No var _ = require('lodash')
since Lodash mysteriously sets this value globally when required.
I faced the same issue and was not able to find it out where git.exe is located. After spending so much time I fount that in my windows 8, it is located at
C:\Program Files (x86)\Git\bin
And for command line :
C:\Program Files (x86)\Git\cmd
Hope this helps someone facing the same issue.
three different approaches:
Classic client/server approach: don't put any database in the shops; simply have the applications access your server. Of course it's better if you set a VPN, but simply wrapping the connection in SSL or ssh is reasonable. Pro: it's the way databases were originally thought. Con: if you have high latency, complex operations could get slow, you might have to use stored procedures to reduce the number of round trips.
replicated master/master: as @Book Of Zeus suggested. Cons: somewhat more complex to setup (especially if you have several shops), breaking in any shop machine could potentially compromise the whole system. Pros: better responsivity as read operations are totally local and write operations are propagated asynchronously.
offline operations + sync step: do all work locally and from time to time (might be once an hour, daily, weekly, whatever) write a summary with all new/modified records from the last sync operation and send to the server. Pros: can work without network, fast, easy to check (if the summary is readable). Cons: you don't have real-time information.
<span>
is an inline element so you cant make spacing on them without making it block level.
Try this
Horizontal
span{
margin-right: 10px;
float: left;
}
Vertical
span{
margin-bottom: 10px;
}
Compatible with all browsers.
char **options[2][100];
declares a size-2 array of size-100 arrays of pointers to pointers to char
. You'll want to remove one *
. You'll also want to put your string literals in double quotes.
The easiest way to install it is using Homebrew:
brew install jmeter
Or if you need plugins also:
brew install jmeter --with-plugins
And to open it, use the following command (since it doesn't appear in your Applications):
open /usr/local/bin/jmeter
What you have will find a space anywhere in the string, not just between words.
If you want to find any kind of whitespace, you can use this, which uses a regular expression:
if (/\s/.test(str)) {
// It has any kind of whitespace
}
\s
means "any whitespace character" (spaces, tabs, vertical tabs, formfeeds, line breaks, etc.), and will find that character anywhere in the string.
According to MDN, \s
is equivalent to: [ \f\n\r\t\v?\u00a0\u1680?\u180e\u2000?\u2001\u2002?\u2003\u2004?\u2005\u2006?\u2007\u2008?\u2009\u200a?\u2028\u2029??\u202f\u205f?\u3000]
.
For some reason, I originally read your question as "How do I see if a string contains only spaces?" and so I answered with the below. But as @CrazyTrain points out, that's not what the question says. I'll leave it, though, just in case...
If you mean literally spaces, a regex can do it:
if (/^ *$/.test(str)) {
// It has only spaces, or is empty
}
That says: Match the beginning of the string (^
) followed by zero or more space characters followed by the end of the string ($
). Change the *
to a +
if you don't want to match an empty string.
If you mean whitespace as a general concept:
if (/^\s*$/.test(str)) {
// It has only whitespace
}
That uses \s
(whitespace) rather than the space, but is otherwise the same. (And again, change *
to +
if you don't want to match an empty string.)
sorted returns a list, hence your error when you try to iterate over it, but because you can't order a dict you will have to deal with a list.
I have no idea what the larger context of your code is, but you could try adding an iterator to the resulting list. like this maybe?:
return iter(sorted(dict.iteritems()))
of course you will be getting back tuples now because sorted turned your dict into a list of tuples
ex:
say your dict was:
{'a':1,'c':3,'b':2}
sorted turns it into a list:
[('a',1),('b',2),('c',3)]
so when you actually iterate over the list you get back (in this example) a tuple composed of a string and an integer, but at least you will be able to iterate over it.
Here how it looks for Swift 4:
import MessageUI
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients(["[email protected]"])
mail.setSubject("Bla")
mail.setMessageBody("<b>Blabla</b>", isHTML: true)
present(mail, animated: true, completion: nil)
} else {
print("Cannot send mail")
// give feedback to the user
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
switch result.rawValue {
case MFMailComposeResult.cancelled.rawValue:
print("Cancelled")
case MFMailComposeResult.saved.rawValue:
print("Saved")
case MFMailComposeResult.sent.rawValue:
print("Sent")
case MFMailComposeResult.failed.rawValue:
print("Error: \(String(describing: error?.localizedDescription))")
default:
break
}
controller.dismiss(animated: true, completion: nil)
}
from scipy import stats
l = [15, 18, 2, 36, 12, 78, 5, 6, 9]
print(stats.describe(l))
# DescribeResult(nobs=9, minmax=(2, 78), mean=20.11111111111111,
# variance=572.3611111111111, skewness=1.7791785448425341,
# kurtosis=1.9422716419666397)
select regexp_replace('This is a test ' || chr(9) || ' foo ', '[[:space:]]', '') from dual;
REGEXP_REPLACE
--------------
Thisisatestfoo
if you want to pass POST variables, you have to use a HTML Form:
<form action="http://localhost:8080/login" method="POST" target="_blank">
<input type="text" name="cid" />
<input type="password" name="pwd" />
<input type="submit" value="open" />
</form>
or:
if you want to pass GET variables in an URL, write them without single-quotes:
http://yourdomain.com/login?cid=username&pwd=password
here's how to create the string above with javascrpt variables:
myu = document.getElementById('cid').value;
myp = document.getElementById('pwd').value;
window.open("http://localhost:8080/login?cid="+ myu +"&pwd="+ myp ,"MyTargetWindowName");
in the document with that url, you have to read the GET parameters. if it's in php, use:
$_GET['username']
be aware: to transmit passwords that way is a big security leak!
For Windows you can try below solution
Copy your gradle-->bin
path and add it to system environment variable path
.
In my case gradle path is
C:\Users\username\.gradle\wrapper\dists\gradle-3.3-all\55gk2rcmfc6p2dg9u9ohc3hw9\gradle-3.3\bin
This solution worked for me.
I may be quite late to the party, but we can create custom foldr
using simple lambda calculus and curried function. Here is my implementation of foldr in python.
def foldr(func):
def accumulator(acc):
def listFunc(l):
if l:
x = l[0]
xs = l[1:]
return func(x)(foldr(func)(acc)(xs))
else:
return acc
return listFunc
return accumulator
def curried_add(x):
def inner(y):
return x + y
return inner
def curried_mult(x):
def inner(y):
return x * y
return inner
print foldr(curried_add)(0)(range(1, 6))
print foldr(curried_mult)(1)(range(1, 6))
Even though the implementation is recursive (might be slow), it will print the values 15
and 120
respectively
any mileage in
var d = new Date(xiYear, xiMonth, xiDate).toLocaleString();
RUN git clone http://username:password@url/example.git
WORKDIR /folder
RUN make
If you are a vim purist, skip reading this answer. OTOH, if you are new to vim and are looking for a few helpful tips you wont find in the many hundred of vim tutorials and blogs, read on... :-)
It's 2014, and as someone who's recently gone back to vim
I can offer a few, potentially contrarian, points of view and tips.
While repetition is a powerful concept in vim, I (personally) find it strange that using it either forces me to count (lines, characters, words, etc.) or make guesses. My brain usually works like "I want the cursor there" and not like "I want the cursor _5_words_to_the_left_". Quickly being able to move the cursor, and visually observe where the insertion point this way allows me to keep my mind on what I'm editing instead of having to count how many hops I need to make to get to where I need to edit.
...to navigate large bodies of text.
Most (all) modern computers have a touchpad that is closely integrated with the keyboard (e.g. MacBooks). Industrial designers have spent many man years optimizing these designs so that the old problem of having to move the hand away from the keyboard is no longer a real issue. Okay, it is if you are used to a mouse and don't like to switch, but for anyone new to vim (like those that might find this post via a search), this should not be much of an issue.
With mouse enabled, clicking and dragging has the effect of switching to visual mode and marking a region for yanking.
Using the mouse (wheel) to scroll around, and clicking to position the cursor (duh) just works. See http://usevim.com/2012/05/16/mouse/ for more on this.
These are what I'd call more modern (using mouse, scroll wheel, etc.) ways of navigating in vim, equally effective depending on your preference of input.
HTH
Well, late by 5 years and unsure if it helps :
I was trying to count the no. of rows in a SQL Server table using MS SQL Server Management Studio and ran into some overflow error, then I used the below :
select count_big(1) FROM [dbname].[dbo].[FactSampleValue];
The result :
24296650578 rows
The Most simple code you can write:
persons.stream().map(x-> x.getName()).distinct().collect(Collectors.toList());
For my case, I deleted the mappedBy and joined tables like this:
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_group", joinColumns = {
@JoinColumn(name = "user", referencedColumnName = "user_id")
}, inverseJoinColumns = {
@JoinColumn(name = "group", referencedColumnName = "group_id")
})
private List<User> users;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JsonIgnore
private List<Group> groups;
If you are looking for an specific hex character in the middle of the string, you can use "\xhh" where hh is the character in hexadecimal. I've tried and it works. I use framework for C++ Qt but it can solve problems in other cases, depends on the flavor you need to use (php, javascript, python , golang, etc.).
This answer was taken from:http://ult-tex.net/info/perl/
In sonar.properties file in conf folder I had hardcoaded ip of my machine where sobarqube was installed in property sonar.web.host=10.9 235.22 I commented this and it started working for me.
Use -e
or --env value to set environment variables (default []).
An example from a startup script:
docker run -e myhost='localhost' -it busybox sh
If you want to use multiple environments from the command line then before every environment variable use the -e
flag.
Example:
sudo docker run -d -t -i -e NAMESPACE='staging' -e PASSWORD='foo' busybox sh
Note: Make sure put the container name after the environment variable, not before that.
If you need to set up many variables, use the --env-file
flag
For example,
$ docker run --env-file ./my_env ubuntu bash
For any other help, look into the Docker help:
$ docker run --help
Official documentation: https://docs.docker.com/compose/environment-variables/
According to eduLINQ:
The best way to get to grips with what GroupJoin does is to think of Join. There, the overall idea was that we looked through the "outer" input sequence, found all the matching items from the "inner" sequence (based on a key projection on each sequence) and then yielded pairs of matching elements. GroupJoin is similar, except that instead of yielding pairs of elements, it yields a single result for each "outer" item based on that item and the sequence of matching "inner" items.
The only difference is in return statement:
Join:
var lookup = inner.ToLookup(innerKeySelector, comparer);
foreach (var outerElement in outer)
{
var key = outerKeySelector(outerElement);
foreach (var innerElement in lookup[key])
{
yield return resultSelector(outerElement, innerElement);
}
}
GroupJoin:
var lookup = inner.ToLookup(innerKeySelector, comparer);
foreach (var outerElement in outer)
{
var key = outerKeySelector(outerElement);
yield return resultSelector(outerElement, lookup[key]);
}
Read more here:
This also works in Silverlight 5 (perhaps earlier as well but i haven't tested it). I used the relative source like this and it worked fine.
RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=telerik:RadGridView}"
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
A better option
set my_message=Hello world
&& start cmd /c "@echo off & mode con cols=15 lines=2 & echo %my_message% & pause>nul"
Description:
lines=
amount of lines,plus 1
cols=
amount of characters in the message, plus 3 (However, minimum must be 15
)
cols
version:set my_message=Hello world
&& (echo %my_message%>EMPTY_FILE123 && FOR %? IN (EMPTY_FILE123 ) DO SET strlength=%~z? && del EMPTY_FILE123 ) && start cmd /c "@echo off && mode con lines=2 cols=%strlength% && echo %my_message% && pause>nul"
You can dump the value in hex using UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2())
.
SELECT b FROM foo;
-- (BLOB)
SELECT UTL_RAW.CAST_TO_RAW(UTL_RAW.CAST_TO_VARCHAR2(b))
FROM foo;
-- 1F8B080087CDC1520003F348CDC9C9D75128CF2FCA49D1E30200D7BBCDFC0E000000
This is handy because you this is the same format used for inserting into BLOB columns:
CREATE GLOBAL TEMPORARY TABLE foo (
b BLOB);
INSERT INTO foo VALUES ('1f8b080087cdc1520003f348cdc9c9d75128cf2fca49d1e30200d7bbcdfc0e000000');
DESC foo;
-- Name Null Type
-- ---- ---- ----
-- B BLOB
However, at a certain point (2000 bytes?) the corresponding hex string exceeds Oracle’s maximum string length. If you need to handle that case, you’ll have to combine How do I get textual contents from BLOB in Oracle SQL with the documentation for DMBS_LOB.SUBSTR
for a more complicated approach that will allow you to see substrings of the BLOB.
A process normally has two outputs to screen: stdout (standard out), and stderr (standard error).
Normally informational messages go to sdout
, and errors and alerts go to stderr
.
You can turn off stdout
for a command by doing
MyCommand >/dev/null
and turn off stderr
by doing:
MyCommand 2>/dev/null
If you want both off, you can do:
MyCommand 2>&1 >/dev/null
The 2>&1
says send stderr to the same place as stdout.
In your version rand() % 10000
will yield an integer between 0
and 9999
. Since RAND_MAX may be as little as 32767, and since this is not exactly divisible by 10000 and not large relative to 10000, there will be significant bias in the 'randomness' of the result, moreover, the maximum value will be 0.9999, not 1.0, and you have unnecessarily restricted your values to four decimal places.
It is simple arithmetic, a random number divided by the maximum possible random number will yield a number from 0 to 1 inclusive, while utilising the full resolution and distribution of the RNG
double r2()
{
return (double)rand() / (double)RAND_MAX ;
}
Use (double)rand() / (double)((unsigned)RAND_MAX + 1)
if exclusion of 1.0 was intentional.
I came here looking for making an input that's actually multiple lines. Turns out I didn't want an input, I wanted a textarea. You can set height or line-height as other answers specify, but it'll still just be one line of a textbox. If you want actual multiple lines, use a textarea instead. The following is an example of a 3-row textarea with a width of 500px (should be a good part of the page, not necessary to set this and will have to change it based on your requirements).
<textarea name="roleExplanation" style="width: 500px" rows="3">This role is for facility managers and holds the highest permissions in the application.</textarea>
Example that works for me on OSX / MacOS (replace name of device)
~/Library/Android/sdk/emulator/emulator @Pixel_2_API_28 -no-snapshot -wipe-data
I had a similar issue with Eclipse and the same steps as Sanders did solve it. It happens because the proxy restricts call to maven repository
D:\Maven\apache-maven-3.0.4-bin\apache-maven-3.0.4\conf
(ie your maven installation folder) settings.xml
and paste it in .m2
folder, which is in the users folder of your windows machine.Something like this:
<proxies>
<!-- proxy
Specification for one proxy, to be used in connecting to the network.
-->
<proxy>
<active>true</active>
<protocol>http</protocol>
<username>your username</username>
<password>password</password>
<host>proxy.host.net</host>
<port>80</port>
</proxy>
</proxies>
I'd suggest <a href='page1.jsp'>Refresh</a>
.
May be useful for some:
(a function that allow you to add the data to the form using an object, with override for existing inputs, if there is) [pure js]
(form is a dom el, and not a jquery object [jqryobj.get(0) if you need])
function addDataToForm(form, data) {
if(typeof form === 'string') {
if(form[0] === '#') form = form.slice(1);
form = document.getElementById(form);
}
var keys = Object.keys(data);
var name;
var value;
var input;
for (var i = 0; i < keys.length; i++) {
name = keys[i];
// removing the inputs with the name if already exists [overide]
// console.log(form);
Array.prototype.forEach.call(form.elements, function (inpt) {
if(inpt.name === name) {
inpt.parentNode.removeChild(inpt);
}
});
value = data[name];
input = document.createElement('input');
input.setAttribute('name', name);
input.setAttribute('value', value);
input.setAttribute('type', 'hidden');
form.appendChild(input);
}
return form;
}
addDataToForm(form, {
'uri': window.location.href,
'kpi_val': 150,
//...
});
you can use it like that too
var form = addDataToForm('myFormId', {
'uri': window.location.href,
'kpi_val': 150,
//...
});
you can add # if you like too ("#myformid").
DateTimePicker1.value = Format(Date.Now)
You can use the ImageLocation
property of pictureBox1
:
pictureBox1.ImageLocation = @"C:\Users\MSI\Desktop\MYAPP\Slider\Slider\bt1.jpg";
This problem arises when you have composer installed locally. To make it globally executable,run the below command in terminal
sudo mv composer.phar /usr/local/bin/composer
For CentOS 7 the command is
sudo mv composer.phar /usr/bin/composer
I wrote a simple jQuery extension to disable selection some time back: Disabling Selection in jQuery. You can invoke it through $('.button').disableSelection();
Alternately, using CSS (cross-browser):
.button {
user-select: none;
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
}
The Windows x64 installer shows the a path in the installer UI/wizard.
You can confirm which path it used later, by opening your mongod.cfg
file. My mongod.cfg
was located here C:\Program Files\MongoDB\Server\4.0\bin\mongod.cfg
(change for your version of MongoDB!
When I opened my mongd.cfg
I found this line, showing the default db path:
dbPath: C:\Program Files\MongoDB\Server\4.0\data
However, this caused an error when trying to run mongod
, which was still expecting to find C:\data\db
:
2019-05-05T09:32:36.084-0700 I STORAGE [initandlisten] exception in initAndListen: NonExistentPath: Data directory C:\data\db\ not found., terminating
You could pass mongod
a --dbpath=...
parameter. In my case:
mongod --dbpath="C:\Program Files\MongoDB\Server\4.0\data"
You should do the following:
SELECT cr.review_sk,
cr.cs_sk,
cr.full_name,
tolist(to_char(cf.fact_date, 'mm/dd/yyyy')) "appt",
cs.cs_id,
cr.tracking_number
from review cr, cs, fact cf
where cr.cs_sk = cs.cs_sk
and UPPER(cs.cs_id) like '%' || UPPER(i_cs_id) || '%'
and row_delete_date_time is null
and cr.review_sk = cf.review_wk (+)
and cr.fact_type_code (+) = 183050
GROUP BY cr.review_sk, cr.cs_sk, cf.fact_date, cr.tracking_number, cs.cs_id, cr.full_name
ORDER BY cs.cs_id, cr.full_name;
As an addendum to the other answers, this sounds like a fine use-case for a context manager that will re-map the names of these functions to ones which return a list and introduce reduce
in the global namespace.
A quick implementation might look like this:
from contextlib import contextmanager
@contextmanager
def noiters(*funcs):
if not funcs:
funcs = [map, filter, zip] # etc
from functools import reduce
globals()[reduce.__name__] = reduce
for func in funcs:
globals()[func.__name__] = lambda *ar, func = func, **kwar: list(func(*ar, **kwar))
try:
yield
finally:
del globals()[reduce.__name__]
for func in funcs: globals()[func.__name__] = func
With a usage that looks like this:
with noiters(map):
from operator import add
print(reduce(add, range(1, 20)))
print(map(int, ['1', '2']))
Which prints:
190
[1, 2]
Just my 2 cents :-)
1.Check your server status.
2.Check the port status.
For example 3306 netstat -nupl|grep 3306
.
3.Check your firewalls. For example add 3306
vim /etc/sysconfig/iptables
# add
-A INPUT -p tcp -m state --state NEW -m tcp --dport 3306 -j ACCEPT
This post may help. https://css-tricks.com/snippets/html/responsive-meta-tag/ It gives a full description on the meta tags and its different attributes.
My solution if you work with the Trunk/
and Release/
workflow:
Right click on Trunk/
which you will be creating your Branch from:
Select Branch/Tag:
Type in location of your new branch, commit message, and any externals (if your repository has them):
There are no implicit copies made in java via the assignment operator. Variables contain a reference value (pointer) and when you use =
you're only coping that value.
In order to preserve the contents of myTempObject
you would need to make a copy of it.
This can be done by creating a new ArrayList
using the constructor that takes another ArrayList
:
ArrayList<Object> myObject = new ArrayList<Object>(myTempObject);
Edit: As Bohemian points out in the comments below, is this what you're asking? By doing the above, both ArrayList
s (myTempObject
and myObject
) would contain references to the same objects. If you actually want a new list that contains new copies of the objects contained in myTempObject
then you would need to make a copy of each individual object in the original ArrayList
Add an :order parameter to the query
You should design your table WITHOUT considering the views.
Apart from saving joins and conditions, Views do have a performance advantage: SQL Server may calculate and save its execution plan in the view, and therefore make it faster than "on the fly" SQL statements.
View may also ease your work regarding user access at field level.
Update: Joyent now has their own guide. The following information is more of a summary:
Ideally we'd like to avoid uncaught errors as much as possible, as such, instead of literally throwing the error, we can instead safely "throw" the error using one of the following methods depending on our code architecture:
For synchronous code, if an error happens, return the error:
// Define divider as a syncrhonous function
var divideSync = function(x,y) {
// if error condition?
if ( y === 0 ) {
// "throw" the error safely by returning it
return new Error("Can't divide by zero")
}
else {
// no error occured, continue on
return x/y
}
}
// Divide 4/2
var result = divideSync(4,2)
// did an error occur?
if ( result instanceof Error ) {
// handle the error safely
console.log('4/2=err', result)
}
else {
// no error occured, continue on
console.log('4/2='+result)
}
// Divide 4/0
result = divideSync(4,0)
// did an error occur?
if ( result instanceof Error ) {
// handle the error safely
console.log('4/0=err', result)
}
else {
// no error occured, continue on
console.log('4/0='+result)
}
For callback-based (ie. asynchronous) code, the first argument of the callback is err
, if an error happens err
is the error, if an error doesn't happen then err
is null
. Any other arguments follow the err
argument:
var divide = function(x,y,next) {
// if error condition?
if ( y === 0 ) {
// "throw" the error safely by calling the completion callback
// with the first argument being the error
next(new Error("Can't divide by zero"))
}
else {
// no error occured, continue on
next(null, x/y)
}
}
divide(4,2,function(err,result){
// did an error occur?
if ( err ) {
// handle the error safely
console.log('4/2=err', err)
}
else {
// no error occured, continue on
console.log('4/2='+result)
}
})
divide(4,0,function(err,result){
// did an error occur?
if ( err ) {
// handle the error safely
console.log('4/0=err', err)
}
else {
// no error occured, continue on
console.log('4/0='+result)
}
})
For eventful code, where the error may happen anywhere, instead of throwing the error, fire the error
event instead:
// Definite our Divider Event Emitter
var events = require('events')
var Divider = function(){
events.EventEmitter.call(this)
}
require('util').inherits(Divider, events.EventEmitter)
// Add the divide function
Divider.prototype.divide = function(x,y){
// if error condition?
if ( y === 0 ) {
// "throw" the error safely by emitting it
var err = new Error("Can't divide by zero")
this.emit('error', err)
}
else {
// no error occured, continue on
this.emit('divided', x, y, x/y)
}
// Chain
return this;
}
// Create our divider and listen for errors
var divider = new Divider()
divider.on('error', function(err){
// handle the error safely
console.log(err)
})
divider.on('divided', function(x,y,result){
console.log(x+'/'+y+'='+result)
})
// Divide
divider.divide(4,2).divide(4,0)
Sometimes though, there may still be code that throws an error somewhere which can lead to an uncaught exception and a potential crash of our application if we don't catch it safely. Depending on our code architecture we can use one of the following methods to catch it:
When we know where the error is occurring, we can wrap that section in a node.js domain
var d = require('domain').create()
d.on('error', function(err){
// handle the error safely
console.log(err)
})
// catch the uncaught errors in this asynchronous or synchronous code block
d.run(function(){
// the asynchronous or synchronous code that we want to catch thrown errors on
var err = new Error('example')
throw err
})
If we know where the error is occurring is synchronous code, and for whatever reason can't use domains (perhaps old version of node), we can use the try catch statement:
// catch the uncaught errors in this synchronous code block
// try catch statements only work on synchronous code
try {
// the synchronous code that we want to catch thrown errors on
var err = new Error('example')
throw err
} catch (err) {
// handle the error safely
console.log(err)
}
However, be careful not to use try...catch
in asynchronous code, as an asynchronously thrown error will not be caught:
try {
setTimeout(function(){
var err = new Error('example')
throw err
}, 1000)
}
catch (err) {
// Example error won't be caught here... crashing our app
// hence the need for domains
}
If you do want to work with try..catch
in conjunction with asynchronous code, when running Node 7.4 or higher you can use async/await
natively to write your asynchronous functions.
Another thing to be careful about with try...catch
is the risk of wrapping your completion callback inside the try
statement like so:
var divide = function(x,y,next) {
// if error condition?
if ( y === 0 ) {
// "throw" the error safely by calling the completion callback
// with the first argument being the error
next(new Error("Can't divide by zero"))
}
else {
// no error occured, continue on
next(null, x/y)
}
}
var continueElsewhere = function(err, result){
throw new Error('elsewhere has failed')
}
try {
divide(4, 2, continueElsewhere)
// ^ the execution of divide, and the execution of
// continueElsewhere will be inside the try statement
}
catch (err) {
console.log(err.stack)
// ^ will output the "unexpected" result of: elsewhere has failed
}
This gotcha is very easy to do as your code becomes more complex. As such, it is best to either use domains or to return errors to avoid (1) uncaught exceptions in asynchronous code (2) the try catch catching execution that you don't want it to. In languages that allow for proper threading instead of JavaScript's asynchronous event-machine style, this is less of an issue.
Finally, in the case where an uncaught error happens in a place that wasn't wrapped in a domain or a try catch statement, we can make our application not crash by using the uncaughtException
listener (however doing so can put the application in an unknown state):
// catch the uncaught errors that weren't wrapped in a domain or try catch statement
// do not use this in modules, but only in applications, as otherwise we could have multiple of these bound
process.on('uncaughtException', function(err) {
// handle the error safely
console.log(err)
})
// the asynchronous or synchronous code that emits the otherwise uncaught error
var err = new Error('example')
throw err
You can either use:
[x / 10.0 for x in range(5, 50, 15)]
or use lambda / map:
map(lambda x: x/10.0, range(5, 50, 15))
Note need root than:
adb root
adb pull /data/data/com.google.android.apps.nexuslauncher/databases/launcher.db launcher.db
If you have PHP installed as a command line tool (try issuing php
to the terminal and see if it works), your shebang (#!
) line needs to look like this:
#!/usr/bin/php
Put that at the top of your script, make it executable (chmod +x myscript.php
), and make a Cron job to execute that script (same way you'd execute a bash script).
You can also use php myscript.php
.
Not direct answer to your question, but I've been quite frustrated myself trying find and update all of the tnsnames files, as I had several oracle installs: Client, BI tools, OWB, etc, each of which had its own oracle home. I ended up creating a utility called TNSNamesSync that will update all of the tnsnames in all of the oracle homes. It's under the MIT license, free to use here https://github.com/artybug/TNSNamesSync/releases
The docs are here: https://github.com/artchik/TNSNamesSync/blob/master/README.md
This is for Windows only, though.
Easiest way is to do this from your accounts with Xcode:
Head over Xcode -> Preferences -> Choose Accounts Tab -> View Details -> Hit refresh button on the bottom left -> Done.
Build again and it should work.
Pure JavaScript solution:
function scrollToTop() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
I write an animated solution on Codepen
Also, you can try another solution with CSS scroll-behavior: smooth
property.
html {
scroll-behavior: smooth;
}
@media (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
}
The best way for me was using vector with categories in order I need as limits
parameter to scale_x_discrete
. I think it is pretty simple and straightforward solution.
ggplot(mtcars, aes(factor(cyl))) +
geom_bar() +
scale_x_discrete(limits=c(8,4,6))
You can transfer array from javascript to PHP...
Javascript... ArraySender.html
<script language="javascript">
//its your javascript, your array can be multidimensional or associative
plArray = new Array();
plArray[1] = new Array(); plArray[1][0]='Test 1 Data'; plArray[1][1]= 'Test 1'; plArray[1][2]= new Array();
plArray[1][2][0]='Test 1 Data Dets'; plArray[1][2][1]='Test 1 Data Info';
plArray[2] = new Array(); plArray[2][0]='Test 2 Data'; plArray[2][1]= 'Test 2';
plArray[3] = new Array(); plArray[3][0]='Test 3 Data'; plArray[3][1]= 'Test 3';
plArray[4] = new Array(); plArray[4][0]='Test 4 Data'; plArray[4][1]= 'Test 4';
plArray[5] = new Array(); plArray[5]["Data"]='Test 5 Data'; plArray[5]["1sss"]= 'Test 5';
function convertJsArr2Php(JsArr){
var Php = '';
if (Array.isArray(JsArr)){
Php += 'array(';
for (var i in JsArr){
Php += '\'' + i + '\' => ' + convertJsArr2Php(JsArr[i]);
if (JsArr[i] != JsArr[Object.keys(JsArr)[Object.keys(JsArr).length-1]]){
Php += ', ';
}
}
Php += ')';
return Php;
}
else{
return '\'' + JsArr + '\'';
}
}
function ajaxPost(str, plArrayC){
var xmlhttp;
if (window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}
else{xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.open("POST",str,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('Array=' + plArrayC);
}
ajaxPost('ArrayReader.php',convertJsArr2Php(plArray));
</script>
and PHP Code... ArrayReader.php
<?php
eval('$plArray = ' . $_POST['Array'] . ';');
print_r($plArray);
?>
I had the same issue, I had to remove the async keyword from the method and also remove the await keyword from the calling method to use getawaiter() without any error.
If you have a large array and only want to see a subsection of the array you can type this into the watch window;
ptr+100,10
to show a list of the 10 elements starting at ptr[100]. Beware that the displayed array subscripts will start at [0], so you will have to remember that ptr[0] is really ptr[100] and ptr[1] is ptr[101] etc.
System call it!
system( "dir /b /s /a-d * > file_names.txt" );
Then just read the file.
EDIT: This answer should be considered a hack, but it really does work (albeit in a platform specific way) if you don't have access to more elegant solutions.
Say you have multiple jar files a.jar,b.jar and c.jar. To add them to classpath while compiling you need to do
$javac -cp .:a.jar:b.jar:c.jar HelloWorld.java
To run do
$java -cp .:a.jar:b.jar:c.jar HelloWorld
By default, if you have an identity column, you do not need to specify it in the VALUES section. If your table is:
ID NAME ADDRESS
Then you can do:
INSERT INTO MyTbl VALUES ('Joe', '123 State Street, Boston, MA')
This will auto-generate the ID for you, and you don't have to think about it at all. If you SET IDENTITY_INSERT MyTbl ON
, you can assign a value to the ID column.
This is probably what you want
var uri = new Uri("http://domain.test/Default.aspx?var1=true&var2=test&var3=3");
var query = HttpUtility.ParseQueryString(uri.Query);
var var2 = query.Get("var2");
You can use QString.arg like this
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", "Jane");
// You get "~/Tom-Jane.txt"
This method is preferred over sprintf because:
Changing the position of the string without having to change the ordering of substitution, e.g.
// To get "~/Jane-Tom.txt"
QString my_formatted_string = QString("%1/%3-%2.txt").arg("~", "Tom", "Jane");
Or, changing the type of the arguments doesn't require changing the format string, e.g.
// To get "~/Tom-1.txt"
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", QString::number(1));
As you can see, the change is minimal. Of course, you generally do not need to care about the type that is passed into QString::arg() since most types are correctly overloaded.
One drawback though: QString::arg() doesn't handle std::string. You will need to call: QString::fromStdString() on your std::string to make it into a QString before passing it to QString::arg(). Try to separate the classes that use QString from the classes that use std::string. Or if you can, switch to QString altogether.
UPDATE: Examples are updated thanks to Frank Osterfeld.
UPDATE: Examples are updated thanks to alexisdm.
The method tf.shape is a TensorFlow static method. However, there is also the method get_shape for the Tensor class. See
https://www.tensorflow.org/api_docs/python/tf/Tensor#get_shape
I hope I am not overstating the obvious, but why not do it directly in the ASP side? Unless you are dynamically altering the SQL based on certain conditions in your program, you should avoid codebehind as much as possible.
You could do the above all in ASP directly without code using the SqlDataSource control and a property in your dropdownlist.
<asp:GridView ID="gvSubjects" runat="server" DataKeyNames="SubjectID" OnRowDataBound="GridView_RowDataBound" OnDataBound="GridView_DataBound">
<Columns>
<asp:TemplateField HeaderText="Subjects">
<ItemTemplate>
<asp:DropDownList ID="ddlSubjects" runat="server" DataSourceID="sdsSubjects" DataTextField="SubjectName" DataValueField="SubjectID">
</asp:DropDownList>
<asp:SqlDataSource ID="sdsSubjects" runat="server"
SelectCommand="SELECT SubjectID,SubjectName FROM Students.dbo.Subjects"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can use SEPARATOR and ORDER BY inside the GROUP_CONCAT function in this way:
SELECT li.client_id, group_concat(li.percentage ORDER BY li.views ASC SEPARATOR ',')
AS views, group_concat(li.percentage ORDER BY li.percentage ASC SEPARATOR ',') FROM li
GROUP BY client_id;
Source code of CSS/JS we usually minified/compress. Now if we want to debug those minified files then we have to add following line at the end of minified file
/*# sourceMappingURL=bootstrap.min.css.map */
This tells compiler where is source file actually mapped.
In the case of JS its make sense
but in the case of CSS, its actually debugging of SCSS.
To Remove Warning: remove /*# sourceMappingURL=bootstrap.min.css.map */ from the end of minified file
, .
not so elegant but you dont need to declare any variable:
for k in (select max(1) from table where 1 = 1) loop
update x where column = value;
end loop;
You need to call self.a()
to invoke a
from b
. a
is not a global function, it is a method on the class.
You may want to read through the Python tutorial on classes some more to get the finer details down.
SQL has an error raising mechanism
RAISERROR ( { msg_id | msg_str | @local_variable }
{ ,severity ,state }
[ ,argument [ ,...n ] ] )
[ WITH option [ ,...n ] ]
Just look up Raiserror in the Books Online. But.. you have to generate an error of the appropriate severity, an error at severity 0 thru 10 do not cause you to jump to the catch block.
Take care not to include
#include <string.h>
but only
#include <string>
It took me 1 hour to find this in my code.
Hope this can help
Use @Column
annotation and define its length
attribute. Check Hibernate's documentation for references (section 2.2.2.3).
It is also possible to open the pdf link in a new window and let the browser handle the rest:
window.open(pdfUrl, '_blank');
or:
window.open(pdfUrl);
put id attribute on anchor element
<a id="link2">
set href attribute on page load event:
(function() {
var scrt_var = 10;
var strLink = "2.html&Key=" + scrt_var;
document.getElementById("link2").setAttribute("href",strLink);
})();
This isn't a direct answer, but I think it is a pretty sweet alternative.
It allows you to host your pages behind basic auth. Great for things like api docs in your private github repo. just ad a s3 put as part of your api build.
For multi-line shell scripts or those run multiple times, I would create a new bash script file (starting from #!/bin/bash
), and simply run it with sh
from Jenkinsfile:
sh 'chmod +x ./script.sh'
sh './script.sh'
Possibly not cross browser but I managed get this: http://jsfiddle.net/QexkH/
basically it requires a fixed height header and footer. and it absolute positions the table.
table {
width: 50%;
height: 50%;
border-spacing: 0;
position:absolute;
}
td {
border: 1px solid black;
}
#content {
position:absolute;
width:100%;
left:0px;
top:20px;
bottom:20px;
overflow: hidden;
}
You can handle WM_NCPAINT
message of TextBox
and draw a border on the non-client area of control if the control has focus. You can use any color to draw border:
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class ExTextBox : TextBox
{
[DllImport("user32")]
private static extern IntPtr GetWindowDC(IntPtr hwnd);
private const int WM_NCPAINT = 0x85;
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_NCPAINT && this.Focused)
{
var dc = GetWindowDC(Handle);
using (Graphics g = Graphics.FromHdc(dc))
{
g.DrawRectangle(Pens.Red, 0, 0, Width - 1, Height - 1);
}
}
}
}
Result
The painting of borders while the control is focused is completely flicker-free:
BorderColor property for TextBox
In the current post I just change the border color on focus. You can also add a BorderColor
property to the control. Then you can change border-color based on your requirement at design-time or run-time. I've posted a more completed version of TextBox
which has BorderColor
property:
in the following post:
Subversion does not yet have a first-class rename operations.
There's a 6-year-old bug on the problem: http://subversion.tigris.org/issues/show_bug.cgi?id=898
It's being considered for 1.6, now that merge tracking (a higher priority) has been added (in 1.5).
Once upon a time in MySQL you could just copy all the table files to another directory in the mysql tree
mysql cli - create database db2
linux cli - cp db1 db2
The direct answer to this question is:
if(rows.Any()) //prevent IndexOutOfRangeException for empty list
{
rows.RemoveAt(rows.Count - 1);
}
However... in the specific case of this question, it makes more sense not to add the row in the first place:
Row row = new Row();
//...
if (!row.cell[0].Equals("Something"))
{
rows.Add(row);
}
TBH, I'd go a step further by testing "Something"
against user.""
, and not even instantiating a Row
unless the condition is satisfied, but seeing as user.""
won't compile, I'll leave that as an exercise for the reader.
Another veneration of find_elements_by_xpath(".//*")
is:
from selenium.webdriver.common.by import By
find_elements(By.XPATH, ".//*")
Several pointers:
You need to handle a return value of 0, which tells you that the remote host closed the socket.
For nonblocking sockets, you also need to check an error return value (-1) and make sure that errno isn't EINPROGRESS, which is expected.
You definitely need better error handling - you're potentially leaking the buffer pointed to by 'buffer'. Which, I noticed, you don't allocate anywhere in this code snippet.
Someone else made a good point about how your buffer isn't a null terminated C string if your read() fills the entire buffer. That is indeed a problem, and a serious one.
Your buffer size is a bit small, but should work as long as you don't try to read more than 256 bytes, or whatever you allocate for it.
If you're worried about getting into an infinite loop when the remote host sends you a malformed message (a potential denial of service attack) then you should use select() with a timeout on the socket to check for readability, and only read if data is available, and bail out if select() times out.
Something like this might work for you:
fd_set read_set;
struct timeval timeout;
timeout.tv_sec = 60; // Time out after a minute
timeout.tv_usec = 0;
FD_ZERO(&read_set);
FD_SET(socketFileDescriptor, &read_set);
int r=select(socketFileDescriptor+1, &read_set, NULL, NULL, &timeout);
if( r<0 ) {
// Handle the error
}
if( r==0 ) {
// Timeout - handle that. You could try waiting again, close the socket...
}
if( r>0 ) {
// The socket is ready for reading - call read() on it.
}
Depending on the volume of data you expect to receive, the way you scan the entire message repeatedly for the "end;" token is very inefficient. This is better done with a state machine (the states being 'e'->'n'->'d'->';') so that you only look at each incoming character once.
And seriously, you should consider finding a library to do all this for you. It's not easy getting it right.
Use a try catch block like below:
try {
const phoneNumber = this.phoneUtil.parseAndKeepRawInput(value, this.countryCode);
}catch(e){}
queryString = "SELECT name FROM user WHERE id=" & Worksheets("Sheet1").Range("D4").Value
// CMakeLists.txt : release
set(CMAKE_CONFIGURATION_TYPES "Release" CACHE STRING "" FORCE)
// CMakeLists.txt : debug
set(CMAKE_CONFIGURATION_TYPES "Debug" CACHE STRING "" FORCE)
Few years ago, when working on loyality program, we had an issue with the amount of points given to customers. The issue was related to casting/converting double to int.
In code below:
double d = 13.6;
int i1 = Convert.ToInt32(d);
int i2 = (int)d;
does i1 == i2 ?
It turns out that i1 != i2. Because of different rounding policies in Convert and cast operator the actual values are:
i1 == 14
i2 == 13
It's always better to call Math.Ceiling() or Math.Floor() (or Math.Round with MidpointRounding that meets our requirements)
int i1 = Convert.ToInt32( Math.Ceiling(d) );
int i2 = (int) Math.Ceiling(d);
There is more than one way to do it.
1). A long statement:
>>> def print_something():
print 'This is a really long line,', \
'but we can make it across multiple lines.'
2). Using parenthesis:
>>> def print_something():
print ('Wow, this also works?',
'I never knew!')
3). Using \
again:
>>> x = 10
>>> if x == 10 or x > 0 or \
x < 100:
print 'True'
Quoting PEP8:
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it.
Indeed, the simplest way is to use intValue()
. However, this merely returns the integer part; it does not do any rounding. If you want the Integer nearest to the Double value, you'll need to do this:
Integer integer = Integer.valueOf((int) Math.round(myDouble)));
And don't forget the null case:
Integer integer = myDouble == null ? null : Integer.valueOf((int) Math.round(myDouble)));
Math.round()
handles odd duck cases, like infinity and NaN, with relative grace.
Have you looked in firebug if POST or GET?.
check the console display.
Put in the test script:
console.log(data);
You can see the response from the server, if it shows something.
Try this please, <a target="_blank" routerLink="/Page2">
Update1: Custom directives to the rescue! Full code is here: https://github.com/pokearound/angular2-olnw
import { Directive, ElementRef, HostListener, Input, Inject } from '@angular/core';
@Directive({ selector: '[olinw007]' })
export class OpenLinkInNewWindowDirective {
//@Input('olinwLink') link: string; //intro a new attribute, if independent from routerLink
@Input('routerLink') link: string;
constructor(private el: ElementRef, @Inject(Window) private win:Window) {
}
@HostListener('mousedown') onMouseEnter() {
this.win.open(this.link || 'main/default');
}
}
Notice, Window is provided and OpenLinkInNewWindowDirective declared below:
import { AppAboutComponent } from './app.about.component';
import { AppDefaultComponent } from './app.default.component';
import { PageNotFoundComponent } from './app.pnf.component';
import { OpenLinkInNewWindowDirective } from './olinw.directive';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
const appRoutes: Routes = [
{ path: '', pathMatch: 'full', component: AppDefaultComponent },
{ path: 'home', component: AppComponent },
{ path: 'about', component: AppAboutComponent },
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
declarations: [
AppComponent, AppAboutComponent, AppDefaultComponent, PageNotFoundComponent, OpenLinkInNewWindowDirective
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(appRoutes)
],
providers: [{ provide: Window, useValue: window }],
bootstrap: [AppComponent]
})
export class AppModule { }
First link opens in new Window, second one will not:
<h1>
{{title}}
<ul>
<li><a routerLink="/main/home" routerLinkActive="active" olinw007> OLNW</a></li>
<li><a routerLink="/main/home" routerLinkActive="active"> OLNW - NOT</a></li>
</ul>
<div style="background-color:#eee;">
<router-outlet></router-outlet>
</div>
</h1>
Tada! ..and you are welcome =)
Update2: As of v2.4.10 <a target="_blank" routerLink="/Page2">
works
Take a look at Simple JavaScript Inheritance and Inheritance Patterns in JavaScript.
The simplest method is probably functional inheritance but there are pros and cons.
Dim
and Private
work the same, though the common convention is to use Private
at the module level, and Dim
at the Sub/Function level. Public
and Global
are nearly identical in their function, however Global
can only be used in standard modules, whereas Public
can be used in all contexts (modules, classes, controls, forms etc.) Global
comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public
.
Update: as of Python 3.7, insertion order is maintained, so you don't need an OrderedDict
here. You can use the below approaches with a normal dict
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
Python 3.6 and earlier*
If you are talking about a regular dict
, then the "first key" doesn't mean anything. The keys are not ordered in any way you can depend on. If you iterate over your dict
you will likely not get "banana"
as the first thing you see.
If you need to keep things in order, then you have to use an OrderedDict
and not just a plain dictionary.
import collections
prices = collections.OrderedDict([
("banana", 4),
("apple", 2),
("orange", 1.5),
("pear", 3),
])
If you then wanted to see all the keys in order you could do so by iterating through it
for k in prices:
print(k)
You could, alternatively put all of the keys into a list and then work with that
ks = list(prices)
print(ks[0]) # will print "banana"
A faster way to get the first element without creating a list would be to call next
on the iterator. This doesn't generalize nicely when trying to get the nth
element though
>>> next(iter(prices))
'banana'
* CPython had guaranteed insertion order as an implementation detail in 3.6.
Quoting http://php.net/manual/en/intro.mssql.php:
The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.
Once you downloaded that, follow the instructions at this page:
In a nutshell:
Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:extension=php_sqlsrv_53_nts_vc9.dll
Restart the Web server.
See Also (copied from that page)
The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:
The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.
The drivers can also be used with PDO.
First, as a one-time data-scrubbing exercise, delete the orphaned rows e.g.
DELETE
FROM ReferencingTable
WHERE NOT EXISTS (
SELECT *
FROM MainTable AS T1
WHERE T1.pk_col_1 = ReferencingTable.pk_col_1
);
Second, as a one-time schema-alteration exercise, add the ON DELETE CASCADE
referential action to the foreign key on the referencing table e.g.
ALTER TABLE ReferencingTable DROP
CONSTRAINT fk__ReferencingTable__MainTable;
ALTER TABLE ReferencingTable ADD
CONSTRAINT fk__ReferencingTable__MainTable
FOREIGN KEY (pk_col_1)
REFERENCES MainTable (pk_col_1)
ON DELETE CASCADE;
Then, forevermore, rows in the referencing tables will automatically be deleted when their referenced row is deleted.
I realize this is an old question, and the OP is talking about using custom gx that aren't necessary 'checkbox'-looking, but there is a fantastic resource for generating custom colored assets here: http://kobroor.pl/
Just give it the relevant details and it spits out graphics, complete with xml resources, that you can just drop right in.
If you don't care about the actual key, a concise way to iterate over all the Map's values would be to use its values()
method
Map<String, List<String>> myMap;
for ( List<String> stringList : myMap.values() ) {
for ( String myString : stringList ) {
// process the string here
}
}
The values()
method is part of the Map interface and returns a Collection view of the values in the map.
As @Ian explained, the problem is that jQuery's click()
is not the same as the native one.
Therefore, consider using vanilla-js instead of jQuery:
var a = document.createElement('a');
a.href = "img.png";
a.download = "output.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
Add readonly
:
<input type="text" value="3" class="field left" readonly>
If you want the value to be not submitted in a form, instead add the disabled
attribute.
<input type="text" value="3" class="field left" disabled>
There is no way to use CSS that always works to do this.
Why? CSS can't "disable" anything. You can still turn off display or visibility and use pointer-events: none
but pointer-events
doesn't work on versions of IE that came out earlier than IE 11.
Use the spec parameter.
Instructions below.
Create a new javascript file in the same directory as index.html (/dist/)
Then insert spec
variable declaration:
var spec =
Then paste in the swagger.json file contents after. It does not have to be on the same line as the =
sign.
Example:
var spec =
{
"swagger": "2.0",
"info": {
"title": "I love Tex-Mex API",
"description": "You can barbecue it, boil it, broil it, bake it, sauté it. Dey's uh, Tex-Mex-kabobs, Tex-Mex creole, Tex-Mex gumbo. Pan fried, deep fried, stir-fried. There's pineapple Tex-Mex, lemon Tex-Mex, coconut Tex-Mex, pepper Tex-Mex, Tex-Mex soup, Tex-Mex stew, Tex-Mex salad, Tex-Mex and potatoes, Tex-Mex burger, Tex-Mex sandwich..",
"version": "1.0.0"
},
...
}
}
This is a two-step like Ciara.
Modify the /dist/index.html file to include the external spec.js
file.
<script src='spec.js' type="text/javascript"></script>
Example:
<!-- Some basic translations -->
<!-- <script src='lang/translator.js' type='text/javascript'></script> -->
<!-- <script src='lang/ru.js' type='text/javascript'></script> -->
<!-- <script src='lang/en.js' type='text/javascript'></script> -->
<!-- Original file pauses -->
<!-- Insert external modified swagger.json -->
<script src='spec.js' type="text/javascript"></script>
<!-- Original file resumes -->
<script type="text/javascript">
$(function () {
var url = window.location.search.match(/url=([^&]+)/);
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
} else {
url = "http://petstore.swagger.io/v2/swagger.json";
}
Modify the SwaggerUi instance to include the spec
parameter:
window.swaggerUi = new SwaggerUi({
url: url,
spec: spec,
dom_id: "swagger-ui-container",
While Arvin Amir's answer comes close to a full one-line solution you can drop in anywhere; he's got a slight bug in his select statement (missing the end of the line), and I wanted to handle the most common character references.
What I ended up doing was this:
SELECT replace(replace(replace(CAST(CAST(replace([columnNameHere], '&', '&') as xml).query('for $x in //. return concat((($x)//text())[1]," ")') as varchar(max)), '&', '&'), ' ', ' '), ' ', ' ')
FROM [tableName]
Without the character reference code it can be simplified to this:
SELECT CAST(CAST([columnNameHere] as xml).query('for $x in //. return concat((($x)//text())[1]," ")') as varchar(max))
FROM [tableName]
There really isn't a need to create a custom click event as suggested in the bountied answer or to show the url as suggested in the accepted answer.
window.open(url)
1 does open web pages automatically without user interaction, provided pop- up blockers are disabled(as is the case with Stephen's answer)
<!DOCTYPE html>
<html>
<head>
<base target="_blank">
<script>
var url1 ='https://stackoverflow.com/a/54675103';
var winRef = window.open(url1);
winRef ? google.script.host.close() : window.alert('Allow popup to redirect you to '+url1) ;
window.onload=function(){document.getElementById('url').href = url1;}
</script>
</head>
<body>
Kindly allow pop ups</br>
Or <a id='url'>Click here </a>to continue!!!
</body>
</html>
function modalUrl(){
SpreadsheetApp.getUi()
.showModalDialog(
HtmlService.createHtmlOutputFromFile('openUrl').setHeight(50),
'Opening StackOverflow'
)
}
Scope prototype means that every time you ask spring (getBean or dependency injection) for an instance it will create a new instance and give a reference to that.
In your example a new instance of LoginAction is created and injected into your HomeController . If you have another controller into which you inject LoginAction you will get a different instance.
If you want a different instance for each call - then you need to call getBean each time - injecting into a singleton bean will not achieve that.
Subclipse gets confused by Windows' truly diabolical locking behaviour. Unlocker is your friend. This can find locked files and forcibly release the locks.