Alternatively, constructing a JMX console yourself doesn't need to be hard. Just plug in Jolokia and create a web page getting the attributes that you're interested in. Admittedly, it doesn't allow you to do trend analysis, but it does allow you to construct something that is really geared towards your purpose.
I constructed something in just a few lines: http://nxt.flotsam.nl/ears-and-eyes.html
Make a batch file "Pc.bat" as, typeperf -sc 1 "\mukit\processor(_Total)\%% Processor Time"
You can use the class MProcess,
/* *Md. Mukit Hasan *CSE-JU,35 **/ import java.io.*;public class MProcessor {
public MProcessor() { String s; try { Process ps = Runtime.getRuntime().exec("Pc.bat"); BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); while((s = br.readLine()) != null) { System.out.println(s); } } catch( Exception ex ) { System.out.println(ex.toString()); } }
}
Then after some string manipulation, you get the CPU use. You can use the same process for other tasks.
--Mukit Hasan
I used Zack Argyle's suggestion above to get this, which I find very elegant:
CSS:
.active {
background-position: 0 -46px !important;
}
HTML:
<button ng-click="satisfaction = 'VeryHappy'" ng-class="{active:satisfaction == 'VeryHappy'}">
<img src="images/VeryHappy.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'Happy'" ng-class="{active:satisfaction == 'Happy'}">
<img src="images/Happy.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'Indifferent'" ng-class="{active:satisfaction == 'Indifferent'}">
<img src="images/Indifferent.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'Unhappy'" ng-class="{active:satisfaction == 'Unhappy'}">
<img src="images/Unhappy.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'VeryUnhappy'" ng-class="{active:satisfaction == 'VeryUnhappy'}">
<img src="images/VeryUnhappy.png" style="height:24px;" />
</button>
Using
generates a try / finally around the object being allocated and calls Dispose()
for you.
It saves you the hassle of manually creating the try / finally block and calling Dispose()
If you want to use straight PowerShell check out the below code.
$content = Get-Content C:\Users\You\Documents\test.txt
foreach ($line in $content)
{
Write-Host $line
}
Phone Number will be a country code followed by WhatsApp mobile number without any symbol. Please refer below code.
<a href="https://api.whatsapp.com/send?phone=19998887878&text=Hi%20There!">WhatsApp Now</a>
Since I was in a widget and not in an activity I did:
`getRootView().clearFocus();
Death is a simple library that uses channels and a wait group to wait for shutdown signals. Once the signal has been received it will then call a close method on all of your structs that you want to cleanup.
To get all the columns in your result you need to place something as:
SELECT distinct a, Table.* FROM Table
it will place a as the first column and the rest will be ALL of the columns in the same order as your definition. This is, column a will be repeated.
var clickButton = document.getElementById("<%= btnClearSession.ClientID %>");
clickButton.click();
That solution works for me, but remember it wont work if your asp button has
Visible="False"
To hide button that should be triggered with that script you should hide it with <div hidden></div>
I use do-while loops all the time when reading in files. I work with a lot of text files that include comments in the header:
# some comments
# some more comments
column1 column2
1.234 5.678
9.012 3.456
... ...
i'll use a do-while loop to read up to the "column1 column2" line so that I can look for the column of interest. Here's the pseudocode:
do {
line = read_line();
} while ( line[0] == '#');
/* parse line */
Then I'll do a while loop to read through the rest of the file.
You can creat the table you want, save it as an image and then use an image map to creat the link (this way you can put the coords of the hole td to make it in to a link).
You should be able to replace it with a preg that removes all newlines and carriage returns. The code is:
preg_replace( "/\r|\n/", "", $yourString );
Even though the \n
characters are not appearing, if you are getting carriage returns there is an invisible character there. The preg replace should grab and fix those.
You can do this simply by using pandas drop duplicates function
df.drop_duplicates(['A','B'],keep= 'last')
opencv has changed some functions and moved them to their opencv_contrib repo so you have to call the mentioned method with:
recognizer = cv2.face.createLBPHFaceRecognizer()
Note: You can see this issue about missing docs. Try using help function help(cv2.face.createLBPHFaceRecognizer)
for more details.
this error messages means that CABundle is not given by (-CAfile ...) OR the CABundle file is not closed by a self-signed root certificate.
Don't worry. The connection to server will work even you get theis message from openssl s_client ... (assumed you dont take other mistake too)
$image="img_name.jpg";
$pdf =new FPDF();
$pdf-> AddPage();
$pdf-> SetFont("Arial","B",10);
$pdf-> Image('profileimage/'.$image,100,15,35,35);
Two ways.
i. You can put it in ApplicationController and add the filters in the controller
class ApplicationController < ActionController::Base def filter_method end end class FirstController < ApplicationController before_filter :filter_method end class SecondController < ApplicationController before_filter :filter_method end
But the problem here is that this method will be added to all the controllers since all of them extend from application controller
ii. Create a parent controller and define it there
class ParentController < ApplicationController def filter_method end end class FirstController < ParentController before_filter :filter_method end class SecondController < ParentController before_filter :filter_method end
I have named it as parent controller but you can come up with a name that fits your situation properly.
You can also define the filter method in a module and include it in the controllers where you need the filter
i found this help:
git checkout --orphan empty.branch.name
git rm --cached -r .
echo "init empty branch" > README.md
git add README.md
git commit -m "init empty branch"
The ActionBar
usually exists along Fragments
so from the Activity
you can hide it
getActionBar().hide();
getActionBar().show();
and from the Fragment
you can do it
getActivity().getActionBar().hide();
getActivity().getActionBar().show();
Just putting an r in front works well.
eg:
white = pd.read_csv(r"C:\Users\hydro\a.csv")
Since the OP has mentioned he does not have access to the base class inside of which exists a HashMap - I am afraid there are very few options available.
One (painfully slow and resource intensive) way of performing a deep copy of an object in Java is to abuse the 'Serializable' interface which many classes either intentionally - or unintentionally extend - and then utilise this to serialise your class to ByteStream. Upon de-serialisation you will have a deep copy of the object in question.
A guide for this can be found here: https://www.avajava.com/tutorials/lessons/how-do-i-perform-a-deep-clone-using-serializable.html
SELECT @LastChangeDate = GETDATE()
For your use case, it may be easier to utilize a while
loop.
t1 = [137, 42]
t2 = ["Hello", "world"]
i = 0
j = 0
while i < len(t1) and j < len(t2):
print t1[i], t2[j]
i += 1
j += 1
# 137 Hello
# 42 world
As a caveat, this approach will truncate to the length of your shortest list.
The syntax of Array.splice
is:
yourArray.splice(index, howmany, element1, /*.....,*/ elementX);
Where:
This means that splice()
can be used to remove elements, add elements, or replace elements in an array, depending on the arguments you pass.
Note that it returns an array of the removed elements.
Something nice and generic would be:
Array.prototype.move = function (from, to) {
this.splice(to, 0, this.splice(from, 1)[0]);
};
Then just use:
var ar = [1,2,3,4,5];
ar.move(0,3);
alert(ar) // 2,3,4,1,5
Diagram:
select regexp_replace(field, E'[\\n\\r]+', ' ', 'g' )
read the manual http://www.postgresql.org/docs/current/static/functions-matching.html
The source of your error, however, is that you need to place the full JSON string in quotes. The following will fix your sample:
<!doctype HTML>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var cur_ques_details ='{"ques_id":"15","ques_title":"jlkjlkjlkjljl"}';
var ques_list = JSON.parse(cur_ques_details);
document.write(ques_list['ques_title']);
</script>
</body>
</html>
As the other respondents have mentioned, the object is already parsed into a JS object so you don't need to parse it. To demonstrate how to accomplish the same thing without parsing, you can do the following:
<!doctype HTML>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var cur_ques_details ={"ques_id":"15","ques_title":"jlkjlkjlkjljl"};
document.write(cur_ques_details.ques_title);
</script>
</body>
</html>
Express 3.x no longer support partial. According to the post ejs 'partial is not defined', you can use "include" keyword in EJS to replace the removed partial functionality.
try this function
function summary($str, $limit=100, $strip = false) {
$str = ($strip == true)?strip_tags($str):$str;
if (strlen ($str) > $limit) {
$str = substr ($str, 0, $limit - 3);
return (substr ($str, 0, strrpos ($str, ' ')).'...');
}
return trim($str);
}
ColumnNames
is a property of type List<String>
so when you are setting up you need to pass a List<String>
in the Returns
call as an argument (or a func which return a List<String>
)
But with this line you are trying to return just a string
input.SetupGet(x => x.ColumnNames).Returns(temp[0]);
which is causing the exception.
Change it to return whole list:
input.SetupGet(x => x.ColumnNames).Returns(temp);
In addition to previous answers, I recommend to first calculate the ratio in the exponent, then taking the square:
def gaussian(x,x0,sigma):
return np.exp(-np.power((x - x0)/sigma, 2.)/2.)
That way, you can also calculate the gaussian of very small or very large numbers:
In: gaussian(1e-12,5e-12,3e-12)
Out: 0.64118038842995462
The shortest way to write a selector that accesses that specific div is to simply use
[role=main] {
/* CSS goes here */
}
The previous answers are not wrong, but they rely on you using either a div or using the specific id. With this selector, you'll be able to have all kinds of crazy markup and it would still work and you avoid problems with specificity.
[role=main] {_x000D_
background: rgba(48, 96, 144, 0.2);_x000D_
}_x000D_
div,_x000D_
span {_x000D_
padding: 5px;_x000D_
margin: 5px;_x000D_
display: inline-block;_x000D_
}
_x000D_
<div id="content" role="main">_x000D_
<span role="main">Hello</span>_x000D_
</div>
_x000D_
Using map or other similar solution do not help to clone deeply an array of object. An easier way to do this without adding a new library is using JSON.stringfy and then JSON.parse.
In your case this should work :
this.backupData = JSON.parse(JSON.stringify(genericItems));
For small objet lodash cloneDeep can be faster but for larger/deeper object json clone become faster. So in this cases you should not hesitate to use it. check https://www.measurethat.net/Benchmarks/Show/6039/0/lodash-clonedeep-vs-json-clone-larger-object and for infos https://v8.dev/blog/cost-of-javascript-2019#json
The inconvenient is that your source object must be convertible to JSON.
Heavily influenced by Ruslan Tushov's library, I've created my own small library. Just add the script in the <head>
and it will patch setInterval
and setTimeout
with ones that use WebWorker
.
number_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
number_string = number_string.split(',')
number_string = [int(i) for i in number_string]
Another thing is that all libraries from google (e.g. support lib, CardView
and etc.) should have identical versions
In case the dictionaries are only uniquely identified by all items (ID is not available) you can use the answer using JSON. The following is an alternative that does not use JSON, and will work as long as all dictionary values are immutable
[dict(s) for s in set(frozenset(d.items()) for d in L)]
I don't like to see the {id}
part of the URLs overlap with sub-resources, as an id
could theoretically be anything and there would be ambiguity. It is mixing different concepts (identifiers and sub-resource names).
Similar issues are often seen in enum
constants or folder structures, where different concepts are mixed (for example, when you have folders Tigers
, Lions
and Cheetahs
, and then also a folder called Animals
at the same level -- this makes no sense as one is a subset of the other).
In general I think the last named part of an endpoint should be singular if it deals with a single entity at a time, and plural if it deals with a list of entities.
So endpoints that deal with a single user:
GET /user -> Not allowed, 400
GET /user/{id} -> Returns user with given id
POST /user -> Creates a new user
PUT /user/{id} -> Updates user with given id
DELETE /user/{id} -> Deletes user with given id
Then there is separate resource for doing queries on users, which generally return a list:
GET /users -> Lists all users, optionally filtered by way of parameters
GET /users/new?since=x -> Gets all users that are new since a specific time
GET /users/top?max=x -> Gets top X active users
And here some examples of a sub-resource that deals with a specific user:
GET /user/{id}/friends -> Returns a list of friends of given user
Make a friend (many to many link):
PUT /user/{id}/friend/{id} -> Befriends two users
DELETE /user/{id}/friend/{id} -> Unfriends two users
GET /user/{id}/friend/{id} -> Gets status of friendship between two users
There is never any ambiguity, and the plural or singular naming of the resource is a hint to the user what they can expect (list or object). There are no restrictions on id
s, theoretically making it possible to have a user with the id new
without overlapping with a (potential future) sub-resource name.
At a guess I'd say the directory index is set to index.html, or some variant, try:
DirectoryIndex index.html index.php
This will still give index.html priority over index.php (handy if you need to throw up a maintenance page)
Using str_replace()
to remove the dots is not overkill.
$string_number = '1.512.523,55';
// NOTE: You don't really have to use floatval() here, it's just to prove that it's a legitimate float value.
$number = floatval(str_replace(',', '.', str_replace('.', '', $string_number)));
// At this point, $number is a "natural" float.
print $number;
This is almost certainly the least CPU-intensive way you can do this, and odds are that even if you use some fancy function to do it, that this is what it does under the hood.
Your best solution is to look at the "opacity" tag of an element.
For example:
.image
{
opacity:0.4;
filter:alpha(opacity=40); /* For IE8 and earlier */
}
So in your case it should look something like :
<html><span style="opacity: 0.5;"><font color=\"black\" face=\"arial\" size=\"4\">THIS IS MY TEXT</font></html>
However don't forget the tag isn't supported in HTML5.
You should use a CSS too :)
As rcar says, you can't without losing some quality, the best you can do in c# is:
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics gr = Graphics.FromImage(newImage))
{
gr.SmoothingMode = SmoothingMode.HighQuality;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
}
1) Add any remote repositories you want to compare:
git remote add foobar git://github.com/user/foobar.git
2) Update your local copy of a remote:
git fetch foobar
Fetch won't change your working copy.
3) Compare any branch from your local repository to any remote you've added:
git diff master foobar/master
datamap = eval(input('Provide some data here: '))
means that you actually evaluate the code before you deem it to be unsafe or not. It evaluates the code as soon as the function is called. See also the dangers of eval
.
ast.literal_eval
raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.
Use ast.literal_eval
whenever you need eval
. You shouldn't usually evaluate literal Python statements.
For example, lets say we want to display only the first 10 items of an array, we could do this using the SlicePipe like so:
<ul>
<li *ngFor="let item of items | slice:0:10">
{{ item }}
</li>
</ul>
In Rails 4 all I had to do was the def change
def change
rename_table :old_table_name, :new_table_name
end
And all of my indexes were taken care of for me. I did not need to manually update the indexes by removing the old ones and adding new ones.
And it works using the change for going up or down in regards to the indexes as well.
Here is the implementation that was mentioned above:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
try
{
String passEncrypt = "my password";
byte[] saltEncrypt = "choose a better salt".getBytes();
int iterationsEncrypt = 10000;
SecretKeyFactory factoryKeyEncrypt = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp = factoryKeyEncrypt.generateSecret(new PBEKeySpec(
passEncrypt.toCharArray(), saltEncrypt, iterationsEncrypt,
128));
SecretKeySpec encryptKey = new SecretKeySpec(tmp.getEncoded(),
"AES");
Cipher aesCipherEncrypt = Cipher
.getInstance("AES/ECB/PKCS5Padding");
aesCipherEncrypt.init(Cipher.ENCRYPT_MODE, encryptKey);
// get the bytes
byte[] bytes = StringUtils.getBytesUtf8(toEncodeEncryptString);
// encrypt the bytes
byte[] encryptBytes = aesCipherEncrypt.doFinal(bytes);
// encode 64 the encrypted bytes
String encoded = Base64.encodeBase64URLSafeString(encryptBytes);
System.out.println("e: " + encoded);
// assume some transport happens here
// create a new string, to make sure we are not pointing to the same
// string as the one above
String encodedEncrypted = new String(encoded);
//we recreate the same salt/encrypt as if its a separate system
String passDecrypt = "my password";
byte[] saltDecrypt = "choose a better salt".getBytes();
int iterationsDecrypt = 10000;
SecretKeyFactory factoryKeyDecrypt = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp2 = factoryKeyDecrypt.generateSecret(new PBEKeySpec(passDecrypt
.toCharArray(), saltDecrypt, iterationsDecrypt, 128));
SecretKeySpec decryptKey = new SecretKeySpec(tmp2.getEncoded(), "AES");
Cipher aesCipherDecrypt = Cipher.getInstance("AES/ECB/PKCS5Padding");
aesCipherDecrypt.init(Cipher.DECRYPT_MODE, decryptKey);
//basically we reverse the process we did earlier
// get the bytes from encodedEncrypted string
byte[] e64bytes = StringUtils.getBytesUtf8(encodedEncrypted);
// decode 64, now the bytes should be encrypted
byte[] eBytes = Base64.decodeBase64(e64bytes);
// decrypt the bytes
byte[] cipherDecode = aesCipherDecrypt.doFinal(eBytes);
// to string
String decoded = StringUtils.newStringUtf8(cipherDecode);
System.out.println("d: " + decoded);
}
catch (Exception e)
{
e.printStackTrace();
}
Things to remember:
class A
has an object of class B
as a member or vice versa. Read the FAQ:
A year or so has passed since the question was asked, but I thought a substantial improvement of the answers was possible. I find this the easiest and most versatile script, because it checks whether a button has been checked, and if so, what its value is:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check radio checked and its value</title>
</head>
<body>
<form name="theFormName">
<input type="radio" name="theRadioGroupName" value="10">
<input type="radio" name="theRadioGroupName" value="20">
<input type="radio" name="theRadioGroupName" value="30">
<input type="radio" name="theRadioGroupName" value="40">
<input type="button" value="Check" onclick="getRadioValue('theRadioGroupName')">
</form>
<script>
function getRadioValue(groupName) {
var radios = theFormName.elements[groupName];
window.rdValue; // declares the global variable 'rdValue'
for (var i=0; i<radios.length; i++) {
var someRadio = radios[i];
if (someRadio.checked) {
rdValue = someRadio.value;
break;
}
else rdValue = 'noRadioChecked';
}
if (rdValue == '10') {
alert('10'); // or: console.log('10')
}
else if (rdValue == 'noRadioChecked') {
alert('no radio checked');
}
}
</script>
</body>
</html>
You can also call the function within another function, like this:
function doSomething() {
getRadioValue('theRadioGroupName');
if (rdValue == '10') {
// do something
}
else if (rdValue == 'noRadioChecked') {
// do something else
}
}
Role attribute mainly improve accessibility for people using screen readers. For several cases we use it such as accessibility, device adaptation,server-side processing, and complex data description. Know more click: https://www.w3.org/WAI/PF/HTML/wiki/RoleAttribute.
result()
is recursive in that it returns an std class object where as result_array()
just returns a pure array, so result_array()
would be choice regarding performance. There is very little difference in speed though.
I've seen this issue before with 2.7.14. Fixed it by :
In cmd, run "where python" and then "where pip". Which will show for example:
? where python
C:\Python\python.exe
? where pip
C:\Python\Scripts\pip.exe
Run pip, then it should show different pip run command options.
A Functor is a object which acts like a function.
Basically, a class which defines operator()
.
class MyFunctor
{
public:
int operator()(int x) { return x * 2;}
}
MyFunctor doubler;
int x = doubler(5);
The real advantage is that a functor can hold state.
class Matcher
{
int target;
public:
Matcher(int m) : target(m) {}
bool operator()(int x) { return x == target;}
}
Matcher Is5(5);
if (Is5(n)) // same as if (n == 5)
{ ....}
First, you need to understand the difference between window
and document
. The window
object is a top level client side object. There is nothing above the window
object. JavaScript is an object orientated language. You start with an object and apply methods to its properties or the properties of its object groups. For example, the document
object is an object of the window
object. To change the document
's background color, you'd set the document
's bgcolor
property.
window.document.bgcolor = "red"
To answer your question, There is no difference in the end result between window
and document
scrollTop
. Both will give the same output.
In general use document
mainly to register events and use window
to do things like scroll
, scrollTop
, and resize
.
Use setInterval(func, delay) to run the func
every delay
milliseconds.
setTimeout()
runs your function once after delay
milliseconds -- it does not run it repeatedly. A common strategy is to run your code with setTimeout and call setTimeout again at the end of your code.
With JPA 2.1 you should be able to do it.
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Index;
import javax.persistence.Table;
@Entity
@Table(name = "region",
indexes = {@Index(name = "my_index_name", columnList="iso_code", unique = true),
@Index(name = "my_index_name2", columnList="name", unique = false)})
public class Region{
@Column(name = "iso_code", nullable = false)
private String isoCode;
@Column(name = "name", nullable = false)
private String name;
}
Update: If you ever need to create and index with two or more columns you may use commas. For example:
@Entity
@Table(name = "company__activity",
indexes = {@Index(name = "i_company_activity", columnList = "activity_id,company_id")})
public class CompanyActivity{
I ended up adding the following method to jQuery in my script:
jQuery["postJSON"] = function( url, data, callback ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: "POST",
contentType:"application/json; charset=utf-8",
dataType: "json",
data: data,
success: callback
});
};
And to use it
$.postJSON('http://url', {data: 'goes', here: 'yey'}, function (data, status, xhr) {
alert('Nailed it!')
});
This was done by simply copying the code of "get" and "post" from the original JQuery sources and hardcoding a few parameters to force a JSON POST.
Thanks!
I have struggled with this same problem (Ubuntu 16.04, Bluefish editor, FireFox, Google Chrome.
Solution: Clear browsing data in Chrome "Settings > Advanced Settings > Clear Browsing Data", In Firefox, "Open Menu image top right tool bar 'Preferences' > Advanced ", look for this image in the menu: Cached Web Content click the button "Clear Now". Browser's cache the .css file and if it has not changed they usually won't reload it. So when you change your .css file clear this web cache and it should work unless a problem exists in your .css file. Peace, Stan
Following this resource page, if the length of x is varying, we can use:
', '.join(['%.2f']*len(x))
to create a place holder for each element from the list x
. Here is the example:
x = [1/3.0, 1/6.0, 0.678]
s = ("elements in the list are ["+', '.join(['%.2f']*len(x))+"]") % tuple(x)
print s
>>> elements in the list are [0.33, 0.17, 0.68]
if ($done)
{
header("Location: /url/to/the/other/page");
exit;
}
Try this one:
android.support.v7.app.ActionBar ab = getSupportActionBar();
ab.setTitle("This is Title");
ab.setSubtitle("This is Subtitle");
Have you tried?
df = pd.read_csv("Users/alekseinabatov/Documents/Python/FBI-CRIME11.csv")
or maybe
df = pd.read_csv('Users/alekseinabatov/Documents/Python/"FBI-CRIME11.csv"')
(If the file name has quotes)
After fetching a zillion times still added remotes didn't show up, although the blobs were in the pool. Turns out the --tags option shouldn't be given to git remote add
for whatever reason. You can manually remove it from the .git/config to make git fetch create the refs.
You can use jQuery:
$(function() {
$("form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('button[type=submit] .default').click();
return false;
} else {
return true;
}
});
});
Also, you can see the build dependencies in the file setup.cfg
I prefer:
SUBSTRING (my_column, 1, 1)
because it is Standard SQL-92 syntax and therefore more portable.
Strictly speaking, the standard version would be
SUBSTRING (my_column FROM 1 FOR 1)
The point is, transforming from one to the other, hence to any similar vendor variation, is trivial.
p.s. It was only recently pointed out to me that functions in standard SQL are deliberately contrary, by having parameters lists that are not the conventional commalists, in order to make them easily identifiable as being from the standard!
That's the vi editor. Try ESC
:q!
.
What you want is impossible.
A Date
object represents an "absolute" moment in time. You cannot "remove the time part" from it. When you print a Date
object directly with System.out.println(date)
, it will always be formatted in a default format that includes the time. There is nothing you can do to change that.
Instead of somehow trying to use class Date
for something that it was not designed for, you should look for another solution. For example, use SimpleDateFormat
to format the date in whatever format you want.
The Java date and calendar APIs are unfortunately not the most well-designed classes of the standard Java API. There's a library called Joda-Time which has a much better and more powerful API.
Joda-Time has a number of special classes to support dates, times, periods, durations, etc. If you want to work with just a date without a time, then Joda-Time's LocalDate
class would be what you'd use.
On a branch I was able to do it like this (for the last 4 commits)
git checkout my_branch
git reset --soft HEAD~4
git commit
git push --force origin my_branch
You don't have any error in either of your queries. My guess is the following:
No need to use a macro. Supposing your first string is in A1.
=RIGHT(A1, 4)
Drag this down and you will get your four last characters.
Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()
=RIGHT(TRIMSPACES(A1), 4)
Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:
=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;
protected void Button1_Click(object sender, EventArgs e)
{
//Upload and save the file
string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(excelPath);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
excel_con.Open();
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
//[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
dtExcelData.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)) });
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["dbcn"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.Table1";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("Sl", "Id");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
}
}
Copy this in web config
<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
<add name="Excel07+ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
you can also refer this link : https://athiraji.blogspot.com/2019/03/how-to-upload-excel-fle-to-database.html
I was also trying to get Debug or Trace or Console or TestContext to work in unit testing.
None of these methods would appear to work or show output in the output window:
Trace.WriteLine("test trace");
Debug.WriteLine("test debug");
TestContext.WriteLine("test context");
Console.WriteLine("test console");
(from comments) In Visual Studio 2012, there is no icon. Instead, there is a link in the test results called Output. If you click on the link, you see all of the WriteLine
.
I then noticed in my Test Results window, after running the test, next to the little success green circle, there is another icon. I doubled clicked it. It was my test results, and it included all of the types of writelines above.
You can use calendar.timegm
to convert your time to seconds since Unix epoch and time.localtime
to convert back:
import calendar
import time
time_tuple = time.strptime("2011-01-21 02:37:21", "%Y-%m-%d %H:%M:%S")
t = calendar.timegm(time_tuple)
print time.ctime(t)
Gives Fri Jan 21 05:37:21 2011
(because I'm in UTC+03:00 timezone).
Changing
RestResponse response = client.Execute(request);
to
IRestResponse response = client.Execute(request);
worked for me.
@Baxter's is mostly correct but it is missing one important Windows-specific detail.
Subversion's runtime configuration area is stored in the %APPDATA%\Subversion\
directory. The files are config
and servers
.
However, in addition to text-based configuration files, Subversion clients can use Windows Registry to store the client settings. It makes it possible to modify the settings with PowerShell in a convenient manner, and also distribute these settings to user workstations in Active Directory environment via AD Group Policy. See SVNBook | Configuration and the Windows Registry (you can find examples and a sample *.reg
file there).
An easier alternative for those who would prefer not to write all that configuration boilerplate manually...
1) Install Nerdle.AutoConfig from NuGet
2) Define your ServiceConfig type (either a concrete class or just an interface, either will do)
public interface IServiceConfiguration
{
int Port { get; }
ReportType ReportType { get; }
}
3) You'll need a type to hold the collection, e.g.
public interface IServiceCollectionConfiguration
{
IEnumerable<IServiceConfiguration> Services { get; }
}
4) Add the config section like so (note camelCase naming)
<configSections>
<section name="serviceCollection" type="Nerdle.AutoConfig.Section, Nerdle.AutoConfig"/>
</configSections>
<serviceCollection>
<services>
<service port="6996" reportType="File" />
<service port="7001" reportType="Other" />
</services>
</serviceCollection>
5) Map with AutoConfig
var services = AutoConfig.Map<IServiceCollectionConfiguration>();
Edited for clarity:
This will work to to get the value if the remote.origin.url is in the form protocol://auth_info@git_host:port/project/repo.git. If you find it doesn't work, adjust the -f5 option that is part of the first cut command.
For the example remote.origin.url of protocol://auth_info@git_host:port/project/repo.git the output created by the cut command would contain the following:
-f1: protocol: -f2: (blank) -f3: auth_info@git_host:port -f4: project -f5: repo.git
If you are having problems, look at the output of the git config --get remote.origin.url
command to see which field contains the original repository. If the remote.origin.url does not contain the .git string then omit the pipe to the second cut command.
#!/usr/bin/env bash
repoSlug="$(git config --get remote.origin.url | cut -d/ -f5 | cut -d. -f1)"
echo ${repoSlug}
If you're writing a bash script, call it by name:
#!/bin/bash
/bin/sh is not guaranteed to be bash. This caused a ton of broken scripts in Ubuntu some years ago (IIRC).
The source builtin works just fine in bash; but you might as well just use dot like Norman suggested.
AJAX requests are asynchronous. Your doSomething function is being exectued, the AJAX request is being made but it happens asynchronously; so the remainder of doSomething is executed and the value of status
is undefined when it is returned.
Effectively, your code works as follows:
function doSomething(someargums) {
return status;
}
var response = doSomething();
And then some time later, your AJAX request is completing; but it's already too late
You need to alter your code, and populate the "response" variable in the "success" callback of your AJAX request. You're going to have to delay using the response until the AJAX call has completed.
Where you previously may have had
var response = doSomething();
alert(response);
You should do:
function doSomething() {
$.ajax({
url:'action.php',
type: "POST",
data: dataString,
success: function (txtBack) {
alert(txtBack);
})
});
};
When doing recursive replacement, the path and filename need to be included:
Get-ChildItem -Recurse | ForEach { (Get-Content $_.PSPath |
ForEach {$ -creplace "old", "new"}) | Set-Content $_.PSPath }
This wil replace all "old" with "new" case-sensitive in all the files of your folders of your current directory.
You can also format the string like so:
>>> print ("{index}. {word} appears {count} times".format(index=1, word='Hello', count=42))
Which outputs
1. Hello appears 42 times.
Because the values are named, their order does not matter. Making the example below output the same as the above example.
>>> print ("{index}. {word} appears {count} times".format(count=42, index=1, word='Hello'))
Formatting string this way allows you to do this.
>>> data = {'count':42, 'index':1, 'word':'Hello'}
>>> print ("{index}. {word} appears {count} times.".format(**data))
1. Hello appears 42 times.
Consider following code
<ul id="myTask">
<li>Coding</li>
<li>Answering</li>
<li>Getting Paid</li>
</ul>
Now, here goes the difference
// Remove the myTask item when clicked.
$('#myTask').children().click(function () {
$(this).remove()
});
Now, what if we add a myTask again?
$('#myTask').append('<li>Answer this question on SO</li>');
Clicking this myTask item will not remove it from the list, since it doesn't have any event handlers bound. If instead we'd used .on
, the new item would work without any extra effort on our part. Here's how the .on version would look:
$('#myTask').on('click', 'li', function (event) {
$(event.target).remove()
});
Summary:
The difference between .on()
and .click()
would be that .click()
may not work when the DOM elements associated with the .click()
event are added dynamically at a later point while .on()
can be used in situations where the DOM elements associated with the .on()
call may be generated dynamically at a later point.
People have recommended MailChimp which is a good vendor for bulk email. If you're looking for a good vendor for transactional email, I might be able to help.
Over the past 6 months, we used four different SMTP vendors with the goal of figuring out which was the best one.
Here's a summary of what we found...
Conclusion
SendGrid was the best with Postmark coming in second place. We never saw any hesitation in send times with either of those two - in some cases we sent several hundred emails at once - and they both have the best ROI, given a solid featureset.
Seaborn's barplot returns an axis-object (not a figure). This means you can do the following:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
ax = sns.barplot(x = 'val', y = 'cat',
data = fake,
color = 'black')
ax.set(xlabel='common xlabel', ylabel='common ylabel')
plt.show()
They may look a bit different from normal HTML, but : and @ are valid chars for attribute names and all Vue.js supported browsers can parse it correctly. In addition, they do not appear in the final rendered markup. The shorthand syntax is totally optional, but you will likely appreciate it when you learn more about its usage later.
Source: official documentation.
Speaking for current (2021-2) Java versions there is still the old ISO-8859-1 function utils.Properties#load.
Allow me to quote from the official doc.
PropertyResourceBundle
PropertyResourceBundle can be constructed either from an InputStream or a Reader, which represents a property file. Constructing a PropertyResourceBundle instance from an InputStream requires that the input stream be encoded in UTF-8. By default, if a MalformedInputException or an UnmappableCharacterException occurs on reading the input stream, then the PropertyResourceBundle instance resets to the state before the exception, re-reads the input stream in ISO-8859-1, and continues reading. If the system property java.util.PropertyResourceBundle.encoding is set to either "ISO-8859-1" or "UTF-8", the input stream is solely read in that encoding, and throws the exception if it encounters an invalid sequence. If "ISO-8859-1" is specified, characters that cannot be represented in ISO-8859-1 encoding must be represented by Unicode Escapes as defined in section 3.3 of The Java™ Language Specification whereas the other constructor which takes a Reader does not have that limitation. Other encoding values are ignored for this system property. The system property is read and evaluated when initializing this class. Changing or removing the property has no effect after the initialization.
https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/PropertyResourceBundle.html
Properties#load
Reads a property list (key and element pairs) from the input byte stream. The input stream is in a simple line-oriented format as specified in load(Reader) and is assumed to use the ISO 8859-1 character encoding; that is each byte is one Latin1 character. Characters not in Latin1, and certain special characters, are represented in keys and elements using Unicode escapes as defined in section 3.3 of The Java™ Language Specification.
Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.
Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:
UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:
let counter = 0;
function handleInstantiate() {
counter++;
}
constructor(props) {
super(props);
handleInstantiate();
}
1> Add this namspace. using Newtonsoft.Json.Linq;
2> use this source code.
JObject joResponse = JObject.Parse(response);
JObject ojObject = (JObject)joResponse["response"];
JArray array= (JArray)ojObject ["chats"];
int id = Convert.ToInt32(array[0].toString());
The clean way to use mbstowcs
is to call it twice to find the length of the result:
const char * cs = <your input char*>
size_t wn = mbsrtowcs(NULL, &cs, 0, NULL);
// error if wn == size_t(-1)
wchar_t * buf = new wchar_t[wn + 1](); // value-initialize to 0 (see below)
wn = mbsrtowcs(buf, &cs, wn + 1, NULL);
// error if wn == size_t(-1)
assert(cs == NULL); // successful conversion
// result now in buf, return e.g. as std::wstring
delete[] buf;
Don't forget to call setlocale(LC_CTYPE, "");
at the beginning of your program!
The advantage over the Windows MultiByteToWideChar
is that this is entirely standard C, although on Windows you might prefer the Windows API function anyway.
I usually wrap this method, along with the opposite one, in two conversion functions string
->wstring
and wstring
->string
. If you also add trivial overloads string
->string
and wstring
->wstring
, you can easily write code that compiles with the Winapi TCHAR
typedef in any setting.
[Edit:] I added zero-initialization to buf
, in case you plan to use the C array directly. I would usually return the result as std::wstring(buf, wn)
, though, but do beware if you plan on using C-style null-terminated arrays.[/]
In a multithreaded environment you should pass a thread-local conversion state to the function as its final (currently invisible) parameter.
Here is a small rant of mine on this topic.
1)
public static Object deepClone(Object object) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(object);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
2)
// (1) create a MyPerson object named Al
MyAddress address = new MyAddress("Vishrantwadi ", "Pune", "India");
MyPerson al = new MyPerson("Al", "Arun", address);
// (2) make a deep clone of Al
MyPerson neighbor = (MyPerson)deepClone(al);
Here your MyPerson and MyAddress class must implement serilazable interface
You can do replace tabs with spaces in all project files by:
Ctrl+Shif+F
^\A(.*)$
Your dir
Replace by \1
This will cause all project files to be opened, with their buffer marked as dirty. With this, you can now optionally enable these next Sublime Text settings, to trim all files trailing white space and ensure a new line at the end of every file.
You can enabled these settings by going on the menu Preferences -> Settings
and adding these contents to your settings file:
"ensure_newline_at_eof_on_save": true,
"trim_trailing_white_space_on_save": true,
View -> Show Console (Ctrl+`)
and run the command:
import threading; threading.Thread( args=(set(),), target=lambda counterset: [ (view.run_command( "expand_tabs", {"set_translate_tabs": True} ), print( "Processing {:>5} view of {:>5}, view id {} {}".format( len( counterset ) + 1, len( window.views() ), view.id(), ( "Finished converting!" if len( counterset ) > len( window.views() ) - 2 else "" ) ) ), counterset.add( len( counterset ) ) ) for view in window.views() ] ).start()
File -> Save All
I tested lots of solutions. Dynamic password field name, multiple password fields (invisible for fake ones), changing input type from "text" to "password", autocomplete="off", autocomplete="new-password",... but nothing solved it with recent browser.
To get rid of password remember, I finally treated the password as input field, and "blur" the text typed.
It is less "safe" than a native password field since selecting the typed text would show it as clear text, but password is not remembered. It also depends on having Javascript activated.
You will have estimate the risk of using below proposal vs password remember option from navigator.
While password remember can be managed (disbaled per site) by the user, it's fine for a personal computer, not for a "public" or shared computer.
I my case it's for a ERP running on shared computers, so I'll give it a try to my solution below.
<input style="background-color: rgb(239, 179, 196); color: black; text-shadow: none;" name="password" size="10" maxlength="30" onfocus="this.value='';this.style.color='black'; this.style.textShadow='none';" onkeypress="this.style.color='transparent'; this.style.textShadow='1px 1px 6px green';" autocomplete="off" type="text">
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.
Create a static method in the Fragment
and then get it using getArguments()
.
Example:
public class CommentsFragment extends Fragment {
private static final String DESCRIBABLE_KEY = "describable_key";
private Describable mDescribable;
public static CommentsFragment newInstance(Describable describable) {
CommentsFragment fragment = new CommentsFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(DESCRIBABLE_KEY, describable);
fragment.setArguments(bundle);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
mDescribable = (Describable) getArguments().getSerializable(
DESCRIBABLE_KEY);
// The rest of your code
}
You can afterwards call it from the Activity
doing something like:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment fragment = CommentsFragment.newInstance(mDescribable);
ft.replace(R.id.comments_fragment, fragment);
ft.commit();
You can also use %
as follows:
source = "#{ROOT_DIR}/%s/App.config" % project
This approach works with '
(single) quotation mark as well.
Yes. bar.a
and bar.b
are set to true, but bar.c
is undefined. However, certain compilers will set it to false.
See a live example here: struct demo
According to C++ standard Section 8.5.12:
if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value
For primitive built-in data types (bool, char, wchar_t, short, int, long, float, double, long double), only global variables (all static storage variables) get default value of zero if they are not explicitly initialized.
If you don't really want undefined bar.c
to start with, you should also initialize it like you did for bar.a
and bar.b
.
file_exists($filepath)
will return a true result for a directory and full filepath, so is not always a solution when a filename is not passed.
is_file($filepath)
will only return true for fully filepaths
You'd need attach an onFocus
event to the input field via Javascript:
<input type="text" onfocus="this.value=''" value="..." ... />
It is actually very easy to do this using the "set" and "get" methods available on an express object.
Example as follows, say you have a variable called config with your configuration related stuff that you want to be available in other places:
In app.js:
var config = require('./config');
app.configure(function() {
...
app.set('config', config);
...
}
In routes/index.js
exports.index = function(req, res){
var config = req.app.get('config');
// config is now available
...
}
This error could be an indication that variable with the same name has been used in your code earlier, but for other purposes. Possibly, a variable has been given a name that coincides with the existing function used later in the code.
The expression 'AND' and 'OR' and 'NOT'
always evaluates to 'NOT'
, so you are effectively doing
while 'NOT' not in some_list:
print 'No boolean operator'
You can either check separately for all of them
while ('AND' not in some_list and
'OR' not in some_list and
'NOT' not in some_list):
# whatever
or use sets
s = set(["AND", "OR", "NOT"])
while not s.intersection(some_list):
# whatever
Try this:
def get_script_path(for_file = None):
path = os.path.dirname(os.path.realpath(sys.argv[0] or 'something'))
return path if not for_file else os.path.join(path, for_file)
The question was asked and has, so far, been answered as though the decision should be made purely on "syntactic" grounds.
I would say that the right answer of how you lay-out a number of conditions within an if, ought to depend on "semantics" too. So conditions should be broken up and grouped according to what things go together "conceptually".
If two tests are really two sides of the same coin eg. if (x>0) && (x<=100) then put them together on the same line. If another condition is conceptually far more distant eg. user.hasPermission(Admin()) then put it on it's own line
Eg.
if user.hasPermission(Admin()) {
if (x >= 0) && (x < 100) {
// do something
}
}
By definition, by multiplying a 1D vector by its transpose, you've created a singular matrix.
Each row is a linear combination of the first row.
Notice that the second row is just 8x the first row.
Likewise, the third row is 50x the first row.
There's only one independent row in your matrix.
If anyone came here from python-graphql client looking for a solution to pass an object as variable here's what I used:
query = """
{{
pairs(block: {block} first: 200, orderBy: trackedReserveETH, orderDirection: desc) {{
id
txCount
reserveUSD
trackedReserveETH
volumeUSD
}}
}}
""".format(block=''.join(['{number: ', str(block), '}']))
query = gql(query)
Make sure to escape all curly braces like I did: "{{", "}}"
You could use Gson library
Type type = new TypeToken<HashMap<String, String>>() {}.getType();
new Gson().fromJson(jsonString, type);
If you ever merge and still get problems that dont know what they are, I mean not the obvious marks of a diff
<<<<<
....
======
>>>>>>
Then you can analise your project files with https://github.com/Karumi/Kin, install it and use it
kin project.pbxproj
It has make extrange erros that doesn't allow open the project more easy to understand and solve (ones of hashes, groups and so on).
And by the way, this could also be helpful, thought I have not used it try to diff 2 versions of your project files https://github.com/bloomberg/xcdiff so this will give you really what is going on.
If you want to be able to concatenate vectors concisely, you could overload the +=
operator.
template <typename T>
std::vector<T>& operator +=(std::vector<T>& vector1, const std::vector<T>& vector2) {
vector1.insert(vector1.end(), vector2.begin(), vector2.end());
return vector1;
}
Then you can call it like this:
vector1 += vector2;
You can do this using the java.time classes built into Java 8 and later.
ZonedDateTime temporal = ...
long epochSecond = temporal.getLong(INSTANT_SECONDS);
int nanoOfSecond = temporal.get(NANO_OF_SECOND);
Date date = new Date(epochSecond * 1000 + nanoOfSecond / 1000000);
I have just experienced this issue in one of my MySQL db's and I looked at the phpMyAdmin answer here. However the best way I fixed it in phpMyAdmin was in the affected table, drop the id column and make a fresh/new id column (adding A-I -autoincrement-). This restored my table id correctly-simples! Hope that helps (no MySQL code needed-I hope to learn to use that but later!) anyone else with this problem.
You can try checking some of the class generators online for further information. However, I believe some of the answers have been useful. Here's my approach that may be useful.
The following code was made with a dynamic method in mind.
dynObj = (JArray) JsonConvert.DeserializeObject(nvm);
foreach(JObject item in dynObj) {
foreach(JObject trend in item["trends"]) {
Console.WriteLine("{0}-{1}-{2}", trend["query"], trend["name"], trend["url"]);
}
}
This code basically allows you to access members contained in the Json string. Just a different way without the need of the classes. query
, trend
and url
are the objects contained in the Json string.
You can also use this website. Don't trust the classes a 100% but you get the idea.
I've created this fiddle:
http://jsfiddle.net/wo40ev18/3/
<div id="table">
<div class="caption">
Center Caption
</div>
<div class="group">
<div class="row">
<div class="cell">Link 1t</div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell ">Link 2</div>
</div>
</div>
#table {
display:table;
}
.group {display: table-row-group; }
.row {
display:table-row;
height: 80px;
line-height: 80px;
}
.cell {
display:table-cell;
width:1%;
text-align: center;
border:1px solid grey;
height: 80px
line-height: 80px;
}
.caption {
border:1px solid red; caption-side: top; display: table-caption; text-align: center;
position: relative;
top: 80px;
height: 80px;
height: 80px;
line-height: 80px;
}
Look up the specification of HTTP. Or to get started, try http://www.jmarshall.com/easy/http/
XOR behaves like Austin explained, as an exclusive OR, either A or B but not both and neither yields false.
There are 16 possible logical operators for two inputs since the truth table consists of 4 combinations there are 16 possible ways to arrange two boolean parameters and the corresponding output.
They all have names according to this wikipedia article
I think these both blog post should help you solving your problem.
http://blog.the-dargans.co.uk/2007/04/programmatically-adding-items-to.html http://asadewa.wordpress.com/2007/11/19/adding-a-custom-content-type-specific-item-on-a-sharepoint-list/
Short walk through:
Add a new item to the list:
SPListItem newItem = list.AddItem();
To bind you new item to a content type you have to set the content type id for the new item:
newItem["ContentTypeId"] = <Id of the content type>;
Set the fields specified within your content type.
Commit your changes:
newItem.Update();
Please try something like:
=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))
You seem to have three main possible scenarios:
ColumnA below is formatted General and ColumnB as Date (my default setting). ColumnC also as date but with custom formatting to suit the appearances mentioned in your question.
A clue as to whether or not text format is the left or right alignment of the cells’ contents.
I am suggesting separate treatment for each of the above three main cases, so use =IF to differentiate them.
This is longer than any of the others, so can be distinguished as having a length greater than say 10 characters, with =LEN.
In this case we want all but the last six characters but for added flexibility (for instance, in case the time element included seconds) I have chosen to count from the left rather than from the right. The problem then is that the month names may vary in length, so I have chosen to look for the space that immediately follows the year to indicate the limit for the relevant number of characters.
This with =FIND which looks for a space (" "
) in C1
, starting with the eighth character within C1
counting from the left, on the assumption that for this case days will be expressed as two characters and months as three or more.
Since =LEFT is a string function it returns a string, but this can be converted to a value with=VALUE.
So
=VALUE(LEFT(C1,FIND(" ",C1,8)))
returns 40671
in this example – in Excel’s 1900 date system the date serial number for May 5, 2011.
If the length of C1 is not greater than 10 characters, we still need to distinguish between a text entry or a value entry which I have chosen to do with =ISTEXT and, where the if condition is TRUE (as for C2) apply =DATE which takes three parameters, here provided by:
=RIGHT(C2,4)
Takes the last four characters of C2, hence 2011
in this example.
=MID(C2,4,2)
Starting at the fourth character, takes the next two characters of C2, hence 05
in this example (representing May).
=LEFT(C2,2))
Takes the first two characters of C2, hence 08
in this example (representing the 8th day of the month).
Date is not a text function so does not need to be wrapped in =VALUE.
Taken together
=DATE(RIGHT(C2,4),MID(C2,4,2),LEFT(C2,2))
also returns 40671
in this example, but from different input from Case #1.
Is simple because already a date serial number, so just
=C2
is sufficient.
Put the above together to cover all three cases in a single formula:
=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))
as applied in ColumnF (formatted to suit OP) or in General format (to show values are integers) in ColumnH:
Your Call works if it were a Table Valued Function. Since its a scalar function, you need to call it like:
SELECT dbo.fn_HomePageSlider(9, 3025) AS MyResult
Short answer: You can't.
Long answer: You could use a modal to display a popup with the image you need.
You can refer to this as an example to a modal.
"As with bootstrap’s own plugins, datepicker provides a data-api that can be used to instantiate datepickers without the need for custom javascript..."
Boostrap DatePicker Documentation
Maybe you want to set format without DatePicker instance, for that, you have to add the property data-date-format="DateFormat"
to main Div tag, for example:
<div class="input-group date" data-provide="datepicker" data-date-format="yyyy-mm-dd">
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
<input type="text" name="YourName" id="YourId" class="YourClass">
</div>
If you pass the -v
flag to the ansible-playbook command, then ansible will show the output on your terminal.
For your use case, you may want to try using the fetch module to copy the public key from the server to your local machine. That way, it will only show a "changed" status when the file changes.
There are several possible methods, but for you, there is already a builtin parse_str
function
$array = array();
parse_str($string, $array);
var_dump($array);
Assuming you're in control of the pattern used to find test classes, I'd suggest changing it to match *Test
rather than *Test*
. That way TestHelper
won't get matched, but FooTest
will.
You could use the following generic method:
public static List<T> GetItemsList<T>(this int enums) where T : struct, IConvertible
{
if (!typeof (T).IsEnum)
{
throw new Exception("Type given must be an Enum");
}
return (from int item in Enum.GetValues(typeof (T))
where (enums & item) == item
select (T) Enum.Parse(typeof (T), item.ToString(new CultureInfo("en")))).ToList();
}
Try the following:
print "First is: %f" % (first)
print "Second is: %f" % (second)
I am unsure what answer is. But apart from that, this will be:
print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans)
There's a lot of text on Format String Specifiers. You can google it and get a list of specifiers. One thing I forgot to note:
If you try this:
print "First is: %s" % (first)
It converts the float value in first to a string. So that would work as well.
to add parameter to post urls (to perma-links), i use this:
add_filter( 'post_type_link', 'append_query_string', 10, 2 );
function append_query_string( $url, $post )
{
return add_query_arg('my_pid',$post->ID, $url);
}
output:
http://yoursite.com/pagename?my_pid=12345678
In addition to the above you can use the System.exit()
to return an exit code which may be very usuefull specially if your calling the process automatically using the System.exit(code);
this can help you determine for example if an error has occured during the run.
This will change your current working directory to so that opening relative paths will work:
import os
os.chdir("/home/udi/foo")
However, you asked how to change into whatever directory your Python script is located, even if you don't know what directory that will be when you're writing your script. To do this, you can use the os.path
functions:
import os
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
This takes the filename of your script, converts it to an absolute path, then extracts the directory of that path, then changes into that directory.
It also happens when the view returned by onCreateView() isn't the view that was inflated.
Example:
View rootView = inflater.inflate(R.layout.my_fragment, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.text_view);
textView.setText("Some text.");
return textView;
Fix:
return rootView;
Instead of:
return textView; // or whatever you returned
Here's a function that will return the content of any meta tag and will memoize the result, avoiding unnecessary querying of the DOM.
var getMetaContent = (function(){
var metas = {};
var metaGetter = function(metaName){
var theMetaContent, wasDOMQueried = true;;
if (metas[metaName]) {
theMetaContent = metas[metaName];
wasDOMQueried = false;
}
else {
Array.prototype.forEach.call(document.getElementsByTagName("meta"), function(el) {
if (el.name === metaName) theMetaContent = el.content;
metas[metaName] = theMetaContent;
});
}
console.log("Q:wasDOMQueried? A:" + wasDOMQueried);
return theMetaContent;
}
return metaGetter;
})();
getMetaContent("description"); /* getMetaContent console.logs the content of the description metatag. If invoked a second time it confirms that the DOM was only queried once */
And here's an extended version that also queries for open graph tags, and uses Array#some:
var getMetaContent = (function(){
var metas = {};
var metaGetter = function(metaName){
wasDOMQueried = true;
if (metas[metaName]) {
wasDOMQueried = false;
}
else {
Array.prototype.some.call(document.getElementsByTagName("meta"), function(el) {
if(el.name === metaName){
metas[metaName] = el.content;
return true;
}
if(el.getAttribute("property") === metaName){
metas[metaName] = el.content;
return true;
}
else{
metas[metaName] = "meta tag not found";
}
});
}
console.info("Q:wasDOMQueried? A:" + wasDOMQueried);
console.info(metas);
return metas[metaName];
}
return metaGetter;
})();
getMetaContent("video"); // "http://video.com/video33353.mp4"
I'm not familiar with the package WriteXLS
; I generally use XLConnect
:
library(XLConnect)
##
newWB <- loadWorkbook(
filename="F:/TempDir/tempwb.xlsx",
create=TRUE)
##
for(i in 1:10){
wsName <- paste0("newsheet",i)
createSheet(
newWB,
name=wsName)
##
writeWorksheet(
newWB,
data=data.frame(
X=1:10,
Dataframe=paste0("DF ",i)),
sheet=wsName,
header=TRUE,
rownames=NULL)
}
saveWorkbook(newWB)
This can certainly be vectorized, as @joran noted above, but just for the sake of generating dynamic sheet names quickly, I used a for
loop to demonstrate.
I used the create=TRUE
argument in loadWorkbook
since I was creating a new .xlsx file, but if your file already exists then you don't have to specify this, as the default value is FALSE
.
Here are a few screenshots of the created workbook:
The windows.load function is useful if you want to do something when everything is loaded.
$(window).load(function(){
// full load
});
But you can also use the .load function on any other element. So if you have one particularly large image and you want to do something when that loads but the rest of your page loading code when the dom has loaded you could do:
$(function(){
// Dom loaded code
$('#largeImage').load({
// Image loaded code
});
});
Also the jquery .load function is pretty much the same as a normal .onload.
Construct some data
df <- data.frame( name=c("John", "Adam"), date=c(3, 5) )
Extract exact matches:
subset(df, date==3)
name date
1 John 3
Extract matches in range:
subset(df, date>4 & date<6)
name date
2 Adam 5
The following syntax produces identical results:
df[df$date>4 & df$date<6, ]
name date
2 Adam 5
That's something controlled by your terminal, not by printf
.
printf
simply sends a \t
to the output stream (which can be a tty, a file etc), it doesn't send a number of spaces.
You can use text-overflow: ellipsis; which according to caniuse is supported by all the major browsers.
Here's a demo on jsbin.
.cut-text {
text-overflow: ellipsis;
overflow: hidden;
width: 160px;
height: 1.2em;
white-space: nowrap;
}
_x000D_
<div class="cut-text">
I like big butts and I can not lie.
</div>
_x000D_
This works for me
find _CACHE_* | while read line; do
cat "$line" | grep "something"
done
Yes. In Ruby the not equal to operator is:
!=
You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.
Or without (
and the need to escape it:
find . -not -name "*.exe" -not -name "*.dll"
and to also exclude the listing of directories
find . -not -name "*.exe" -not -name "*.dll" -not -type d
or in positive logic ;-)
find . -not -name "*.exe" -not -name "*.dll" -type f
Since PostgreSQL 10
CREATE TABLE test_new (
id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
payload text
);
If you have lots of columns and only one is different you could do:
In[1]: grouper = df.groupby('Company Name')
In[2]: res = grouper.count()
In[3]: res['Amount'] = grouper.Amount.sum()
In[4]: res
Out[4]:
Organisation Name Amount
Company Name
Vifor Pharma UK Ltd 5 4207.93
Note you can then rename the Organisation Name column as you wish.
Look in the Python re documentation for lookaheads (?=...)
and lookbehinds (?<=...)
-- I'm pretty sure they're what you want. They match strings, but do not "consume" the bits of the strings they match.
You can try with jQuery also
$('textarea').css("resize", "none");
Building on Graham's answer, the extra code saves the workbook back into it's original location in it's original format.
Public Sub SaveWorksheetsAsCsv()
Dim WS As Excel.Worksheet
Dim SaveToDirectory As String
Dim CurrentWorkbook As String
Dim CurrentFormat As Long
CurrentWorkbook = ThisWorkbook.FullName
CurrentFormat = ThisWorkbook.FileFormat
' Store current details for the workbook
SaveToDirectory = "C:\"
For Each WS In ThisWorkbook.Worksheets
WS.SaveAs SaveToDirectory & WS.Name, xlCSV
Next
Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat
Application.DisplayAlerts = True
' Temporarily turn alerts off to prevent the user being prompted
' about overwriting the original file.
End Sub
Even though above answers are correct, I wanna add a notice to distinguish types of storage:
Here is the link to source code for cases I mentioned above: https://github.com/mttdat/utils/blob/master/utils/src/main/java/mttdat/utils/FileUtils.java
This console warning is not an error or an actual problem — Chrome is just spreading the word about this new standard to increase developer adoption.
It has nothing to do with your code. It is something their web servers will have to support.
Release date for a fix is February 4, 2020 per: https://www.chromium.org/updates/same-site
February, 2020: Enforcement rollout for Chrome 80 Stable: The SameSite-by-default and SameSite=None-requires-Secure behaviors will begin rolling out to Chrome 80 Stable for an initial limited population starting the week of February 17, 2020, excluding the US President’s Day holiday on Monday. We will be closely monitoring and evaluating ecosystem impact from this initial limited phase through gradually increasing rollouts.
For the full Chrome release schedule, see here.
I solved same problem by adding in response header
response.setHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Strict");
SameSite
prevents the browser from sending the cookie along with cross-site requests. The main goal is mitigating the risk of cross-origin information leakage. It also provides some protection against cross-site request forgery attacks. Possible values for the flag are Lax or Strict.
SameSite cookies explained here
Please refer this before applying any option.
Hope this helps you.
The return
there is returning from the lambda expression rather than from the containing method. Instead of forEach
you need to filter
the stream:
players.stream().filter(player -> player.getName().contains(name))
.findFirst().orElse(null);
Here filter
restricts the stream to those items that match the predicate, and findFirst
then returns an Optional
with the first matching entry.
This looks less efficient than the for-loop approach, but in fact findFirst()
can short-circuit - it doesn't generate the entire filtered stream and then extract one element from it, rather it filters only as many elements as it needs to in order to find the first matching one. You could also use findAny()
instead of findFirst()
if you don't necessarily care about getting the first matching player from the (ordered) stream but simply any matching item. This allows for better efficiency when there's parallelism involved.
nanoScrollerJS is simply to use. I always use them...
Browser compatibility:
Mobile browsers support:
Code example from the Documentation,
<div id="about" class="nano">
<div class="nano-content"> ... content here ... </div>
</div>
This problem comes while you are running Test. Add dependency
testCompile group: 'com.h2database', name: 'h2', version: '1.4.197'
Add folder resources under test source add file bootstrap.yml and provide content.
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
url: jdbc:h2:mem:TEST
driver-class-name: org.h2.Driver
username: username
password: password
hikari:
idle-timeout: 10000
this will setup your data source.
Very simple to fix, you just need to turn the parameter to writerow into a list.
for item in RESULTS:
wr.writerow([item,])
Merge squash merges a tree (a sequence of commits) into a single commit. That is, it squashes all changes made in n commits into a single commit.
Rebasing is re-basing, that is, choosing a new base (parent commit) for a tree. Maybe the mercurial term for this is more clear: they call it transplant because it's just that: picking a new ground (parent commit, root) for a tree.
When doing an interactive rebase, you're given the option to either squash, pick, edit or skip the commits you are going to rebase.
Hope that was clear!
Could you not have simply added:
align-items:center;
to a new class in your row div. Essentially:
<div class="row align_center">
.align_center { align-items:center; }
Using awk only
foo="uNcapItalizedstrIng"
echo $foo | awk '{print toupper(substr($0,0,1))tolower(substr($0,2))}'
Try this code
public class WiFiDemo extends Activity implements OnClickListener
{
WifiManager wifi;
ListView lv;
TextView textStatus;
Button buttonScan;
int size = 0;
List<ScanResult> results;
String ITEM_KEY = "key";
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter;
/* Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
lv = (ListView)findViewById(R.id.list);
wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled() == false)
{
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
wifi.setWifiEnabled(true);
}
this.adapter = new SimpleAdapter(WiFiDemo.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
lv.setAdapter(this.adapter);
registerReceiver(new BroadcastReceiver()
{
@Override
public void onReceive(Context c, Intent intent)
{
results = wifi.getScanResults();
size = results.size();
}
}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
public void onClick(View view)
{
arraylist.clear();
wifi.startScan();
Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
try
{
size = size - 1;
while (size >= 0)
{
HashMap<String, String> item = new HashMap<String, String>();
item.put(ITEM_KEY, results.get(size).SSID + " " + results.get(size).capabilities);
arraylist.add(item);
size--;
adapter.notifyDataSetChanged();
}
}
catch (Exception e)
{ }
}
}
WiFiDemo.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="@+id/textStatus"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Status" />
<Button
android:id="@+id/buttonScan"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:text="Scan" />
</LinearLayout>
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"></ListView>
</LinearLayout>
For ListView- row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/list_value"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14dp" />
</LinearLayout>
Add these permission in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Use Bootstrap to have a hustle free with your images as shown. Use class img-responsive and you are done:
<img src="cinqueterre.jpg" class="img-responsive" alt="Cinque Terre" width="304" height="236">
Well, people are talking about Asp.net 4.0 only... I guess we need to address other versions too. Today, I had the same problem when I replaced my AjaxToolkit editor with TinyMCE and with the postback I found the same issue.
"A potentially dangerous Request.Form value was detected from the client"..
So I used this line inside my webconfig and it worked for me.
<system.web>
<pages validateRequest="false" />
</system.web>
It should work across Asp.net 2.0 to 3.5.
UPDATE: Even works upto .net 4.5
UPDATE: You can also try to validate the request on page level rather whole website. Just wanted to let the readers to choose the best way. Thanks DVD for pointing this out.
public static boolean like(String source, String exp) {
if (source == null || exp == null) {
return false;
}
int sourceLength = source.length();
int expLength = exp.length();
if (sourceLength == 0 || expLength == 0) {
return false;
}
boolean fuzzy = false;
char lastCharOfExp = 0;
int positionOfSource = 0;
for (int i = 0; i < expLength; i++) {
char ch = exp.charAt(i);
// ????
boolean escape = false;
if (lastCharOfExp == '\\') {
if (ch == '%' || ch == '_') {
escape = true;
// System.out.println("escape " + ch);
}
}
if (!escape && ch == '%') {
fuzzy = true;
} else if (!escape && ch == '_') {
if (positionOfSource >= sourceLength) {
return false;
}
positionOfSource++;// <<<----- ???1
} else if (ch != '\\') {// ????,?????????
if (positionOfSource >= sourceLength) {// ?????source????
return false;
}
if (lastCharOfExp == '%') { // ??????%,?????
int tp = source.indexOf(ch);
// System.out.println("?????=%,?????=" + ch + ",position=" + position + ",tp=" + tp);
if (tp == -1) { // ????????,????
return false;
}
if (tp >= positionOfSource) {
positionOfSource = tp + 1;// <<<----- ????
if (i == expLength - 1 && positionOfSource < sourceLength) { // exp??????????,????source?????????
return false;
}
} else {
return false;
}
} else if (source.charAt(positionOfSource) == ch) {// ????????ch??
positionOfSource++;
} else {
return false;
}
}
lastCharOfExp = ch;// <<<----- ??
// System.out.println("?????=" + ch + ",position=" + position);
}
// expr???????,???????,??source???????????source???
if (!fuzzy && positionOfSource < sourceLength) {
// System.out.println("?????=" + lastChar + ",position=" + position );
return false;
}
return true;// ????true
}
Assert.assertEquals(true, like("abc_d", "abc\\_d"));
Assert.assertEquals(true, like("abc%d", "abc\\%%d"));
Assert.assertEquals(false, like("abcd", "abc\\_d"));
String source = "1abcd";
Assert.assertEquals(true, like(source, "_%d"));
Assert.assertEquals(false, like(source, "%%a"));
Assert.assertEquals(false, like(source, "1"));
Assert.assertEquals(true, like(source, "%d"));
Assert.assertEquals(true, like(source, "%%%%"));
Assert.assertEquals(true, like(source, "1%_"));
Assert.assertEquals(false, like(source, "1%_2"));
Assert.assertEquals(false, like(source, "1abcdef"));
Assert.assertEquals(true, like(source, "1abcd"));
Assert.assertEquals(false, like(source, "1abcde"));
// ????case?????
Assert.assertEquals(true, like(source, "_%_"));
Assert.assertEquals(true, like(source, "_%____"));
Assert.assertEquals(true, like(source, "_____"));// 5?
Assert.assertEquals(false, like(source, "___"));// 3?
Assert.assertEquals(false, like(source, "__%____"));// 6?
Assert.assertEquals(false, like(source, "1"));
Assert.assertEquals(false, like(source, "a_%b"));
Assert.assertEquals(true, like(source, "1%"));
Assert.assertEquals(false, like(source, "d%"));
Assert.assertEquals(true, like(source, "_%"));
Assert.assertEquals(true, like(source, "_abc%"));
Assert.assertEquals(true, like(source, "%d"));
Assert.assertEquals(true, like(source, "%abc%"));
Assert.assertEquals(false, like(source, "ab_%"));
Assert.assertEquals(true, like(source, "1ab__"));
Assert.assertEquals(true, like(source, "1ab__%"));
Assert.assertEquals(false, like(source, "1ab___"));
Assert.assertEquals(true, like(source, "%"));
Assert.assertEquals(false, like(null, "1ab___"));
Assert.assertEquals(false, like(source, null));
Assert.assertEquals(false, like(source, ""));
Here is a more elaborated solution with a SQL function:
GetFirstname
CREATE FUNCTION [dbo].[ufn_GetFirstName]
(
@FullName varchar(500)
)
RETURNS varchar(500)
AS
BEGIN
-- Declare the return variable here
DECLARE @RetName varchar(500)
SET @FullName = replace( replace( replace( replace( @FullName, '.', '' ), 'Mrs', '' ), 'Ms', '' ), 'Mr', '' )
SELECT
@RetName =
CASE WHEN charindex( ' ', ltrim( rtrim( @FullName ) ) ) > 0 THEN left( ltrim( rtrim( @FullName ) ), charindex( ' ', ltrim( rtrim( @FullName ) ) ) - 1 ) ELSE '' END
RETURN @RetName
END
GetLastName
CREATE FUNCTION [dbo].[ufn_GetLastName]
(
@FullName varchar(500)
)
RETURNS varchar(500)
AS
BEGIN
DECLARE @RetName varchar(500)
IF(right(ltrim(rtrim(@FullName)), 2) <> ' I')
BEGIN
set @RetName = left(
CASE WHEN
charindex( ' ', reverse( ltrim( rtrim(
replace( replace( replace( replace( replace( replace( @FullName, ' Jr', '' ), ' III', '' ), ' II', '' ), ' Jr.', '' ), ' Sr', ''), 'Sr.', '')
) ) ) ) > 0
THEN
right( ltrim( rtrim(
replace( replace( replace( replace( replace( replace( @FullName, ' Jr', '' ), ' III', '' ), ' II', '' ), ' Jr.', '' ), ' Sr', ''), 'Sr.', '')
) ) , charindex( ' ', reverse( ltrim( rtrim(
replace( replace( replace( replace( replace( replace( @FullName, ' Jr', '' ), ' III', '' ), ' II', '' ), ' Jr.', '' ), ' Sr', ''), 'Sr.', '')
) ) ) ) - 1 )
ELSE '' END
, 25 )
END
ELSE
BEGIN
SET @RetName = left(
CASE WHEN
charindex( ' ', reverse( ltrim( rtrim(
replace( replace( replace( replace( replace( replace( replace( @FullName, ' Jr', '' ), ' III', '' ), ' II', '' ), ' I', '' ), ' Jr.', '' ), ' Sr', ''), 'Sr.', '')
) ) ) ) > 0
THEN
right( ltrim( rtrim(
replace( replace( replace( replace( replace( replace( replace( @FullName, ' Jr', '' ), ' III', '' ), ' II', '' ), ' I', '' ), ' Jr.', '' ), ' Sr', ''), 'Sr.', '')
) ) , charindex( ' ', reverse( ltrim( rtrim(
replace( replace( replace( replace( replace( replace( replace( @FullName, ' Jr', '' ), ' III', '' ), ' II', '' ), ' I', '' ), ' Jr.', '' ), ' Sr', ''), 'Sr.', '')
) ) ) ) - 1 )
ELSE '' END
, 25 )
END
RETURN @RetName
END
USE:
SELECT dbo.ufn_GetFirstName(Fullname) as FirstName, dbo.ufn_GetLastName(Fullname) as LastName FROM #Names
You can use mysql scheduler to run it each 5 seconds. You can find samples at http://dev.mysql.com/doc/refman/5.1/en/create-event.html
Never used it but I hope this would work:
CREATE EVENT myevent
ON SCHEDULE EVERY 5 SECOND
DO
CALL delete_rows_links();
just change your JDK I installed the JDK of SUN not Oracle and it works for me....
In RxJS 5+ you can do it like this
import { Observable } from "rxjs/Observable";
import { of } from "rxjs/observable/of";
import { delay } from "rxjs/operators";
fakeObservable = of('dummy').pipe(delay(5000));
In RxJS 6+
import { of } from "rxjs";
import { delay } from "rxjs/operators";
fakeObservable = of('dummy').pipe(delay(5000));
If you want to delay each emitted value try
from([1, 2, 3]).pipe(concatMap(item => of(item).pipe(delay(1000))));
The acceptable verbs are controlled in web.config (found in the root of the website) in <system.web><httpHandlers>
and possibly <webServices><protocols>
. Web.config will be accessible to you if it exists. There is also a global server.config which probably won't. If you can get a look at either of these you may get a clue.
The acceptable verbs can differ with the content types - have you set Content-type headers in your page at all ? (i.e. if your Content-type was application/json then different verbs would be allowed)
downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?
You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.
http://www.microsoft.com/en-us/download/details.aspx?id=1695
Bernhard's answer needed some tweaking work for me because the %DATE% environment variable is in a different format (as commented elsewhere). Also, there was a tilde (~) missing.
Instead of:
set backupFilename=%DATE:~6,4%%DATE:~3,2%%DATE:0,2%
I had to use:
set backupFilename=%DATE:~10,4%%DATE:~4,2%%DATE:~7,2%
for the date format:
c:\Scripts>echo %DATE%
Thu 05/14/2009
This is due to staticmethod being a descriptor and requires a class-level attribute fetch to exercise the descriptor protocol and get the true callable.
From the source code:
It can be called either on the class (e.g.
C.f()
) or on an instance (e.g.C().f()
); the instance is ignored except for its class.
But not directly from inside the class while it is being defined.
But as one commenter mentioned, this is not really a "Pythonic" design at all. Just use a module level function instead.
Try with the fully qualified name for the resource:
private static final String FILENAME = "resources/skyscrapper";
I assume 0
means false
(which is the case in a lot of programming languages). That means true
is not 0
(some languages use -1
some others use 1
; doesn't hurt to be compatible to either). So assuming by "better" you mean less typing, you can just write:
bool boolValue = intValue != 0;
The same as you would in .NET:
$DateStr = $Date.ToString("yyyyMMdd")
Or:
$DateStr = '{0:yyyyMMdd}' -f $Date
Try this.
public static void main(String[] args) {
EchoServer0 myServer;
myServer = new EchoServer0();
myServer.listen();
}
What you were trying to do was declaring a variable of type Object
, not creating anything for that variable to reference, then trying to call a method that didn't exist (in the class Object
) on an object that hadn't been created. It was never going to work.
You can use SUBSTRING
and CONVERT
:
SELECT stuff
FROM table
WHERE conditions
ORDER BY CONVERT(SUBSTRING(name_column, 6), SIGNED INTEGER);
Where name_column
is the column with the "name-" values. The SUBSTRING
removes everything up before the sixth character (i.e. the "name-" prefix) and then the CONVERT
converts the left over to a real integer.
UPDATE: Given the changing circumstances in the comments (i.e. the prefix can be anything), you'll have to throw a LOCATE
in the mix:
ORDER BY CONVERT(SUBSTRING(name_column, LOCATE('-', name_column) + 1), SIGNED INTEGER);
This of course assumes that the non-numeric prefix doesn't have any hyphens in it but the relevant comment says that:
name
can be any sequence of letters
so that should be a safe assumption.
The first thing you need to decide is whether the data structure needs to be mutable or not. As has been mentioned, lists are mutable, tuples are not. This also means that tuples can be used for dictionary keys, wheres lists cannot.
In my experience, tuples are generally used where order and position is meaningful and consistant. For example, in creating a data structure for a choose your own adventure game, I chose to use tuples instead of lists because the position in the tuple was meaningful. Here is one example from that data structure:
pages = {'foyer': {'text' : "some text",
'choices' : [('open the door', 'rainbow'),
('go left into the kitchen', 'bottomless pit'),
('stay put','foyer2')]},}
The first position in the tuple is the choice displayed to the user when they play the game and the second position is the key of the page that choice goes to and this is consistent for all pages.
Tuples are also more memory efficient than lists, though I'm not sure when that benefit becomes apparent.
Also check out the chapters on lists and tuples in Think Python.
That's the way to create complex boolean expressions: combine them with AND and OR. The snippet you posted doesn't throw any error for the IF.
You need to do something like this,
$.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
prevText: '<Préc', prevStatus: 'Voir le mois précédent',
nextText: 'Suiv>', nextStatus: 'Voir le mois suivant',
currentText: 'Courant', currentStatus: 'Voir le mois courant',
monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
'Jul','Aoû','Sep','Oct','Nov','Déc'],
monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
weekHeader: 'Sm', weekStatus: '',
dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: 'Choisir la date', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['fr']);
for sv data follow the following link
http://code.google.com/p/logicss/source/browse/trunk/media/jquery/jquery.ui.i18n.all.min.js?r=41
<div class="input-group date" data-provide="datepicker" data-date-start-date="0d">
<input type="text" class="form-control" id="input_id" name="input_name" />
<div class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</div>
</div>
There's a technique called Immersive Full-Screen Mode available in KitKat.
[StringLength(16, ErrorMessageResourceName= "PasswordMustBeBetweenMinAndMaxCharacters", ErrorMessageResourceType = typeof(Resources.Resource), MinimumLength = 6)]
[Display(Name = "Password", ResourceType = typeof(Resources.Resource))]
public string Password { get; set; }
Save resource like this
"ThePasswordMustBeAtLeastCharactersLong" | "The password must be {1} at least {2} characters long"
As seen in this Angular example, there is a way to disable a button until the whole form is valid:
<button type="submit" [disabled]="!ngForm.valid">Submit</button>
Because when you access a static field, you should do so on the class (or in this case the enum). As in
MyUnits.MILLISECONDS;
Not on an instance as in
m.MILLISECONDS;
Edit To address the question of why: In Java, when you declare something as static
, you are saying that it is a member of the class, not the object (hence why there is only one). Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.
//the following code checks if your radio button having name like 'yourRadioName'
//is checked or not
$(document).ready(function() {
if($("input:radio[name='yourRadioName']").is(":checked")) {
//its checked
}
});
If you want to harness Selenium IDE record & playback capabilities for Chrome browser there is an equivalent extension for Chrome called Scirocco. You can add it to Chrome by visiting here using your Chrome browser https://chrome.google.com/webstore/search/scirocco
Scirocco is created by Sonix Asia and is not as polished as Selenium IDE for Firefox. It is in fact quite buggy in places. But it does what you ask.
Iterating through elements of two lists simultaneously is known as zipping, and python provides a built in function for it, which is documented here.
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True
[Example is taken from pydocs]
In your case, it will be simply:
for (lat, lon) in zip(latitudes, longitudes):
... process lat and lon
You need to use WITH ROLLBACK IMMEDIATE
to boot other conections out with no regards to what or who is is already using it.
Or use WITH NO_WAIT
to not hang and not kill existing connections. See http://www.blackwasp.co.uk/SQLOffline.aspx for details
it's in <algorithm>
and called std::find
.
This is maybe not the case of original OP question, but: if you exceeds the default max size, this maybe a symptom of some other issue you have. in my case, I had the warrning, but finally it turned into a FATAL ERROR: MarkCompactCollector: semi-space copy, fallback in old gen Allocation failed - JavaScript heap out of memory. the reason was that i dynamically imported the current module, so this ended up with an endless loop...
Here's a clue why an onchange() call might not fire your bound function:
I created this table which contains both the heights of iPhone and iPad keyboards, both for landscape and portrait mode, both with the toolbar on and off.
I even explained how you can use these dimensions in your code here.
Note that you should only use these dimensions if you need to know the keyboard's dimension before you layout the view. Otherwise the solutions from the other answers work better.
Also worth mentioning, if you are setting the title attribute with Javascript like this:
divElement.setAttribute("title", "Line one Line two");
It won't work. You have to replace that ASCII decimal 10 to a ASCII hexadecimal A in the way it's escaped with Javascript. Like this:
divElement.setAttribute("title", "Line one\x0ALine two");
I use explicit interface implementation most of the time. Here are the main reasons.
Refactoring is safer
When changing an interface, it's better if the compiler can check it. This is harder with implicit implementations.
Two common cases come to mind:
Adding a function to an interface, where an existing class that implements this interface already happens to have a method with the same signature as the new one. This can lead to unexpected behavior, and has bitten me hard several times. It's difficult to "see" when debugging because that function is likely not located with the other interface methods in the file (the self-documenting issue mentioned below).
Removing a function from an interface. Implicitly implemented methods will be suddenly dead code, but explicitly implemented methods will get caught by compile error. Even if the dead code is good to keep around, I want to be forced to review it and promote it.
It's unfortunate that C# doesn't have a keyword that forces us to mark a method as an implicit implementation, so the compiler could do the extra checks. Virtual methods don't have either of the above problems due to required use of 'override' and 'new'.
Note: for fixed or rarely-changing interfaces (typically from vendor API's), this is not a problem. For my own interfaces, though, I can't predict when/how they will change.
It's self-documenting
If I see 'public bool Execute()' in a class, it's going to take extra work to figure out that it's part of an interface. Somebody will probably have to comment it saying so, or put it in a group of other interface implementations, all under a region or grouping comment saying "implementation of ITask". Of course, that only works if the group header isn't offscreen..
Whereas: 'bool ITask.Execute()' is clear and unambiguous.
Clear separation of interface implementation
I think of interfaces as being more 'public' than public methods because they are crafted to expose just a bit of the surface area of the concrete type. They reduce the type to a capability, a behavior, a set of traits, etc. And in the implementation, I think it's useful to keep this separation.
As I am looking through a class's code, when I come across explicit interface implementations, my brain shifts into "code contract" mode. Often these implementations simply forward to other methods, but sometimes they will do extra state/param checking, conversion of incoming parameters to better match internal requirements, or even translation for versioning purposes (i.e. multiple generations of interfaces all punting down to common implementations).
(I realize that publics are also code contracts, but interfaces are much stronger, especially in an interface-driven codebase where direct use of concrete types is usually a sign of internal-only code.)
Related: Reason 2 above by Jon.
And so on
Plus the advantages already mentioned in other answers here:
It's not all fun and happiness. There are some cases where I stick with implicits:
Also, it can be a pain to do the casting when you do in fact have the concrete type and want to call an explicit interface method. I deal with this in one of two ways:
public IMyInterface I { get { return this; } }
(which should get inlined) and call foo.I.InterfaceMethod()
. If multiple interfaces that need this ability, expand the name beyond I (in my experience it's rare that I have this need).Currently there is no language support for enum flags, Meta classes might inherently add this feature if it would ever be part of the c++ standard.
My solution would be to create enum-only instantiated template functions adding support for type-safe bitwise operations for enum class using its underlying type:
File: EnumClassBitwise.h
#pragma once
#ifndef _ENUM_CLASS_BITWISE_H_
#define _ENUM_CLASS_BITWISE_H_
#include <type_traits>
//unary ~operator
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum& operator~ (Enum& val)
{
val = static_cast<Enum>(~static_cast<std::underlying_type_t<Enum>>(val));
return val;
}
// & operator
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum operator& (Enum lhs, Enum rhs)
{
return static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) & static_cast<std::underlying_type_t<Enum>>(rhs));
}
// &= operator
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum operator&= (Enum& lhs, Enum rhs)
{
lhs = static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) & static_cast<std::underlying_type_t<Enum>>(rhs));
return lhs;
}
//| operator
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum operator| (Enum lhs, Enum rhs)
{
return static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) | static_cast<std::underlying_type_t<Enum>>(rhs));
}
//|= operator
template <typename Enum, typename std::enable_if_t<std::is_enum<Enum>::value, int> = 0>
constexpr inline Enum& operator|= (Enum& lhs, Enum rhs)
{
lhs = static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(lhs) | static_cast<std::underlying_type_t<Enum>>(rhs));
return lhs;
}
#endif // _ENUM_CLASS_BITWISE_H_
For convenience and for reducing mistakes, you might want to wrap your bit flags operations for enums and for integers as well:
File: BitFlags.h
#pragma once
#ifndef _BIT_FLAGS_H_
#define _BIT_FLAGS_H_
#include "EnumClassBitwise.h"
template<typename T>
class BitFlags
{
public:
constexpr inline BitFlags() = default;
constexpr inline BitFlags(T value) { mValue = value; }
constexpr inline BitFlags operator| (T rhs) const { return mValue | rhs; }
constexpr inline BitFlags operator& (T rhs) const { return mValue & rhs; }
constexpr inline BitFlags operator~ () const { return ~mValue; }
constexpr inline operator T() const { return mValue; }
constexpr inline BitFlags& operator|=(T rhs) { mValue |= rhs; return *this; }
constexpr inline BitFlags& operator&=(T rhs) { mValue &= rhs; return *this; }
constexpr inline bool test(T rhs) const { return (mValue & rhs) == rhs; }
constexpr inline void set(T rhs) { mValue |= rhs; }
constexpr inline void clear(T rhs) { mValue &= ~rhs; }
private:
T mValue;
};
#endif //#define _BIT_FLAGS_H_
Possible usage:
#include <cstdint>
#include <BitFlags.h>
void main()
{
enum class Options : uint32_t
{
NoOption = 0 << 0
, Option1 = 1 << 0
, Option2 = 1 << 1
, Option3 = 1 << 2
, Option4 = 1 << 3
};
const uint32_t Option1 = 1 << 0;
const uint32_t Option2 = 1 << 1;
const uint32_t Option3 = 1 << 2;
const uint32_t Option4 = 1 << 3;
//Enum BitFlags
BitFlags<Options> optionsEnum(Options::NoOption);
optionsEnum.set(Options::Option1 | Options::Option3);
//Standard integer BitFlags
BitFlags<uint32_t> optionsUint32(0);
optionsUint32.set(Option1 | Option3);
return 0;
}
Using 3dGrabber's solution:
public static T GetEnumeratedType<T>(this IEnumerable<T> _)
{
return default(T);
}
//and now
var list = new Dictionary<string, int>();
var stronglyTypedVar = list.GetEnumeratedType();
Solution with Jquery (first include this file): Replace multiple strings with multiple other strings:
var replacetext = {
"abc": "123",
"def": "456"
"ghi": "789"
};
$.each(replacetext, function(txtorig, txtnew) {
$(".eng-to-urd").each(function() {
$(this).text($(this).text().replace(txtorig, txtnew));
});
});
A simple and jQuery free solution:
document.querySelector('#elitable').onclick = function(ev) {
// ev.target <== td element
// ev.target.parentElement <== tr
var index = ev.target.parentElement.rowIndex;
}
Bonus: It works even if rows are added/removed dynamically
The underlying issue is using max-device-width
vs plain old max-width
.
Using the "device" keyword targets physical dimension of the screen, not the width of the browser window.
For example:
@media only screen and (max-device-width: 480px) {
/* STYLES HERE for DEVICES with physical max-screen width of 480px */
}
Versus
@media only screen and (max-width: 480px) {
/* STYLES HERE for BROWSER WINDOWS with a max-width of 480px.
This will work on desktops when the window is narrowed. */
}
Ok, finally found the solution.
Probably due to lack of experience with ReactJS and web development...
var Task = React.createClass({
render: function() {
var percentage = this.props.children + '%';
....
<div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
...
I created the percentage variable outside in the render function.
As suggested above the inclusion of
/usr/lib/openmpi/include
in the include path takes care of this (in my case)
Same way you'd hide anything: visibility: hidden;
Using CSS:
.button {_x000D_
display: block;_x000D_
width: 115px;_x000D_
height: 25px;_x000D_
background: #4E9CAF;_x000D_
padding: 10px;_x000D_
text-align: center;_x000D_
border-radius: 5px;_x000D_
color: white;_x000D_
font-weight: bold;_x000D_
line-height: 25px;_x000D_
}
_x000D_
<a class="button">Add Problem</a>
_x000D_
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
This worked for me
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
HTTP authorization does not differ between GET and POST requests, so I would first assume that something else is wrong. Instead of setting the Authorization header directly, I would suggest using the java.net.Authorization class, but I am not sure if it solves your problem. Perhaps your server is somehow configured to require a different authorization scheme than "basic" for post requests?
You can get the current route using
const currentRoute = this.props.routes[this.props.routes.length - 1];
...which gives you access to the props from the lowest-level active <Route ...>
component.
Given...
<Route path="childpath" component={ChildComponent} />
currentRoute.path
returns 'childpath'
and currentRoute.component
returns function _class() { ... }
.