I had used JCL about 2 years back so cannot write a code for you but here is the idea;
again i apologize for solution without code, but i am out of touch by 2 yrs+
As suggested by @linqu you should not change your data for presentation. Since pandas 0.17.1, (conditional) formatting was made easier. Quoting the documentation:
You can apply conditional formatting, the visual styling of a
DataFrame
depending on the data within, by using theDataFrame.style
property. This is a property that returns apandas.Styler
object, which has useful methods for formatting and displayingDataFrames
.
For your example, that would be (the usual table will show up in Jupyter):
df.style.format({
'var1': '{:,.2f}'.format,
'var2': '{:,.2f}'.format,
'var3': '{:,.2%}'.format,
})
You can use continue
if condition:
continue
else:
#do something
header = table_df.iloc[0]
table_df.drop([0], axis =0, inplace=True)
table_df.reset_index(drop=True)
table_df.columns = header
table_df
Here is how we solved it
a Users table looked like this
Users
-------------------------------------------------
id | name | address | phone | email | created_on | updated_on
And the business requirement changed and we were in a need to check all previous addresses and phone numbers a user ever had. new schema looks like this
Users (the data that won't change over time)
-------------
id | name
UserData (the data that can change over time and needs to be tracked)
-------------------------------------------------
id | id_user | revision | city | address | phone | email | created_on
1 | 1 | 0 | NY | lake st | 9809 | @long | 2015-10-24 10:24:20
2 | 1 | 2 | Tokyo| lake st | 9809 | @long | 2015-10-24 10:24:20
3 | 1 | 3 | Sdny | lake st | 9809 | @long | 2015-10-24 10:24:20
4 | 2 | 0 | Ankr | lake st | 9809 | @long | 2015-10-24 10:24:20
5 | 2 | 1 | Lond | lake st | 9809 | @long | 2015-10-24 10:24:20
To find the current address of any user, we search for UserData with revision DESC and LIMIT 1
To get the address of a user between a certain period of time we can use created_on bewteen (date1 , date 2)
First of all, you don't quite get what's reduce's previous value is.
In you pseudo code you have return previous.value + current.value
, therefore the previous
value will be a number on the next call, not an object.
Second, reduce
is an Array method, not an Object's one, and you can't rely on the order when you're iterating the properties of an object (see: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...in, this is applied to Object.keys too); so I'm not sure if applying reduce
over an object makes sense.
However, if the order is not important, you can have:
Object.keys(obj).reduce(function(sum, key) {
return sum + obj[key].value;
}, 0);
Or you can just map the object's value:
Object.keys(obj).map(function(key) { return this[key].value }, obj).reduce(function (previous, current) {
return previous + current;
});
P.S. in ES6 with the fat arrow function's syntax (already in Firefox Nightly), you could shrink a bit:
Object.keys(obj).map(key => obj[key].value).reduce((previous, current) => previous + current);
The tag is not closed:
$form.append("<input type=button value=button");
Should be:
$form.append('<input type="button" value="button">');
If the images are generated via an ASP Response.Write()
, make sure you don't call Response.Close();
. Chrome doesn't like it.
You cannot get the exact code, but you can get a decompiled version of it.
The most popular (and best) tool is Reflector, but there are also other .Net decompilers (such as Dis#). You can also decompile the IL using ILDASM, which comes bundled with the .Net Framework SDK Tools.
The fix is to stop using correlated subqueries and use joins instead. Correlated subqueries are essentially cursors as they cause the query to run row-by-row and should be avoided.
You may need a derived table in the join in order to get the value you want in the field if you want only one record to match, if you need both values then the ordinary join
will do that but you will get multiple records for the same id in the results set. If you only want one, you need to decide which one and do that in the code, you could use a top 1
with an order by
, you could use max()
, you could use min()
, etc, depending on what your real requirement for the data is.
Check the file in <TOMCAT_HOME>/conf
named tomcat-users.xml
.
If you don't find something there edit to look something like:
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="admin"/>
<user username="admin" password="password" roles="standard,manager,admin"/>
</tomcat-users>
None of the bulk action solutions have worked for me. The extended attributes don't get removed. Each time this has happened for me it was a problem with one or more 3D models (.dae) or a .png file.
I have found that removing attributes (detritus) one file at a time works out to be faster in the end. I had to switch to the art.scnassets directory in terminal. (You can drag it from finder to terminal) For each suspect (new) file, I ran "xattr -lr filename.ext" to see if it had extended attributes. If so, I ran "xattr -cr filename.ext" to remove them. It has worked every time, but only by removing the attributes for each file. Then use Product - Clean Build Folder, and Build again. It has worked every time without fail.
1 - Change Your tables search engine from 'My ISAM' to 'Inno DB' by Operations tab 2 - you must do this for all tables that you want make relationship between 3 - localhost/phpmyadmin/tbl_relation.php?db=your_database_name&table=your_table_name then replace this url in browser, then you will be able to see the relationship page
Instead of Str(RequestID)
, try convert(varchar(38), RequestID)
In bootstrap 4
to center the children horizontally, use bootstrap-4 class
justify-content-center
to center the children vertically, use bootstrap-4 class
align-items-center
but remember don't forget to use d-flex class with these it's a bootstrap-4 utility class, like so
<div class="d-flex justify-content-center align-items-center" style="height:100px;">
<div class="bg-primary">MIDDLE</div>
</div>
Note: make sure to add bootstrap-4 utilities if this code does not work
HTML
<div id="wrapper">
<div id="nav"></div>
<div id="content"></div>
<div class="clearFloat"></div>
</div>
CSS
.clearFloat {
font-size: 0px;
line-height: 0px;
margin: 0px;
padding: 0px;
clear: both;
height: 0px;
}
If you use vim-plug (Plug), " A minimalist Vim plugin manager.":
:PlugStatus
That will not only list your plugins but check their status.
System.Environment.TickCount and the System.Diagnostics.Stopwatch class are two that work well for finer resolution and straightforward usage.
See Also:
Just use the plain ol' class selector.
$('#my_id .my_class')
It doesn't matter if the element also has other classes. It has the .my_class class, and it's somewhere inside #my_id, so it will match that selector.
According to the jQuery selector performance documentation, it's faster to use the two selectors separately, like this:
$('#my_id').find('.my_class')
Here's the relevant part of the documentation:
ID-Based Selectors
// Fast: $( "#container div.robotarm" ); // Super-fast: $( "#container" ).find( "div.robotarm" );
The
.find()
approach is faster because the first selection is handled without going through the Sizzle selector engine – ID-only selections are handled usingdocument.getElementById()
, which is extremely fast because it is native to the browser.
Selecting by ID or by class alone (among other things) invokes browser-supplied functions like document.getElementById()
which are quite rapid, whereas using a descendent selector invokes the Sizzle engine as mentioned which, although fast, is slower than the suggested alternative.
I think this simply just work with bootstrap 4, i adding in inline but you always can bind event from script.
<a
onmouseover="$('#navbarDropdownMenuLink').dropdown('toggle')"
class="nav-link dropdown-toggle"
href="http://example.com"
id="navbarDropdownMenuLink"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false">
Dropdown link
</a>
A secret that you share with lots of people is not a secret. If you have secret stuff in your code, obfuscating it is no protection; it only has to be deobfuscated once. If you have a secret that you don't want to share with your customers, then don't share it with your customers. Write your code as a web service and keep your super secret code on your own server, where only you can see it.
I found the solution to this with path name: /usr/lib/jvm/java-8-oracle
I'm on mint 18.1
If preg_match
did not find a match, $matches
is an empty array. So you should check if preg_match
found an match before accessing $matches[0]
, for example:
function get_match($regex,$content)
{
if (preg_match($regex,$content,$matches)) {
return $matches[0];
} else {
return null;
}
}
This is supposedly because you trying to make cross-domain request, or something that is clarified as it.
You could try adding header('Access-Control-Allow-Origin: *');
to the requested file.
Also, such problem is sometimes occurs on server-sent events implementation in case of using event-source
or XHR polling
in IE 8-10 (which confused me first time).
Solution it's quite simple
Just enable Builds for iOS 8 and Later
Like this:
>>> text = 'a,b,c'
>>> text = text.split(',')
>>> text
[ 'a', 'b', 'c' ]
Alternatively, you can use eval()
if you trust the string to be safe:
>>> text = 'a,b,c'
>>> text = eval('[' + text + ']')
I know it was not available at the time, but now you could also use Anaconda navigator to install a specific version of packages in the environments tab.
As an alternative to BalusC answer as it has been deprecated and you have to use proxies, you can use this package. Code sample:
Map<String, String> parameter = new HashMap<>();
parameter.put("q", "Coffee");
parameter.put("location", "Portland");
GoogleSearchResults serp = new GoogleSearchResults(parameter);
JsonObject data = serp.getJson();
JsonArray results = (JsonArray) data.get("organic_results");
JsonObject first_result = results.get(0).getAsJsonObject();
System.out.println("first coffee: " + first_result.get("title").getAsString());
Library on GitHub
Something as simple as this will work
awk 'BEGIN{system("echo hello")}'
and
awk 'BEGIN { system("date"); close("date")}'
CSS zoom
property is widely supported now > 86% of total browser population.
See: http://caniuse.com/#search=zoom
document.querySelector('#sel-jsz').style.zoom = 4;
_x000D_
#sel-001 {_x000D_
zoom: 2.5;_x000D_
}_x000D_
#sel-002 {_x000D_
zoom: 5;_x000D_
}_x000D_
#sel-003 {_x000D_
zoom: 300%;_x000D_
}
_x000D_
<div id="sel-000">IMG - Default</div>_x000D_
_x000D_
<div id="sel-001">IMG - 1X</div>_x000D_
_x000D_
<div id="sel-002">IMG - 5X</div>_x000D_
_x000D_
<div id="sel-003">IMG - 3X</div>_x000D_
_x000D_
_x000D_
<div id="sel-jsz">JS Zoom - 4x</div>
_x000D_
try
{
// your code
}
catch (Exception w)
{
MessageDialog msgDialog = new MessageDialog(w.ToString());
}
Have you got access to SSH?
You can use this command in shell to backup an entire database:
mysqldump -u [username] -p[password] [databasename] > [filename.sql]
This is actually one command followed by the >
operator, which says, "take the output of the previous command and store it in this file."
Note: The lack of a space between -p and the mysql password is not a typo. However, if you leave the -p
flag present, but the actual password blank then you will be prompted for your password. Sometimes this is recommended to keep passwords out of your bash history.
The usual way is to use zip()
:
for x, y in zip(a, b):
# x is from a, y is from b
This will stop when the shorter of the two iterables a
and b
is exhausted. Also worth noting: itertools.izip()
(Python 2 only) and itertools.izip_longest()
(itertools.zip_longest()
in Python 3).
The Philippe solution but cleaner:
My subtraction data is: '2018-09-22T11:05:00.000Z'
import datetime
import pandas as pd
df_modified = pd.to_datetime(df_reference.index.values) - datetime.datetime(2018, 9, 22, 11, 5, 0)
I wasn't able to make the accepted answer work in a Docker container.
What worked for me was to set the Personal Access Token from github in a file .nextrc
ARG GITHUB_READ_TOKEN
RUN echo -e "machine github.com\n login $GITHUB_READ_TOKEN" > ~/.netrc
RUN npm install --only=production --force \
&& npm cache clean --force
RUN rm ~/.netrc
in package.json
"my-lib": "github:username/repo",
This code will check whether the alert is present or not.
public static void isAlertPresent(){
try{
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText()+" Alert is Displayed");
}
catch(NoAlertPresentException ex){
System.out.println("Alert is NOT Displayed");
}
}
Try this:
var keys = [];
for (var key in dictionary) {
if (dictionary.hasOwnProperty(key)) {
keys.push(key);
}
}
hasOwnProperty
is needed because it's possible to insert keys into the prototype object of dictionary
. But you typically don't want those keys included in your list.
For example, if you do this:
Object.prototype.c = 3;
var dictionary = {a: 1, b: 2};
and then do a for...in
loop over dictionary
, you'll get a
and b
, but you'll also get c
.
It could be something like that:
var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
var arrays = [], size = 3;
while (a.length > 0)
arrays.push(a.splice(0, size));
console.log(arrays);
_x000D_
See splice Array's method.
In your component.ts
import { Component } from '@angular/core';
@Component({
...
})
export class AppComponent {
...
goToSpecificUrl(url): void {
window.location.href=url;
}
gotoGoogle() : void {
window.location.href='https://www.google.com';
}
}
In your component.html
<button type="button" (click)="goToSpecificUrl('http://stackoverflow.com/')">Open URL</button>
<button type="button" (click)="gotoGoogle()">Open Google</button>
<li *ngFor="item of itemList" (click)="goToSpecificUrl(item.link)"> // (click) don't enable pointer when we hover so we should enable it by using css like: **cursor: pointer;**
You need to disable quoting.
cit <- read.csv("citations.CSV", quote = "",
row.names = NULL,
stringsAsFactors = FALSE)
str(cit)
## 'data.frame': 112543 obs. of 13 variables:
## $ row.names : chr "10.2307/675394" "10.2307/30007362" "10.2307/4254931" "10.2307/20537934" ...
## $ id : chr "10.2307/675394\t" "10.2307/30007362\t" "10.2307/4254931\t" "10.2307/20537934\t" ...
## $ doi : chr "Archaeological Inference and Inductive Confirmation\t" "Sound and Sense in Cath Almaine\t" "Oak Galls Preserved by the Eruption of Mount Vesuvius in A.D. 79_ and Their Probable Use\t" "The Arts Four Thousand Years Ago\t" ...
## $ title : chr "Bruce D. Smith\t" "Tomás Ó Cathasaigh\t" "Hiram G. Larew\t" "\t" ...
## $ author : chr "American Anthropologist\t" "Ériu\t" "Economic Botany\t" "The Illustrated Magazine of Art\t" ...
## $ journaltitle : chr "79\t" "54\t" "41\t" "1\t" ...
## $ volume : chr "3\t" "\t" "1\t" "3\t" ...
## $ issue : chr "1977-09-01T00:00:00Z\t" "2004-01-01T00:00:00Z\t" "1987-01-01T00:00:00Z\t" "1853-01-01T00:00:00Z\t" ...
## $ pubdate : chr "pp. 598-617\t" "pp. 41-47\t" "pp. 33-40\t" "pp. 171-172\t" ...
## $ pagerange : chr "American Anthropological Association\tWiley\t" "Royal Irish Academy\t" "New York Botanical Garden Press\tSpringer\t" "\t" ...
## $ publisher : chr "fla\t" "fla\t" "fla\t" "fla\t" ...
## $ type : logi NA NA NA NA NA NA ...
## $ reviewed.work: logi NA NA NA NA NA NA ...
I think is because of this kind of lines (check "Thorn" and "Minus")
readLines("citations.CSV")[82]
[1] "10.2307/3642839,10.2307/3642839\t,\"Thorn\" and \"Minus\" in Hieroglyphic Luvian Orthography\t,H. Craig Melchert\t,Anatolian Studies\t,38\t,\t,1988-01-01T00:00:00Z\t,pp. 29-42\t,British Institute at Ankara\t,fla\t,\t,"
The below function gives distance between two geocoordinates in miles
create function [dbo].[fnCalcDistanceMiles] (@Lat1 decimal(8,4), @Long1 decimal(8,4), @Lat2 decimal(8,4), @Long2 decimal(8,4))
returns decimal (8,4) as
begin
declare @d decimal(28,10)
-- Convert to radians
set @Lat1 = @Lat1 / 57.2958
set @Long1 = @Long1 / 57.2958
set @Lat2 = @Lat2 / 57.2958
set @Long2 = @Long2 / 57.2958
-- Calc distance
set @d = (Sin(@Lat1) * Sin(@Lat2)) + (Cos(@Lat1) * Cos(@Lat2) * Cos(@Long2 - @Long1))
-- Convert to miles
if @d <> 0
begin
set @d = 3958.75 * Atan(Sqrt(1 - power(@d, 2)) / @d);
end
return @d
end
The below function gives distance between two geocoordinates in kilometres
CREATE FUNCTION dbo.fnCalcDistanceKM(@lat1 FLOAT, @lat2 FLOAT, @lon1 FLOAT, @lon2 FLOAT)
RETURNS FLOAT
AS
BEGIN
RETURN ACOS(SIN(PI()*@lat1/180.0)*SIN(PI()*@lat2/180.0)+COS(PI()*@lat1/180.0)*COS(PI()*@lat2/180.0)*COS(PI()*@lon2/180.0-PI()*@lon1/180.0))*6371
END
The below function gives distance between two geocoordinates in kilometres using Geography data type which was introduced in sql server 2008
DECLARE @g geography;
DECLARE @h geography;
SET @g = geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656)', 4326);
SET @h = geography::STGeomFromText('POINT(-122.34900 47.65100)', 4326);
SELECT @g.STDistance(@h);
Usage:
select [dbo].[fnCalcDistanceKM](13.077085,80.262675,13.065701,80.258916)
if I got your question correct...
main() method is defined in the class below...
public class ToBeCalledClass{
public static void main (String args[ ]) {
System.out.println("I am being called");
}
}
you want to call this main method in another class.
public class CallClass{
public void call(){
ToBeCalledClass.main(null);
}
}
Here's the solution:
#sec-one{padding: 15px 0;}_x000D_
p{text-align: center;}_x000D_
/*_x000D_
* Change the color to any color you want;_x000D_
* or set to none if you don't any outline at all._x000D_
*/_x000D_
*:focus:not(a){_x000D_
outline: 2px solid #f90d0e !important;_x000D_
box-shadow: none !important;_x000D_
}
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
</head>_x000D_
<body>_x000D_
<section id="sec-one">_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col">_x000D_
<form>_x000D_
<fieldset class="form-group">_x000D_
<input type="text" class="form-control" placeholder="Full Name" required>_x000D_
</fieldset>_x000D_
<fieldset class="form-group">_x000D_
<input type="email" class="form-control" placeholder="Email Address" required>_x000D_
</fieldset>_x000D_
<fieldset class="form-group">_x000D_
<input type="submit" class="btn btn-default" value="Sign Up">_x000D_
</fieldset>_x000D_
</form>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</section>_x000D_
</body>_x000D_
</html>
_x000D_
This works 100% hope it helps you.
Yes, the list of keyboard shortcuts for Android Studio is at https://developer.android.com/studio/intro/keyboard-shortcuts.html.
Here are a few that I know.
Check :File ->Settings ->Keymap -> <Choose Eclipse from Keymaps dropdown> or
Add unimplemented methods: CTRL + I
Override methods: CTRL + O
Format code: CTRL + ALT + L
Show project: ALT + 1
Show logcat: ALT + 6
Hide project - logcat: SHIFT + ESC
Build: CTRL + F9
Build and Run: CTRL + F10
Expand all: CTRL + SHIFT + NumPad +
Collapse all: CTRL + SHIFT + NumPad -
Find and replace: CTRL + R
Find: CTRL + F
In case I'm missing any shortcut that you need you can ask here and for more check implink!! or link!!:)
I know it's an old question and Path.GetFileNameWithoutExtension
is a better and maybe cleaner option. But personally I've added this two methods to my project and wanted to share them. This requires C# 8.0 due to it using ranges and indices.
public static string RemoveExtension(this string file) => ReplaceExtension(file, null);
public static string ReplaceExtension(this string file, string extension)
{
var split = file.Split('.');
if (string.IsNullOrEmpty(extension))
return string.Join(".", split[..^1]);
split[^1] = extension;
return string.Join(".", split);
}
I just went through the same problem. And found out once you have a syntax or any type of error in you javascript, the whole file don't get loaded so you cannot use any of the other functions at all.
I am a pragmatist, so I will try to look at this in terms of costs and benefits.
Note that for any disadvantage I give, I recognize that they are solvable. That's why I don't look at anything as black and white, but rather, costs and benefits.
Advantages
Disadvantages
Again, I recognize that every one of these problems is solvable, at some cost. But there comes a point where you are spending all your time solving problems which you could have just avoided in the first place. It comes back to the benefits and how important they are to you.
Let us say we are migrating Jenkins LTS from PC1 to PC2 (irrispective of LTS version is same of upgraded). It is easy to use ThinBackUp Plugin for migration or Upgrade of Jenkins version.
Step1: Prepare PC1 for migration
Note: This Thinbackup will also take Plugin Backup which is optional.
Step2: Install Jenkins (Install using .war file or Paste archived version) in PC2.
sc create <Jenkins_PC2Servicename> binPath="<Path_to_Jenkinsexe>/jenkins.exe"
NOTE: If you are using Database setting of SCM in your Jenkins jobs then you need to take extra care as all SCM plugins do not support to carry Database settings with the help of ThinbackUp plugin. e.g. If you are using PTC Integrity SCM Plugin, and some Jenkins jobs are using DB using Integrity, then it will create a directory JENKINS_Home/IntegritySCM, ThinbackUp will not include this DB while taking backup.
Solution: Directly Copy this JENKINS_Home/IntegritySCM folder from PC1 to PC2.
If you would like to use a more functional approach to iterating over a string (perhaps to transform it somehow), you can split the string into characters, apply a function to each one, then join the resulting list of characters back into a string.
A string is inherently a list of characters, hence 'map' will iterate over the string - as second argument - applying the function - the first argument - to each one.
For example, here I use a simple lambda approach since all I want to do is a trivial modification to the character: here, to increment each character value:
>>> ''.join(map(lambda x: chr(ord(x)+1), "HAL"))
'IBM'
or more generally:
>>> ''.join(map(my_function, my_string))
where my_function takes a char value and returns a char value.
You can generate an AWR (automatic workload repository) report from the database.
Run from the SQL*Plus command line:
SQL> @$ORACLE_HOME/rdbms/admin/awrrpt.sql
Read the document related to how to generate & understand an AWR report. It will give a complete view of database performance and resource issues. Once we are familiar with the AWR report it will be helpful to find Top SQL which is consuming resources.
Also, in the 12C EM Express UI we can generate an AWR.
In order to include a global library, eg jquery.js
file in the scripts array from angular-cli.json
(angular.json
when using angular 6+):
"scripts": [
"../node_modules/jquery/dist/jquery.js"
]
After this, restart ng serve if it is already started.
For the first question, I find dev.print
to be the best when working interactively. First, you set up your plot visually and when you are happy with what you see, you can ask R to save the current plot to disk
dev.print(pdf, file="filename.pdf");
You can replace pdf
with other formats such as png
.
This will copy the image exactly as you see it on screen. The problem with dev.copy
is that the image is often different and doesn't remember the window size and aspect ratio - it forces the plot to be square by default.
For the second question, (as others have already answered), you must direct the output to disk before you execute your plotting commands
pdf('filename.pdf')
plot( yourdata )
points (some_more_data)
dev.off() # to complete the writing process and return output to your monitor
The field is formatted as 'Text', which means that formulas aren't evaluated. Change the formatting to something else, press F2 on the cell and Enter.
As Tyler has suggested in one of the comments here, using
max-width: 100%;
on the child may work (worked for me). Using align-self: stretch
only works if you aren't using align-items: center
(which I did). width: 100%
only works if you haven't multiple childs inside your flexbox which you want to show side by side.
Personally I rarely write loops myself now when I can get away with it... I use the Jakarta commons libs:
Customer findCustomerByid(final int id){
return (Customer) CollectionUtils.find(customers, new Predicate() {
public boolean evaluate(Object arg0) {
return ((Customer) arg0).getId()==id;
}
});
}
Yay! I saved one line!
Try using cut... its fast and easy
First you have repeated spaces, you can squeeze those down to a single space between columns if thats what you want with tr -s ' '
If each column already has just one delimiter between it, you can use cut -d ' ' -f-2
to print fields (columns) <= 2.
for example if your data is in a file input.txt you can do one of the following:
cat input.txt | tr -s ' ' | cut -d ' ' -f-2
Or if you better reason about this problem by removing the 3rd column you can write the following
cat input.txt | tr -s ' ' | cut -d ' ' --complement -f3
cut is pretty powerful, you can also extract ranges of bytes, or characters, in addition to columns
excerpt from the man page on the syntax of how to specify the list range
Each LIST is made up of one range, or many ranges separated by commas.
Selected input is written in the same order that it is read, and is
written exactly once. Each range is one of:
N N'th byte, character or field, counted from 1
N- from N'th byte, character or field, to end of line
N-M from N'th to M'th (included) byte, character or field
-M from first to M'th (included) byte, character or field
so you also could have said you want specific columns 1 and 2 with...
cat input.txt | tr -s ' ' | cut -d ' ' -f1,2
For those who are looking to combine 2 color images into one, this is a slight mod on Andrey's answer which worked for me :
img1 = cv2.imread(imageFile1)
img2 = cv2.imread(imageFile2)
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
#create empty matrix
vis = np.zeros((max(h1, h2), w1+w2,3), np.uint8)
#combine 2 images
vis[:h1, :w1,:3] = img1
vis[:h2, w1:w1+w2,:3] = img2
What could the reason be
A query cancel is immediate, provided that your attention can reach the server and be processed. A query must be in a cancelable state, which is almost always true except if you do certain operations like calling a web service from SQLCLR. If your attention cannot reach the server it's usually due to scheduler overload.
But if your query is part of a transaction that must rollback, then rollback cannot be interrupted. If it takes 10 minutes then it needs 10 minutes and there's nothing you can do about it. Even restarting the server will not help, it will only make startup longer since recovery must finish the rollback.
To answer which specific reason applies to your case, you'll need to investigate yourself.
Because that syntax simply isn't defined? Besides, x < y
evaluates as a bool, so what does bool < int
mean? It isn't really an overhead; besides, you could write a utility method if you really want - isBetween(10,x,20)
- I wouldn't myself, but hey...
I had a similar error which caused json_encode to return a null field whenever there was a hi-ascii character such as a curly apostrophe in a string, due to the wrong character set being returned in the query.
The solution was to make sure it comes as utf8 by adding:
mysql_set_charset('utf8');
after the mysql connect statement.
.toString()
is available, or just add ""
to the end of the int
var x = 3,
toString = x.toString(),
toConcat = x + "";
Angular is simply JavaScript at the core.
Under Cygwin, the only thing that worked for me is the following:
git config --global merge.tool myp4merge
git config --global mergetool.myp4merge.cmd 'p4merge.exe "$(cygpath -wla $BASE)" "$(cygpath -wla $LOCAL)" "$(cygpath -wla $REMOTE)" "$(cygpath -wla $MERGED)"'
git config --global diff.tool myp4diff
git config --global difftool.myp4diff.cmd 'p4merge.exe "$(cygpath -wla $LOCAL)" "$(cygpath -wla $REMOTE)"'
Also, I like to turn off the prompt message for difftool:
git config --global difftool.prompt false
HTML 5 allows summary tag, details element. That can be used to view or hide (collapse/expand) a section. Link
You can try this also:
private void Page_Loaded_1(object sender, RoutedEventArgs e)
{
Uri iconUri = new Uri(@"C:\Apps\R&D\WPFNavigation\WPFNavigation\Images\airport.ico", UriKind.RelativeOrAbsolute);
(this.Parent as Window).Icon = BitmapFrame.Create(iconUri);
}
As David Aldridge explained, your parentheses should start right after the sqlplus command, so it should be:
sqlplus 'test/test@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=hostname.com )(PORT=1521)))(CONNECT_DATA=(SID=mysid))'
Solution as dictionary comprehension with enumerate:
dict = {item : values[index] for index, item in enumerate(keys)}
Solution as for loop with enumerate:
dict = {}
for index, item in enumerate(keys):
dict[item] = values[index]
Create a new array with a thousand true
values:
var items = Enumerable.Repeat<bool>(true, 1000).ToArray(); // Or ToList(), etc.
Similarly, you can generate integer sequences:
var items = Enumerable.Range(0, 1000).ToArray(); // 0..999
pt is a derivation (abbreviation) of "point" which historically was used in print type faces where the size was commonly "measured" in "points" where 1 point has an approximate measurement of 1/72 of an inch, and thus a 72 point font would be 1 inch in size.
px is an abbreviation for "pixel" which is a simple "dot" on either a screen or a dot matrix printer or other printer or device which renders in a dot fashion - as opposed to old typewriters which had a fixed size, solid striker which left an imprint of the character by pressing on a ribbon, thus leaving an image of a fixed size.
Closely related to point are the terms "uppercase" and "lowercase" which historically had to do with the selection of the fixed typographical characters where the "captital" characters where placed in a box (case) above the non-captitalized characters which were place in a box below, and thus the "lower" case.
There were different boxes (cases) for different typographical fonts and sizes, but still and "upper" and "lower" case for each of those.
Another term is the "pica" which is a measure of one character in the font, thus a pica is 1/6 of an inch or 12 point units of measure (12/72) of measure.
Strickly speaking the measurement is on computers 4.233mm or 0.166in whereas the old point (American) is 1/72.27 of an inch and French is 4.512mm (0.177in.). Thus my statement of "approximate" regarding the measurements.
Further, typewriters as used in offices, had either and "Elite" or a "Pica" size where the size was 10 and 12 characters per inch repectivly.
Additionally, the "point", prior to standardization was based on the metal typographers "foot" size, the size of the basic footprint of one character, and varied somewhat in size.
Note that a typographical "foot" was originally from a deceased printers actual foot. A typographic foot contains 72 picas or 864 points.
As to CSS use, I prefer to use EM rather than px or pt, thus gaining the advantage of scaling without loss of relative location and size.
EDIT: Just for completeness you can think of EM (em) as an element of measure of one font height, thus 1em for a 12pt font would be the height of that font and 2em would be twice that height. Note that for a 12px font, 2em is 24 pixels. SO 10px is typically 0.63em of a standard font as "most" browsers base on 16px = 1em as a standard font size.
The problem, as the Traceback says, comes from the line x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
. Let's replace it in its context:
i + 1 >= len(x)
<=> i >= 0
, the element x[i+1]
doesn't exist. Here, this element doesn't exist since the beginning of the for loop.To solve this, you must replace x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )
by x.append(x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ))
.
You can also create a generic function to get the ID of the post, whether its outside or inside the loop (handles both the cases):
<?php
/**
* @uses WP_Query
* @uses get_queried_object()
* @see get_the_ID()
* @return int
*/
function get_the_post_id() {
if (in_the_loop()) {
$post_id = get_the_ID();
} else {
global $wp_query;
$post_id = $wp_query->get_queried_object_id();
}
return $post_id;
} ?>
And simply do:
$page_id = get_the_post_id();
The exact code will vary for each of the columns you want to do, but it's likely you'll want to use the map
and apply
functions. In some cases you can just compute using the existing columns directly, since the columns are Pandas Series objects, which also work as Numpy arrays, which automatically work element-wise for usual mathematical operations.
>>> d
A B C
0 11 13 5
1 6 7 4
2 8 3 6
3 4 8 7
4 0 1 7
>>> (d.A + d.B) / d.C
0 4.800000
1 3.250000
2 1.833333
3 1.714286
4 0.142857
>>> d.A > d.C
0 True
1 True
2 True
3 False
4 False
If you need to use operations like max and min within a row, you can use apply
with axis=1
to apply any function you like to each row. Here's an example that computes min(A, B)-C
, which seems to be like your "lower wick":
>>> d.apply(lambda row: min([row['A'], row['B']])-row['C'], axis=1)
0 6
1 2
2 -3
3 -3
4 -7
Hopefully that gives you some idea of how to proceed.
Edit: to compare rows against neighboring rows, the simplest approach is to slice the columns you want to compare, leaving off the beginning/end, and then compare the resulting slices. For instance, this will tell you for which rows the element in column A is less than the next row's element in column C:
d['A'][:-1] < d['C'][1:]
and this does it the other way, telling you which rows have A less than the preceding row's C:
d['A'][1:] < d['C'][:-1]
Doing ['A"][:-1]
slices off the last element of column A, and doing ['C'][1:]
slices off the first element of column C, so when you line these two up and compare them, you're comparing each element in A with the C from the following row.
Edit: As Atspulgs comment suggest, you can achieve the same without jQuery using the querySelector:
document.querySelector('head').innerHTML += '<link rel="stylesheet" href="styles.css" type="text/css"/>';
Older answer below.
You could use the jQuery library to select your head element and append HTML to it, in a manner like:
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
You can find a complete tutorial for this problem here
This is one of the most commonly asked question to obtain the paginated result and the total number of results simultaneously in single query. I can't explain how I felt when I finally achieved it LOL.
$result = $collection->aggregate(array(
array('$match' => $document),
array('$group' => array('_id' => '$book_id', 'date' => array('$max' => '$book_viewed'), 'views' => array('$sum' => 1))),
array('$sort' => $sort),
// get total, AND preserve the results
array('$group' => array('_id' => null, 'total' => array( '$sum' => 1 ), 'results' => array( '$push' => '$$ROOT' ) ),
// apply limit and offset
array('$project' => array( 'total' => 1, 'results' => array( '$slice' => array( '$results', $skip, $length ) ) ) )
))
Result will look something like this:
[
{
"_id": null,
"total": ...,
"results": [
{...},
{...},
{...},
]
}
]
AndroidManifest file:
<activity android:name=".activity.DetailsActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="br.com.halyson.materialdesign.activity.HomeActivity" />
</activity>
add in DetailsActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
it's work :]
strings.xml
<string name="sentence">This price is <b>%1$s</b> USD</string>
page.java
String successMessage = getText(R.string.message,"5.21");
This price 5.21 USD
In the end I had had to make changes to the content of the page behind the modal screen to ensure that it never got long enough to scroll the page.
Once I did that, the problems I encountered when applying position: absolute
to the dialog were resolved as the user could no longer scroll down the page.
The best way to solve this problem is:
git checkout -- <path/file_name>
After that you can overwrite the file by:
git pull origin master
It returns whether the statement can evaluate to false. eg:
!false // true
!true // false
!isValid() // is not valid
You can use it twice to coerce a value to boolean:
!!1 // true
!!0 // false
So, to more directly answer your question:
var myVar = !function(){ return false; }(); // myVar contains true
Edit: It has the side effect of changing the function declaration to a function expression. E.g. the following code is not valid because it is interpreted as a function declaration that is missing the required identifier (or function name):
function () { return false; }(); // syntax error
The performance of the suggested answer is fine. According to the MongoDB documentation:
When a $sort immediately precedes a $limit, the optimizer can coalesce the $limit into the $sort. This allows the sort operation to only maintain the top n results as it progresses, where n is the specified limit, and MongoDB only needs to store n items in memory.
Changed in version 4.0.
So in the case of
db.collection.find().sort({age:-1}).limit(1)
we get only the highest element WITHOUT sorting the collection because of the mentioned optimization.
import scipy.interpolate
y_interp = scipy.interpolate.interp1d(x, y)
print y_interp(5.0)
scipy.interpolate.interp1d
does linear interpolation by and can be customized to handle error conditions.
If you're behind a proxy, you should use X-Forwarded-For
: http://en.wikipedia.org/wiki/X-Forwarded-For
It is an IETF draft standard with wide support:
The X-Forwarded-For field is supported by most proxy servers, including Squid, Apache mod_proxy, Pound, HAProxy, Varnish cache, IronPort Web Security Appliance, AVANU WebMux, ArrayNetworks, Radware's AppDirector and Alteon ADC, ADC-VX, and ADC-VA, F5 Big-IP, Blue Coat ProxySG, Cisco Cache Engine, McAfee Web Gateway, Phion Airlock, Finjan's Vital Security, NetApp NetCache, jetNEXUS, Crescendo Networks' Maestro, Web Adjuster and Websense Web Security Gateway.
If not, here are a couple other common headers I've seen:
You might want to try kt. It's also quite faster than the bundled kafka-topics
.
This is the current most complete info description you can get out of a topic with kt:
kt topic -brokers localhost:9092 -filter my_topic_name -partitions -leaders -replicas
It also outputs as JSON, so you can pipe it to jq
for further flexibility.
You can just:
var f = new Date(from.split('-').reverse().join('/'));
If you would like to auto format on save just with Javascript source, add this one into Users Setting
(press Cmd, or Ctrl,):
"[javascript]": { "editor.formatOnSave": true }
I solved this by doing the following:
<body class="container-fluid">
<div class="row">
<div class="span6" style="float: none; margin: 0 auto;">
....
</div>
</div>
</body>
SELECT * FROM Table_Name LIMIT 5;
For those who might have the same problem as me, I got this error when the DB I was using was actually master, and not the DB I should have been using.
Just put use [DBName]
on the top of your script, or manually change the DB in use in the SQL Server Management Studio GUI.
select{
*zoom: 1.6;
*font-size: 9px;
}
If you change properties, size of select
will change also in IE7.
The data in COL1 is in dd-mon-yy
No it's not. A DATE
column does not have any format. It is only converted (implicitely) to that representation by your SQL client when you display it.
If COL1 is really a DATE
column using to_date()
on it is useless because to_date()
converts a string to a DATE.
You only need to_char(), nothing else:
SELECT TO_CHAR(col1, 'mm/dd/yyyy')
FROM TABLE1
What happens in your case is that calling to_date()
converts the DATE
into a character value (applying the default NLS format) and then converting that back to a DATE. Due to this double implicit conversion some information is lost on the way.
Edit
So you did make that big mistake to store a DATE in a character column. And that's why you get the problems now.
The best (and to be honest: only sensible) solution is to convert that column to a DATE
. Then you can convert the values to any rerpresentation that you want without worrying about implicit data type conversion.
But most probably the answer is "I inherited this model, I have to cope with it" (it always is, apparently no one ever is responsible for choosing the wrong datatype), then you need to use RR
instead of YY
:
SELECT TO_CHAR(TO_DATE(COL1,'dd-mm-rr'), 'mm/dd/yyyy')
FROM TABLE1
should do the trick. Note that I also changed mon
to mm
as your example is 27-11-89
which has a number for the month, not an "word" (like NOV)
For more details see the manual: http://docs.oracle.com/cd/B28359_01/server.111/b28286/sql_elements004.htm#SQLRF00215
Try this:
var var1=42;
var var2;
alert(var2 = var1); //show result of assignment expression is assigned value
alert(var2); // show assignment did occur.
Note the single '=' in the first alert. This will show that the result of an assignment expression is the assigned value, and the 2nd alert will show you that assignment did occur.
It follows logically that assignment must have chained from right to left. However, since this is all atomic to the javascript (there's no threading) a particular engine may choose to actually optimize it a little differently.
The OnChange
event is a good choice. But if a user select the same image, the event will not be triggered because the current value is the same as the previous.
The image is the same with a width changed, for example, and it should be uploaded to the server.
To prevent this problem you could to use the following code:
$(document).ready(function(){
$("input[type=file]").click(function(){
$(this).val("");
});
$("input[type=file]").change(function(){
alert($(this).val());
});
});
I've ran across this problem recently while trying to retrieve a null decimal from a DataTable
object from db and I haven't seen this answer here. I find this easier and shorter:
var value = rdrSelect.Field<decimal?>("ColumnName") ?? 0;
This was useful in my case since i didn't have a nullable decimal in the model, but needed a quick check against one. If the db value happens to be null, it'll just assign the default value.
You could alternatively overwrite the 'yourElement.addEventListener()' method and use the '.apply()' method to execute the listener like normal, but intercepting the function in the process. Like:
<script type="text/javascript">
var args = [];
var orginalAddEvent = yourElement.addEventListener;
yourElement.addEventListener = function() {
//console.log(arguments);
args[args.length] = arguments[0];
args[args.length] = arguments[1];
orginalAddEvent.apply(this, arguments);
};
function removeListeners() {
for(var n=0;n<args.length;n+=2) {
yourElement.removeEventListener(args[n], args[n+1]);
}
}
removeListeners();
</script>
This script must be run on page load or it might not intercept all event listeners.
Make sure to remove the 'removeListeners()' call before using.
Sharing this in case anyone needs it:
Old Gradle config( without Gitlab , Docker deployments , for simple projects)
repositories {
google()
jcenter()
maven { url "http://dl.bintray.com/davideas/maven" }
maven { url 'https://plugins.gradle.org/m2/' }
maven { url 'http://repo1.maven.org/maven2' }
maven { url 'http://jcenter.bintray.com' }
}
New config :
repositories {
google()
jcenter()
maven { url "https://dl.bintray.com/davideas/maven" }
maven { url 'https://plugins.gradle.org/m2/' }
maven { url 'https://repo1.maven.org/maven2' }
maven { url 'https://jcenter.bintray.com' }
}
Notice the https. Happy coding :)
A real literal suffixed by M or m is of type decimal (money). For example, the literals 1m, 1.5m, 1e10m, and 123.456M are all of type decimal. This literal is converted to a decimal value by taking the exact value, and, if necessary, rounding to the nearest representable value using banker's rounding. Any scale apparent in the literal is preserved unless the value is rounded or the value is zero (in which latter case the sign and scale will be 0). Hence, the literal 2.900m will be parsed to form the decimal with sign 0, coefficient 2900, and scale 3.
I was thinking of a subclass of UserDict to automagically flat the keys.
class FlatDict(UserDict):
def __init__(self, *args, separator='.', **kwargs):
self.separator = separator
super().__init__(*args, **kwargs)
def __setitem__(self, key, value):
if isinstance(value, dict):
for k1, v1 in FlatDict(value, separator=self.separator).items():
super().__setitem__(f"{key}{self.separator}{k1}", v1)
else:
super().__setitem__(key, value)
? The advantages it that keys can be added on the fly, or using standard dict instanciation, without surprise:
?
>>> fd = FlatDict(
... {
... 'person': {
... 'sexe': 'male',
... 'name': {
... 'first': 'jacques',
... 'last': 'dupond'
... }
... }
... }
... )
>>> fd
{'person.sexe': 'male', 'person.name.first': 'jacques', 'person.name.last': 'dupond'}
>>> fd['person'] = {'name': {'nickname': 'Bob'}}
>>> fd
{'person.sexe': 'male', 'person.name.first': 'jacques', 'person.name.last': 'dupond', 'person.name.nickname': 'Bob'}
>>> fd['person.name'] = {'civility': 'Dr'}
>>> fd
{'person.sexe': 'male', 'person.name.first': 'jacques', 'person.name.last': 'dupond', 'person.name.nickname': 'Bob', 'person.name.civility': 'Dr'}
Well, the first question is easy. There are many en
s (Englishes) but (mostly) only one US English. One would guess there are en-CN
, en-GB
, en-AU
. Guess there might even be Austrian English but that's more yes you can than yes there is.
In my understanding you want to match a non-blank and non-empty string, so the top answer is doing the opposite. I suggest:
(.|\s)*\S(.|\s)*
- this matches any string containing at least one non-whitespace character (the \S
in the middle). It can be preceded and followed by anything, any char or whitespace sequence (including new lines) - (.|\s)*
.
You can try it with explanation on https://regex101.com/.
This analyze pretty much what is available out there: http://www.slideshare.net/SlexAxton/breaking-the-cross-domain-barrier
For postMessage solution take a look to:
https://github.com/chrissrogers/jquery-postmessage/blob/master/jquery.ba-postmessage.js
and a slightly different version:
https://github.com/thomassturm/ender-postmessage/blob/master/ender-postmessage.js
The easiest way to match both
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
and
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
is to use alternation ((...|...)
): specify them as two mostly-separate options:
^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$
By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234
, not (123)123-1234
. So you might want to write:
^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$
(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)
To answer your question, you can explore the contents of the model's output by saving the model as a variable and clicking on it in the environment window. You can then click around to see what it contains and what is stored where.
Another way is to type yourmodelname$
and select the components of the model one by one to see what each contains. When you get to yourmodelname$coefficients
, you will see all of beta-, p, and t- values you desire.
I find the STR function the cleanest means of accomplishing this.
SELECT STR(ceiling(123.415432875), 6, 2)
I prefer specific imports, because it allows me to see all the external references used in the file without looking at the whole file. (Yes, I know it won't necessarily show fully qualified references. But I avoid them whenever possible.)
I object with something I keep seeing over and over in most of these answers, that what makes a function a function is that it returns a value.
A function is not just any old method that returns a value. Not so: In order for a method to be a real function it must return the same value always given a specific input. An example of a method that is not a function is the random
method in most languages, because although it does return a value the value is not always the same.
A function therefore is more akin to a map (e.g. where x -> x'
for a one dimensional function). This is a very important distinction between regular methods and functions because when dealing with real functions the timing and the order in which they are evaluated should never matter where as this is not always the case with non functions.
Here's another example of a method that is not a function but will otherwise still return a value.
// The following is pseudo code:
g(x) = {
if (morning()) {
g = 2 * x;
}
else {
g = x;
}
return g;
}
I further object to the notion that procedures do not return values. A procedure is just a specific way of talking about a function or method. So that means if the underlying method that your procedure defines or implements returns a value then, guess what that procedure returns a value. Take for example the following snippet from the SICP:
// We can immediately translate this definition into a recursive procedure
// for computing Fibonacci numbers:
(define (fib n)
(cond ((= n 0) 0)
((= n 1) 1)
(else (+ (fib (- n 1))
(fib (- n 2))))))
Have you heard of recursive procedures much lately? They are talking about a recursive function (a real function) and it's returning a value and they are using the word "procedure". So what's the difference, then?
Well another way of thinking of a function (besides the meaning mentioned above) is as an abstract representation of an ideal like the numeral 1. A procedure is that actual implementation of that thing. I personally think they are interchangeable.
(Note, if you read that chapter from the link I provide you may find that a harder concept to grasp is not the difference between a function and a procedure, but a process and a procedure. Did you know that a recursive procedure can have an iterative process?)
An analog for procedures are recipes. For example; suppose you have a machine called make-pies
this machine takes in ingredients of (fruit, milk, flower, eggs, sugar, heat)
and this machine returns a pie
.
A representation of this machine might look like
make-pies (fruit, milk, flower, eggs, sugar, heat) = {
return (heat (add fruit (mix eggs flower milk)))
}
Of course that's not the only way to make a pie.
In this case we can see that:
A function is to a machine
as a procedure is to a recipe
as attributes are to ingredients
as output is to product
That analogy is OK but it breaks down when you take into account that when you are dealing with a computer program everything is an abstraction. So unlike in the case of a recipe to a machine we are comparing two things that are themselves abstractions; two things that might as well be the same thing. And I hold that they are (for all intent and purposes) the same thing.
You want to use URI templates. Look carefully at the README of this project: URLEncoder.encode()
does NOT work for URIs.
Let us take your original URL:
http://site-test.test.com/Meetings/IC/DownloadDocument?meetingId=c21c905c-8359-4bd6-b864-844709e05754&itemId=a4b724d1-282e-4b36-9d16-d619a807ba67&file=\s604132shvw140\Test-Documents\c21c905c-8359-4bd6-b864-844709e05754_attachments\7e89c3cb-ce53-4a04-a9ee-1a584e157987\myDoc.pdf
and convert it to a URI template with two variables (on multiple lines for clarity):
http://site-test.test.com/Meetings/IC/DownloadDocument
?meetingId={meetingID}&itemId={itemID}&file={file}
Now let us build a variable map with these three variables using the library mentioned in the link:
final VariableMap = VariableMap.newBuilder()
.addScalarValue("meetingID", "c21c905c-8359-4bd6-b864-844709e05754")
.addScalarValue("itemID", "a4b724d1-282e-4b36-9d16-d619a807ba67e")
.addScalarValue("file", "\\\\s604132shvw140\\Test-Documents"
+ "\\c21c905c-8359-4bd6-b864-844709e05754_attachments"
+ "\\7e89c3cb-ce53-4a04-a9ee-1a584e157987\\myDoc.pdf")
.build();
final URITemplate template
= new URITemplate("http://site-test.test.com/Meetings/IC/DownloadDocument"
+ "meetingId={meetingID}&itemId={itemID}&file={file}");
// Generate URL as a String
final String theURL = template.expand(vars);
This is GUARANTEED to return a fully functional URL!
You can also do like this:
template <typename T>
class make_vector {
public:
typedef make_vector<T> my_type;
my_type& operator<< (const T& val) {
data_.push_back(val);
return *this;
}
operator std::vector<T>() const {
return data_;
}
private:
std::vector<T> data_;
};
And use it like this:
std::vector<int> v = make_vector<int>() << 1 << 2 << 3;
I have been fiddling around with this problem and found out that this solution works for Firefox and safari (yes, im on a mac at the moment).
when getting the request, i made a content-type=iso-8859-1 here:
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/xml; charset=ISO-8859-1');
}
}
Please tell me if someone finds out this doesn't work in ie.
The data-toggle attribute simple tell Bootstrap what exactly to do by giving it the name of the toggle action it is about to perform on a target element. If you specify collapse. It means bootstrap will collapse or uncollapse the element pointed by data-target of the action you clicked
Note: the target element must have the appropriate class for bootstrap to carry out the action
Source action:
data-toggle = collapse //type of toggle
data-target = #myDiv
Target:
class=collapse //I can collapse
id=myDiv
This is same for other type of toggle actions like tab, modal, dropdown
You guessed right MySQL have limitation for size of data, you need to break your query in small group of records or you can Change your max_allowed_packet by using SET GLOBAL max_allowed_packet=524288000;
A simple solution is using the scalers offered by the sklearn.preprocessing library.
scaler = sk.MinMaxScaler(feature_range=(0, 250))
scaler = scaler.fit(X)
X_scaled = scaler.transform(X)
# Checking reconstruction
X_rec = scaler.inverse_transform(X_scaled)
The error X_rec-X will be zero. You can adjust the feature_range for your needs, or even use a standart scaler sk.StandardScaler()
I've been forgetting to share my solution, I couldn't find a way to do this without using JS. There are some corner cases where @Jeffery A Wooden's suggested CSS just wont cover.
This is what I apply to all of my UI containers, no need to apply to each element since it recuses on all the child elements.
CSS:
.unselectable {
/* For Opera and <= IE9, we need to add unselectable="on" attribute onto each element */
/* Check this site for more details: http://help.dottoro.com/lhwdpnva.php */
-moz-user-select: none; /* These user-select properties are inheritable, used to prevent text selection */
-webkit-user-select: none;
-ms-user-select: none; /* From IE10 only */
user-select: none; /* Not valid CSS yet, as of July 2012 */
-webkit-user-drag: none; /* Prevents dragging of images/divs etc */
user-drag: none;
}
JS:
var makeUnselectable = function( $target ) {
$target
.addClass( 'unselectable' ) // All these attributes are inheritable
.attr( 'unselectable', 'on' ) // For IE9 - This property is not inherited, needs to be placed onto everything
.attr( 'draggable', 'false' ) // For moz and webkit, although Firefox 16 ignores this when -moz-user-select: none; is set, it's like these properties are mutually exclusive, seems to be a bug.
.on( 'dragstart', function() { return false; } ); // Needed since Firefox 16 seems to ingore the 'draggable' attribute we just applied above when '-moz-user-select: none' is applied to the CSS
$target // Apply non-inheritable properties to the child elements
.find( '*' )
.attr( 'draggable', 'false' )
.attr( 'unselectable', 'on' );
};
This was way more complicated than it needed to be.
#include <iostream>
#include <cstdio>
#include <ctime>
int main() {
std::clock_t start;
double duration;
start = std::clock();
/* Your algorithm here */
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
std::cout<<"printf: "<< duration <<'\n';
}
Complementing Marco Bonelli's answer: the best current way of interacting between frames/iframes is using window.postMessage
, supported by all browsers
To pass XML content, you need to wrap the content in a Reader
, and unmarshal that instead:
JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader("xml string here");
Person person = (Person) unmarshaller.unmarshal(reader);
Not necessarily true. It will be encrypted on the wire however it still lands in the logs plain text
Clearly HttpContext.Current
is not null
only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".
It won't work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which has no HTTP context associated with.
Overall, don't use Application["Setting"]
to store global stuffs, as they are not global as you discovered.
If you need to pass certain information down to business logic layer, pass as arguments to the related methods. Don't let your business logic layer access things like HttpContext
or Application["Settings"]
, as that violates the principles of isolation and decoupling.
Update:
Due to the introduction of async/await
it is more often that such issues happen, so you might consider the following tip,
In general, you should only call HttpContext.Current
in only a few scenarios (within an HTTP module for example). In all other cases, you should use
Page.Context
https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.page.context?view=netframework-4.7.2 Controller.HttpContext
https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.controller.httpcontext?view=aspnet-mvc-5.2instead of HttpContext.Current
.
Use javascript:
<button onclick="window.location.href='/css_page.html'">CSS page</button>
You can always style the button in css anyaways. Hope it helped!
Good luck!
If you prefer a solution that does not require the initialization of the counter outside the loop, I propose comparing the current iteration key against the function that tells you the last / first key of the array.
This becomes somewhat more efficient (and more readable) with the upcoming PHP 7.3.
foreach($array as $key => $element) {
if ($key === array_key_first($array))
echo 'FIRST ELEMENT!';
if ($key === array_key_last($array))
echo 'LAST ELEMENT!';
}
foreach($array as $key => $element) {
reset($array);
if ($key === key($array))
echo 'FIRST ELEMENT!';
end($array);
if ($key === key($array))
echo 'LAST ELEMENT!';
}
/**
* Simple Java implementation without any input/error checking
* (expects all digits as input)
**/
public class PhoneSpeller
{
private static final char[][] _letters = new char[][]{
{'0'},
{'1'},
{'A', 'B', 'C'},
{'D', 'E', 'F'},
{'G', 'H', 'I'},
{'J', 'K', 'L'},
{'M', 'N', 'O'},
{'P', 'Q', 'R', 'S'},
{'T', 'U', 'V'},
{'W', 'X', 'Y', 'Z'}
};
public static void main(String[] args)
{
if (args.length != 1)
{
System.out.println("Please run again with your phone number (no dashes)");
System.exit(0);
}
recursive_phoneSpell(args[0], 0, new ArrayList<String>());
}
private static void recursive_phoneSpell(String arg, int index, List<String> results)
{
if (index == arg.length())
{
printResults(results);
return;
}
int num = Integer.parseInt(arg.charAt(index)+"");
if (index==0)
{
for (int j = 0; j<_letters[num].length; j++)
{
results.add(_letters[num][j]+"");
}
recursive_phoneSpell(arg, index+1, results);
}
else
{
List<String> combos = new ArrayList<String>();
for (int j = 0; j<_letters[num].length; j++)
{
for (String result : results)
{
combos.add(result+_letters[num][j]);
}
}
recursive_phoneSpell(arg, index+1, combos);
}
}
private static void printResults(List<String> results)
{
for (String result : results)
{
System.out.println(result);
}
}
}
Using MAMP ON Mac, I solve my problem by renaming
/Applications/MAMP/tmp/mysql/mysql.sock.lock
to
/Applications/MAMP/tmp/mysql/mysql.sock
There are many ways of doing it, I am listing few here.
Using backgroundColor
Scaffold(
backgroundColor: Colors.black,
body: Center(...),
)
Using Container
in SizedBox.expand
Scaffold(
body: SizedBox.expand(
child: Container(
color: Colors.black,
child: Center(...)
),
),
)
Using Theme
Theme(
data: Theme.of(context).copyWith(scaffoldBackgroundColor: Colors.black),
child: Scaffold(
body: Center(...),
),
)
Editing the path of the keystore file solved my problem.
If you're up for it, use the DateTime class
In macOS, i had to source it using source ~/.nvm/nvm.sh
command to fix this problem.
After that, add these lines
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
onto ~/.bash_profile
so that nvm will be sourced automatically upon login.
While the answers above are correct, for those who want to get this working in IISNODE you also need to specify
<configuration>
<system.webServer>
<httpErrors existingResponse="PassThrough"/>
</system.webServer>
<configuration>
in your web.config (otherwise IIS will eat your output).
You have to tell the browser what you are sending back so that the browser can take appropriate action like launching a PDF viewer if its a PDF that is being received or launching a video player to play video file ,rendering the HTML if the content type is simple html response, save the bytes of the response as a downloaded file, etc.
some common MIME types are text/html,application/pdf,video/quicktime,application/java,image/jpeg,application/jar etc
In your case since you are sending HTML response to client you will have to set the content type as text/html
If the list to compare against is large, (ie the manilaListRange range in the example above), it is a smart move to use the match function. It avoids the use of a loop which could slow down the procedure. If you can ensure that the manilaListRange is all upper or lower case then this seems to be the best option to me. It is quick to apply 'UCase' or 'LCase' as you do your match.
If you did not have control over the ManilaListRange then you might have to resort to looping through this range in which case there are many ways to compare 'search', 'Instr', 'replace' etc.
If you had a problem as me, that you have already committed some changes, but now, for any reason you want to get rid of it, the quickest way is to use git reset
like this:
git reset --hard HEAD~2
I had 2 not needed commits, hence the number 2. You can change it to your own number of commits to reset.
So answering your question - if you're 5 commits ahead of remote repository HEAD, you should run this command:
git reset --hard HEAD~5
Notice that you will lose the changes you've made, so be careful!
Use \Q
to autoescape any potentially problematic characters in your variable.
if($text_to_search =~ m/\Q$search_string/) print "wee";
SAP released SAP Crystal Reports, developer version for Microsoft Visual Studio
To integrate “SAP Crystal Reports, developer version for Microsoft Visual Studio” you must run the Install Executable. Running the MSI will not fully integrate Crystal Reports into VS. MSI files by definition are for runtime distribution only.
New In SP25 Release
Visual Studio 2019, Addressed incidents, Win10 1809, Security update
You may also use the following code:
USE AdventureWork
GO
CREATE TABLE #GetLargest
(
table_name sysname ,
row_count INT,
reserved_size VARCHAR(50),
data_size VARCHAR(50),
index_size VARCHAR(50),
unused_size VARCHAR(50)
)
SET NOCOUNT ON
INSERT #GetLargest
EXEC sp_msforeachtable 'sp_spaceused ''?'''
SELECT
a.table_name,
a.row_count,
COUNT(*) AS col_count,
a.data_size
FROM #GetLargest a
INNER JOIN information_schema.columns b
ON a.table_name collate database_default
= b.table_name collate database_default
GROUP BY a.table_name, a.row_count, a.data_size
ORDER BY CAST(REPLACE(a.data_size, ' KB', '') AS integer) DESC
DROP TABLE #GetLargest
You can just convert everything to lowercase for the purposes of sorting:
SELECT * FROM NOTES ORDER BY LOWER(title);
If you want to make sure that the uppercase ones still end up ahead of the lowercase ones, just add that as a secondary sort:
SELECT * FROM NOTES ORDER BY LOWER(title), title;
What about to use the specialized version of the "bind" command "one". Once the event handler executes the first time, it’s automatically removed as an event handler.
$(window).one("beforeunload", BeforeUnload);
Basically with UNSIGNED
, you're giving yourself twice as much space for the integer since you explicitly specify you don't need negative numbers (usually because values you store will never be negative).
Another framework which has not been mentioned so far is Laravel. It's great for building PHP apps in general but thanks to the great router it's really comfortable and simple to build rich APIs. It might not be that slim as Slim or Sliex but it gives you a solid structure.
See Aaron Kuzemchak - Simple API Development With Laravel on YouTube and
Laravel 4: A Start at a RESTful API on NetTuts+
It can depend on what your are initialising, for example you cannot just use field initialisation if a checked exception is involved. For example, the following:
public class Foo {
FileInputStream fis = new FileInputStream("/tmp"); // throws FileNotFoundException
}
Will cause a compile-time error unless you also include a constructor declaring that checked exception, or extend a superclass which does, e.g.:
public Foo() throws FileNotFoundException {}
Iterable
were introduced to use in for each loop in java
public interface Collection<E> extends Iterable<E>
Iterator
is class that manages iteration over an Iterable
. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.
According to the Java Virtual Machine Specification (Java SE 8), JVM §4.3.2. Field Descriptors:
FieldType term | Type | Interpretation -------------- | --------- | -------------- L ClassName ; | reference | an instance of class ClassName [ | reference | one array dimension ... | ... | ...
the expression [Ljava.lang.String;@45a877
means this is an array ( [
) of class java.lang.String ( Ljava.lang.String;
). And @45a877
is the address where the String object is stored in memory.
I just switched the main shell to zsh. It suppresses the warnings and it isn't too complicated.
Not all code paths set a value for lateFee
. You may want to set a default value for it at the top.
For those who may find this later, after .NET version 4.6, I was running into this problem as well.
Make sure that you check your web.config file for the following lines:
<compilation debug="true" targetFramework="4.5">
...
<httpRuntime targetFramework="4.5" />
If you are running 4.6.x or a higher version of .NET on the server, make sure you adjust these targetFramework values to match the version of the framework on your server. If your versions read less than 4.6.x, then I would recommend you upgrade .NET and use the newer version unless your code is dependent on an older version (which, in that case, you should consider updating it).
I changed the targetFrameworks to 4.7.2 and the problem disappeared:
<compilation debug="true" targetFramework="4.7.2">
...
<httpRuntime targetFramework="4.7.2" />
The newer frameworks sort this issue out by using the best protocol available and blocking insecure or obsolete ones. If the remote service you are trying to connect to or call is giving this error, it could be that they don't support the old protocols anymore.
you have an type error in example of code. You forget curlybracket after success
$.ajax({
type: "POST",
url: '@Url.Action("Search","Controller")',
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.d.toString());
}
})
;
On top of mentioning your environment variable for HADOOP_HOME
in windows as C:\winutils
, you also need to make sure you are the administrator of the machine. If not and adding environment variables prompts you for admin credentials (even under USER
variables) then these variables will be applicable once you start your command prompt as administrator.
var test = document.getElementById( 'test' );
// To get the text only, you can use "textContent"
console.log( test.textContent ); // "1 2 3 4"
textContent
is the standard way. innerText
is the property to use for legacy IE. If you want something as cross browser as possible, recursively use nodeValue
.
What about a more direct approach?
if (Request.QueryString.AllKeys.Contains("mykey")
Rusty actually produced a whole set of build conditionals in ccan, check out the build assert module:
#include <stddef.h>
#include <ccan/build_assert/build_assert.h>
struct foo {
char string[5];
int x;
};
char *foo_string(struct foo *foo)
{
// This trick requires that the string be first in the structure
BUILD_ASSERT(offsetof(struct foo, string) == 0);
return (char *)foo;
}
There are lots of other helpful macros in the actual header, which are easy to drop into place.
I try, with all of my might to resist the pull of the dark side (and preprocessor abuse) by sticking mostly to inline functions, but I do enjoy clever, useful macros like the ones you described.
Use this:
SELECT *
FROM Sales.SalesOrderHeader
ORDER BY OrderDate
OFFSET (@Skip) ROWS FETCH NEXT (@Take) ROWS ONLY
You probably want ANSI color codes. Most *nix terminals support them.
I usually start with the following when styling definition lists as tables:
dt,
dd{
/* Override browser defaults */
display: inline;
margin: 0;
}
dt {
clear:left;
float:left;
line-height:1; /* Adjust this value as you see fit */
width:33%; /* 1/3 the width of the parent. Adjust this value as you see fit */
}
dd {
clear:right;
float: right;
line-height:1; /* Adjust this value as you see fit */
width:67%; /* 2/3 the width of the parent. Adjust this value as you see fit */
}
var imgSrc, imgW, imgH;
function myFunction(image){
var img = new Image();
img.src = image;
img.onload = function() {
return {
src:image,
width:this.width,
height:this.height};
}
return img;
}
var x = myFunction('http://www.google.com/intl/en_ALL/images/logo.gif');
//Waiting for the image loaded. Otherwise, system returned 0 as both width and height.
x.addEventListener('load',function(){
imgSrc = x.src;
imgW = x.width;
imgH = x.height;
});
x.addEventListener('load',function(){
console.log(imgW+'x'+imgH);//276x110
});
console.log(imgW);//undefined.
console.log(imgH);//undefined.
console.log(imgSrc);//undefined.
This is my method, hope this helpful. :)
One of the way to do this is you can use ResponseEntity as a return object.
@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)
public ResponseEntity<?> create(@RequestBody String data) {
if(everything_fine)
return new ResponseEntity<>(RestModel, HttpStatus.OK);
else
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
Take a look at the following function - REPLACE():
select replace(DataColumn, StringToReplace, NewStringValue)
//example to replace the s in test with the number 1
select replace('test', 's', '1')
//yields te1t
http://msdn.microsoft.com/en-us/library/ms186862.aspx
EDIT
If you want to remove a string, simple use the replace function with an empty string as the third parameter like:
select replace(DataColumn, 'StringToRemove', '')
@ts-expect-error
TS 3.9 introduces a new magic comment. @ts-expect-error
will:
@ts-ignore
if (false) {
// @ts-expect-error: Let's ignore a single compiler error like this unreachable code
console.log("hello"); // compiles
}
// If @ts-expect-error didn't suppress anything at all, we now get a nice warning
let flag = true;
// ...
if (flag) {
// @ts-expect-error
// ^~~~~~~~~~~~~~~^ error: "Unused '@ts-expect-error' directive.(2578)"
console.log("hello");
}
@ts-ignore
and @ts-expect-error
can be used for all sorts of compiler errors. For type issues (like in OP), I recommend one of the following alternatives due to narrower error suppression scope:
? Use any
type
// type assertion for single expression
delete ($ as any).summernote.options.keyMap.pc.TAB;
// new variable assignment for multiple usages
const $$: any = $
delete $$.summernote.options.keyMap.pc.TAB;
delete $$.summernote.options.keyMap.mac.TAB;
? Augment JQueryStatic
interface
// ./global.d.ts
interface JQueryStatic {
summernote: any;
}
// ./main.ts
delete $.summernote.options.keyMap.pc.TAB; // works
In other cases, shorthand module declarations or module augmentations for modules with no/extendable types are handy utilities. A viable strategy is also to keep not migrated code in .js
and use --allowJs
with checkJs: false
.
You could implement your own exceptions and their handling for example like here:
// define exceptions "classes"
function NotNumberException() {}
function NotPositiveNumberException() {}
// try some code
try {
// some function/code that can throw
if (isNaN(value))
throw new NotNumberException();
else
if (value < 0)
throw new NotPositiveNumberException();
}
catch (e) {
if (e instanceof NotNumberException) {
alert("not a number");
}
else
if (e instanceof NotPositiveNumberException) {
alert("not a positive number");
}
}
There is another syntax for catching a typed exception, although this won't work in every browser (for example not in IE):
// define exceptions "classes"
function NotNumberException() {}
function NotPositiveNumberException() {}
// try some code
try {
// some function/code that can throw
if (isNaN(value))
throw new NotNumberException();
else
if (value < 0)
throw new NotPositiveNumberException();
}
catch (e if e instanceof NotNumberException) {
alert("not a number");
}
catch (e if e instanceof NotPositiveNumberException) {
alert("not a positive number");
}
re.Match
objects have a number of methods to help you with this:
>>> m = re.search("is", String)
>>> m.span()
(2, 4)
>>> m.start()
2
>>> m.end()
4
I guess it would work to use reflection to get whatever property you want to sort on:
IEnumerable<T> myEnumerables
var query=from enumerable in myenumerables
where some criteria
orderby GetPropertyValue(enumerable,"SomeProperty")
select enumerable
private static object GetPropertyValue(object obj, string property)
{
System.Reflection.PropertyInfo propertyInfo=obj.GetType().GetProperty(property);
return propertyInfo.GetValue(obj, null);
}
Note that using reflection is considerably slower than accessing the property directly, so the performance would have to be investigated.
On Windows, Chrome might be installed in your AppData folder:
"C:\Users\\AppData\Local\Google\Chrome\Application"
Before you execute the command, make sure all of your Chrome windows are closed and not otherwise running. Or, the command line param would not be effective.
chrome.exe --allow-file-access-from-files
Example for Windows (no extra dependencies and error handling)
const path = require('path');
const fs = require('fs');
let dir = "C:\\temp\\dir1\\dir2\\dir3";
function createDirRecursively(dir) {
if (!fs.existsSync(dir)) {
createDirRecursively(path.join(dir, ".."));
fs.mkdirSync(dir);
}
}
createDirRecursively(dir); //creates dir1\dir2\dir3 in C:\temp
Well, one way is to compile it as x64 with VS2008
This runs as you would expect:
int normalInt = 5;
unsigned long long int num=285212672;
printf(
"My number is %d bytes wide and its value is %ul.
A normal number is %d \n",
sizeof(num),
num,
normalInt);
For 32 bit code, we need to use the correct __int64 format specifier %I64u. So it becomes.
int normalInt = 5;
unsigned __int64 num=285212672;
printf(
"My number is %d bytes wide and its value is %I64u.
A normal number is %d",
sizeof(num),
num, normalInt);
This code works for both 32 and 64 bit VS compiler.
All the major color codes are given at https://www.siafoo.net/snippet/88
In the documentation of the version 4.11.x, says: ` "This method is like _.sortBy except that it allows specifying the sort orders of the iteratees to sort by. If orders is unspecified, all values are sorted in ascending order. Otherwise, specify an order of "desc" for descending or "asc" for ascending sort order of corresponding values." (source https://lodash.com/docs/4.17.10#orderBy)
let sorted = _.orderBy(this.items, ['fieldFoo', 'fieldBar'], ['asc', 'desc'])
A good plugin that I have used before is DataTables.
With Java 7, it's as simple as:
final String EoL = System.getProperty("line.separator");
List<String> lines = Files.readAllLines(Paths.get(fileName),
Charset.defaultCharset());
StringBuilder sb = new StringBuilder();
for (String line : lines) {
sb.append(line).append(EoL);
}
final String content = sb.toString();
However, it does havea few minor caveats (like handling files that does not fit into the memory).
I would suggest taking a look on corresponding section in the official Java tutorial (that's also the case if you have a prior Java).
As others pointed out, you might find sime 3rd party libraries useful (like Apache commons I/O or Guava).
The linked list holds operations on the shared data structure.
For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).
In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.
In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.
Arrays.toString() can be used to convert String Array to String. The extra characters can be removed by using Regex expressions or simply by using replace method.
Arrays.toString(strArray).replace(",", "").replace("[", "").replace("]", "");
Java 8 has introduced new method for String join public static String join(CharSequence delimiter, CharSequence... elements)
String.join("", strArray);
This answer should be enough to get you set up to follow this tutorial on Building a functional search component with MongoDB, Elasticsearch, and AngularJS.
If you're looking to use faceted search with data from an API then Matthiasn's BirdWatch Repo is something you might want to look at.
So here's how you can setup a single node Elasticsearch "cluster" to index MongoDB for use in a NodeJS, Express app on a fresh EC2 Ubuntu 14.04 instance.
Make sure everything is up to date.
sudo apt-get update
Install NodeJS.
sudo apt-get install nodejs
sudo apt-get install npm
Install MongoDB - These steps are straight from MongoDB docs. Choose whatever version you're comfortable with. I'm sticking with v2.4.9 because it seems to be the most recent version MongoDB-River supports without issues.
Import the MongoDB public GPG Key.
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
Update your sources list.
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
Get the 10gen package.
sudo apt-get install mongodb-10gen
Then pick your version if you don't want the most recent. If you are setting your environment up on a windows 7 or 8 machine stay away from v2.6 until they work some bugs out with running it as a service.
apt-get install mongodb-10gen=2.4.9
Prevent the version of your MongoDB installation being bumped up when you update.
echo "mongodb-10gen hold" | sudo dpkg --set-selections
Start the MongoDB service.
sudo service mongodb start
Your database files default to /var/lib/mongo and your log files to /var/log/mongo.
Create a database through the mongo shell and push some dummy data into it.
mongo YOUR_DATABASE_NAME
db.createCollection(YOUR_COLLECTION_NAME)
for (var i = 1; i <= 25; i++) db.YOUR_COLLECTION_NAME.insert( { x : i } )
Now to Convert the standalone MongoDB into a Replica Set.
First Shutdown the process.
mongo YOUR_DATABASE_NAME
use admin
db.shutdownServer()
Now we're running MongoDB as a service, so we don't pass in the "--replSet rs0" option in the command line argument when we restart the mongod process. Instead, we put it in the mongod.conf file.
vi /etc/mongod.conf
Add these lines, subbing for your db and log paths.
replSet=rs0
dbpath=YOUR_PATH_TO_DATA/DB
logpath=YOUR_PATH_TO_LOG/MONGO.LOG
Now open up the mongo shell again to initialize the replica set.
mongo DATABASE_NAME
config = { "_id" : "rs0", "members" : [ { "_id" : 0, "host" : "127.0.0.1:27017" } ] }
rs.initiate(config)
rs.slaveOk() // allows read operations to run on secondary members.
Now install Elasticsearch. I'm just following this helpful Gist.
Make sure Java is installed.
sudo apt-get install openjdk-7-jre-headless -y
Stick with v1.1.x for now until the Mongo-River plugin bug gets fixed in v1.2.1.
wget https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.1.1.deb
sudo dpkg -i elasticsearch-1.1.1.deb
curl -L http://github.com/elasticsearch/elasticsearch-servicewrapper/tarball/master | tar -xz
sudo mv *servicewrapper*/service /usr/local/share/elasticsearch/bin/
sudo rm -Rf *servicewrapper*
sudo /usr/local/share/elasticsearch/bin/service/elasticsearch install
sudo ln -s `readlink -f /usr/local/share/elasticsearch/bin/service/elasticsearch` /usr/local/bin/rcelasticsearch
Make sure /etc/elasticsearch/elasticsearch.yml has the following config options enabled if you're only developing on a single node for now:
cluster.name: "MY_CLUSTER_NAME"
node.local: true
Start the Elasticsearch service.
sudo service elasticsearch start
Verify it's working.
curl http://localhost:9200
If you see something like this then you're good.
{
"status" : 200,
"name" : "Chi Demon",
"version" : {
"number" : "1.1.2",
"build_hash" : "e511f7b28b77c4d99175905fac65bffbf4c80cf7",
"build_timestamp" : "2014-05-22T12:27:39Z",
"build_snapshot" : false,
"lucene_version" : "4.7"
},
"tagline" : "You Know, for Search"
}
Now install the Elasticsearch plugins so it can play with MongoDB.
bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb/1.6.0
bin/plugin --install elasticsearch/elasticsearch-mapper-attachments/1.6.0
These two plugins aren't necessary but they're good for testing queries and visualizing changes to your indexes.
bin/plugin --install mobz/elasticsearch-head
bin/plugin --install lukas-vlcek/bigdesk
Restart Elasticsearch.
sudo service elasticsearch restart
Finally index a collection from MongoDB.
curl -XPUT localhost:9200/_river/DATABASE_NAME/_meta -d '{
"type": "mongodb",
"mongodb": {
"servers": [
{ "host": "127.0.0.1", "port": 27017 }
],
"db": "DATABASE_NAME",
"collection": "ACTUAL_COLLECTION_NAME",
"options": { "secondary_read_preference": true },
"gridfs": false
},
"index": {
"name": "ARBITRARY INDEX NAME",
"type": "ARBITRARY TYPE NAME"
}
}'
Check that your index is in Elasticsearch
curl -XGET http://localhost:9200/_aliases
Check your cluster health.
curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'
It's probably yellow with some unassigned shards. We have to tell Elasticsearch what we want to work with.
curl -XPUT 'localhost:9200/_settings' -d '{ "index" : { "number_of_replicas" : 0 } }'
Check cluster health again. It should be green now.
curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'
Go play.
One of the easiest ways is:
$my_latitude = "";
$my_longitude = "";
$her_latitude = "";
$her_longitude = "";
$distance = round((((acos(sin(($my_latitude*pi()/180)) * sin(($her_latitude*pi()/180))+cos(($my_latitude*pi()/180)) * cos(($her_latitude*pi()/180)) * cos((($my_longitude- $her_longitude)*pi()/180))))*180/pi())*60*1.1515*1.609344), 2);
echo $distance;
It will round off up to 2 decimal points.
To understand why we need constraints, you must first understand the value of data integrity.
Data Integrity refers to the validity of data. Are your data valid? Are your data representing what you have designed them to?
What weird questions I ask you might think, but sadly enough all too often, databases are filled with garbage data, invalid references to rows in other tables, that are long gone... and values that doesn't mean anything to the business logic of your solution any longer.
All this garbage is not alone prone to reduce your performance, but is also a time-bomb under your application logic that eventually will retreive data that it is not designed to understand.
Constraints are rules you create at design-time that protect your data from becoming corrupt. It is essential for the long time survival of your heart child of a database solution. Without constraints your solution will definitely decay with time and heavy usage.
You have to acknowledge that designing your database design is only the birth of your solution. Here after it must live for (hopefully) a long time, and endure all kinds of (strange) behaviour by its end-users (ie. client applications). But this design-phase in development is crucial for the long-time success of your solution! Respect it, and pay it the time and attention it requires.
A wise man once said: "Data must protect itself!". And this is what constraints do. It is rules that keep the data in your database as valid as possible.
There are many ways of doing this, but basically they boil down to:
sys.check_constraints
view in the AdventureWorks sample databaseAs I've hinted here, it takes some thorough considerations to construct the best and most defensive constraint approach for your database design. You first need to know the possibilities and limitations of the different constraint types above. Further reading could include:
FOREIGN KEY Constraints - Microsoft
Foreign key constraint - w3schools
Good luck! ;)
We can extend jQuery to make shortcuts for PUT and DELETE:
jQuery.each( [ "put", "delete" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
and now you can use:
$.put('http://stackoverflow.com/posts/22786755/edit', {text:'new text'}, function(result){
console.log(result);
})
copy from here
regular expression starts with number->'^[0-9]'
Pattern pattern = Pattern.compile('^[0-9]');
Matcher matcher = pattern.matcher(String);
if(matcher.find()){
System.out.println("true");
}
Add a "shebang" at the top of your file:
#!/bin/bash
And make your file executable (chmod +x script.sh
).
Finally, modify your path to add the directory where your script is located:
export PATH=$PATH:/appropriate/directory
(typically, you want $HOME/bin
for storing your own scripts)
Use the CREATE TABLE SELECT syntax.
http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html
CREATE TABLE new_tbl SELECT * FROM orig_tbl;
If you don't care about supporting old browsers, you can use :not()
to exclude that element:
.parent:hover span:not(:hover) {
border: 10px solid red;
}
Demo: http://jsfiddle.net/vz9A9/1/
If you do want to support them, the I guess you'll have to either use JavaScript or override the CSS properties again:
.parent span:hover {
border: 10px solid green;
}
i ran mvn generate-resources and then marked the /target/generated-resources folder as "sources" (Project Structure -> Project Settings -> Modules -> Select /target/generated-resources -> Click on blue "Sources" icon.
Another way to effectively do this is:
git fetch
git branch -d branchB
git branch -t branchB origin/branchB
Because it's a lower case -d
, it will only delete it if the data will still exist somewhere. It's similar to @kkoehne's answer except it doesn't force. Because of the -t
it will set up the remote again.
I had a slightly different need than OP, which was to create a new feature branch off develop
(or master
), after merging a pull request. That can be accomplished in a one-liner without force, but it doesn't update the local develop
branch. It's just a matter of checking out a new branch and having it be based off origin/develop
:
git checkout -b new-feature origin/develop
Hide scroll bar, but while still being able to scroll using CSS
To hide the scrollbar use -webkit- because it is supported by major browsers (Google Chrome, Safari or newer versions of Opera). There are many other options for the other browsers which are listed below:
-webkit- (Chrome, Safari, newer versions of Opera):
.element::-webkit-scrollbar { width: 0 !important }
-moz- (Firefox):
.element { overflow: -moz-scrollbars-none; }
-ms- (Internet Explorer +10):
.element { -ms-overflow-style: none; }
ref: https://www.geeksforgeeks.org/hide-scroll-bar-but-while-still-being-able-to-scroll-using-css/
It looks like you might have inserted an extra +
at the beginning of each line, which R is interpreting as a unary operator (like -
interpreted as negation, rather than subtraction). I think what will work is
ggplot(combined.data, aes(x = region, y = expression, fill = species)) +
geom_boxplot() +
scale_fill_manual(values = c("yellow", "orange")) +
ggtitle("Expression comparisons for ACTB") +
theme(axis.text.x = element_text(angle=90, face="bold", colour="black"))
Perhaps you copy and pasted from the output of an R console? The console uses +
at the start of the line when the input is incomplete.
In addition to what the other answers have said, some databases and systems may require a primary to be present. One situation comes to mind; when using enterprise replication with Informix a PK must be present for a table to participate in replication.
eldNew <- eld[-14,]
See ?"["
for a start ...
For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.
(emphasis added)
edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?
edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame
...
Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame
You asked: 'Are there any applicable differences between dict.items() and dict.iteritems()'
This may help (for Python 2.x):
>>> d={1:'one',2:'two',3:'three'}
>>> type(d.items())
<type 'list'>
>>> type(d.iteritems())
<type 'dictionary-itemiterator'>
You can see that d.items()
returns a list of tuples of the key, value pairs and d.iteritems()
returns a dictionary-itemiterator.
As a list, d.items() is slice-able:
>>> l1=d.items()[0]
>>> l1
(1, 'one') # an unordered value!
But would not have an __iter__
method:
>>> next(d.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list object is not an iterator
As an iterator, d.iteritems() is not slice-able:
>>> i1=d.iteritems()[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dictionary-itemiterator' object is not subscriptable
But does have __iter__
:
>>> next(d.iteritems())
(1, 'one') # an unordered value!
So the items themselves are same -- the container delivering the items are different. One is a list, the other an iterator (depending on the Python version...)
So the applicable differences between dict.items() and dict.iteritems() are the same as the applicable differences between a list and an iterator.
Like all of us, you are another victim of asynchronous I/O. With asynchronous calls, if you loop around a lot of files, Node.js will start to open a file descriptor for each file to read and then will wait for action until you close it.
File descriptor remains open until resource is available on your server to read it. Even if your files are small and reading or updating is fast, it takes some time, but in the same time your loop don't stop to open new files descriptor. So if you have too many files, the limit will be soon reached and you get a beautiful EMFILE.
There is one solution, creating a queue to avoid this effect.
Thanks to people who wrote Async, there is a very useful function for that. There is a method called Async.queue, you create a new queue with a limit and then add filenames to the queue.
Note: If you have to open many files, it would be a good idea to store which files are currently open and don't reopen them infinitely.
const fs = require('fs')
const async = require("async")
var q = async.queue(function(task, callback) {
console.log(task.filename);
fs.readFile(task.filename,"utf-8",function (err, data_read) {
callback(err,task.filename,data_read);
}
);
}, 4);
var files = [1,2,3,4,5,6,7,8,9,10]
for (var file in files) {
q.push({filename:file+".txt"}, function (err,filename,res) {
console.log(filename + " read");
});
}
You can see that each file is added to the queue (console.log filename), but only when the current queue is under the limit you set previously.
async.queue get information about availability of the queue through a callback, this callback is called only when data file is read and any action you have to do is achieved. (see fileRead method)
So you cannot be overwhelmed by files descriptor.
> node ./queue.js
0.txt
1.txt
2.txt
0.txt read
3.txt
3.txt read
4.txt
2.txt read
5.txt
4.txt read
6.txt
5.txt read
7.txt
1.txt read (biggest file than other)
8.txt
6.txt read
9.txt
7.txt read
8.txt read
9.txt read
I solved this problem by doing these:
Right click on your project.
Click on Team
Click Refresh/Cleaup
I prefer using the ggfortify
library. It is a ggplot2
wrapper that recognizes the type of object inside the autoplot function and chooses the best ggplot methods to plot. At least I don't have to remember the syntax of ggplot2.
library(ggfortify)
ts1 <- 1:100
ts2 <- 1:100*0.8
autoplot(ts( cbind(ts1, ts2) , start = c(2010,5), frequency = 12 ),
facets = FALSE)
A cookie is basically just an item in a dictionary. Each item has a key and a value. For authentication, the key could be something like 'username' and the value would be the username. Each time you make a request to a website, your browser will include the cookies in the request, and the host server will check the cookies. So authentication can be done automatically like that.
To set a cookie, you just have to add it to the response the server sends back after requests. The browser will then add the cookie upon receiving the response.
There are different options you can configure for the cookie server side, like expiration times or encryption. An encrypted cookie is often referred to as a signed cookie. Basically the server encrypts the key and value in the dictionary item, so only the server can make use of the information. So then cookie would be secure.
A browser will save the cookies set by the server. In the HTTP header of every request the browser makes to that server, it will add the cookies. It will only add cookies for the domains that set them. Example.com can set a cookie and also add options in the HTTP header for the browsers to send the cookie back to subdomains, like sub.example.com. It would be unacceptable for a browser to ever sends cookies to a different domain.
what i feel like we could use:
import os
import signal
import subprocess
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
os.killpg(os.getpgid(pro.pid), signal.SIGINT)
this will not kill all your task but the process with the p.pid
If you're looking for "update if exists else create" use case, please refer to @Zags excellent answer
Django already has a get_or_create
, https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create
For you it could be :
id = 'some identifier'
person, created = Person.objects.get_or_create(identifier=id)
if created:
# means you have created a new person
else:
# person just refers to the existing one
I faced the same problem. Though I am a little bit backdated developer (Still using windows to develop :P)
To solve this issue on windows :
STEP 1: Install jdk 8 if it wasn't installed (jdk 9 or 11 doesn't work but you may have them installed for using in other dev uses).
Very simple using Chocolatey:
choco install jdk8
(If installed using Chocolatey, skip steps 2 and 3)
STEP 2: Go to the Environment variables settings and set JAVA_HOME TO jdk 8's installation directory.
STEP 3: Go to path variable and add bin directory of jdk 8 and move it to top.
STEP 4: Close any open terminal sessions and restart a new session
OPTIONAL STEP 5: Depending on your objective in the terminal run (may need to add sdkmanager to path or just navigate to the directory):
sdkmanager --update
That's all! :O Enjoy fluttering! :D
As the error information said first please try to increase the timeout value in the both the client side and service side as following:
<basicHttpBinding>
<binding name="basicHttpBinding_ACRMS" maxBufferSize="2147483647"
maxReceivedMessageSize="2147483647"
openTimeout="00:20:00"
receiveTimeout="00:20:00" closeTimeout="00:20:00"
sendTimeout="00:20:00">
<readerQuotas maxDepth="32" maxStringContentLength="2097152"
maxArrayLength="2097152" maxBytesPerRead="4006" maxNameTableCharCount="16384" />
</binding>
Then please do not forget to apply this binding configuration to the endpoint by doing the following:
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="basicHttpBinding_ACRMS"
contract="MonitorRAM.IService1" />
If the above can not help, it will be better if you can try to upload your main project here, then I want to have a test in my side.
I am also no expert in this but I made it work by setting the all_proxy
variable in the ~/.bashrc file. To open ~/.bashrc
file and edit it from a terminal run following commands,
gedit ~/.bashrc &
Add following at the end of file,
export all_proxy="http://x.y.z.w:port"
Then either open a new terminal or run following in the same terminal,
source ~/.bashrc
Just setting http_proxy
and https_proxy
variables aren't enough for simple usage pip install somepackage
. Though somehow sudo -E pip install somepackage
works, but this have given me some problem in case I am using a local installation of Anaconda in my users' folder.
P.S. - I am using Ubuntu 16.04.
To know when a table view finishes loading its content, we first need to have a basic understanding of how the views are put on screen.
In the life cycle of an app, there are 4 key moments :
The 2 and 3 times are totally separated. Why ? For performance reasons, we don't want to perform all the computations (done at 3) each time a modification is done.
So, I think you are facing a case like this :
tableView.reloadData()
tableView.visibleCells.count // wrong count oO
What’s wrong here?
A table view reloads its content lazily. Actually, if you call reloadData
multiple times it won’t create performance issues. The table view only recomputes its content size based on its delegate implementation and waits the moment 3 to loads its cells. This time is called a layout pass.
Okay, how to get involved in the layout pass?
During the layout pass, the app computes all the frames of the view hierarchy. To get involved, you can override the dedicated methods layoutSubviews
, updateLayoutConstraints
etc in a UIView
subclass and the equivalent methods in a view controller subclass.
That’s exactly what a table view does. It overrides layoutSubviews
and based on your delegate implementation adds or removes cells. It calls cellForRow
right before adding and laying out a new cell, willDisplay
right after. If you called reloadData
or just added the table view to the hierarchy, the tables view adds as many cells as necessary to fill its frame at this key moment.
Alright, but now, how to know when a tables view has finished reloading its content?
We can rephrase this question: how to know when a table view has finished laying out its subviews?
• The easiest way is to get into the layout of the table view :
class MyTableView: UITableView {
func layoutSubviews() {
super.layoutSubviews()
// the displayed cells are loaded
}
}
Note that this method is called many times in the life cycle of the table view. Because of the scroll and the dequeue behavior of the table view, cells are modified, removed and added often. But it works, right after the super.layoutSubviews()
, cells are loaded. This solution is equivalent to wait the willDisplay
event of the last index path. This event is called during the execution of layoutSubviews
of the table view when a cell is added.
• Another way is to be notified when the app finishes a layout pass.
As described in the documentation, you can use an option of the UIView.animate(withDuration:completion)
:
tableView.reloadData()
UIView.animate(withDuration: 0) {
// layout done
}
This solution works but the screen will refresh once between the time the layout is done and the time the block is executed. This is equivalent to the DispatchMain.async
solution but specified.
• Alternatively, I would prefer to force the layout of the table view
There is a dedicated method to force any view to compute immediately its subview frames layoutIfNeeded
:
tableView.reloadData()
table.layoutIfNeeded()
// layout done
Be careful however, doing so will remove the lazy loading used by the system. Calling those methods repeatedly could create performance issues. Make sure that they won’t be called before the frame of the table view is computed, otherwise the table view will be loaded again and you won’t be notified.
I think there is no perfect solution. Subclassing classes could lead to trubles. A layout pass starts from the top and goes to the bottom so it’s not easy to get notified when all the layout is done. And layoutIfNeeded()
could create performance issues etc.
Image.fromarray -> returns an image object
from PIL import Image
import numpy as np
PIL_image = Image.fromarray(np.uint8(numpy_image)).convert('RGB')
PIL_image = Image.fromarray(numpy_image.astype('uint8'), 'RGB')
In case someone struggling with the recaptcha of contact form 7 (wordpress) here is a solution working for me
.wpcf7-recaptcha{
clear: both;
float: left;
}
.wpcf7-recaptcha{
margin-right: 6px;
width: 206px;
height: 65px;
overflow: hidden;
border-right: 1px solid #D3D3D3;
}
.wpcf7-recaptcha iframe{
padding-bottom: 15px;
border-bottom: 1px solid #D3D3D3;
background: #F9F9F9;
border-left: 1px solid #d3d3d3;
}
In my case I have 3 params, one of them is string (mensaje):
exec("C:\wamp\bin\php\php5.5.12\php.exe C:/test/N/trunk/api/v1/Process.php $idTest2 $idTest3 \"$mensaje\" >> c:/log.log &");
In my Process.php I have this code:
if (!isset($argv[1]) || !isset($argv[2]) || !isset($argv[3]))
{
die("Error.");
}
$idCurso = $argv[1];
$idDestino = $argv[2];
$mensaje = $argv[3];
You could try using the with binding that knockout offers: http://knockoutjs.com/documentation/with-binding.html The idea is to use apply bindings once, and whenever your data changes, just update your model.
Lets say you have a top level view model storeViewModel, your cart represented by cartViewModel, and a list of items in that cart - say cartItemsViewModel.
You would bind the top level model - the storeViewModel to the whole page. Then, you could separate the parts of your page that are responsible for cart or cart items.
Lets assume that the cartItemsViewModel has the following structure:
var actualCartItemsModel = { CartItems: [
{ ItemName: "FirstItem", Price: 12 },
{ ItemName: "SecondItem", Price: 10 }
] }
The cartItemsViewModel can be empty at the beginning.
The steps would look like this:
Define bindings in html. Separate the cartItemsViewModel binding.
<div data-bind="with: cartItemsViewModel">
<div data-bind="foreach: CartItems">
<span data-bind="text: ItemName"></span>
<span data-bind="text: Price"></span>
</div>
</div>
The store model comes from your server (or is created in any other way).
var storeViewModel = ko.mapping.fromJS(modelFromServer)
Define empty models on your top level view model. Then a structure of that model can be updated with actual data.
storeViewModel.cartItemsViewModel = ko.observable();
storeViewModel.cartViewModel = ko.observable();
Bind the top level view model.
ko.applyBindings(storeViewModel);
When the cartItemsViewModel object is available then assign it to the previously defined placeholder.
storeViewModel.cartItemsViewModel(actualCartItemsModel);
If you would like to clear the cart items:
storeViewModel.cartItemsViewModel(null);
Knockout will take care of html - i.e. it will appear when model is not empty and the contents of div (the one with the "with binding") will disappear.
The WITH syntax appears to be valid in an inline view, e.g.
UPDATE (WITH comp AS ...
SELECT SomeColumn, ComputedValue FROM t INNER JOIN comp ...)
SET SomeColumn=ComputedValue;
But in the quick tests I did this always failed with ORA-01732: data manipulation operation not legal on this view
, although it succeeded if I rewrote to eliminate the WITH clause. So the refactoring may interfere with Oracle's ability to guarantee key-preservation.
You should be able to use a MERGE, though. Using the simple example you've posted this doesn't even require a WITH clause:
MERGE INTO mytable t
USING (select *, 42 as ComputedValue from mytable where id = 1) comp
ON (t.id = comp.id)
WHEN MATCHED THEN UPDATE SET SomeColumn=ComputedValue;
But I understand you have a more complex subquery you want to factor out. I think that you will be able to make the subquery in the USING
clause arbitrarily complex, incorporating multiple WITH
clauses.