Probably the new PyCharm from the makers of IntelliJ and ReSharper.
When ntsd access is denied, try:
ZeroWave was designed to be a simple tool that will provide a multilevel termination of any kind of process.
ZeroWave is also a easy-to-use program due to its simple installation and its very friendly graphical interface.
ZeroWave has three termination modes and with the "INSANE" mode can terminate any kind of process that can run on Windows.
It seems that ZeroWave can't kill avp.exe
You have a few options:
Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms.
Read the submit button values from the POST data. You can tell which submit button was clicked: How can I build multiple submit buttons django form?
This is it guys! FIXED!
Wait and see: https://bugzilla.mozilla.org/show_bug.cgi?id=649849
or workaround
For those wondering:
https://bugzilla.mozilla.org/show_bug.cgi?id=649849#c59
First, because the bug has a lot of hostile spam in it, it creates a hostile workplace for anyone who gets assigned to this.
Secondly, the person who has the ability to do this (which includes rewriting ) has been allocated to another project (b2g) for the time being and wont have time until that project get nearer to completion.
Third, even when that person has the time again, there is no guarantee that this will be a priority because, despite webkit having this, it breaks the spec for how is supposed to work (This is what I was told, I do not personally know the spec)
Now see https://wiki.mozilla.org/B2G/Schedule_Roadmap ;)
The page no longer exists and the bug hasn't be fixed but an acceptable workaround came from João Cunha, you guys can thank him for now!
Use a loop
for(var i = 0; i < obj.length; ++i){
//do something with obj[i]
for(var ind in obj[i]) {
console.log(ind);
for(var vals in obj[i][ind]){
console.log(vals, obj[i][ind][vals]);
}
}
}
Most of these answers use sp_executesql as the solution to this problem. I have found that there are some limitations when using sp_executesql, which I will not go into, but I wanted to offer an alternative using EXEC(). I am using SQL Server 2008 and I know that some of the objects I am using in this script are not available in earlier versions of SQL Server so be wary.
DECLARE @CountResults TABLE (CountReturned INT)
DECLARE
@SqlStatement VARCHAR(8000) = 'SELECT COUNT(*) FROM table'
, @Count INT
INSERT @CountResults
EXEC(@SqlStatement)
SET @Count = (SELECT CountReturned FROM @CountResults)
SELECT @Count
Solution #1: Your statement
.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does not refer to a proper Range
to act upon. Instead,
.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does (and similarly in some other cases).
Solution #2:
Activate Worksheets("Cable Cards")
prior to using its cells.
Explanation:
Cells(RangeStartRow, RangeStartColumn)
(e.g.) gives you a Range
, that would be ok, and that is why you often see Cells
used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet
. Thus, your code attempts using .Range(rng1, rng2)
, where .Range
is a method of one Worksheet
object and rng1
and rng2
are in a different Worksheet
.
There are two checks that you can do to make this quite evident:
Activate your Worksheets("Cable Cards")
prior to executing your Sub
and it will start working (now you have well-formed references to Range
s). For the code you posted, adding .Activate
right after With...
would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range
in another Worksheet
.
With a sheet other than Worksheets("Cable Cards")
active, set a breakpoint at the line throwing the error, start your Sub
, and when execution breaks, write at the immediate window
Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
and see the different outcomes.
Conclusion:
Using Cells
or Range
without a specified object (e.g., Worksheet
, or Range
) might be dangerous, especially when working with more than one Sheet
, unless one is quite sure about what Sheet
is active.
The following definition might be more efficient than the first solution proposed
def new_list_from_intervals(original_list, *intervals):
n = sum(j - i for i, j in intervals)
new_list = [None] * n
index = 0
for i, j in intervals :
for k in range(i, j) :
new_list[index] = original_list[k]
index += 1
return new_list
then you can use it like below
new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))
You can use jQuery .getJSON()
function:
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback', function(data) {
// JSON result in `data` variable
});
If you don't want to use jQuery you should look at this answer for pure JS solution: https://stackoverflow.com/a/2499647/1361042
If efficiency is an issue and you have to build multiple different n-grams (up to a hundred as you say), but you want to use pure python I would do:
from itertools import chain
def n_grams(seq, n=1):
"""Returns an itirator over the n-grams given a listTokens"""
shiftToken = lambda i: (el for j,el in enumerate(seq) if j>=i)
shiftedTokens = (shiftToken(i) for i in range(n))
tupleNGrams = zip(*shiftedTokens)
return tupleNGrams # if join in generator : (" ".join(i) for i in tupleNGrams)
def range_ngrams(listTokens, ngramRange=(1,2)):
"""Returns an itirator over all n-grams for n in range(ngramRange) given a listTokens."""
return chain(*(n_grams(listTokens, i) for i in range(*ngramRange)))
Usage :
>>> input_list = input_list = 'test the ngrams generator'.split()
>>> list(range_ngrams(input_list, ngramRange=(1,3)))
[('test',), ('the',), ('ngrams',), ('generator',), ('test', 'the'), ('the', 'ngrams'), ('ngrams', 'generator'), ('test', 'the', 'ngrams'), ('the', 'ngrams', 'generator')]
~Same speed as NLTK:
import nltk
%%timeit
input_list = 'test the ngrams interator vs nltk '*10**6
nltk.ngrams(input_list,n=5)
# 7.02 ms ± 79 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%%timeit
input_list = 'test the ngrams interator vs nltk '*10**6
n_grams(input_list,n=5)
# 7.01 ms ± 103 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%%timeit
input_list = 'test the ngrams interator vs nltk '*10**6
nltk.ngrams(input_list,n=1)
nltk.ngrams(input_list,n=2)
nltk.ngrams(input_list,n=3)
nltk.ngrams(input_list,n=4)
nltk.ngrams(input_list,n=5)
# 7.32 ms ± 241 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%%timeit
input_list = 'test the ngrams interator vs nltk '*10**6
range_ngrams(input_list, ngramRange=(1,6))
# 7.13 ms ± 165 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Repost from my previous answer.
Callee vs caller saved is a convention for who is responsible for saving and restoring the value in a register across a call. ALL registers are "global" in that any code anywhere can see (or modify) a register and those modifications will be seen by any later code anywhere. The point of register saving conventions is that code is not supposed to modify certain registers, as other code assumes that the value is not modified.
In your example code, NONE of the registers are callee save, as it makes no attempt to save or restore the register values. However, it would seem to not be an entire procedure, as it contains a branch to an undefined label (l$loop
). So it might be a fragment of code from the middle of a procedure that treats some registers as callee save; you're just missing the save/restore instructions.
As of lodash 3.5.0 you can use sortByOrder (renamed orderBy in v4.3.0):
var data = _.sortByOrder(array_of_objects, ['type','name'], [true, false]);
Since version 3.10.0 you can even use standard semantics for ordering (asc, desc):
var data = _.sortByOrder(array_of_objects, ['type','name'], ['asc', 'desc']);
In version 4 of lodash this method has been renamed orderBy:
var data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']);
They are the same thing.
Acceptance testing is performed on the completed system in as identical as possible to the real production/deployement environment before the system is deployed or delivered.
You can do acceptance testing in an automated manner, or manually.
@Garret Wilson Thank you so much! As a noob to android coding, I've been stuck with the preferences incompatibility issue for so many hours, and I find it so disappointing they deprecated the use of some methods/approaches for new ones that aren't supported by the older APIs thus having to resort to all sorts of workarounds to make your app work in a wide range of devices. It's really frustrating!
Your class is great, for it allows you to keep working in new APIs wih preferences the way it used to be, but it's not backward compatible. Since I'm trying to reach a wide range of devices I tinkered with it a bit to make it work in pre API 11 devices as well as in newer APIs:
import android.annotation.TargetApi;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
public class MyPrefsActivity extends PreferenceActivity
{
private static int prefs=R.xml.myprefs;
@Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try {
getClass().getMethod("getFragmentManager");
AddResourceApi11AndGreater();
} catch (NoSuchMethodException e) { //Api < 11
AddResourceApiLessThan11();
}
}
@SuppressWarnings("deprecation")
protected void AddResourceApiLessThan11()
{
addPreferencesFromResource(prefs);
}
@TargetApi(11)
protected void AddResourceApi11AndGreater()
{
getFragmentManager().beginTransaction().replace(android.R.id.content,
new PF()).commit();
}
@TargetApi(11)
public static class PF extends PreferenceFragment
{
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(MyPrefsActivity.prefs); //outer class
// private members seem to be visible for inner class, and
// making it static made things so much easier
}
}
}
Tested in two emulators (2.2 and 4.2) with success.
Why my code looks so crappy:
I'm a noob to android coding, and I'm not the greatest java fan.
In order to avoid the deprecated warning and to force Eclipse to allow me to compile I had to resort to annotations, but these seem to affect only classes or methods, so I had to move the code onto two new methods to take advantage of this.
I wouldn't like having to write my xml resource id twice anytime I copy&paste the class for a new PreferenceActivity, so I created a new variable to store this value.
I hope this will be useful to somebody else.
P.S.: Sorry for my opinionated views, but when you come new and find such handicaps, you can't help it but to get frustrated!
Please note that this only work with python 2.x
You should try using the PyTTSx package since PyTTS is outdated. PyTTSx works with the lastest python version.
http://pypi.python.org/pypi/pyttsx/1.0 -> The package
Hope it helps
rm .git/refs/remotes/origin/master
It works to me!
I have been toying with this idea too, but I was trying to achieve a slightly different behavior. My idea was to make a list which inherits itself, thus creating a data structure that by nature allows you to embed lists within lists within lists within lists...infinitely!
Implementation
//InfiniteList<T> is a list of itself...
public class InfiniteList<T> : List<InfiniteList<T>>
{
//This is necessary to allow your lists to store values (of type T).
public T Value { set; get; }
}
T is a generic type parameter. It is there to ensure type safety in your class. When you create an instance of InfiniteList, you replace T with the type you want your list to be populated with, or in this instance, the type of the Value property.
Example
//The InfiniteList.Value property will be of type string
InfiniteList<string> list = new InfiniteList<string>();
A "working" example of this, where T is in itself, a List of type string!
//Create an instance of InfiniteList where T is List<string>
InfiniteList<List<string>> list = new InfiniteList<List<string>>();
//Add a new instance of InfiniteList<List<string>> to "list" instance.
list.Add(new InfiniteList<List<string>>());
//access the first element of "list". Access the Value property, and add a new string to it.
list[0].Value.Add("Hello World");
Let's say we have a menu like this:
<div class="menu">
<a href="link1.html">Link 1</a>
<a href="link2.html">Link 2</a>
<a href="link3.html">Link 3</a>
<a href="link4.html">Link 4</a>
</div>
Let our current url be https://demosite.com/link1.html
With the following function we can add the active class to which menu's href is in our url.
let currentURL = window.location.href;
document.querySelectorAll(".menu a").forEach(p => {
if(currentURL.indexOf(p.getAttribute("href")) !== -1){
p.classList.add("active");
}
})
I resolved this by adding following code to the HTML page, since we are using the third party API which is not controlled by us.
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
Hope this would help, and for a record as well.
normed_matrix = normalize(input_data, axis=1, norm='l1')
print(normed_matrix)
where input_data is the name of your 2D array
The FOR loop worked well, I modified it a tiny bit:
#include<iostream>
using namespace std;
int main ()
{
int sum = 0;
int number;
int numberitems;
cout << "Enter number of items: \n";
cin >> numberitems;
for(int i=0;i<numberitems;i++)
{
cout << "Enter number: \n";
cin >> number;
sum=sum+number;
}
cout<<"sum is: "<< sum<<endl;
}
HOWEVER, the WHILE loop has got some errors on line 11 (Count was not declared in this scope). What could be the issue? Also, if you would have a solution using DO,WHILE loop it would be wonderful. Thanks
If you are using form control then the simplest way to do this:
this.FormName.get('ControlName').setValue(value);
Yes, you can store any object (I assume you are using ASP.NET with default settings, which is in-process session state):
Session["test"] = myList;
You should cast it back to the original type for use:
var list = (List<int>)Session["test"];
// list.Add(something);
As Richard points out, you should take extra care if you are using other session state modes (e.g. SQL Server) that require objects to be serializable.
Sometimes it doesn't get login with username = root
and password
, then you can change the default settings or the reset settings.
Open config.inc.php
file in the phpmyadmin folder
Instead of
$cfg['Servers'][$i]['AllowNoPassword'] = false;
change it to:
$cfg['Servers'][$i]['AllowNoPassword'] = true;
Do not specify any password and put the user name as it was before, which means root
.
E.g.
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
This worked for me after i had edited my config.inc.php
file.
Swift 5
extension String {
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString(
data: data,
options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
documentAttributes: nil) else { return nil }
return html
}
}
Call:
myLabel.attributedText = "myString".htmlAttributedString()
While both of the answers above are good, the procedure for extracting parts of objects is more general.
In many cases, functions return lists, and the individual components can be accessed using str()
which will print the components along with their names. You can then access them using the $ operator, i.e. myobject$componentname
.
In the case of lm objects, there are a number of predefined methods one can use such as coef()
, resid()
, summary()
etc, but you won't always be so lucky.
Try this:
<html>
<table>
<tr>
<td style="padding-left: 5px;
padding-bottom: 3px;">
<strong style="font-size: 35px;">Datum:</strong><br />
November 2010
</td>
</tr>
</table>
</html>
Notice that I also included the table-tag, which you seem to have forgotten. This has to be included if you want this to appear as a table.
I did the test using java 8 It wont matter the order the builder always takes 0 milliseconds and the concat between 26 and 33 milliseconds under and iteration of a 1000 concatenation
Hope it helps try it with your ide
public void count() {
String result = "";
StringBuilder builder = new StringBuilder();
long millis1 = System.currentTimeMillis(),
millis2;
for (int i = 0; i < 1000; i++) {
builder.append("hello world this is the concat vs builder test enjoy");
}
millis2 = System.currentTimeMillis();
System.out.println("Diff: " + (millis2 - millis1));
millis1 = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
result += "hello world this is the concat vs builder test enjoy";
}
millis2 = System.currentTimeMillis();
System.out.println("Diff: " + (millis2 - millis1));
}
Simple and fast since a 1d array is essentially a vector
vector <- array[1:length(array)]
The following code works only if the minimum value is 1
. It does not work for minimum values other than 1
.
If you wanted to get a random integer between 1 (and only 1) and 6, you would calculate:
Math.floor(Math.random() * 6) + 1
Where:
Just remove the .value
, like this:
function(arrayP){
for(var i = 0; i < arrayP.length; i++){
alert(arrayP[i]); //no .value here
}
}
Sure you can pass an array, but to get the element at that position, use only arrayName[index]
, the .value
would be getting the value
property off an object at that position in the array - which for things like strings, numbers, etc doesn't exist. For example, "myString".value
would also be undefined
.
You can use following formulas.
For Excel 2007 or later:
=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")
For Excel 2003:
=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))
Note, that
List!A:C
in VLOOKUP
and returns value from column ? 3
VLOOKUP
equals to FALSE
, in that case VLOOKUP
will only find an exact match, and the values in the first column of List!A:C
do not need to be sorted (opposite to case when you're using TRUE
).A shortcut for using a lambda with as a C function pointer is this:
"auto fun = +[](){}"
Using Curl as exmample (curl debug info)
auto callback = +[](CURL* handle, curl_infotype type, char* data, size_t size, void*){ //add code here :-) };
curl_easy_setopt(curlHande, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curlHande,CURLOPT_DEBUGFUNCTION,callback);
<button id="OpenImgUpload" onclick="$('#imgupload').trigger('click');">Image Upload</button>
<input type="file" id="imgupload" style="display:none"/>
Here is an alternate syntax I use:
INSERT INTO tab_student
SET name_student = 'Bobby Tables',
id_teacher_fk = (
SELECT id_teacher
FROM tab_teacher
WHERE name_teacher = 'Dr. Smith')
I'm doing this in Excel to import a pivot table to a dimension table and a fact table in SQL so you can import to both department
and expenses
tables from the following:
Luckily, MySQL supports LAST_INSERT_ID()
exactly for this purpose.
INSERT INTO tab_teacher
SET name_teacher = 'Dr. Smith';
INSERT INTO tab_student
SET name_student = 'Bobby Tables',
id_teacher_fk = LAST_INSERT_ID()
I just had the same issue, and spend about an hour trying to solve the problem. In the end it was a '#' character in the path.
So I renamed "C:\# IDE\eclipse 3.7\" to "C:\+ IDE\eclipse 3.7\" and that solved the problem.
In addition to Gusev Slava's answer, you might want to use groupby's groups:
{key: df.loc[value] for key, value in df.groupby("name").groups.items()}
This will yield a dictionary with the keys you have grouped by, pointing to the corresponding partitions. The advantage is that the keys are maintained and don't vanish in the list index.
If the dataset is called data, then all the rows meeting a condition where value of column 'pm2.5' > 300 can be received by -
data[data['pm2.5'] >300,]
Getting a cross-domain JSON with jQuery in Internet Explorer 8 and newer versions
Very useful link:
Can help with the trouble of returning json from a X Domain Request.
Hope this helps somebody.
Below is a long polling solution I have developed for Inform8 Web. Basically you override the class and implement the loadData method. When the loadData returns a value or the operation times out it will print the result and return.
If the processing of your script may take longer than 30 seconds you may need to alter the set_time_limit() call to something longer.
Apache 2.0 license. Latest version on github https://github.com/ryanhend/Inform8/blob/master/Inform8-web/src/config/lib/Inform8/longpoll/LongPoller.php
Ryan
abstract class LongPoller {
protected $sleepTime = 5;
protected $timeoutTime = 30;
function __construct() {
}
function setTimeout($timeout) {
$this->timeoutTime = $timeout;
}
function setSleep($sleep) {
$this->sleepTime = $sleepTime;
}
public function run() {
$data = NULL;
$timeout = 0;
set_time_limit($this->timeoutTime + $this->sleepTime + 15);
//Query database for data
while($data == NULL && $timeout < $this->timeoutTime) {
$data = $this->loadData();
if($data == NULL){
//No new orders, flush to notify php still alive
flush();
//Wait for new Messages
sleep($this->sleepTime);
$timeout += $this->sleepTime;
}else{
echo $data;
flush();
}
}
}
protected abstract function loadData();
}
This is an adding to @Sam answer that though is correct is missing the fact that anytime you open a folder in visual studio code, it create a .vscode folder, but those can be multiple, created any time you eventually open a directory. The .vscode folder has JSON objects that content properties such "setting.json", in which one declare the Interpreter to use at that ".vscode" level( refer to this for more clarifications What is a 'workspace' in VS Code?).
{
{
"python.pythonPath": "VirtualEnPath/bin/python3.6"
}
}
So potentially you could open VS code at another level in the virtual Env, it create another .vscode folder that assume as Python directory those of the global machine and so having such error, and has I experienced has nothing to do if the Virtual Env is activated or not.
This indeed what happened to me, I have indeed a DjangoRESTAPI_GEN folder in which I initially opened the IDE and it did recognize the Virtual Env Python path, the a few days after I opened it at the level where git is, so it did created another .vscode, that picked the global Python Interpreter, causing my lint in the Virtual Environment not been used, and the virtual env interpreter not even showed in "select python interpreter". But as wrote opening the IDE at the level where the .vscode that has the settings.json with correct path, it does.
Once you set the correct path in the setting.json and select the virtual env interpreter, then VS Code will automatically activate the VE in its terminal
i solved it using jquery
<script type="text/javascript">_x000D_
$(document).ready(function(e) {_x000D_
var h = $('nav').height() + 20;_x000D_
$('body').animate({ paddingTop: h });_x000D_
});_x000D_
</script>
_x000D_
Building off the accepted answer, a multi-dimensional array type, that is a fixed-length array of fixed-length arrays, can't be declared with
typedef char[M] T[N]; // wrong!
instead, the intermediate 1D array type can be declared and used as in the accepted answer:
typedef char T_t[M];
typedef T_t T[N];
or, T
can be declared in a single (arguably confusing) statement:
typedef char T[N][M];
which defines a type of N
arrays of M
chars (be careful about the order, here).
import java.util.HashMap;
public class Students {
String name;
int age;
Students(String name, int age ){
this.name = name;
this.age=age;
}
@Override
public int hashCode() {
System.out.println("__hash__");
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
System.out.println("__eq__");
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Students other = (Students) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public static void main(String[] args) {
Students S1 = new Students("taj",22);
Students S2 = new Students("taj",21);
System.out.println(S1.hashCode());
System.out.println(S2.hashCode());
HashMap<Students,String > HM = new HashMap<Students,String > ();
HM.put(S1, "tajinder");
HM.put(S2, "tajinder");
System.out.println(HM.size());
}
}
Output:
__ hash __
116232
__ hash __
116201
__ hash __
__ hash __
2
So here we see that if both the objects S1 and S2 have different content, then we are pretty sure that our overridden Hashcode method will generate different Hashcode(116232,11601) for both objects. NOW since there are different hash codes, so it won't even bother to call EQUALS method. Because a different Hashcode GUARANTEES DIFFERENT content in an object.
public static void main(String[] args) {
Students S1 = new Students("taj",21);
Students S2 = new Students("taj",21);
System.out.println(S1.hashCode());
System.out.println(S2.hashCode());
HashMap<Students,String > HM = new HashMap<Students,String > ();
HM.put(S1, "tajinder");
HM.put(S2, "tajinder");
System.out.println(HM.size());
}
}
Now lets change out main method a little bit. Output after this change is
__ hash __
116201
__ hash __
116201
__ hash __
__ hash __
__ eq __
1
We can clearly see that equal method is called. Here is print statement __eq__, since we have same hashcode, then content of objects MAY or MAY not be similar. So program internally calls Equal method to verify this.
Conclusion
If hashcode is different , equal method will not get called.
if hashcode is same, equal method will get called.
Thanks , hope it helps.
$self has little to do with $, which is an alias for jQuery in this case. Some people prefer to put a dollar sign together with the variable to make a distinction between regular vars and jQuery objects.
example:
var self = 'some string';
var $self = 'another string';
These are declared as two different variables. It's like putting underscore before private variables.
A somewhat popular pattern is:
var foo = 'some string';
var $foo = $('.foo');
That way, you know $foo is a cached jQuery object later on in the code.
The first answer is good for understanding how it works. But I wanted to understand how I should be using it in practice.
SUMMARY
class_weight="balanced"
works decent in the absence of you wanting to optimize manuallyclass_weight="balanced"
you capture more true events (higher TRUE recall) but also you are more likely to get false alerts (lower TRUE precision)
NB
The result might differ when using RF or GBM. sklearn does not have class_weight="balanced"
for GBM but lightgbm has LGBMClassifier(is_unbalance=False)
CODE
# scikit-learn==0.21.3
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, classification_report
import numpy as np
import pandas as pd
# case: moderate imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.8]) #,flip_y=0.1,class_sep=0.5)
np.mean(y) # 0.2
LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.184
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X).mean() # 0.296 => seems to make things worse?
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.292 => seems to make things worse?
roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.83
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X)) # 0.86 => about the same
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.86 => about the same
# case: strong imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.95])
np.mean(y) # 0.06
LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.02
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X).mean() # 0.25 => huh??
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.22 => huh??
(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).mean() # same as last
roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.64
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X)) # 0.84 => much better
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.85 => similar to manual
roc_auc_score(y,(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).astype(int)) # same as last
print(classification_report(y,LogisticRegression(C=1e9).fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True,normalize='index') # few prediced TRUE with only 28% TRUE recall and 86% TRUE precision so 6%*28%~=2%
print(classification_report(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True,normalize='index') # 88% TRUE recall but also lot of false positives with only 23% TRUE precision, making total predicted % TRUE > actual % TRUE
If the LINQ query is executed in database context, a call to Contains()
is mapped to the LIKE
operator:
.Where(a => a.Field.Contains("hello"))
becomes Field LIKE '%hello%'
. The LIKE
operator is case insensitive by default, but that can be changed by changing the collation of the column.
If the LINQ query is executed in .NET context, you can use IndexOf(), but that method is not supported in LINQ to SQL.
LINQ to SQL does not support methods that take a CultureInfo as parameter, probably because it can not guarantee that the SQL server handles cultures the same as .NET. This is not completely true, because it does support StartsWith(string, StringComparison)
.
However, it does not seem to support a method which evaluates to LIKE
in LINQ to SQL, and to a case insensitive comparison in .NET, making it impossible to do case insensitive Contains() in a consistent way.
One alternative would be to use a drawable/textview instead of a checkbox and manipulate it accordingly. I have used this method to have my own checked and unchecked images for a task application.
there is no actual overloading in JS, anyway we still can simulate method overloading in several ways:
method #1: use object
function test(x,options){
if("a" in options)doSomething();
else if("b" in options)doSomethingElse();
}
test("ok",{a:1});
test("ok",{b:"string"});
method #2: use rest (spread) parameters
function test(x,...p){
if(p[2])console.log("3 params passed"); //or if(typeof p[2]=="string")
else if (p[1])console.log("2 params passed");
else console.log("1 param passed");
}
method #3: use undefined
function test(x, y, z){
if(typeof(z)=="undefined")doSomething();
}
method #4: type checking
function test(x){
if(typeof(x)=="string")console.log("a string passed")
else ...
}
I found it easier to move the files into a separate Class Library project and then reference that project in the web project and apply the namespace in the using
section of the file.
For some reason the other solutions were not working for me, but this work around did.
Inside your lib file
Create a folder called colors
.
Inside the colors
folder create a dart file and name it color
.
Paste this code inside it
const MaterialColor primaryOrange = MaterialColor(
_orangePrimaryValue,
<int, Color>{
50: Color(0xFFFF9480),
100: Color(0xFFFF9480),
200: Color(0xFFFF9480),
300: Color(0xFFFF9480),
400: Color(0xFFFF9480),
500: Color(0xFFFF9480),
600: Color(0xFFFF9480),
700: Color(0xFFFF9480),
800: Color(0xFFFF9480),
900: Color(0xFFFF9480),
},
);
const int _orangePrimaryValue = 0xFFFF9480;
Go to your main.dart
file and place this code in your theme
theme:ThemeData(
primarySwatch: primaryOrange,
),
Import the color
folder in your main.dart
like this import 'colors/colors.dart'
;
I suggest to have array of buffers and concat to resulting buffer only once at the end. Its easy to do manually, or one could use node-buffers
There's little. From portability viewpoint, char
cannot be smaller than 8 bits, and nothing can be smaller than char
, so if a given C implementation has an unsigned 8-bit integer type, it's going to be char
. Alternatively, it may not have one at all, at which point any typedef
tricks are moot.
It could be used to better document your code in a sense that it's clear that you require 8-bit bytes there and nothing else. But in practice it's a reasonable expectation virtually anywhere already (there are DSP platforms on which it's not true, but chances of your code running there is slim, and you could just as well error out using a static assert at the top of your program on such a platform).
Based on Haim's answer here's a simplified example if you're looking to compare values that exist in BOTH tables, otherwise if there's a row in one table but not the other it will also return it....
Took me a couple of hours to figure out. Here's a fully tested simply query for comparing "tbl_a" and "tbl_b"
SELECT ID, col
FROM
(
SELECT
tbl_a.ID, tbl_a.col FROM tbl_a
UNION ALL
SELECT
tbl_b.ID, tbl_b.col FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
GROUP BY
ID, col
HAVING COUNT(*) = 1
ORDER BY ID
So you need to add the extra "where in" clause:
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
Also:
For ease of reading if you want to indicate the table names you can use the following:
SELECT tbl, ID, col
FROM
(
SELECT
tbl_a.ID, tbl_a.col, "name_to_display1" as "tbl" FROM tbl_a
UNION ALL
SELECT
tbl_b.ID, tbl_b.col, "name_to_display2" as "tbl" FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
GROUP BY
ID, col
HAVING COUNT(*) = 1
ORDER BY ID
I test this code and
$db=new PDO('mysql:host=localhost;dbname=cwDB','root','',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$sql="select * from products ";
$stmt=$db->prepare($sql);
$stmt->execute();
while($result=$stmt->fetch(PDO::FETCH_ASSOC)){
$id=$result['id'];
}
An easier solution with attributed string extension.
extension NSMutableAttributedString {
// this function attaches color to string
func setColorForText(textToFind: String, withColor color: UIColor) {
let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive)
self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
}
}
Try this and see (Tested in Swift 3 & 4)
let label = UILabel()
label.frame = CGRect(x: 120, y: 100, width: 200, height: 30)
let first = "first"
let second = "second"
let third = "third"
let stringValue = "\(first)\(second)\(third)" // or direct assign single string value like "firstsecondthird"
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColorForText(textToFind: first, withColor: UIColor.red) // use variable for string "first"
attributedString.setColorForText(textToFind: "second", withColor: UIColor.green) // or direct string like this "second"
attributedString.setColorForText(textToFind: third, withColor: UIColor.blue)
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString
self.view.addSubview(label)
Here is expected result:
PID is the process ID - not the port number. You need to look for an entry with ":8080" at the end of the address/port part (the second column). Then you can look at the PID and use Task Manager to work out which process is involved... or run netstat -abn
which will show the process names (but must be run under an administrator account).
Having said that, I would expect the find "8080"
to find it...
Another thing to do is just visit http://localhost:8080
- on that port, chances are it's a web server of some description.
In case you're dealing with <a>
tag, and you want to interrupt going to the default href
you should use this
instead.
Go to default url (yahoo):
<a href="https://yahoo.com" onclick="location.href='https://google.com';">
Go to new url (google) onclick
:
<a href="https://yahoo.com" onclick="this.href='https://google.com';">
By using this
you're interrupting the current browser onclick
event and changing href
before continuing to default behaviour of <a href='...
A POST with httpClient in Angular 6 was also doing an OPTIONS request:
Headers General:
Request URL:https://hp-probook/perl-bin/muziek.pl/=/postData Request Method:OPTIONS Status Code:200 OK Remote Address:127.0.0.1:443 Referrer Policy:no-referrer-when-downgrade
My Perl REST server implements the OPTIONS request with return code 200.
The next POST request Header:
Accept:*/* Accept-Encoding:gzip, deflate, br Accept-Language:nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4 Access-Control-Request-Headers:content-type Access-Control-Request-Method:POST Connection:keep-alive Host:hp-probook Origin:http://localhost:4200 Referer:http://localhost:4200/ User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36
Notice Access-Control-Request-Headers:content-type.
So, my backend perl script uses the following headers:
-"Access-Control-Allow-Origin" => '*', -"Access-Control-Allow-Methods" => 'GET,POST,PATCH,DELETE,PUT,OPTIONS', -"Access-Control-Allow-Headers" => 'Origin, Content-Type, X-Auth-Token, content-type',
With this setup the GET and POST worked for me!
Hope Below steps will help
Add the dependency to your project-level build.gradle:
classpath 'com.google.gms:google-services:3.0.0'
Add the plugin to your app-level build.gradle:
apply plugin: 'com.google.gms.google-services'
app-level build.gradle:
dependencies {
compile 'com.google.android.gms:play-services-auth:9.8.0'
}
With large arrays, print_r can show far more information than is useful. You can truncate it like this, showing the first 2000 characters or however many you need.
echo "<pre>" . substr(print_r($dataset, 1), 0, 2000) . "</pre>";
keeps things simple just add app:tabMode="scrollable" and android:layout_gravity= "bottom"
just like this
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="bottom"
app:tabMode="scrollable"
app:tabIndicatorColor="@color/colorAccent" />
By using css property --> display:table-cell
div {_x000D_
border: 1px solid #000;_x000D_
margin: 5px;_x000D_
padding: 4px;_x000D_
display:table-cell;_x000D_
width:25% ;position:relative;_x000D_
}_x000D_
body{display:table;_x000D_
border-collapse:separate;_x000D_
border-spacing:5px 5px}
_x000D_
<div>_x000D_
This is my div one This is my div one This is my div one_x000D_
</div>_x000D_
<div>_x000D_
This is my div two This is my div two This is my div two This is my div two This is my div two This is my div two_x000D_
</div>_x000D_
<div>_x000D_
This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3_x000D_
</div>
_x000D_
Here's how you can get the surrounding dimentions:
var elem = $('#myId');
var marginTopBottom = elem.outerHeight(true) - elem.outerHeight();
var marginLeftRight = elem.outerWidth(true) - elem.outerWidth();
var borderTopBottom = elem.outerHeight() - elem.innerHeight();
var borderLeftRight = elem.outerWidth() - elem.innerWidth();
var paddingTopBottom = elem.innerHeight() - elem.height();
var paddingLeftRight = elem.innerWidth() - elem.width();
Pay attention that each variable, paddingTopBottom
for example, contains the sum of the margins on the both sides of the element; i.e., paddingTopBottom == paddingTop + paddingBottom
. I wonder if there is a way to get them separately. Of course, if they are equal you can divide by 2 :)
There are a bunch of resources out there:
Plugins with ThemeRoller support:
UPDATE: Here is something I put together that will style the table:
<script type="text/javascript">
(function ($) {
$.fn.styleTable = function (options) {
var defaults = {
css: 'styleTable'
};
options = $.extend(defaults, options);
return this.each(function () {
input = $(this);
input.addClass(options.css);
input.find("tr").live('mouseover mouseout', function (event) {
if (event.type == 'mouseover') {
$(this).children("td").addClass("ui-state-hover");
} else {
$(this).children("td").removeClass("ui-state-hover");
}
});
input.find("th").addClass("ui-state-default");
input.find("td").addClass("ui-widget-content");
input.find("tr").each(function () {
$(this).children("td:not(:first)").addClass("first");
$(this).children("th:not(:first)").addClass("first");
});
});
};
})(jQuery);
$(document).ready(function () {
$("#Table1").styleTable();
});
</script>
<table id="Table1" class="full">
<tr>
<th>one</th>
<th>two</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
The CSS:
.styleTable { border-collapse: separate; }
.styleTable TD { font-weight: normal !important; padding: .4em; border-top-width: 0px !important; }
.styleTable TH { text-align: center; padding: .8em .4em; }
.styleTable TD.first, .styleTable TH.first { border-left-width: 0px !important; }
I could not get the accepted answer to work, but as per the current WebDriver documentation, the following worked fine for me with Java 7 on OS X v10.9 (Mavericks):
import java.io.File;
import java.net.URL;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class Testing {
public void myTest() throws Exception {
WebDriver driver = new RemoteWebDriver(
new URL("http://localhost:4444/wd/hub"),
DesiredCapabilities.firefox());
driver.get("http://www.google.com");
// RemoteWebDriver does not implement the TakesScreenshot class
// if the driver does have the Capabilities to take a screenshot
// then Augmenter will add the TakesScreenshot methods to the instance
WebDriver augmentedDriver = new Augmenter().augment(driver);
File screenshot = ((TakesScreenshot)augmentedDriver).
getScreenshotAs(OutputType.FILE);
}
}
As an update for those who come across this question after 2018, if you are using Kotlin, you can simply use the Android KTX extension property ViewGroup.children to get a sequence of the View's immediate children.
in the spotlight, search for Activity Monitor. You can force fully remove any application from here.
Try innerText property:
var content = document.getElementById("one").innerText;
alert(content);
See also this fiddle http://fiddle.jshell.net/4g8vb/
Your concatenation syntax is correct.
Most likely the callback function isn't even being called. You can test that by putting an alert()
, console.log()
or debugger
line in that function.
If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail()
handler after $.post()
to find out what the error is, e.g.:
$.post('ajaxskeleton.php', {
red: text
}, function(){
$('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(arguments);
});
Try this:
<td bgcolor="#FFFFFF" style="line-height:10px;" colspan=3> </td>
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
Subscribing what basil said in a comment to the question itself, if method = RequestMethod.GET
you can use @RequestParam List<String> groupVal
.
Then calling the service with the list of params is as simple as:
API_URL?groupVal=kkk,ccc,mmm
If you're able to use MySQL Workbench, you can do this by right-clicking the row and selecting 'Copy row', and then right-clicking the empty row and selecting 'Paste row', and then changing the ID, and then clicking 'Apply'.
Copy the row:
Paste the copied row into the blank row:
Change the ID:
Apply:
For someone not using the signing configs and trying to test out the Cordova Release command by typing all the parameters at command line, you may need to enclose your passwords with single quotes if you have special characters in your password
cordova run android --release -- --keystore=../my-release-key.keystore --storePassword='password' --alias=alias_name --password='password'
Maybe you want set -e
:
www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:
This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.
Here is a very recent answer to this question from the file: 07reader.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
date_default_timezone_set('Europe/London');
/** Include PHPExcel_IOFactory */
require_once '../Classes/PHPExcel/IOFactory.php';
if (!file_exists("05featuredemo.xlsx")) {
exit("Please run 05featuredemo.php first." . EOL);
}
echo date('H:i:s') , " Load from Excel2007 file" , EOL;
$callStartTime = microtime(true);
$objPHPExcel = PHPExcel_IOFactory::load("05featuredemo.xlsx");
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
echo 'Call time to read Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
// Echo memory usage
echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
echo date('H:i:s') , " Write to Excel2007 format" , EOL;
$callStartTime = microtime(true);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
// Echo memory usage
echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;
// Echo memory peak usage
echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;
// Echo done
echo date('H:i:s') , " Done writing file" , EOL;
echo 'File has been created in ' , getcwd() , EOL;
What fixed the "Could not find schema information for the element ..." for me was
app.config
.Properties
.Schemas
, I clicked that row and selected the browse ...
box that appears in the row.use
box for all the rows that had my project somewhere in them, and also for the current version of .Net I was using. For instance: DotNetConfig30.xsd
.After that everything went to working fine.
How those schema rows with my project got unchecked I'm not sure, but when I made sure they were checked, I was back in business.
You can make a directory "fonts" in a root of your project and put your fonts (sans_serif.ttf) file there. Then you can make something like this:
fonts_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'fonts')
font = ImageFont.truetype(os.path.join(fonts_path, 'sans_serif.ttf'), 24)
It can depend, especially on whether your file will have the same number of items on each row or not. If it will, then you probably want a 2D matrix class of some sort, usually something like this:
class array2D {
std::vector<double> data;
size_t columns;
public:
array2D(size_t x, size_t y) : columns(x), data(x*y) {}
double &operator(size_t x, size_t y) {
return data[y*columns+x];
}
};
Note that as it's written, this assumes you know the size you'll need up-front. That can be avoided, but the code gets a little larger and more complex.
In any case, to read the numbers and maintain the original structure, you'd typically read a line at a time into a string, then use a stringstream to read numbers from the line. This lets you store the data from each line into a separate row in your array.
If you don't know the size ahead of time or (especially) if different rows might not all contain the same number of numbers:
11 12 13
23 34 56 78
You might want to use a std::vector<std::vector<double> >
instead. This does impose some overhead, but if different rows may have different sizes, it's an easy way to do the job.
std::vector<std::vector<double> > numbers;
std::string temp;
while (std::getline(infile, temp)) {
std::istringstream buffer(temp);
std::vector<double> line((std::istream_iterator<double>(buffer)),
std::istream_iterator<double>());
numbers.push_back(line);
}
...or, with a modern (C++11) compiler, you can use brackets for line
's initialization:
std::vector<double> line{std::istream_iterator<double>(buffer),
std::istream_iterator<double>()};
This is because you are referring to property of controller named HttpContext
. To access the current context use full class name:
System.Web.HttpContext.Current
However this is highly not recommended to access context like this in ASP.NET MVC, so yes, you can think of System.Web.HttpContext.Current
as being deprecated inside ASP.NET MVC. The correct way to access current context is
this.ControllerContext.HttpContext
or if you are inside a Controller, just use member
this.HttpContext
For a binary search tree, an inorder traversal will return elements ... in order.
Just do an inorder traversal and stop after traversing k elements.
O(1) for constant values of k.
Chrome - Press CTRL + L while focusing the console input.
Firefox - clear()
in console input.
Internet Explorer - Press CTRL + L while focusing the console input.
Edge - Press CTRL + L while focusing the console input.
Have a good day!
I followed a post in this thread and got it working perfectly:
Make the bat file with the following, and save it anywhere in your PATH. I suggest C:\Program Files\Java\jdk*\bin\ to keep everything together.
@ECHO OFF
cd %~dp1
javac %~nx1
java %~n1
then edit C:\Users\your_user_name\AppData\Roaming\Sublime Text 2\Packages\Java\JavaC.sublime-build, the contents will be
{
"cmd": ["javac", "$file"],
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java"
}
replace "javac" with the name of your bat file (for instance, javacexec.bat) and save it.
If you are not using the transferTo feature or non-blocking features you will not notice a difference between traditional IO and NIO(2) because the traditional IO maps to NIO.
But if you can use the NIO features like transferFrom/To or want to use Buffers, then of course NIO is the way to go.
To check whether postfix is running or not
sudo postfix status
If it is not running, start it.
sudo postfix start
Then telnet to localhost port 25 to test the email id
ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix
Hi,
Are you there?
regards,
Admin
.
Do not forget the . at the end, which indicates end of line
Herb Sutter has an excellent article on string formatting. I recommend reading it. I've linked it before on SO.
All the other solutions are creepy because they are from someone that arrogantly simply thinks that English is the only language in the world :)
All those solutions strip also diacritics like ç or à.
The perfect solution, as stated in PHP documentation, is simply:
$clear = strip_tags($des);
I found some trick for your problem! Here you can see it: Habrahabr -- Redesigning Qt Creator by your hands (russian lang.)
According to that article, that trick is kind of not so dirty, but "hack" (probably it wouldn't harm your system, but it can leave some artifacts on your interface).
You don't need to patch something (there is possibility, but I don't recommend).
Main idea is to use stylesheet like this stylesheet.css:
// on Linux
qtcreator -stylesheet='.qt-stylesheet.css'
// on Windows
[pathToQt]\QtCreator\bin\qtcreator.exe -stylesheet [pathToStyleSheet]
To get such effect:
To customize by your needs, you may need to read documentation: Qt Style Sheets Reference, Qt Style Sheets Examples and so on.
This wiki page is dedicated to custom Qt Creator styling.
P.S. If you'll got better stylesheet, share it, I'll be happy! :)
UPD (10.12.2014): Hopefully, now we can close this topic. Thanks, Simon G., Things have changed once again. Users may use custom themes since QtCreator 3.3. So hacky stylesheets are no longer needed.
Everyone can take a look at todays update: Qt 5.4 released. There you can find information that Qt 5.4, also comes with a brand new version of Qt Creator 3.3. Just take a look at official video at Youtube.
So, to apply dark theme you need go to "Tools" -> "Options" -> "Environment" -> "General" tab, and there you need to change "Theme".
See more information about its configuring here: Configuring Qt Creator.
When the "%f" for micro seconds isn't working, please use the following method:
import datetime
def getTimeStamp():
dt = datetime.datetime.now()
return dt.strftime("%Y%j%H%M%S") + str(dt.microsecond)
This is my solution, it supports keySelectors of different types:
public static IEnumerable<TSource> DistinctBy<TSource>(this IEnumerable<TSource> source, params Func<TSource, object>[] keySelectors)
{
// initialize the table
var seenKeysTable = keySelectors.ToDictionary(x => x, x => new HashSet<object>());
// loop through each element in source
foreach (var element in source)
{
// initialize the flag to true
var flag = true;
// loop through each keySelector a
foreach (var (keySelector, hashSet) in seenKeysTable)
{
// if all conditions are true
flag = flag && hashSet.Add(keySelector(element));
}
// if no duplicate key was added to table, then yield the list element
if (flag)
{
yield return element;
}
}
}
To use it:
list.DistinctBy(d => d.CategoryId, d => d.CategoryName)
You would use the read.csv
function; for example:
dat = read.csv("spam.csv", header = TRUE)
You can also reference this tutorial for more details.
Note: make sure the .csv
file to read is in your working directory (using getwd()
) or specify the right path to file. If you want, you can set the current directory using setwd
.
Here is a simpler way to iterate and print values in vector.
for(int x: A) // for integer x in vector A
cout<< x <<" ";
This is my favourite way of decoding HTML characters. The advantage of using this code is that tags are also preserved.
function decodeHtml(html) {
var txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}
Example: http://jsfiddle.net/k65s3/
Input:
Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>
Output:
Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>
To create elements with equal width using Flex
, you should set to your's child (flex elements):
flex-basis: 25%;
flex-grow: 0;
It will give to all elements in row 25% width. They will not grow and go one by one.
You can use print_r
to get human-readable output.
It's probably easiest to create your query object directly as:
Test.find({
$and: [
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
]
}, function (err, results) {
...
}
But you can also use the Query#and
helper that's available in recent 3.x Mongoose releases:
Test.find()
.and([
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
])
.exec(function (err, results) {
...
});
How to preventing decompilation of any C# application
Pretty much describes the entire situation.
At some point the code will have to be translated to VM bytecode, and the user can get at it then.
Machine code isn't that much different either. A good interactive disassembler/debugger like IDA Pro makes just about any native application transparent. The debugger is smart enough to use AI to identify common APIs, compiler optimizations, etc. it allows the user to meticuloulsy rebuild higher level constructs from the assembly generated from machine code.
And IDA Pro supports .Net to some extent too.
Honestly, after working on an reverse engineering ( for compatibility ) project for a few years, the main thing I got out of my experience is that I probably shouldn't worry too much about people stealing my code. If anyone wants it, it will never be very hard to get it no matter what scheme I implement.
In config/app.php file make a instance of env variable like 'name' => env('APP_NAME', 'Laravel')
& In your controller call it like config('app.name')
Run following commands php artisan config:cache
php artisan cache:clear
if it is not working.
You need to use a directed graph instead of a graph, i.e.
G = nx.DiGraph()
Then, create a list of the edge colors you want to use and pass those to nx.draw
(as shown by @Marius).
Putting this all together, I get the image below. Still not quite the other picture you show (I don't know where your edge weights are coming from), but much closer! If you want more control of how your output graph looks (e.g. get arrowheads that look like arrows), I'd check out NetworkX with Graphviz.
Alternatively, I think it is worth mentioning that the behavior of equals and compareTo methods in the class BigDecimal are not consistent with each other.
This basically means that:
BigDecimal someValue = new BigDecimal("0.00");
System.out.println(someValue.compareTo(BigDecimal.ZERO) == 0); // true
System.out.println(someValue.equals(BigDecimal.ZERO)); // false
Therefore, you have to be very careful with the scale in your someValue
variable, otherwise you would get unexpected result.
There is also http://appyframework.org/pod.html which takes a LibreOffice or OpenOffice document as template and can generate pdf, rtf, odt ... To generate pdf it requires a headless OOo on some server. Documentation is concise but relatively complete. http://appyframework.org/podWritingTemplates.html If you need advice, the author is rather helpful.
For Fedora (can be useful for someone)
sudo dnf install zlib-1.2.8-10.fc24.i686 libgcc-6.1.1-2.fc24.i686
dir /ad /b /s
will give the required answer.
Use Area/Location format properly. Example:
TIME_ZONE = 'Asia/Kolkata'
It seems important to exactly match the format of the ISO string for TryParseExact
to work. I guess Exact is Exact and this answer is obvious to most but anyway...
In my case, Reb.Cabin's answer doesn't work as I have a slightly different input as per my "value" below.
Value: 2012-08-10T14:00:00.000Z
There are some extra 000's in there for milliseconds and there may be more.
However if I add some .fff
to the format as shown below, all is fine.
Format String: @"yyyy-MM-dd\THH:mm:ss.fff\Z"
In VS2010 Immediate Window:
DateTime.TryParseExact(value,@"yyyy-MM-dd\THH:mm:ss.fff\Z", CultureInfo.InvariantCulture,DateTimeStyles.AssumeUniversal, out d);
true
You may have to use DateTimeStyles.AssumeLocal
as well depending upon what zone your time is for...
Any JS code which executes and deals with DOM elements should execute after the DOM elements have been created. JS code is interpreted from top to down as layed out in the HTML. So, if there is a tag before the DOM elements, the JS code within script tag will execute as the browser parses the HTML page.
So, in your case, you can put your DOM interacting code inside a function so that only function is defined but not executed.
Then you can add an event listener for document load to execute the function.
That will give you something like:
<script>
function init() {
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
}
}
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
document.addEventListener('readystatechange', function() {
if (document.readyState === "complete") {
init();
}
});
</script>
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="button" id="myButton" value="Go" />
</form>
Fiddle at - http://jsfiddle.net/poonia/qQMEg/4/
android:editable="false"
should work, but it is deprecated, you should be using android:inputType="none"
instead.
Alternatively, if you want to do it in the code you could do this :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);
This is also a viable alternative :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);
If you're going to make your EditText
non-editable, may I suggest using the TextView
widget instead of the EditText
, since using a EditText seems kind of pointless in that case.
EDIT: Altered some information since I've found that android:editable
is deprecated, and you should use android:inputType="none"
, but there is a bug about it on android code; So please check this.
What you need to do is configure Fiddler to work as a "reverse proxy"
There are instructions on 2 different ways you can do this on Fiddler's website. Here is a copy of the steps:
Step #0
Before either of the following options will work, you must enable other computers to connect to Fiddler. To do so, click Tools > Fiddler Options > Connections and tick the "Allow remote computers to connect" checkbox. Then close Fiddler.
Option #1: Configure Fiddler as a Reverse-Proxy
Fiddler can be configured so that any traffic sent to http://127.0.0.1:8888
is automatically sent to a different port on the same machine. To set this configuration:
http://127.0.0.1:8888
Option #2: Write a FiddlerScript rule
Alternatively, you can write a rule that does the same thing.
Say you're running a website on port 80 of a machine named WEBSERVER. You're connecting to the website using Internet Explorer Mobile Edition on a Windows SmartPhone device for which you cannot configure the web proxy. You want to capture the traffic from the phone and the server's response.
http://webserver:8888
Requests from the SmartPhone will appear in Fiddler. The requests are forwarded from port 8888 to port 80 where the webserver is running. The responses are sent back through Fiddler to the SmartPhone, which has no idea that the content originally came from port 80.
Using std::string_view
and Eric Niebler's range-v3
library:
https://wandbox.org/permlink/kW5lwRCL1pxjp2pW
#include <iostream>
#include <string>
#include <string_view>
#include "range/v3/view.hpp"
#include "range/v3/algorithm.hpp"
int main() {
std::string s = "Somewhere down the range v3 library";
ranges::for_each(s
| ranges::view::split(' ')
| ranges::view::transform([](auto &&sub) {
return std::string_view(&*sub.begin(), ranges::distance(sub));
}),
[](auto s) {std::cout << "Substring: " << s << "\n";}
);
}
By using a range for
loop instead of ranges::for_each
algorithm:
#include <iostream>
#include <string>
#include <string_view>
#include "range/v3/view.hpp"
int main()
{
std::string str = "Somewhere down the range v3 library";
for (auto s : str | ranges::view::split(' ')
| ranges::view::transform([](auto&& sub) { return std::string_view(&*sub.begin(), ranges::distance(sub)); }
))
{
std::cout << "Substring: " << s << "\n";
}
}
Try:
<c:if test = "${ansokanInfo.PSystem == 'NAT'}">
JSP/Servlet 2.4 (I think that's the version number) doesn't support method calls in EL and only support properties. The latest servlet containers do support method calls (ie Tomcat 7).
Yes you need to use overlays.
You need to get the MapView's overlays and add your new overlay onto it.
Your class extends Overlay, which is a transparent canvas in which you can draw on it like any other canvas.
You can use mapView.getProjection() to get projection of map view.
...
More info found here: http://blogoscoped.com/archive/2008-12-15-n14.html
Left Click on the WAMP icon the system try -> PHP -> PHP Extensions -> Enable php_curl
Also you can check using Keras backend function:
from keras import backend as K
K.tensorflow_backend._get_available_gpus()
I test this on Keras (2.1.1)
I had a very similar error message as you, although listing a particular file:
$ make
make: execvp: ../HoughLineExtractor/houghlineextractor.hh: Permission denied
make: *** [../HoughLineAccumulator/houghlineaccumulator.o] Error 127
$ sudo make
make: execvp: ../HoughLineExtractor/houghlineextractor.hh: Permission denied
make: *** [../HoughLineAccumulator/houghlineaccumulator.o] Error 127
In my case, I forgot to add a trailing slash to indicate continuation of the line as shown:
${LINEDETECTOR_OBJECTS}:\
../HoughLineAccumulator/houghlineaccumulator.hh # <-- missing slash!!
../HoughLineExtractor/houghlineextractor.hh
Hope that helps someone else who lands here from a search engine.
copy your --.MDF
,--.LDF
files to pate this location For 2008 server C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA 2
.
In sql server 2008 use ATTACH and select same location for add
This is one way I know of. With git
, there always seems to be more than one way to do it.
git log -p commit1 commit2
As per your question vertical listing have a scrollbar effect.
CSS / HTML :
nav ul{height:200px; width:18%;}_x000D_
nav ul{overflow:hidden; overflow-y:scroll;}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<header>header area</header>_x000D_
<nav>_x000D_
<ul>_x000D_
<li>Link 1</li>_x000D_
<li>Link 2</li>_x000D_
<li>Link 3</li>_x000D_
<li>Link 4</li>_x000D_
<li>Link 5</li>_x000D_
<li>Link 6</li> _x000D_
<li>Link 7</li> _x000D_
<li>Link 8</li>_x000D_
<li>Link 9</li>_x000D_
<li>Link 10</li>_x000D_
<li>Link 11</li>_x000D_
<li>Link 13</li>_x000D_
<li>Link 13</li>_x000D_
_x000D_
</ul>_x000D_
</nav>_x000D_
_x000D_
<footer>footer area</footer>_x000D_
</body>_x000D_
</html>
_x000D_
You are looking for child_process.exec
Here is the example:
const exec = require('child_process').exec;
const child = exec('cat *.js bad_file | wc -l',
(error, stdout, stderr) => {
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
public String decodeString(String URL)
{
String urlString="";
try {
urlString = URLDecoder.decode(URL,"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
}
return urlString;
}
Using Bootstrap, the correct way is to use the offset class. Use math to determine the left offset. Example: You want a button full width on mobile, but 1/3 width and centered on tablet, desktop, large desktop.
So out of 12 "bootstrap" columns, you're using 4 to offset, 4 for the button, then 4 is blank to the right.
See if that works!
item's border color in swift 4.2:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell_lastOrderId") as! Cell_lastOrder
cell.layer.borderWidth = 1
cell.layer.borderColor = UIColor.white.cgColor
cell.layer.cornerRadius = 10
Note: There is no magic to animating a gif: it is either an animated gif or it is not. If the gif is not visible, very likely the path to the gif is wrong - or, as in your case, the container (div/p/etc) is not large enough to display it. In your code sample, you did not specify height or width and that appeared to be problem.
If the gif is displayed but not animating, see reference links at very bottom of this answer.
Displaying the gif + overlay, however, is easier than you might think.
All you need are two absolute-position DIVs: an overlay div, and a div that contains your loading gif. Both have higher z-index than your page content, and the image has a higher z-index than the overlay - so they will display above the page when visible.
So, when the button is pressed, just unhide those two divs. That's it!
$("#button").click(function() {_x000D_
$('#myOverlay').show();_x000D_
$('#loadingGIF').show();_x000D_
setTimeout(function(){_x000D_
$('#myOverlay, #loadingGIF').fadeOut();_x000D_
},2500);_x000D_
});_x000D_
/* Or, remove overlay/image on click background... */_x000D_
$('#myOverlay').click(function(){_x000D_
$('#myOverlay, #loadingGIF').fadeOut();_x000D_
});
_x000D_
body{font-family:Calibri, Helvetica, sans-serif;}_x000D_
#myOverlay{position:absolute;top:0;left:0;height:100%;width:100%;}_x000D_
#myOverlay{display:none;backdrop-filter:blur(4px);background:black;opacity:.4;z-index:2;}_x000D_
_x000D_
#loadingGIF{position:absolute;top:10%;left:35%;z-index:3;display:none;}_x000D_
_x000D_
button{margin:5px 30px;padding:10px 20px;}
_x000D_
<div id="myOverlay"></div>_x000D_
<div id="loadingGIF"><img src="http://placekitten.com/150/80" /></div>_x000D_
_x000D_
<div id="abunchoftext">_x000D_
Once upon a midnight dreary, while I pondered weak and weary, over many a quaint and curious routine of forgotten code... While I nodded, nearly napping, suddenly there came a tapping... as of someone gently rapping - rapping at my office door. 'Tis the team leader, I muttered, tapping at my office door - only this and nothing more. Ah, distinctly I remember it was in the bleak December and each separate React print-out lay there crumpled on the floor. Eagerly I wished the morrow; vainly I had sought to borrow from Stack-O surcease from sorrow - sorrow for my routine's core. For the brilliant but unworking code my angels seem to just ignore. I'll be tweaking code... forevermore! - <a href="http://www.online-literature.com/poe/335/" target="_blank">Apologies To Poe</a></div>_x000D_
<button id="button">Submit</button>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
_x000D_
You might enjoy playing with the new backdrop-filter:blur(_px)
css property that gives a blur effect to the underlying content, as used in above demo... (As of April 2020: works in Chrome, Edge, Safari, Android, but not yet in Firefox)
References:
http://www.paulirish.com/2007/animated-gif-not-animating/
Animated GIF while loading page does not animate
https://wordpress.org/support/topic/animated-gif-not-working
Here is a screenshot of me fixing this. I've encountered it many times, and it's always due to this config-related jazz:
Event Log
(bottom right)Configure
of the Android Framework detected notificationIf you do this and your icon still isn't lit up, then you probably need to set up the emulator still. I would recommend investigating the SDK Manager
if so.
There can be several reasons for this error message:
Several processes have the database open at the same time (see the FAQ).
There is a plugin to compress and encrypt the database. It doesn't allow to modify the DB.
Lastly, another FAQ says: "Make sure that the directory containing the database file is also writable to the user executing the CGI script." I think this is because the engine needs to create more files in the directory.
The whole filesystem might be read only, for example after a crash.
On Unix systems, another process can replace the whole file.
It's built in Eclipse since ages. Which Eclipse version are you using? How were you trying to create a new JUnit test case? It should be File > New > Other > Java - JUnit - JUnit Test Case (you can eventually enter Filter text "junit").
Exception code 0xc0000005
is an Access Violation. An AV at fault offset 0x00000000
means that something in your service's code is accessing a nil
pointer. You will just have to debug the service while it is running to find out what it is accessing. If you cannot run it inside a debugger, then at least install a third-party exception logger framework, such as EurekaLog or MadExcept, to find out what your service was doing at the time of the AV.
When you already have an older version of NumPy, use this:
pip install numpy --upgrade
If it still doesn't work, try:
pip install numpy --upgrade --ignore-installed
Just to explain what others are saying (it took me some time to understand) is that, simply put, when you see this error, it means you already have a container and what you have to do is run it. While intuitively docker run
is supposed to run it, it doesn't. The command docker run
is used to only START a container for the very first time. To run an existing container what you need is docker start $container-name
. So much for asking developers to create meaningful/intuitive commands.
The solution of creating a new HTML file with HTML (Web Forms) Designer worked for that file but not for other, individual HTML files that I wanted to edit.
I did find the Open With option in the Open File dialogue and was able to select the HTML (Web Forms) Editor there. Having clicked the "Set as Default" option in that window, VS then remembered to use that editor when I opened other HTML files.
That line works as-is in Python 3.
>>> sys.version
'3.2 (r32:88445, Oct 20 2012, 14:09:29) \n[GCC 4.5.2]'
>>> "(%d goals, $%d)" % (self.goals, self.penalties)
'(1 goals, $2)'
The selected answer is probably correct but it seems needlessly unclear.
I found Shomz's Fiddle to be very helpful, but again, needlessly unclear. (Edit: I now see that that Fiddle is based on the OP's Fiddle.)
Here's my version (which I've created a Fiddle for) which I think is more clear:
function downloadableCSV(rows) {
var content = "data:text/csv;charset=utf-8,";
rows.forEach(function(row, index) {
content += row.join(",") + "\n";
});
return encodeURI(content);
}
var rows = [
["name1", 2, 3],
["name2", 4, 5],
["name3", 6, 7],
["name4", 8, 9],
["name5", 10, 11]
];
$("#download").click(function() {
window.open(downloadableCSV(rows));
});
You could use IsEmpty()
function like this:
...
Set rRng = Sheet1.Range("A10")
If IsEmpty(rRng.Value) Then ...
you could also use following:
If ActiveCell.Value = vbNullString Then ...
Run these commands for Beyond Compare 2:
git config --global diff.tool bc2
git config --global difftool.bc2.cmd "\"c:/program files (x86)/beyond compare 2/bc2.exe\" \"$LOCAL\" \"$REMOTE\""
git config --global difftool.prompt false
Run these commands for Beyond Compare 3:
git config --global diff.tool bc3
git config --global difftool.bc3.cmd "\"c:/program files (x86)/beyond compare 3/bcomp.exe\" \"$LOCAL\" \"$REMOTE\""
git config --global difftool.prompt false
Then use git difftool
you are better off with a decompiler like redgates .net reflector or jetbrains resharper decompiler. there are open source ones also like
If you have defined a method inside your class as static, this is actually possible.
class myClass
{
public:
static void saySomething()
{
std::cout << "This is a static method!" << std::endl;
}
};
And from main, you declare a pointer and try to invoke the static method.
myClass * pmyClass;
pmyClass->saySomething();
/*
Output:
This is a static method!
*/
This works fine because static methods do not belong to a specific instance of the class and they are not allocated as a part of any instance of the class.
Read more on static methods here: http://en.wikipedia.org/wiki/Static_method#Static_methods
If Table variable has large data, then instead of table variable(@table) create temp table (#table).table variable doesn't allow to create index after insert.
CREATE TABLE #Table(C1 int,
C2 NVarchar(100) , C3 varchar(100)
UNIQUE CLUSTERED (c1)
);
Create table with unique clustered index
Insert data into Temp "#Table" table
Create non clustered indexes.
CREATE NONCLUSTERED INDEX IX1 ON #Table (C2,C3);
I assume you use Graphics.CopyFromScreen
to get the screenshot.
You can use P/Invoke to GetForegroundWindow (and then get its position and size) to determine which region you need to copy from.
Also if you want selected field from table and aggregated then as array .
SELECT json_agg(json_build_object('data_a',a,
'data_b',b,
)) from t;
The result will come .
[{'data_a':1,'data_b':'value1'}
{'data_a':2,'data_b':'value2'}]
I would consider writing a CLR replace function with RegEx support for this kind of string manipulation.
If you can add another wrapping div "block3" you could do something like this.
<html>
<head>
<style type="text/css">
.block1 {color:red;width:120px;border:1px solid green; height: 100px;}
.block3 {float:left; width:10px;}
.block2 {color:blue;width:70px;border:2px solid black;position:relative;float:right;}
</style>
</head>
<body>
<div class='block1'>
<div class='block3'>
<p>text1</p>
<p>text2</p>
</div>
<div class='block2'>block2</DIV>
</div>
</body>
</html>
Best avoid casting by declaring f to be f the correct type to correspond to the JSON.
http://madurangasblogs.blogspot.in/2013/08/avoiding-javaxnetsslsslpeerunverifiedex.html
Courtesy Maduranga
When developing an application that uses https, your test server doesn't have a valid SSL certificate. Or sometimes the web site is using a self-signed certificate or the web site is using free SSL certificate. So if you try to connect to the server using Apache HttpClient
, you will get a exception telling that the "peer not authenticated". Though it is not a good practice to trust all the certificates in a production software, you may have to do so according to the situation.
This solution resolves the exception caused by "peer not authenticated".
But before we go to the solution, I must warn you that this is not a good idea for a production application. This will violate the purpose of using a security certificate. So unless you have a good reason or if you are sure that this will not cause any problem, don't use this solution.
Normally you create a HttpClient
like this.
HttpClient httpclient = new DefaultHttpClient();
But you have to change the way you create the HttpClient.
First you have to create a class extending org.apache.http.conn.ssl.SSLSocketFactory
.
import org.apache.http.conn.ssl.SSLSocketFactory;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
Then create a method like this.
public HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
Then you can create the HttpClient
.
HttpClient httpclient = getNewHttpClient();
If you are trying to send a post request to a login page the rest of the code would be like this.
private URI url = new URI("url of the action of the form");
HttpPost httppost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", "user"));
nameValuePairs.add(new BasicNameValuePair("password", "password"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You get the html page to the InputStream. Then you can do whatever you want with the returned html page.
But here you will face a problem. If you want to manage a session using cookies, you will not be able to do it with this method. If you want to get the cookies, you will have to do it via a browser. Then only you will receive cookies.
using System.Security.Cryptography;
public static byte[] GetHash(string inputString)
{
using (HashAlgorithm algorithm = SHA256.Create())
return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
}
public static string GetHashString(string inputString)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in GetHash(inputString))
sb.Append(b.ToString("X2"));
return sb.ToString();
}
Additional Notes
A NULL
pointer points to memory that doesn't exist. This may be address 0x00000000
or any other implementation-defined value (as long as it can never be a real address). Dereferencing it means trying to access whatever is pointed to by the pointer. The *
operator is the dereferencing operator:
int a, b, c; // some integers
int *pi; // a pointer to an integer
a = 5;
pi = &a; // pi points to a
b = *pi; // b is now 5
pi = NULL;
c = *pi; // this is a NULL pointer dereference
This is exactly the same thing as a NullReferenceException
in C#, except that pointers in C can point to any data object, even elements inside an array.
If you installed php with homebrew, then check if your apache2.conf file is using homebrew version of php5.so file.
Some basics:
RTSP server can be used for dead source as well as for live source. RTSP protocols provides you commands (Like your VCR Remote), and functionality depends upon your implementation.
RTP is real time protocol used for transporting audio and video in real time. Transport used can be unicast, multicast or broadcast, depending upon transport address and port. Besides transporting RTP does lots of things for you like packetization, reordering, jitter control, QoS, support for Lip sync.....
In your case if you want broadcasting streaming server then you need both RTSP (for control) as well as RTP (broadcasting audio and video)
To start with you can go through sample code provided by live555
Easiest: http://www.addthis.com/
Best? Well. probably not, But If you don't want to design something bespoke this is the best there is...
I had the same issue caused by importing the internal version of 'takeUntil' instead of the operators Change
import { takeUntil } from 'rxjs/internal/operators/takeUntil';
to
import { takeUntil } from 'rxjs/operators';
This happen also for other operators
DISCLAIMER: The below solution does not preserve trailing tabs.
If you know the exact number of lines in the text file, try the following method:
@ECHO OFF
SET origfile=original file
SET tempfile=temporary file
SET insertbefore=4
SET totallines=200
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
SETLOCAL EnableDelayedExpansion
SET /P L=
IF %%i==%insertbefore% ECHO(
ECHO(!L!
ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%
The loop reads lines from the original file one by one and outputs them. The output is redirected to a temporary file. When a certain line is reached, an empty line is output before it.
After finishing, the original file is deleted and the temporary one gets assigned the original name.
UPDATE
If the number of lines is unknown beforehand, you can use the following method to obtain it:
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
(This line simply replaces the SET totallines=200
line in the above script.)
The method has one tiny flaw: if the file ends with an empty line, the result will be the actual number of lines minus one. If you need a workaround (or just want to play safe), you can use the method described in this answer.
The AAR file consists of a JAR file and some resource files (it is basically a standard zip file with a custom file extension). Here are the steps to convert:
I know this is old, but I was just working on a project that required me to filter HTML and this worked fine:
noHTMLString.replaceAll("\\&.*?\\;", "");
instead of this:
html = html.replaceAll(" ","");
html = html.replaceAll("&"."");
There are multiple ways to fix the same. PFB two of them -
1st Way using position: fixed - position: fixed; positions relative to the viewport, which means it always stays in the same place even if the page is scrolled. Adding the left and top value to 50% will place it into the middle of the screen.
button {
position: fixed;
left: 50%;
top:50%;
}
2nd Way using margin: auto -margin: 0 auto; for horizontal centering, but margin: auto; has refused to work for vertical centering… until now! But actually absolute centering only requires a declared height and these styles:
button {
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
height: 40px;
}
#include<stdio.h>
int main()
{
char str[100];
scanf("%[^\n]s",str);
printf("%s",str);
return 0;
}
input: read the string
ouput: print the string
This code prints the string with gaps as shown above.
Plugin run Tomcat 7.0.47:
mvn org.apache.tomcat.maven:tomcat7-maven-plugin:2.2:run
...
INFO: Starting Servlet Engine: Apache Tomcat/7.0.47
This is sample to run plugin with Tomcat 8 and Java 8: Cargo embedded tomcat: custom context.xml
In vue cli-3 You can define the variable in main.js like
window.basurl="http://localhost:8000/";
And you can also access this variable in any component by using the the window.basurl
from the sourcecode at http://mozilla.github.com/pdf.js/build/pdf.js
/**
* This is the main entry point for loading a PDF and interacting with it.
* NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
* is used, which means it must follow the same origin rules that any XHR does
* e.g. No cross domain requests without CORS.
*
* @param {string|TypedAray|object} source Can be an url to where a PDF is
* located, a typed array (Uint8Array) already populated with data or
* and parameter object with the following possible fields:
* - url - The URL of the PDF.
* - data - A typed array with PDF data.
* - httpHeaders - Basic authentication headers.
* - password - For decrypting password-protected PDFs.
*
* @return {Promise} A promise that is resolved with {PDFDocumentProxy} object.
*/
So a standard XMLHttpRequest(XHR) is used for retrieving the document. The Problem with this is that XMLHttpRequests do not support data: uris (eg. data:application/pdf;base64,JVBERi0xLjUK...).
But there is the possibility of passing a typed Javascript Array to the function. The only thing you need to do is to convert the base64 string to a Uint8Array. You can use this function found at https://gist.github.com/1032746
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(var i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
tl;dr
var pdfAsDataUri = "data:application/pdf;base64,JVBERi0xLjUK..."; // shortened
var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray)
(//*[@attribute='value'])[index] to find target of element while your finding multiple matches in it
Use the following Code:-
../css/main.css
Note: The "../" is shorthand for "The containing directory", or "Up one directory".
If you don't know the previous folder this will be very helpful..
The MultiCell
is used for print text with multiple lines. It has the same atributes of Cell
except for ln
and link
.
$pdf->MultiCell( 200, 40, $reportSubtitle, 1);
What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).
MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])
You can read the full documentation here.
There is no reliable way to do this in pure Java. Setting the user.dir
property via System.setProperty()
or java -Duser.dir=...
does seem to affect subsequent creations of Files
, but not e.g. FileOutputStreams
.
The File(String parent, String child)
constructor can help if you build up your directory path separately from your file path, allowing easier swapping.
An alternative is to set up a script to run Java from a different directory, or use JNI native code as suggested below.
The relevant Sun bug was closed in 2008 as "will not fix".
Nowadays it's like:
var collection = new List<object>(objectVar);
You probably aborted a clearcache halfway and now you already have an app/cache/dev_old.
Try this (in the root of your project, assuming you're on a Unixy environment like OS X or Linux):
rm -rf app/cache/dev*
Travis-ci and Jenkins, while both are tools for continuous integration are very different.
Travis is a hosted service (free for open source) while you have to host, install and configure Jenkins.
Travis does not have jobs as in Jenkins. The commands to run to test the code are taken from a file named .travis.yml
which sits along your project code. This makes it easy to have different test code per branch since each branch can have its own version of the .travis.yml file.
You can have a similar feature with Jenkins if you use one of the following plugins:
.jervis.yml
file found at the root of project code. If .jervis.yml
does not exist, it will fall back to using .travis.yml
file instead.There are other hosted services you might also consider for continuous integration (non exhaustive list):
You might want to stay with Jenkins because you are familiar with it or don't want to depend on 3rd party for your continuous integration system. Else I would drop Jenkins and go with one of the free hosted CI services as they save you a lot of trouble (host, install, configure, prepare jobs)
Depending on where your code repository is hosted I would make the following choices:
To setup Travis-CI on a github project, all you have to do is:
The features you get are:
The below css code always keep the button at the bottom of the page
position:absolute;
bottom:0;
Since you want to do it in relative positioning, you should go for margin-top:100%
position:relative;
margin-top:100%;
EDIT1: JSFiddle1
EDIT2: To place button at center of the screen,
position:relative;
left: 50%;
margin-top:50%;
As far as the Python languages is concerned, _
has no special meaning. It is a valid identifier just like _foo
, foo_
or _f_o_o_
.
Any special meaning of _
is purely by convention. Several cases are common:
A dummy name when a variable is not intended to be used, but a name is required by syntax/semantics.
# iteration disregarding content
sum(1 for _ in some_iterable)
# unpacking disregarding specific elements
head, *_ = values
# function disregarding its argument
def callback(_): return True
Many REPLs/shells store the result of the last top-level expression to builtins._
.
The special identifier
_
is used in the interactive interpreter to store the result of the last evaluation; it is stored in thebuiltins
module. When not in interactive mode,_
has no special meaning and is not defined. [source]
Due to the way names are looked up, unless shadowed by a global or local _
definition the bare _
refers to builtins._
.
>>> 42
42
>>> f'the last answer is {_}'
'the last answer is 42'
>>> _
'the last answer is 42'
>>> _ = 4 # shadow ``builtins._`` with global ``_``
>>> 23
23
>>> _
4
Note: Some shells such as ipython
do not assign to builtins._
but special-case _
.
In the context internationalization and localization, _
is used as an alias for the primary translation function.
Return the localized translation of message, based on the current global domain, language, and locale directory. This function is usually aliased as _() in the local namespace (see examples below).
At https://github.com/golang/go/issues/44196 randall77 suggested
time.Now().Sub(time.Unix(0,0)).Milliseconds()
which exploits the fact that Go's time.Duration
already have Milliseconds
method.
Have a look at this article, it's not an exact match to your problem, but suits it:
This header is defined in RFC 2183, so that would be the best place to start reading.
Permitted values are those registered with the Internet Assigned Numbers Authority (IANA); their registry of values should be seen as the definitive source.
From a blog I found:
"This [git-credential-cache] doesn’t work for Windows systems as git-credential-cache communicates through a Unix socket."
Since msysgit has been superseded by Git for Windows, using Git for Windows is now the easiest option. Some versions of the Git for Windows installer (e.g. 2.7.4) have a checkbox during the install to enable the Git Credential Manager. Here is a screenshot:
The wincred
helper was added in msysgit 1.8.1. Use it as follows:
git config --global credential.helper wincred
First, download git-credential-winstore and install it in your git bin directory.
Next, make sure that the directory containing git.cmd is in your Path environment variable. The default directory for this is C:\Program Files (x86)\Git\cmd on a 64-bit system or C:\Program Files\Git\cmd on a 32-bit system. An easy way to test this is to launch a command prompt and type git
. If you don't get a list of git commands, then it's not set up correctly.
Finally, launch a command prompt and type:
git config --global credential.helper winstore
Or you can edit your .gitconfig file manually:
[credential]
helper = winstore
Once you've done this, you can manage your git credentials through Windows Credential Manager which you can pull up via the Windows Control Panel.
Needle module is also good, here is an example which uses needle
module
var needle = require('needle');
needle.get('http://www.google.com', function(error, response) {
if (!error && response.statusCode == 200)
console.log(response.body);
});
When a folder is created, many Linux filesystems allocate 4096 bytes to store some metadata about the directory itself. This space is increased by a multiple of 4096 bytes as the directory grows.
du command (with or without -b option) take in count this space, as you can see typing:
mkdir test && du -b test
you will have a result of 4096 bytes for an empty dir. So, if you put 2 files of 10000 bytes inside the dir, the total amount given by du -sb would be 24096 bytes.
If you read carefully the question, this is not what asked. The questioner asked:
the sum total of all the data in files and subdirectories I would get if I opened each file and counted the bytes
that in the example above should be 20000 bytes, not 24096.
So, the correct answer IMHO could be a blend of Nelson answer and hlovdal suggestion to handle filenames containing spaces:
find . -type f -print0 | xargs -0 stat --format=%s | awk '{s+=$1} END {print s}'
Junit 4.11 doesn't work with Spring Test framework. Also this link InitializationError When Use Spring + Junit explains how to debug junit initalizationError in eclipse.
Take a look at this answer:
from numpy import matrix
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] ) # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] ) # Creates a matrix (like a row vector).
print A.T # Transpose of A.
print A*x # Matrix multiplication of A and x.
print A.I # Inverse of A.
print linalg.solve(A, x) # Solve the linear equation system.
Unobtrusive validation is enabled by default in new version of ASP.NET. Unobtrusive validation aims to decrease the page size by replacing the inline JavaScript for performing validation with a small JavaScript library that uses jQuery.
You can either disable it by editing web.config to include the following:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
Or better yet properly configure it by modifying the Application_Start method in global.asax:
void Application_Start(object sender, EventArgs e)
{
RouteConfig.RegisterRoutes(System.Web.Routing.RouteTable.Routes);
ScriptManager.ScriptResourceMapping.AddDefinition("jquery",
new ScriptResourceDefinition
{
Path = "/~Scripts/jquery-2.1.1.min.js"
}
);
}
Page 399 of Beginning ASP.NET 4.5.1 in C# and VB provides a discussion on the benefit of unobtrusive validation and a walkthrough for configuring it.
For those looking for RouteConfig. It is added automatically when you make a new project in visual studio to the App_Code folder. The contents look something like this:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;
namespace @default
{
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
}
}
Your problem is this
<button type="button" value=" Send" class="btn btn-success" type="submit" id="submit" />
You've set the type twice. Your browser is only accepting the first, which is "button".
<button type="submit" value=" Send" class="btn btn-success" id="submit" />
FWIW the removal of Apache library was foreshadowed a while ago. Our good friend Jesse Wilson gave us a clue back in 2011: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
Google stopped working on ApacheHTTPClient a while ago, so any library that is still relying upon that should be put onto the list of deprecated libraries unless the maintainers update their code.
<rant>
I can't tell you how many technical arguments I've had with people who insisted on sticking with Apache HTTP client. There are some major apps that are going to break because management at my not-to-be-named previous employers didn't listen to their top engineers or knew what they were talking about when they ignored the warning ... but, water under the bridge.
I win.
</rant>
The answers above are correct, and what I'd consider the "best" answers. But just to be as complete as possible, you can also do this directly in CF using queryAddColumn.
See http://www.cfquickdocs.com/cf9/#queryaddcolumn
Again, it's more efficient to do it at the database level... but it's good to be aware of as many alternatives as possible (IMO, of course) :)
I've needed to do testing of an insert-heavy application in both MyISAM and InnoDB simultaneously. There was a single setting that resolved the speed issues I was having. Try setting the following:
innodb_flush_log_at_trx_commit = 2
Make sure you understand the risks by reading about the setting here.
Also see https://dba.stackexchange.com/questions/12611/is-it-safe-to-use-innodb-flush-log-at-trx-commit-2/12612 and https://dba.stackexchange.com/a/29974/9405
This is for the worst-case scenario of exiting Vim if you just want out, have no idea what you've done and you don't care what will happen to the files you opened.
Ctrl-cEnterEntervi
EnterCtrl-\Ctrl-n:qa!
Enter
This should get you out most of the time.
Some interesting cases where you need something like this:
i
Ctrl-ovg
(you enter insert mode, then visual mode and then operator pending mode)
Qappend
Enter
i
Ctrl-ogQ
Ctrl-r=
Ctrl-k (thanks to porges for this case)
:set insertmode
(this is a case when Ctrl-\Ctrl-n returns you to normal mode)
Edit: This answer was corrected due to cases above. It used to be:
EscEscEsc:qa!
Enter
However, that doesn't work if you have entered Ex mode. In that case you would need to do:
vi
Enter:qa!
Enter
So a complete command for "I don't want to know what I've done and I don't want to save anything, I just want out now!" would be
vi
EnterEscEscEsc:qa!
Enter
Remove the multiple="multiple" attribute and add SIZE=6 with the number of elements you want
you may want to check this site
In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.
You can try a box-shadow inset
something like this: box-shadow:inset 0px -5px 0px 0px #fff
adds a white 5px border to the bottom of the element without increasing the size
No need for a StringBuilder
:
string path = @"c:\hereIAm.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Here");
sw.WriteLine("I");
sw.WriteLine("am.");
}
}
But of course you can use the StringBuilder
to create all lines and write them to the file at once.
sw.Write(stringBuilder.ToString());
StreamWriter.Write
Method (String) (.NET Framework 1.1)
how about complex types? when array contains objects... or any else
My variant:
Object.prototype.copy = function(){
var v_newObj = {};
for(v_i in this)
v_newObj[v_i] = (typeof this[v_i]).contains(/^(array|object)$/) ? this[v_i].copy() : this[v_i];
return v_newObj;
}
Array.prototype.copy = function(){
var v_newArr = [];
this.each(function(v_i){
v_newArr.push((typeof v_i).contains(/^(array|object)$/) ? v_i.copy() : v_i);
});
return v_newArr;
}
It's not final version, just an idea.
PS: method each and contains are prototypes also.
In the top of the bootstrap.css
you should have comments like the below:
/*!
* Bootstrap v2.3.1
*
* Copyright 2012 Twitter, Inc
* Licensed under the Apache License v2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Designed and built with all the love in the world @twitter by @mdo and @fat.
*/
If they are not there, then they have probably been deleted.
VERSIONS:
You can review version history here. Backward compatibility shouldn't be broken if the source is v2.0.0 (Jan 2012) and above. If it is prior to v2.0.0 there are details on upgrading here.
select *
from ROLE_TAB_PRIVS
where role in (
select granted_role
from dba_role_privs
where granted_role in ('ROLE1','ROLE2')
)
Here is my simplistic log4j2.xml
that prints to console and writes to a daily rolling file:
// java
private static final Logger LOGGER = LogManager.getLogger(MyClass.class);
// log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="logPath">target/cucumber-logs</Property>
<Property name="rollingFileName">cucumber</Property>
</Properties>
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
</Console>
<RollingFile name="rollingFile" fileName="${logPath}/${rollingFileName}.log" filePattern="${logPath}/${rollingFileName}_%d{yyyy-MM-dd}.log">
<PatternLayout pattern="[%highlight{%-5level}] %d{DEFAULT} %c{1}.%M() - %msg%n%throwable{short.lineNumber}" />
<Policies>
<!-- Causes a rollover if the log file is older than the current JVM's start time -->
<OnStartupTriggeringPolicy />
<!-- Causes a rollover once the date/time pattern no longer applies to the active file -->
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="DEBUG" additivity="false">
<AppenderRef ref="console" />
<AppenderRef ref="rollingFile" />
</Root>
</Loggers>
</Configuration>
TimeBasedTriggeringPolicy
interval (integer) - How often a rollover should occur based on the most specific time unit in the date pattern. For example, with a date pattern with hours as the most specific item and and increment of 4 rollovers would occur every 4 hours. The default value is 1.
modulate (boolean) - Indicates whether the interval should be adjusted to cause the next rollover to occur on the interval boundary. For example, if the item is hours, the current hour is 3 am and the interval is 4 then the first rollover will occur at 4 am and then next ones will occur at 8 am, noon, 4pm, etc.
Source: https://logging.apache.org/log4j/2.x/manual/appenders.html
Output:
[INFO ] 2018-07-21 12:03:47,412 ScenarioHook.beforeScenario() - Browser=CHROME32_NOHEAD
[INFO ] 2018-07-21 12:03:48,623 ScenarioHook.beforeScenario() - Screen Resolution (WxH)=1366x768
[DEBUG] 2018-07-21 12:03:52,125 HomePageNavigationSteps.I_Am_At_The_Home_Page() - Base URL=http://simplydo.com/projector/
[DEBUG] 2018-07-21 12:03:52,700 NetIncomeProjectorSteps.I_Enter_My_Start_Balance() - Start Balance=348000
A new log file will be created daily with previous day automatically renamed to:
cucumber_yyyy-MM-dd.log
In a Maven project, you would put the log4j2.xml
in src/main/resources
or src/test/resources
.
**If you want hibernate to print generated sql queries with real values instead of question marks.**
**add following entry in hibernate.cfg.xml/hibernate.properties:**
show_sql=true
format_sql=true
use_sql_comments=true
**And add following entry in log4j.properties :**
log4j.logger.org.hibernate=INFO, hb
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
log4j.appender.hb=org.apache.log4j.ConsoleAppender
log4j.appender.hb.layout=org.apache.log4j.PatternLayout
No there isn't. Instead use a while
loop such as:
while 1:
...statements...
if cond:
break
I'm not aware of anything that combines this information, but you can use the nvidia-smi
tool to get the raw data, like so (thanks to @jmsu for the tip on -l):
$ nvidia-smi -q -g 0 -d UTILIZATION -l
==============NVSMI LOG==============
Timestamp : Tue Nov 22 11:50:05 2011
Driver Version : 275.19
Attached GPUs : 2
GPU 0:1:0
Utilization
Gpu : 0 %
Memory : 0 %
As session.query(SomeModel.col1)
returns an array of tuples like this [('value_1',),('value_2',)]
if you want t cast the result to a plain array you can do it by using one of the following statements:
values = [value[0] for value in session.query(SomeModel.col1)]
values = [model.col1 for model in session.query(SomeModel).options(load_only('col1'))]
Result:
['value_1', 'value_2']
This solution works with complex JSONs:
public Object toJSON(Object object) throws JSONException {
if (object instanceof HashMap) {
JSONObject json = new JSONObject();
HashMap map = (HashMap) object;
for (Object key : map.keySet()) {
json.put(key.toString(), toJSON(map.get(key)));
}
return json;
} else if (object instanceof Iterable) {
JSONArray json = new JSONArray();
for (Object value : ((Iterable) object)) {
json.put(toJSON(value));
}
return json;
}
else {
return object;
}
}
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "07/06/2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Output:
2014/08/06 16:06:54
2014/08/06 16:06:54
I couldn't figure out how to do this in pure MS LINQ, so I wrote my own extension method to do it:
public static bool In<T>(this T objToCheck, params T[] values)
{
if (values == null || values.Length == 0)
{
return false; //early out
}
else
{
foreach (T t in values)
{
if (t.Equals(objToCheck))
return true; //RETURN found!
}
return false; //nothing found
}
}
An instance variable would probably be the way to do what you want. You could make it static to persist the same value for the life of the program (or thread depending on your static memory model), or make it an ordinary instance var to control it over the life of an object instance. If that instance is a singleton, they'll behave the same way.
#if DEBUG
private /*static*/ bool s_bDoDebugOnlyCode = false;
#endif
void foo()
{
// ...
#if DEBUG
if (s_bDoDebugOnlyCode)
{
// Code here gets executed only when compiled with the DEBUG constant,
// and when the person debugging manually sets the bool above to true.
// It then stays for the rest of the session until they set it to false.
}
#endif
// ...
}
Just to be complete, pragmas (preprocessor directives) are considered a bit of a kludge to use to control program flow. .NET has a built-in answer for half of this problem, using the "Conditional" attribute.
private /*static*/ bool doDebugOnlyCode = false;
[Conditional("DEBUG")]
void foo()
{
// ...
if (doDebugOnlyCode)
{
// Code here gets executed only when compiled with the DEBUG constant,
// and when the person debugging manually sets the bool above to true.
// It then stays for the rest of the session until they set it to false.
}
// ...
}
No pragmas, much cleaner. The downside is that Conditional can only be applied to methods, so you'll have to deal with a boolean variable that doesn't do anything in a release build. As the variable exists solely to be toggled from the VS execution host, and in a release build its value doesn't matter, it's pretty harmless.
I believe right now your output printing as below
~ echo -e "String1\nString2"
String1
String2
You can use xargs
to get multiline stdout into same line.
~ echo -e "String1\nString2" | xargs
String1 String2
~
In answer to your first question, it should be as simple as replacing:
when(LoggerFactory.getLogger(GoodbyeController.class)).thenReturn(loggerMock);
with
when(LoggerFactory.getLogger(any(Class.class))).thenReturn(loggerMock);
Regarding your second question (and possibly the puzzling behavior with the first), I think the problem is that logger is static. So,
private static Logger logger = LoggerFactory.getLogger(GoodbyeController.class);
is executed when the class is initialized, not the when the object is instantiated. Sometimes this can be at about the same time, so you'll be OK, but it's hard to guarantee that. So you set up LoggerFactory.getLogger to return your mock, but the logger variable may have already been set with a real Logger object by the time your mocks are set up.
You may be able to set the logger explicitly using something like ReflectionTestUtils (I don't know if that works with static fields) or change it from a static field to an instance field. Either way, you don't need to mock LoggerFactory.getLogger because you'll be directly injecting the mock Logger instance.
A subquery is a select statement that is embedded in a clause of another select statement.
EX:
select ename, sal
from emp where sal > (select sal
from emp where ename ='FORD');
A Correlated subquery is a subquery that is evaluated once for each row processed by the outer query or main query. Execute the Inner query based on the value fetched by the Outer query all the values returned by the main query are matched. The INNER Query is driven by the OUTER Query.
Ex:
select empno,sal,deptid
from emp e
where sal=(select avg(sal)
from emp where deptid=e.deptid);
DIFFERENCE
The inner query executes first and finds a value, the outer query executes once using the value from the inner query (subquery)
Fetch by the outer query, execute the inner query using the value of the outer query, use the values resulting from the inner query to qualify or disqualify the outer query (correlated)
For more information : http://www.oraclegeneration.com/2014/01/sql-interview-questions.html