Use sudo npm install -g appium
.
You should always use the resource manager and not read files directly to ensure globalization is taken into account.
using System.Collections;
using System.Globalization;
using System.Resources;
...
/* Reference to your resources class -- may be named differently in your case */
ResourceManager MyResourceClass =
new ResourceManager(typeof(Resources));
ResourceSet resourceSet =
MyResourceClass.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
string resourceKey = entry.Key.ToString();
object resource = entry.Value;
}
@Entity
@Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames = "column1"),@UniqueConstraint(columnNames = "column2")})
-- Here both Column1 and Column2 acts as unique constraints separately. Ex : if any time either the value of column1 or column2 value matches then you will get UNIQUE_CONSTRAINT Error.
@Entity
@Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames ={"column1","column2"})})
-- Here both column1 and column2 combined values acts as unique constraints
In case you wonder, In Bootstrap templating system (which is very accurate), here is how they divide the columns when you apply the class .col-md-4 (1/3 of the 12 column system)
CSS
.col-md-4{
float: left;
width: 33.33333333%;
}
I'm not a fan of float, but if you really want your element to be perfectly 1/3 of your page, then you don't have a choice because sometimes when you use inline-block element, browser can consider space in your HTML as a 1px space which would break your perfect 1/3. Hope it helped !
If you are making the boolean column as not null then the default 'default' value is false; you don't have to explicitly specify it.
Have you tried height: auto;
on your .container
div?
Here is a fiddle, if you change img height, container height will adjust to it.
EDIT
So if you "can't" change the inline min-height
, you can overwrite the inline style with an !important
parameter. It's not the cleanest way, but it solves your problem.
add to your .container
class this line
min-height:0px !important;
I've updated my fiddle to give you an example.
You best see if you have a parent element of the div you are querying. If so get the parent element and perform an element.querySelectorAll("div")
. Once you get the nodeList
apply a filter on it over the innerText
property. Assume that a parent element of the div that we are querying has an id
of container
. You can normally access container directly from the id but let's do it the proper way.
var conty = document.getElementById("container"),
divs = conty.querySelectorAll("div"),
myDiv = [...divs].filter(e => e.innerText == "SomeText");
So that's it.
Another implementation, using Array.reduce (I think it’s the only one missing!):
const splitArray = (arr, size) =>
{
if (size === 0) {
return [];
}
return arr.reduce((split, element, index) => {
index % size === 0 ? split.push([element]) : split[Math.floor(index / size)].push(element);
return split;
}, []);
};
As many solutions above, this one’s non-destructive. Returning an empty array when the size is 0 is just a convention. If the if
block is omitted you get an error, which might be what you want.
Unless otherwise definied (<tfoot>
, <thead>
), browsers put <tr>
implicitly in a <tbody>
.
You need to put a > tbody
in between > table
and > tr
:
$("div.custList > table > tbody > tr")
Alternatively, you can also be less strict in selecting the rows (the >
denotes the immediate child):
$("div.custList table tr")
That said, you can get the immediate <td>
children there by $(this).children('td')
.
I have done it accessing the controls inside the cell control. Find in all control collections.
ControlCollection cc = (ControlCollection)e.Row.Controls[1].Controls;
Label lbCod = (Label)cc[1];
bobince's answer will let you know in which cases "height: XX%;" will or won't work.
If you want to create an element with a set ratio (height: % of it's own width), the best way to do that is by effectively setting the height using padding-bottom
. Example for square:
<div class="square-container">
<div class="square-content">
<!-- put your content in here -->
</div>
</div>
.square-container { /* any display: block; element */
position: relative;
height: 0;
padding-bottom: 100%; /* of parent width */
}
.square-content {
position: absolute;
left: 0;
top: 0;
height: 100%;
width: 100%;
}
The square container will just be made of padding, and the content will expand to fill the container. Long article from 2009 on this subject: http://alistapart.com/article/creating-intrinsic-ratios-for-video
I have solved this issue,
login to server computer where SQL Server is installed get you csv file on server computer and execute your query it will insert the records.
If you will give datatype compatibility issue change the datatype for that column
You have to patch catalina.jar
, as this is version number the WTP adapter looks at. It's a quite useless check, and the adapter should allow you to start the server anyway, but nobody has though of that yet.
For years and with every version of Tomcat this is always a problem.
To patch you can do the following:
cd [tomcat or tomee home]/lib
mkdir catalina
cd catalina/
unzip ../catalina.jar
vim org/apache/catalina/util/ServerInfo.properties
Make sure it looks like the following (the version numbers all need to start with 8.0):
server.info=Apache Tomcat/8.0.0
server.number=8.0.0
server.built=May 11 2016 21:49:07 UTC
Then:
jar uf ../catalina.jar org/apache/catalina/util/ServerInfo.properties
cd ..
rm -rf catalina
refer below link for getting ScanResult with redundant ssid removed from the list
To see your log in SQL Developer
then press:
CTRL+SHIFT + L (or CTRL + CMD + L on macOS)
or
View -> Log
or by using mysql query
show errors;
The only way that I know that enables you to use ajax cross-domain is JSONP (http://ajaxian.com/archives/jsonp-json-with-padding).
And here's a post that posts some various techniques to achieve cross-domain ajax (http://usejquery.com/posts/9/the-jquery-cross-domain-ajax-guide)
Here is the most inefficient way to get the count in all answers. But you'll get a Dictionary that contains key-value pairs as a bonus.
string test = "key1=value1&key2=value2&key3=value3";
var keyValues = Regex.Matches(test, @"([\w\d]+)=([\w\d]+)[&$]*")
.Cast<Match>()
.ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);
var count = keyValues.Count - 1;
Use a parameter array with the params
modifier:
public static int AddUp(params int[] values)
{
int sum = 0;
foreach (int value in values)
{
sum += value;
}
return sum;
}
If you want to make sure there's at least one value (rather than a possibly empty array) then specify that separately:
public static int AddUp(int firstValue, params int[] values)
(Set sum
to firstValue
to start with in the implementation.)
Note that you should also check the array reference for nullity in the normal way. Within the method, the parameter is a perfectly ordinary array. The parameter array modifier only makes a difference when you call the method. Basically the compiler turns:
int x = AddUp(4, 5, 6);
into something like:
int[] tmp = new int[] { 4, 5, 6 };
int x = AddUp(tmp);
You can call it with a perfectly normal array though - so the latter syntax is valid in source code as well.
{{convertToDate | date : dateformat}}
$rootScope.dateFormat = 'MM/dd/yyyy';
You need to use linecolor instead of lc, like:
set style line 1 lt 1 lw 3 pt 3 linecolor rgb "red"
"help set style line" gives you more info.
You can also use this
let str = "hello single ' double \" and slash \\ yippie";
let escapeStr = escape(str);
document.write("<b>str : </b>"+str);
document.write("<br/><b>escapeStr : </b>"+escapeStr);
document.write("<br/><b>unEscapeStr : </b> "+unescape(escapeStr));
_x000D_
find your target element "d" however you wish and then:
d.className += ' additionalClass'; //note the space
you can wrap that in cleverer ways to check pre-existence, and check for space requirements etc..
Also for eg. you can use IPC::Run:
use IPC::Run qw(run);
my $pid = 5892;
run [qw(top -H -n 1 -p), $pid],
'|', sub { print grep { /myprocess/ } <STDIN> },
'|', [qw(wc -l)],
'>', \my $out;
print $out;
You need to use ?param instead of @param when performing queries to MySQL
str_carSql = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (?id,?m_id,?model,?color,?ch_id,?pt_num,?code)"
sqlCommand.Connection = SQLConnection
sqlCommand.CommandText = str_carSql
sqlCommand.Parameters.AddWithValue("?id", TextBox20.Text)
sqlCommand.Parameters.AddWithValue("?m_id", TextBox20.Text)
sqlCommand.Parameters.AddWithValue("?model", TextBox23.Text)
sqlCommand.Parameters.AddWithValue("?color", TextBox24.Text)
sqlCommand.Parameters.AddWithValue("?ch_id", TextBox22.Text)
sqlCommand.Parameters.AddWithValue("?pt_num", TextBox21.Text)
sqlCommand.Parameters.AddWithValue("?code", ComboBox1.SelectedItem)
sqlCommand.ExecuteNonQuery()
Change the catch block to see the actual exception:
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
Because char
is by default signed
declared that means the range of the variable is
-127 to +127>
your value is overflowed. To get the desired value you have to declared the unsigned
modifier. the modifier's (unsigned
) range is:
0 to 255
to get the the range of any data type follow the process 2^bit
example char
is 8 bit length to get its range just 2 ^(power) 8
.
select case
when exists (select 1
from sales
where sales_type = 'Accessories')
then 'Y'
else 'N'
end as rec_exists
from dual;
Here is a method that works for me. NOTE: There is some code within this method that may not apply to you, so try and ignore it. For example "logStandardOut(...), git-bash, etc".
private String exeShellCommand(String doCommand, String inDir, boolean ignoreErrors) {
logStandardOut("> %s", doCommand);
ProcessBuilder builder = new ProcessBuilder();
StringBuilder stdOut = new StringBuilder();
StringBuilder stdErr = new StringBuilder();
boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
if (isWindows) {
String gitBashPathForWindows = "C:\\Program Files\\Git\\bin\\bash";
builder.command(gitBashPathForWindows, "-c", doCommand);
} else {
builder.command("bash", "-c", doCommand);
}
//Do we need to change dirs?
if (inDir != null) {
builder.directory(new File(inDir));
}
//Execute it
Process process = null;
BufferedReader brStdOut;
BufferedReader brStdErr;
try {
//Start the command line process
process = builder.start();
//This hangs on a large file
// https://stackoverflow.com/questions/5483830/process-waitfor-never-returns
//exitCode = process.waitFor();
//This will have both StdIn and StdErr
brStdOut = new BufferedReader(new InputStreamReader(process.getInputStream()));
brStdErr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
//Get the process output
String line = null;
String newLineCharacter = System.getProperty("line.separator");
while (process.isAlive()) {
//Read the stdOut
while ((line = brStdOut.readLine()) != null) {
stdOut.append(line + newLineCharacter);
}
//Read the stdErr
while ((line = brStdErr.readLine()) != null) {
stdErr.append(line + newLineCharacter);
}
//Nothing else to read, lets pause for a bit before trying again
process.waitFor(100, TimeUnit.MILLISECONDS);
}
//Read anything left, after the process exited
while ((line = brStdOut.readLine()) != null) {
stdOut.append(line + newLineCharacter);
}
//Read anything left, after the process exited
while ((line = brStdErr.readLine()) != null) {
stdErr.append(line + newLineCharacter);
}
//cleanup
if (brStdOut != null) {
brStdOut.close();
}
if (brStdErr != null) {
brStdOut.close();
}
//Log non-zero exit values
if (!ignoreErrors && process.exitValue() != 0) {
String exMsg = String.format("%s%nprocess.exitValue=%s", stdErr, process.exitValue());
throw new ExecuteCommandException(exMsg);
}
} catch (ExecuteCommandException e) {
throw e;
} catch (Exception e) {
throw new ExecuteCommandException(stdErr.toString(), e);
} finally {
//Log the results
logStandardOut(stdOut.toString());
logStandardError(stdErr.toString());
}
return stdOut.toString();
}
This should work:
s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)
Here is an easy way.
@Test
void exceptionTest() {
try{
model.someMethod("invalidInput");
fail("Exception Expected!");
}
catch(SpecificException e){
assertTrue(true);
}
catch(Exception e){
fail("wrong exception thrown");
}
}
It only succeeds when the Exception you expect is thrown.
As everyone said above
var str = "foo"
str += " bar"
console.log(str) //will now give you "foo bar"
_x000D_
Check this out as well https://www.sitepoint.com/shorthand-javascript-techniques/
double d = 1.234;
int i = Convert.ToInt32(d);
Handles rounding like so:
rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.
I went to File -> Project Structure -> Modules clicked on + and then import module found my root folder and selected it.
It worked.
For IntelliJ 14
All the answers so far are pretty flawed - they either involve adding class="noprint"
to everything or will mess up display
within #printable
.
I think the best solution would be to create a wrapper around the non-printable stuff:
<head>
<style type="text/css">
#printable { display: none; }
@media print
{
#non-printable { display: none; }
#printable { display: block; }
}
</style>
</head>
<body>
<div id="non-printable">
Your normal page contents
</div>
<div id="printable">
Printer version
</div>
</body>
Of course this is not perfect as it involves moving things around in your HTML a bit...
If you truly wish to use PHP, you could use
include "file.php";
or
require "file.php";
and then in file.php, use a heredoc & echo it in.
file.php contents:
$some_js_code <<<_code
function myFunction()
{
Alert("Some JS code would go here.");
}
_code;
At the top of your PHP file, bring in the file using either include or require then in head (or body section) echo it in
<?php
require "file.php";
?>
<html>
<head>
<?php
echo $some_js_code;
?>
</script>
</head>
<body>
</body>
</html>
Different way but it works. Just my $.02...
On the Eclipse toolbar, select Window ? Preferences, set the font size (General ? Appearance ? Colors and Fonts ? Basic ? Text Font).
Save the preferences.
Possible first line of every Bash script/session:
say() { for line in "${@}" ; do printf "%s\n" "${line}" ; done ; }
Use e.g.:
$ aa=( 7 -4 -e ) ; say "${aa[@]}"
7
-4
-e
May consider: echo
interprets -e
as option here
Please refer the below-detailed explanation.
I have used Built-in data frame in R, called mtcars.
> mtcars
mpg cyl disp hp drat wt ...
Mazda RX4 21.0 6 160 110 3.90 2.62 ...
Mazda RX4 Wag 21.0 6 160 110 3.90 2.88 ...
Datsun 710 22.8 4 108 93 3.85 2.32 ...
............
The top line of the table is called the header which contains the column names. Each horizontal line afterward denotes a data row, which begins with the name of the row, and then followed by the actual data. Each data member of a row is called a cell.
To retrieve data in a cell, we would enter its row and column coordinates in the single square bracket "[]" operator. The two coordinates are separated by a comma. In other words, the coordinates begin with row position, then followed by a comma, and ends with the column position. The order is important.
Eg 1:- Here is the cell value from the first row, second column of mtcars.
> mtcars[1, 2]
[1] 6
Eg 2:- Furthermore, we can use the row and column names instead of the numeric coordinates.
> mtcars["Mazda RX4", "cyl"]
[1] 6
We reference a data frame column with the double square bracket "[[]]" operator.
Eg 1:- To retrieve the ninth column vector of the built-in data set mtcars, we write mtcars[[9]].
mtcars[[9]] [1] 1 1 1 0 0 0 0 0 0 0 0 ...
Eg 2:- We can retrieve the same column vector by its name.
mtcars[["am"]] [1] 1 1 1 0 0 0 0 0 0 0 0 ...
The type comes after the name in TypeScript, partly because types are optional.
So your line:
HTMLElement el = document.getElementById('content');
Needs to change to:
const el: HTMLElement = document.getElementById('content');
Back in 2013, the type HTMLElement
would have been inferred from the return value of getElementById
, this is still the case if you aren't using strict null checks (but you ought to be using the strict modes in TypeScript). If you are enforcing strict null checks you will find the return type of getElementById
has changed from HTMLElement
to HTMLElement | null
. The change makes the type more correct, because you don't always find an element.
So when using type mode, you will be encouraged by the compiler to use a type assertion to ensure you found an element. Like this:
const el: HTMLElement | null = document.getElementById('content');
if (el) {
const definitelyAnElement: HTMLElement = el;
}
I have included the types to demonstrate what happens when you run the code. The interesting bit is that el
has the narrower type HTMLElement
within the if
statement, due to you eliminating the possibility of it being null.
You can do exactly the same thing, with the same resulting types, without any type annotations. They will be inferred by the compiler, thus saving all that extra typing:
const el = document.getElementById('content');
if (el) {
const definitelyAnElement = el;
}
Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.
In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.
Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.
Another way to find out where a class is loaded from (without manipulating the source) is to start the Java VM with the option: -verbose:class
you can do this in different ways:
see here for more details on the second case:
http://msdn.microsoft.com/en-us/library/ff647786.aspx#scalenetchapt10_topic14
and here for details on the last case:
You can specify how to initialize members in the member initializer list:
BigMommaClass {
BigMommaClass(int, int);
private:
ThingOne thingOne;
ThingTwo thingTwo;
};
BigMommaClass::BigMommaClass(int numba1, int numba2)
: thingOne(numba1 + numba2), thingTwo(numba1, numba2) {}
Mikeal's request module can do this easily:
var request = require('request');
var options = {
uri: 'https://www.googleapis.com/urlshortener/v1/url',
method: 'POST',
json: {
"longUrl": "http://www.google.com/"
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body.id) // Print the shortened url.
}
});
Here is a dplyr/tidyverse solution using the na_if() function:
dat %>% mutate_if(is.numeric, list(~na_if(., Inf)))
Note that this only replaces positive infinity with NA. Need to repeat if negative infinity values also need to be replaced.
dat %>% mutate_if(is.numeric, list(~na_if(., Inf))) %>%
mutate_if(is.numeric, list(~na_if(., -Inf)))
In case you want to search for all the issues updated after 9am previous day until today at 9AM, please try: updated >= startOfDay(-15h) and updated <= startOfDay(9h)
. (explanation: 9AM - 24h/day = -15h)
You can also use updated >= startOfDay(-900m)
. where 900m = 15h*60m
Reference: https://confluence.atlassian.com/display/JIRA/Advanced+Searching
os.path.exists
will also return True
if there's a regular file with that name.
os.path.isdir
will only return True
if that path exists and is a directory, or a symbolic link to a directory.
In VSCODE ctrl+z (undo) worked for me
I did git checkout .
instead of git add .
and all my file changes were lost.
But Now using command + z
in my mac , recovered the changes and saved a tone of work for me.
count number of lines and store result in variable use this command:
count=$(wc -l < file.txt)
echo "Number of lines: $count"
The ThreadPoolExecutor
class is the base implementation for the executors that are returned from many of the Executors
factory methods. So let's approach Fixed and Cached thread pools from ThreadPoolExecutor
's perspective.
The main constructor of this class looks like this:
public ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler
)
The corePoolSize
determines the minimum size of the target thread pool. The implementation would maintain a pool of that size even if there are no tasks to execute.
The maximumPoolSize
is the maximum number of threads that can be active at once.
After the thread pool grows and becomes bigger than the corePoolSize
threshold, the executor can terminate idle threads and reach to the corePoolSize
again.
If allowCoreThreadTimeOut
is true, then the executor can even terminate core pool threads if they were idle more than keepAliveTime
threshold.
So the bottom line is if threads remain idle more than keepAliveTime
threshold, they may get terminated since there is no demand for them.
What happens when a new task comes in and all core threads are occupied? The new tasks will be queued inside that BlockingQueue<Runnable>
instance. When a thread becomes free, one of those queued tasks can be processed.
There are different implementations of the BlockingQueue
interface in Java, so we can implement different queuing approaches like:
Bounded Queue: New tasks would be queued inside a bounded task queue.
Unbounded Queue: New tasks would be queued inside an unbounded task queue. So this queue can grow as much as the heap size allows.
Synchronous Handoff: We can also use the SynchronousQueue
to queue the new tasks. In that case, when queuing a new task, another thread must already be waiting for that task.
Here's how the ThreadPoolExecutor
executes a new task:
corePoolSize
threads are running, tries to start a
new thread with the given task as its first job.BlockingQueue#offer
method. The offer
method won't block if the queue is full and immediately returns false
.offer
returns false
), then it tries to add a new thread to the thread pool with this task as its first job.RejectedExecutionHandler
.The main difference between the fixed and cached thread pools boils down to these three factors:
+-----------+-----------+-------------------+---------------------------------+ | Pool Type | Core Size | Maximum Size | Queuing Strategy | +-----------+-----------+-------------------+---------------------------------+ | Fixed | n (fixed) | n (fixed) | Unbounded `LinkedBlockingQueue` | +-----------+-----------+-------------------+---------------------------------+ | Cached | 0 | Integer.MAX_VALUE | `SynchronousQueue` | +-----------+-----------+-------------------+---------------------------------+
Excutors.newFixedThreadPool(n)
works:
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
As you can see:
OutOfMemoryError
.When should I use one or the other? Which strategy is better in terms of resource utilization?
A fixed-size thread pool seems to be a good candidate when we're going to limit the number of concurrent tasks for resource management purposes.
For example, if we're going to use an executor to handle web server requests, a fixed executor can handle the request bursts more reasonably.
For even better resource management, it's highly recommended to create a custom ThreadPoolExecutor
with a bounded BlockingQueue<T>
implementation coupled with reasonable RejectedExecutionHandler
.
Here's how the Executors.newCachedThreadPool()
works:
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
As you can see:
Integer.MAX_VALUE
. Practically, the thread pool is unbounded.SynchronousQueue
always fails when there is no one on the other end to accept it! When should I use one or the other? Which strategy is better in terms of resource utilization?
Use it when you have a lot of predictable short-running tasks.
I think that since return validateView();
will return a value (to the click event?), your second call ShowDiv1();
will not get called.
You can always wrap multiple function calls in another function, i.e.
<asp:LinkButton OnClientClick="return display();"> function display() { if(validateView() && ShowDiv1()) return true; }
You also might try:
<asp:LinkButton OnClientClick="return (validateView() && ShowDiv1());">
Though I have no idea if that would throw an exception.
Use System.Diagnostics.Process.Start()
method.
Check out this article on how to use it.
Process.Start("notepad", "readme.txt");
string winpath = Environment.GetEnvironmentVariable("windir");
string path = System.IO.Path.GetDirectoryName(
System.Windows.Forms.Application.ExecutablePath);
Process.Start(winpath + @"\Microsoft.NET\Framework\v1.0.3705\Installutil.exe",
path + "\\MyService.exe");
If you're an Android developer you can use android.util.Base64
class for this purpose.
My 2 cents:
def token(length=16)
chars = [*('A'..'Z'), *('a'..'z'), *(0..9)]
(0..length).map {chars.sample}.join
end
We simply did:
import io
from pathlib import Path
def test_my_upload(self, accept_json):
"""Test my uploads endpoint for POST."""
data = {
"filePath[]": "/tmp/bin",
"manifest[]": (io.StringIO(str(Path(__file__).parent /
"path_to_file/npmlist.json")).read(),
'npmlist.json'),
}
headers = {
'a': 'A',
'b': 'B'
}
res = self.client.post(api_route_for('/test'),
data=data,
content_type='multipart/form-data',
headers=headers,
)
assert res.status_code == 200
Try this! If you want to find the maximum duplicated element with their how many time is it has duplicated then should try
def get_maximum_duplicated_element_with_count(input_array)
a = input_array
max_duplicated_val = max_duplicated_val_count = 0
a.each do |n|
max_duplicated_val, max_duplicated_val_count = n, a.count(n) if a.count(n) > max_duplicated_val_count
end
puts "Maximun Duplicated element Is => #{max_duplicated_val}"
puts "#{max_duplicated_val} is Duplicated #{max_duplicated_val_count} times"
end
get_maximum_duplicated_element_with_count([1, 4, 4, 5, 6, 6, 2, 6])
Output will be
Maximun Duplicated element Is => 6
6 is Duplicated 3 times
Note: All of the following instructions apply universally (aka to all OSes) unless otherwise specified.
You will need:
Change the file extension of the .apk
file by either adding a .zip
extension to the filename, or to change .apk
to .zip
.
For example, com.example.apk
becomes com.example.zip
, or com.example.apk.zip
. Note that on Windows and macOS, it may prompt you whether you are sure you want to change the file extension. Click OK or Add if you're using macOS:
Extract the renamed APK file in a specific folder. For example, let that folder be demofolder
.
If it didn't work, try opening the file in another application such as WinZip or 7-Zip.
For macOS, you can try running unzip
in Terminal (available at /Applications/Terminal.app
), where it takes one or more arguments: the file to unzip + optional arguments. See man unzip
for documentation and arguments.
Download dex2jar
(see all releases on GitHub) and extract that zip file in the same folder as stated in the previous point.
Open command prompt (or a terminal) and change your current directory to the folder created in the previous point and type the command d2j-dex2jar.bat classes.dex
and press enter. This will generate classes-dex2jar.jar
file in the same folder.
d2j-dex2jar.bat
with d2j-dex2jar.sh
. In other words, run d2j-jar2dex.sh classes.dex
in the terminal and press enter.Download Java Decompiler (see all releases on Github) and extract it and start (aka double click) the executable/application.
From the JD-GUI window, either drag and drop the generated classes-dex2jar.jar
file into it, or go to File > Open File...
and browse for the jar.
Next, in the menu, go to File > Save All Sources
(Windows: Ctrl+Alt+S, macOS: ?+?+S). This should open a dialog asking you where to save a zip file named `classes-dex2jar.jar.src.zip" consisting of all packages and java files. (You can rename the zip file to be saved)
Extract that zip file (classes-dex2jar.jar.src.zip
) and you should get all java files of the application.
xml
files from APKapktool
website for installation instructions and moreWindows:
myxmlfolder
).myxmlfolder
folder and rename the apktool jar file to apktool.jar
..apk
file in the same folder (i.e myxmlfolder
).Open the command prompt (or terminal) and change your current directory to the folder where apktool
is stored (in this case, myxmlfolder
). Next, type the command apktool if framework-res.apk
.
What we're doing here is that we are installing a framework. For more info, see the docs.
In the command prompt, type the command apktool d filename.apk
(where filename
is the name of apk file). This should decode the file. For more info, see the docs.
This should result in a folder filename.out
being outputted, where filename
is the original name of the apk file without the .apk
file extension. In this folder are all the XML files such as layout, drawables etc.
Source: How to get source code from APK file - Comptech Blogspot
This will work for you in Python;
# Call JIRA API with HTTPBasicAuth
import json
import requests
from requests.auth import HTTPBasicAuth
JIRA_EMAIL = "****"
JIRA_TOKEN = "****"
BASE_URL = "https://****.atlassian.net"
API_URL = "/rest/api/3/serverInfo"
API_URL = BASE_URL+API_URL
BASIC_AUTH = HTTPBasicAuth(JIRA_EMAIL, JIRA_TOKEN)
HEADERS = {'Content-Type' : 'application/json;charset=iso-8859-1'}
response = requests.get(
API_URL,
headers=HEADERS,
auth=BASIC_AUTH
)
print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))
This page has overcomplicated solutions to the problem. Most of numpy / scipy users should not need to compile their numpy installations or need to rely on 3rd party "numpy+mkl" wheels.
Downloading a compiler is an anti-pattern, you do not want to build numpy, only use it. [github.com/numpy]
pip uninstall numpy
and install scipy with
pip install scipy --only-binary numpy
The --only-binary
numpy
will force installing binary wheel (.whl
) version of numpy. If it fails, you have too new (not yet supported) version of python.
If you have multiple python versions installed, you can ensure that pip is installing the python version you want by
<path_to_python_executable> -m pip install <X>
instead of pip install <X>
.
numpy 1.19.3
or above, and Python 3.8 for numpy 1.19.2
. (For compatibility of older numpy versions, see numpy release notes)pip
trying to install numpy-<x>.tag.gz
, you know it probably will not work. Try older version of Python, instead. You want to see pip to installing a binary wheel for numpy for Windows (numpy-<x>.whl
). You can check the wheels in pip available for numpy here.Do it in your xml
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButtonSettings"
android:layout_gravity="right|bottom"
android:src="@drawable/tabbar_settings_icon"
android:background="@android:color/transparent"/>
you can use indexOf
method from lodash
var tv = [{id:1},{id:2}]
var voteID = 2;
var data = _.find(tv, function(voteItem){ return voteItem.id == voteID; });
var index=_.indexOf(tv,data);
Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like
INSERT INTO HISTORICAL_CAR_STATS (
HISTORICAL_CAR_STATS_ID,
YEAR,
MONTH,
MAKE,
MODEL,
REGION,
AVG_MSRP,
CNT)
SELECT MY_SEQ.nextval,
year,
month,
make,
model,
region,
avg_msrp,
cnt
FROM (SELECT '2010' year,
'12' month,
'ALL' make,
'ALL' model,
REGION,
sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp,
sum(cnt) cnt
FROM HISTORICAL_CAR_STATS
WHERE YEAR = '2010'
AND MONTH = '12'
AND MAKE != 'ALL'
GROUP BY REGION)
Enabling Java 8 features caused deadly slow build
gradle
jackOptions {
enabled true
}
compileOptions {
targetCompatibility 1.8
sourceCompatibility 1.8
}
After deleting above lines, it builds in seconds.
There is issue Compiling with Jack takes very long time
Project Manager's Answer
We're aware that build times are an issue with Jack right now. We have improvements in the 2.4 Gradle plugin that should be a significant improvement for incremental builds.
As of now, latest Gradle version i can find is 2.3.0-beta4
if you have enum like this
public enum PcapLinkType {
DLT_NULL(0)
DLT_EN10MB(1)
DLT_EN3MB(2),
DLT_AX25(3),
DLT_UNKNOWN(-1);
private final int value;
PcapLinkType(int value) {
this.value= value;
}
}
then you can use it like
PcapLinkType type = PcapLinkType.values()[1]; /*convert val to a PcapLinkType */
SimpleDateFormat
sdf=new SimpleDateFormat("dd/MM/YYYY hh:mm:ss");
String dateString=sdf.format(date);
It will give the output 28/09/2013 09:57:19
as you expected.
In JavaScript
setLocation(base: string) {
window.location.href = base;
}
In HTML
<button onclick="setLocation('/<whatever>')>GO</button>"
In A1 of your new sheet, put this:
=OFFSET(Sheet1!$A$1,(ROW()-1)*7,0)
... and copy down. If you start somewhere other than row 1, change ROW() to ROW(A1) or some other cell on row 1, then copy down again.
If you want to copy the nth line but multiple columns, use the formula:
=OFFSET(Sheet1!A$1,(ROW()-1)*7,0)
This can be copied right too.
this will help you in - convert first letter of each word to uppercase
<script>
/* convert First Letter UpperCase */
$('#txtField').on('keyup', function (e) {
var txt = $(this).val();
$(this).val(txt.replace(/^(.)|\s(.)/g, function ($1) {
return $1.toUpperCase( );
}));
});
</script>
Example : this is a title case sentence -> This Is A Title Case Sentence
this might be helpful:
// Operator overloading in C++
//assignment operator overloading
#include<iostream>
using namespace std;
class Employee
{
private:
int idNum;
double salary;
public:
Employee ( ) {
idNum = 0, salary = 0.0;
}
void setValues (int a, int b);
void operator= (Employee &emp );
};
void Employee::setValues ( int idN , int sal )
{
salary = sal; idNum = idN;
}
void Employee::operator = (Employee &emp) // Assignment operator overloading function
{
salary = emp.salary;
}
int main ( )
{
Employee emp1;
emp1.setValues(10,33);
Employee emp2;
emp2 = emp1; // emp2 is calling object using assignment operator
}
Just extend Julian's table:
Here is my version using the BuildConfig
class:
Intent marketIntent = new Intent(Intent.ACTION_VIEW, uri);
marketIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
marketIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
}
try {
startActivity(marketIntent);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID)));
}
First, check that whatever you are returning via unicode is a String.
If it is not a string you can change it to a string like this (where self.id is an integer)
def __unicode__(self):
return '%s' % self.id
following which, if it still doesn't work, restart your ./manage.py shell for the changes to take effect and try again. It should work.
Best Regards
If you set the border-collapse
style to collapse
on the parent table you should be able to style the tr
:
(styles are inline for demo)
<table style="border-collapse: collapse;">
<tr>
<td>No Border</td>
</tr>
<tr style="border:2px solid #f00;">
<td>Border</td>
</tr>
<tr>
<td>No Border</td>
</tr>
</table>
Output:
If you look at the 'display' property in the CSS spec, you will see that 'list-item' is specifically a display type. When you set an item to "inline", you're replacing the default display type of list-item, and the marker is specifically a part of the list-item type.
The above answer suggests float, but I've tried that and it doesn't work (at least on Chrome). According to the spec, if you set your boxes to float left or right,"The 'display' is ignored, unless it has the value 'none'." I take this to mean that the default display type of 'list-item' is gone (taking the marker with it) as soon as you float the element.
Edit: Yeah, I guess I was wrong. See top entry. :)
Normally, you'd get an RST if you do a close which doesn't linger (i.e. in which data can be discarded by the stack if it hasn't been sent and ACK'd) and a normal FIN if you allow the close to linger (i.e. the close waits for the data in transit to be ACK'd).
Perhaps all you need to do is set your socket to linger so that you remove the race condition between a non lingering close done on the socket and the ACKs arriving?
Use raw:
<%=raw @str >
But as @jmort253 correctly says, consider where the HTML really belongs.
It seems your curl points to a non-existing file with CA certs or similar.
For the primary reference on CA certs with curl, see: https://curl.haxx.se/docs/sslcerts.html
If you own the server you should use the windows task scheduler. Use AT /? from the command line to see the options.
Otherwise, from a web based environment, you might have to do something nasty like set up a different machine to make requests to a certain page on a timed interval.
For completeness, using the Guava library, you'd do: Splitter.on(",").split(“dog,cat,fox”)
Another example:
String animals = "dog,cat, bear,elephant , giraffe , zebra ,walrus";
List<String> l = Lists.newArrayList(Splitter.on(",").trimResults().split(animals));
// -> [dog, cat, bear, elephant, giraffe, zebra, walrus]
Splitter.split()
returns an Iterable, so if you need a List, wrap it in Lists.newArrayList()
as above. Otherwise just go with the Iterable, for example:
for (String animal : Splitter.on(",").trimResults().split(animals)) {
// ...
}
Note how trimResults()
handles all your trimming needs without having to tweak regexes for corner cases, as with String.split()
.
If your project uses Guava already, this should be your preferred solution. See Splitter documentation in Guava User Guide or the javadocs for more configuration options.
I will reuse the data example from @PaulRougieux
x <- data_frame(i = c("a","b","c"), j = 1:3)
y <- data_frame(i = c("b","c","d"), k = 4:6)
z <- data_frame(i = c("c","d","a"), l = 7:9)
Here's a short and sweet solution using purrr
and tidyr
library(tidyverse)
list(x, y, z) %>%
map_df(gather, key=key, value=value, -i) %>%
spread(key, value)
All the answers worked. However, I had to add the variables that I needed to get to the sudoers files as follows:
sudo visudo
Defaults env_keep += "<var1>, <var2>, ..., <varn>"
Use this css, as you already have the markup for it:
.img-container {
position: absolute;
top: 50%;
left: 50%;
}
.img-container > img {
margin-top:-50%;
margin-left:-50%;
}
Here is a working JsBin: http://jsbin.com/ihilUnI/1/edit
This solution only works for square images (because a percentage margin-top value depends on the width of the container, not the height). For random-size images, you can do the following:
.img-container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* add browser-prefixes */
}
Working JsBin solution: http://jsbin.com/ihilUnI/2/edit
For newer versions of Windows (including but not limited to both Windows 10 and Windows Server 2016), the event IDs are:
Locking and unlocking a workstation also involve the following logon and logoff events:
When using a Terminal Services session, locking and unlocking may also involve the following events if the session is disconnected, and event 4778 may replace event 4801:
Events 4800 and 4801 are not audited by default, and must be enabled using either Local Group Policy Editor (gpedit.msc
) or Local Security Policy (secpol.msc
).
The path for the policy using Local Group Policy Editor is:
The path for the policy using Local Security Policy is the following subset of the path for Local Group Policy Editor:
I had the same issue using Eclipse CDT (Kepler)
on Windows
with Cygwin
installed. After pointing the project properties at every Cygwin include I could think of, it still couldn't find cout
.
The final missing piece turned out to be C:cygwin64\lib\gcc\x86_64-pc-cygwin\4.8.2\install-tool\include
.
To sum up:
Properties
C/C++ General
> Paths and Symbols
> Includes
tabAdd...
File system...
lib\gcc\x86_64-pc-cygwin\4.8.2\install-tool\include
OK
Here is what my project includes ended up looking like when it was all said and done:
In general, the key to avoiding an explicit loop would be to join (merge) 2 instances of the dataframe on rowindex-1==rowindex.
Then you would have a big dataframe containing rows of r and r-1, from where you could do a df.apply() function.
However the overhead of creating the large dataset may offset the benefits of parallel processing...
C# does have a preprocessor. It works just slightly differently than that of C++ and C.
Here is a MSDN links - the section on all preprocessor directives.
I know this is quite out of date, but this might still be useful for those coming late to the party. (EDIT: updated since this still gets traffic and @Goozak has pointed out in the comments that my original analysis of the sample was incorrect as well.)
I pulled this from the example code in your link:
IF !%1==! GOTO VIEWDATA
REM IF NO COMMAND-LINE ARG...
FIND "%1" C:\BOZO\BOOKLIST.TXT
GOTO EXIT0
REM PRINT LINE WITH STRING MATCH, THEN EXIT.
:VIEWDATA
TYPE C:\BOZO\BOOKLIST.TXT | MORE
REM SHOW ENTIRE FILE, 1 PAGE AT A TIME.
:EXIT0
!%1==!
is simply an idiomatic use of ==
intended to verify that the thing on the left, that contains your variable, is different from the thing on the right, that does not. The !
in this case is just a character placeholder. It could be anything. If %1
has content, then the equality will be false, if it does not you'll just be comparing !
to !
and it will be true.
!==!
is not an operator, so writing "asdf" !==! "fdas"
is pretty nonsensical.
The suggestion to use if not "asdf" == "fdas"
is definitely the way to go.
The onclick
attribute of a button takes a string of JavaScript, not an href like you provided. Just remove the "javascript:" part.
The third argument is the XMLHttpRequest object, so you can do whatever you want.
$.ajax({
url : 'http://example.com',
type : 'post',
data : 'a=b'
}).done(function(data, statusText, xhr){
var status = xhr.status; //200
var head = xhr.getAllResponseHeaders(); //Detail header info
});
You're instantiating the Random
object inside your method.
The Random
object is seeded from the system clock, which means that if you call your method several times in quick succession it'll use the same seed each time, which means that it'll generate the same sequence of random numbers, which means that you'll get the same string.
To solve the problem, move your Random
instance outside of the method itself (and while you're at it you could get rid of that crazy sequence of calls to Convert
and Floor
and NextDouble
):
private readonly Random _rng = new Random();
private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private string RandomString(int size)
{
char[] buffer = new char[size];
for (int i = 0; i < size; i++)
{
buffer[i] = _chars[_rng.Next(_chars.Length)];
}
return new string(buffer);
}
To do links, you can do
.social h2 a:link {
color: pink;
font-size: 14px;
}
You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.
First thing's first, if your dates are in varchar format change that, store dates as dates it will save you a lot of headaches and it is something that is best done sooner rather than later. The problem will only get worse.
Secondly, once you have a date DO NOT convert the date to a varchar! Keep it in date format and use formatting on the application side to get the required date format.
There are various methods to do this depending on your DBMS:
SQL-Server 2008 and later:
SELECT CAST(CURRENT_TIMESTAMP AS DATE)
SQL-Server 2005 and Earlier
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0)
SQLite
SELECT DATE(NOW())
Oracle
SELECT TRUNC(CURRENT_TIMESTAMP)
Postgresql
SELECT CURRENT_TIMESTAMP::DATE
If you need to use culture specific formatting in your report you can either explicitly state the format of the receiving text box (e.g. dd/MM/yyyy), or you can set the language so that it shows the relevant date format for that language.
Either way this is much better handled outside of SQL as converting to varchar within SQL will impact any sorting you may do in your report.
If you cannot/will not change the datatype to DATETIME, then still convert it to a date within SQL (e.g. CONVERT(DATETIME, yourField)
) before sending to report services and handle it as described above.
The best way to deal with angle computation is to use atan2(y, x)
that given a point x, y
returns the angle from that point and the X+
axis in respect to the origin.
Given that the computation is
double result = atan2(P3.y - P1.y, P3.x - P1.x) -
atan2(P2.y - P1.y, P2.x - P1.x);
i.e. you basically translate the two points by -P1
(in other words you translate everything so that P1
ends up in the origin) and then you consider the difference of the absolute angles of P3
and of P2
.
The advantages of atan2
is that the full circle is represented (you can get any number between -p and p) where instead with acos
you need to handle several cases depending on the signs to compute the correct result.
The only singular point for atan2
is (0, 0)
... meaning that both P2
and P3
must be different from P1
as in that case doesn't make sense to talk about an angle.
(I know the question is old, but I think this might be good as a reference for people with similar questions)
If you want to load data from an ASCII/text file (which has the benefit or being more or less human-readable and easy to parse in other software), numpy.loadtxt is probably what you want:
If you just want to quickly save and load numpy arrays/matrices to and from a file, take a look at numpy.save and numpy.load:
class KeyStatisticCollection(DataDownloadUtilities.DataDownloadCollection):
def GenerateAddressStrings(self):
pass
def worker(self):
pass
def DownloadProc(self):
pass
I think you can use the following command: git reset --hard
Please change only the name of the function; no other change is required
<script>
function totalbandwidthresult() {
alert("fdf");
var fps = Number(document.calculator.fps.value);
var bitrate = Number(document.calculator.bitrate.value);
var numberofcameras = Number(document.calculator.numberofcameras.value);
var encoding = document.calculator.encoding.value;
if (encoding = "mjpeg") {
storage = bitrate * fps;
} else {
storage = bitrate;
}
totalbandwidth = (numberofcameras * storage) / 1000;
alert(totalbandwidth);
document.calculator.totalbandwidthresult.value = totalbandwidth;
}
</script>
<form name="calculator" class="formtable">
<div class="formrow">
<label for="rcname">RC Name</label>
<input type="text" name="rcname">
</div>
<div class="formrow">
<label for="fps">FPS</label>
<input type="text" name="fps">
</div>
<div class="formrow">
<label for="bitrate">Bitrate</label>
<input type="text" name="bitrate">
</div>
<div class="formrow">
<label for="numberofcameras">Number of Cameras</label>
<input type="text" name="numberofcameras">
</div>
<div class="formrow">
<label for="encoding">Encoding</label>
<select name="encoding" id="encodingoptions">
<option value="h264">H.264</option>
<option value="mjpeg">MJPEG</option>
<option value="mpeg4">MPEG4</option>
</select>
</div>Total Storage:
<input type="text" name="totalstorage">Total Bandwidth:
<input type="text" name="totalbandwidth">
<input type="button" value="totalbandwidthresult" onclick="totalbandwidthresult();">
</form>
Dictionary<,> is the equivalent. While it doesn't have a Get(...) method, it does have an indexed property called Item which you can access in C# directly using index notation:
class Test {
Dictionary<int,String> entities;
public String getEntity(int code) {
return this.entities[code];
}
}
If you want to use a custom key type then you should consider implementing IEquatable<> and overriding Equals(object) and GetHashCode() unless the default (reference or struct) equality is sufficient for determining equality of keys. You should also make your key type immutable to prevent weird things happening if a key is mutated after it has been inserted into a dictionary (e.g. because the mutation caused its hash code to change).
I was having a lot of problems to get this working, every single solution I found didn't seem to work.
I realized that I had to set the div display to flex, so basically this is my CSS:
div{
display: flex;
}
div img{
max-height: 100%;
max-width: 100%;
}
This can happen due to a different language in the phone for which your code doesn't have the asset for. For example your preference.xml is placed in xml-en and you are trying to run your app in a phone which has French selected, the app will crash.
Docker with BRIDGE network. for Ubuntu 16.04 with display manager lightdm:
cd /etc/lightdm/lightdm.conf.d
sudo nano user.conf
[Seat:*]
xserver-allow-tcp=true
xserver-command=X -listen tcp
you can use more private permissions
xhost +
docker run --volume="$HOME/.Xauthority:/root/.Xauthority:rw" --env="DISPLAY=$HOST_IP_IN_BRIDGE_NETWORK:0" --net=bridge $container_name
Better change the class of the element (.regular is black, .alert is red):
function abc(){
var myDiv = document.getElementById("test");
if (myDiv.className == 'alert') {
myDiv.className = 'regular';
} else {
myDiv.className = 'alert';
}
}
In ES5 there is no efficient way to iterate over a sparse array without using the length property. In ES6 you can use for...of
. Take this examples:
'use strict';_x000D_
_x000D_
var arr = ['one', 'two', undefined, 3, 4],_x000D_
output;_x000D_
_x000D_
arr[6] = 'five';_x000D_
_x000D_
output = '';_x000D_
arr.forEach(function (val) {_x000D_
output += val + ' ';_x000D_
});_x000D_
console.log(output);_x000D_
_x000D_
output = '';_x000D_
for (var i = 0; i < arr.length; i++) {_x000D_
output += arr[i] + ' ';_x000D_
}_x000D_
console.log(output);_x000D_
_x000D_
output = '';_x000D_
for (var val of arr) {_x000D_
output += val + ' ';_x000D_
};_x000D_
console.log(output);
_x000D_
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->_x000D_
<script src="//gh-canon.github.io/stack-snippet-console/console.min.js"></script>
_x000D_
All array methods which you can use to iterate safely over dense arrays use the length
property of an object created by calling ToObject
internaly. See for instance the algorithm used in the forEach
method: http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18
However in es6, you can use for...of
safely for iterating over sparse arrays.
See also Are Javascript arrays sparse?.
<table style="width: auto;" ...
works fine. Tested in Chrome 38 , IE 11 and Firefox 34.
jsfiddle : http://jsfiddle.net/rpaul/taqodr8o/
You can do this:
gdb --args path/to/executable -every -arg you can=think < of
The magic bit being --args
.
Just type run
in the gdb command console to start debugging.
Regarding your queries:
Is Facade a class which contains a lot of other classes?
Yes. It is a wrapper for many sub-systems in application.
What makes it a design pattern? For me, it is like a normal class
All design patterns too are normal classes. @Unmesh Kondolikar rightly answered this query.
Can you explain me about this Facade, I am new to design patterns.
According to GoF, Facade design pattern is defind as :
Provide a unified interface to a set of interfaces in a subsystem. Facade Pattern defines a higher-level interface that makes the subsystem easier to use
The Facade pattern is typically used when:
Let's take a real word example of cleartrip website.
This website provides options to book
Code snippet:
import java.util.*;
public class TravelFacade{
FlightBooking flightBooking;
TrainBooking trainBooking;
HotelBooking hotelBooking;
enum BookingType {
Flight,Train,Hotel,Flight_And_Hotel,Train_And_Hotel;
};
public TravelFacade(){
flightBooking = new FlightBooking();
trainBooking = new TrainBooking();
hotelBooking = new HotelBooking();
}
public void book(BookingType type, BookingInfo info){
switch(type){
case Flight:
// book flight;
flightBooking.bookFlight(info);
return;
case Hotel:
// book hotel;
hotelBooking.bookHotel(info);
return;
case Train:
// book Train;
trainBooking.bookTrain(info);
return;
case Flight_And_Hotel:
// book Flight and Hotel
flightBooking.bookFlight(info);
hotelBooking.bookHotel(info);
return;
case Train_And_Hotel:
// book Train and Hotel
trainBooking.bookTrain(info);
hotelBooking.bookHotel(info);
return;
}
}
}
class BookingInfo{
String source;
String destination;
Date fromDate;
Date toDate;
List<PersonInfo> list;
}
class PersonInfo{
String name;
int age;
Address address;
}
class Address{
}
class FlightBooking{
public FlightBooking(){
}
public void bookFlight(BookingInfo info){
}
}
class HotelBooking{
public HotelBooking(){
}
public void bookHotel(BookingInfo info){
}
}
class TrainBooking{
public TrainBooking(){
}
public void bookTrain(BookingInfo info){
}
}
Explanation:
FlightBooking, TrainBooking and HotelBooking
are different sub-systems of large system : TravelFacade
TravelFacade
offers a simple interface to book one of below options
Flight Booking
Train Booking
Hotel Booking
Flight + Hotel booking
Train + Hotel booking
book API from TravelFacade internally calls below APIs of sub-systems
flightBooking.bookFlight
trainBooking.bookTrain(info);
hotelBooking.bookHotel(info);
In this way, TravelFacade
provides simpler and easier API with-out exposing sub-system APIs.
Key takeaways : ( from journaldev article by Pankaj Kumar)
Have a look at sourcemaking article too for better understanding.
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
So you can use:
myvar = getURLParameter('myvar');
you can try http://datatables.net/
DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table. Key features:
change
<input type="submit" value="Submit" />
to
<input type="submit" value="Submit" name='submit'/>
change
<form method="post" action="<?php echo $PHP_SELF;?>">
to
<form method="post" action="">
if
only when it is submitted.Using the indexOf function was not cutting it on my collection of REST resources.
I had to create a function that retrieves the array index of a resource sitting in a collection of resources:
factory.getResourceIndex = function(resources, resource) {
var index = -1;
for (var i = 0; i < resources.length; i++) {
if (resources[i].id == resource.id) {
index = i;
}
}
return index;
}
$scope.unassignedTeams.splice(CommonService.getResourceIndex($scope.unassignedTeams, data), 1);
You can use:
UPDATE Station AS st1, StationOld AS st2
SET st1.already_used = 1
WHERE st1.code = st2.code
1) Open the project folder in Android Studio.
2) Select app folder -> Right click, and select refactor.
3) Click on move. It will ask to which package name type you own full package name and it will ask to create a new package yes create new automatically it ask for gradle
to sync
.
val newDf =
df.withColumn(
"NEW_COLUMN",
concat(
when(col("COL1").isNotNull, col("COL1")).otherwise(lit("null")),
when(col("COL2").isNotNull, col("COL2")).otherwise(lit("null"))))
Note: For this code to work you need to put the parentheses "()" in the "isNotNull" function. -> The correct one is "isNotNull()".
val newDf =
df.withColumn(
"NEW_COLUMN",
concat(
when(col("COL1").isNotNull(), col("COL1")).otherwise(lit("null")),
when(col("COL2").isNotNull(), col("COL2")).otherwise(lit("null"))))
This worked for me to get domain in intranet
https://gist.github.com/jrothmanshore/2656003
It's a powershell script. Run it in PowerShell
.\ip_lookup.ps1 <ip>
&&
and ||
are what is called "short circuiting". That means that they will not evaluate the second operand if the first operand is enough to determine the value of the expression.
For example if the first operand to &&
is false then there is no point in evaluating the second operand, since it can't change the value of the expression (false && true
and false && false
are both false). The same goes for ||
when the first operand is true.
You can read more about this here: http://en.wikipedia.org/wiki/Short-circuit_evaluation From the table on that page you can see that &&
is equivalent to AndAlso
in VB.NET, which I assume you are referring to.
SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.
Let's suppose you have two databases on the same server - Db1
and Db2
. Db1
has a table called Clients
with a column ClientId
and Db2
has a table called Messages
with a column ClientId
(let's leave asside why those tables are in different databases).
Now, to perform a join on the above-mentioned tables you will be using this query:
select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId
Put
finish();
immediately after ActivityStart to stop the activity preventing any way of going back to it. Then add
onCreate(){
getActionBar().setDisplayHomeAsUpEnabled(false);
...
}
to the activity you are starting.
I was trying to do the same, but without keeping a variable of autocomplete. I walk throught this calling change handler programatically on the select event, you only need to worry about the actual value of input.
$("#CompanyList").autocomplete({
source: context.companies,
change: handleCompanyChanged,
select: function(event,ui){
$("#CompanyList").trigger('blur');
$("#CompanyList").val(ui.item.value);
handleCompanyChanged();
}
});
int rgb = ((r&0x0ff)<<16)|((g&0x0ff)<<8)|(b&0x0ff);
If you know that your r, g, and b values are never > 255 or < 0 you don't need the &0x0ff
Additionaly
int red = (rgb>>16)&0x0ff;
int green=(rgb>>8) &0x0ff;
int blue= (rgb) &0x0ff;
No need for multipling.
Better way till now:
If you give display:inline-block; to inner divs then child elements of inner divs will also get this property and disturb alignment of inner divs.
Better way is to use two different classes for inner divs with width, margin and float.
Best way till now:
Use flexbox.
A WC product may belong to none, one or more WC categories. Supposing you just want to get one WC category id.
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat_id = $term->term_id;
break;
}
Please look into the meta.php file in the "templates/single-product/" folder of the WooCommerce plugin.
<?php echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' ); ?>
Dim o
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET", "http://www.example.com", False
o.send
' o.responseText now holds the response as a string.
The problem is frequently with 'secure' setup of mountpoints, such as /tmp
If they are mounted noexec
(check with cat /etc/mtab
and or sudo mount
) then there is no permission to execute any binaries or build scripts from within the (temporary) folder.
E.g. to remount temporarily:
sudo mount -o remount,exec /tmp
Or to change permanently, remove noexec
in /etc/fstab
This is how you do it column-wise:
[df[col].update((df[col] - df[col].min()) / (df[col].max() - df[col].min())) for col in df.columns]
CTRL+R, CTRL+W : Toggle showing whitespace
or under the Edit Menu:
[BTW, it also appears you are using Tabs. It's common practice to have the IDE turn Tabs into spaces (often 4), via Options.]
/**
* Remove an onclick listener
*
* @param view
* @author [email protected]
* @website https://github.com/androidmalin
* @data 2016-05-16
*/
public static void unBingListener(View view) {
if (view != null) {
try {
if (view.hasOnClickListeners()) {
view.setOnClickListener(null);
}
if (view.getOnFocusChangeListener() != null) {
view.setOnFocusChangeListener(null);
}
if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
ViewGroup viewGroup = (ViewGroup) view;
int viewGroupChildCount = viewGroup.getChildCount();
for (int i = 0; i < viewGroupChildCount; i++) {
unBingListener(viewGroup.getChildAt(i));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
var x= {}
var y= {x:'hi'}
console.log(Object.keys(x).length===0)
console.log(Object.keys(y).length===0)
true
false
An optional in Swift is a type that can hold either a value or no value. Optionals are written by appending a ? to any type:
var name: String?
You can refer to this link to get knowledge in deep: https://medium.com/@agoiabeladeyemi/optionals-in-swift-2b141f12f870
You can use this script to export or import any database from terminal given at this link: https://github.com/Ridhwanluthra/mysql_import_export_script/blob/master/mysql_import_export_script.sh
echo -e "Welcome to the import/export database utility\n"
echo -e "the default location of mysqldump file is: /opt/lampp/bin/mysqldump\n"
echo -e "the default location of mysql file is: /opt/lampp/bin/mysql\n"
read -p 'Would like you like to change the default location [y/n]: ' location_change
read -p "Please enter your username: " u_name
read -p 'Would you like to import or export a database: [import/export]: ' action
echo
mysqldump_location=/opt/lampp/bin/mysqldump
mysql_location=/opt/lampp/bin/mysql
if [ "$action" == "export" ]; then
if [ "$location_change" == "y" ]; then
read -p 'Give the location of mysqldump that you want to use: ' mysqldump_location
echo
else
echo -e "Using default location of mysqldump\n"
fi
read -p 'Give the name of database in which you would like to export: ' db_name
read -p 'Give the complete path of the .sql file in which you would like to export the database: ' sql_file
$mysqldump_location -u $u_name -p $db_name > $sql_file
elif [ "$action" == "import" ]; then
if [ "$location_change" == "y" ]; then
read -p 'Give the location of mysql that you want to use: ' mysql_location
echo
else
echo -e "Using default location of mysql\n"
fi
read -p 'Give the complete path of the .sql file you would like to import: ' sql_file
read -p 'Give the name of database in which to import this file: ' db_name
$mysql_location -u $u_name -p $db_name < $sql_file
else
echo "please select a valid command"
fi
Try this:
SELECT CUSTOMER_ID, MAX(FIRSTNAME) AS FIRSTNAME, MAX(LASTNAME) AS LASTNAME ...
FROM
(
SELECT CUSTOMER_ID,
CASE WHEN DBCOLUMNNAME='FirstName' then DATA ELSE NULL END AS FIRSTNAME,
CASE WHEN DBCOLUMNNAME='LastName' then DATA ELSE NULL END AS LASTNAME,
... and so on ...
GROUP BY CUSTOMER_ID
) TEMP
GROUP BY CUSTOMER_ID
I'm using the following sql to find entries in all_synonyms where there is no corresponding object for the object_name (in user_objects):
select *
from all_synonyms
where table_owner = 'SCOTT'
and synonym_name not like '%/%'
and table_name not in (
select object_name from user_objects
where object_type in (
'TABLE', 'VIEW', 'PACKAGE', 'SEQUENCE',
'PROCEDURE', 'FUNCTION', 'TYPE'
)
);
Both examples work like a charm :)
JAVASCRIPT:
function CopyToClipboard(containerid) {_x000D_
if (document.selection) {_x000D_
var range = document.body.createTextRange();_x000D_
range.moveToElementText(document.getElementById(containerid));_x000D_
range.select().createTextRange();_x000D_
document.execCommand("copy");_x000D_
} else if (window.getSelection) {_x000D_
var range = document.createRange();_x000D_
range.selectNode(document.getElementById(containerid));_x000D_
window.getSelection().addRange(range);_x000D_
document.execCommand("copy");_x000D_
alert("Text has been copied, now paste in the text-area")_x000D_
}_x000D_
}
_x000D_
<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>_x000D_
<br /><br />_x000D_
<div id="div1">Text To Copy </div>_x000D_
<br />_x000D_
<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
_x000D_
JQUERY (relies on Adobe Flash): https://paulund.co.uk/jquery-copy-to-clipboard
You can install your GCC manually
either through
sudo port install gcc46
or your download the source code from one of the mirrors from here for example here
tar xzvf gcc-4.6.0.tar.gz cd gcc-4.6.0 ./configure make
well if you have multiple version, then through you can choose one
port select --list gcc
remember port
on mac is called macport https://www.macports.org/install.php
and add add the bin into your path export PATH=$PATH:/opt/local/bin
You may want to try running eclipse with the -clean startup option - it tries re-building eclipse's metadata of the workspace.
Just an addition to the answers above.
If you want to execute a SQL with an "IN" statement you could do this:
ids_list = [1,2,3]
query = "SELECT id, name FROM user WHERE id IN %s"
args = [(ids_list,)] # Don't forget the "comma", to force the tuple
conn.execute(query, args)
Two points:
EDIT Watch out that if the length of list is one or zero this will raise an error!
Use htmlspecialchars()
:
echo htmlspecialchars($_POST['contact_list']);
You can even improve your form processing by stripping all tags with strip_tags()
and remove all white spaces with trim()
:
function processText($text) {
$text = strip_tags($text);
$text = trim($text);
$text = htmlspecialchars($text);
return $text;
}
echo processText($_POST['contact_list']);
If anyone is trying to solve this on a 64-bit version of Windows, you might need to create the following key:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Prefs
Preferences -> Advanced -> Network -> Connection (Configure how Firefox connects to the Internet)
Regarding the “summary” line (the 50 in your formula), the Linux kernel documentation has this to say:
For these reasons, the "summary" must be no more than 70-75
characters, and it must describe both what the patch changes, as well
as why the patch might be necessary. It is challenging to be both
succinct and descriptive, but that is what a well-written summary
should do.
That said, it seems like kernel maintainers do indeed try to keep things around 50. Here’s a histogram of the lengths of the summary lines in the git log for the kernel:
There is a smattering of commits that have summary lines that are longer (some much longer) than this plot can hold without making the interesting part look like one single line. (There’s probably some fancy statistical technique for incorporating that data here but oh well… :-)
If you want to see the raw lengths:
cd /path/to/repo
git shortlog | grep -e '^ ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{print length($0)}'
or a text-based histogram:
cd /path/to/repo
git shortlog | grep -e '^ ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{lens[length($0)]++;} END {for (len in lens) print len, lens[len] }' | sort -n
Ok, so you've found a solution already. Just wanted to share what has been useful to me so many times;
I have created setpy2
alias which helps me switch python.
alias setpy2="mkdir -p /tmp/bin; ln -s `which python2.7` /tmp/bin/python; export PATH=/tmp/bin:$PATH"
Execute setpy2
before you run npm install
. The switch stays in effect until you quit the terminal, afterwards python
is set back to system default.
You can make use of this technique for any other command/tool as well.
IMHO the best option is to use YAML's native block scalars. Specifically in this case, the folded style block.
By invoking sh -c
you can pass arguments to your container as commands, but if you want to elegantly separate them with newlines, you'd want to use the folded style block, so that YAML will know to convert newlines to whitespaces, effectively concatenating the commands.
A full working example:
apiVersion: v1
kind: Pod
metadata:
name: myapp
labels:
app: myapp
spec:
containers:
- name: busy
image: busybox:1.28
command: ["/bin/sh", "-c"]
args:
- >
command_1 &&
command_2 &&
...
command_n
It seems your makefile's name is not 'Makefile' or 'makefile'. In case it is different say 'abc' try running 'make -f abc clean'
For Angular 9/8
Source Link with Examples
export class AppComponent {
isDone = true;
}
1) *ngIf
<div *ngIf="isDone">
It's Done!
</div>
<!-- Negation operator-->
<div *ngIf="!isDone">
It's Not Done!
</div>
2) *ngIf and Else
<ng-container *ngIf="isDone; else elseNotDone">
It's Done!
</ng-container>
<ng-template #elseNotDone>
It's Not Done!
</ng-template>
3) *ngIf, Then and Else
<ng-container *ngIf="isDone; then iAmDone; else iAmNotDone">
</ng-container>
<ng-template #iAmDone>
It's Done!
</ng-template>
<ng-template #iAmNotDone>
It's Not Done!
</ng-template>
You have to bind your event handlers to correct context (this
):
onChange={this.setAuthorState.bind(this)}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_margin="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<SeekBar
android:id="@+id/seekBar"
android:max="100"
android:progress="50"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Notes
max
is the highest value that the seek bar can go to. The default is 100
. The minimum is 0
. The xml min
value is only available from API 26, but you can just programmatically convert the 0-100
range to whatever you need for earlier versions.progress
is the initial position of the slider dot (called a "thumb").android:rotation="270"
.public class MainActivity extends AppCompatActivity {
TextView tvProgressLabel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// set a change listener on the SeekBar
SeekBar seekBar = findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(seekBarChangeListener);
int progress = seekBar.getProgress();
tvProgressLabel = findViewById(R.id.textView);
tvProgressLabel.setText("Progress: " + progress);
}
SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// updated continuously as the user slides the thumb
tvProgressLabel.setText("Progress: " + progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// called when the user first touches the SeekBar
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// called after the user finishes moving the SeekBar
}
};
}
Notes
onStopTrackingTouch
.yes, you can have associative arrays also in javascript:
var obj =
{
name:'some name',
otherProperty:'prop value',
date: new Date()
};
for(i in obj)
{
var propVal = obj[i]; // i is the key, and obj[i] is the value ...
}
you can use TextBlock control and assign the text property.
If you only want find missing values in b, you can do:
List toReturn = new ArrayList(a);
toReturn.removeAll(b);
return toReturn;
If you want to find out values which are present in either list you can execute upper code twice. With changed lists.
It depends on what you do: Web developement, business software, etc. I think for this kind of stuff, you don't need math.
If you want to do computer graphics, audio/video processing, AI, cryptography, etc. then you need a math background, otherwise you can simply not do it.
If you’re not opposed to jquery, this can be done in one line:
jQuery 1.7+
$("#myEl").off()
jQuery < 1.7
$('#myEl').replaceWith($('#myEl').clone());
Here’s an example:
I'm a big fan of Business Rules Engines, since it can help you make your life much easier as a programmer. One of the first experiences I've had while working on a Data Warehouse project was to find Stored Procedures containing complicated CASE structures stretching over entire pages. It was a nightmare to debug, since it was very difficult to understand the logic applied in such long CASE structures, and to determine if you have an overlapping between a rule at page 1 of the code and another from page 5. Overall, we had more than 300 such rules embedded in the code.
When we've received a new development requirement, for something called Accounting Destination, which was involving treating more than 3000 rules, i knew something had to change. Back then I've been working on a prototype which later on become the parent of what now is a Custom Business Rule engine, capable of handling all SQL standard operators. Initially we've been using Excel as an authoring tool and , later on, we've created an ASP.net application which will allow the Business Users to define their own business rules, without the need of writing code. Now the system works fine, with very few bugs, and contains over 7000 rules for calculating this Accounting Destination. I don't think such scenario would have been possible by just hard-coding. And the users are pretty happy that they can define their own rules without IT becoming their bottleneck.
Still, there are limits to such approach:
More details on this topic can be found on a post I've written: http://dwhbp.com/post/2011/10/30/Implementing-a-Business-Rule-Engine.aspx
Overall, the biggest advantage of using a Business Rule Engines is that it allows the users to take back control over the Business Rule definitions and authoring, without the need of going to the IT department each time they need to modify something. It also the reduces the workload over IT development teams, which can now focus on building stuff with more added value.
Cheers,
Nicolae
As already mentioned you can use Fine Code Coverage that visualize coverlet output. If you create a xunit test project
(dotnet new xunit
) you'll find coverlet reference already present in csproj
file because Coverlet
is the default coverage tool for every .NET Core and >= .NET 5 applications.
Microsoft has an example using ReportGenerator that converts coverage reports generated by coverlet, OpenCover, dotCover, Visual Studio, NCover, Cobertura, JaCoCo, Clover, gcov or lcov into human readable reports in various formats.
Example report:
While the article focuses on C# and xUnit as the test framework, both MSTest and NUnit would also work.
Guide:
If you want code coverage in .xml files you can run any of these commands:
dotnet test --collect:"XPlat Code Coverage"
dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura
You have a lot of variants for using @RequestParam
with additional optional elements, e.g.
@RequestParam(required = false, defaultValue = "someValue", value="someAttr") String someAttr
If you don't put required = false
- param will be required by default.
defaultValue = "someValue"
- the default value to use as a fallback when the request parameter is not provided or has an empty value.
If request and method param are the same - you don't need value = "someAttr"
You could simply print the difference:
print tend - tstart
This question inspired me to write a blog post: http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/
I think that, ideally, the .NET Framework would include a static sorting method that accepts an IList<T>, but the next best thing is to create your own extension method. It's not too hard to create a couple of methods that will allow you to sort an IList<T> as you would a List<T>. As a bonus you can overload the LINQ OrderBy extension method using the same technique, so that whether you're using List.Sort, IList.Sort, or IEnumerable.OrderBy, you can use the exact same syntax.
public static class SortExtensions
{
// Sorts an IList<T> in place.
public static void Sort<T>(this IList<T> list, Comparison<T> comparison)
{
ArrayList.Adapter((IList)list).Sort(new ComparisonComparer<T>(comparison));
}
// Sorts in IList<T> in place, when T is IComparable<T>
public static void Sort<T>(this IList<T> list) where T: IComparable<T>
{
Comparison<T> comparison = (l, r) => l.CompareTo(r);
Sort(list, comparison);
}
// Convenience method on IEnumerable<T> to allow passing of a
// Comparison<T> delegate to the OrderBy method.
public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> list, Comparison<T> comparison)
{
return list.OrderBy(t => t, new ComparisonComparer<T>(comparison));
}
}
// Wraps a generic Comparison<T> delegate in an IComparer to make it easy
// to use a lambda expression for methods that take an IComparer or IComparer<T>
public class ComparisonComparer<T> : IComparer<T>, IComparer
{
private readonly Comparison<T> _comparison;
public ComparisonComparer(Comparison<T> comparison)
{
_comparison = comparison;
}
public int Compare(T x, T y)
{
return _comparison(x, y);
}
public int Compare(object o1, object o2)
{
return _comparison((T)o1, (T)o2);
}
}
With these extensions, sort your IList just like you would a List:
IList<string> iList = new []
{
"Carlton", "Alison", "Bob", "Eric", "David"
};
// Use the custom extensions:
// Sort in-place, by string length
iList.Sort((s1, s2) => s1.Length.CompareTo(s2.Length));
// Or use OrderBy()
IEnumerable<string> ordered = iList.OrderBy((s1, s2) => s1.Length.CompareTo(s2.Length));
There's more info in the post: http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/
That is the backbone of CSS, the "cascade" in Cascading Style Sheets.
If you write your CSS rules in a single line it makes it easier to see the structure:
.area1 .item { color:red; }
.area2 .item { color:blue; }
.area2 .item span { font-weight:bold; }
Using multiple classes is also a good intermediate/advanced use of CSS, unfortunately there is a well known IE6 bug which limits this usage when writing cross browser code:
<div class="area1 larger"> .... </div>
.area1 { width:200px; }
.area1.larger { width:300px; }
IE6 IGNORES the first selector in a multi-class rule, so IE6 actually applies the .area1.larger rule as
/*.area1*/.larger { ... }
Meaning it will affect ALL .larger elements.
It's a very nasty and unfortunate bug (one of many) in IE6 that forces you to pretty much never use that feature of CSS if you want one clean cross-browser CSS file.
The solution then is to use CSS classname prefixes to avoid colliding wiht generic classnames:
.area1 { ... }
.area1.area1Larger { ... }
.area2.area2Larger { ... }
May as well use just one class, but that way you can keep the CSS in the logic you intended, while knowing that .area1Larger only affects .area1, etc.
string name = System.Environment.MachineName;
From Item 46 in Effective Java by Joshua Bloch :
The for-each loop, introduced in release 1.5, gets rid of the clutter and the opportunity for error by hiding the iterator or index variable completely. The resulting idiom applies equally to collections and arrays:
// The preferred idiom for iterating over collections and arrays for (Element e : elements) { doSomething(e); }
When you see the colon (:), read it as “in.” Thus, the loop above reads as “for each element e in elements.” Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once. While you can do this by hand (Item 45), programmers don’t always do so.
Keystore is used by a server to store private keys, and Truststore is used by third party client to store public keys provided by server to access. I have done that in my production application. Below are the steps for generating java certificates for SSL communication:
keytool -genkey -keystore server.keystore -alias mycert -keyalg RSA -keysize 2048 -validity 3950
keytool -selfcert -alias mycert -keystore server.keystore -validity 3950
keytool -export -alias mycert -keystore server.keystore -rfc -file mycert.cer
keytool -importcert -alias mycert -file mycert.cer -keystore truststore
Go doesn't really have a character type as such. byte is often used for ASCII characters, and rune is used for Unicode characters, but they are both just aliases for integer types (uint8 and int32). So if you want to force them to be printed as characters instead of numbers, you need to use Printf("%c", x)
. The %c
format specification works for any integer type.
Such difference between the output of du -sh
and df -h
may happen if some large file has been deleted, but is still opened by some process. Check with the command lsof | grep deleted
to see which processes have opened descriptors to deleted files. You can restart the process and the space will be freed.
queryForList returns a List of LinkedHashMap objects.
You need to cast it first like this:
List list = jdbcTemplate.queryForList(...); for (Object o : list) { Map m = (Map) o; ... }
math.log10 is fast but gives problem when your number is greater than 999999999999997. This is because the float have too many .9s, causing the result to round up.
The solution is to use a while counter method for numbers above that threshold.
To make this even faster, create 10^16, 10^17 so on so forth and store as variables in a list. That way, it is like a table lookup.
def getIntegerPlaces(theNumber):
if theNumber <= 999999999999997:
return int(math.log10(theNumber)) + 1
else:
counter = 15
while theNumber >= 10**counter:
counter += 1
return counter
In SWT you need not be in a listener to get at the mouse location. The Display object has the method getCursorLocation()
.
In vanilla SWT/JFace, call Display.getCurrent().getCursorLocation()
.
In an RCP application, call PlatformUI.getWorkbench().getDisplay().getCursorLocation()
.
For SWT applications, it is preferable to use getCursorLocation()
over the MouseInfo.getPointerInfo()
that others have mentioned, as the latter is implemented in the AWT toolkit that SWT was designed to replace.
You can try with below one:
<div style="width: 100%; height: 100%; overflow-x: visible; overflow-y: scroll;">Text</div>
Do it like this:
public static void main(String[] args) throws ParseException {
String dateStr = "2016-10-19T14:15:36+08:00";
Date date = javax.xml.bind.DatatypeConverter.parseDateTime(dateStr).getTime();
System.out.println(date);
}
Here is the output:
Wed Oct 19 15:15:36 CST 2016
If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?
I'm assuming your using a streams here, there are other ways to write a file.
It usually happens when the certificate does not match with the host name.
The solution would be to contact the host and ask it to fix its certificate.
Otherwise you can turn off cURL's verification of the certificate, use the -k
(or --insecure
) option.
Please note that as the option said, it is insecure. You shouldn't use this option because it allows man-in-the-middle attacks and defeats the purpose of HTTPS.
More can be found in here: http://curl.haxx.se/docs/sslcerts.html
The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:
struct { 11
char a; 012345678901
short b; ------------
char c; axbbcxxxdddd
int d;
};
This structure will occupy 12 bytes of memory (x being pad bytes).
Python works similarly (see the struct documentation):
>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12
Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:
>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'
Beware of letting struct handle padding. In C, these structures:
struct A { struct B {
short a; int a;
char b; char b;
}; };
are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:
>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'
I tried ultrasawblade's recipe as it seemed the most practical to me, and couldn't make it work. In the end i devised another way though, based as others in parameter substitution, this time with regex replacement:
[[ "${var//*([[:digit:]])}" ]]; && echo "$var is not numeric" || echo "$var is numeric"
It removes every :digit: class character in $var and checks if we are left with an empty string, meaning that the original was only numbers.
What i like about this one is its small footprint and flexibility. In this form it only works for non-delimited, base 10 integers, though surely you can use pattern matching to suit it to other needs.
If you are using Jenkins templates you could have additional VM settings defined in it and this might conflicting with your system VM settings
example your tempalate may have references such as these
<mavenOpts>-Xms512m -Xmx1024m -Xss1024k -XX:MaxPermSize=1024m -Dmaven.test.failure.ignore=false</mavenOpts>
Ensure to align these template entries with the VM setting of your system
you can use between too:
SELECT Table.date
FROM Table
WHERE date between current_date and current_date - interval '10 day';
Use Projections to specify which columns you would like to return.
Example
SQL Query
SELECT user.id, user.name FROM user;
Hibernate Alternative
Criteria cr = session.createCriteria(User.class)
.setProjection(Projections.projectionList()
.add(Projections.property("id"), "id")
.add(Projections.property("Name"), "Name"))
.setResultTransformer(Transformers.aliasToBean(User.class));
List<User> list = cr.list();
You could also have a union of the blank select with the select that has content:
select '' value, '' name
union
select value, name from mytable
The short answer: there is no difference.
The long answer: CHARACTER VARYING
is the official type name from the ANSI SQL standard, which all compliant databases are required to support. VARCHAR
is a shorter alias which all modern databases also support. I prefer VARCHAR
because it's shorter and because the longer name feels pedantic. However, postgres tools like pg_dump
and \d
will output character varying
.
There's no direct way to do it yet, unfortunately, but there are a couple indirect ways:
[dt.year for dt in dates.astype(object)]
or
[datetime.datetime.strptime(repr(d), "%Y-%m-%d %H:%M:%S").year for d in dates]
both inspired by the examples here.
Both of these work for me on Numpy 1.6.1. You may need to be a bit more careful with the second one, since the repr() for the datetime64 might have a fraction part after a decimal point.
Node MergeLists(Node list1, Node list2) {
if (list1 == null) return list2;
if (list2 == null) return list1;
if (list1.data < list2.data) {
list1.next = MergeLists(list1.next, list2);
return list1;
} else {
list2.next = MergeLists(list2.next, list1);
return list2;
}
}
You can try the following. It's working...
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
template <class T>
string to_string(T t, ios_base & (*f)(ios_base&))
{
ostringstream oss;
oss << f << t;
return oss.str();
}
int main ()
{
cout<<to_string<long>(123456, hex)<<endl;
system("PAUSE");
return 0;
}
This code I programmed is much faster for very large files:
public String readDoc(File f) {
String text = "";
int read, N = 1024 * 1024;
char[] buffer = new char[N];
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
while(true) {
read = br.read(buffer, 0, N);
text += new String(buffer, 0, read);
if(read < N) {
break;
}
}
} catch(Exception ex) {
ex.printStackTrace();
}
return text;
}
Using the bitstring module:
>>> bitstring.BitArray(uint=1245427, length=24).bytes
'\x13\x00\xf3'
Note though that for this method you need to specify the length in bits of the bitstring you are creating.
Internally this is pretty much the same as Alex's answer, but the module has a lot of extra functionality available if you want to do more with your data.
No it's not. Besides the documented URL handlers, there's no way to communicate with/launch another app.
Here is how removed special characters.
I simply applied regex
Dim strPattern As String: strPattern = "[^a-zA-Z0-9]" 'The regex pattern to find special characters
Dim strReplace As String: strReplace = "" 'The replacement for the special characters
Set regEx = CreateObject("vbscript.regexp") 'Initialize the regex object
Dim GCID As String: GCID = "Text #N/A" 'The text to be stripped of special characters
' Configure the regex object
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
' Perform the regex replacement
GCID = regEx.Replace(GCID, strReplace)
i know a Class is a bit the overkill
class Foo
{
private $sum = NULL;
public function __construct($array)
{
$this->sum[] = $array;
return $this;
}
public function getSum()
{
$sum = $this->sum;
for($i=0;$i<count($sum);$i++)
{
// get the last array index
$res[$i] = $sum[$i] + $sum[count($sum)-$i];
}
return $res;
}
}
$fo = new Foo($myarray)->getSum();
Based on the answer of @erwanp, you can use the formatted string literals of Python 3,
x = '2'
percentage = f'{x}%' # 2%
inside the FuncFormatter()
and combined with a lambda expression.
All wrapped:
ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: f'{y}%'))
Its another way to declare the constructor. You can also use the class name, for ex:
class Cat
{
function Cat()
{
echo 'meow';
}
}
and
class Cat
{
function __construct()
{
echo 'meow';
}
}
Are equivalent. They are called whenever a new instance of the class is created, in this case, they will be called with this line:
$cat = new Cat();
In order to make your code work without having to return the slice from Test, you can pass a pointer like this:
package main
import (
"fmt"
)
var a = make([]int, 7, 8)
func Test(slice *[]int) {
*slice = append(*slice, 100)
fmt.Println(*slice)
}
func main() {
for i := 0; i < 7; i++ {
a[i] = i
}
Test(&a)
fmt.Println(a)
}
This will check if particular email address exist in the table:
if (isset(User::where('email', Input::get('email'))->value('email')))
{
// Input::get('email') exist in the table
}
This started happening to me when my database size grew and I was doing a lot of transactions on it.
Truth is there is probably some way to optimize either your queries or your DB but try these 2 queries for a work around fix.
Run this:
SET GLOBAL innodb_lock_wait_timeout = 5000;
And then this:
SET innodb_lock_wait_timeout = 5000;
When you say "doesn't work", how do you know it doesn't work?
You might try to figure out if the file actually exists by adding:
while [ ! -f /tmp/list.txt ]
do
sleep 2 # or less like 0.2
done
ls -l /tmp/list.txt
You might also make sure that you're using a Bash (or related) shell by typing 'echo $SHELL'. I think that CSH and TCSH use a slightly different semantic for this loop.
It means that a process or script you have created is sending mail to an account on your local machine (for example, a mail server running on localhost application).
Manage this mail with these commands:
t <message list> type messages
n goto and type next message
e <message list> edit messages
f <message list> give head lines of messages
d <message list> delete messages
s <message list> file append messages to file
u <message list> undelete messages
R <message list> reply to message senders
r <message list> reply to message senders and all recipients
pre <message list> make messages go back to /var/mail
m <user list> mail to specific users
q quit, saving unresolved messages in mbox
x quit, do not remove system mailbox
h print out active message headers
! shell escape
cd [directory] chdir to directory or home if none given
A consists of integers, ranges of same, or user names separated by spaces. If omitted, Mail uses the last message typed.
A consists of user names or aliases separated by spaces. Aliases are defined in .mailrc in your home directory.
While jm-'s answer is the best way to handle this case, for future reference it is possible to access child scopes using a scope's $$childHead, $$childTail, $$nextSibling and $$prevSibling members. These aren't documented so they might change without notice, but they're there if you really need to traverse scopes.
// get $$childHead first and then iterate that scope's $$nextSiblings
for(var cs = scope.$$childHead; cs; cs = cs.$$nextSibling) {
// cs is child scope
}
Instead of using the conditions
syntax from Rails 2, use Rails 4's where
method instead:
def self.search(search, page = 1 )
wildcard_search = "%#{search}%"
where("name ILIKE :search OR postal_code LIKE :search", search: wildcard_search)
.page(page)
.per_page(5)
end
NOTE: the above uses parameter syntax instead of ? placeholder: these both should generate the same sql.
def self.search(search, page = 1 )
wildcard_search = "%#{search}%"
where("name ILIKE ? OR postal_code LIKE ?", wildcard_search, wildcard_search)
.page(page)
.per_page(5)
end
NOTE: using ILIKE
for the name - postgres case insensitive version of LIKE
I use PHP's file modified time function, for example:
echo <img src='Images/image.png?" . filemtime('Images/image.png') . "' />";
If you change the image then the new image is used rather than the cached one, due to having a different modified timestamp.
This will surely help you.
int n[] = {4,6,9,1,7};
for(int i=n.length;i>=0;i--){
for(int j=0;j<n.length-1;j++){
if(n[j] > n[j+1]){
swapNumbers(j,j+1,n);
}
}
}
printNumbers(n);
}
private static void swapNumbers(int i, int j, int[] array) {
int temp;
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static void printNumbers(int[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + ", ");
}
System.out.println("\n");
}
It depends which version of oracle you have, for 9i and below Statspack is what you are after, 10g and above, you want awr , both these tools will give you the top sql's and lots of other stuff.
If you are using Sass/Scss, then follow this,
Do npm install
npm install bootstrap --save
and add import
statement to your sass/scss file,
@import '~bootstrap/dist/css/bootstrap.css'
Cardinality of a set is the namber of the elements in set for we have a set a > a,b,c < so ths set contain 3 elements 3 is the cardinality of that set
Tbl.ListRows.Add
doesn't work for me and I believe lot others are facing the same problem. I use the following workaround:
'First check if the last row is empty; if not, add a row
If table.ListRows.count > 0 Then
Set lastRow = table.ListRows(table.ListRows.count).Range
For col = 1 To lastRow.Columns.count
If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
lastRow.Cells(1, col).EntireRow.Insert
'Cut last row and paste to second last
lastRow.Cut Destination:=table.ListRows(table.ListRows.count - 1).Range
Exit For
End If
Next col
End If
'Populate last row with the form data
Set lastRow = table.ListRows(table.ListRows.count).Range
Range("E7:E10").Copy
lastRow.PasteSpecial Transpose:=True
Range("E7").Select
Application.CutCopyMode = False
Hope it helps someone out there.
A slight extension to the answer given, so, hopefully useful to the asker and anyone else looking.
You can also SELECT
the values you want to delete. But watch out for the Error 1093 - You can't specify the target table for update in FROM clause.
DELETE FROM
orders_products_history
WHERE
(branchID, action) IN (
SELECT
branchID,
action
FROM
(
SELECT
branchID,
action
FROM
orders_products_history
GROUP BY
branchID,
action
HAVING
COUNT(*) > 10000
) a
);
I wanted to delete all history records where the number of history records for a single action/branch exceed 10,000. And thanks to this question and chosen answer, I can.
Hope this is of use.
Richard.