I know this asks for a Jquery solution, but I just thought I'd point out that it is very easy to toggle this in plain javascript.
var element = document.getElementById("estado_cat");
element.checked = 1;
It will work in all current and future versions.
You can create your own extension method to do this:
public static bool Contains(this string source, string toCheck, StringComparison comp)
{
return source != null && toCheck != null && source.IndexOf(toCheck, comp) >= 0;
}
And then call:
mystring.Contains(myStringToCheck, StringComparison.OrdinalIgnoreCase);
If you are using Python 2, just run
sudo apt-get install python-matplotlib
The best way to get matplotlib
is :
pip install matplotlib
cause the previous way may give you a old version of matplotlib
The first day of the previous month is always 1, to get the last day of the previous month, use 0 with DateSerial:
''Today is 20/03/2013 in dd/mm/yyyy
DateSerial(Year(Date),Month(Date),0) = 28/02/2013
DateSerial(Year(Date),1,0) = 31/12/2012
You can get the first day from the above like so:
LastDay = DateSerial(Year(Date),Month(Date),0)
FirstDay = LastDay-Day(LastDay)+1
See also: How to caculate last business day of month in VBScript
2x faster than the versions before mentioned - mostly because transform() and inner_product() loops are joined. Sorry about my shortcut/typedefs/macro: Flo = float. CR const ref. VFlo - vector. Tested in VS2010
#define fe(EL, CONTAINER) for each (auto EL in CONTAINER) //VS2010
Flo stdDev(VFlo CR crVec) {
SZ n = crVec.size(); if (n < 2) return 0.0f;
Flo fSqSum = 0.0f, fSum = 0.0f;
fe(f, crVec) fSqSum += f * f; // EDIT: was Cit(VFlo, crVec) {
fe(f, crVec) fSum += f;
Flo fSumSq = fSum * fSum;
Flo fSumSqDivN = fSumSq / n;
Flo fSubSqSum = fSqSum - fSumSqDivN;
Flo fPreSqrt = fSubSqSum / (n - 1);
return sqrt(fPreSqrt);
}
This is probably caused by the JSON field names not having quotation marks.
Change the JSON structure from:
{welcome:"Welcome"}
to:
{"welcome":"Welcome"}
beginupd.getTime()
will give you time in milliseconds since January 1, 1970, 00:00:00 GMT till the time you have specified in Date
object
You can ping without "-t" and check the exit code of the ping. It reports failure when there is no answer.
pp can create an executable that includes perl and your script (and any module dependencies), but it will be specific to your architecture, so you couldn't run it on both Windows and linux for instance.
From its doc:
To make a stand-alone executable, suitable for running on a machine that doesn't have perl installed:
% pp -o packed.exe source.pl # makes packed.exe # Now, deploy 'packed.exe' to target machine... $ packed.exe # run it
(% and $ there are command prompts on different machines).
Look up the specification of HTTP. Or to get started, try http://www.jmarshall.com/easy/http/
You will want to move the loop for the files outside of the loop for the folders. In addition you will need to pass the data structure holding the collection of files to each call of the method. That way all files go into a single list.
public static List<string> DirSearch(string sDir, List<string> files)
{
foreach (string f in Directory.GetFiles(sDir, "*.xml"))
{
string extension = Path.GetExtension(f);
if (extension != null && (extension.Equals(".xml")))
{
files.Add(f);
}
}
foreach (string d in Directory.GetDirectories(sDir))
{
DirSearch(d, files);
}
return files;
}
Then call it like this.
List<string> files = DirSearch("c:\foo", new List<string>());
Update:
Well unbeknownst to me, until I read the other answer anyway, there is already a builtin mechanism for doing this. I will leave my answer in case you are interested in seeing how your code needs to be modified to make it work.
The last argument of CONVERT
seems to determine the format used for parsing. Consult MSDN docs for CONVERT.
111
- the one you are using is Japan yy/mm/dd
.
I guess the one you are looking for is 103
, that is dd/mm/yyyy
.
So you should try:
SELECT convert(datetime, '23/07/2009', 103)
you can use more_itertools package.
import more_itertools
lst = range(1, 7)
for i, j in more_itertools.chunked(lst, 2):
print(f'{i} + {j} = {i+j}')
With RHEL 7 / CentOS 7, firewalld was introduced to manage iptables. IMHO, firewalld is more suited for workstations than for server environments.
It is possible to go back to a more classic iptables setup. First, stop and mask the firewalld service:
systemctl stop firewalld
systemctl mask firewalld
Then, install the iptables-services package:
yum install iptables-services
Enable the service at boot-time:
systemctl enable iptables
Managing the service
systemctl [stop|start|restart] iptables
Saving your firewall rules can be done as follows:
service iptables save
or
/usr/libexec/iptables/iptables.init save
One way would be to use a nested query:
SELECT count(*)
FROM (
SELECT COUNT(Genre) AS count
FROM movies
GROUP BY ID
HAVING (count = 4)
) AS x
The inner query gets all the movies that have exactly 4 genres, then outer query counts how many rows the inner query returned.
If you intend to use the default VB6 Collection
, then the easiest you can do is:
col1.add array("first key", "first string"), "first key"
col1.add array("second key", "second string"), "second key"
col1.add array("third key", "third string"), "third key"
Then you can list all values:
Dim i As Variant
For Each i In col1
Debug.Print i(1)
Next
Or all keys:
Dim i As Variant
For Each i In col1
Debug.Print i(0)
Next
You should use val
instead of value
.
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('input[name="testing"]').val('Work!');
});
</script>
A lot of years after... I like this one:
For x = LBound(arr) To UBound(arr): Do
sname = arr(x)
If instr(sname, "Configuration item") Then Exit Do
'// other code to copy past and do various stuff
Loop While False: Next x
JavaScript has two number types: Number
and BigInt
.
The most frequently-used number type, Number
, is a 64-bit floating point IEEE 754 number.
The largest exact integral value of this type is Number.MAX_SAFE_INTEGER
, which is:
To put this in perspective: one quadrillion bytes is a petabyte (or one thousand terabytes).
"Safe" in this context refers to the ability to represent integers exactly and to correctly compare them.
Note that all the positive and negative integers whose magnitude is no greater than 253 are representable in the
Number
type (indeed, the integer 0 has two representations, +0 and -0).
To safely use integers larger than this, you need to use BigInt
, which has no upper bound.
Note that the bitwise operators and shift operators operate on 32-bit integers, so in that case, the max safe integer is 231-1, or 2,147,483,647.
const log = console.log_x000D_
var x = 9007199254740992_x000D_
var y = -x_x000D_
log(x == x + 1) // true !_x000D_
log(y == y - 1) // also true !_x000D_
_x000D_
// Arithmetic operators work, but bitwise/shifts only operate on int32:_x000D_
log(x / 2) // 4503599627370496_x000D_
log(x >> 1) // 0_x000D_
log(x | 1) // 1
_x000D_
Technical note on the subject of the number 9,007,199,254,740,992: There is an exact IEEE-754 representation of this value, and you can assign and read this value from a variable, so for very carefully chosen applications in the domain of integers less than or equal to this value, you could treat this as a maximum value.
In the general case, you must treat this IEEE-754 value as inexact, because it is ambiguous whether it is encoding the logical value 9,007,199,254,740,992 or 9,007,199,254,740,993.
one more variant, but almost the same as Gumbos solution:
var isDebug = function(){
return window.location.href.search("[?&]debug=") != -1;
};
so, it seems there arent, but you can use this workaround using guava or an equivalent Function class implementation, because that class is extremely simple, ex.:
assert false : new com.google.common.base.Function<Void,String>(){
@Override public String apply(Void input) {
//your complex code go here
return "weird message";
}}.apply(null);
yes, this is dead code just to exemplify how to create a complex code block (within {}) to do something so specific that shouldnt bother us on creating any method for it, AKA inline!
using subprocess ping command to ping decode it because the response is binary:
import subprocess
ping_response = subprocess.Popen(["ping", "-a", "google.com"], stdout=subprocess.PIPE).stdout.read()
result = ping_response.decode('utf-8')
print(result)
Percent encoding. Replace the hash with %23
.
Using mongoose.js you can count documents,
const count = await Schema.countDocuments();
const count = await Schema.countDocuments({ key: value });
Listen to this podcast to find out. If you want to know the answer without listening, then OK, its REST. But I really do recommend listening.
Actually there are quite a few methods.
int sum_of_elems = 0;
Classic for loop:
for(std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it)
sum_of_elems += *it;
Using a standard algorithm:
#include <numeric>
sum_of_elems = std::accumulate(vector.begin(), vector.end(), 0);
Important Note: The last argument's type is used not just for the initial value, but for the type of the result as well. If you put an int there, it will accumulate ints even if the vector has float. If you are summing floating-point numbers, change 0
to 0.0
or 0.0f
(thanks to nneonneo). See also the C++11 solution below.
b. Automatically keeping track of the vector type even in case of future changes:
#include <numeric>
sum_of_elems = std::accumulate(vector.begin(), vector.end(),
decltype(vector)::value_type(0));
Using std::for_each
:
std::for_each(vector.begin(), vector.end(), [&] (int n) {
sum_of_elems += n;
});
Using a range-based for loop (thanks to Roger Pate):
for (auto& n : vector)
sum_of_elems += n;
I had a similar issue, and following previous answers (thanks!), I was able to search and find how to handle correctly the ThreadPoolExecutor terminaison.
In my case, that just fix my progressive increase of similar blocked threads:
ExecutorService::awaitTermination(x, TimeUnit)
and ExecutorService::shutdownNow()
(if necessary) in my finally clause.For information, I've used the following commands to detect thread count & list locked threads:
ps -u javaAppuser -L|wc -l
jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayA.log
jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayAPlusOne.log
cat threadPrint*.log |grep "pool-"|wc -l
import subprocess
filepath="D:/path/to/batch/myBatch.bat"
p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE)
stdout, stderr = p.communicate()
print p.returncode # is 0 if success
Use np.ravel (for a 1D view) or np.ndarray.flatten (for a 1D copy) or np.ndarray.flat (for an 1D iterator):
In [12]: a = np.array([[1,2,3], [4,5,6]])
In [13]: b = a.ravel()
In [14]: b
Out[14]: array([1, 2, 3, 4, 5, 6])
Note that ravel()
returns a view
of a
when possible. So modifying b
also modifies a
. ravel()
returns a view
when the 1D elements are contiguous in memory, but would return a copy
if, for example, a
were made from slicing another array using a non-unit step size (e.g. a = x[::2]
).
If you want a copy rather than a view, use
In [15]: c = a.flatten()
If you just want an iterator, use np.ndarray.flat
:
In [20]: d = a.flat
In [21]: d
Out[21]: <numpy.flatiter object at 0x8ec2068>
In [22]: list(d)
Out[22]: [1, 2, 3, 4, 5, 6]
This css script might be useful to all - It is not for syntax highlighting but works well for presenting the source code in original format :
<pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace;
color: #000000; background-color: #eee;
font-size: 12px; border: 1px dashed #999999;
line-height: 14px; padding: 5px;
overflow: auto; width: 100%">
<code style="color:#000000;word-wrap:normal;">
<<<<<<<YOUR CODE HERE>>>>>>>
</code>
</pre>
How to use :
BENEFITS : Simple and easy to use, less configuration, easy to reconfigure, no extra software
Facing the very same problem (avoiding the default path in a network) I came up to this solution with the hints given in other answers.
The solution is editing the Rprofile
file to overwrite the variable R_LIBS_USER
which by default points to the home directory.
Here the steps:
~\target
.Rprofile
file. In my case it was at C:\Program Files\R\R-3.3.3\library\base\R\Rprofile
.R_LIBS_USER
. In my case, I replaced the this line file.path(Sys.getenv("R_USER"), "R",
with file.path("~\target", "R",
.The documentation that support this solution is here
Original file with:
if(!nzchar(Sys.getenv("R_LIBS_USER")))
Sys.setenv(R_LIBS_USER=
file.path(Sys.getenv("R_USER"), "R",
"win-library",
paste(R.version$major,
sub("\\..*$", "", R.version$minor),
sep=".")
))
Modified file:
if(!nzchar(Sys.getenv("R_LIBS_USER")))
Sys.setenv(R_LIBS_USER=
file.path("~\target", "R",
"win-library",
paste(R.version$major,
sub("\\..*$", "", R.version$minor),
sep=".")
))
Swift 4 version for @dmarnel answer:
tableView.reloadSections(IndexSet(integer: 0), with: .automatic)
since you only want the files, you don't need to treat it as a git repo.
rsync -rlp --exclude '.git' user@host:path/to/git/repo/ .
and this only works with local path and remote ssh/rsync path, it may not work if the remote server only provides git:// or https:// access.
When using Python 2.4, try
inf = float("9e999")
nan = inf - inf
I am facing the issue when I was porting the simplejson to an embedded device which running the Python 2.4, float("9e999")
fixed it. Don't use inf = 9e999
, you need convert it from string.
-inf
gives the -Infinity
.
At this point:
for (String[] s : myEntries) {
System.out.println("Next item: " + s);
}
You need to join the array of Strings in a line. Check this post: A method to reverse effect of java String.split()?
The .css()
function doesn't queue behind running animations, it's instantaneous.
To match the behaviour that you're after, you'd need to do the following:
$(document).ready(function() {
$("button").mouseover(function() {
var p = $("p#44.test").css("background-color", "yellow");
p.hide(1500).show(1500);
p.queue(function() {
p.css("background-color", "red");
});
});
});
The .queue()
function waits for running animations to run out and then fires whatever's in the supplied function.
As already said, the easiest way is to use querystring.
But if you cannot, because of security reason, you should consider using cookies.
Because you haven't declared it. If you want to use a variable of another class you must use
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var DestViewController : ViewController = segue.destinationViewController as ViewController
DestViewController.signedIn = false
}
You have to put this code at the end of the NewClass code
I'm adding a response for those that use the httpclient-4.5, and probably works for 4.4 as well.
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.fluent.ContentResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
public class HttpClientUtils{
public static HttpClient getHttpClientWithoutSslValidation_UsingHttpClient_4_5_2() {
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), new NoopHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpclient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Update
All modern browsers now support the unprefixed event:
element.addEventListener('transitionend', callback, false);
https://caniuse.com/#feat=css-transitions
I was using the approach given by Pete, however I have now started using the following
$(".myClass").one('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd',
function() {
//do something
});
Alternatively if you use bootstrap then you can simply do
$(".myClass").one($.support.transition.end,
function() {
//do something
});
This is becuase they include the following in bootstrap.js
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd otransitionend',
'transition' : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
$(function () {
$.support.transition = transitionEnd()
})
}(jQuery);
Note they also include an emulateTransitionEnd function which may be needed to ensure a callback always occurs.
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false, $el = this
$(this).one($.support.transition.end, function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
Be aware that sometimes this event doesn’t fire, usually in the case when properties don’t change or a paint isn’t triggered. To ensure we always get a callback, let’s set a timeout that’ll trigger the event manually.
To change use of class instead of ID
<script type="text/javascript">
$(function() {
$('.my_date1').datepicker();
$('.my_date2').datepicker();
$('.my_date3').datepicker();
...
});
</script>
You most likely have your virtual machine’s networking set to NAT. If you set your networking to Bridged you should be able to access your host machine by its hostname. For example, if your hostname is “jsmith-Precision-7510” and you want to open http://localhost:3000/, you will be able to view that page at http://jsmith-Precision-7510:3000/.
To find your hostname, open a terminal/console and then run the command hostname
. Your hostname will be outputted on the next line.
See the VirtualBox documentation for instructions on how to set your networking setttings to Bridged.
I was getting this error because I was using an older version of angular that wasn't compatible with my code.
I had this issue, I run 64 bit Windows and had downloaded the 64 bit TOAD package. I finally arrived at the conclusion that it was because I unzipped the package in a windows share using cygwin command line unzip. Turned out TOAD wasn't liking the permissions on some files. When I unzipped using windows File Explorer everything worked as expected.
I suggest to use an extension for code neatness. Note that extending an internal object prototype could potentially mess with libraries that depend on them.
String.prototype.trimEllip = function (length) {
return this.length > length ? this.substring(0, length) + "..." : this;
}
And use it like:
var stringObject= 'this is a verrrryyyyyyyyyyyyyyyyyyyyyyyyyyyyylllooooooooooooonggggggggggggsssssssssssssttttttttttrrrrrrrrriiiiiiiiiiinnnnnnnnnnnnggggggggg';
stringObject.trimEllip(25)
[+]is simpler
String s = "ddjdjdj+kfkfkf";
if(s.contains ("+"))
{
String parts[] = s.split("[+]");
s = parts[0]; // i want to strip part after +
}
System.out.println(s);
Here is a fast implementation using numba (mind the types). Note it does contain nans where shifted.
import numpy as np
import numba as nb
@nb.jit(nb.float64[:](nb.float64[:],nb.int64),
fastmath=True,nopython=True)
def moving_average( array, window ):
ret = np.cumsum(array)
ret[window:] = ret[window:] - ret[:-window]
ma = ret[window - 1:] / window
n = np.empty(window-1); n.fill(np.nan)
return np.concatenate((n.ravel(), ma.ravel()))
Nowadays, you should use ERB::Util.url_encode
or CGI.escape
. The primary difference between them is their handling of spaces:
>> ERB::Util.url_encode("foo/bar? baz&")
=> "foo%2Fbar%3F%20baz%26"
>> CGI.escape("foo/bar? baz&")
=> "foo%2Fbar%3F+baz%26"
CGI.escape
follows the CGI/HTML forms spec and gives you an application/x-www-form-urlencoded
string, which requires spaces be escaped to +
, whereas ERB::Util.url_encode
follows RFC 3986, which requires them to be encoded as %20
.
See "What's the difference between URI.escape and CGI.escape?" for more discussion.
If you no longer need the hided elements, just use element.remove()
instead of element.style.display = 'none';
.
With C++0x we can use lambda functions:
using namespace std;
vector<pair<int, int>> v;
.
.
sort(v.begin(), v.end(),
[](const pair<int, int>& lhs, const pair<int, int>& rhs) {
return lhs.second < rhs.second; } );
In this example the return type bool
is implicitly deduced.
Lambda return types
When a lambda-function has a single statement, and this is a return-statement, the compiler can deduce the return type. From C++11, §5.1.2/4:
...
- If the compound-statement is of the form
{ return expression ; }
the type of the returned expression after lvalue-to-rvalue conversion (4.1), array-to-pointer conversion (4.2), and function-to-pointer conversion (4.3);- otherwise,
void
.
To explicitly specify the return type use the form []() -> Type { }
, like in:
sort(v.begin(), v.end(),
[](const pair<int, int>& lhs, const pair<int, int>& rhs) -> bool {
if (lhs.second == 0)
return true;
return lhs.second < rhs.second; } );
You are using jQuery, right? Separate JavaScript from HTML.
You can use trigger or triggerHandler.
var $myInput = $('#changeProgramatic').on('change', ChangeValue);
var anotherFunction = function() {
$myInput.val('Another value');
$myInput.trigger('change');
};
Notepad++ Add Word To Start Of Every Line
Follow this instruction to write anything at the start of every line with Notepad++
Open Notepad++,
Press Cntrl+H open the Find/Replace Dialog.
Now type ^ in the Find what textbox (Type ^ without any spaces)
Type anything(like in our example I am writing "John ") in the Replace with textbox (Write text one/more space for adding one/more space after your text in every line)
Select the Regular Expression option
Place your cursor in the first line of your file to ensure all lines are affected
Click Replace All button
Notepad++ Add Text To End Of Every Line
Follow this instruction to write anything at the end of every line with Notepad++
Open Notepad++,
Press Cntrl+H open the Find/Replace Dialog.
Now type $ in the Find what textbox (Type $ without any spaces)
Type anything(like in our example I am writing " John") in the Replace with textbox (Write one/more space text for adding one/more space before your text in every line)
Select the Regular Expression option
Place your cursor in the first line of your file to ensure all lines are affected
Click Replace All button
For all Notepadd++ Tutorials: VISIT:)
The override function getParams works fine. You use POST method and you have set the jBody as null. That's why it doesn't work. You could use GET method if you want to send null jBody. I have override the method getParams and it works either with GET method (and null jBody) either with POST method (and jBody != null)
Also there are all the examples here
From this question -- add the following styles to a print-only stylesheet. This solution will work in IE and Firefox, but not in Chrome (as of version 21):
#header {
display: table-header-group;
}
#main {
display: table-row-group;
}
#footer {
display: table-footer-group;
}
If you look close, you'll see the difference:
/var/run/mysqld/mysqld.sock
/var/run/mysqld/mysql.sock
You'll have to adjust the one or the other.
That meta tag basically specifies which character set a website is written with.
Here is a definition of UTF-8:
UTF-8 (U from Universal Character Set + Transformation Format—8-bit) is a character encoding capable of encoding all possible characters (called code points) in Unicode. The encoding is variable-length and uses 8-bit code units.
Add file to res/drawable
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:left="-2dp" android:right="-2dp">
<shape android:shape="rectangle">
<stroke
android:width="1dp"
android:color="#000000" />
</shape>
</item>
</layer-list>
Add link on this file to background property
I recommend using:
#!/bin/bash
It's not 100% portable (some systems place bash
in a location other than /bin
), but the fact that a lot of existing scripts use #!/bin/bash
pressures various operating systems to make /bin/bash
at least a symlink to the main location.
The alternative of:
#!/usr/bin/env bash
has been suggested -- but there's no guarantee that the env
command is in /usr/bin
(and I've used systems where it isn't). Furthermore, this form will use the first instance of bash
in the current users $PATH
, which might not be a suitable version of the bash shell.
(But /usr/bin/env
should work on any reasonably modern system, either because env
is in /usr/bin
or because the system does something to make it work. The system I referred to above was SunOS 4, which I probably haven't used in about 25 years.)
If you need a script to run on a system that doesn't have /bin/bash
, you can modify the script to point to the correct location (that's admittedly inconvenient).
I've discussed the tradeoffs in greater depth in my answer to this question.
A somewhat obscure update: One system I use, Termux, a desktop-Linux-like layer that runs under Android, doesn't have /bin/bash
(bash
is /data/data/com.termux/files/usr/bin/bash
) -- but it has special handling to support #!/bin/bash
.
As for me, i need the view diraction:
in -> swipe from right
out -> swipe to left
Here works for me code:
slide_in_right.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="50%p" android:toXDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
slide_out_left.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="-50%p"
android:duration="@android:integer/config_mediumAnimTime"/>
<alpha android:fromAlpha="1.0" android:toAlpha="0.0"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
transaction code:
inline fun FragmentActivity.setContentFragment(
containerViewId: Int,
backStack: Boolean = false,
isAnimate: Boolean = false,
f: () -> Fragment
): Fragment? {
val manager = supportFragmentManager
return f().apply {
manager.beginTransaction().let {
if (isAnimate)
it.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left)
if (backStack) {
it.replace(containerViewId, this, "Fr").addToBackStack("Fr").commit()
} else {
it.replace(containerViewId, this, "Fr").commit()
}
}
}
}
Use the following:
echo (text here) >> (name here).txt
Ex. echo my name is jeff >> test.txt
test.txt
my name is jeff
You can use it in a script too.
Like mentioned earlier, I'd recommend boost lexical_cast. Not only does it have a fairly nice syntax:
#include <boost/lexical_cast.hpp>
std::string s = boost::lexical_cast<std::string>(i);
it also provides some safety:
try{
std::string s = boost::lexical_cast<std::string>(i);
}catch(boost::bad_lexical_cast &){
...
}
You can double.Parse("41.00027357629127");
Switch cases should almost always have a default
case.
Reasons to use a default
1.To 'catch' an unexpected value
switch(type)
{
case 1:
//something
case 2:
//something else
default:
// unknown type! based on the language,
// there should probably be some error-handling
// here, maybe an exception
}
2. To handle 'default' actions, where the cases are for special behavior.
You see this a LOT in menu-driven programs and bash shell scripts. You might also see this when a variable is declared outside the switch-case but not initialized, and each case initializes it to something different. Here the default needs to initialize it too so that down the line code that accesses the variable doesn't raise an error.
3. To show someone reading your code that you've covered that case.
variable = (variable == "value") ? 1 : 2;
switch(variable)
{
case 1:
// something
case 2:
// something else
default:
// will NOT execute because of the line preceding the switch.
}
This was an over-simplified example, but the point is that someone reading the code shouldn't wonder why variable
cannot be something other than 1 or 2.
The only case I can think of to NOT use default
is when the switch is checking something where its rather obvious every other alternative can be happily ignored
switch(keystroke)
{
case 'w':
// move up
case 'a':
// move left
case 's':
// move down
case 'd':
// move right
// no default really required here
}
This is old question but in my case...
- (void) scrollViewWillBeginDragging:(UIScrollView *)scrollView {
_m_offsetIdx = [m_cv indexPathForCell:m_cv.visibleCells.firstObject].row;
}
- (void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
_m_offsetIdx = [m_cv indexPathForCell:m_cv.visibleCells.lastObject].row;
}
You can add properties dynamically using some of the options below:
In you example:
var data = {
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
};
You can define a property with a dynamic value in the next two ways:
data.key = value;
or
data['key'] = value;
Even more..if your key is also dynamic you can define using the Object class with:
Object.defineProperty(data, key, withValue(value));
where data is your object, key is the variable to store the key name and value is the variable to store the value.
I hope this helps!
ATTENTION! the chosen answer contains a bug (Jac's answer).
if you have more than one cookie (very likely..) and the cookie you are retrieving is the first on the list, it doesn't set the variable "end" and therefore it will return the entire string of characters following the "cookieName=" within the document.cookie string!
here is a revised version of that function:
function getCookie( name ) {
var dc,
prefix,
begin,
end;
dc = document.cookie;
prefix = name + "=";
begin = dc.indexOf("; " + prefix);
end = dc.length; // default to end of the string
// found, and not in first position
if (begin !== -1) {
// exclude the "; "
begin += 2;
} else {
//see if cookie is in first position
begin = dc.indexOf(prefix);
// not found at all or found as a portion of another cookie name
if (begin === -1 || begin !== 0 ) return null;
}
// if we find a ";" somewhere after the prefix position then "end" is that position,
// otherwise it defaults to the end of the string
if (dc.indexOf(";", begin) !== -1) {
end = dc.indexOf(";", begin);
}
return decodeURI(dc.substring(begin + prefix.length, end) ).replace(/\"/g, '');
}
if a.Correct
is a bool
flag for the correct answer then you need.
Answer answer = Answers.Single(a => a.Correct);
Use imageWithData:
method, which gets translated to Swift as UIImage(data:)
let image : UIImage = UIImage(data: imageData)
class Program
{
static void Main(string[] args)
{
string method = args[0]; // get name method
CallMethod(method);
}
public static void CallMethod(string method)
{
try
{
Type type = typeof(Program);
MethodInfo methodInfo = type.GetMethod(method);
methodInfo.Invoke(method, null);
}
catch(Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
Console.ReadKey();
}
}
public static void Hello()
{
string a = "hello world!";
Console.WriteLine(a);
Console.ReadKey();
}
}
Create a foreground service with the START_STICKY
flag.
@Override
public int onStartCommand(Intent startIntent, int flags, int startId) {
if (startIntent != null) {
String action = startIntent.getAction();
String command = startIntent.getStringExtra(CMD_NAME);
if (ACTION_CMD.equals(action)) {
if (CMD_PAUSE.equals(command)) {
if (mPlayback != null && mPlayback.isPlaying()) {
handlePauseRequest();
}
} else if (CMD_PLAY.equals(command)) {
ArrayList<Track> queue = new ArrayList<>();
for (Parcelable input : startIntent.getParcelableArrayListExtra(ARG_QUEUE)) {
queue.add((Track) Parcels.unwrap(input));
}
int index = startIntent.getIntExtra(ARG_INDEX, 0);
playWithQueue(queue, index);
}
}
}
return START_STICKY;
}
This can then be called from any activity to play some music
Intent intent = new Intent(MusicService.ACTION_CMD, fileUrlToPlay, activity, MusicService::class.java)
intent.putParcelableArrayListExtra(MusicService.ARG_QUEUE, tracks)
intent.putExtra(MusicService.ARG_INDEX, position)
intent.putExtra(MusicService.CMD_NAME, MusicService.CMD_PLAY)
activity.startService(intent)
You can bind to the service using bindService and to make the Service pause/stop from the corresponding activity lifecycle methods.
Here's a good tutorial about Playing music in the background on Android
Best option to do this according to WP Codex is as follow.
Use the global variable $post:
<?php
global $post;
$post_slug = $post->post_name;
?>
Here are some guideline steps...
Give this a go and if you get stuck then come back and ask more specific questions relating to your problems
Don't use "source"
, it's designed to run a small number of sql queries
and display the output, not to import large databases.
I use Wamp Developer
(not XAMPP
) but it should be the same.
What you want to do is use the MySQL Client
to do the work for you.
MySQL
is running.phpMyAdmin
or the MySQL shell
.cmd.exe
, and change to the directory your sql
file is
located in.mysql -u root -p database_name_here < dump_file_name_here.sql
database name
and dump file name
.MySQL root account password
when prompted (if no password set, remove the "-p" switch).This assumes that mysql.exe
can be located via the environmental path, and that sql
file is located in the directory you are running this from. Otherwise, use full paths.
build.gradle
dependencies {
compile 'com.google.android.gms:play-services-vision:9.4.0+'
}
Set View
CameraSourcePreview mPreview = (CameraSourcePreview) findViewById(R.id.preview);
GraphicOverlay mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay);
CameraSource mCameraSource = new CameraSource.Builder(context, detector)
.setRequestedPreviewSize(640, 480)
.setFacing(CameraSource.CAMERA_FACING_FRONT)
.setRequestedFps(30.0f)
.build();
mPreview.start(mCameraSource, mGraphicOverlay);
If you do throw an exception from a constructor, keep in mind that you need to use the function try/catch syntax if you need to catch that exception in a constructor initializer list.
e.g.
func::func() : foo()
{
try {...}
catch (...) // will NOT catch exceptions thrown from foo constructor
{ ... }
}
vs.
func::func()
try : foo() {...}
catch (...) // will catch exceptions thrown from foo constructor
{ ... }
I like...
@data = `cat /var/tmp/somefile`;
It's not as glamorous as others, but, it works all the same. And...
$todays_data = '/var/tmp/somefile' ;
open INFILE, "$todays_data" ;
@data = <INFILE> ;
close INFILE ;
Cheers.
Firstly you can find duplicate rows and find count of rows is used how many times and order it by number like this;
SELECT q.id,q.name,q.password,q.NID,(select count(*) from UserInfo k where k.NID= q.NID) as Count,_x000D_
(_x000D_
CASE q.NID_x000D_
WHEN @curCode THEN_x000D_
@curRow := @curRow + 1_x000D_
ELSE_x000D_
@curRow := 1_x000D_
AND @curCode := q.NID_x000D_
END_x000D_
) AS No_x000D_
FROM UserInfo q,_x000D_
(_x000D_
SELECT_x000D_
@curRow := 1,_x000D_
@curCode := ''_x000D_
) rt_x000D_
WHERE q.NID IN_x000D_
(_x000D_
SELECT NID_x000D_
FROM UserInfo_x000D_
GROUP BY NID_x000D_
HAVING COUNT(*) > 1_x000D_
)
_x000D_
after that create a table and insert result to it.
create table CopyTable _x000D_
SELECT q.id,q.name,q.password,q.NID,(select count(*) from UserInfo k where k.NID= q.NID) as Count,_x000D_
(_x000D_
CASE q.NID_x000D_
WHEN @curCode THEN_x000D_
@curRow := @curRow + 1_x000D_
ELSE_x000D_
@curRow := 1_x000D_
AND @curCode := q.NID_x000D_
END_x000D_
) AS No_x000D_
FROM UserInfo q,_x000D_
(_x000D_
SELECT_x000D_
@curRow := 1,_x000D_
@curCode := ''_x000D_
) rt_x000D_
WHERE q.NID IN_x000D_
(_x000D_
SELECT NID_x000D_
FROM UserInfo_x000D_
GROUP BY NID_x000D_
HAVING COUNT(*) > 1_x000D_
)
_x000D_
Finally, delete dublicate rows.No is start 0. Except fist number of each group delete all dublicate rows.
delete from CopyTable where No!= 0;
_x000D_
here is a copy-paste example that worked for me.
http://swiftdeveloperblog.com/code-examples/determine-users-current-location-example-in-swift/
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
determineMyCurrentLocation()
}
func determineMyCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
//locationManager.startUpdatingHeading()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
// Call stopUpdatingLocation() to stop listening for location updates,
// other wise this function will be called every time when user location changes.
// manager.stopUpdatingLocation()
print("user latitude = \(userLocation.coordinate.latitude)")
print("user longitude = \(userLocation.coordinate.longitude)")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
print("Error \(error)")
}
}
Simply you can go with
a = [['hand', 'head'], ['phone', 'wallet'], ['lost', 'stock']]
b = ['phone', 'lost']
res = [[x[0] for x in a].index(y) for y in b]
For whatever reason the above would not work for me. This is what did:
if (tabControl.SelectedTab.Name == "tabName" )
{
.. do stuff
}
where tabControl.SelectedTab.Name is the name attribute assigned to the page in the tabcontrol itself.
Your main() method is static, but it is referencing two non-static members: con2 and getConnectionUrl2(). You need to do one of three things:
1) Make con2 and getConnectionUrl2() static.
2) Inside main(), create an instance of class testconnect and access con2 and getConnectionUrl2() off of that.
3) Break out a different class to hold con2 and getConnectionUrl2() so that testconnect only has main in it. It will still need to instantiate the different class and call the methods off that.
Option #3 is the best option. #1 is the worst.
But, you cannot access non-static members from within a static method.
Thank you All...
My issue solved by below code:
<a href="javascript:void(0)"> >>> </a>
To use BeginForm
, here's the way to use it:
using(Html.BeginForm("uploadfiles",
"home", FormMethod.POST, new Dictionary<string, object>(){{"type", "file"}})
How to execute Python scripts in Windows?
You could install pylauncher. It is used to launch .py, .pyw, .pyc, .pyo files and supports multiple Python installations:
T\:> blah.py argument
You can run your Python script without specifying .py extension if you have .py, .pyw in PATHEXT environment variable:
T:\> blah argument
It adds support for shebang (#!
header line) to select desired Python version on Windows if you have multiple versions installed. You could use *nix-compatible syntax #! /usr/bin/env python
.
You can specify version explicitly e.g., to run using the latest installed Python 3 version:
T:\> py -3 blah.py argument
It should also fix your sys.argv
issue as a side-effect.
You can use fuckit module.
Wrap your code in a function with @fuckit
decorator:
@fuckit
def func():
code a
code b #if b fails, it should ignore, and go to c.
code c #if c fails, go to d
code d
string jsonData1=@"[{""name"":""0"",""price"":""40"",""count"":""1"",""productId"":""4"",""catid"":""4"",""productTotal"":""40"",""orderstatus"":""0"",""orderkey"":""123456789""}]";
string jsonData = jsonData1.Replace("\"", "");
DataSet ds = new DataSet();
DataTable dt = new DataTable();
JArray array= JArray.Parse(jsonData);
couldnot parse , if the vaule is a string..
look at name : meals , if name : 1 then it will parse
An alternative to using keytool
, you can use the command
openssl x509 -in certificate.pem -text
This should work for any x509 .pem file provided you have openssl
installed.
Try this way:
select * from tab
where DateCol between DateAdd(DD,-7,GETDATE() ) and GETDATE()
lubos hasko's method fails for nullables. The method below will work for nullables. I didn't come up with it, though. I found it via Google: http://web.archive.org/web/20101214042641/http://dogaoztuzun.com/post/C-Generic-Type-Conversion.aspx Credit to "Tuna Toksoz"
Usage first:
TConverter.ChangeType<T>(StringValue);
The class is below.
public static class TConverter
{
public static T ChangeType<T>(object value)
{
return (T)ChangeType(typeof(T), value);
}
public static object ChangeType(Type t, object value)
{
TypeConverter tc = TypeDescriptor.GetConverter(t);
return tc.ConvertFrom(value);
}
public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter
{
TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
}
}
Typing /**
+ then pressing Enter above a method signature will create Javadoc stubs for you.
Simple utility method:
public static boolean isBetween(int value, int min, int max)
{
return((value > min) && (value < max));
}
What about :
List myList = new ArrayList();
String[] myStringArray = new String[] {"Java", "is", "Cool"};
Collections.addAll(myList, myStringArray);
ALTER TABLE TableName
ALTER COLUMN ColumnName NVARCHAR(200) [NULL | NOT NULL]
EDIT As noted NULL/NOT NULL should have been specified, see Rob's answer as well.
Try this. This should work:
<div data-role="page" id="page" style="background-image: url('#URL'); background-attachment: fixed; background-repeat: no-repeat; background-size: 100% 100%;"
data-theme="a">
select * from table_name LIMIT 100
remember this only works with MYSQL
Press Ctrl + Alt + O.
A dialog box will appear with a few options. You can choose to have the dialog box not appear again in the future if you wish, setting a default behavior.
As Sagiv b.g. pointed out, the npm start
command is a shortcut for npm run start
. I just wanted to add a real-life example to clarify it a bit more.
The setup below comes from the create-react-app
github repo. The package.json
defines a bunch of scripts which define the actual flow.
"scripts": {
"start": "npm-run-all -p watch-css start-js",
"build": "npm run build-css && react-scripts build",
"watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
"build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
"start-js": "react-scripts start"
},
For clarity, I added a diagram.
The blue boxes are references to scripts, all of which you could executed directly with an npm run <script-name>
command. But as you can see, actually there are only 2 practical flows:
npm run start
npm run build
The grey boxes are commands which can be executed from the command line.
So, for instance, if you run npm start
(or npm run start
) that actually translate to the npm-run-all -p watch-css start-js
command, which is executed from the commandline.
In my case, I have this special npm-run-all
command, which is a popular plugin that searches for scripts that start with "build:", and executes all of those. I actually don't have any that match that pattern. But it can also be used to run multiple commands in parallel, which it does here, using the -p <command1> <command2>
switch. So, here it executes 2 scripts, i.e. watch-css
and start-js
. (Those last mentioned scripts are watchers which monitor file changes, and will only finish when killed.)
The watch-css
makes sure that the *.scss
files are translated to *.css
files, and looks for future updates.
The start-js
points to the react-scripts start
which hosts the website in a development mode.
In conclusion, the npm start
command is configurable. If you want to know what it does, then you have to check the package.json
file. (and you may want to make a little diagram when things get complicated).
For Spring Boot I found this RegexCorsConfiguration
which extends the official CorsConfiguration
: https://github.com/looorent/spring-security-jwt/blob/master/src/main/java/be/looorent/security/jwt/RegexCorsConfiguration.java
On macOS:
Cmd + 1
On Windows, probably
Ctrl + (/) near right shift key
If you're using PDO, use PDO::lastInsertId
.
If you're using Mysqli, use mysqli::$insert_id
.
If you're still using Mysql:
Please, don't use
mysql_*
functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
But if you have to, use mysql_insert_id
.
What I tend to do is create a C array with the names in the same order and position as the enum values.
eg.
enum colours { red, green, blue };
const char *colour_names[] = { "red", "green", "blue" };
then you can use the array in places where you want a human-readable value, eg
colours mycolour = red;
cout << "the colour is" << colour_names[mycolour];
You could experiment a little with the stringizing operator (see # in your preprocessor reference) that will do what you want, in some circumstances- eg:
#define printword(XX) cout << #XX;
printword(red);
will print "red" to stdout. Unfortunately it won't work for a variable (as you'll get the variable name printed out)
Click Developer Tools to inspect element. You may also use keyboard shortcuts, such as CtrlL+Shift+I, F12 (or Fn+F12), etc.
$.getJSon expects a callback functions either you pass it to the callback function or in callback function assign it to global variale.
var globalJsonVar;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
//do some thing with json or assign global variable to incoming json.
globalJsonVar=json;
});
IMO best is to call the callback function. which is nicer to eyes, readability aspects.
$.getJSON("http://127.0.0.1:8080/horizon-update", callbackFuncWithData);
function callbackFuncWithData(data)
{
// do some thing with data
}
Try restarting the apache server. This was the mistake I had made - forgetting to restart the server after installing php!
service httpd restart
Thanks to cryo for improved version that I based my tested code below:
#Instead of adding silence at start and end of recording (values=0) I add the original audio . This makes audio sound more natural as volume is >0. See trim()
#I also fixed issue with the previous code - accumulated silence counter needs to be cleared once recording is resumed.
from array import array
from struct import pack
from sys import byteorder
import copy
import pyaudio
import wave
THRESHOLD = 500 # audio levels not normalised.
CHUNK_SIZE = 1024
SILENT_CHUNKS = 3 * 44100 / 1024 # about 3sec
FORMAT = pyaudio.paInt16
FRAME_MAX_VALUE = 2 ** 15 - 1
NORMALIZE_MINUS_ONE_dB = 10 ** (-1.0 / 20)
RATE = 44100
CHANNELS = 1
TRIM_APPEND = RATE / 4
def is_silent(data_chunk):
"""Returns 'True' if below the 'silent' threshold"""
return max(data_chunk) < THRESHOLD
def normalize(data_all):
"""Amplify the volume out to max -1dB"""
# MAXIMUM = 16384
normalize_factor = (float(NORMALIZE_MINUS_ONE_dB * FRAME_MAX_VALUE)
/ max(abs(i) for i in data_all))
r = array('h')
for i in data_all:
r.append(int(i * normalize_factor))
return r
def trim(data_all):
_from = 0
_to = len(data_all) - 1
for i, b in enumerate(data_all):
if abs(b) > THRESHOLD:
_from = max(0, i - TRIM_APPEND)
break
for i, b in enumerate(reversed(data_all)):
if abs(b) > THRESHOLD:
_to = min(len(data_all) - 1, len(data_all) - 1 - i + TRIM_APPEND)
break
return copy.deepcopy(data_all[_from:(_to + 1)])
def record():
"""Record a word or words from the microphone and
return the data as an array of signed shorts."""
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK_SIZE)
silent_chunks = 0
audio_started = False
data_all = array('h')
while True:
# little endian, signed short
data_chunk = array('h', stream.read(CHUNK_SIZE))
if byteorder == 'big':
data_chunk.byteswap()
data_all.extend(data_chunk)
silent = is_silent(data_chunk)
if audio_started:
if silent:
silent_chunks += 1
if silent_chunks > SILENT_CHUNKS:
break
else:
silent_chunks = 0
elif not silent:
audio_started = True
sample_width = p.get_sample_size(FORMAT)
stream.stop_stream()
stream.close()
p.terminate()
data_all = trim(data_all) # we trim before normalize as threshhold applies to un-normalized wave (as well as is_silent() function)
data_all = normalize(data_all)
return sample_width, data_all
def record_to_file(path):
"Records from the microphone and outputs the resulting data to 'path'"
sample_width, data = record()
data = pack('<' + ('h' * len(data)), *data)
wave_file = wave.open(path, 'wb')
wave_file.setnchannels(CHANNELS)
wave_file.setsampwidth(sample_width)
wave_file.setframerate(RATE)
wave_file.writeframes(data)
wave_file.close()
if __name__ == '__main__':
print("Wait in silence to begin recording; wait in silence to terminate")
record_to_file('demo.wav')
print("done - result written to demo.wav")
Besides redefining console._commandLineAPI
,
there are some other ways to break into InjectedScriptHost on WebKit browsers, to prevent or alter the evaluation of expressions entered into the developer's console.
Edit:
Chrome has fixed this in a past release. - which must have been before February 2015, as I created the gist at that time
So here's another possibility. This time we hook in, a level above, directly into InjectedScript
rather than InjectedScriptHost
as opposed to the prior version.
Which is kind of nice, as you can directly monkey patch InjectedScript._evaluateAndWrap
instead of having to rely on InjectedScriptHost.evaluate
as that gives you more fine-grained control over what should happen.
Another pretty interesting thing is, that we can intercept the internal result when an expression is evaluated and return that to the user instead of the normal behavior.
Here is the code, that does exactly that, return the internal result when a user evaluates something in the console.
var is;
Object.defineProperty(Object.prototype,"_lastResult",{
get:function(){
return this._lR;
},
set:function(v){
if (typeof this._commandLineAPIImpl=="object") is=this;
this._lR=v;
}
});
setTimeout(function(){
var ev=is._evaluateAndWrap;
is._evaluateAndWrap=function(){
var res=ev.apply(is,arguments);
console.log();
if (arguments[2]==="completion") {
//This is the path you end up when a user types in the console and autocompletion get's evaluated
//Chrome expects a wrapped result to be returned from evaluateAndWrap.
//You can use `ev` to generate an object yourself.
//In case of the autocompletion chrome exptects an wrapped object with the properties that can be autocompleted. e.g.;
//{iGetAutoCompleted: true}
//You would then go and return that object wrapped, like
//return ev.call (is, '', '({test:true})', 'completion', true, false, true);
//Would make `test` pop up for every autocompletion.
//Note that syntax as well as every Object.prototype property get's added to that list later,
//so you won't be able to exclude things like `while` from the autocompletion list,
//unless you wou'd find a way to rewrite the getCompletions function.
//
return res; //Return the autocompletion result. If you want to break that, return nothing or an empty object
} else {
//This is the path where you end up when a user actually presses enter to evaluate an expression.
//In order to return anything as normal evaluation output, you have to return a wrapped object.
//In this case, we want to return the generated remote object.
//Since this is already a wrapped object it would be converted if we directly return it. Hence,
//`return result` would actually replicate the very normal behaviour as the result is converted.
//to output what's actually in the remote object, we have to stringify it and `evaluateAndWrap` that object again.`
//This is quite interesting;
return ev.call (is, null, '(' + JSON.stringify (res) + ')', "console", true, false, true)
}
};
},0);
It's a bit verbose, but I thought I put some comments into it
So normally, if a user, for example, evaluates [1,2,3,4]
you'd expect the following output:
After monkeypatching InjectedScript._evaluateAndWrap
evaluating the very same expression, gives the following output:
As you see the little-left arrow, indicating output, is still there, but this time we get an object. Where the result of the expression, the array [1,2,3,4]
is represented as an object with all its properties described.
I recommend trying to evaluate this and that expression, including those that generate errors. It's quite interesting.
Additionally, take a look at the is
- InjectedScriptHost
- object. It provides some methods to play with and get a bit of insight into the internals of the inspector.
Of course, you could intercept all that information and still return the original result to the user.
Just replace the return statement in the else path by a console.log (res)
following a return res
. Then you'd end up with the following.
End of Edit
This is the prior version which was fixed by Google. Hence not a possible way anymore.
One of it is hooking into Function.prototype.call
Chrome evaluates the entered expression by call
ing its eval function with InjectedScriptHost
as thisArg
var result = evalFunction.call(object, expression);
Given this, you can listen for the thisArg
of call
being evaluate
and get a reference to the first argument (InjectedScriptHost
)
if (window.URL) {
var ish, _call = Function.prototype.call;
Function.prototype.call = function () { //Could be wrapped in a setter for _commandLineAPI, to redefine only when the user started typing.
if (arguments.length > 0 && this.name === "evaluate" && arguments [0].constructor.name === "InjectedScriptHost") { //If thisArg is the evaluate function and the arg0 is the ISH
ish = arguments[0];
ish.evaluate = function (e) { //Redefine the evaluation behaviour
throw new Error ('Rejected evaluation of: \n\'' + e.split ('\n').slice(1,-1).join ("\n") + '\'');
};
Function.prototype.call = _call; //Reset the Function.prototype.call
return _call.apply(this, arguments);
}
};
}
You could e.g. throw an error, that the evaluation was rejected.
Here is an example where the entered expression gets passed to a CoffeeScript compiler before passing it to the evaluate
function.
If you are comfortable mixing and matching between function and class syntax you can declare constants after the class (the constants are 'lifted') . Note that Visual Studio Code will struggle to auto-format the mixed syntax, (though it works).
class MyClass {_x000D_
// ..._x000D_
_x000D_
}_x000D_
MyClass.prototype.consts = { _x000D_
constant1: 33,_x000D_
constant2: 32_x000D_
};_x000D_
mc = new MyClass();_x000D_
console.log(mc.consts.constant2);
_x000D_
When I was doing the same query, I had hard time adjusting the solutions to my case, though all the previous answers have good insights.
Here is a solution when one has to acquire a list of unique objects, NOT strings.
Let's say, one has a list of Record object. Record
class has only properties of type String
, NO property of type int
.
Here implementing hashCode()
becomes difficult as hashCode()
needs to return an int
.
The following is a sample Record
Class.
public class Record{
String employeeName;
String employeeGroup;
Record(String name, String group){
employeeName= name;
employeeGroup = group;
}
public String getEmployeeName(){
return employeeName;
}
public String getEmployeeGroup(){
return employeeGroup;
}
@Override
public boolean equals(Object o){
if(o instanceof Record){
if (((Record) o).employeeGroup.equals(employeeGroup) &&
((Record) o).employeeName.equals(employeeName)){
return true;
}
}
return false;
}
@Override
public int hashCode() { //this should return a unique code
int hash = 3; //this could be anything, but I would chose a prime(e.g. 5, 7, 11 )
//again, the multiplier could be anything like 59,79,89, any prime
hash = 89 * hash + Objects.hashCode(this.employeeGroup);
return hash;
}
As suggested earlier by others, the class needs to override both the equals()
and the hashCode()
method to be able to use HashSet
.
Now, let's say, the list of Records is allRecord
(List<Record> allRecord
).
Set<Record> distinctRecords = new HashSet<>();
for(Record rc: allRecord){
distinctRecords.add(rc);
}
This will only add the distinct Records to the Hashset, distinctRecords.
Hope this helps.
Well, much as I like the list(s) version, here's another more verbose way I found (but it's cool so I thought I'd add it to the fray):
>>> text = "My hovercraft is full of eels"
>>> [text[i] for i in range(len(text))]
['M', 'y', ' ', 'h', 'o', 'v', 'e', 'r', 'c', 'r', 'a', 'f', 't', ' ', 'i', 's', ' ', 'f', 'u', 'l', 'l', ' ', 'o', 'f', ' ', 'e', 'e', 'l', 's']
Quote from "Eloquent Javascript" 3rd edition by Marijn Haverbeke:
The difference in meaning between
undefined
andnull
is an accident of Javascript's design, and it doesn't matter most of the time. In cases where you actually have to concern yourself with these values, I recommend treating them as mostly interchangeable
Honestly, at first, I am a bit skeptical about this advice. However, in my own interpretation, it is a lazy
(vs eager
) way to deal with their differences. Maybe, we don't have to deal with the differences at all. If we have to, we can delay our concern (util we have to) and not hyperactively/defensively
worry about it every step of the way as those values (null
and undefined
) flow through our code.
PS: This is not a direct answer to your question. This is just a related opinion.
I don't think you can use fractional seconds with to_date or the DATE type in Oracle. I think you need to_timestamp which returns a TIMESTAMP type.
There are several ways to configure angular2 with Bootstrap, one of the most complete ways to get the most of it is to use ng-bootstrap, using this configuration we give to algular2 complete control over our DOM, avoiding the need to use JQuery and Boostrap.js.
1-Take as a starting point a new project created with Angular-CLI and using the command line, install ng-bootstrap:
npm install @ng-bootstrap/ng-bootstrap --save
Note: More info at https://ng-bootstrap.github.io/#/getting-started
2-Then we need to install bootstrap for the css and the grid system.
npm install [email protected] --save
Note: More info at https://getbootstrap.com/docs/4.0/getting-started/download/
Now we have the setup the environment and for that we have to change the .angular-cli.json adding to the style:
"../node_modules/bootstrap/dist/css/bootstrap.min.css"
Here is an example:
"apps": [
{
"root": "src",
...
],
"index": "index.html",
...
"prefix": "app",
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
"styles.css"
],
"scripts": [],
"environmentSource": "environments/environment.ts",
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
]
The next step is to add the ng-boostrap module to our project, to do so we need to add on the app.module.ts:
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
Then add the new module to the application app: NgbModule.forRoot()
Example:
@NgModule({
declarations: [
AppComponent,
AppNavbarComponent
],
imports: [
BrowserModule,
NgbModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
Now we can start using bootstrap4 on our angular2/5 project.
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.
The error comes when you try to call sum(x)
and x
is a factor.
What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)
simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:
family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))
For a detailed explanation of why the intermediate as.character
step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?
Useful method from Apache Commons:
org.apache.commons.lang.StringUtils.isBlank(String str)
select age(timestamp_A, timestamp_B)
Answering to Igor's comment:
select age('2013-02-28 11:01:28'::timestamp, '2011-12-31 11:00'::timestamp);
age
-------------------------------
1 year 1 mon 28 days 00:01:28
This is not an answer per se, but here's something interesting:
$y = str_replace('z', 'e', 'zxzc');
$y("malicious code");
In the same spirit, call_user_func_array()
can be used to execute obfuscated functions.
You will have to use some sort of network sniffer if you want to get at this sort of data and you're likely to run into the same problem (pulling out the relevant data from the overall network traffic) with those that you do now with Wireshark.
I have just found this site – http://unused-css.com/
Looks good but I would need to thoroughly check its outputted 'clean' css before uploading it to any of my sites.
Also as with all these tools I would need to check it didn't strip id's and classes with no style but are used as JavaScript selectors.
The below content is taken from http://unused-css.com/ so credit to them for recommending other solutions:
Latish Sehgal has written a windows application to find and remove unused CSS classes. I haven't tested it but from the description, you have to provide the path of your html files and one CSS file. The program will then list the unused CSS selectors. From the screenshot, it looks like there is no way to export this list or download a new clean CSS file. It also looks like the service is limited to one CSS file. If you have multiple files you want to clean, you have to clean them one by one.
Dust-Me Selectors is a Firefox extension (for v1.5 or later) that finds unused CSS selectors. It extracts all the selectors from all the stylesheets on the page you're viewing, then analyzes that page to see which of those selectors are not used. The data is then stored so that when testing subsequent pages, selectors can be crossed off the list as they're encountered. This tool is supposed to be able to spider a whole website but I unfortunately could make it work. Also, I don't believe you can configure and download the CSS file with the styles removed.
Topstyle is a windows application including a bunch of tools to edit CSS. I haven't tested it much but it looks like it has the ability to removed unused CSS selectors. This software costs 80 USD.
Liquidcity CSS cleaner is a php script that uses regular expressions to check the styles of one page. It will tell you the classes that aren't available in the HTML code. I haven't tested this solution.
Deadweight is a CSS coverage tool. Given a set of stylesheets and a set of URLs, it determines which selectors are actually used and lists which can be "safely" deleted. This tool is a ruby module and will only work with rails website. The unused selectors have to be manually removed from the CSS file.
Helium CSS is a javascript tool for discovering unused CSS across many pages on a web site. You first have to install the javascript file to the page you want to test. Then, you have to call a helium function to start the cleaning.
UnusedCSS.com is web application with an easy to use interface. Type the url of a site and you will get a list of CSS selectors. For each selector, a number indicates how many times a selector is used. This service has a few limitations. The @import statement is not supported. You can't configure and download the new clean CSS file.
CSSESS is a bookmarklet that helps you find unused CSS selectors on any site. This tool is pretty easy to use but it won't let you configure and download clean CSS files. It will only list unused CSS files.
FirebaseMessaging.getInstance().getToken().addOnSuccessListener(new
OnSuccessListener<String>() {
@Override
public void onSuccess(String newToken) {
....
}
});
CREATE TABLE `voting` (
`QuestionID` int(10) unsigned NOT NULL,
`MemberId` int(10) unsigned NOT NULL,
`vote` int(10) unsigned NOT NULL,
PRIMARY KEY (`QuestionID`,`MemberId`)
);
Do following steps to detect your device in eclipse : -
On Mobile Side:- For Connect USB sync, your Android device needs to have USB Debugging enabled.
To enable Android USB Debugging Mode do following steps :-
Android 2.x - 3.x devices:
Go to Settings > Application > Development > USB Debugging.
Android 4.x devices:
Go to Settings > Developer Options > USB Debugging.
For devices running Android 4.2.2 or later, you may need to unlock Developer Options before it is available within the Menu:
On PC side
Now in eclipse do following steps to install your app in your device:-
You need to remove the <a>
tag to get rid of this.
or try using :-
<a href="/" onclick="return false;">123n</a>
This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....
To cover the identities listed:
IIS_IUSRS:
This is analogous to the old IIS6 IIS_WPG
group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.
IUSR:
This account is analogous to the old IUSR_<MACHINE_NAME>
local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).
For more information about IIS_IUSRS
and IUSR
see:
DefaultAppPool:
If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name>
will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool
created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>
. You also won't see these pool accounts in your computers User Manager. See the following for more information:
ASP.NET v4.0:
-
This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool
above.
NETWORK SERVICE:
-
The NETWORK SERVICE
account is a built-in identity introduced on Windows 2003. NETWORK SERVICE
is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).
In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE
). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" />
setting in web.config
file locally (if that setting is locked then it would need to be done by an admin in the machine.config
file).
Setting <identity impersonate="true">
is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).
In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR
or a specific custom anonymous account.
LOCAL SERVICE:
The LOCAL SERVICE
account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:
LOCAL SYSTEM:
You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.
In Practice:
In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity
. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity
:
In the website you should then configure the Authentication feature:
Right click and edit the Anonymous Authentication entry:
Ensure that "Application pool identity" is selected:
When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0
pool permissions then you can either do this via Explorer:
Click the "Check Names" button:
Or you can do this using the ICACLS.EXE
utility:
icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)
...or...if you site's application pool is called BobsCatPicBlog
then:
icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)
I hope this helps clear things up.
Update:
I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:
The difference between the 'Local System' account and the 'Network Service' account?
for x in y[:-1]
If y
is a generator, then the above will not work.
initialize the Session class in the constructor of controller using
$this->load->library('session');
for example :
function __construct()
{
parent::__construct();
$this->load->model('user','',TRUE);
$this->load->model('user_activity','',TRUE);
$this->load->library('session');
}
Your example does work. Here's a simplified version.
package main
import "fmt"
func weird(i int) interface{} {
if i < 0 {
return "negative"
}
return i
}
func main() {
var i = 42
if w, ok := weird(7).(int); ok {
i += w
}
if w, ok := weird(-100).(int); ok {
i += w
}
fmt.Println("i =", i)
}
Output:
i = 49
It uses Type assertions.
You have a ; at the end of the if
.
Change:
if (fp == NULL);
return 0;
to
if (fp == NULL)
return 0;
If you are willing to add a few characters to your pool of allowed characters, you can make the code work with anything which provides random bytes through a io.Reader. Here we are using crypto/rand
.
// len(encodeURL) == 64. This allows (x <= 265) x % 64 to have an even
// distribution.
const encodeURL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
// A helper function create and fill a slice of length n with characters from
// a-zA-Z0-9_-. It panics if there are any problems getting random bytes.
func RandAsciiBytes(n int) []byte {
output := make([]byte, n)
// We will take n bytes, one byte for each character of output.
randomness := make([]byte, n)
// read all random
_, err := rand.Read(randomness)
if err != nil {
panic(err)
}
// fill output
for pos := range output {
// get random item
random := uint8(randomness[pos])
// random % 64
randomPos := random % uint8(len(encodeURL))
// put into output
output[pos] = encodeURL[randomPos]
}
return output
}
Also, there is an awesome open-source pure-python distributed and scaleable locust framework that uses greenlets. It's great at simulating enormous amount of simultaneous users.
i think you use this method to compress the bitmap
BitmapFactory.Option imageOpts = new BitmapFactory.Options ();
imageOpts.inSampleSize = 2; // for 1/2 the image to be loaded
Bitmap thumb = Bitmap.createScaledBitmap (BitmapFactory.decodeFile(photoPath, imageOpts), 96, 96, false);
I have to say your workflow is not in a standard Android way. In Android, you don't need to finish()
your activity if you want to open another activity from Intent. As for user's convenience, Android allows user to use 'back' key to go back from the activity that you opened to your app.
So just let the system stop you activity and save anything need to when you activity is called back.
The following code can be used to read the input string from a user. But it's space is limited to 64.
char word[64] = { '\0' }; //initialize all elements with '\0'
int i = 0;
while ((word[i] != '\n')&& (i<64))
{
scanf_s("%c", &word[i++], 1);
}
You can only include a script file in an HTML page, not in another script file. That said, you can write JavaScript which loads your "included" script into the same page:
var imported = document.createElement('script');
imported.src = '/path/to/imported/script';
document.head.appendChild(imported);
There's a good chance your code depends on your "included" script, however, in which case it may fail because the browser will load the "imported" script asynchronously. Your best bet will be to simply use a third-party library like jQuery or YUI, which solves this problem for you.
// jQuery
$.getScript('/path/to/imported/script.js', function()
{
// script is now loaded and executed.
// put your dependent JS here.
});
To view console while debugging your chrome extension, you should use the chrome.extension.getBackgroundPage();
API, after that you can use console.log()
as usual:
chrome.extension.getBackgroundPage().console.log('Testing');
This is good when you use multiple time, so for that you create custom function:
const console = {
log: (info) => chrome.extension.getBackgroundPage().console.log(info),
};
console.log("foo");
you only use console.log('learnin')
everywhere
The accepted answer is very old.
I found a better modern answer here:
https://kevinmccarthy.org/2016/07/25/streaming-subprocess-stdin-and-stdout-with-asyncio-in-python/
and made some changes:
import sys
import asyncio
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
async def _read_stream(stream, cb):
while True:
line = await stream.readline()
if line:
cb(line)
else:
break
async def _stream_subprocess(cmd, stdout_cb, stderr_cb):
try:
process = await asyncio.create_subprocess_exec(
*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)
await asyncio.wait(
[
_read_stream(process.stdout, stdout_cb),
_read_stream(process.stderr, stderr_cb),
]
)
rc = await process.wait()
return process.pid, rc
except OSError as e:
# the program will hang if we let any exception propagate
return e
def execute(*aws):
""" run the given coroutines in an asyncio loop
returns a list containing the values returned from each coroutine.
"""
loop = asyncio.get_event_loop()
rc = loop.run_until_complete(asyncio.gather(*aws))
loop.close()
return rc
def printer(label):
def pr(*args, **kw):
print(label, *args, **kw)
return pr
def name_it(start=0, template="s{}"):
"""a simple generator for task names
"""
while True:
yield template.format(start)
start += 1
def runners(cmds):
"""
cmds is a list of commands to excecute as subprocesses
each item is a list appropriate for use by subprocess.call
"""
next_name = name_it().__next__
for cmd in cmds:
name = next_name()
out = printer(f"{name}.stdout")
err = printer(f"{name}.stderr")
yield _stream_subprocess(cmd, out, err)
if __name__ == "__main__":
cmds = (
[
"sh",
"-c",
"""echo "$SHELL"-stdout && sleep 1 && echo stderr 1>&2 && sleep 1 && echo done""",
],
[
"bash",
"-c",
"echo 'hello, Dave.' && sleep 1 && echo dave_err 1>&2 && sleep 1 && echo done",
],
[sys.executable, "-c", 'print("hello from python");import sys;sys.exit(2)'],
)
print(execute(*runners(cmds)))
It is unlikely that the example commands will work perfectly on your system, and it doesn't handle weird errors, but this code does demonstrate one way to run multiple subprocesses using asyncio and stream the output.
#include <algorithm>
std::reverse(str.begin(), str.end());
This is the simplest way in C++.
As of macOS Catalina 10.15.6, I run:
brew install git
brew install git-gui
and it worked for me.
you could also grep the line out and then cut it like for instance:
grep 'text' filename | cut -c 1-5
The CSS styles for text input controls such as TextField for JavaFX 8 are defined in the modena.css stylesheet as below. Create a custom CSS stylesheet and modify the colors as you wish. Use the CSS reference guide if you need help understanding the syntax and available attributes and values.
.text-input {
-fx-text-fill: -fx-text-inner-color;
-fx-highlight-fill: derive(-fx-control-inner-background,-20%);
-fx-highlight-text-fill: -fx-text-inner-color;
-fx-prompt-text-fill: derive(-fx-control-inner-background,-30%);
-fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border),
linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
-fx-background-insets: 0, 1;
-fx-background-radius: 3, 2;
-fx-cursor: text;
-fx-padding: 0.333333em 0.583em 0.333333em 0.583em; /* 4 7 4 7 */
}
.text-input:focused {
-fx-highlight-fill: -fx-accent;
-fx-highlight-text-fill: white;
-fx-background-color:
-fx-focus-color,
-fx-control-inner-background,
-fx-faint-focus-color,
linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
-fx-background-insets: -0.2, 1, -1.4, 3;
-fx-background-radius: 3, 2, 4, 0;
-fx-prompt-text-fill: transparent;
}
Although using an external stylesheet is a preferred way to do the styling, you can style inline, using something like below:
textField.setStyle("-fx-text-inner-color: red;");
Error happens in your function declarations,look the following sentence!You need a semicolon!
AST_NODE* Statement(AST_NODE* node)
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
Reproducing my answer from this post as it is a better fit here.
Starting C# v7.0, now it is possible to name the tuple properties which earlier used to default to predefined names like Item1
, Item2
and so on.
Naming the properties of Tuple Literals:
var myDetails = (MyName: "RBT_Yoga", MyAge: 22, MyFavoriteFood: "Dosa");
Console.WriteLine($"Name - {myDetails.MyName}, Age - {myDetails.MyAge}, Passion - {myDetails.MyFavoriteFood}");
The output on console:
Name - RBT_Yoga, Age - 22, Passion - Dosa
Returning Tuple (having named properties) from a method:
static void Main(string[] args)
{
var empInfo = GetEmpInfo();
Console.WriteLine($"Employee Details: {empInfo.firstName}, {empInfo.lastName}, {empInfo.computerName}, {empInfo.Salary}");
}
static (string firstName, string lastName, string computerName, int Salary) GetEmpInfo()
{
//This is hardcoded just for the demonstration. Ideally this data might be coming from some DB or web service call
return ("Rasik", "Bihari", "Rasik-PC", 1000);
}
The output on console:
Employee Details: Rasik, Bihari, Rasik-PC, 1000
Creating a list of Tuples having named properties
var tupleList = new List<(int Index, string Name)>
{
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};
foreach (var tuple in tupleList)
Console.WriteLine($"{tuple.Index} - {tuple.Name}");
Output on console:
1 - cow 5 - chickens 1 - airplane
I hope I've covered everything. In case, there is anything which I've missed then please give me a feedback in comments.
Note: My code snippets are using string interpolation feature of C# v7 as detailed here.
I'm going to leave this one here: https://stackoverflow.com/a/14509697/1356953
Please note that this works with java.lang.SuppressWarnings
so no need to use a separate annotation.
@SuppressWarnings on a field only suppresses findbugs warnings reported for that field declaration, not every warning associated with that field.
For example, this suppresses the "Field only ever set to null" warning:
@SuppressWarnings("UWF_NULL_FIELD") String s = null; I think the best you can do is isolate the code with the warning into the smallest method you can, then suppress the warning on the whole method.
Use the following query:
SELECT * FROM SAMPLE_TABLE ORDER BY ROWID ASC LIMIT 1
Note: Sqlite's row id references are detailed here.
For the same reason you can also use inheritIO()
to map Java console with external app console like:
ProcessBuilder pb = new ProcessBuilder(appPath, arguments);
pb.directory(new File(appFile.getParent()));
pb.inheritIO();
Process process = pb.start();
int success = process.waitFor();
Here's Jeanne's lovely answer, but wrapped in a tidy function for muppets like me:
private static String getUrl(String aUrl) throws MalformedURLException, IOException
{
String urlData = "";
URL urlObj = new URL(aUrl);
URLConnection conn = urlObj.openConnection();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)))
{
urlData = reader.lines().collect(Collectors.joining("\n"));
}
return urlData;
}
An example with VBScript (.vbs)
Sub sety(wsh, action, typey, vary, value)
Dim wu
Set wu = wsh.Environment(typey)
wui = wu.Item(vary)
Select Case action
Case "ls"
WScript.Echo wui
Case "del"
On Error Resume Next
wu.remove(vary)
On Error Goto 0
Case "set"
wu.Item(vary) = value
Case "add"
If wui = "" Then
wu.Item(vary) = value
ElseIf InStr(UCase(";" & wui & ";"), UCase(";" & value & ";")) = 0 Then
wu.Item(vary) = value & ";" & wui
End If
Case Else
WScript.Echo "Bad action"
End Select
End Sub
Dim wsh, args
Set wsh = WScript.CreateObject("WScript.Shell")
Set args = WScript.Arguments
Select Case WScript.Arguments.Length
Case 3
value = ""
Case 4
value = args(3)
Case Else
WScript.Echo "Arguments - 0: ls,del,set,add; 1: user,system, 2: variable; 3: value"
value = "```"
End Select
If Not value = "```" Then
' 0: ls,del,set,add; 1: user,system, 2: variable; 3: value
sety wsh, args(0), args(1), UCase(args(2)), value
End If
Try this using this single code:
import javax.ws.rs.POST;
import javax.ws.rs.Path;
@Path("/serviceX")
public class MyClassRESTService {
@POST
@Path("/doSomething")
public void someMethod(String x) {
System.out.println(x);
// String x contains the body, you can process
// it, parse it using JAXB and so on ...
}
}
The url for try rest services ends .... /serviceX/doSomething
For me it was due to insufficient disk space , and it was resolved after I freed up some disk space on my local drive.
For IPython version 3.1, 4.x, and 5.x
%load_ext autoreload
%autoreload 2
Then your module will be auto-reloaded by default. This is the doc:
File: ...my/python/path/lib/python2.7/site-packages/IPython/extensions/autoreload.py
Docstring:
``autoreload`` is an IPython extension that reloads modules
automatically before executing the line of code typed.
This makes for example the following workflow possible:
.. sourcecode:: ipython
In [1]: %load_ext autoreload
In [2]: %autoreload 2
In [3]: from foo import some_function
In [4]: some_function()
Out[4]: 42
In [5]: # open foo.py in an editor and change some_function to return 43
In [6]: some_function()
Out[6]: 43
The module was reloaded without reloading it explicitly, and the
object imported with ``from foo import ...`` was also updated.
There is a trick: when you forget all of the above when using ipython
, just try:
import autoreload
?autoreload
# Then you get all the above
Because templates are compiled when required, this forces a restriction for multi-file projects: the implementation (definition) of a template class or function must be in the same file as its declaration. That means that we cannot separate the interface in a separate header file, and that we must include both interface and implementation in any file that uses the templates.
You need to load your class replace :
foobar::foobarfunc();
by :
(new foobar())->foobarfunc();
or :
$Foobar = new foobar();
$Foobar->foobarfunc();
Or make static function to use foobar::
.
class foobar {
//...
static function foobarfunc() {
return $this->foo();
}
}
I was scratching my head about this for a while too, and since Dave's explanation is a little hard to understand I'll post my (apparently working) code:
private class TabListener<T extends Fragment> implements ActionBar.TabListener {
private Fragment mFragment;
private Activity mActivity;
private final String mTag;
private final Class<T> mClass;
public TabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
mFragment=mActivity.getFragmentManager().findFragmentByTag(mTag);
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.replace(android.R.id.content, mFragment, mTag);
} else {
if (mFragment.isDetached()) {
ft.attach(mFragment);
}
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
As you can see it's pretty much like the Android sample, apart from not detaching in the constructor, and using replace instead of add.
After much headscratching and trial-and-error I found that finding the fragment in the constructor seems to make the double onCreateView problem magically go away (I assume it just ends up being null for onTabSelected when called through the ActionBar.setSelectedNavigationItem() path when saving/restoring state).
In addition to the Carlos Heuberger's reply: if a different than the default (80) is needed, the 7 param constructor should be used:
URI uri = new URI(
"http",
null, // this is for userInfo
"www.google.com",
8080, // port number as int
"/ig/api",
"weather=São Paulo",
null);
String request = uri.toASCIIString();
I've had to do this a few times to-date. Note that this only works on 1 file at a time.
Get a list of all commits that modified a file. The one at the bottom will the the first commit:
git log --pretty=oneline --branches -- pathToFile
To remove the file from history use the first commit sha1 and the path to file from the previous command, and fill them into this command:
git filter-branch --index-filter 'git rm --cached --ignore-unmatch <path-to-file>' -- <sha1-where-the-file-was-first-added>..
value="<?php echo htmlspecialchars($name); ?>"
- (void)viewWillAppear:(BOOL)animated
{
[self setDetailViewNavigationBar];
}
-(void)setDetailViewNavigationBar
{
self.navigationController.navigationBar.tintColor = [UIColor purpleColor];
[self setNavigationBarRightButton];
[self setNavigationBarBackButton];
}
-(void)setNavigationBarBackButton// using custom button
{
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@" Back " style:UIBarButtonItemStylePlain target:self action:@selector(onClickLeftButton:)];
self.navigationItem.leftBarButtonItem = leftButton;
}
- (void)onClickLeftButton:(id)sender
{
NSLog(@"onClickLeftButton");
}
-(void)setNavigationBarRightButton
{
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Show" style:UIBarButtonItemStylePlain target:self action:@selector(onClickrighttButton:)];
self.navigationItem.rightBarButtonItem = anotherButton;
}
- (void)onClickrighttButton:(id)sender
{
NSLog(@"onClickrighttButton");
}
This is all you need:
background-repeat: no-repeat;
as @fabrizio-valencia said use lower case. in windows if you export mysql database (phpmyadmin) the tables name will converted to lower case and this lead to all sort of problems. see Are table names in MySQL case sensitive?
Simple and easy!
get_queried_object_id()
I was trying to install fancyimpute package for imputation but there was not luck. But when i tried below commands, it got installed: Commands:
conda update conda
conda update anaconda
pip install fancyimpute
(here i was trying to give command conda install fancyimpute which did't work)
I was getting the same error with building USBView project in VS2015. I removed this error by selecting 'Platform Toolset' settings to to "Visual Studio 2015 (v140)" and than right click on solution (in VS2015) and select 'Retarget Solution' and selected 10.0.10240.0 on that dialog.
It seems like there is also ProjectUpgradeTool from microsoft which is suppose to convert older projects to upgrade to post VS2012 VS but I couldn't locate that tool on my machine.
I still have to fix some new linker error with help of this.
Writing an extension method is the most efficient way in my opinion
public static string PeekBody(this HttpRequest request)
{
try
{
request.EnableBuffering();
var buffer = new byte[Convert.ToInt32(request.ContentLength)];
request.Body.Read(buffer, 0, buffer.Length);
return Encoding.UTF8.GetString(buffer);
}
finally
{
request.Body.Position = 0;
}
}
You can use Request.Body.Peeker Nuget Package as well (source code)
//Return string
var request = HttpContext.Request.PeekBody();
//Return in expected type
LoginRequest request = HttpContext.Request.PeekBody<LoginRequest>();
//Return in expected type asynchronously
LoginRequest request = await HttpContext.Request.PeekBodyAsync<LoginRequest>();
To view the stdout, you can start the docker container with -i
. This of course does not enable you to leave the started process and explore the container.
docker start -i containerid
Alternatively you can view the filesystem of the container at
/var/lib/docker/containers/containerid/root/
However neither of these are ideal. If you want to view logs or any persistent storage, the correct way to do so would be attaching a volume with the -v
switch when you use docker run
. This would mean you can inspect log files either on the host or attach them to another container and inspect them there.
Example from http://www.cplusplus.com/reference/string/string/find_last_of/
// string::find_last_of
#include <iostream>
#include <string>
using namespace std;
void SplitFilename (const string& str)
{
size_t found;
cout << "Splitting: " << str << endl;
found=str.find_last_of("/\\");
cout << " folder: " << str.substr(0,found) << endl;
cout << " file: " << str.substr(found+1) << endl;
}
int main ()
{
string str1 ("/usr/bin/man");
string str2 ("c:\\windows\\winhelp.exe");
SplitFilename (str1);
SplitFilename (str2);
return 0;
}
I solved this issue by running cmd as an administrator. before that, I was trying to run in vs code.
run it in Power Shell or Cmd with administrative privilege. I hope that it will help.
npm install –g @angular/cli@latest
I realise this is an old question, but another possible consideration depending on your exact requirements is that validating on https://validator.w3.org/ generates warnings as follows:
Warning: The form role is unnecessary for element form.
There are a few ways to do this:
1) Get values from array of form elements by index
handleSubmit = (event) => {
event.preventDefault();
console.log(event.target[0].value)
}
2) Using name attribute in html
handleSubmit = (event) => {
event.preventDefault();
console.log(event.target.elements.username.value) // from elements property
console.log(event.target.username.value) // or directly
}
<input type="text" name="username"/>
3) Using refs
handleSubmit = (event) => {
console.log(this.inputNode.value)
}
<input type="text" name="username" ref={node => (this.inputNode = node)}/>
Full example
class NameForm extends React.Component {
handleSubmit = (event) => {
event.preventDefault()
console.log(event.target[0].value)
console.log(event.target.elements.username.value)
console.log(event.target.username.value)
console.log(this.inputNode.value)
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input
type="text"
name="username"
ref={node => (this.inputNode = node)}
/>
</label>
<button type="submit">Submit</button>
</form>
)
}
}
1.You don't need the @
prefix for attribute names any more:
http://api.jquery.com/category/selectors/attribute-selectors/:
Note: In jQuery 1.3 [@attr] style selectors were removed (they were previously deprecated in jQuery 1.2). Simply remove the ‘@’ symbol from your selectors in order to make them work again.
2.Your selector queries radio buttons by name
, but that attribute is not defined in your HTML structure.
Here's what I found at https://perldoc.perl.org/perlvar.html:
$\ The output record separator for the print operator. If defined, this value is printed after the last of print's arguments. Default is undef.
You cannot call output_record_separator() on a handle, only as a static method. See IO::Handle.
Mnemonic: you set $\ instead of adding "\n" at the end of the print. Also, it's just like $/ , but it's what you get "back" from Perl.
example:
$\ = "\n";
print "a newline will be appended to the end of this line automatically";
Frankly I use a tcomment plugin for that link. It can handle almost every syntax. It defines nice movements, using it with some text block matchers specific for python makes it a powerful tool.
Are you using JTextArea
's append(String)
method to add additional text?
JTextArea txtArea = new JTextArea("Hello, World\n", 20, 20);
txtArea.append("Goodbye Cruel World\n");
You can use the collate clause in a query (I can't find my example right now, so my syntax is probably wrong - I hope it points you in the right direction)
select sone_field collate SQL_Latin1_General_CP850_CI_AI
from table_1
inner join table_2
on (table_1.field collate SQL_Latin1_General_CP850_CI_AI = table_2.field)
where whatever
I'm guessing you didn't run this command after the commit failed so just actually run this to create the remote :
git remote add origin https://github.com/VijayNew/NewExample.git
And the commit failed because you need to git add
some files you want to track.
Chain both class selectors (without a space in between):
.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}
If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar
in this case) instead, regardless of what other classes you list.
To illustrate how other browsers and IE6 interpret this, consider this CSS:
* {
color: black;
}
.foo.bar {
color: red;
}
Output on supported browsers is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Not selected, black text [3] -->
Output on IE6 is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Selected, red text [2] -->
Footnotes:
foo
.foo
and bar
.bar
.
bar
.bar
, regardless of any other classes listed.My first contribution to the site. Also, according to the tests that I have done, this code runs faster than all the other methods mentioned here before this date, of course it is minimal if there are few values, but the time increases exponentially when adding too many.
var result = permutations([1,2,3,4]);
var output = window.document.getElementById('output');
output.innerHTML = JSON.stringify(result);
function permutations(arr) {
var finalArr = [];
function iterator(arrayTaken, tree) {
var temp;
for (var i = 0; i < tree; i++) {
temp = arrayTaken.slice();
temp.splice(tree - 1 - i, 0, temp.splice(tree - 1, 1)[0]);
if (tree >= arr.length) {
finalArr.push(temp);
} else {
iterator(temp, tree + 1);
}
}
}
iterator(arr, 1);
return finalArr;
};
_x000D_
<div id="output"></div>
_x000D_
try with
sudo adb kill-server
sudo devices
or
echo $ANDROID_HOME
sudo $ANDROID_HOME/platform-tools/adb kill-server
sudo $ANDROID_HOME/platform-tools/adb devices
Follow the below steps for push the local repo into Master branchenter code here
$git status
Also worth noting window.scrollBy(dx,dy)
(ref)
You wrote """I assume that means the HTML contains some wrongly-formed attempt at unicode somewhere."""
The HTML is NOT expected to contain any kind of "attempt at unicode", well-formed or not. It must of necessity contain Unicode characters encoded in some encoding, which is usually supplied up front ... look for "charset".
You appear to be assuming that the charset is UTF-8 ... on what grounds? The "\xA0" byte that is shown in your error message indicates that you may have a single-byte charset e.g. cp1252.
If you can't get any sense out of the declaration at the start of the HTML, try using chardet to find out what the likely encoding is.
Why have you tagged your question with "regex"?
Update after you replaced your whole question with a non-question:
html = urllib.urlopen(link).read()
# html refers to a str object. To get unicode, you need to find out
# how it is encoded, and decode it.
html.encode("utf8","ignore")
# problem 1: will fail because html is a str object;
# encode works on unicode objects so Python tries to decode it using
# 'ascii' and fails
# problem 2: even if it worked, the result will be ignored; it doesn't
# update html in situ, it returns a function result.
# problem 3: "ignore" with UTF-n: any valid unicode object
# should be encodable in UTF-n; error implies end of the world,
# don't try to ignore it. Don't just whack in "ignore" willy-nilly,
# put it in only with a comment explaining your very cogent reasons for doing so.
# "ignore" with most other encodings: error implies that you are mistaken
# in your choice of encoding -- same advice as for UTF-n :-)
# "ignore" with decode latin1 aka iso-8859-1: error implies end of the world.
# Irrespective of error or not, you are probably mistaken
# (needing e.g. cp1252 or even cp850 instead) ;-)
Add:
display: inline-block;
to the style of your td
.
Add:
display: inline-block;
word-break: break-word;
to the style of your td
.
Note:
Mind that, as for now, break-word
is not part of the standard specification for webkit; therefore, you might be interested in employing the break-all
instead. This alternative value provides a undoubtedly drastic solution; however, it conforms to the standard.
Add:
display: inline-block;
word-break: break-word;
to the style of your td
.
The previous paragraph applies to Opera in a similar way.
str_replace will do the trick thusly
$new_str = str_replace(' ', '', $old_str);
For those wondering if jQuery id selectors are slower than document.getElementById, the answer is yes, but not because of the preconception that it searches through the entire DOM looking for an element. jQuery does actually use the native method. It's actually because jQuery uses a regular expression first to separate out strings in the selector to check by, and of course running the constructor:
rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/
Whereas using a DOM element as an argument returns immediately with 'this'.
So this:
$(document.getElementById('blah')).doSomething();
Will always be faster than this:
$('#blah').doSomething();
Try to assign the image that way instead:
imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, @"/Assets/favorited.png"));
just edit the function cell in the fpdf.php file, look for the line that looks like this
function cell ($w, $h = 0, $txt = '', $border = 0, $ln = 0, $align = '', $fill = false, $link = '')
{
after finding the line
write after the {
,
$txt = utf8_decode($txt);
save the file and ready, the accents and the utf8 encoding will be working :)
Here's a variation on this theme. I want to uninstall Cisco Amp, wait, and get the exit code. But the uninstall program starts a second program called "un_a" and exits. With this code, I can wait for un_a to finish and get the exit code of it, which is 3010 for "needs reboot". This is actually inside a .bat file.
If you've ever wanted to uninstall folding@home, it works in a similar way.
rem uninstall cisco amp, probably needs a reboot after
rem runs Un_A.exe and exits
rem start /wait isn't useful
"c:\program files\Cisco\AMP\6.2.19\uninstall.exe" /S
powershell while (! ($proc = get-process Un_A -ea 0)) { sleep 1 }; $handle = $proc.handle; 'waiting'; wait-process Un_A; exit $proc.exitcode
The question can be read as:
I was in detached-state with HEAD
at 23b6772
and typed git reset origin/master
(because I wanted to squash). Now I've changed my mind, how do I go back to HEAD
being at 23b6772
?
The straightforward answer being: git reset 23b6772
But I hit this question because I got sick of typing (copy & pasting) commit hashes or its abbreviation each time I wanted to reference the previous HEAD
and was Googling to see if there were any kind of shorthand.
git reset -
(or in my case git cherry-pick -
)
Which incidentally was the same as cd -
to return to the previous current directory in *nix! So hurrah, I learned two things with one stone.
If you need to write a lot of sprocs for an API of some sort. You may like this tools I wrote when I was a programmer. Say you have a 200 columns table that need to have a sproc written to insert/update and another one to delete. Because you don't want your application to directly access the tables. Just the declaration part will be a tedious task but not if a part of the code is written for you. Here's an example...
CREATE PROC upsert_Table1(@col1 int, @col2 varchar(200), @col3 float, etc.)
AS
BEGIN
UPDATE table1 SET col1 = @col1, col2 = @col2, col3 = @col3, etc.
IF @@error <> 0
INSERT Table1 (col1, col2, col3, etc.)
VALUES(@col1, @col2, @col3, etc.)
END
GO
CREATE PROC delete_Table1(@col1)
AS DELETE FROM Table1 WHERE col1 = @col1
http://snipplr.com/view/13451/spcoldefinition-or-writing-upsert-sp-in-a-snap/
Note : You can also get to the original code and article written in 2002 (I feel old now!)
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=549&lngWId=5
Try grepl
on the names of your data.frame
. grepl
matches a regular expression to a target and returns TRUE
if a match is found and FALSE
otherwise. The function is vectorised so you can pass a vector of strings to match and you will get a vector of boolean values returned.
# Data
df <- data.frame( ABC_1 = runif(3),
ABC_2 = runif(3),
XYZ_1 = runif(3),
XYZ_2 = runif(3) )
# ABC_1 ABC_2 XYZ_1 XYZ_2
#1 0.3792645 0.3614199 0.9793573 0.7139381
#2 0.1313246 0.9746691 0.7276705 0.0126057
#3 0.7282680 0.6518444 0.9531389 0.9673290
# Use grepl
df[ , grepl( "ABC" , names( df ) ) ]
# ABC_1 ABC_2
#1 0.3792645 0.3614199
#2 0.1313246 0.9746691
#3 0.7282680 0.6518444
# grepl returns logical vector like this which is what we use to subset columns
grepl( "ABC" , names( df ) )
#[1] TRUE TRUE FALSE FALSE
To answer the second part, I'd make the subset data.frame and then make a vector that indexes the rows to keep (a logical vector) like this...
set.seed(1)
df <- data.frame( ABC_1 = sample(0:1,3,repl = TRUE),
ABC_2 = sample(0:1,3,repl = TRUE),
XYZ_1 = sample(0:1,3,repl = TRUE),
XYZ_2 = sample(0:1,3,repl = TRUE) )
# We will want to discard the second row because 'all' ABC values are 0:
# ABC_1 ABC_2 XYZ_1 XYZ_2
#1 0 1 1 0
#2 0 0 1 0
#3 1 1 1 0
df1 <- df[ , grepl( "ABC" , names( df ) ) ]
ind <- apply( df1 , 1 , function(x) any( x > 0 ) )
df1[ ind , ]
# ABC_1 ABC_2
#1 0 1
#3 1 1
Bootstrap 4.0
Be aware of all migration changes from Bootstrap 3 to 4. On the table you now need to enable flex box by adding the class d-flex
, and drop the xs
to allow bootstrap to automatically detect the viewport.
<div class="container-fluid">
<table id="productSizes" class="table">
<thead>
<tr class="d-flex">
<th class="col-1">Size</th>
<th class="col-3">Bust</th>
<th class="col-3">Waist</th>
<th class="col-5">Hips</th>
</tr>
</thead>
<tbody>
<tr class="d-flex">
<td class="col-1">6</td>
<td class="col-3">79 - 81</td>
<td class="col-3">61 - 63</td>
<td class="col-5">89 - 91</td>
</tr>
<tr class="d-flex">
<td class="col-1">8</td>
<td class="col-3">84 - 86</td>
<td class="col-3">66 - 68</td>
<td class="col-5">94 - 96</td>
</tr>
</tbody>
</table>
Bootstrap 3.2
Table column width use the same layout as grids do; using col-[viewport]-[size]
. Remember the column sizes should total 12; 1 + 3 + 3 + 5 = 12
in this example.
<thead>
<tr>
<th class="col-xs-1">Size</th>
<th class="col-xs-3">Bust</th>
<th class="col-xs-3">Waist</th>
<th class="col-xs-5">Hips</th>
</tr>
</thead>
Remember to set the <th>
elements rather than the <td>
elements so it sets the whole column. Here is a working BOOTPLY.
Thanks to @Dan for reminding me to always work mobile view (col-xs-*
) first.
Try this
public static void main(String[] args)
{
String original = "ABCDEFGHIJKLMNOPQ";
String tobeChecked = "GHi";
System.out.println(containsString(original, tobeChecked, true));
System.out.println(containsString(original, tobeChecked, false));
}
public static boolean containsString(String original, String tobeChecked, boolean caseSensitive)
{
if (caseSensitive)
{
return original.contains(tobeChecked);
}
else
{
return original.toLowerCase().contains(tobeChecked.toLowerCase());
}
}
The second part of your question is answered well. Here is the answer for the first part: How to output multiple files with webpack:
entry: {
outputone: './source/fileone.jsx',
outputtwo: './source/filetwo.jsx'
},
output: {
path: path.resolve(__dirname, './wwwroot/js/dist'),
filename: '[name].js'
},
This will generate 2 files: outputone.js und outputtwo.js in the target folder.
https://stackoverflow.com/a/16350929/11860907
If you add e.SuppressKeyPress = true;
as shown in the answer in this link you will suppress the annoying ding sound that occurs.
Just extend your formula out a little bit:
dateadd(day, -1,
dateadd(month, 1,
cast(month('5/15/2009') as varchar(2)) +
'/1/' +
cast(year('5/15/2009') as varchar(4)))
You were setting BCC but then overwriting the variable with the FROM
$to = "[email protected]";
$subject .= "".$emailSubject."";
$headers .= "Bcc: ".$emailList."\r\n";
$headers .= "From: [email protected]\r\n" .
"X-Mailer: php";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= 'THE MESSAGE FROM THE FORM';
if (mail($to, $subject, $message, $headers)) {
$sent = "Your email was sent!";
} else {
$sent = ("Error sending email.");
}
React:
If you are using React, you can do it as follows:
placeholder={'Address Line1\nAddress Line2\nCity State, Zip\nCountry'}