is all this really necessary, human perception and CRT vs LCD will vary, but the R G B intensity does not, Why not L = (R + G + B)/3
and set the new RGB to L, L, L?
Quick answer
On jQuery (more specifically on Sizzle), we use this (checkout master and open speed/index.html on your browser), which in turn uses benchmark.js. This is used to performance test the library.
Long answer
If the reader doesn't know the difference between benchmark, workload and profilers, first read some performance testing foundations on the "readme 1st" section of spec.org. This is for system testing, but understanding this foundations will help JS perf testing as well. Some highlights:
What is a benchmark?
A benchmark is "a standard of measurement or evaluation" (Webster’s II Dictionary). A computer benchmark is typically a computer program that performs a strictly defined set of operations - a workload - and returns some form of result - a metric - describing how the tested computer performed. Computer benchmark metrics usually measure speed: how fast was the workload completed; or throughput: how many workload units per unit time were completed. Running the same computer benchmark on multiple computers allows a comparison to be made.
Should I benchmark my own application?
Ideally, the best comparison test for systems would be your own application with your own workload. Unfortunately, it is often impractical to get a wide base of reliable, repeatable and comparable measurements for different systems using your own application with your own workload. Problems might include generation of a good test case, confidentiality concerns, difficulty ensuring comparable conditions, time, money, or other constraints.
If not my own application, then what?
You may wish to consider using standardized benchmarks as a reference point. Ideally, a standardized benchmark will be portable, and may already have been run on the platforms that you are interested in. However, before you consider the results you need to be sure that you understand the correlation between your application/computing needs and what the benchmark is measuring. Are the benchmarks similar to the kinds of applications you run? Do the workloads have similar characteristics? Based on your answers to these questions, you can begin to see how the benchmark may approximate your reality.
Note: A standardized benchmark can serve as reference point. Nevertheless, when you are doing vendor or product selection, SPEC does not claim that any standardized benchmark can replace benchmarking your own actual application.
Performance testing JS
Ideally, the best perf test would be using your own application with your own workload switching what you need to test: different libraries, machines, etc.
If this is not feasible (and usually it is not). The first important step: define your workload. It should reflect your application's workload. In this talk, Vyacheslav Egorov talks about shitty workloads you should avoid.
Then, you could use tools like benchmark.js to assist you collect metrics, usually speed or throughput. On Sizzle, we're interested in comparing how fixes or changes affect the systemic performance of the library.
If something is performing really bad, your next step is to look for bottlenecks.
How do I find bottlenecks? Profilers
In my case the problem occurred since I wanted to use a SDK that doesnt include the required library. When I increased the min. SDK level the problem dissappeared. Of course directly including the library's itself, should remove the error as well.
Yes
SELECT id || '' FROM some_table;
or SELECT id::text FROM some_table;
is postgresql, but mySql doesn't allow that!
short cut in mySql:
SELECT concat(id, '') FROM some_table;
EDIT: The below implementation proved to have problems on at least some HTC devices (they crashed). For that reason I don't use setclassname and stick with the action chooser menu. I strongly discourage using my old implementation.
Following is the old implementation:
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(youtubelink));
if(Utility.isAppInstalled("com.google.android.youtube", getActivity())) {
intent.setClassName("com.google.android.youtube", "com.google.android.youtube.WatchActivity");
}
startActivity(intent);
Where Utility is my own personal utility class with following methode:
public static boolean isAppInstalled(String uri, Context context) {
PackageManager pm = context.getPackageManager();
boolean installed = false;
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
installed = true;
} catch (PackageManager.NameNotFoundException e) {
installed = false;
}
return installed;
}
First I check if youtube is installed, if it is installed, I tell android which package I prefer to open my intent.
To do this you should alter the vertical-align property of the input.
<dd><label class="<?=$email_confirm_class;?>" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; border:none;" name="email_confirm" id="email_confirm" size="18" value="<?=$_POST['email_confirm'];?>" tabindex="4" /> *</dd>
Here is a more complete version. It has been tested in IE 8 and it works. see the difference by removing the vertical-align: middle from the input:
<html><head></head><body><dl><dt>test</dt><dd><label class="test" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; font-size: 22px" name="email_confirm" id="email_confirm" size="28" value="test" tabindex="4" /> *</dd></dl></body></html>
require('url').parse('/status?name=ryan', {parseQueryString: true}).query
returns
{ name: 'ryan' }
You need an scp client. Putty is not one. You can use WinSCP or PSCP. Both are free software.
You need
var i = $("#panel input");
or, depending on what exactly you want (see below)
var i = $("#panel :input");
the >
will restrict to children, you want all descendants.
EDIT: As Nick pointed out, there's a subtle difference between $("#panel input")
and $("#panel :input)
.
The first one will only retrieve elements of type input, that is <input type="...">
, but not <textarea>
, <button>
and <select>
elements. Thanks Nick, didn't know this myself and corrected my post accordingly. Left both options, because I guess the OP wasn't aware of that either and -technically- asked for inputs... :-)
One item that seems to have been missed is star transformations. Index Intersection operators resolve the predicate by calculating the set of rows hit by each of the predicates before any I/O is done on the fact table. On a star schema you would index each individual dimension key and the query optimiser can resolve which rows to select by the index intersection computation. The indexes on individual columns give the best flexibility for this.
This is unappealing as it requires I assign
df
to a variable before being able to filter on its values.
df[df["column_name"] != 5].groupby("other_column_name")
seems to work: you can nest the []
operator as well. Maybe they added it since you asked the question.
The easiest solution is to use numpy.insert().
The Advantage of np.insert()
over np.append
is that you can insert the new columns into custom indices.
import numpy as np
X = np.arange(20).reshape(10,2)
X = np.insert(X, [0,2], np.random.rand(X.shape[0]*2).reshape(-1,2)*10, axis=1)
'''
If you want the table to still be 100% then set one of the columns to have a width:100%; That will extend that column to fill the extra space and allow the other columns to keep their auto width :)
Kind of a trick realty... Even references are passed by value in Java, hence a change to the reference itself being scoped at the called function level. The compiler and/or JVM will often turn a value type into a reference.
This type of the function belongs to element operators. Some useful element operators are defined below.
We use element operators when we need to select a single element from a sequence based on a certain condition. Here is an example.
List<int> items = new List<int>() { 8, 5, 2, 4, 2, 6, 9, 2, 10 };
First() operator returns the first element of a sequence after satisfied the condition. If no element is found then it will throw an exception.
int result = items.Where(item => item == 2).First();
FirstOrDefault() operator returns the first element of a sequence after satisfied the condition. If no element is found then it will return default value of that type.
int result1 = items.Where(item => item == 2).FirstOrDefault();
Use the "REPLACE" string function on the column in question:
UPDATE (yourTable)
SET YourColumn = REPLACE(YourColumn, '*', '')
WHERE (your conditions)
Replace the "*" with the character you want to strip out and specify your WHERE clause to match the rows you want to apply the update to.
Of course, the REPLACE function can also be used - as other answerer have shown - in a SELECT statement - from your question, I assumed you were trying to update a table.
Marc
Stored procedure is the best way to do it. Because Meherzad's solution would work only if the data follows the same order.
If we have a table structure like this
col1 | col2 | col3
-----+------+------
3 | k | 7
5 | d | 3
1 | a | 5
6 | o | 2
2 | 0 | 8
It wont work. SQL Fiddle Demo
Here is a sample procedure code to achieve the same.
delimiter //
CREATE PROCEDURE chainReaction
(
in inputNo int
)
BEGIN
declare final_id int default NULL;
SELECT col3
INTO final_id
FROM table1
WHERE col1 = inputNo;
IF( final_id is not null) THEN
INSERT INTO results(SELECT col1, col2, col3 FROM table1 WHERE col1 = inputNo);
CALL chainReaction(final_id);
end if;
END//
delimiter ;
call chainReaction(1);
SELECT * FROM results;
DROP TABLE if exists results;
When using
$("#content").load("content.html");
Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server
this is a known problem with CSS resizing, unless all images have the same proportion, you have no way to do this via CSS.
The best approach would be to have a container, and resize one of the dimensions (always the same) of the images. In my example I resized the width.
If the container has a specified dimension (in my example the width), when telling the image to have the width at 100%, it will make it the full width of the container. The auto
at the height will make the image have the height proportional to the new width.
Ex:
HTML:
<div class="container">
<img src="something.png" />
</div>
<div class="container">
<img src="something2.png" />
</div>
CSS:
.container {
width: 200px;
height: 120px;
}
/* resize images */
.container img {
width: 100%;
height: auto;
}
From How to get full date with correct format?:
Please, use
android.text.format.DateFormat.getDateFormat(Context context)
android.text.format.DateFormat.getTimeFormat(Context context)
to get valid time and date formats in sense of current user settings (12/24 time format, for example).
import android.text.format.DateFormat;
private void some() {
final Calendar t = Calendar.getInstance();
textView.setText(DateFormat.getTimeFormat(this/*Context*/).format(t.getTime()));
}
UPDATE Employee SET Empid=emp3.empid
FROM EMP_Employee AS emp3
WHERE Employee.Empid=emp3.empid
The terms resource and endpoint are often used synonymously. But in fact they do not mean the same thing.
The term endpoint is focused on the URL that is used to make a request.
The term resource is focused on the data set that is returned by a request.
Now, the same resource can often be accessed by multiple different endpoints.
Also the same endpoint can return different resources, depending on a query string.
Let us see some examples:
Have a look at the following examples of different endpoints:
/api/companies/5/employees/3
/api/v2/companies/5/employees/3
/api/employees/3
They obviously could all access the very same resource in a given API.
Also an existing API could be changed completely. This could lead to new endpoints that would access the same old resources using totally new and different URLs:
/api/employees/3
/new_api/staff/3
If your endpoint returns a collection, you could implement searching/filtering/sorting using query strings. As a result the following URLs all use the same endpoint (/api/companies
), but they can return different resources (or resource collections, which by definition are resources in themselves):
/api/companies
/api/companies?sort=name_asc
/api/companies?location=germany
/api/companies?search=siemens
Accepted answer is good, but be careful with multilingual pages. The text differ in length:
English: Like
Dutch: Vind ik leuk
German: Gefällt mir
Just a heads up.
If you are using pandas you can access the index by calling .index of whatever array you wish to mimic. The train_test_split carries over the pandas indices to the new dataframes.
In your code you simply use
x1.index
and the returned array is the indexes relating to the original positions in x.
Or you can just use this simple 2 liner code :)
if (e.KeyCode == Keys.Enter)
button1.PerformClick();
Adding on top of @VonC superb answer, here is a ZSH function that you can add into your .zshrc file:
dockstop() {
docker rm $(docker stop $(docker ps -a -q --filter ancestor="$1" --format="{{.ID}}"))
}
Then in your command line, simply do dockstop myImageName
and it will stop and remove all containers that were started from an image called myImageName.
This is what I was looking for here:
declare -A hashmap
hashmap["key"]="value"
hashmap["key2"]="value2"
echo "${hashmap["key"]}"
for key in ${!hashmap[@]}; do echo $key; done
for value in ${hashmap[@]}; do echo $value; done
echo hashmap has ${#hashmap[@]} elements
This did not work for me with bash 4.1.5:
animals=( ["moo"]="cow" )
I use both Charles Proxy and Fiddler for my HTTP/HTTPS level debugging.
Pros of Charles Proxy:
Cons of Charles Proxy:
This is an old post however, one alternative is to use the command options:
ftp -n -s:ftpcmd.txt
the -n will suppress the initial login and then the file contents would be: (replace the 127.0.0.1 with your FTP site url)
open 127.0.0.1
user myFTPuser myftppassword
other commands here...
This avoids the user/password on separate lines
This is one more option to find the element for above question
$("#tbIntervalos").find('td[id="'+horaInicial+'"]')
If you use lightweight html ux lang, check here an example, write:
div root
.onmouseover = ev => {root.style.backgroundColor='red'}
.onmouseleave = ev => {root.style.backgroundColor='initial'}
The code above performes the css :hover metatag.
Here's how I did it in Excel 2003 using conditional formatting.
To apply conditional formatting to Sheet1
using values from Sheet2
, you need to mirror the values into Sheet1
.
Sheet1
.Enter the following formula into A1:
=IF(ISBLANK(Sheet2!B1),"",Sheet2!B1)
A1
by right-clicking it and selecting "Copy
".A
by right-clicking its header and selecting "Paste
".Sheet1
, column A
should now exactly mirror the values in Sheet2
, column B
.
(Note: if you don't like it in column A
, it works just as well to have it in column Z
or anywhere else.)
Sheet1
.B
by left-clicking its header.Format > Conditional Formatting...
Change Condition 1
to "Formula is
" and enter this formula:
=MATCH(B1,$A:$A,0)
Click the Format...
button and select a green background.
You should now see the green background applied to the matching cells in Sheet1
.
Sheet1
.A
and select "Hide
".This should automatically update Sheet1
whenever anything in Sheet2
is changed.
Making it invisible with visibility still makes it use up space. Rather try set the display to none to make it invisible, and then set the display to block to make it visible.
A very simple solution is put the below code in your .htaccess
. I had the same issue and it solve my problem.
<IfModule mod_alias.c>
RedirectMatch 403 favicon.ico
</IfModule>
Reference: http://perishablepress.com/block-favicon-url-404-requests/
Make it lowercase first:
.m_title {text-transform: lowercase}
Then make it the first letter uppercase:
.m_title:first-letter {text-transform: uppercase}
"text-transform: capitalize" works for a word; but if you want to use for sentences this solution is perfect.
use setTag();
like this:
@Override
public void onClick(View v) {
int tag = (Integer) v.getTag();
switch (tag) {
case 1:
System.out.println("button1 click");
break;
case 2:
System.out.println("button2 click");
break;
}
}
if you want to catch the keyboard enter button for doing your job which you want to done through any event like button click, you can write the below simple code for that text view
Edittext ed= (EditText) findViewById(R.id.edit_text);
ed.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
// Do you job here which you want to done through event
}
return false;
}
});
<asp:DropDownList id="MyDropDown" runat="server" />
Use $("select[name$='MyDropDown']").val()
.
You need to create an alias for the mother.kind
. You do this like so.
Criteria c = session.createCriteria(Cat.class);
c.createAlias("mother.kind", "motherKind");
c.addOrder(Order.asc("motherKind.value"));
return c.list();
You are mixing mysqli and mysql extensions, which will not work.
You need to use
$myConnection= mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysqli_select_db($myConnection, "mrmagicadam") or die ("no database");
mysqli
has many improvements over the original mysql
extension, so it is recommended that you use mysqli
.
Wanted to add that my problem was in an activity where I tried to make a FragmentTransaction
in onCreate BEFORE I called super.onCreate()
. I just moved super.onCreate()
to top of function and was worked fine.
You have the color you just need to convert it into the format you want.
Here's a script that should do the trick: http://www.phpied.com/rgb-color-parser-in-javascript/
All depends on the app you're trying to build. Use Window
s if you're building a dialog based app. Use Page
s if you're building a navigation based app. UserControl
s will be useful regardless of the direction you go as you can use them in both Windows and Pages.
A good place to start exploring is here: http://windowsclient.net/learn
len(repr(float(x)/3))
However I must say that this isn't as reliable as you think.
Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:
>>> print len(repr(0.1))
19
>>> print repr(0.1)
0.10000000000000001
The explanation on why this happens is in this chapter of the python tutorial.
A solution would be to use a type that specifically tracks decimal numbers, like python's decimal.Decimal
:
>>> print len(str(decimal.Decimal('0.1')))
3
This is one solution. If you want to make it more generic, you can use the StringUtils
library.
String value = "{first_name = naresh,last_name = kumar,gender = male}";
value = value.substring(1, value.length()-1); //remove curly brackets
String[] keyValuePairs = value.split(","); //split the string to creat key-value pairs
Map<String,String> map = new HashMap<>();
for(String pair : keyValuePairs) //iterate over the pairs
{
String[] entry = pair.split("="); //split the pairs to get key and value
map.put(entry[0].trim(), entry[1].trim()); //add them to the hashmap and trim whitespaces
}
For example you can switch
value = value.substring(1, value.length()-1);
to
value = StringUtils.substringBetween(value, "{", "}");
if you are using StringUtils
which is contained in apache.commons.lang
package.
You have 2 options
1) Use javascript to confirm deletion (use onsubmit event handler), however if the client has JS disabled, you're in trouble.
2) Use PHP to echo out a confirmation message, along with the contents of the form (hidden if you like) as well as a submit button called "confirmation", in PHP check if $_POST["confirmation"]
is set.
Uncommenting extension=php_pgsql.dll
in the php.ini
configuration files does work but, you may have to also restart your XAMPP server to finally get it working. I had to do this.
This is my function. Works with all currencies..
function toFloat(num) {
dotPos = num.indexOf('.');
commaPos = num.indexOf(',');
if (dotPos < 0)
dotPos = 0;
if (commaPos < 0)
commaPos = 0;
if ((dotPos > commaPos) && dotPos)
sep = dotPos;
else {
if ((commaPos > dotPos) && commaPos)
sep = commaPos;
else
sep = false;
}
if (sep == false)
return parseFloat(num.replace(/[^\d]/g, ""));
return parseFloat(
num.substr(0, sep).replace(/[^\d]/g, "") + '.' +
num.substr(sep+1, num.length).replace(/[^0-9]/, "")
);
}
Usage : toFloat("$1,100.00")
or toFloat("1,100.00$")
', '.join(set_3)
The join
is a string method, not a set method.
Although Günter's answer is correct, it doesn't cover the "jump to" the anchor tag part.
Therefore, additionally to:
<a [routerLink]="['somepath']" fragment="Test">Jump to 'Test' anchor </a>
this._router.navigate( ['/somepath', id ], {fragment: 'test'});
... in the component (parent) where you need a "jump to" behavior, add:
import { Router, NavigationEnd } from '@angular/router';
class MyAppComponent {
constructor(router: Router) {
router.events.subscribe(s => {
if (s instanceof NavigationEnd) {
const tree = router.parseUrl(router.url);
if (tree.fragment) {
const element = document.querySelector("#" + tree.fragment);
if (element) { element.scrollIntoView(true); }
}
}
});
}
}
Please note that this is a workaround! Follow this github issue for future updates. Credits to Victor Savkin for providing the solution!
Platform-Independent Line Breaks
finalString = "physical" + System.lineSeparator() + "distancing";
System.out.println(finalString);
Output:
physical
distancing
Notes:
Java 6: System.getProperty("line.separator")
Java 7 & above: System.lineSeparator()
From: http://www.cplusplus.com/reference/map/map/
"Internally, the elements in a map are always sorted by its key following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).
map containers are generally slower than unordered_map containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order."
I had the same thing happen to a PNG with transparency that was set as the background-image of an <A> element with opacity applied.
The fix was to set the background-color of the <A> element.
So, the following:
filter: alpha(opacity=40);
-moz-opacity: 0.4;
-khtml-opacity: 0.4;
opacity: 0.4;
background-image: ...;
Turns into:
/* "Overwritten" by the background-image. However this fixes the IE7 and IE8 PNG-transparency-plus-opacity bug. */
background-color: #FFFFFF;
filter: alpha(opacity=40);
-moz-opacity: 0.4;
-khtml-opacity: 0.4;
opacity: 0.4;
background-image: ...;
Maybe it's this part:
if speed > self.buginfo["maxspeed"]: self.buginfo["maxspeed"] = speed
if generation > self.buginfo["maxgen"] : self.buginfo["maxgen"] = generation
Try to remove the extra space to make it look aligned.
Edit: from pep8
Yes: x = 1 y = 2 long_variable = 3 No: x = 1 y = 2 long_variable = 3
Try to follow that coding style.
You can fire an event yourself in ngOnInit()
of your Angular root component and then listen for this event outside of Angular.
This is Dart code (I don't know TypeScript) but should't be to hard to translate
@Component(selector: 'app-element')
@View(
templateUrl: 'app_element.html',
)
class AppElement implements OnInit {
ElementRef elementRef;
AppElement(this.elementRef);
void ngOnInit() {
DOM.dispatchEvent(elementRef.nativeElement, new CustomEvent('angular-ready'));
}
}
The second (assuming you means CONTAINS
, and actually put it in a valid query) should be faster, because it can use some form of index (in this case, a full text index). Of course, this form of query is only available if the column is in a full text index. If it isn't, then only the first form is available.
The first query, using LIKE, will be unable to use an index, since it starts with a wildcard, so will always require a full table scan.
The CONTAINS
query should be:
SELECT * FROM table WHERE CONTAINS(Column, 'test');
I had a problem using forEach in IE 11 and also Firefox 49
I have found a workaround like this
Array.prototype.slice.call(document.getElementsByClassName("events")).forEach(function (key) {
console.log(key.id);
}
If you using latest Owl Carousel 2 version. You can replace the Navigation text by fontawesome icon. Code is below.
$('.your-class').owlCarousel({
loop: true,
items: 1, // Select Item Number
autoplay:true,
dots: false,
nav: true,
navText: ["<i class='fa fa-long-arrow-left'></i>","<i class='fa fa-long-arrow-right'></i>"],
});
Is there some command to create this folder?
If smb face this issue again, you should know the most simple way to create .m2
folder.
If you unzipped maven and set up maven path variable - just try mvn clean
command from anywhere you like!
Dont be afraid of error messages when running - it works and creates needed directory.
I had problems with this and this is the story (sad but true) :
If your table name is all lower case like : accounts
you can use: select * from AcCounTs
and it will work fine
If your table name is all lower case like : accounts
The following will fail:
select * from "AcCounTs"
If your table name is mixed case like : Accounts
The following will fail:
select * from accounts
If your table name is mixed case like : Accounts
The following will work OK:
select * from "Accounts"
I dont like remembering useless stuff like this but you have to ;)
You can use int casting which allows the base specification.
int(b, 2) # Convert a binary string to a decimal int.
Here's another LINQ solution:
string input = "dtststx";
char searchChar = 't';
int occurrencePosition = 3; // third occurrence of the char
var result = input.Select((c, i) => new { Char = c, Index = i })
.Where(item => item.Char == searchChar)
.Skip(occurrencePosition - 1)
.FirstOrDefault();
if (result != null)
{
Console.WriteLine("Position {0} of '{1}' occurs at index: {2}",
occurrencePosition, searchChar, result.Index);
}
else
{
Console.WriteLine("Position {0} of '{1}' not found!",
occurrencePosition, searchChar);
}
Just for fun, here's a Regex solution. I saw some people initially used Regex to count, but when the question changed no updates were made. Here is how it can be done with Regex - again, just for fun. The traditional approach is best for simplicity.
string input = "dtststx";
char searchChar = 't';
int occurrencePosition = 3; // third occurrence of the char
Match match = Regex.Matches(input, Regex.Escape(searchChar.ToString()))
.Cast<Match>()
.Skip(occurrencePosition - 1)
.FirstOrDefault();
if (match != null)
Console.WriteLine("Index: " + match.Index);
else
Console.WriteLine("Match not found!");
Try:
g = pd.DataFrame(['A','B','A','C','D','D','E'])
# Group by the contents of column 0
gg = g.groupby(0)
# Create a DataFrame with the counts of each letter
histo = gg.apply(lambda x: x.count())
# Add a new column that is the count / total number of elements
histo[1] = histo.astype(np.float)/len(g)
print histo
Output:
0 1
0
A 2 0.285714
B 1 0.142857
C 1 0.142857
D 2 0.285714
E 1 0.142857
So some days I lack brain cells and:
<android.support.v7.widget.SwitchCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/CustomSwitchStyle"/>
does not apply the theme because style is incorrect. I was supposed to use app:theme :P
<android.support.v7.widget.SwitchCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:theme="@style/CustomSwitchStyle"/>
Whoopsies. This post was what gave me insight into my mistake...hopefully if someone stumbles across this it will help them like it did me. Thank you Gaëtan Maisse for your answer
I believe, it is not possible to mock constructors using mockito. Instead, I suggest following approach
Class First {
private Second second;
public First(int num, String str) {
if(second== null)
{
//when junit runs, you get the mocked object(not null), hence don't
//initialize
second = new Second(str);
}
this.num = num;
}
... // some other methods
}
And, for test:
class TestFirst{
@InjectMock
First first;//inject mock the real testable class
@Mock
Second second
testMethod(){
//now you can play around with any method of the Second class using its
//mocked object(second),like:
when(second.getSomething(String.class)).thenReturn(null);
}
}
If Xcode complains when linking, e.g. Library not found for -lPods, it doesn't detect the implicit dependencies:
Go to Product > Edit Scheme Click on Build Add the Pods static library Clean and build again
Turns out I will missing a class called mysql-connector-java-5.1.2.jar, I added it this folder (C:\Program Files\pentaho\design-tools\data-integration\lib) and it worked with a MySQL connection and my data and tables appear.
I was able to use the workspace setting that other people on this page have been asking for.
In Preferences, ?+P, search for python.pythonPath
in the search bar.
You should see something like:
// Path to Python, you can use a custom version of Python by modifying this setting to include the full path.
"python.pythonPath": "python"
Then click on the WORKSPACE SETTINGS tab on the right side of the window. This will make it so the setting is only applicable to the workspace you're in.
Afterwards, click on the pencil icon next to "python.pythonPath". This should copy the setting over the workspace settings.
Change the value to something like:
"python.pythonPath": "${workspaceFolder}/venv"
The system I was working on is Windows Server 2008 Standard with IIS 7 (I guess that my experience will apply for all Windows systems of the same age).
Running
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir
SEEMED to work, as
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -lv
showed the .Net framework v4 registered with IIS.
But, running the same for .Net v2, namely
C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -ir
did NOT result in
C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -lv
showing the framework registered.
(And, for me, the installer for Kofax Capture Network Server was still missing ASP.NET.)
The solution was:
After that, aspnet_regiis.exe -lv (either version) shows the framework registered. (And the Kofax installer was also happy and worked.)
The linefeed character \n
is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n
instead, then it'll both see the line-break with only \n
and \r\n
, I've never had any problems using it.
Also, you should look into using a StringBuilder
instead of concatenating the String
in the while-loop at BookCatalog.toString()
, it is a lot more effective. For instance:
public String toString() {
BookNode current = front;
StringBuilder sb = new StringBuilder();
while (current!=null){
sb.append(current.getData().toString()+"\r\n ");
current = current.getNext();
}
return sb.toString();
}
Following @BobBrunius 2010 suggestion I created this with jQuery. No doubt it could be improved but it may help some.
$(document).ready(function() {_x000D_
_x000D_
alert("Number of lines: " + getTextLinesNum($("#textbox")));_x000D_
_x000D_
});_x000D_
_x000D_
function getTextLinesNum($element) {_x000D_
_x000D_
var originalHtml = $element.html();_x000D_
var words = originalHtml.split(" ");_x000D_
var linePositions = [];_x000D_
_x000D_
// Wrap words in spans_x000D_
for (var i in words) {_x000D_
words[i] = "<span>" + words[i] + "</span>";_x000D_
}_x000D_
_x000D_
// Temporarily replace element content with spans. Layout should be identical._x000D_
$element.html(words.join(" "));_x000D_
_x000D_
// Iterate through words and collect positions of text lines_x000D_
$element.children("span").each(function () {_x000D_
var lp = $(this).position().top;_x000D_
if (linePositions.indexOf(lp) == -1) linePositions.push(lp);_x000D_
});_x000D_
_x000D_
// Revert to original html content_x000D_
$element.html(originalHtml);_x000D_
_x000D_
// Return number of text lines_x000D_
return linePositions.length;_x000D_
_x000D_
}
_x000D_
#textbox {_x000D_
width: 200px;_x000D_
text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div id="textbox">Lorem ipsum dolor sit amet, consectetuer adipiscing elit,_x000D_
<br>sed diam nonummy</div>
_x000D_
You have to wrap the word in a span to accomplish this.
You can try this
click Help>Install New Software on the menu bar
<stdarg.h>
allows you to define variadic functions (which accept an indefinite number of arguments, like printf()
). I would define a function which took an arbitrary number of pairs of arguments, one which specifies the property to be updated, and one which specifies the value. Use an enum
or a string to specify the name of the property.
To set custom headers ON A REQUEST, build a request with the custom header before passing it to httpclient to send to http server. eg:
HttpClient client = HttpClients.custom().build();
HttpUriRequest request = RequestBuilder.get()
.setUri(someURL)
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.build();
client.execute(request);
Default header is SET ON HTTPCLIENT to send on every request to the server.
You can overwrite Bootstraps default CSS by adding your own rules.
<style type="text/css">
body { background: navy !important; } /* Adding !important forces the browser to overwrite the default style applied by Bootstrap */
</style>
That's because you are using JSON Object. When you face such problems then change your JSON Object to JSON Array Object.
For Example,
{"India":"IN","America":"US","United Kingdon":"UK"} json object
[{"country":"India","countryId":"IN"},{"country":"America","countryId":"US"},{"country":"United Kingdon","countryId":"UK"}]
No mention of Merge?
DataSet newdataset = new DataSet();
newdataset.Merge( olddataset.Tables[0].Select( filterstring, sortstring ));
Assuming that you have your data in a 2d array, this should work:
import numpy
import pylab
xy = numpy.zeros((2, 1000))
xy[0] = range(1000)
xy[1] = range(1000)
colors = [int(i % 23) for i in xy[0]]
pylab.scatter(xy[0], xy[1], c=colors)
pylab.show()
You can also set a cmap
attribute to control which colors will appear through use of a colormap; i.e. replace the pylab.scatter
line with:
pylab.scatter(xy[0], xy[1], c=colors, cmap=pylab.cm.cool)
A list of color maps can be found here
As already mentioned, awk is the right tool for this. If you don't want to use awk, instead of parsing output of "ls -l" line by line, you could iterate over all files and do an "ls -l" for each individual file like this:
for x in * ; do echo `ls -ld $x` ; done
If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^
. Then add all files and commit again.
If you don't set an expiration date the cookie will expire at the end of the user's session. I recommend using the date right before unix epoch time will extend passed a 32-bit integer. To put that in the cookie you would use document.cookie = "randomCookie=true; expires=Tue, 19 Jan 2038 03:14:07 UTC;
, assuming that randomCookie
is the cookie you are setting and true
is it's respective value.
Another alternative is to use a combination of mutate_if()
and str_to_uper()
function, both from the tidyverse package:
df %>% mutate_if(is.character, str_to_upper) -> df
This will convert all string variables in the data frame to upper case.
str_to_lower()
do the opposite.
Stupid as it may sound but all "Provisioning Profiles" re-appear under "Organizer - Devices" once you connect a real device.
This is what I use in my application:
static void Main()
{
bool mutexCreated = false;
System.Threading.Mutex mutex = new System.Threading.Mutex( true, @"Local\slimCODE.slimKEYS.exe", out mutexCreated );
if( !mutexCreated )
{
if( MessageBox.Show(
"slimKEYS is already running. Hotkeys cannot be shared between different instances. Are you sure you wish to run this second instance?",
"slimKEYS already running",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question ) != DialogResult.Yes )
{
mutex.Close();
return;
}
}
// The usual stuff with Application.Run()
mutex.Close();
}
Your string may contain non Latin1 characters, which leads to undefined data. It depends of what you mean by "it deosn't seem to work".
Lets check how the comparison with null is defined:
static void Main()
{
Console.WriteLine($"null != null => {null != null}");
Console.WriteLine($"null == null => {null == null}");
Console.WriteLine($"null != true => {null != true}");
Console.WriteLine($"null == true => {null == true}");
Console.WriteLine($"null != false => {null != false}");
Console.WriteLine($"null == false => {null == false}");
}
and the results are:
null != null => False
null == null => True
null != true => True
null == true => False
null != false => True
null == false => False
So you can safely use:
// check if null or false
if (nullable != true) ...
// check if null or true
if (nullable != false) ...
// check if true or false
if (nullable != null) ...
In theory SMTP can be handled by either TCP, UDP, or some 3rd party protocol.
As defined in RFC 821, RFC 2821, and RFC 5321:
SMTP is independent of the particular transmission subsystem and requires only a reliable ordered data stream channel.
In addition, the Internet Assigned Numbers Authority has allocated port 25 for both TCP and UDP for use by SMTP.
In practice however, most if not all organizations and applications only choose to implement the TCP protocol. For example, in Microsoft's port listing port 25 is only listed for TCP and not UDP.
The big difference between TCP and UDP that makes TCP ideal here is that TCP checks to make sure that every packet is received and re-sends them if they are not whereas UDP will simply send packets and not check for receipt. This makes UDP ideal for things like streaming video where every single packet isn't as important as keeping a continuous flow of packets from the server to the client.
Considering SMTP, it makes more sense to use TCP over UDP. SMTP is a mail transport protocol, and in mail every single packet is important. If you lose several packets in the middle of the message the recipient might not even receive the message and if they do they might be missing key information. This makes TCP more appropriate because it ensures that every packet is delivered.
Be aware that when you do press your <leader>
key you have only 1000ms (by default) to enter the command following it.
This is exacerbated because there is no visual feedback (by default) that you have pressed your <leader>
key and vim is awaiting the command; and so there is also no visual way to know when this time out has happened.
If you add set showcmd
to your vimrc
then you will see your <leader>
key appear in the bottom right hand corner of vim (to the left of the cursor location) and perhaps more importantly you will see it disappear when the time out happens.
The length of the timeout can also be set in your vimrc
, see :help timeoutlen
for more information.
You should be able to achieve that with the help of EditText's
method setSelection()
, see here
Personally I don't find the standard diagramming technique very helpful - the arrows always seem to point the wrong way for me. (They generally point towards the "parent" of each commit, which ends up being backwards in time, which is weird).
To explain it in words:
For reasons I don't understand, GUI tools for Git have never made much of an effort to present merge histories more cleanly, abstracting out the individual merges. So if you want a "clean history", you need to use rebase.
I seem to recall having read blog posts from programmers who only use rebase and others that never use rebase.
I'll try explaining this with a just-words example. Let's say other people on your project are working on the user interface, and you're writing documentation. Without rebase, your history might look something like:
Write tutorial
Merge remote-tracking branch 'origin/master' into fixdocs
Bigger buttons
Drop down list
Extend README
Merge remote-tracking branch 'origin/master' into fixdocs
Make window larger
Fix a mistake in howto.md
That is, merges and UI commits in the middle of your documentation commits.
If you rebased your code onto master instead of merging it, it would look like this:
Write tutorial
Extend README
Fix a mistake in howto.md
Bigger buttons
Drop down list
Make window larger
All of your commits are at the top (newest), followed by the rest of the master
branch.
(Disclaimer: I'm the author of the "10 things I hate about Git" post referred to in another answer)
For maximum flexibility, I usually prefer working with SizedBox like this:
Row(
children: <Widget>[
SizedBox(
width: 235,
child: Text('Hey, ')),
SizedBox(
width: 110,
child: Text('how are'),
SizedBox(
width: 10,
child: Text('you?'))
],
)
I've experienced problems with text alignment when using alignment in the past, whereas sizedbox always does the work.
Here is an example:
Via css:
<style>
.my-table {
page-break-before: always;
page-break-after: always;
}
.my-table tr {
page-break-inside: avoid;
}
</style>
or directly on the element:
<table style="page-break-before: always; page-break-after: always;">
<tr style="page-break-inside: avoid;">
..
</tr>
</table>
For what it's worth, I encountered this when I created an IntelliJ project on a Mac, and then moved the project over to my Windows machine. I had to manually open every file and change the encoding setting at the bottom right of the IntelliJ window. Probably not happening to most if any who read this question but that could have saved me a couple of hours of work...
//Multiple selection:
private void clbsec(CheckedListBox clb, string text)
{
for (int i = 0; i < clb.Items.Count; i++)
{
if(text == clb.Items[i].ToString())
{
clb.SetItemChecked(i, true);
}
}
}
using ==>
clbsec(checkedListBox1,"michael");
or
clbsec(checkedListBox1,textBox1.Text);
or
clbsec(checkedListBox1,dataGridView1.CurrentCell.Value.toString());
No software & No too much steps..
Just upload your APK & get your all resources from this site..
https://www.apkdecompilers.com/
This website will decompile the code embedded in APK files and extract all the other assets in the file.
note: I decompile my APK file & get code within one miniute from this website
Update 1:
I found another online decompiler site,
http://www.javadecompilers.com/apk/ - Not working continuously asking for popup blocking
Update 2:
I found apk decompiler app in play store,
https://play.google.com/store/apps/details?id=com.njlabs.showjava
We can decompile the apk files in our android phone. and also we can able to view the java & xml files in this application
Update 3:
We can use another option Analyze APK feature from Android studio 2.2 version
Build -> Analyze APK -> Select your APK -> it give results
<select v-model="challan.warehouse_id">
<option value="">Select Warehouse</option>
<option v-for="warehouse in warehouses" v-bind:value="warehouse.id" >
{{ warehouse.name }}
</option>
Here "challan.warehouse_id" come from "challan" object you get from:
editChallan: function() {
let that = this;
axios.post('/api/challan_list/get_challan_data', {
challan_id: that.challan_id
})
.then(function (response) {
that.challan = response.data;
})
.catch(function (error) {
that.errors = error;
});
}
When you have changes on your working copy, from command line do:
git stash
This will stash your changes and clear your status report
git pull
This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge
git stash pop
This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.
if you need to see what is in your stash
git stash list
Edit your phpmyadmin config.inc.php file and if you have Password, insert that in front of Password in following code:
$cfg['Servers'][$i]['verbose'] = 'localhost';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '3306';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = '**your-root-username**';
$cfg['Servers'][$i]['password'] = '**root-password**';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
Right-click on an aspx file and choose 'browse with'. I think there's an option there to set as default.
If you want to force-run a single specific directory or daemon's log files, you can usually find the configuration in /etc/logrotate.d
, and they will work standalone.
Keep in mind that global configuration specified in /etc/logrotate.conf
will not apply, so if you do this you should ensure you specify all the options you want in the /etc/logrotate.d/[servicename]
config file specifically.
You can try it out with -d
to see what would happen:
logrotate -df /etc/logrotate.d/nginx
Then you can run (using nginx as an example):
logrotate -f /etc/logrotate.d/nginx
And the nginx logs alone will be rotated.
It is easy to check for removable devices. However, there's no guarantee that it is a USB device:
var drives = DriveInfo.GetDrives()
.Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);
This will return a list of all removable devices that are currently accessible. More information:
DriveInfo
class (msdn documentation)DriveType
enumeration (msdn documentation)function arr(arr1,arr2){_x000D_
_x000D_
function filt(value){_x000D_
return arr2.indexOf(value) === -1;_x000D_
}_x000D_
_x000D_
return arr1.filter(filt)_x000D_
}_x000D_
_x000D_
document.getElementById("p").innerHTML = arr([1,2,3,4],[2,4])
_x000D_
<p id="p"></p>
_x000D_
Just Javascript (as requested)
Add this function somewhere on your page (preferably in the <head>
)
function clearBox(elementID)
{
document.getElementById(elementID).innerHTML = "";
}
Then add the button on click event:
<button onclick="clearBox('cart_item')" />
In JQuery (for reference)
If you prefer JQuery you could do:
$("#cart_item").html("");
Step 1: add &html5=True
to your favorite youtube url
Step 2: Find <video/>
tag in source
Step 3: Add controls="controls"
to video tag: <video controls="controls"..../>
Example:
<video controls="controls" class="video-stream" x-webkit-airplay="allow" data-youtube-id="N9oxmRT2YWw" src="http://v20.lscache8.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Cratebypass%2Coc%3AU0hPRVRMVV9FSkNOOV9MRllD&itag=43&ipbits=0&signature=D2BCBE2F115E68C5FF97673F1D797F3C3E3BFB99.59252109C7D2B995A8D51A461FF9A6264879948E&sver=3&ratebypass=yes&expire=1300417200&key=yt1&ip=0.0.0.0&id=37da319914f6616c"></video>
_x000D_
Note there seems to some expire
stuff. I don't know how long the src
string will work.
Still testing myself.
Edit (July 28, 2011): Note that this video src is specific to the browser you use to retrieve the page source. I think Youtube generates this HTML dynamically (at least currently) so in testing if I copy in Firefox this works in Firefox, but not Chrome, for example.
backdrop-filter
Unfortunately Mozilla has really dropped the ball and taken it's time with the feature. I'm personally hoping it makes it in to the next Firefox ESR as that is what the next major version of Waterfox will use.
MDN (Mozilla Developer Network) article: https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter
Mozilla implementation: https://bugzilla.mozilla.org/show_bug.cgi?id=1178765
From the MDN documentation page:
/* URL to SVG filter */
backdrop-filter: url(commonfilters.svg#filter);
/* <filter-function> values */
backdrop-filter: blur(2px);
backdrop-filter: brightness(60%);
backdrop-filter: contrast(40%);
backdrop-filter: drop-shadow(4px 4px 10px blue);
backdrop-filter: grayscale(30%);
backdrop-filter: hue-rotate(120deg);
backdrop-filter: invert(70%);
backdrop-filter: opacity(20%);
backdrop-filter: sepia(90%);
backdrop-filter: saturate(80%);
/* Multiple filters */
backdrop-filter: url(filters.svg#filter) blur(4px) saturate(150%);
As doc says also keep in mind the correct value combination:
The setting must be one of the values listed in the following table, or a combination of one "state..." value plus one "adjust..." value. Setting multiple values in either group — multiple "state..." values, for example — has undefined results. Individual values are separated by a vertical bar (|). For example:
<activity android:windowSoftInputMode="stateVisible|adjustResize" . . . >
Try setting your num_threads inside your omp parallel code, it worked for me. This will give output as 4
#pragma omp parallel
{
omp_set_num_threads(4);
int id = omp_get_num_threads();
#pragma omp for
for (i = 0:n){foo(A);}
}
printf("Number of threads: %d", id);
Here, I solved this issue by making two functions.
1. dynamicColors() to generate random color
function dynamicColors() {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
return "rgba(" + r + "," + g + "," + b + ", 0.5)";
}
2. poolColors() to create array of colors
function poolColors(a) {
var pool = [];
for(i = 0; i < a; i++) {
pool.push(dynamicColors());
}
return pool;
}
Then, just pass it
datasets: [{
data: arrData,
backgroundColor: poolColors(arrData.length),
borderColor: poolColors(arrData.length),
borderWidth: 1
}]
The length of an array in Java is immutable. So, you need to copy the desired part as a new array.
Use copyOfRange
method from java.util.Arrays class:
int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);
startIndex is the initial index of the range to be copied, inclusive.
endIndex is the final index of the range to be copied, exclusive. (This index may lie outside the array)
E.g.:
//index 0 1 2 3 4
int[] arr = {10, 20, 30, 40, 50};
Arrays.copyOfRange(arr, 0, 2); // returns {10, 20}
Arrays.copyOfRange(arr, 1, 4); // returns {20, 30, 40}
Arrays.copyOfRange(arr, 2, arr.length); // returns {30, 40, 50} (length = 5)
Try it this way,
ArrayList<String> List_Of_Array = new ArrayList<String>();
List_Of_Array.add("A");
List_Of_Array.add("B");
List_Of_Array.add("C");
List_Of_Array.add("D");
List_Of_Array.add("E");
List_Of_Array.add("F");
List_Of_Array.add("G");
List_Of_Array.add("H");
int i[] = {5,3,1};
for (int j = 0; j < i.length; j++) {
List_Of_Array.remove(i[j]);
}
The command palette
tells you the colours and their order when col = somefactor
. It can also be used to set the colours as well.
palette()
[1] "black" "red" "green3" "blue" "cyan" "magenta" "yellow" "gray"
In order to see that in your graph you could use a legend.
legend('topright', legend = levels(iris$Species), col = 1:3, cex = 0.8, pch = 1)
You'll notice that I only specified the new colours with 3 numbers. This will work like using a factor. I could have used the factor originally used to colour the points as well. This would make everything logically flow together... but I just wanted to show you can use a variety of things.
You could also be specific about the colours. Try ?rainbow
for starters and go from there. You can specify your own or have R do it for you. As long as you use the same method for each you're OK.
use moment in your function like this
moment(new Date(date)).format('MM/DD/YYYY')
As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.
ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)
As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().
Try this!
List<String> x = new ArrayList<String>(Arrays.asList("xyz", "abc"));
It's a good practice to declare the ArrayList
with interface List
if you don't have to invoke the specific methods.
This is really late to the party, but none of the solutions above worked for me. I didn't want the "Found total xxx records
" so I added info:false
to the config. When I removed that everything worked.
I should note that the first page loaded fine. When I hit next, the second page loaded, but immediately threw the above console error
There are different ways to return status code, 1 : RestController class should extends BaseRest class, in BaseRest class we can handle exception and return expected error codes. for example :
@RestController
@RequestMapping
class RestController extends BaseRest{
}
@ControllerAdvice
public class BaseRest {
@ExceptionHandler({Exception.class,...})
@ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorModel genericError(HttpServletRequest request,
HttpServletResponse response, Exception exception) {
ErrorModel error = new ErrorModel();
resource.addError("error code", exception.getLocalizedMessage());
return error;
}
I suppose this is a cleaner approach.
It works with inline height
and width
properties (I set random value in the fiddle to prove that) and with CSS max-width
property.
HTML:
<div class="wrapper">
<div class="h_iframe">
<iframe height="2" width="2" src="http://www.youtube.com/embed/WsFWhL4Y84Y" frameborder="0" allowfullscreen></iframe>
</div>
<p>Please scale the "result" window to notice the effect.</p>
</div>
CSS:
html,body {height: 100%;}
.wrapper {width: 80%; max-width: 600px; height: 100%; margin: 0 auto; background: #CCC}
.h_iframe {position: relative; padding-top: 56%;}
.h_iframe iframe {position: absolute; top: 0; left: 0; width: 100%; height: 100%;}
What you need to do is this:
int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };
int[][] lists = new int[][] { list1 , list2 , list3 , list4 };
Another alternative would be to create a List<int[]>
type:
List<int[]> data=new List<int[]>(){list1,list2,list3,list4};
Future version of C# is going to include named tuples. Have a look at this channel9 session for the demo https://channel9.msdn.com/Events/Build/2016/B889
Skip to 13:00 for the tuple stuff. This will allow stuff like:
(int sum, int count) Tally(IEnumerable<int> list)
{
// calculate stuff here
return (0,0)
}
int resultsum = Tally(numbers).sum
(incomplete example from video)
PsSuspend command line utility from SysInternals
suite. It suspends / resumes a process by its id.
I have this folder structure:
D:\JavaProjects\OlivePressApp\com\lynda\olivepress\Main.class D:\JavaProjects\OlivePressApp\com\lynda\olivepress\press\OlivePress.class D:\JavaProjects\OlivePressApp\com\lynda\olivepress\olives\Kalamata.class D:\JavaProjects\OlivePressApp\com\lynda\olivepress\olives\Ligurian.class D:\JavaProjects\OlivePressApp\com\lynda\olivepress\olives\Olive.class
Main.class
is in package com.lynda.olivepress
There are two other packages:
com.lynda.olivepress.press
com.lynda.olivepress.olive
1) Create a file named "Manifest.txt"
with Two Lines, First with Main-Class and a Second Empty Line.
Main-Class: com.lynda.olivepress.Main
D:\JavaProjects\OlivePressApp\ Manifest.txt
2) Create JAR with Manifest and Main-Class Entry Point
D:\JavaProjects\OlivePressApp>jar cfm OlivePressApp.jar Manifest.txt com/lynda/olivepress/Main.class com/lynda/olivepress/*
3) Run JAR
java -jar OlivePressApp.jar
Note: com/lynda/olivepress/*
means including the other two packages mentioned above, before point 1)
Check this fully functional directive for MEAN.JS (Angular.js, bootstrap, Express.js and MongoDb)
Based on @Blackhole ´s response, we just finished it to be used with mongodb and express.
It will allow you to save and load dates from a mongoose connector
Hope it Helps!!
angular.module('myApp')
.directive(
'dateInput',
function(dateFilter) {
return {
require: 'ngModel',
template: '<input type="date" class="form-control"></input>',
replace: true,
link: function(scope, elm, attrs, ngModelCtrl) {
ngModelCtrl.$formatters.unshift(function (modelValue) {
return dateFilter(modelValue, 'yyyy-MM-dd');
});
ngModelCtrl.$parsers.push(function(modelValue){
return angular.toJson(modelValue,true)
.substring(1,angular.toJson(modelValue).length-1);
})
}
};
});
The JADE/HTML:
div(date-input, ng-model="modelDate")
Note that if you want to rebuild the MYI file then the correct use of REPAIR TABLE is:
REPAIR TABLE sometable USE_FRM;
Otherwise you will probably just get another error.
if nothing worked, try this
public struct Platform {
public static var isSimulator: Bool {
return TARGET_OS_SIMULATOR != 0 // Use this line in Xcode 7 or newer
}
}
Easiest thing to do is a simple loop. I'm going to assume that you want the trimmed string returned in place.
char *
strTrim(char * s){
int ix, jx;
int len ;
char * buf
len = strlen(s); /* possibly should use strnlen */
buf = (char *) malloc(strlen(s)+1);
for(ix=0, jx=0; ix < len; ix++){
if(!isspace(s[ix]))
buf[jx++] = s[ix];
buf[jx] = '\0';
strncpy(s, buf, jx); /* always looks as far as the null, but who cares? */
free(buf); /* no good leak goes unpunished */
return s; /* modifies s in place *and* returns it for swank */
}
This gets rid of embedded blanks too, if String.Trim doesn't then it needs a bit more logic.
In PowerShell v3, have a look at the Invoke-WebRequest and Invoke-RestMethod e.g.:
$msg = Read-Host -Prompt "Enter message"
$encmsg = [System.Web.HttpUtility]::UrlEncode($msg)
Invoke-WebRequest -Uri "http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$encmsg&encoding=windows-1255"
It's no join since the relationship will only be evaluated when needed. A join (in a SQL database) on the other hand will resolve relationships and return them as if they were a single table (you "join two tables into one").
You can read more about DBRef here: http://docs.mongodb.org/manual/applications/database-references/
There are two possible solutions for resolving references. One is to do it manually, as you have almost described. Just save a document's _id in another document's other_id, then write your own function to resolve the relationship. The other solution is to use DBRefs as described on the manual page above, which will make MongoDB resolve the relationship client-side on demand. Which solution you choose does not matter so much because both methods will resolve the relationship client-side (note that a SQL database resolves joins on the server-side).
Using Houshalter's suggestion, I made this simple tone synthesizer demo.
Here is a screenshot. Try the live demo further down in this Answer (click Run code snippet).
audioCtx = new(window.AudioContext || window.webkitAudioContext)();_x000D_
_x000D_
show();_x000D_
_x000D_
function show() {_x000D_
frequency = document.getElementById("fIn").value;_x000D_
document.getElementById("fOut").innerHTML = frequency + ' Hz';_x000D_
_x000D_
switch (document.getElementById("tIn").value * 1) {_x000D_
case 0: type = 'sine'; break;_x000D_
case 1: type = 'square'; break;_x000D_
case 2: type = 'sawtooth'; break;_x000D_
case 3: type = 'triangle'; break;_x000D_
}_x000D_
document.getElementById("tOut").innerHTML = type;_x000D_
_x000D_
volume = document.getElementById("vIn").value / 100;_x000D_
document.getElementById("vOut").innerHTML = volume;_x000D_
_x000D_
duration = document.getElementById("dIn").value;_x000D_
document.getElementById("dOut").innerHTML = duration + ' ms';_x000D_
}_x000D_
_x000D_
function beep() {_x000D_
var oscillator = audioCtx.createOscillator();_x000D_
var gainNode = audioCtx.createGain();_x000D_
_x000D_
oscillator.connect(gainNode);_x000D_
gainNode.connect(audioCtx.destination);_x000D_
_x000D_
gainNode.gain.value = volume;_x000D_
oscillator.frequency.value = frequency;_x000D_
oscillator.type = type;_x000D_
_x000D_
oscillator.start();_x000D_
_x000D_
setTimeout(_x000D_
function() {_x000D_
oscillator.stop();_x000D_
},_x000D_
duration_x000D_
);_x000D_
};
_x000D_
frequency_x000D_
<input type="range" id="fIn" min="40" max="6000" oninput="show()" />_x000D_
<span id="fOut"></span><br>_x000D_
type_x000D_
<input type="range" id="tIn" min="0" max="3" oninput="show()" />_x000D_
<span id="tOut"></span><br>_x000D_
volume_x000D_
<input type="range" id="vIn" min="0" max="100" oninput="show()" />_x000D_
<span id="vOut"></span><br>_x000D_
duration_x000D_
<input type="range" id="dIn" min="1" max="5000" oninput="show()" />_x000D_
<span id="dOut"></span>_x000D_
<br>_x000D_
<button onclick='beep();'>Play</button>
_x000D_
You can clone and tweak the code here: Tone synthesizer demo on JS Bin
Have fun!
If you have your arguments in an array, you might be interested by the call_user_func_array
function.
If the number of arguments you want to pass depends on the length of an array, it probably means you can pack them into an array themselves -- and use that one for the second parameter of call_user_func_array
.
Elements of that array you pass will then be received by your function as distinct parameters.
For instance, if you have this function :
function test() {
var_dump(func_num_args());
var_dump(func_get_args());
}
You can pack your parameters into an array, like this :
$params = array(
10,
'glop',
'test',
);
And, then, call the function :
call_user_func_array('test', $params);
This code will the output :
int 3
array
0 => int 10
1 => string 'glop' (length=4)
2 => string 'test' (length=4)
ie, 3 parameters ; exactly like iof the function was called this way :
test(10, 'glop', 'test');
Set display.max_rows
:
pd.set_option('display.max_rows', 500)
For older versions of pandas (<=0.11.0) you need to change both display.height
and display.max_rows
.
pd.set_option('display.height', 500)
pd.set_option('display.max_rows', 500)
See also pd.describe_option('display')
.
You can set an option only temporarily for this one time like this:
from IPython.display import display
with pd.option_context('display.max_rows', 100, 'display.max_columns', 10):
display(df) #need display to show the dataframe when using with in jupyter
#some pandas stuff
You can also reset an option back to its default value like this:
pd.reset_option('display.max_rows')
And reset all of them back:
pd.reset_option('all')
There's also WordNet. Its data files format are well-documented.
I used it for building an embeddable dictionary library for iOS developers (www.lexicontext.com) and also in one of my apps.
sizeof(source)
returns sizeof a pointer as source is declared as char *.
Correct way to use it is strlen(source)
.
Next:
printf("%s",source[i]);
expects string. i.e %s expects string but you are iterating in a loop to print each character. Hence use %c.
However your way of accessing(iterating) a string using the index i is correct and hence there are no other issues in it.
You can use ImportRow
method to copy Row from DataTable to DataTable with the same schema:
var row = SourceTable.Rows[RowNum];
DestinationTable.ImportRow(row);
Update:
With your new Edit, I believe:
var desRow = dataTable.NewRow();
var sourceRow = dataTable.Rows[rowNum];
desRow.ItemArray = sourceRow.ItemArray.Clone() as object[];
will work
In Excel 2007 you have the option to show empty cells as gaps, zero or connect data points with a line (I assume it's similar for Excel 2010):
If none of these are optimal and you have a "chunk" of data points (or even single ones) missing, you can group-and-hide them, which will remove them from the chart.
Before hiding:
After hiding:
function trimNumber(num, len) {
const modulu_one = 1;
const start_numbers_float=2;
var int_part = Math.trunc(num);
var float_part = String(num % modulu_one);
float_part = float_part.slice(start_numbers_float, start_numbers_float+len);
return int_part+'.'+float_part;
}
One quick solution that came to mind :-
<input type="checkbox" id="markitem" name="markitem" value="1" onchange="GetMarkedItems(1)">
<label for="markitem" style="position:absolute; top:1px; left:165px;"> </label>
<!-- Fire the below javascript everytime the page reloads -->
<script type=text/javascript>
document.getElementById("markitem").checked = false;
</script>
<!-- Tested on Latest FF, Chrome, Opera and IE. -->
From http://docs.python.org/library/csv.html#csv.writer:
If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.
In other words, when opening the file you pass 'wb' as opposed to 'w'.
You can also use a with
statement to close the file when you're done writing to it.
Tested example below:
from __future__ import with_statement # not necessary in newer versions
import csv
headers=['id', 'year', 'activity', 'lineitem', 'datum']
with open('file3.csv','wb') as fou: # note: 'wb' instead of 'w'
output = csv.DictWriter(fou,delimiter=',',fieldnames=headers)
output.writerow(dict((fn,fn) for fn in headers))
output.writerows(rows)
Use this one:
Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")
Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")
With rng.Validation
.Delete 'delete previous validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & ws.Name & "'!" & range1.Address
End With
Note that when you're using Dim range1, rng As range
, only rng
has type of Range
, but range1
is Variant
. That's why I'm using Dim range1 As Range, rng As Range
.
About meaning of parameters you can read is MSDN, but in short:
Type:=xlValidateList
means validation type, in that case you should select value from listAlertStyle:=xlValidAlertStop
specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.Operator:= xlBetween
is odd. It can be used only if two formulas are provided for validation.Formula1:="='" & ws.Name & "'!" & range1.Address
for list data validation provides address of list with values (in format =Sheet!A1:A5
)Here is some weak adobe documentation on different flash 9 wmode settings.
A note of caution on wmode transparent is here in the adobe bug trac.
And new for flash 10, are two new wmodes: gpu and direct. Please refer to Adobe Knowledge Base about wmode.
My blog will work 100 percent.
function showLoader()_x000D_
{_x000D_
$(".loader").fadeIn("slow");_x000D_
}_x000D_
function hideLoader()_x000D_
{_x000D_
$(".loader").fadeOut("slow");_x000D_
}
_x000D_
.loader {_x000D_
position: fixed;_x000D_
left: 0px;_x000D_
top: 0px;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
z-index: 9999;_x000D_
background: url('pageLoader2.gif') 50% 50% no-repeat rgb(249,249,249);_x000D_
opacity: .8;_x000D_
}
_x000D_
<div class="loader">
_x000D_
First create a 'Solution Folder' with the desired relative path. Note that Visual Studio 2012 does not create a system folder with the same relative path.
Now inside that 'Solution Folder' add a new project, but you must be careful when defining it that the relative path in the system matches the relative path of your new 'Solution Folder'. If the system folder you want does not exist, Visual Studio 2012 will now create it for the new project. (As noted above, it does not do this when you add a new 'Solution Folder'.)
If you want to add an existing file with the matching relative path, you must first create the file in the matching system relative path, from outside of Visual Studio. Then you can Add existing file in Visual Studio.
Hello what about something like this? Very simple implementation, Injector itself is singleton and also added classes into it. Of course can be extended very easily. If you are looking for something more sophisticated check this package: https://pub.dartlang.org/packages/flutter_simple_dependency_injection
void main() {
Injector injector = Injector();
injector.add(() => Person('Filip'));
injector.add(() => City('New York'));
Person person = injector.get<Person>();
City city = injector.get<City>();
print(person.name);
print(city.name);
}
class Person {
String name;
Person(this.name);
}
class City {
String name;
City(this.name);
}
typedef T CreateInstanceFn<T>();
class Injector {
static final Injector _singleton = Injector._internal();
final _factories = Map<String, dynamic>();
factory Injector() {
return _singleton;
}
Injector._internal();
String _generateKey<T>(T type) {
return '${type.toString()}_instance';
}
void add<T>(CreateInstanceFn<T> createInstance) {
final typeKey = _generateKey(T);
_factories[typeKey] = createInstance();
}
T get<T>() {
final typeKey = _generateKey(T);
T instance = _factories[typeKey];
if (instance == null) {
print('Cannot find instance for type $typeKey');
}
return instance;
}
}
If you don't need the DATETIME value in the rest of your code, it'd be more efficient, simple and secure to use an UPDATE query with a sub-select, something like
UPDATE products SET t=(SELECT f FROM products WHERE id=17) WHERE id=42;
or in case it's in the same row in a single table, just
UPDATE products SET t=f WHERE id=42;
Open the Command Palette
Ctrl + Shift + P
Then type:
Reload Window
Try to use the WEEKDAY()
function.
Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).
If you really want to scale an image, do it, but you should resize it before using it. Resizing it at run time will just lose CPU cycles.
This is the category I'm using to scale an image :
UIImage+Extra.h
@interface UIImage (Extras)
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
@end;
UIImage+Extra.m
@implementation UIImage (Extras)
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {
UIImage *sourceImage = self;
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
if (!CGSizeEqualToSize(imageSize, targetSize)) {
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
if (widthFactor < heightFactor)
scaleFactor = widthFactor;
else
scaleFactor = heightFactor;
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
// center the image
if (widthFactor < heightFactor) {
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
} else if (widthFactor > heightFactor) {
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
// this is actually the interesting part:
UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0);
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if(newImage == nil) NSLog(@"could not scale image");
return newImage ;
}
@end
You can use it to the size you want. Like :
[self.itemImageButton setImage:[stretchImage imageByScalingProportionallyToSize:CGSizeMake(20,20)]];
ASCII encoding is 7-bit, but in practice, characters encoded in ASCII are not stored in groups of 7 bits. Instead, one ASCII is stored in a byte, with the MSB usually set to 0 (yes, it's wasted in ASCII).
You can verify this by inputting a string in the ASCII character set in a text editor, setting the encoding to ASCII, and viewing the binary/hex:
Aside: the use of (strictly) ASCII encoding is now uncommon, in favor of UTF-8 (which does not waste the MSB mentioned above - in fact, an MSB of 1 indicates the code point is encoded with more than 1 byte).
You could also try this:
SELECT DISTINCT (DATE(dateadded)) AS unique_date, COUNT(*) AS amount
FROM table
GROUP BY unique_date
ORDER BY unique_date ASC
You could simply get the character length of the current directory, and remove them from your absolute list
setlocal EnableDelayedExpansion
for /L %%n in (1 1 500) do if "!__cd__:~%%n,1!" neq "" set /a "len=%%n+1"
setlocal DisableDelayedExpansion
for /r . %%g in (*.log) do (
set "absPath=%%g"
setlocal EnableDelayedExpansion
set "relPath=!absPath:~%len%!"
echo(!relPath!
endlocal
)
Can't tell you how many times this has caught. me.
Guid myGuid = Guid.NewGuid();
try this
var locations = [
['San Francisco: Power Outage', 37.7749295, -122.4194155,'http://labs.google.com/ridefinder/images/mm_20_purple.png'],
['Sausalito', 37.8590937, -122.4852507,'http://labs.google.com/ridefinder/images/mm_20_red.png'],
['Sacramento', 38.5815719, -121.4943996,'http://labs.google.com/ridefinder/images/mm_20_green.png'],
['Soledad', 36.424687, -121.3263187,'http://labs.google.com/ridefinder/images/mm_20_blue.png'],
['Shingletown', 40.4923784, -121.8891586,'http://labs.google.com/ridefinder/images/mm_20_yellow.png']
];
//inside the loop
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: locations[i][3]
});
This method will prevent you from getting an 'Access-Control-Allow-Origin' error from the server you are accessing to.
var img = new Image();
var timestamp = new Date().getTime();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url + '?' + timestamp;
You should bring your data into long (i.e. molten) format to use it with ggplot2
:
library("reshape2")
mdf <- melt(mdf, id.vars="Company", value.name="value", variable.name="Year")
And then you have to use aes( ... , group = Company )
to group them:
ggplot(data=mdf, aes(x=Year, y=value, group = Company, colour = Company)) +
geom_line() +
geom_point( size=4, shape=21, fill="white")
This is totally valid, I do it all the time. I usually use IllegalArguemntException if it is a result of parameter checking.
In this case I wouldn't suggest asserts because they are turned off in a deployment build and you always want to stop this from happening, but they are valid if your group does ALL it's testing with asserts turned on and you think the chance of missing a parameter problem at runtime is more acceptable than throwing an exception that is maybe more likely to cause a runtime crash.
Also, an assert would be more difficult for the caller to trap, this is easy.
You probably want to list it as a "throws" in your method's javadocs along with the reason so that callers aren't surprised.
You can use the Material Design Switch for Bootstrap 3.3.0
http://bootsnipp.com/snippets/featured/material-design-switch
Yes you can. The default location for script files is data/db
If you put any script there you can call it as
load("myjstest.js") // or
load("/data/db/myjstest.js")
db.runCommand( { "connPoolStats" : 1 } )
{
"numClientConnections" : 0,
"numAScopedConnections" : 0,
"totalInUse" : 0,
"totalAvailable" : 0,
"totalCreated" : 0,
"hosts" : {
},
"replicaSets" : {
},
"ok" : 1
}
If you absolutely have to add the property to the object, I believe you could cast it as an array, add your property (as a new array key), then cast it back as an object. The only time you run into stdClass
objects (I believe) is when you cast an array as an object or when you create a new stdClass
object from scratch (and of course when you json_decode()
something - silly me for forgetting!).
Instead of:
$foo = new StdClass();
$foo->bar = '1234';
You'd do:
$foo = array('bar' => '1234');
$foo = (object)$foo;
Or if you already had an existing stdClass object:
$foo = (array)$foo;
$foo['bar'] = '1234';
$foo = (object)$foo;
Also as a 1 liner:
$foo = (object) array_merge( (array)$foo, array( 'bar' => '1234' ) );
I just want to add that there is another Lifecycle hook called DoCheck
that is useful if the @Input
value is not a primitive value.
I have an Array as an Input
so this does not fire the OnChanges
event when the content changes (because the checking that Angular does is 'simple' and not deep so the Array is still an Array, even though the content on the Array has changed).
I then implement some custom checking code to decide if I want to update my view with the changed Array.
I know question is already answered.
But let me add one point here. This is not only case of true or false. See below:
var val="Do";
Var c= (val == "Do" || val == "Done")
? 7
: 0
Here if val is Do or Done then c will be 7 else it will be zero. In this case c will be 7.
This is actually another perspective of this operator.
-Dspring.profiles.active=staging -Dspring.config.location=C:\Config
is not correct.
should be:
--spring.profiles.active=staging --spring.config.location=C:\Config
The following is applicable for docker-compose 3.x Set environment variables inside the container
method - 1 Straight method
web:
environment:
- DEBUG=1
POSTGRES_PASSWORD: 'postgres'
POSTGRES_USER: 'postgres'
method - 2 The “.env” file
Create a .env file in the same location as the docker-compose.yml
$ cat .env
TAG=v1.5
POSTGRES_PASSWORD: 'postgres'
and your compose file will be like
$ cat docker-compose.yml
version: '3'
services:
web:
image: "webapp:${TAG}"
postgres_password: "${POSTGRES_PASSWORD}"
I know this was posted a long while ago, and it has been marked answered, but to me, the selected answer was not answering the question I thought the user was posing. It seemed to me he was looking for the approach one can take in ASP .Net that corresponds to his inline data binding previously performed in php.
Here was his php:
<p>Here is the username: <?php echo GetUserName(); ?></p>
Here is what one would do in ASP .Net:
<p>Here is the username: <%= GetUserName() %></p>
I agree with the common answer here that yes you should dispose and no you generally shouldn't set the variable to null... but I wanted to point out that dispose is NOT primarily about memory management. Yes, it can help (and sometimes does) with memory management, but it's primary purpose is to give you deterministic releasing of scarce resources.
For example, if you open a hardware port (serial for example), a TCP/IP socket, a file (in exclusive access mode) or even a database connection you have now prevented any other code from using those items until they are released. Dispose generally releases these items (along with GDI and other "os" handles etc. which there are 1000's of available, but are still limited overall). If you don't call dipose on the owner object and explicitly release these resources, then try to open the same resource again in the future (or another program does) that open attempt will fail because your undisposed, uncollected object still has the item open. Of course, when the GC collects the item (if the Dispose pattern has been implemented correctly) the resource will get released... but you don't know when that will be, so you don't know when it's safe to re-open that resource. This is the primary issue Dispose works around. Of course, releasing these handles often releases memory too, and never releasing them may never release that memory... hence all the talk about memory leaks, or delays in memory clean up.
I have seen real world examples of this causing problems. For instance, I have seen ASP.Net web applications that eventually fail to connect to the database (albeit for short periods of time, or until the web server process is restarted) because the sql server 'connection pool is full'... i.e, so many connections have been created and not explicitly released in so short a period of time that no new connections can be created and many of the connections in the pool, although not active, are still referenced by undiposed and uncollected objects and so can't be reused. Correctly disposing the database connections where necessary ensures this problem doesn't happen (at least not unless you have very high concurrent access).
Instead of doing file_put_contents(***WebSiteURL***...)
you need to use the server path to /cache/lang/file.php
(e.g. /home/content/site/folders/filename.php
).
You cannot open a file over HTTP
and expect it to be written. Instead you need to open it using the local path.
Assuming the points are (Ax,Ay) (Bx,By) and (Cx,Cy), you need to compute:
(Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax)
This will equal zero if the point C is on the line formed by points A and B, and will have a different sign depending on the side. Which side this is depends on the orientation of your (x,y) coordinates, but you can plug test values for A,B and C into this formula to determine whether negative values are to the left or to the right.
Since Node.js v0.12 and as of Node.js v4.0.0, there is a stable readline core module. Here's the easiest way to read lines from a file, without any external modules:
const fs = require('fs');
const readline = require('readline');
async function processLineByLine() {
const fileStream = fs.createReadStream('input.txt');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in input.txt as a single line break.
for (const line of rl) {
// Each line in input.txt will be successively available here as `line`.
console.log(`Line from file: ${line}`);
}
}
processLineByLine();
Or alternatively:
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream('file.in')
});
lineReader.on('line', function (line) {
console.log('Line from file:', line);
});
The last line is read correctly (as of Node v0.12 or later), even if there is no final \n
.
UPDATE: this example has been added to Node's API official documentation.
Use the following. It works in Firefox and Internet Explorer.
<object id="MediaPlayer1" width="690" height="500" classid="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95"
codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701"
standby="Loading Microsoft® Windows® Media Player components..." type="application/x-oleobject"
>
<param name="FileName" value='<%= GetSource() %>' />
<param name="AutoStart" value="True" />
<param name="DefaultFrame" value="mainFrame" />
<param name="ShowStatusBar" value="0" />
<param name="ShowPositionControls" value="0" />
<param name="showcontrols" value="0" />
<param name="ShowAudioControls" value="0" />
<param name="ShowTracker" value="0" />
<param name="EnablePositionControls" value="0" />
<!-- BEGIN PLUG-IN HTML FOR FIREFOX-->
<embed type="application/x-mplayer2" pluginspage="http://www.microsoft.com/Windows/MediaPlayer/"
src='<%= GetSource() %>' align="middle" width="600" height="500" defaultframe="rightFrame"
id="MediaPlayer2" />
And in JavaScript,
function playVideo() {
try{
if(-1 != navigator.userAgent.indexOf("MSIE"))
{
var obj = document.getElementById("MediaPlayer1");
obj.Play();
}
else
{
var player = document.getElementById("MediaPlayer2");
player.controls.play();
}
}
catch(error) {
alert(error)
}
}
The grep utility is not needed. Awk can do it all:
netstat -rn | awk '/default/ {print $2}'
192.168.128.1
Note that if you have something like Parallels (or a VPN, or both) running, you may see two or more default routing entries - it will be true if you use the 'grep' suggestion above, too.
netstat -rn | awk '/default/ {print $2}'
192.168.128.1
link#12
and
netstat -rn | awk '/default/ {print $2}'
utun1
192.168.128.1
link#12
To set a variable (_default) for further use (assuming only one entry for 'default') .....
_default=$( netstat -rn inet | awk '/default/ {print $2}' ) # I prefer $( ... ) over back-ticks
In the case of multiple default routes use:
netstat -rn | awk '/default/ {if ( index($6, "en") > 0 ){print $2} }'
192.168.128.1
These examples tested in Mavericks Terminal.app and are specific to OSX only. For example, other *nix versions frequently use 'eth' for ethernet/wireless connections, not 'en'. This is also only tested with ksh. Other shells may need a slightly different syntax.
Create a new branch using the svn copy
command as follows:
$ svn copy svn+ssh://host.example.com/repos/project/trunk \
svn+ssh://host.example.com/repos/project/branches/NAME_OF_BRANCH \
-m "Creating a branch of project"
exec sp_lock
This query should give you existing locks.
exec sp_who SPID -- will give you some info
Having spids, you could check activity monitor(processes tab) to find out what processes are locking the tables ("details" for more info and "kill process" to kill it).
The op mentions in the comments that he wants to keep the decimal place. This can be done with the re.sub method (as per the second and IMHO best answer) by explicitly listing the characters to keep e.g.
>>> re.sub("[^0123456789\.]","","poo123.4and5fish")
'123.45'
Select Req_ID, sum(R1+R2+R3+R4+R5)/5 as Average
from Request
Group by Req_ID;
The Request Payload - or to be more precise: payload body of a HTTP Request
- is the data normally send by a POST or PUT Request.
It's the part after the headers and the CRLF
of a HTTP Request.
A request with Content-Type: application/json
may look like this:
POST /some-path HTTP/1.1
Content-Type: application/json
{ "foo" : "bar", "name" : "John" }
If you submit this per AJAX the browser simply shows you what it is submitting as payload body. That’s all it can do because it has no idea where the data is coming from.
If you submit a HTML-Form with method="POST"
and Content-Type: application/x-www-form-urlencoded
or Content-Type: multipart/form-data
your request may look like this:
POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded
foo=bar&name=John
In this case the form-data is the request payload. Here the Browser knows more: it knows that bar is the value of the input-field foo of the submitted form. And that’s what it is showing to you.
So, they differ in the Content-Type
but not in the way data is submitted. In both cases the data is in the message-body. And Chrome distinguishes how the data is presented to you in the Developer Tools.
As paxdiablo said make -f pax.mk
would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.
Also you can just type make
if your file name is makefile/Makefile
.
Suppose you have two files named makefile
and Makefile
in the same directory then makefile
is executed if make
alone is given. You can even pass arguments to makefile.
Check out more about makefile at this Tutorial : Basic understanding of Makefile
I don't know how was the plugin the time the question was asked (2010), but I faced the same problem today and solved it this way:
Give your select tag a name attribute. For example in this case
<select name="myselect">
Instead of working with the attribute value="default" in the tag option, disable the default option or set value="" as suggested by Andrew Coats
<option disabled="disabled">Choose...</option>
or
<option value="">Choose...</option>
Set the plugin validation rule
$( "#YOUR_FORM_ID" ).validate({
rules: {
myselect: { required: true }
}
});
or
<select name="myselect" class="required">
Obs: Andrew Coats' solution works only if you have just one select in your form. If you want his solution to work with more than one select add a name attribute to your select.
Hope it helps! :)
If you are looking at a Table, a Pivot Table, or something with conditional formatting, you can try:
ActiveCell.DisplayFormat.Interior.Color
This also seems to work just fine on regular cells.
And this is how to inject set in some property in Spring:
<bean id="process"
class="biz.bsoft.processing">
<property name="stages">
<set value-type="biz.bsoft.AbstractStage">
<ref bean="stageReady"/>
<ref bean="stageSteady"/>
<ref bean="stageGo"/>
</set>
</property>
</bean>
The package it-self is located under /data/app/com.company.appname-xxx.apk
.
/data/app/com.company.appname
is only a directory created to store files like native libs, cache, ecc...
You can retrieve the package installation path with the Context.getPackageCodePath()
function call.
You're probably talking about unobtrusive Javascript, which would look like this:
<a href="#" id="someLink">link</a>
with the logic in a central javascript file looking something like this:
$('#someLink').click(function(){
popup('/map/', 300, 300, 'map');
return false;
});
The advantages are
Tools > Manage Add-ons, right click "Name" header and enable the "In Folder" section. go to the directory for the plugin you're interested in. Right click the plugin file, and click "remove".
To auto indent on Sublime text 3 with a key bind try going to
Preferences > Key Bindings - users
And adding this code between the square brackets
{"keys": ["alt+shift+f"], "command": "reindent", "args": {"single_line": false}}
it sets shift + alt + f to be your full page auto indent.
Source here
Note: if this doesn't work correctly then you should convert your indentation to tabs. Also comments in your code can push your code to the wrong indentation level and may have to be moved manually.
Okay, twice just today I've seen people wanting a closer equivalent for hg grep
, which is like git log -pS
but confines its output to just the (annotated) changed lines.
Which I suppose would be handier than /pattern/
in the pager if you're after a quick overview.
So here's a diff-hunk scanner that takes git log --pretty=%h -p
output and spits annotated change lines. Put it in diffmarkup.l
, say e.g. make ~/bin/diffmarkup
, and use it like
git log --pretty=%h -pS pattern | diffmarkup | grep pattern
%option main 8bit nodefault
// vim: tw=0
%top{
#define _GNU_SOURCE 1
}
%x commitheader
%x diffheader
%x hunk
%%
char *afile=0, *bfile=0, *commit=0;
int aline,aremain,bline,bremain;
int iline=1;
<hunk>\n ++iline; if ((aremain+bremain)==0) BEGIN diffheader;
<*>\n ++iline;
<INITIAL,commitheader,diffheader>^diff.* BEGIN diffheader;
<INITIAL>.* BEGIN commitheader; if(commit)free(commit); commit=strdup(yytext);
<commitheader>.*
<diffheader>^(deleted|new|index)" ".* {}
<diffheader>^"---".* if (afile)free(afile); afile=strdup(strchrnul(yytext,'/'));
<diffheader>^"+++".* if (bfile)free(bfile); bfile=strdup(strchrnul(yytext,'/'));
<diffheader,hunk>^"@@ ".* {
BEGIN hunk; char *next=yytext+3;
#define checkread(format,number) { int span; if ( !sscanf(next,format"%n",&number,&span) ) goto lostinhunkheader; next+=span; }
checkread(" -%d",aline); if ( *next == ',' ) checkread(",%d",aremain) else aremain=1;
checkread(" +%d",bline); if ( *next == ',' ) checkread(",%d",bremain) else bremain=1;
break;
lostinhunkheader: fprintf(stderr,"Lost at line %d, can't parse hunk header '%s'.\n",iline,yytext), exit(1);
}
<diffheader>. yyless(0); BEGIN INITIAL;
<hunk>^"+".* printf("%s:%s:%d:%c:%s\n",commit,bfile+1,bline++,*yytext,yytext+1); --bremain;
<hunk>^"-".* printf("%s:%s:%d:%c:%s\n",commit,afile+1,aline++,*yytext,yytext+1); --aremain;
<hunk>^" ".* ++aline, ++bline; --aremain; --bremain;
<hunk>. fprintf(stderr,"Lost at line %d, Can't parse hunk.\n",iline), exit(1);
I understand this is an older question, but I would like to add another disadvantage of Single Page Applications:
If you build an API that returns results in a data language (such as XML or JSON) rather than a formatting language (like HTML), you are enabling greater application interoperability, for example, in business-to-business (B2B) applications. Such interoperability has great benefits but does allow people to write software to "mine" (or steal) your data. This particular disadvantage is common to all APIs that use a data language, and not to SPAs in general (indeed, an SPA that asks the server for pre-rendered HTML avoids this, but at the expense of poor model/view separation). This risk exposed by this disadvantage can be mitigated by various means, such as request limiting and connection blocking, etc.
Separate with commas:
http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505
Either way, your method signature needs to be:
@RequestMapping(value = "/GetJson", method = RequestMethod.GET)
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
//code to get results from db for those params.
}
.boundingbox {
width: 400px;
height: 500px;
border: 2px solid #F63;
}
img{
width:400px;
max-height: 500px;
height:auto;
}
I'm editing my answer to further explain my soluton as I've got a down vote.
With the styles set as shown above in css, now the following html div will show the image always fit width wise and will adjust hight aspect ratio to width. Thus image will scale to fit a bounding box as asked in the question.
<div class="boundingbox"><img src="image.jpg"/></div>
Also, every link clicked with a target value of _new will replace the page loaded in the previously spawned window.
You can click here When to use _blank or _new to try it out for yourself.
A production quality program should use one of the many logging alternatives (e.g. log4j, logback, java.util.logging) to report errors and other diagnostics. This has a number of advantages:
By contrast, if you just use printStackTrace, the deployer / end user has little if any control, and logging messages are liable to either be lost or shown to the end user in inappropriate circumstances. (And nothing terrifies a timid user more than a random stack trace.)
Deploy the app as exploded (project.war folder), add in your web.xml:
<web-app>
<context-param>
<param-name>org.jboss.weld.development</param-name>
<param-value>true</param-value>
</context-param>
Update the web.xml time every-time you deploy (append blank line):
set PRJ_HOME=C:\Temp2\MyProject\src\main\webapp
set PRJ_CLSS_HOME=%PRJ_HOME%\WEB-INF\classes\com\myProject
set JBOSS_HOME= C:\Java\jboss-4.2.3.GA-jdk6\server\default\deploy\MyProject.war
set JBOSS_CLSS_HOME= %JBOSS_HOME%\WEB-INF\classes\com\myProject
copy %PRJ_CLSS_HOME%\frontend\actions\profile\ProfileAction.class %JBOSS_CLSS_HOME%\frontend\actions\profile\ProfileAction.class
copy %PRJ_CLSS_HOME%\frontend\actions\profile\AjaxAction.class %JBOSS_CLSS_HOME%\frontend\actions\profile\AjaxAction.class
ECHO.>>%JBOSS_HOME%\WEB-INF\web.xml
For now, it seems that I could get over that by adding a ?
after the URL.
This is how I write my AsyncTask
the key point is add Thread.sleep(1);
@Override protected Integer doInBackground(String... params) {
Log.d(TAG, PRE + "url:" + params[0]);
Log.d(TAG, PRE + "file name:" + params[1]);
downloadPath = params[1];
int returnCode = SUCCESS;
FileOutputStream fos = null;
try {
URL url = new URL(params[0]);
File file = new File(params[1]);
fos = new FileOutputStream(file);
long startTime = System.currentTimeMillis();
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
byte[] data = new byte[10240];
int nFinishSize = 0;
while( bis.read(data, 0, 10240) != -1){
fos.write(data, 0, 10240);
nFinishSize += 10240;
**Thread.sleep( 1 ); // this make cancel method work**
this.publishProgress(nFinishSize);
}
data = null;
Log.d(TAG, "download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d(TAG, PRE + "Error: " + e);
returnCode = FAIL;
} catch (Exception e){
e.printStackTrace();
} finally{
try {
if(fos != null)
fos.close();
} catch (IOException e) {
Log.d(TAG, PRE + "Error: " + e);
e.printStackTrace();
}
}
return returnCode;
}
I will try to answer the question of "why". Imagine a situation where you have a huge database with a lot of columns in a table, and your project/system uses tools to generate entities from database. (Hibernate has those, etc...) Now, suppose that by your business logic you need a particular field NOT to be persisted. You have to "configure" your entity in a particular way. While Transient keyword works on an object - as it behaves within a java language, the @Transient only designed to answer the tasks that pertains only to persistence tasks.
In case of JBoss... right click on project ? Build Java path ? add external JAR files.
Then browse to jboss-folder ? Common ? lib ? servlet-api.jar
. . Click OK, refresh the project, and run it...
A better approach is to store the old value using .data. This spares the creation of a global var which you should stay away from and keeps the information encapsulated within the element. A real world example as to why Global Vars are bad is documented here
e.g
<script>
//look no global needed:)
$(document).ready(function(){
// Get the initial value
var $el = $('#myInputElement');
$el.data('oldVal', $el.val() );
$el.change(function(){
//store new value
var $this = $(this);
var newValue = $this.data('newVal', $this.val());
})
.focus(function(){
// Get the value when input gains focus
var oldValue = $(this).data('oldVal');
});
});
</script>
<input id="myInputElement" type="text">
Try like this.
var hostname = window.location.origin
If the URL is "http://example.com/path" then you will get "http://example.com" as the result.
This won't work for local domains
When you have URL like "https://localhost/MyProposal/MyDir/MyTestPage.aspx"
and your virtual directory path is "https://localhost/MyProposal/"
In such cases, you will get "https://localhost".
The jsoncons C++ header-only library also supports conversion between JSON text and C++ objects. Decode and encode are defined for all C++ classes that have json_type_traits defined. The standard library containers are already supported, and json_type_traits can be specialized for user types in the jsoncons namespace.
Below is an example:
#include <iostream>
#include <jsoncons/json.hpp>
namespace ns {
enum class hiking_experience {beginner,intermediate,advanced};
class hiking_reputon
{
std::string rater_;
hiking_experience assertion_;
std::string rated_;
double rating_;
public:
hiking_reputon(const std::string& rater,
hiking_experience assertion,
const std::string& rated,
double rating)
: rater_(rater), assertion_(assertion), rated_(rated), rating_(rating)
{
}
const std::string& rater() const {return rater_;}
hiking_experience assertion() const {return assertion_;}
const std::string& rated() const {return rated_;}
double rating() const {return rating_;}
};
class hiking_reputation
{
std::string application_;
std::vector<hiking_reputon> reputons_;
public:
hiking_reputation(const std::string& application,
const std::vector<hiking_reputon>& reputons)
: application_(application),
reputons_(reputons)
{}
const std::string& application() const { return application_;}
const std::vector<hiking_reputon>& reputons() const { return reputons_;}
};
} // namespace ns
// Declare the traits using convenience macros. Specify which data members need to be serialized.
JSONCONS_ENUM_TRAITS_DECL(ns::hiking_experience, beginner, intermediate, advanced)
JSONCONS_ALL_CTOR_GETTER_TRAITS(ns::hiking_reputon, rater, assertion, rated, rating)
JSONCONS_ALL_CTOR_GETTER_TRAITS(ns::hiking_reputation, application, reputons)
using namespace jsoncons; // for convenience
int main()
{
std::string data = R"(
{
"application": "hiking",
"reputons": [
{
"rater": "HikingAsylum",
"assertion": "advanced",
"rated": "Marilyn C",
"rating": 0.90
}
]
}
)";
// Decode the string of data into a c++ structure
ns::hiking_reputation v = decode_json<ns::hiking_reputation>(data);
// Iterate over reputons array value
std::cout << "(1)\n";
for (const auto& item : v.reputons())
{
std::cout << item.rated() << ", " << item.rating() << "\n";
}
// Encode the c++ structure into a string
std::string s;
encode_json<ns::hiking_reputation>(v, s, indenting::indent);
std::cout << "(2)\n";
std::cout << s << "\n";
}
Output:
(1)
Marilyn C, 0.9
(2)
{
"application": "hiking",
"reputons": [
{
"assertion": "advanced",
"rated": "Marilyn C",
"rater": "HikingAsylum",
"rating": 0.9
}
]
}
There are 2 solutions for this, but it return all columns separately:
import functools
dfs = [df1, df2, df3]
df_final = functools.reduce(lambda left,right: pd.merge(left,right,on='date'), dfs)
print (df_final)
date a_x b_x a_y b_y c_x a b c_y
0 May 15,2017 900.00 0.2% 1,900.00 1000000 0.2% 2,900.00 2000000 0.2%
k = np.arange(len(dfs)).astype(str)
df = pd.concat([x.set_index('date') for x in dfs], axis=1, join='inner', keys=k)
df.columns = df.columns.map('_'.join)
print (df)
0_a 0_b 1_a 1_b 1_c 2_a 2_b 2_c
date
May 15,2017 900.00 0.2% 1,900.00 1000000 0.2% 2,900.00 2000000 0.2%
To find all types in an assembly that implement IFoo interface:
var results = from type in someAssembly.GetTypes()
where typeof(IFoo).IsAssignableFrom(type)
select type;
Note that Ryan Rinaldi's suggestion was incorrect. It will return 0 types. You cannot write
where type is IFoo
because type is a System.Type instance, and will never be of type IFoo. Instead, you check to see if IFoo is assignable from the type. That will get your expected results.
Also, Adam Wright's suggestion, which is currently marked as the answer, is incorrect as well, and for the same reason. At runtime, you'll see 0 types come back, because all System.Type instances weren't IFoo implementors.
You can checkout Angular UI @ http://angular-ui.github.io/ui-utils/ which provide details event handle callback function for detecting keydown,keyup,keypress (also Enter key, backspace key, alter key ,control key)
<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
<textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>
Wrapping it with div should work. I tested it in Firefox, Chrome on Fedora 13 (demo).
#content {
width: 95%;
height: 95%;
margin: auto;
}
#myCanvas {
width: 100%;
height: 100%;
border: 1px solid black;
}
And the canvas should be enclosed in tag
<div id="content">
<canvas id="myCanvas">Your browser doesn't support canvas tag</canvas>
</div>
Let me know if it works. Cheers.
Or a nested List (okay, the OP was for a single column and this is for multiple columns..):
//Base list is a list of fields, ie a data record
//Enclosing list is then a list of those records, ie the Result set
List<List<String>> ResultSet = new List<List<String>>();
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(qString, connection);
// Create and execute the DataReader..
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var rec = new List<string>();
for (int i = 0; i <= reader.FieldCount-1; i++) //The mathematical formula for reading the next fields must be <=
{
rec.Add(reader.GetString(i));
}
ResultSet.Add(rec);
}
}