I removed all the unused plugins in the pubspec.yaml and in the External Libraries to solve the problem.
You're mixing if statement with a ternary expression, that's why you're having a syntax error. It might be easier for you to understand what's going on if you extract mapping function outside of your render method:
renderItem = (id) => {
// just standard if statement
if (this.props.schema.collectionName.length < 0) {
return (
<Expandable>
<ObjectDisplay
key={id}
parentDocumentId={id}
schema={schema[this.props.schema.collectionName]}
value={this.props.collection.documents[id]}
/>
</Expandable>
);
}
return (
<h1>hejsan</h1>
);
}
Then just call it when mapping:
render() {
return (
<div>
<div className="box">
{
this.props.collection.ids
.filter(
id =>
// note: this is only passed when in top level of document
this.props.collection.documents[id][
this.props.schema.foreignKey
] === this.props.parentDocumentId
)
.map(this.renderItem)
}
</div>
</div>
)
}
Of course, you could have used the ternary expression as well, it's a matter of preference. What you use, however, affects the readability, so make sure to check different ways and tips to properly do conditional rendering in react and react native.
In case anyone is still looking for this functionality: I made an Android library that has this ability and much more, called ExpandableFab (https://github.com/nambicompany/expandable-fab).
The Material Design spec refers to this functionality as 'Speed Dial' and ExpandableFab implements it along with many additional features.
Nearly everything is customizable (colors, text, size, placement, margins, animations and more) and optional (don't need an Overlay, or FabOptions, or Labels, or icons, etc). Every property can be accessed or set through XML layouts or programmatically - whatever you prefer.
Written 100% in Kotlin but comes with full JavaDoc and KDoc (published API is well documented). Also comes with an example app so you can see different use cases with 0 coding.
Github: https://github.com/nambicompany/expandable-fab
Library website (w/ links to full documentation): https://nambicompany.github.io/expandable-fab/
Solved by using "http://jcenter.bintray.com/" instead of "https://jcenter.bintray.com/".
repositories {
jcenter( { url "http://jcenter.bintray.com/" } )
}
It is actually quite easy to do this, if you are using android.support.v7
library.
Declare a menu item
<item android:id="@+id/action_search"
android:title="Search"
android:icon="@drawable/abc_ic_search_api_mtrl_alpha"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView" />
Extend AppCompatActivity
and in the onCreateOptionsMenu
setup the SearchView.
import android.support.v7.widget.SearchView;
...
public class YourActivity extends AppCompatActivity {
...
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
// Retrieve the SearchView and plug it into SearchManager
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return true;
}
...
}
I am surprised that there's no concise answer yet, although such an expand/collapse animation is very easy to achieve with just 2 lines of code:
(recycler.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false // called once
together with
notifyItemChanged(position) // in adapter, whenever a child view in item's recycler gets hidden/shown
So for me, the explanations in the link below were really useful: https://medium.com/@nikola.jakshic/how-to-expand-collapse-items-in-recyclerview-49a648a403a6
<ul id="category-tabs">
<li><a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>
<ul>
<li><a href="javascript:void">item 1</a></li>
<li><a href="javascript:void">item 2</a></li>
<li><a href="javascript:void">item 3</a></li>
</ul>
</li> </ul>
//Jquery
$(document).ready(function() {
$('li').click(function() {
$('i').toggleClass('fa-plus-square fa-minus-square');
});
});
put your jquery function inside ready function for call click event:
$(document).ready(function() {
$("#ancherComplaint").click(function () {
alert($(this).attr("id"));
});
});
Use the id instead:
This is the easiest method that can handle even if the list is long:
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.list_item, null);
//Handle your items.
//StringHolder.mSelectedItem is a public static variable.
if(getItemId(position)==StringHolder.mSelectedItem){
rowView.setBackgroundColor(Color.LTGRAY);
}else{
rowView.setBackgroundColor(Color.TRANSPARENT);
}
return rowView;
}
And then in your onclicklistener:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
StringHolder.mSelectedItem = catagoryAdapter.getItemId(i-1);
catagoryAdapter.notifyDataSetChanged();
.....
listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);
You are clearing the list here and adding one element ("first"), the 1st reference of listOfSomething
is updated as well sonce both reference the same object, so when you access the second element myList.get(1)
(which does not exist anymore) you get the null.
Notice both collection.Add(listOfSomething);
save two references to the same arraylist object.
You need to create two different instances for two elements:
ArrayList<ArrayList<String>> collection = new ArrayList<ArrayList<String>>();
ArrayList<String> listOfSomething1 = new ArrayList<String>();
listOfSomething1.Add("first");
listOfSomething1.Add("second");
ArrayList<String> listOfSomething2 = new ArrayList<String>();
listOfSomething2.Add("first");
collection.Add(listOfSomething1);
collection.Add(listOfSomething2);
I attempted to use the toggleClass method to hide an item on my site (using visibility:hidden as opposed to display:none) with a slight animation, but for some reason the animation would not work (possibly due to an older version of jQuery UI).
The class was removed and added correctly, but the duration I added did not seem to make any difference - the item was simply added or removed with no effect.
So to resolve this I used a second class in my toggle method and applied a CSS transition instead:
The CSS:
.hidden{
visibility:hidden;
opacity: 0;
-moz-transition: opacity 1s, visibility 1.3s;
-webkit-transition: opacity 1s, visibility 1.3s;
-o-transition: opacity 1s, visibility 1.3s;
transition: opacity 1s, visibility 1.3s;
}
.shown{
visibility:visible;
opacity: 1;
-moz-transition: opacity 1s, visibility 1.3s;
-webkit-transition: opacity 1s, visibility 1.3s;
-o-transition: opacity 1s, visibility 1.3s;
transition: opacity 1s, visibility 1.3s;
}
The JS:
function showOrHide() {
$('#element').toggleClass("hidden shown");
}
Thanks @tomas.satinsky for the awesome (and super simple) answer on this post.
// -------------------------------------------------------------------------------
// tableView:viewForHeaderInSection:
// -------------------------------------------------------------------------------
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *mView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
[mView setBackgroundColor:[UIColor greenColor]];
UIImageView *logoView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 5, 20, 20)];
[logoView setImage:[UIImage imageNamed:@"carat.png"]];
[mView addSubview:logoView];
UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
[bt setFrame:CGRectMake(0, 0, 150, 30)];
[bt setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[bt setTag:section];
[bt.titleLabel setFont:[UIFont systemFontOfSize:20]];
[bt.titleLabel setTextAlignment:NSTextAlignmentCenter];
[bt.titleLabel setTextColor:[UIColor blackColor]];
[bt setTitle: @"More Info" forState: UIControlStateNormal];
[bt addTarget:self action:@selector(addCell:) forControlEvents:UIControlEventTouchUpInside];
[mView addSubview:bt];
return mView;
}
#pragma mark - Suppose you want to hide/show section 2... then
#pragma mark add or remove the section on toggle the section header for more info
- (void)addCell:(UIButton *)bt{
// If section of more information
if(bt.tag == 2) {
// Initially more info is close, if more info is open
if(ifOpen) {
DLog(@"close More info");
// Set height of section
heightOfSection = 0.0f;
// Reset the parameter that more info is closed now
ifOpen = NO;
}else {
// Set height of section
heightOfSection = 45.0f;
// Reset the parameter that more info is closed now
DLog(@"open more info again");
ifOpen = YES;
}
//[self.tableView reloadData];
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationFade];
}
}// end addCell
#pragma mark -
#pragma mark What will be the height of the section, Make it dynamic
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.section == 2) {
return heightOfSection;
}else {
return 45.0f;
}
// vKj
The webserver is returning an http 500 error code. These errors generally happen when an exception in thrown on the webserver and there's no logic to catch it so it spits out an http 500 error. You can usually resolve the problem by placing try-catch blocks in your code.
I had the same problem in my Test projects - I installed the latest EF6 bits via NuGet and everytime I invoke something EF-related I got:
The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' for the 'System.Data.SqlClient' ADO.NET provider could not be loaded. Make sure the provider assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.
My workaround: I placed this method inside my test project:
public void FixEfProviderServicesProblem()
{
//The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer'
//for the 'System.Data.SqlClient' ADO.NET provider could not be loaded.
//Make sure the provider assembly is available to the running application.
//See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.
var instance = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
}
This method is never been called, but I think the compiler will remove all "unnecessary" assemblies and without using the EntityFramework.SqlServer stuff the test fails.
Anyways: Works on my machine ;)
You can use yahoo's symbol lookup like so:
Where query is the company name.
You'll get something like this in return:
YAHOO.Finance.SymbolSuggest.ssCallback(
{
"ResultSet": {
"Query": "ya",
"Result": [
{
"symbol": "YHOO",
"name": "Yahoo! Inc.",
"exch": "NMS",
"type": "S",
"exchDisp": "NASDAQ"
},
{
"symbol": "AUY",
"name": "Yamana Gold, Inc.",
"exch": "NYQ",
"type": "S",
"exchDisp": "NYSE"
},
{
"symbol": "YZC",
"name": "Yanzhou Coal Mining Co. Ltd.",
"exch": "NYQ",
"type": "S",
"exchDisp": "NYSE"
},
{
"symbol": "YRI.TO",
"name": "YAMANA GOLD INC COM NPV",
"exch": "TOR",
"type": "S",
"exchDisp": "Toronto"
},
{
"symbol": "8046.TW",
"name": "NAN YA PRINTED CIR TWD10",
"exch": "TAI",
"type": "S",
"exchDisp": "Taiwan"
},
{
"symbol": "600319.SS",
"name": "WEIFANG YAXING CHE 'A'CNY1",
"exch": "SHH",
"type": "S",
"exchDisp": "Shanghai"
},
{
"symbol": "1991.HK",
"name": "TA YANG GROUP",
"exch": "HKG",
"type": "S",
"exchDisp": "Hong Kong"
},
{
"symbol": "1303.TW",
"name": "NAN YA PLASTIC TWD10",
"exch": "TAI",
"type": "S",
"exchDisp": "Taiwan"
},
{
"symbol": "0294.HK",
"name": "YANGTZEKIANG",
"exch": "HKG",
"type": "S",
"exchDisp": "Hong Kong"
},
{
"symbol": "YAVY",
"name": "Yadkin Valley Financial Corp.",
"exch": "NMS",
"type": "S",
"exchDisp": "NASDAQ"
}
]
}
}
)
Which is JSON and very easy to work with.
Hush... don't tell anybody.
<script type="text/javascript">
function showDiv(toggle){
document.getElementById(toggle).style.display = 'block';
}
</script>
<input type="button" name="answer" onclick="showDiv('toggle')">Show</input>
<div id="toggle" style="display:none">Hello</div>
There are better and more secure ways to make sure that all your traffic goes over https
. For example setting up two virtual hosts and redirecting all traffic from your http
to your https
host. Read more on this in this answer here on security.stackexchange.com.
With setting up a virtual host for redirecting you can send a 301 status (redirect permanently) so the browser understands that all the following requests should be sent to the https server where it was redirected to. Hence no further http requests will be made after the first redirect response.
You should also carefully check the given answers because with the wrong rewrite rules set you might loose the query params from your incoming requests.
I am a VIMer. I can do some rare Hex edits with:
:%!xxd
to switch into hex mode
:%!xxd -r
to exit from hex mode
But I strongly recommend ht
apt-cache show ht
Package: ht
Version: 2.0.18-1
Installed-Size: 1780
Maintainer: Alexander Reichle-Schmehl <[email protected]>
Homepage: http://hte.sourceforge.net/
Note: The package is called ht
, whereas the executable is named hte
after the package was installed.
On the confirmation page, don't put the content in editable controls, just write them to the page.
Make sure to learn from the padding oracle asp.net vulnerability that just happened (you applied the patch, right? ...) and use protected sections to encrypt the machine key and any other sensitive configuration.
An alternative option is to set it in the machine level web.config, so its not even in the web site folder.
To generate it do it just like the linked article in David's answer.
It's a ProgressDialog, with setIndeterminate(true).
From http://developer.android.com/guide/topics/ui/dialogs.html#ProgressDialog
ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "",
"Loading. Please wait...", true);
An indeterminate progress bar doesn't actually show a bar, it shows a spinning activity circle thing. I'm sure you know what I mean :)
the bottom cell will grow as you enter more text ... setting the table width will help too
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<table id="content" style="min-height:525px; height:525px; width:100%; border:0px; margin:0; padding:0; border-collapse:collapse;">
<tr><td style="height:10px; background-color:#900;">Upper</td></tr>
<tr><td style="min-height:515px; height:515px; background-color:#909;">lower<br/>
</td></tr>
</table>
</body>
</html>
NUL
in Windows seems to be actually a virtual path in any folder. Just like ..
, .
in any filesystem.
Use any folder followed with NUL will work.
Example,
echo 1 > nul
echo 1 > c:\nul
echo 1 > c:\users\nul
echo 1 > c:\windows\nul
have the same effect as /dev/null
on Linux.
This was tested on Windows 7, 64 bit.
You can also simply try this
type file2.txt >> file1.txt
It will append the content of file2.txt at the end of file1.txt
If you need original file1.txt, take a backup beforehand. Or you can do this
type file1.txt > out.txt
type file2.txt >> out.txt
If you want to have a line break at the end of the first file, you can try the following command before appending.
type file1.txt > out.txt
printf "\n" >> out.txt
type file2.txt >> out.txt
If you just want to make some modification to files or inspect processes, here's one another solution you probably want.
You could run the following command to execute a new process from the existing container:
sudo docker exec -ti [CONTAINER-ID] bash
will start a new process with bash shell, and you could escape from it by Ctrl+C directly, it won't affect the original process.
If you broke the tree but didn't commit the code, you can use git reset
, and if you just want to restore one file, you can use git checkout
.
If you broke the tree and committed the code, you can use git revert HEAD
.
http://book.git-scm.com/4_undoing_in_git_-_reset,_checkout_and_revert.html
Just set this extra line in catalina.bat
file
LINE NO AROUND: 143
set "CATALINA_OPTS=-Xms512m -Xmx512m"
And restart Tomcat service
You could use \r\n
, or System.Environment.NewLine
.
Move your image in the (hi-res) drawable to drawable-xxhdpi. But in app development, you do not need to use large image. It will increase your APK file size.
YOu can also rewrite it like this
FROM Resource r WHERE r.ResourceNo IN
(
SELECT m.ResourceNo FROM JobMember m
JOIN Job j ON j.JobNo = m.JobNo
WHERE j.ProjectManagerNo = @UserResourceNo
OR
j.AlternateProjectManagerNo = @UserResourceNo
Union All
SELECT m.ResourceNo FROM JobMember m
JOIN JobTask t ON t.JobTaskNo = m.JobTaskNo
WHERE t.TaskManagerNo = @UserResourceNo
OR
t.AlternateTaskManagerNo = @UserResourceNo
)
Also a return table is expected in your RETURN statement
The runtime type of the object is a relatively arbitrary condition to filter on. I suggest keeping such muckiness away from your collection. This is simply achieved by having your collection delegate to a filter passed in a construction.
public interface FilterObject {
boolean isAllowed(Object obj);
}
public class FilterOptimizedList<E> implements List<E> {
private final FilterObject filter;
...
public FilterOptimizedList(FilterObject filter) {
if (filter == null) {
throw NullPointerException();
}
this.filter = filter;
}
...
public int indexOf(Object obj) {
if (!filter.isAllows(obj)) {
return -1;
}
...
}
...
}
final List<String> longStrs = new FilterOptimizedList<String>(
new FilterObject() { public boolean isAllowed(Object obj) {
if (obj == null) {
return true;
} else if (obj instanceof String) {
String str = (String)str;
return str.length() > = 4;
} else {
return false;
}
}}
);
Unless you want to talk to an SMTP server directly via telnet
you'd use commandline mailers like blat
:
blat -to [email protected] -f [email protected] -s "mail subject" ^
-server smtp.example.net -body "message text"
or bmail
:
bmail -s smtp.example.net -t [email protected] -f [email protected] -h ^
-a "mail subject" -b "message text"
You could also write your own mailer in VBScript or PowerShell.
Go to installed mysql path and find bin folder,open my.ini and search 3306 after that change 3306 to 3360
using json.loads
will turn your data into a python dictionary.
Dictionaries values are accessed using ['key']
resp_str = {
"name" : "ns1:timeSeriesResponseType",
"declaredType" : "org.cuahsi.waterml.TimeSeriesResponseType",
"scope" : "javax.xml.bind.JAXBElement$GlobalScope",
"value" : {
"queryInfo" : {
"creationTime" : 1349724919000,
"queryURL" : "http://waterservices.usgs.gov/nwis/iv/",
"criteria" : {
"locationParam" : "[ALL:103232434]",
"variableParam" : "[00060, 00065]"
},
"note" : [ {
"value" : "[ALL:103232434]",
"title" : "filter:sites"
}, {
"value" : "[mode=LATEST, modifiedSince=null]",
"title" : "filter:timeRange"
}, {
"value" : "sdas01",
"title" : "server"
} ]
}
},
"nil" : false,
"globalScope" : true,
"typeSubstituted" : false
}
would translate into a python diction
resp_dict = json.loads(resp_str)
resp_dict['name'] # "ns1:timeSeriesResponseType"
resp_dict['value']['queryInfo']['creationTime'] # 1349724919000
Maybe you can take a look at closure in JavaScript. Here is a working solution:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Test</title>_x000D_
</head>_x000D_
<body>_x000D_
<p class="button">Button 0</p>_x000D_
<p class="button">Button 1</p>_x000D_
<p class="button">Button 2</p>_x000D_
<script>_x000D_
var buttons = document.getElementsByClassName('button');_x000D_
for (var i=0 ; i < buttons.length ; i++){_x000D_
(function(index){_x000D_
buttons[index].onclick = function(){_x000D_
alert("I am button " + index);_x000D_
};_x000D_
})(i)_x000D_
}_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
This has served me well for a while now. It prints error or warning messages in red, one line per parameter, and allows an optional exit code.
# Custom errors
EX_UNKNOWN=1
warning()
{
# Output warning messages
# Color the output red if it's an interactive terminal
# @param $1...: Messages
test -t 1 && tput setf 4
printf '%s\n' "$@" >&2
test -t 1 && tput sgr0 # Reset terminal
true
}
error()
{
# Output error messages with optional exit code
# @param $1...: Messages
# @param $N: Exit code (optional)
messages=( "$@" )
# If the last parameter is a number, it's not part of the messages
last_parameter="${messages[@]: -1}"
if [[ "$last_parameter" =~ ^[0-9]*$ ]]
then
exit_code=$last_parameter
unset messages[$((${#messages[@]} - 1))]
fi
warning "${messages[@]}"
exit ${exit_code:-$EX_UNKNOWN}
}
I was looking for the same thing when I came here, but the lack of a generic "upsert" function botherd me a bit so I thought you could just pass the update and insert sql as arguments on that function form the manual
that would look like this:
CREATE FUNCTION upsert (sql_update TEXT, sql_insert TEXT)
RETURNS VOID
LANGUAGE plpgsql
AS $$
BEGIN
LOOP
-- first try to update
EXECUTE sql_update;
-- check if the row is found
IF FOUND THEN
RETURN;
END IF;
-- not found so insert the row
BEGIN
EXECUTE sql_insert;
RETURN;
EXCEPTION WHEN unique_violation THEN
-- do nothing and loop
END;
END LOOP;
END;
$$;
and perhaps to do what you initially wanted to do, batch "upsert", you could use Tcl to split the sql_update and loop the individual updates, the preformance hit will be very small see http://archives.postgresql.org/pgsql-performance/2006-04/msg00557.php
the highest cost is executing the query from your code, on the database side the execution cost is much smaller
Use .net 4 BlockingCollection, to enqueue use Add(), to dequeue use Take(). It internally uses non-blocking ConcurrentQueue. More info here Fast and Best Producer/consumer queue technique BlockingCollection vs concurrent Queue
From the definition in objc.h
:
#if (TARGET_OS_IPHONE && __LP64__) || TARGET_OS_WATCH
typedef bool BOOL;
#else
typedef signed char BOOL;
// BOOL is explicitly signed so @encode(BOOL) == "c" rather than "C"
// even if -funsigned-char is used.
#endif
#define YES ((BOOL)1)
#define NO ((BOOL)0)
So, yes, you can assume that BOOL is a char. You can use the (C99) bool
type, but all of Apple's Objective-C frameworks and most Objective-C/Cocoa code uses BOOL, so you'll save yourself headache if the typedef ever changes by just using BOOL.
Below section add in to your web.config
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json"
publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
Use List<T>.Insert(0, item)
or a LinkedList<T>.AddFirst()
.
This may not be possible with cat
. Is there a reason you have to use cat
?
If you simply need to do it with a bash command, this should work for you:
head -n 1 file.txt
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Email Validation</h2>
<input id="textEmail">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo" style="color: red;"></p>
<script>
function myFunction() {
var email;
email = document.getElementById("textEmail").value;
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(textEmail.value) == false)
{
document.getElementById("demo").style.color = "red";
document.getElementById("demo").innerHTML ="Invalid EMail ->"+ email;
alert('Invalid Email Address ->'+email);
return false;
} else{
document.getElementById("demo").style.color = "DarkGreen";
document.getElementById("demo").innerHTML ="Valid Email ->"+email;
}
return true;
}
</script>
</body>
</html>
handle = open(path.rstrip("/") + "/" + filename.lstrip("/"), 'wb')
ftp.retrbinary('RETR %s' % filename, handle.write)
ok, try to go to the home "user@user:~$ " (cd + enter key), and npm install -g your your_module.
@csharptest.net's and Christian Gollhardt's answers are great, thank you very much. But after running this code on production with millions of record, I discovered there is a memory leak. RNGCryptoServiceProvider and Rfc2898DeriveBytes classes are derived from IDisposable but we don't dispose of them. I will write my solution as an answer if someone needs with disposed version.
public static class SecurePasswordHasher
{
/// <summary>
/// Size of salt.
/// </summary>
private const int SaltSize = 16;
/// <summary>
/// Size of hash.
/// </summary>
private const int HashSize = 20;
/// <summary>
/// Creates a hash from a password.
/// </summary>
/// <param name="password">The password.</param>
/// <param name="iterations">Number of iterations.</param>
/// <returns>The hash.</returns>
public static string Hash(string password, int iterations)
{
// Create salt
using (var rng = new RNGCryptoServiceProvider())
{
byte[] salt;
rng.GetBytes(salt = new byte[SaltSize]);
using (var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations))
{
var hash = pbkdf2.GetBytes(HashSize);
// Combine salt and hash
var hashBytes = new byte[SaltSize + HashSize];
Array.Copy(salt, 0, hashBytes, 0, SaltSize);
Array.Copy(hash, 0, hashBytes, SaltSize, HashSize);
// Convert to base64
var base64Hash = Convert.ToBase64String(hashBytes);
// Format hash with extra information
return $"$HASH|V1${iterations}${base64Hash}";
}
}
}
/// <summary>
/// Creates a hash from a password with 10000 iterations
/// </summary>
/// <param name="password">The password.</param>
/// <returns>The hash.</returns>
public static string Hash(string password)
{
return Hash(password, 10000);
}
/// <summary>
/// Checks if hash is supported.
/// </summary>
/// <param name="hashString">The hash.</param>
/// <returns>Is supported?</returns>
public static bool IsHashSupported(string hashString)
{
return hashString.Contains("HASH|V1$");
}
/// <summary>
/// Verifies a password against a hash.
/// </summary>
/// <param name="password">The password.</param>
/// <param name="hashedPassword">The hash.</param>
/// <returns>Could be verified?</returns>
public static bool Verify(string password, string hashedPassword)
{
// Check hash
if (!IsHashSupported(hashedPassword))
{
throw new NotSupportedException("The hashtype is not supported");
}
// Extract iteration and Base64 string
var splittedHashString = hashedPassword.Replace("$HASH|V1$", "").Split('$');
var iterations = int.Parse(splittedHashString[0]);
var base64Hash = splittedHashString[1];
// Get hash bytes
var hashBytes = Convert.FromBase64String(base64Hash);
// Get salt
var salt = new byte[SaltSize];
Array.Copy(hashBytes, 0, salt, 0, SaltSize);
// Create hash with given salt
using (var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations))
{
byte[] hash = pbkdf2.GetBytes(HashSize);
// Get result
for (var i = 0; i < HashSize; i++)
{
if (hashBytes[i + SaltSize] != hash[i])
{
return false;
}
}
return true;
}
}
}
Usage:
// Hash
var hash = SecurePasswordHasher.Hash("mypassword");
// Verify
var result = SecurePasswordHasher.Verify("mypassword", hash);
Following is the solution which I came up with if there are multiple characters in the string all having the highest frequency.
mystr = input("enter string: ")
#define dictionary to store characters and their frequencies
mydict = {}
#get the unique characters
unique_chars = sorted(set(mystr),key = mystr.index)
#store the characters and their respective frequencies in the dictionary
for c in unique_chars:
ctr = 0
for d in mystr:
if d != " " and d == c:
ctr = ctr + 1
mydict[c] = ctr
print(mydict)
#store the maximum frequency
max_freq = max(mydict.values())
print("the highest frequency of occurence: ",max_freq)
#print all characters with highest frequency
print("the characters are:")
for k,v in mydict.items():
if v == max_freq:
print(k)
Input: "hello people"
Output:
{'o': 2, 'p': 2, 'h': 1, ' ': 0, 'e': 3, 'l': 3}
the highest frequency of occurence: 3
the characters are:
e
l
Granted that any image the user can see will be able to be saved on the computer and there is nothing you can do about it. Now if you want to block access to other images that the user is not supposed to see, I am actually doing it that way:
Benefit:
Drawback:
tell you the true, I still don't get what you need, but
window.location(url);
should be
window.location = url;
a search on window.location reference will tell you that.
Your ''.join()
expression is filtering, removing anything non-ASCII; you could use a conditional expression instead:
return ''.join([i if ord(i) < 128 else ' ' for i in text])
This handles characters one by one and would still use one space per character replaced.
Your regular expression should just replace consecutive non-ASCII characters with a space:
re.sub(r'[^\x00-\x7F]+',' ', text)
Note the +
there.
var date = new Date();
document.getElementById("date").value = date.getFullYear() + "-" + (date.getMonth()<10?'0':'') + (date.getMonth() + 1) + "-" + (date.getDate()<10?'0':'') + date.getDate();
document.getElementById("hour").value = (date.getHours()<10?'0':'') + date.getHours() + ":" + (date.getMinutes()<10?'0':'') + date.getMinutes();
The problem is that your controller expect a parameter hasId=false or hasId=true, but you are not passing that. Your hidden field has the id hasId but is passed as hasCustomerName, so no mapping matches.
Either change the path of the hidden field to hasId or the mapping parameter to expect hasCustomerName=true or hasCustomerName=false.
By default the field delimiter is non-blank to blank transition so tab should work just fine.
However, the columns are indexed base 1 and base 0 so you probably want
sort -k4nr file.txt
to sort file.txt by column 4 numerically in reverse order. (Though the data in the question has even 5 fields so the last field would be index 5.)
You can use this outside activities - all you need is to provide a Context
:
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
Then to retrieve your different widgets, you inflate a layout:
View view = inflater.inflate( R.layout.myNewInflatedLayout, null );
Button myButton = (Button) view.findViewById( R.id.myButton );
EDIT as of July 2014
Davide's answer on how to get the LayoutInflater
is actually more correct than mine (which is still valid though).
I think your code is trying to "divide by zero" or "divide by NaN". If you are aware of that and don't want it to bother you, then you can try:
import numpy as np
np.seterr(divide='ignore', invalid='ignore')
For more details see:
Well you understood it partially. You have to tailor the beans according to your need and inform Spring container to manage it when required, by using a methodology populalrly known as IoC (Inversion of Control) coined by Martin Fowler, also known as Dependency Injection (DI).
You wire the beans in a way, so that you do not have to take care of the instantiating or evaluate any dependency on the bean. This is popularly known as Hollywood Principle.
Google is the best tool to explore more on this in addition to the links you would get flooded with here in this question. :)
In fact a string constant literal is neither a const char * nor a char* but a char[]. Its quite strange but written down in the c++ specifications; If you modify it the behavior is undefined because the compiler may store it in the code segment.
Can you show code which you use for setting date object? Anyway< you can use this code for intialisation of date:
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2011-01-01 00:00:00")
the Jquery append function returns a jQuery object so you can just tag a method on the end
$("#root").append(child).anotherJqueryMethod();
None of the other answers worked for me. But doing this did:
When I did this Eclipse added an import into one of my classes. I think this occurred because I saved my project with a missing import, probably rushing to get home after work.
@Ahmed
Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".
Sub test()
dbWb = Application.ActiveWorkbook.FullName
dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2" 'Data2 is a named range
sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command
dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon
dbCommand.CommandText = sCommand
dbCommand.Execute
dbCon.Close
End Sub
For me it was Package.json it was empty from dependencies even though i thought i did install them.. so I had to reinstall them with --save option in the end and verify they were added to the package.json.. and then push it again and it worked.
This seems to be what you're looking for:
g <- ggplot(x, aes(reorder(variable, value), value))
g + geom_bar() + scale_y_continuous(formatter="percent") + coord_flip()
The reorder()
function will reorder your x axis items according to the value
of variable
.
The entity
produces a non-breaking space, which is used when you don't want an automatic line break at that position. The regular space has the character code 32, while the non-breaking space has the character code 160.
For example when you display numbers with space as thousands separator: 1 234 567, then you use non-breaking spaces so that the number can't be split on separate lines. If you display currency and there is a space between the amount and the currency: 42 SEK, then you use a non-breaking space so that you don't get the amount on one line and the currency on the next.
Using the constraints
features UniqueConstraint
is preferred over unique_together.
From the Django documentation for unique_together
:
Use UniqueConstraint with the constraints option instead.
UniqueConstraint provides more functionality than unique_together.
unique_together may be deprecated in the future.
For example:
class Volume(models.Model):
id = models.AutoField(primary_key=True)
journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name="Journal")
volume_number = models.CharField('Volume Number', max_length=100)
comments = models.TextField('Comments', max_length=4000, blank=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=['journal_id', 'volume_number'], name='name of constraint')
]
I had met a similar problem, after i add a scope property of servlet dependency in pom.xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
Then it was ok . maybe that will help you.
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.
You can delete the features folder just like any other in your checkout then commit the change.
To prevent this in the future I suggest you follow the naming conventions for SVN layout.
Either give each project a trunk, branches, tags folder when they are created.
svn
+ project1
+ trunk
+ src
+ etc...
+ branches
+ features
+ src
+ etc...
+ tags
+ project2
+ trunk
+ branches
+ tags
I have tried the below code and its working fine?.
execute the cmd to set new size.
set NODE_OPTIONS=--max_old_space_size=8172
Or you can check the link for more info https://github.com/nodejs/node/issues/10137#issuecomment-487255987
var test = parseInt($("#testid").val());
add this line to your ‘gradle.properties’
android.injected.testOnly=false
Here, you have two options to do this :-
1.You can use the unary plus to convert string number into integer.
2.You can also achieve this via parsing the number into corresponding type. i.e parseInt(), parseFloat() etc
.
Now I am going to show you here with the help of examples(Find the sum of two numbers).
Using unary plus operator
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");//prompt will always return string value
var y = prompt("Please enter the second nubmer.");
var z = +x + +y;
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
Using parsing approach-
<!DOCTYPE html>
<html>
<body>
<H1>Program for sum of two numbers.</H1>
<p id="myId"></p>
<script>
var x = prompt("Please enter the first number.");
var y = prompt("Please enter the second number.");
var z = parseInt(x) + parseInt(y);
document.getElementById("myId").innerHTML ="Sum of "+x+" and "+y+" is "+z;
</script>
</body>
</html>
If you set display:
to inline-block
, block
, flex
, ..., on the element with no content, then
For min-width
to take effect on a tag with no content, you only need to apply padding for either top or bot.
For min-height
to take effect on a tag with no content, you only need to apply padding for left or right.
I was facing the similar type of issue: Code Snippet :
<c:forEach items="${orderList}" var="xx">
${xx.id} <br>
</c:forEach>
There was a space after orderlist like this : "${orderList} " because of which the xx variable was getting coverted into String and was not able to call xx.id.
So make sure about space. They play crucial role sometimes. :p
By default, on many platforms the short will be aligned to an offset at a multiple of 2, so there will be a padding byte added after the char.
To disable this, use: struct.unpack("=BH", data)
. This will use standard alignment, which doesn't add padding:
>>> struct.calcsize('=BH')
3
The =
character will use native byte ordering. You can also use <
or >
instead of =
to force little-endian or big-endian byte ordering, respectively.
If you want to pass a method of a class as an argument but don't yet have the object on which you are going to call it, you can simply pass the object once you have it as the first argument (i.e. the "self" argument).
class FooBar:
def __init__(self, prefix):
self.prefix = prefix
def foo(self, name):
print "%s %s" % (self.prefix, name)
def bar(some_method):
foobar = FooBar("Hello")
some_method(foobar, "World")
bar(FooBar.foo)
This will print "Hello World"
I was having the same issue in Workbench plus insert query from C# application. In my case using ISO format solve the issue
string value = date.ToString("yyyy-MM-dd HH:mm:ss");
Both do different things.
The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }
) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;
The second creates an object with dynamic storage duration and allows two things:
Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete
;
Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)
Neither is preferred; it depends on what you're doing as to which is most appropriate.
Use the former unless you need to use the latter.
Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.
Good luck.
Your original code is broken, as it delete
s a char
array that it did not new
. In fact, nothing new
d the C-style string; it came from a string literal. delete
ing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).
Usually an object should not have the responsibility of delete
ing anything that it didn't itself new
. This behaviour should be well-documented. In this case, the rule is being completely broken.
(Edited to include commenter's good additions:)
D
or its equivalent d$
will delete the rest of the line and leave you in command mode. C
or c$
will delete the rest of the line and put you in insert mode, and new text will be appended to the line.
This is part of vitutor
and vimtutor
, excellent "reads" for vim beginners.
This has support for both title and image.
For iOS 11 and afterwards:
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let action = UIContextualAction(
style: .normal,
title: "My Title",
handler: { (action, view, completion) in
//do what you want here
completion(true)
})
action.image = UIImage(named: "My Image")
action.backgroundColor = .red
let configuration = UISwipeActionsConfiguration(actions: [action])
configuration.performsFirstActionWithFullSwipe = false
return configuration
}
Also, similar method is available for leadingSwipeActions
Source:
https://developer.apple.com/videos/play/wwdc2017/201/ (Talks about this at around 16 mins time) https://developer.apple.com/videos/play/wwdc2017/204/ (Talks about this at around 23 mins time)
According to the android docs view alpha is a value between 0 and 1. So to set it use something like this:
View v;
v.setAlpha(.5f);
it works
first use: git reflog
find your SHA of your previus state and make (HEAD@{1} is an example)
git reset --hard HEAD@{1}
The shorter ones are vectorized, meaning they can return a vector, like this:
((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE TRUE FALSE FALSE
The longer form evaluates left to right examining only the first element of each vector, so the above gives
((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE
As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."
So you want to use the long forms only when you are certain the vectors are length one.
You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all
and any
to reduce it to length one for use in control flow statements, like if
.
The functions all
and any
are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse
.
One final difference: the &&
and ||
only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a
; if it didn't short-circuit, as &
and |
don't, it would give an error.
a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found
Finally, see section 8.2.17 in The R Inferno, titled "and and andand".
If you have your text in your_text
variable, you can use:
your_text[0..29]
Maybe what comes from the server is already evaluated as JSON object? For example, using jQuery get method:
$.get('/service', function(data) {
var obj = data;
/*
"obj" is evaluated at this point if server responded
with "application/json" or similar.
*/
for (var i = 0; i < obj.length; i++) {
console.log(obj[i].Name);
}
});
Alternatively, if you need to turn JSON object into JSON string literal, you can use JSON.stringify
:
var json = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
var jsonString = JSON.stringify(json);
But in this case I don't understand why you can't just take the json
variable and refer to it instead of stringifying and parsing.
you can use the following SQL statement to check the given column on table was indexed or not
select a.table_schema, a.table_name, a.column_name, index_name
from information_schema.columns a
join information_schema.tables b on a.table_schema = b.table_schema and
a.table_name = b.table_name and
b.table_type = 'BASE TABLE'
left join (
select concat(x.name, '/', y.name) full_path_schema, y.name index_name
FROM information_schema.INNODB_SYS_TABLES as x
JOIN information_schema.INNODB_SYS_INDEXES as y on x.TABLE_ID = y.TABLE_ID
WHERE x.name = 'your_schema'
and y.name = 'your_column') d on concat(a.table_schema, '/', a.table_name, '/', a.column_name) = d.full_path_schema
where a.table_schema = 'your_schema'
and a.column_name = 'your_column'
order by a.table_schema, a.table_name;
since the joins are against INNODB_SYS_*, so the match indexes only came from INNODB tables only
Not sure if this is the best way, but you could always do this:
Foo.instance_methods.include? 'bar'
I just went through this and configured it with the following:
Ubuntu 16.04
Tomcat 8.5.9
Apache2.4.25
APR 1.5.2
Tomcat-native 1.2.10
Java 8
These are the steps i used based on the older posts here:
sudo apt-get update
sudo apt-get install libtcnative-1
sudo apt-get install make
sudo apt-get install gcc
sudo apt-get install openssl
sudo apt-get install libssl-dev
cd /opt/tomcat/bin
sudo wget http://apache.mirror.anlx.net//apr/apr-1.5.2.tar.gz
sudo tar -xzvf apr-1.5.2.tar.gz
cd apr-1.5.2
sudo ./configure
sudo make
sudo make install
cd /usr/local/apr/lib/
ls
libapr-1.la
cd /opt/tomcat/bin
sudo wget https://archive.apache.org/dist/tomcat/tomcat-connectors/native/1.2.10/source/tomcat-native-1.2.10-src.tar.gz
sudo tar -xzvf tomcat-native-1.2.10-src.tar.gz
cd tomcat-native-1.2.10-src/native
sudo pico ~/.bashrc
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
source ~/.bashrc
sudo ./configure --with-apr=/usr/local/apr --with-java-home=$JAVA_HOME
sudo make
sudo make install
sudo pico /opt/tomcat/bin/setenv.sh
export LD_LIBRARY_PATH='$LD_LIBRARY_PATH:/usr/local/apr/lib'
sudo service tomcat restart
This question is confusing. A regular object, {}
doesn't have a length
property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).
Meaning, you have to get the "length" by a for..in
statement on the object, since length
is not set, and increment a counter.
I'm confused as to why you need the length
. Are you manually setting 0
on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';
. If the latter, again, why the need for length?
Edit #1: Why can't you just do this?
list = [ {name:'john'}, {name:'bob'} ];
Then iterate over list? The length
is already set.
Just do this
<button OnClick=" location.href='link.html' ">Visit Page Now</button>
Although, it's been a while since I've touched JavaScript - maybe location.href
is outdated? Anyways, that's how I would do it.
If you dont care about the aspect ration (i.e you want to force the image to a particular dimension), here is a simplified answer
// for jpg
function resize_imagejpg($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
// for png
function resize_imagepng($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefrompng($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
// for gif
function resize_imagegif($file, $w, $h) {
list($width, $height) = getimagesize($file);
$src = imagecreatefromgif($file);
$dst = imagecreatetruecolor($w, $h);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
return $dst;
}
Now let's handle the upload part. First step, upload the file to your desired directory. Then called one of the above functions based on file type (jpg, png or gif) and pass the absolute path of your uploaded file as below:
// jpg change the dimension 750, 450 to your desired values
$img = resize_imagejpg('path/image.jpg', 750, 450);
The return value $img
is a resource object. We can save to a new location or override the original as below:
// again for jpg
imagejpeg($img, 'path/newimage.jpg');
Hope this helps someone. Check these links for more on resizing Imagick::resizeImage and imagejpeg()
Python trim
method is called strip
:
str.strip() #trim
str.lstrip() #ltrim
str.rstrip() #rtrim
Usually this happens if something is wrong with the byte array.
File.WriteAllBytes("filename.PDF", Byte[]);
This creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
Asynchronous implementation of this is also available.
public static System.Threading.Tasks.Task WriteAllBytesAsync
(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = null);
You can use Theme.applyStyle to modify your theme at runtime by applying another style to it.
Let's say you have these style definitions:
<style name="DefaultTheme" parent="Theme.AppCompat.Light">
<item name="colorPrimary">@color/md_lime_500</item>
<item name="colorPrimaryDark">@color/md_lime_700</item>
<item name="colorAccent">@color/md_amber_A400</item>
</style>
<style name="OverlayPrimaryColorRed">
<item name="colorPrimary">@color/md_red_500</item>
<item name="colorPrimaryDark">@color/md_red_700</item>
</style>
<style name="OverlayPrimaryColorGreen">
<item name="colorPrimary">@color/md_green_500</item>
<item name="colorPrimaryDark">@color/md_green_700</item>
</style>
<style name="OverlayPrimaryColorBlue">
<item name="colorPrimary">@color/md_blue_500</item>
<item name="colorPrimaryDark">@color/md_blue_700</item>
</style>
Now you can patch your theme at runtime like so:
getTheme().applyStyle(R.style.OverlayPrimaryColorGreen, true);
The method applyStyle
has to be called before the layout gets inflated! So unless you load the view manually you should apply styles to the theme before calling setContentView
in your activity.
Of course this cannot be used to specify an arbitrary color, i.e. one out of 16 million (2563) colors. But if you write a small program that generates the style definitions and the Java code for you then something like one out of 512 (83) should be possible.
What makes this interesting is that you can use different style overlays for different aspects of your theme. Just add a few overlay definitions for colorAccent
for example. Now you can combine different values for primary color and accent color almost arbitrarily.
You should make sure that your overlay theme definitions don't accidentally inherit a bunch of style definitions from a parent style definition. For example a style called AppTheme.OverlayRed
implicitly inherits all styles defined in AppTheme
and all these definitions will also be applied when you patch the master theme. So either avoid dots in the overlay theme names or use something like Overlay.Red
and define Overlay
as an empty style.
Query would be like this:
SELECT ID, AccountID, Quantity,
SUM(Quantity) OVER (PARTITION BY AccountID ) AS TopBorcT
FROM #Empl ORDER BY AccountID
Partition by works like group by. Here we are grouping by AccountID so sum would be corresponding to AccountID.
First first case, AccountID = 1 , then sum(quantity) = 10 + 5 + 2 => 17 & For AccountID = 2, then sum(Quantity) = 7+3 => 10
so result would appear like attached snapshot.
You should also consider using libraries to do that: they allow limiting and much more:
FineUploader. Demo using validation.itemLimit
as of 5.16.2:
var restrictedUploader = new qq.FineUploader({
validation: {
itemLimit: 3,
}
});
bluimp's jQuery File Upload Plugin. Usage: jquery file upload restricting number of files using maxNumberOfFiles
as of v9.22.0:
$('#fileuploadbasic').fileupload({
maxNumberOfFiles: 6
});
They are also available at https://cdnjs.com/
If you are looking for a one liner (not including designations and comments) try this
Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("Name")
'find first empty cell in column F (coming up from the bottom) and return row number
iRow = ws.Range("F:F").Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
i found this way useful also.
import tkinter.filedialog
from_filename = tkinter.filedialog.askopenfilename()
here a window will appear so you can browse till you find the file , you click on it then you can continue using open , and read .
from_file = open(from_filename, 'r')
contents = from_file.read()
contents
Building on previous answers, I think it's a perfect use case for doing it (simple) context manager style:
import sys
class StdoutRedirection:
"""Standard output redirection context manager"""
def __init__(self, path):
self._path = path
def __enter__(self):
sys.stdout = open(self._path, mode="w")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout.close()
sys.stdout = sys.__stdout__
and then:
with StdoutRedirection("path/to/file"):
print("Hello world")
Also it would be really easy to add some functionality to StdoutRedirection
class (e.g. a method that lets you change the path)
Updating the ~/.profile
or ~/.bash_profile
does not work sometimes. I just deleted JDK 6 and source
d .bash_profile
.
Try running this:
sudo rm -rd jdk1.6.0_* #it may not let you delete without sudo
Then, modify/add your JAVA_HOME and PATH variables.
source ~/.bash_profile #assuming you've updated $JAVA_HOME and $PATH
Here's another difference. I will... buy you a beer if you can explain the reasoning or reason as to this state of affairs:
enum Foo { a = 'a', b = 'b' }
type TFoo = {
[k in Foo]: boolean;
}
const foo1: TFoo = { a: true, b: false} // good
// const foo2: TFoo = { a: true } // bad: missing b
// const foo3: TFoo = { a: true, b: 0} // bad: b is not a boolean
// So type does roughly what I'd expect and want
interface IFoo {
// [k in Foo]: boolean;
/*
Uncommenting the above line gives the following errors:
A computed property name in an interface must refer to an expression whose type is a
literal type or a 'unique symbol' type.
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
Cannot find name 'k'.
*/
}
// ???
This sort of makes me want to say the hell with interfaces unless I'm intentionally implementing some OOP design pattern, or require merging as described above (which I'd never do unless I had a very good reason for it).
A simple EXISTS clause is cleanest
select *
from table1 t1
WHERE
EXISTS
(
Select * --or 1. No difference...
From CRM_VCM_CURRENT_LEAD_STATUS Ex
Where Lead_Key = :_Lead_Key
-- correlation here...
AND
t1.CM_PLAN_ID = Ex.CM_PLAN_ID AND t1.CM_PLAN_ID = Ex.Individual_ID
)
If you have multiple rows in the correlation then a JOIN gives multiple rows in the output, so you'd need distinct. Which usually makes the EXISTS more efficient.
Note SELECT *
with a JOIN would also include columns from the row limiting tables
Scato wrotes:
anything you want to use for bitwise operations must be between 0x80000000 (-2147483648 or -2^31) and 0x7fffffff (2147483647 or 2^31 - 1).
the console will tell you that 0x80000000 equals +2147483648, but 0x80000000 & 0x80000000 equals -2147483648
Hex-Decimals are unsigned positive values, so 0x80000000 = 2147483648 - thats mathematically correct. If you want to make it a signed value you have to right shift: 0x80000000 >> 0 = -2147483648. You can write 1 << 31 instead, too.
Did you put void while calling your function?
For example:
void something(int x){
logic..
}
int main() {
**void** something();
return 0;
}
If so, you should delete the last void.
If your trying to fade the backgound image but leave the foreground text/images you could use css to separate the background image into a new div and position it over the div containing the text/images then fade the background div.
The current directory where you exist.
Environment.CurrentDirectory; // This is the current directory of your application
If you copy the .xml file out with build you should find it.
or
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(SomeObject));
// The location of the Assembly
assembly.Location;
@Html.DropDownListFor(m => m.SelectedValue,Your List,"ID","Values")
Here Value is that object of model where you want to save your Selected Value
I have included an example here which demonstrates how you might store the mask in a database column as an int, and how you would reinstate the mask later on:
public enum DaysBitMask { Mon=0, Tues=1, Wed=2, Thu = 4, Fri = 8, Sat = 16, Sun = 32 }
DaysBitMask mask = DaysBitMask.Sat | DaysBitMask.Thu;
bool test;
if ((mask & DaysBitMask.Sat) == DaysBitMask.Sat)
test = true;
if ((mask & DaysBitMask.Thu) == DaysBitMask.Thu)
test = true;
if ((mask & DaysBitMask.Wed) != DaysBitMask.Wed)
test = true;
// Store the value
int storedVal = (int)mask;
// Reinstate the mask and re-test
DaysBitMask reHydratedMask = (DaysBitMask)storedVal;
if ((reHydratedMask & DaysBitMask.Sat) == DaysBitMask.Sat)
test = true;
if ((reHydratedMask & DaysBitMask.Thu) == DaysBitMask.Thu)
test = true;
if ((reHydratedMask & DaysBitMask.Wed) != DaysBitMask.Wed)
test = true;
You can use the HTML5 pattern attribute or use JavaScript.
The pattern could look for example like this:
<input id="groupidtext" type="text" pattern="(.){6,6}" style="width: 100px;" maxlength="6" />
But the pattern attribute will only work with HTML5 browsers. For old browsers you'll need JavaScript.
As suggested in the comments to add, this will only work as soon as a form is about to be submitted. If this input is not in a form and you need validation as a user types, use JavaScript.
My answer would be "be careful". A lot of jQuery table-sorting add-ons only sort what you pass to the browser. In many cases, you have to keep in mind that tables are dynamic sets of data, and could potentially contain zillions of lines of data.
You do mention that you only have 4 columns, but much more importantly, you don't mention how many rows we're talking about here.
If you pass 5000 lines to the browser from the database, knowing that the actual database-table contains 100,000 rows, my question is: what's the point in making the table sortable? In order to do a proper sort, you'd have to send the query back to the database, and let the database (a tool actually designed to sort data) do the sorting for you.
In direct answer to your question though, the best sorting add-on I've come across is Ingrid. There are many reasons that I don't like this add-on ("unnecessary bells and whistles..." as you call it), but one of it's best features in terms of sort, is that it uses ajax, and doesn't assume that you've already passed it all the data before it does its sort.
I recognise that this answer is probably overkill (and over 2 years late) for your requirements, but I do get annoyed when developers in my field overlook this point. So I hope someone else picks up on it.
I feel better now.
string clearText = txtPassword.Text;
string EncryptionKey = "MAKV2SPBNI99212";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
function handle_change(
evt: React.ChangeEvent<HTMLInputElement>
): string {
evt.persist(); // This is needed so you can actually get the currentTarget
const inputValue = evt.currentTarget.value;
return inputValue
}
And make sure you have "lib": ["dom"]
in your tsconfig
.
If you're not wanting to save changes set savechanges to false
Sub CloseBook2()
ActiveWorkbook.Close savechanges:=False
End Sub
for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used
ActiveWorkbook.Close False
Here are the steps that happen internally for both calls:
(Hint: the only difference is in step 3)
new Test()
:
new Object()
objobj.__proto__
to Test.prototype
return Test.call(obj) || obj;
// normally obj is returned but constructors in JS can return a value
Object.create( Test.prototype )
new Object()
objobj.__proto__
to Test.prototype
return obj;
So basically Object.create
doesn't execute the constructor.
The syntax of this question looks like Robot Framework syntax. In this case, although there is no css selector that you can use for contains, there is a SeleniumLibrary keyword that you can use instead. The Wait Until Element Contains.
Example:
Wait Until Element Contains | ${element} | ${contains}
Wait Until Element Contains | td | male
For completeness, there're actually three ways to set the encoding when connecting to MySQL from PDO and which ones are available depend on your PHP version. The order of preference would be:
charset
parameter in the DSN stringSET NAMES utf8
with PDO::MYSQL_ATTR_INIT_COMMAND
connection optionSET NAMES utf8
manuallyThis sample code implements all three:
<?php
define('DB_HOST', 'localhost');
define('DB_SCHEMA', 'test');
define('DB_USER', 'test');
define('DB_PASSWORD', 'test');
define('DB_ENCODING', 'utf8');
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_SCHEMA;
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);
if( version_compare(PHP_VERSION, '5.3.6', '<') ){
if( defined('PDO::MYSQL_ATTR_INIT_COMMAND') ){
$options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . DB_ENCODING;
}
}else{
$dsn .= ';charset=' . DB_ENCODING;
}
$conn = @new PDO($dsn, DB_USER, DB_PASSWORD, $options);
if( version_compare(PHP_VERSION, '5.3.6', '<') && !defined('PDO::MYSQL_ATTR_INIT_COMMAND') ){
$sql = 'SET NAMES ' . DB_ENCODING;
$conn->exec($sql);
}
Doing all three is probably overkill (unless you're writing a class you plan to distribute or reuse).
list_of_e
that has relevant data. df['e'] = list_of_e
Faced the same problem as OP:
Tomcat SSL certificate was expired while a browser showed it as secure - Apache certificate was far from expiration. Updating Tomcat KeyStore file solved the problem.
When you use Entity Framework, it internally uses the OUTPUT
technique to return the newly inserted ID value
DECLARE @generated_keys table([Id] uniqueidentifier)
INSERT INTO TurboEncabulators(StatorSlots)
OUTPUT inserted.TurboEncabulatorID INTO @generated_keys
VALUES('Malleable logarithmic casing');
SELECT t.[TurboEncabulatorID ]
FROM @generated_keys AS g
JOIN dbo.TurboEncabulators AS t
ON g.Id = t.TurboEncabulatorID
WHERE @@ROWCOUNT > 0
The output results are stored in a temporary table variable, joined back to the table, and return the row value out of the table.
Note: I have no idea why EF would inner join the ephemeral table back to the real table (under what circumstances would the two not match).
But that's what EF does.
This technique (OUTPUT
) is only available on SQL Server 2008 or newer.
The reason that Entity Framework joins back to the original table, rather than simply use the OUTPUT
values is because EF also uses this technique to get the rowversion
of a newly inserted row.
You can use optimistic concurrency in your entity framework models by using the Timestamp
attribute:
public class TurboEncabulator
{
public String StatorSlots)
[Timestamp]
public byte[] RowVersion { get; set; }
}
When you do this, Entity Framework will need the rowversion
of the newly inserted row:
DECLARE @generated_keys table([Id] uniqueidentifier)
INSERT INTO TurboEncabulators(StatorSlots)
OUTPUT inserted.TurboEncabulatorID INTO @generated_keys
VALUES('Malleable logarithmic casing');
SELECT t.[TurboEncabulatorID], t.[RowVersion]
FROM @generated_keys AS g
JOIN dbo.TurboEncabulators AS t
ON g.Id = t.TurboEncabulatorID
WHERE @@ROWCOUNT > 0
And in order to retrieve this Timetsamp
you cannot use an OUTPUT
clause.
That's because if there's a trigger on the table, any Timestamp
you OUTPUT will be wrong:
The returned timestamp will never be correct if you have a trigger on the table. So you must use a separate SELECT
.
And even if you were willing to suffer the incorrect rowversion, the other reason to perform a separate SELECT
is that you cannot OUTPUT a rowversion
into a table variable:
DECLARE @generated_keys table([Id] uniqueidentifier, [Rowversion] timestamp)
INSERT INTO TurboEncabulators(StatorSlots)
OUTPUT inserted.TurboEncabulatorID, inserted.Rowversion INTO @generated_keys
VALUES('Malleable logarithmic casing');
The third reason to do it is for symmetry. When performing an UPDATE
on a table with a trigger, you cannot use an OUTPUT
clause. Trying do UPDATE
with an OUTPUT
is not supported, and will give an error:
The only way to do it is with a follow-up SELECT
statement:
UPDATE TurboEncabulators
SET StatorSlots = 'Lotus-O deltoid type'
WHERE ((TurboEncabulatorID = 1) AND (RowVersion = 792))
SELECT RowVersion
FROM TurboEncabulators
WHERE @@ROWCOUNT > 0 AND TurboEncabulatorID = 1
This centers the "A" below the image:
<div style="text-align:center">
<asp:Image ID="Image1" runat="server" ImageUrl="~/Images/opentoselect.gif" />
<br />
A
</div>
That is ASP.Net and it would render the HTML as:
<div style="text-align:center">
<img id="Image1" src="Images/opentoselect.gif" style="border-width:0px;" />
<br />
A
</div>
Although @dunedin15's fantastic answer has served me well on a number of occasions, it can give inaccurate results for some edge-cases, such as when debugging build settings of a static lib for an Archive build.
As an alternative, a Run Script Build Phase can be easily added to any target to “Log Build Settings” when it's built:
To add, (with the target in question selected) under the Build Phases tab-section click the little ? button a dozen-or-so pixels up-left-ward from the Target Dependencies section, and set the shell to /bin/bash
and the command to export
. You'll also probably want to drag the phase upwards so that it happens just after Target Dependencies and before Copy Headers or Compile Sources. Renaming the phase from “Run Script” to “Log Build Settings” isn't a bad idea.
The result is this incredibly helpful listing of current environment variables used for building:
If you don't want to modify the registry or app.config files, an alternate way is to create a simple .NET 4 console app that mimicks what PowerShell.exe does and hosts the PowerShell ConsoleShell.
See Option 2 – Hosting Windows PowerShell yourself
First, add a reference to the System.Management.Automation and Microsoft.PowerShell.ConsoleHost assemblies which can be found under %programfiles%\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0
Then use the following code:
using System;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell;
namespace PSHostCLRv4
{
class Program
{
static int Main(string[] args)
{
var config = RunspaceConfiguration.Create();
return ConsoleShell.Start(
config,
"Windows PowerShell - Hosted on CLR v4\nCopyright (C) 2010 Microsoft Corporation. All rights reserved.",
"",
args
);
}
}
}
There is a problem with every answer provided that can be summarized as "just add this magical incantation to the beginning of your script. See what you can do with just a line or two of code." They will not work in every possible situation!
For example, one such magical incantation uses __file__
. Unfortunately, if you package your script using cx_Freeze or you are using IDLE, this will result in an exception.
Another such magical incantation uses os.getcwd(). This will only work if you are running your script from the command prompt and the directory containing your script is the current working directory (that is you used the cd command to change into the directory prior to running the script). Eh gods! I hope I do not have to explain why this will not work if your Python script is in the PATH somewhere and you ran it by simply typing the name of your script file.
Fortunately, there is a magical incantation that will work in all the cases I have tested. Unfortunately, the magical incantation is more than just a line or two of code.
import inspect
import os
import sys
# Add script directory to sys.path.
# This is complicated due to the fact that __file__ is not always defined.
def GetScriptDirectory():
if hasattr(GetScriptDirectory, "dir"):
return GetScriptDirectory.dir
module_path = ""
try:
# The easy way. Just use __file__.
# Unfortunately, __file__ is not available when cx_Freeze is used or in IDLE.
module_path = __file__
except NameError:
if len(sys.argv) > 0 and len(sys.argv[0]) > 0 and os.path.isabs(sys.argv[0]):
module_path = sys.argv[0]
else:
module_path = os.path.abspath(inspect.getfile(GetScriptDirectory))
if not os.path.exists(module_path):
# If cx_Freeze is used the value of the module_path variable at this point is in the following format.
# {PathToExeFile}\{NameOfPythonSourceFile}. This makes it necessary to strip off the file name to get the correct
# path.
module_path = os.path.dirname(module_path)
GetScriptDirectory.dir = os.path.dirname(module_path)
return GetScriptDirectory.dir
sys.path.append(os.path.join(GetScriptDirectory(), "lib"))
print(GetScriptDirectory())
print(sys.path)
As you can see, this is no easy task!
If anyone is looking for the angular version of this answer then I would suggest creating a directive would be a great idea.
NOTE: ngx-bootstrap is used.
import { Directive, Host, Self, Optional, Input, Renderer2, OnInit, ElementRef } from '@angular/core';
import { CarouselComponent } from 'ngx-bootstrap/carousel';
@Directive({
selector: '[appCarouselSwipe]'
})
export class AppCarouselSwipeDirective implements OnInit {
@Input() swipeThreshold = 50;
private start: number;
private stillMoving: boolean;
private moveListener: Function;
constructor(
@Host() @Self() @Optional() private carousel: CarouselComponent,
private renderer: Renderer2,
private element: ElementRef
) {
}
ngOnInit(): void {
if ('ontouchstart' in document.documentElement) {
this.renderer.listen(this.element.nativeElement, 'touchstart', this.onTouchStart.bind(this));
this.renderer.listen(this.element.nativeElement, 'touchend', this.onTouchEnd.bind(this));
}
}
private onTouchStart(e: TouchEvent): void {
if (e.touches.length === 1) {
this.start = e.touches[0].pageX;
this.stillMoving = true;
this.moveListener = this.renderer.listen(this.element.nativeElement, 'touchmove', this.onTouchMove.bind(this));
}
}
private onTouchMove(e: TouchEvent): void {
if (this.stillMoving) {
const x = e.touches[0].pageX;
const difference = this.start - x;
if (Math.abs(difference) >= this.swipeThreshold) {
this.cancelTouch();
if (difference > 0) {
if (this.carousel.activeSlide < this.carousel.slides.length - 1) {
this.carousel.activeSlide = this.carousel.activeSlide + 1;
}
} else {
if (this.carousel.activeSlide > 0) {
this.carousel.activeSlide = this.carousel.activeSlide - 1;
}
}
}
}
}
private onTouchEnd(e: TouchEvent): void {
this.cancelTouch();
}
private cancelTouch() {
if (this.moveListener) {
this.moveListener();
this.moveListener = undefined;
}
this.start = null;
this.stillMoving = false;
}
}
in html:
<carousel appCarouselSwipe>
...
</carousel>
As Jake points out, TARGET_IPHONE_SIMULATOR
is a subset of TARGET_OS_IPHONE
.
Also, TARGET_OS_IPHONE
is a subset of TARGET_OS_MAC
.
So a better approach might be:
#ifdef _WIN64
//define something for Windows (64-bit)
#elif _WIN32
//define something for Windows (32-bit)
#elif __APPLE__
#include "TargetConditionals.h"
#if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
// define something for simulator
#elif TARGET_OS_IPHONE
// define something for iphone
#else
#define TARGET_OS_OSX 1
// define something for OSX
#endif
#elif __linux
// linux
#elif __unix // all unices not caught above
// Unix
#elif __posix
// POSIX
#endif
There is jq
for parsing json on the command line:
jq '.Body'
Visit this for jq: https://stedolan.github.io/jq/
I use the document.forms java and loop it to get all the elements in the form, then send via xhttp. So this is my solution for javascript / ajax submit (with all html included as an example):
<!DOCTYPE html>
<html>
<body>
<form>
First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br>
Addr1: <input type="text" name="add" value="123 Pond Dr"><br>
City: <input type="text" name="city" value="Duckopolis"><br>
</form>
<button onclick="smc()">Submit</button>
<script>
function smc() {
var http = new XMLHttpRequest();
var url = "yourphpfile.php";
var x = document.forms[0];
var xstr = "";
var ta ="";
var tb ="";
var i;
for (i = 0; i < x.length; i++) {
if (i==0){ta = x.elements[i].name+"="+ x.elements[i].value;}else{
tb = tb+"&"+ x.elements[i].name +"=" + x.elements[i].value;
} }
xstr = ta+tb;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
// do whatever you want to with the html output response here
}
}
http.send(xstr);
}
</script>
</body>
</html>
EDIT: Years ago I gave an answer to this that was gross, too specific, and too complicated. So I'm editing it. I favor the functional answers above for their neat factor but not their readability; but if I were more familiar with javascript then I might like them for that, too.
Pseudo code:
Track index that contains largest value. Assume index 0 is largest initially. Compare against current index. Update index with largest value if necessary.
Code:
var mountains = [3, 1, 5, 9, 4];
function largestIndex(array){
var counter = 1;
var max = 0;
for(counter; counter < array.length; counter++){
if(array[max] < array[counter]){
max = counter;
}
}
return max;
}
console.log("index with largest value is: " +largestIndex(mountains));
// index with largest value is: 3
Rotate by 90 degress around 0,0:
x' = -y
y' = x
Rotate by 90 degress around px,py:
x' = -(y - py) + px
y' = (x - px) + py
Some of the answers here are out of date as of Hive 0.14
It is now possible to insert using syntax such as:
CREATE TABLE students (name VARCHAR(64), age INT, gpa DECIMAL(3, 2));
INSERT INTO TABLE students
VALUES ('fred flintstone', 35, 1.28), ('barney rubble', 32, 2.32);
Straightforward and easy solution is:
docker build .
=> ....
=> Successfully built a3e628814c67
docker run -p 3000:3000 a3e628814c67
3000
- can be any port
a3e628814c68
- hash result given by success build command
NOTE: you should be within directory that contains Dockerfile.
I installed the Role plugin under Jenkins-3.5, but it does not show the "Manage Roles" option under "Manage Jenkins", and when one follows the security install page from the wiki, all users are locked out instantly. I had to manually shutdown Jenkins on the server, restore the correct configuration settings (/me is happy to do proper backups) and restart Jenkins.
I didn't have high hopes, as that plugin was last updated in 2011
The answers here are very good, but still insufficient for me.
I wrote a small loop that compares Uri.EscapeUriString
with Uri.EscapeDataString
for all characters from 0 to 255.
NOTE: Both functions have the built-in intelligence that characters above 0x80 are first UTF-8 encoded and then percent encoded.
Here is the result:
******* Different *******
'#' -> Uri "#" Data "%23"
'$' -> Uri "$" Data "%24"
'&' -> Uri "&" Data "%26"
'+' -> Uri "+" Data "%2B"
',' -> Uri "," Data "%2C"
'/' -> Uri "/" Data "%2F"
':' -> Uri ":" Data "%3A"
';' -> Uri ";" Data "%3B"
'=' -> Uri "=" Data "%3D"
'?' -> Uri "?" Data "%3F"
'@' -> Uri "@" Data "%40"
******* Not escaped *******
'!' -> Uri "!" Data "!"
''' -> Uri "'" Data "'"
'(' -> Uri "(" Data "("
')' -> Uri ")" Data ")"
'*' -> Uri "*" Data "*"
'-' -> Uri "-" Data "-"
'.' -> Uri "." Data "."
'_' -> Uri "_" Data "_"
'~' -> Uri "~" Data "~"
'0' -> Uri "0" Data "0"
.....
'9' -> Uri "9" Data "9"
'A' -> Uri "A" Data "A"
......
'Z' -> Uri "Z" Data "Z"
'a' -> Uri "a" Data "a"
.....
'z' -> Uri "z" Data "z"
******* UTF 8 *******
.....
'Ò' -> Uri "%C3%92" Data "%C3%92"
'Ó' -> Uri "%C3%93" Data "%C3%93"
'Ô' -> Uri "%C3%94" Data "%C3%94"
'Õ' -> Uri "%C3%95" Data "%C3%95"
'Ö' -> Uri "%C3%96" Data "%C3%96"
.....
EscapeUriString
is to be used to encode URLs, while EscapeDataString
is to be used to encode for example the content of a Cookie, because Cookie data must not contain the reserved characters '='
and ';'
.
You need to use a graphics library. Put this in your preamble:
\usepackage{graphicx}
You can then add images like this:
\begin{figure}[ht!]
\centering
\includegraphics[width=90mm]{fixed_dome1.jpg}
\caption{A simple caption \label{overflow}}
\end{figure}
This is the basic template I use in my documents. The position and size should be tweaked for your needs. Refer to the guide below for more information on what parameters to use in \figure
and \includegraphics
. You can then refer to the image in your text using the label you gave in the figure:
And here we see figure \ref{overflow}.
Read this guide here for a more detailed instruction: http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions
You can convert varchars to floats, and you can do it in the manner you have expressed. Your varchar must not be a numeric value. There must be something else in it. You can use IsNumeric to test it. See this:
declare @thing varchar(100)
select @thing = '122.332'
--This returns 1 since it is numeric.
select isnumeric(@thing)
--This converts just fine.
select convert(float,@thing)
select @thing = '122.332.'
--This returns 0 since it is not numeric.
select isnumeric(@thing)
--This convert throws.
select convert(float,@thing)
A good example of a situation when @see
can be useful would be implementing or overriding an interface/abstract class method. The declaration would have javadoc
section detailing the method and the overridden/implemented method could use a @see
tag, referring to the base one.
Related question: Writing proper javadoc with @see?
Java SE documentation: @see
I encounter the same problem. I inited a bean object in static block like below:
static {
try{
mqttConfiguration = SpringBootBeanUtils.<MqttConfiguration>getBean(MqttConfiguration.class);
}catch (Throwable e){
System.out.println(e);
}
}
Just because the process the my bean obejct inition caused a NPE, I get trouble into it. So I think you should check you static code block carefully.
You need to add the column with a default of null
, then alter the column to have default now()
.
ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP;
ALTER TABLE mytable ALTER COLUMN created_at SET DEFAULT now();
Just a quick note (and possible cause).
You can have a perfectly correct VirtualHost
setup with _default_:443
etc. in your Apache .conf file.
But... If there is even one .conf file enabled with incorrect settings that also listens to port 443, then it will bring the whole SSL system down.
Therefore, if you are sure your .conf file is correct, try disabling the other site .conf files in sites-enabled
.
If you refer the official angular docs
https://angular.io/guide/attribute-directives
There are three kinds of directives in Angular:
As the Application grows we find difficulty in maintaining all these codes. For reusability purpose, we separate our logic in smart components and dumb components and we use directives (structural or attribute) to make changes in the DOM.
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("Age")]
public int required { get; set; }
[JsonProperty("Location")]
public string type { get; set; }
and Remove a "{"..,
strFieldString = strFieldString.Remove(0, strFieldString.IndexOf('{'));
DeserializeObject..,
optionsItem objActualField = JsonConvert.DeserializeObject<optionsItem(strFieldString);
Based on John's answer, I changed the GET request to a POST request. It works, without having to change the server configuration. So I went looking how to implement this. The following pages were helpful:
jQuery Ajax POST example with PHP (Note the sanitize posted data remark) and
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
Basically, the difference is that the GET request has the url and parameters in one string and then sends null:
http.open("GET", url+"?"+params, true);
http.send(null);
whereas the POST request sends the url and the parameters in separate commands:
http.open("POST", url, true);
http.send(params);
Here is a working example:
ajaxPOST.html:
<html>
<head>
<script type="text/javascript">
function ajaxPOSTTest() {
try {
// Opera 8.0+, Firefox, Safari
ajaxPOSTTestRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxPOSTTestRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxPOSTTestRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxPOSTTestRequest.onreadystatechange = ajaxCalled_POSTTest;
var url = "ajaxPOST.php";
var params = "lorem=ipsum&name=binny";
ajaxPOSTTestRequest.open("POST", url, true);
ajaxPOSTTestRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxPOSTTestRequest.send(params);
}
//Create a function that will receive data sent from the server
function ajaxCalled_POSTTest() {
if (ajaxPOSTTestRequest.readyState == 4) {
document.getElementById("output").innerHTML = ajaxPOSTTestRequest.responseText;
}
}
</script>
</head>
<body>
<button onclick="ajaxPOSTTest()">ajax POST Test</button>
<div id="output"></div>
</body>
</html>
ajaxPOST.php:
<?php
$lorem=$_POST['lorem'];
print $lorem.'<br>';
?>
I just sent over 12,000 characters without any problems.
Select all text afected by this issue:
Window -> Character, click the icon next to hide the Character Window, Middle Western Features and select Left-to-right character direction.
There is no feature in scp to filter files. For "advanced" stuff like this, I recommend using rsync:
rsync -av --exclude '*.svn' user@server:/my/dir .
(this line copy rsync from distant folder to current one)
Recent versions of rsync tunnel over an ssh connection automatically by default.
You simply need to add that line legend: { display: false }
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[]){
int num ;
num = atoi(argv[1]);
printf("\n%d", num);
}
The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.
To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".
To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".
Explanation:
From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):
4.3.8 ‘Local echo’
With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)
Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.
4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.
If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.
Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)
Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.
Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.
You can also use REPLACE()
:
UPDATE Table
SET Column = REPLACE(Column, 'Test123', 'Test')
Yes you can (provided you have at least the professional version of visual studio), although it requires a little setting up once you've done this it's not much different from debugging code. MSDN has a basic walkthrough.
dir has been mentioned, but that'll only give you the attributes' names. If you want their values as well try __dict__.
class O:
def __init__ (self):
self.value = 3
o = O()
Here is the output:
>>> o.__dict__
{'value': 3}
I've used encodeURIComponent() and decodeURIComponent() too.
Just to add.
Get the seconds since epoch(Jan 1 1970) for any given date(e.g Oct 21 1973).
date -d "Oct 21 1973" +%s
Convert the number of seconds back to date
date --date @120024000
The command date
is pretty versatile. Another cool thing you can do with date(shamelessly copied from date --help
).
Show the local time for 9AM next Friday on the west coast of the US
date --date='TZ="America/Los_Angeles" 09:00 next Fri'
Better yet, take some time to read the man page http://man7.org/linux/man-pages/man1/date.1.html
i would assume fastest and simplest way would be have python call the system commands...
example..
import os
cmd = '<command line call>'
os.system(cmd)
Tar and gzip up the directory.... unzip and untar the directory in the desired place.
yah?
You should use the title attribute for anchor tags if you wish to apply descriptive information similarly as you would for an alt attribute. The title attribute is valid on anchor tags and is serves no other purpose than providing information about the linked page.
W3C recommends that the value of the title attribute should match the value of the title of the linked document but it's not mandatory.
http://www.w3.org/MarkUp/1995-archive/Elements/A.html
Alternatively, and likely to be more beneficial, you can use the ARIA accessibility attribute aria-label
(not to be confused with aria-labeledby
). aria-label
serves the same function as the alt attribute does for images but for non-image elements and includes some measure of optimization since your optimizing for screen readers.
http://www.w3.org/WAI/GL/wiki/Using_aria-label_to_provide_labels_for_objects
If you want to describe an anchor tag though, it's usually appropriate to use the rel or rev tag but your limited to specific values, they should not be used for human readable descriptions.
Rel serves to describe the relationship of the linked page to the current page. (e.g. if the linked page is next in a logical series it would be rel=next)
The rev attribute is essentially the reverse relationship of the rel attribute. Rev describes the relationship of the current page to the linked page.
You can find a list of valid values here: http://microformats.org/wiki/existing-rel-values
The issue you are having is common and not explained well in the documentation. Normal devices do not include the sqlite3 database binary which is why you are getting an error. the Android Emeulator, OSX, Linux (if installed) and Windows (after installed) have the binary so you can open a database locally on your machine.
The workaround is to copy the Database from your device to your local machine. This can be accomplished with ADB but requires a number of steps.
Before you start you will need some information:
<package name>
, for example, com.example.application
<local path>
to place your database, eg. ~/Desktop
or %userprofile%\Desktop
Next you will need to understand what terminal each command gets written to the first character in the examples below does not get typed but lets you know what shell we are in:
>
= you OS command prompt$
= ADB shell command Prompt!
= ADB shell as admin command prompt%
Next enter the following commands from Terminal or Command (don't enter first character or text in ()
)
> adb shell
$ su
! cp /data/data/<package name>/Databases/<database name> /sdcard
! exit
$ exit
> adb pull /sdcard/<database name> <local path>
> sqlite3 <local db path>
% .dump
% .exit (to exit sqldb)
This is a really round about way of copying the database to your local machine and locally reading the database. There are SO and other resources explaining how to install the sqlite3 binary onto your device from an emulator but for one time access this process works.
If you need to access the database interactively I would suggest running your app in an emulator (that already had sqlite3) or installing sqlite onto your devices /xbin path.
You have to add col-md-12 to your inner-navbar. md is for desktop .you can choose other options from bootstrap's list of options . 12 in col-md-12 is for full width .If you want half-width you can use 6 instead of 12 .for e.g. col-md-6.
Here is the solution to your question
<div class="container">
<div class="navbar">
<div class="navbar-inner col-md-12">
<!-- nav bar items here -->
</div>
</div>
</div>
I had to embed my $location.path()
statement like this because my digest was still running:
function routeMe(data) {
var waitForRender = function () {
if ($http.pendingRequests.length > 0) {
$timeout(waitForRender);
} else {
$location.path(data);
}
};
$timeout(waitForRender);
}
Just wrap the textarea with the label and set the textarea style to
vertical-align: middle;
Here is some magic for all textareas on the page:)
<style>
label textarea{
vertical-align: middle;
}
</style>
<label>Blah blah blah Description: <textarea>dura bura</textarea></label>
Just dot is working. The doctype makes a difference however as sometimes the ./ is fine as well.
<a href=".">Link to this folder</a>
Since you have not replied to my comment above, I am posting a solution for both.
You are missing '
in Extended Properties
For Excel 2003 try this (TRIED AND TESTED)
private void button1_Click(object sender, EventArgs e)
{
String name = "Items";
String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
"C:\\Sample.xls" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
grid_items.DataSource = data;
}
BTW, I stopped working with Jet longtime ago. I use ACE now.
private void button1_Click(object sender, EventArgs e)
{
String name = "Items";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"C:\\Sample.xls" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
grid_items.DataSource = data;
}
For Excel 2007+
private void button1_Click(object sender, EventArgs e)
{
String name = "Items";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"C:\\Sample.xlsx" +
";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
grid_items.DataSource = data;
}
You should have to use DateTime.TryParseExact
.
var newDate = DateTime.ParseExact("20111120",
"yyyyMMdd",
CultureInfo.InvariantCulture);
OR
string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;
if (DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
{
//valid
}
I got a similar problem. Breakpoints where not working unless I used debugger;
. I fixed my breakpoints problem with "Restore defaults and reload". It's located in the Chrome Developer Tools, Settings, Restore defaults and reload.
A similar approach to @mwigdahl's answer, you can also implement a .NET CLR in C#, with code such as;
using System.Data.SqlTypes;
using RX = System.Text.RegularExpressions;
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString Regex(string input, string regex)
{
var match = RX.Regex.Match(input, regex).Groups[1].Value;
return new SqlString (match);
}
}
Installation instructions can be found here
Declaration says "this thing exists somewhere":
int foo(); // function
extern int bar; // variable
struct T
{
static int baz; // static member variable
};
Definition says "this thing exists here; make memory for it":
int foo() {} // function
int bar; // variable
int T::baz; // static member variable
Initialisation is optional at the point of definition for objects, and says "here is the initial value for this thing":
int bar = 0; // variable
int T::baz = 42; // static member variable
Sometimes it's possible at the point of declaration instead:
struct T
{
static int baz = 42;
};
…but that's getting into more complex features.
The following worked for me without floating (I modified your example a little for visual effect):
.container_x000D_
{_x000D_
white-space: nowrap; /*Prevents Wrapping*/_x000D_
_x000D_
width: 300px;_x000D_
height: 120px;_x000D_
overflow-x: scroll;_x000D_
overflow-y: hidden;_x000D_
}_x000D_
.slide_x000D_
{_x000D_
display: inline-block; /*Display inline and maintain block characteristics.*/_x000D_
vertical-align: top; /*Makes sure all the divs are correctly aligned.*/_x000D_
white-space: normal; /*Prevents child elements from inheriting nowrap.*/_x000D_
_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-color: red;_x000D_
margin: 5px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="slide">something something something</div>_x000D_
<div class="slide">something something something</div>_x000D_
<div class="slide">something something something</div>_x000D_
<div class="slide">something something something</div>_x000D_
</div>
_x000D_
The divs may be separated by spaces. If you don't want this, use margin-right: -4px;
instead of margin: 5px;
for .slide
(it's ugly but it's a tricky problem to deal with).
wp-config.php
add define('FS_METHOD', 'direct');
wp-content/
, wp-content/plugins/
.wp-content/plugins
dir).Worked on version 3.2.1
You're not looping over the items. Try this instead:
$.getJSON(url, function(data){
$.each(data.response.venue.tips.groups.items, function (index, value) {
console.log(this.text);
});
});
How about:
if (stream.markSupported() == false) {
// lets replace the stream object
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(stream, baos);
stream.close();
stream = new ByteArrayInputStream(baos.toByteArray());
// now the stream should support 'mark' and 'reset'
}
Yes, for scalar values, a combination of implode and array_slice will do:
$bar = implode(array_slice($array, 0, 1));
$bin = implode(array_slice($array, 1, 1));
$ipsum = implode(array_slice($array, 2, 1));
Or mix it up with array_values
and list
(thanks @nikic) so that it works with all types of values:
list($bar) = array_values(array_slice($array, 0, 1));
You can get fairly close with this template struct. However, you need to initialize with expressions that are pointers to T, rather than T; and so, though you can easily make a 'fake_constref_array' similarly, you won't be able to bind that to rvalues as done in the OP's example ('8');
#include <stdio.h>
template<class T, int N>
struct fake_ref_array {
T * ptrs[N];
T & operator [] ( int i ){ return *ptrs[i]; }
};
int A,B,X[3];
void func( int j, int k)
{
fake_ref_array<int,3> refarr = { &A, &B, &X[1] };
refarr[j] = k; // :-)
// You could probably make the following work using an overload of + that returns
// a proxy that overloads *. Still not a real array though, so it would just be
// stunt programming at that point.
// *(refarr + j) = k
}
int
main()
{
func(1,7); //B = 7
func(2,8); // X[1] = 8
printf("A=%d B=%d X = {%d,%d,%d}\n", A,B,X[0],X[1],X[2]);
return 0;
}
--> A=0 B=7 X = {0,8,0}
This is a very simple solution that returns an array of string with the matches
Swift 3.
internal func stringsMatching(regularExpressionPattern: String, options: NSRegularExpression.Options = []) -> [String] {
guard let regex = try? NSRegularExpression(pattern: regularExpressionPattern, options: options) else {
return []
}
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
return results.map {
nsString.substring(with: $0.range)
}
}
It's simpler to use, the -a option :
cat ~/campaigns/release-status.html | mail -s "Release Status [Green]" -a "Content-Type: text/html" [email protected]
a.txt
this is line 1
this is line 2
code:
Python 3.4.0 (default, Mar 20 2014, 22:43:40)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']
I'm on Linux, but I guess you just use \r\n
on Windows and it would also work
It allows you to add as many base type parameters in your call as you like.
addTwoEach(10, 2, 4, 6)
whereas with the second form you have to use an array as parameter
addTwoEach(new int[] {10,2,4,6})
I have done with this.
sudo apt-get update
sudo apt-get install build-essential chrpath git-core libssl-dev libfontconfig1-dev
git clone git://github.com/ariya/phantomjs.git
cd phantomjs
git checkout 1.9
./build.sh
You can use jQuery's $.getScript()
method to do it but if you want a more full feature one, yepnope.js is your choice. It supports conditional loading of scripts and stylesheets and it's easy to use.
Why i Suggest moment.js
it is very popular library
simple to solve all date and time,format,timezone problems
easy to check string date valid or not
var date = moment("2016-10-19");
date.isValid()
we can't solve simple way to validate all the cases
Disspointment
if i insert in valid number like 89,90,95 in new Date() above few answare , i am getting bad result however it return true
const isValidDate = date => {
console.log('input'+date)
var date=new Date(date);
console.log(date)
return !! (Object.prototype.toString.call(date) === "[object Date]" && +date)
//return !isNaN(date.getTime())
}
var test="05/04/2012"
console.log(isValidDate(test))
var test="95"
console.log(isValidDate(test))
var test="89"
console.log(isValidDate(test))
var test="80"
console.log(isValidDate(test))
var test="badstring"
console.log(isValidDate(test))
_x000D_
@Ryan, you are right, hard-coding the height will make it work bad in case of custom navbars. This is the code I am using for BS 3.0.0 happily:
$(window).resize(function () {
$('body').css('padding-top', parseInt($('#main-navbar').css("height"))+10);
});
$(window).load(function () {
$('body').css('padding-top', parseInt($('#main-navbar').css("height"))+10);
});
Fundamentally if you use it as part of a business then its commercial use - so its not a matter of whether the tools are directly generating income or not rather one of if they are being used in support of income generation directly or indirectly.
To take your specific example, if the purpose of the site is to sell or promote your paid services/product then its a commercial enterprise.
Try following code to get count of files in the folder
string strDocPath = Server.MapPath('Enter your path here');
int docCount = Directory.GetFiles(strDocPath, "*",
SearchOption.TopDirectoryOnly).Length;
I meet this question when i use intellij 15.0,then i update to 15.02 version. after that, I edit configurations and reset the Default JRE to my own JRE.It works well for me;
Using Between condition
SELECT *
FROM TEST
WHERE COLUMN_NAME BETWEEN x AND y ;
Or using Just operators,
SELECT *
FROM TEST
WHERE COLUMN_NAME >= x AND COLUMN_NAME <= y;
For iOS7 and before you should indeed use enabledRemoteNotificationTypes
and check if it equals (or doesn't equal depending on what you want) to UIRemoteNotificationTypeNone
.
However for iOS8 it is not always enough to only check with isRegisteredForRemoteNotifications
as many state above. You should also check if application.currentUserNotificationSettings.types
equals (or doesn't equal depending on what you want) UIUserNotificationTypeNone
!
isRegisteredForRemoteNotifications
might return true even though currentUserNotificationSettings.types
returns UIUserNotificationTypeNone
.
Here is a minimal example using moviepy. For me this was the easiest solution.
import os
import moviepy.video.io.ImageSequenceClip
image_folder='folder_with_images'
fps=1
image_files = [image_folder+'/'+img for img in os.listdir(image_folder) if img.endswith(".png")]
clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps)
clip.write_videofile('my_video.mp4')
const config = {
headers: { Authorization: `Bearer ${token}` }
};
const bodyParameters = {
key: "value"
};
Axios.post(
'http://localhost:8000/api/v1/get_token_payloads',
bodyParameters,
config
).then(console.log).catch(console.log);
The first parameter is the URL.
The second is the JSON body that will be sent along your request.
The third parameter are the headers (among other things). Which is JSON as well.
By default reference types have reference equality (i.e. two instances are only equal if they are the same object).
You need to override Object.Equals
(and Object.GetHashCode
to match) to implement your own equality. (And it is then good practice to implement an equality, ==
, operator.)
When you want to differ between a superClass and the inheritedClass you can use:
if([myTestClass class] == [myInheritedClass class]){
NSLog(@"I'm the inheritedClass);
}
if([myTestClass class] == [mySuperClass class]){
NSLog(@"I'm the superClass);
}
Using - (BOOL)isKindOfClass:(Class)aClass
in this case would result in TRUE both times because the inheritedClass is also a kind of the superClass.
You are having a controlled component where input
value is determined by this.state.city
. So once you submit you have to clear your state which will clear your input automatically.
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({
city: ''
});
}
You would want to use ->forget()
$collection->forget($key);
Link to the forget method documentation
I think you can use thread like demon-thread for reading your input and your output reader will already be in while loop in main thread so you can read and write at same time.You can modify your program like this:
Thread T=new Thread(new Runnable() {
@Override
public void run() {
while(true)
{
String input = scan.nextLine();
input += "\n";
try {
writer.write(input);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} );
T.start();
and you can reader will be same as above i.e.
while ((line = reader.readLine ()) != null) {
System.out.println ("Stdout: " + line);
}
make your writer as final otherwise it wont be able to accessible by inner class.
Simple functionality is not included in Swift, expected because it's included in other languages, can often be quickly coded for reuse. Pro tip for programmers to create a bag of tricks file that contains all this reuse code.
So from my bag of tricks we first need string multiplication for use in indentation.
@inlinable func * (string: String, scalar: Int) -> String {
let array = [String](repeating: string, count: scalar)
return array.joined(separator: "")
}
and then the code to add commas.
extension Int {
@inlinable var withCommas:String {
var i = self
var retValue:[String] = []
while i >= 1000 {
retValue.append(String(format:"%03d",i%1000))
i /= 1000
}
retValue.append("\(i)")
return retValue.reversed().joined(separator: ",")
}
@inlinable func withCommas(_ count:Int = 0) -> String {
let retValue = self.withCommas
let indentation = count - retValue.count
let indent:String = indentation >= 0 ? " " * indentation : ""
return indent + retValue
}
}
I just wrote this last function so I could get the columns to line up.
The @inlinable is great because it takes small functions and reduces their functionality so they run faster.
You can use either the variable version or, to get a fixed column, use the function version. Lengths set less than the needed columns will just expand the field.
Now you have something that is pure Swift and does not rely on some old objective C routine for NSString.
You state that
2 is the height of the multi-line text box
No it's not. 2 is the distance between lines of text.
I don't think there is a real way for calculating the height of the actual resulting text box, unless you use GetY()
and then subtract the original Y value used in your SetXY()
statement for placing the Multicell in the first place.
Change the group permission for the folder
sudo chown -R w3cert /home/w3cert/.composer/cache/repo/https---packagist.org
and the Files folder too
sudo chown -R w3cert /home/w3cert/.composer/cache/files/
I'm assuming w3cert is your username, if not change the 4th parameter to your username.
If the problem still persists try
sudo chown -R w3cert /home/w3cert/.composer
Now, there is a chance that you won't be able to create your app directory, if that happens do the same for your html folder or the folder you are trying to create your laravel project in.
Hope this helps.
function showStuff(id, text, btn) {_x000D_
document.getElementById(id).style.display = 'block';_x000D_
// hide the lorem ipsum text_x000D_
document.getElementById(text).style.display = 'none';_x000D_
// hide the link_x000D_
btn.style.display = 'none';_x000D_
}
_x000D_
<td class="post">_x000D_
_x000D_
<a href="#" onclick="showStuff('answer1', 'text1', this); return false;">Edit</a>_x000D_
<span id="answer1" style="display: none;">_x000D_
<textarea rows="10" cols="115"></textarea>_x000D_
</span>_x000D_
_x000D_
<span id="text1">Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</span>_x000D_
</td>
_x000D_
Checkboxes are not able to be styled. You would need a third party js plugin there are many available.
If you want to do this yourself it basically involves hiding the checkbox creating an element and styling that as you want then binding its click event to two functions one to change its look and another to activate the click event of the checkbox.
The same problem will arise when trying to style that little down arrow on a drop-down select element.
If you have an abstract URL string (not from the current window.location
), you can use this trick:
let yourUrlString = "http://example.com:3000/pathname/?search=test#hash";
let parser = document.createElement('a');
parser.href = yourUrlString;
parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.search; // => "?search=test"
parser.hash; // => "#hash"
parser.host; // => "example.com:3000"
Thanks to jlong
I had to update the proxy settings under Plugins -> Plugin Manager -> Show Plugin Manager -> Settings to see any PlugIns in the "Available" list.
After that, installing "XML Tools" was easy and did the requested job as described above.
I had the same problem. Here's a simple solution that works !
const newItems = [...this.state.items];
newItems[item] = value;
this.setState({ items:newItems });
setTimeout would not hold and resume on your own thread however Thread.sleep does. There is no actual equal in Javascript
An XSD file is an XML Schema Definition and it is used to provide a standard method of checking that a given XML document conforms to what you expect.
Use net use
or New-PSDrive
to create a new drive:
New-PsDrive: create a new PsDrive only visible in PowerShell environment:
New-PSDrive -Name Y -PSProvider filesystem -Root \\ServerName\Share
Copy-Item BigFile Y:\BigFileCopy
Net use: create a new drive visible in all parts of the OS.
Net use y: \\ServerName\Share
Copy-Item BigFile Y:\BigFileCopy
Why are people using list slicing (slow because it copies to a new list), importing a library function, or trying to rotate an array for this?
Use a normal for-loop with range(start, stop, step)
(where start
and step
are optional arguments).
For example, looping through an array starting at index 1:
for i in range(1, len(arr)):
print(arr[i])
This may be an old response but I used some examples from this post to create a comparator that would sort an ArrayList
of HashMap<String, String>
by one object in the list, that being the timestamp.
I have these objects:
ArrayList<Map<String, String>> alList = new ArrayList<Map<String, String>>();
The map objects are as follows:
Map<String, Object> map = new HashMap<>();
// of course this is the actual formatted date below in the timestamp
map.put("timestamp", "MM/dd/yyyy HH:mm:ss");
map.put("item1", "my text goes here");
map.put("item2", "my text goes here");
That mapping is what I use to load all my objects into the array list, using the alList.add(map)
function, within a loop.
Now, I created my own comparator:
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
public class DateSorter implements Comparator {
public int compare(Object firstObjToCompare, Object secondObjToCompare) {
String firstDateString = ((HashMap<String, String>) firstObjToCompare).get("timestamp");
String secondDateString = ((HashMap<String, String>) secondObjToCompare).get("timestamp");
if (secondDateString == null || firstDateString == null) {
return 0;
}
// Convert to Dates
DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
DateTime firstDate = dtf.parseDateTime(firstDateString);
DateTime secondDate = dtf.parseDateTime(secondDateString);
if (firstDate.isAfter(secondDate)) return -1;
else if (firstDate.isBefore(secondDate)) return 1;
else return 0;
}
}
I can now just call the Comparator at any time on the array and it will sort my array, giving me the Latest timestamp in position 0 (top of the list) and the earliest timestamp at the end of the list. New posts get put to the top basically.
Collections.sort(alList, new DateSorter());
This may help someone out, which is why I posted it. Take into consideration the return statements within the compare() function. There are 3 types of results. Returning 0 if they are equal, returning >0 if the first date is before the second date and returning <0 if the first date is after the second date. If you want your list to be reversed, then just switch those two return statements! Simple =]
Use:
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
// Create a couple of columns
model.addColumn("Col1");
model.addColumn("Col2");
// Append a row
model.addRow(new Object[]{"v1", "v2"});
Currently, the link dlptest is working fine.
The files will only be stored for 30 minutes before being deleted.
unfortunately, with "mvim -v", ALT plus arrow windows still does not work. I have not found any way to enable it :-(
SELECT * FROM V$TRANSACTION
WHERE STATUS='ACTIVE';
See: http://forums.oracle.com/forums/thread.jspa?threadID=691061
You want $_SERVER['REQUEST_URI']
. From the docs:
'REQUEST_URI'
The URI which was given in order to access this page; for instance,
'/index.html'
.
Views are handy when you need to select from several tables, or just to get a subset of a table.
You should design your tables in such a way that your database is well normalized (minimum duplication). This can make querying somewhat difficult.
Views are a bit of separation, allowing you to view the data in the tables differently than they are stored.