On my AWS beanstalk server, I don't see $_SERVER['HTTPS'] variable. I do see $_SERVER['HTTP_X_FORWARDED_PROTO'] which can be either 'http' or 'https' so if you're hosting on AWS, use this:
if ($_SERVER['HTTP_HOST'] != 'localhost' and $_SERVER['HTTP_X_FORWARDED_PROTO'] != "https") {
$location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $location);
exit;
}
Go to your settings.json file, add the following and, fix the eslint.nodepath. Tailor it to your own preferences.
// PERSONAL
"editor.codeActionsOnSaveTimeout": 2000,
"editor.codeActionsOnSave": {
"source.fixAll": true
},
"editor.fontSize": 16,
"editor.formatOnSave": true,
"explorer.confirmDragAndDrop": true,
"editor.tabSize": 2,
"eslint.codeAction.showDocumentation": {
"enable": true
},
"eslint.nodePath": "C:\\{path}",
"eslint.workingDirectories": ["./backend", "./frontend"],
This is an older question, but if you simply want to run the simulator from the Xcode 4.5 UI, you can do: Xcode > Open Developer Tool > iOS Simulator.
#use return convertView;
Code:
public View getView(final int position, View convertView, ViewGroup parent) {
//convertView = null;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_item, null);
TextView tv = (TextView) convertView.findViewById(R.id.name);
Button rm_btn = (Button) convertView.findViewById(R.id.rm_btn);
Model m = modelList.get(position);
tv.setText(m.getName());
// click listener for remove button ??????????
rm_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
modelList.remove(position);
notifyDataSetChanged();
}
});
}
///#use return convertView;
return convertView;
}
http://quantumsupport.blogspot.com/2011/03/android-sdk-managerexe-wont-start.html
Create a new user account, either re-install or just start android.bat and it should work did for me
You can use dir(your_object)
to get the attributes and getattr(your_object, your_object_attr)
to get the values
usage :
for att in dir(your_object):
print (att, getattr(your_object,att))
This is particularly useful if your object have no __dict__. If that is not the case you can try var(your_object) also
For a 64-bit OS, the path would be:
HKEY_LOCAL_MACHINE\SOFTWARE\wow6432Node\Microsoft\NET Framework Setup\NDP\
$('#textarea').blur()
Documentation at: http://api.jquery.com/blur/
Floating point numbers (IEEE 754) are symmetrical, so if you can represent the greatest value (DBL_MAX
or numeric_limits<double>::max()
), just prepend a minus sign.
And then is the cool way:
double f;
(*((long long*)&f))= ~(1LL<<52);
Either use one of the standard date and time format strings which only specifies the date (e.g. "D" or "d"), or a custom date and time format string which only uses the date parts (e.g. "yyyy/MM/dd").
To augment T.J.'s answer, exceeding the min/max values generates an Invalid Date.
let maxDate = new Date(8640000000000000);_x000D_
let minDate = new Date(-8640000000000000);_x000D_
_x000D_
console.log(new Date(maxDate.getTime()).toString());_x000D_
console.log(new Date(maxDate.getTime() - 1).toString());_x000D_
console.log(new Date(maxDate.getTime() + 1).toString()); // Invalid Date_x000D_
_x000D_
console.log(new Date(minDate.getTime()).toString());_x000D_
console.log(new Date(minDate.getTime() + 1).toString());_x000D_
console.log(new Date(minDate.getTime() - 1).toString()); // Invalid Date
_x000D_
For Example Object variable; hastaId
Object hastaId = session.getAttribute("hastaID");
For Example Cast an Object to an int,hastaID
int hastaID=Integer.parseInt(String.valueOf(hastaId));
There's several ways to do it, depending on your intent.
thisSession.hasOwnProperty('merchant_id');
will tell you if thisSession has that key itself (i.e. not something it inherits from elsewhere)
"merchant_id" in thisSession
will tell you if thisSession has the key at all, regardless of where it got it.
thisSession["merchant_id"]
will return false if the key does not exist, or if its value evaluates to false for any reason (e.g. if it's a literal false
or the integer 0 and so on).
try this
df.rename(columns={ df.columns[1]: "your value" }, inplace = True)
This is the Method to get contact list Name and Number
private void getAllContacts() {
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
null);
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//At here You can add phoneNUmber and Name to you listView ,ModelClass,Recyclerview
phoneCursor.close();
}
}
}
}
}
}
In the root open the .editorconfig file and change:
end_of_line = lf
to
end_of_line = auto
This should fix it for new files.
Use String#replace()
.
To replace them with spaces (as per your question title):
System.out.println("I don't like these \"double\" quotes".replace("\"", " "));
The above can also be done with characters:
System.out.println("I don't like these \"double\" quotes".replace('"', ' '));
To remove them (as per your example):
System.out.println("I don't like these \"double\" quotes".replace("\"", ""));
try:
SELECT * FROM service s WHERE s.service_id = ?;
IF @@ROWCOUNT=0
BEGIN
PRINT 'no rows!'
END
about this specific issue:
12:35:23 [mysql] Found Path: "C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld" --defaults-file="C:\Program Files\MySQL\MySQL Server 5.5\my.ini" MySQL
12:35:23 [mysql] Expected Path: c:\xampp\mysql\bin\mysqld.exe --defaults-file=c:\xampp\mysql\bin\my.ini mysql
notice that .exe is missing from 1st row at the end of mysqld.
To fix this, start regedit.exe and change
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\mysql
ImagePath
by adding the .exe extension.
Restart xampp control panel and this error should not show up.
Here is an option. This is just for the x coordinates.
var div1Pos = $("#div1").offset();
var div1X = div1Pos.left;
$('#div2').css({left: div1X});
From arrays
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.
So in the case of a String array, once you create it with some length, you can't modify it, but you can add elements until you fill it.
String[] arr = new String[10]; // 10 is the length of the array.
arr[0] = "kk";
arr[1] = "pp";
...
So if your requirement is to add many objects, it's recommended that you use Lists like:
List<String> a = new ArrayList<String>();
a.add("kk");
a.add("pp");
It's actually quite simple. Go to the font on Google's website, and add its link to the head of every page you want to include the font.
Tested on Firefox 46 and Chrome 49 using this code.
input:focus, textarea:focus, button:focus {
outline: none !important;
}
Before (white dots are visible )
After ( White dots are invisible )
If you want to apply only on few input fields, buttons etc. Use the more specific code.
input[type=text] {
outline: none !important;
}
Happy Coding!!
I'd print out the result of an2.getNodeName()
as well for debugging purposes. My guess is that your tree crawling code isn't crawling to the nodes that you think it is. That suspicion is enhanced by the lack of checking for node names in your code.
Other than that, the javadoc for Node defines "getNodeValue()" to return null for Nodes of type Element. Therefore, you really should be using getTextContent(). I'm not sure why that wouldn't give you the text that you want.
Perhaps iterate the children of your tag node and see what types are there?
Tried this code and it works for me:
String xml = "<add job=\"351\">\n" +
" <tag>foobar</tag>\n" +
" <tag>foobar2</tag>\n" +
"</add>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
Document doc = db.parse(bis);
Node n = doc.getFirstChild();
NodeList nl = n.getChildNodes();
Node an,an2;
for (int i=0; i < nl.getLength(); i++) {
an = nl.item(i);
if(an.getNodeType()==Node.ELEMENT_NODE) {
NodeList nl2 = an.getChildNodes();
for(int i2=0; i2<nl2.getLength(); i2++) {
an2 = nl2.item(i2);
// DEBUG PRINTS
System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):");
if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getTextContent());
if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getNodeValue());
System.out.println(an2.getTextContent());
System.out.println(an2.getNodeValue());
}
}
}
Output was:
#text: type (3): foobar foobar
#text: type (3): foobar2 foobar2
It's not possible with CSS3. There is a proposed CSS4 selector, $
, to do just that, which could look like this (Selecting the li
element):
ul $li ul.sub { ... }
See the list of CSS4 Selectors here.
As an alternative, with jQuery, a one-liner you could make use of would be this:
$('ul li:has(ul.sub)').addClass('has_sub');
You could then go ahead and style the li.has_sub
in your CSS.
If your string will always be of that format, a regex is overkill:
>>> var g='{getThis}';
>>> g.substring(1,g.length-1)
"getThis"
substring(1
means to start one character in (just past the first {
) and ,g.length-1)
means to take characters until (but not including) the character at the string length minus one. This works because the position is zero-based, i.e. g.length-1
is the last position.
For readers other than the original poster: If it has to be a regex, use /{([^}]*)}/
if you want to allow empty strings, or /{([^}]+)}/
if you want to only match when there is at least one character between the curly braces. Breakdown:
/
: start the regex pattern
{
: a literal curly brace
(
: start capturing
[
: start defining a class of characters to capture
^}
: "anything other than }
"]
: OK, that's our whole class definition*
: any number of characters matching that class we just defined)
: done capturing}
: a literal curly brace must immediately follow what we captured/
: end the regex pattern$('#someid').attr('disabled', 'true');
The local branches and their remotes.
git branch -vv
All branches and tracking remotes.
git branch -a -vv
See where the local branches are explicitly configured for push and pull.
git remote show {remote_name}
For windows. if Ctrl+p doesn't always work use Ctrl+shift+n instead.
For playing sound in java, you can refer to the following code.
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
import javax.swing.*;
// To play sound using Clip, the process need to be alive.
// Hence, we use a Swing application.
public class SoundClipTest extends JFrame {
public SoundClipTest() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Test Sound Clip");
this.setSize(300, 200);
this.setVisible(true);
try {
// Open an audio input stream.
URL url = this.getClass().getClassLoader().getResource("gameover.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new SoundClipTest();
}
}
Issue: 'id1' is missing in props validation, eslintreact/prop-types
<div id={props.id1} >
...
</div>
Below solution worked, in a function component:
let { id1 } = props;
<div id={id1} >
...
</div>
Hope that helps.
You can always abuse the fact that duplicated keys are overwritten. This is what I just wrote:
"dependencies": {
"grunt": "...",
"grunt-cli": "...",
"api-easy": "# Here is the pull request: https://github.com/...",
"api-easy": "git://..."
"grunt-vows": "...",
"vows": "..."
}
However, it is not clear whether JSON allows duplicated keys (see Does JSON syntax allow duplicate keys in an object?. It seems to work with npm, so I take the risk.
The recommened hack is to use "//"
keys (from the nodejs mailing list). When I tested it, it did not work with "dependencies" sections, though. Also, the example in the post uses multiple "//"
keys, which implies that npm does not reject JSON files with duplicated keys. In other words, the hack above should always be fine.
Update: One annoying disadvantage of the duplicated key hack is that npm install --save
silently eliminates all duplicates. Unfortunately, it is very easy to overlook it and your well-intentioned comments are gone.
The "//"
hack is still the safest as it seems. However, multi-line comments will be removed by npm install --save
, too.
Current route properties are present in this.$route
, this.$router
is the instance of router object which gives the configuration of the router. You can get the current route query using this.$route.query
nchar is fixed-length and can hold unicode characters. it uses two bytes storage per character.
varchar is of variable length and cannot hold unicode characters. it uses one byte storage per character.
To add to this epic saga of a thread...
My view controller had an attribution above it: @objc(TheNameOfMyViewController)
This made all the Outlets crash with "not key value compliant" error for each Outlet. This was only an issue on IOS12 and below. It worked fine on iOS 13.
Removing that modifier fixed this problem. All the outlets are working fine now.
For @atari2600, this is what the answer would look like using ToLookup in lambda syntax:
var x = listOfCustomObjects
.GroupBy(o => o.PropertyName)
.ToLookup(customObject => customObject);
Basically, it takes the IGrouping and materializes it for you into a dictionary of lists, with the values of PropertyName as the key.
select phone, phone2 from jewishyellow.users
where phone like '813%' and phone2 is not null
I faced the same issue:
E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation
I resolved by using the following commands:
apt-get update
apt-get install gnupg
If you are using SDK 28 or higher, you need to migrate to AndroidX library.
With Android Studio 3.2 and higher, you can migrate an existing project to AndroidX by selecting Refactor > Migrate to AndroidX from the menu bar.
This problem happens because you are calling fun.cpp
instead of fun.hpp
. So c++ compiler finds func.cpp definition twice and throws this error.
Change line 3 of your main.cpp
file, from #include "fun.cpp"
to #include "fun.hpp"
.
querystring can help.
So, you can
const querystring = require('querystring')
url += '?' + querystring.stringify(parameters)
Use ORACLE equivalent of getdate()
which is sysdate
. Read about here.
Getdate() belongs to SQL Server , will not work on Oracle.
Other option is current_date
"cell one","cell "" two","cell "" ,three"
Save this to csv file and see the results, so double quote is used to escape itself
Important Note
"cell one","cell "" two", "cell "" ,three"
will give you a different result because there is a space after the comma, and that will be treated as "
There are many ways to update the rows.
When it comes to UPDATE
the rows using subqueries, you can use any of these approaches.
UPDATE
<table1>
SET
customer=<table2>.customer,
address=<table2>.address,
partn=<table2>.partn
FROM
<table2>
WHERE
<table1>.address_id=<table2>.address_i;
Explanation:
table1
is the table which we want to update,table2
is the table, from which we'll get the value to be replaced/updated. We are usingFROM
clause, to fetch thetable2
's data.WHERE
clause will help to set the proper data mapping.
UPDATE
<table1>
SET
customer=subquery.customer,
address=subquery.address,
partn=subquery.partn
FROM
(
SELECT
address_id, customer, address, partn
FROM /* big hairy SQL */ ...
) AS subquery
WHERE
dummy.address_id=subquery.address_id;
Explanation: Here we are using subquerie inside the
FROM
clause, and giving an alias to it. So that it will act like the table.
UPDATE
<table1>
SET
customer=<table2>.customer,
address=<table2>.address,
partn=<table2>.partn
FROM
<table2> as t2
JOIN <table3> as t3
ON
t2.id = t3.id
WHERE
<table1>.address_id=<table2>.address_i;
Explanation: Sometimes we face the situation in that table join is so important to get proper data for the update. To do so, Postgres allows us to Join multiple tables inside the
FROM
clause.
Approach-4 [Using WITH statement]
WITH subquery AS (
SELECT
address_id,
customer,
address,
partn
FROM
<table1>;
)
UPDATE <table-X>
SET customer = subquery.customer,
address = subquery.address,
partn = subquery.partn
FROM subquery
WHERE <table-X>.address_id = subquery.address_id;
WITH subquery AS (
SELECT address_id, customer, address, partn
FROM
<table1> as t1
JOIN
<table2> as t2
ON
t1.id = t2.id;
-- You can build as COMPLEX as this query as per your need.
)
UPDATE <table-X>
SET customer = subquery.customer,
address = subquery.address,
partn = subquery.partn
FROM subquery
WHERE <table-X>.address_id = subquery.address_id;
Explanation: From Postgres 9.1, this(
WITH
) concept has been introduces. Using that We can make any complex queries and generate desire result. Here we are using this approach to update the table.
I hope, this would be helpful.
Who says a file name needs an extension?? take a look on a *nix machine sometime...
I agree with your friend, no trailing slash.
To elaborate on https://stackoverflow.com/a/59311063/1328979, here is a fully documented, annotated and tested Python 3 implementation for the general case.
from __future__ import annotations # To allow "MinHeap.push -> MinHeap:"
from typing import Generic, List, Optional, TypeVar
from heapq import heapify, heappop, heappush, heapreplace
T = TypeVar('T')
class MinHeap(Generic[T]):
'''
MinHeap provides a nicer API around heapq's functionality.
As it is a minimum heap, the first element of the heap is always the
smallest.
>>> h = MinHeap([3, 1, 4, 2])
>>> h[0]
1
>>> h.peek()
1
>>> h.push(5) # N.B.: the array isn't always fully sorted.
[1, 2, 4, 3, 5]
>>> h.pop()
1
>>> h.pop()
2
>>> h.pop()
3
>>> h.push(3).push(2)
[2, 3, 4, 5]
>>> h.replace(1)
2
>>> h
[1, 3, 4, 5]
'''
def __init__(self, array: Optional[List[T]] = None):
if array is None:
array = []
heapify(array)
self.h = array
def push(self, x: T) -> MinHeap:
heappush(self.h, x)
return self # To allow chaining operations.
def peek(self) -> T:
return self.h[0]
def pop(self) -> T:
return heappop(self.h)
def replace(self, x: T) -> T:
return heapreplace(self.h, x)
def __getitem__(self, i) -> T:
return self.h[i]
def __len__(self) -> int:
return len(self.h)
def __str__(self) -> str:
return str(self.h)
def __repr__(self) -> str:
return str(self.h)
class Reverse(Generic[T]):
'''
Wrap around the provided object, reversing the comparison operators.
>>> 1 < 2
True
>>> Reverse(1) < Reverse(2)
False
>>> Reverse(2) < Reverse(1)
True
>>> Reverse(1) <= Reverse(2)
False
>>> Reverse(2) <= Reverse(1)
True
>>> Reverse(2) <= Reverse(2)
True
>>> Reverse(1) == Reverse(1)
True
>>> Reverse(2) > Reverse(1)
False
>>> Reverse(1) > Reverse(2)
True
>>> Reverse(2) >= Reverse(1)
False
>>> Reverse(1) >= Reverse(2)
True
>>> Reverse(1)
1
'''
def __init__(self, x: T) -> None:
self.x = x
def __lt__(self, other: Reverse) -> bool:
return other.x.__lt__(self.x)
def __le__(self, other: Reverse) -> bool:
return other.x.__le__(self.x)
def __eq__(self, other) -> bool:
return self.x == other.x
def __ne__(self, other: Reverse) -> bool:
return other.x.__ne__(self.x)
def __ge__(self, other: Reverse) -> bool:
return other.x.__ge__(self.x)
def __gt__(self, other: Reverse) -> bool:
return other.x.__gt__(self.x)
def __str__(self):
return str(self.x)
def __repr__(self):
return str(self.x)
class MaxHeap(MinHeap):
'''
MaxHeap provides an implement of a maximum-heap, as heapq does not provide
it. As it is a maximum heap, the first element of the heap is always the
largest. It achieves this by wrapping around elements with Reverse,
which reverses the comparison operations used by heapq.
>>> h = MaxHeap([3, 1, 4, 2])
>>> h[0]
4
>>> h.peek()
4
>>> h.push(5) # N.B.: the array isn't always fully sorted.
[5, 4, 3, 1, 2]
>>> h.pop()
5
>>> h.pop()
4
>>> h.pop()
3
>>> h.pop()
2
>>> h.push(3).push(2).push(4)
[4, 3, 2, 1]
>>> h.replace(1)
4
>>> h
[3, 1, 2, 1]
'''
def __init__(self, array: Optional[List[T]] = None):
if array is not None:
array = [Reverse(x) for x in array] # Wrap with Reverse.
super().__init__(array)
def push(self, x: T) -> MaxHeap:
super().push(Reverse(x))
return self
def peek(self) -> T:
return super().peek().x
def pop(self) -> T:
return super().pop().x
def replace(self, x: T) -> T:
return super().replace(Reverse(x)).x
if __name__ == '__main__':
import doctest
doctest.testmod()
https://gist.github.com/marccarre/577a55850998da02af3d4b7b98152cf4
I ran across this question and I thought I'd provide an update on this topic. jQuery (v1.5+) includes a Deferred
model, which (despite not adhering to the Promises/A spec until jQuery 3) is generally regarded as being a clearer way to approach many asynchronous problems. Implementing a $.wait()
method using this approach is particularly readable I believe:
$.wait = function(ms) {
var defer = $.Deferred();
setTimeout(function() { defer.resolve(); }, ms);
return defer;
};
And here's how you can use it:
$.wait(5000).then(disco);
However if, after pausing, you only wish to perform actions on a single jQuery selection, then you should be using jQuery's native .delay()
which I believe also uses Deferred's under the hood:
$(".my-element").delay(5000).fadeIn();
This is one of those things that are missing. Your best bet is to create your own custom Navigation Bar, add a text box, and manipulate the color that way.
The concept of interval notation comes up in both Mathematics and Computer Science. The Mathematical notation [
, ]
, (
, )
denotes the domain (or range) of an interval.
The brackets [
and ]
means:
The parenthesis (
and )
means:
An interval with mixed states is called "half-open".
For example, the range of consecutive integers from 1 .. 10 (inclusive) would be notated as such:
Notice how the word inclusive
was used. If we want to exclude the end point but "cover" the same range we need to move the end-point:
For both left and right edges of the interval there are actually 4 permutations:
(1,10) = 2,3,4,5,6,7,8,9 Set has 8 elements
(1,10] = 2,3,4,5,6,7,8,9,10 Set has 9 elements
[1,10) = 1,2,3,4,5,6,7,8,9 Set has 9 elements
[1,10] = 1,2,3,4,5,6,7,8,9,10 Set has 10 elements
How does this relate to Mathematics and Computer Science?
Array indexes tend to use a different offset depending on which field are you in:
These differences can lead to subtle fence post errors, aka, off-by-one bugs when implementing Mathematical algorithms such as for-loops.
If we have a set or array, say of the first few primes [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ]
, Mathematicians would refer to the first element as the 1st
absolute element. i.e. Using subscript notation to denote the index:
Some programming languages, in contradistinction, would refer to the first element as the zero'th
relative element.
Since the array indexes are in the range [0,N-1] then for clarity purposes it would be "nice" to keep the same numerical value for the range 0 .. N instead of adding textual noise such as a -1
bias.
For example, in C or JavaScript, to iterate over an array of N elements a programmer would write the common idiom of i = 0, i < N
with the interval [0,N) instead of the slightly more verbose [0,N-1]:
function main() {_x000D_
var output = "";_x000D_
var a = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ];_x000D_
for( var i = 0; i < 10; i++ ) // [0,10)_x000D_
output += "[" + i + "]: " + a[i] + "\n";_x000D_
_x000D_
if (typeof window === 'undefined') // Node command line_x000D_
console.log( output )_x000D_
else_x000D_
document.getElementById('output1').innerHTML = output;_x000D_
}
_x000D_
<html>_x000D_
<body onload="main();">_x000D_
<pre id="output1"></pre>_x000D_
</body>_x000D_
</html>
_x000D_
Mathematicians, since they start counting at 1, would instead use the i = 1, i <= N
nomenclature but now we need to correct the array offset in a zero-based language.
e.g.
function main() {_x000D_
var output = "";_x000D_
var a = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ];_x000D_
for( var i = 1; i <= 10; i++ ) // [1,10]_x000D_
output += "[" + i + "]: " + a[i-1] + "\n";_x000D_
_x000D_
if (typeof window === 'undefined') // Node command line_x000D_
console.log( output )_x000D_
else_x000D_
document.getElementById( "output2" ).innerHTML = output;_x000D_
}
_x000D_
<html>_x000D_
<body onload="main()";>_x000D_
<pre id="output2"></pre>_x000D_
</body>_x000D_
</html>
_x000D_
Aside:
In programming languages that are 0-based you might need a kludge of a dummy zero'th element to use a Mathematical 1-based algorithm. e.g. Python Index Start
Interval notation is also important for floating-point numbers to avoid subtle bugs.
When dealing with floating-point numbers especially in Computer Graphics (color conversion, computational geometry, animation easing/blending, etc.) often times normalized numbers are used. That is, numbers between 0.0 and 1.0.
It is important to know the edge cases if the endpoints are inclusive or exclusive:
Where M is some machine epsilon. This is why you might sometimes see const float EPSILON = 1e-#
idiom in C code (such as 1e-6
) for a 32-bit floating point number. This SO question Does EPSILON guarantee anything? has some preliminary details. For a more comprehensive answer see FLT_EPSILON
and David Goldberg's What Every Computer Scientist Should Know About Floating-Point Arithmetic
Some implementations of a random number generator, random()
may produce values in the range 0.0 .. 0.999... instead of the more convenient 0.0 .. 1.0. Proper comments in the code will document this as [0.0,1.0) or [0.0,1.0] so there is no ambiguity as to the usage.
Example:
random()
colors. You convert three floating-point values to unsigned 8-bit values to generate a 24-bit pixel with red, green, and blue channels respectively. Depending on the interval output by random()
you may end up with near-white
(254,254,254) or white
(255,255,255). +--------+-----+
|random()|Byte |
|--------|-----|
|0.999...| 254 | <-- error introduced
|1.0 | 255 |
+--------+-----+
For more details about floating-point precision and robustness with intervals see Christer Ericson's Real-Time Collision Detection, Chapter 11 Numerical Robustness, Section 11.3 Robust Floating-Point Usage.
I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.
For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:
curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>
Note that j_username
and j_password
is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case.
After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:
curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>
This SO question is missing the following approach :
-- List down all columns of table 'Logging'
select * from sys.all_columns where object_id = OBJECT_ID('Logging')
Firstly you need to change credentials from your local machine
git config [--global] user.name "Your Name"
git config [--global] user.email "[email protected]"
It depends on what you define as the difference. To compare two dates at midnight you can do.
long day1 = ...; // in milliseconds.
long day2 = ...; // in milliseconds.
long days = (day2 - day1) / 86400000;
RxJS 6
When upgrading to version 6 of the RxJS
library and not using the rxjs-compat
package the following code
import 'rxjs/add/observable/of';
// ...
return Observable.of(res);
has to be changed into
import { of } from 'rxjs';
// ...
return of(res);
I was looking for an answer to find the "blah" name and not its value (not the text). base on @Manu (@Mano)answer I find this code useful:
public enum Blah {
A("text1"),
B("text2"),
C("text3"),
D("text4");
private String text;
Blah(String text) {
this.text = text;
}
public String getText() {
return this.text;
}
public static Blah valueOfCode(String blahCode) throws IllegalArgumentException {
Blah blah = Arrays.stream(Blah.values())
.filter(val -> val.name().equals(blahCode))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unable to resolve blah : " + blahCode));
return blah;
}
}
i accomplished this with the install
command on linux:
root@logstash:# myfile=bash_history.log.2021-02-04.gz ; install -v -p -D $myfile /tmp/a/b/$myfile
bash_history.log.2021-02-04.gz -> /tmp/a/b/bash_history.log.2021-02-04.gz
the only downside being the file permissions are changed:
root@logstash:# ls -lh /tmp/a/b/
-rwxr-xr-x 1 root root 914 Fev 4 09:11 bash_history.log.2021-02-04.gz
if you dont mind resetting the permission, you can use:
-g, --group=GROUP set group ownership, instead of process' current group
-m, --mode=MODE set permission mode (as in chmod), instead of rwxr-xr-x
-o, --owner=OWNER set ownership (super-user only)
As per this article, it's not. The article also argues that it's not a good idea to make it one.
To quote from one of the comments:
So, I do not believe that CSS is turing complete. There is no capability to define a function in CSS. In order for a system to be turing-complete it has to be possible to write an interpreter: a function that interprets expressions that denote programs to execute. CSS has no variables that are directly accessible to the user; so you cannot even model the structure that represents the program to be interpreted in CSS.
.query
with Pandas >= 0.25.0:August 2019 updated answer
Since Pandas >= 0.25.0 we can use the query
method to filter dataframes with Pandas methods and even column names which have spaces. Normally the spaces in column names would give an error, but now we can solve that using a backtick (`) - see GitHub:
# Example dataframe
df = pd.DataFrame({'Sender email':['[email protected]', "[email protected]", "[email protected]"]})
Sender email
0 [email protected]
1 [email protected]
2 [email protected]
Using .query
with method str.endswith
:
df.query('`Sender email`.str.endswith("@shop.com")')
Output
Sender email
1 [email protected]
2 [email protected]
Also we can use local variables by prefixing it with an @
in our query:
domain = 'shop.com'
df.query('`Sender email`.str.endswith(@domain)')
Output
Sender email
1 [email protected]
2 [email protected]
With query syntax:
var values =
from inner in outer
from value in inner
select value;
Doesn't have to be; "64-bit machine" can mean many things, but typically means that the CPU has registers that big. The sizeof a type is determined by the compiler, which doesn't have to have anything to do with the actual hardware (though it typically does); in fact, different compilers on the same machine can have different values for these.
I solved it by adding this to the /etc/profile - system wide (or to user local .profile, or _.bash_profile_):
# SSH-AGENT
#!/usr/bin/env bash
SERVICE='ssh-agent'
WHOAMI=`who am i |awk '{print $1}'`
if pgrep -u $WHOAMI $SERVICE >/dev/null
then
echo $SERVICE running.
else
echo $SERVICE not running.
echo starting
ssh-agent > ~/.ssh/agent_env
fi
. ~/.ssh/agent_env
This starts a new ssh-agent if not running for the current user, or re-sets the ssh-agent env parameter if running.
(Side notes too big for a Comment)
There is no need for an AUTO_INCREMENT
id in a mapping table; get rid of it.
Change the PRIMARY KEY
to (role_id, role_group_id)
(in either order). This will make accesses faster.
Since you probably want to map both directions, also add an INDEX
with those two columns in the opposite order. (There is no need to make it UNIQUE
.)
More tips: http://mysql.rjweb.org/doc.php/index_cookbook_mysql#speeding_up_wp_postmeta
This is a simple way to show a spinner that does not require a third-party library, intercepters, or jQuery.
In the controller, set and reset a flag.
function starting() {
//ADD SPINNER
vm.starting = true;
$http.get(url)
.then(function onSuccess(response) {
vm.data = response.data;
}).catch(function onReject(errorResponse) {
console.log(errorResponse.status);
}).finally(function() {
//REMOVE SPINNER
vm.starting = false;
});
};
In the HTML, use the flag:
<div ng-show="vm.starting">
<img ng-src="spinnerURL" />
</div>
<div ng-hide="vm.starting">
<p>{{vm.data}}</p>
</div>
The vm.starting
flag is set true
when the XHR starts and cleared when the XHR completes.
If your are using android studio go to file >> project structure on the left pane press on SDK location . you will find the path where your sdk is located
Python offers you the ability to do some of the things you could do with a goto using first class functions. For example:
void somefunc(int a)
{
if (a == 1)
goto label1;
if (a == 2)
goto label2;
label1:
...
label2:
...
}
Could be done in python like this:
def func1():
...
def func2():
...
funcmap = {1 : func1, 2 : func2}
def somefunc(a):
funcmap[a]() #Ugly! But it works.
Granted, that isn't the best way to substitute for goto. But without knowing exactly what you're trying to do with the goto, it's hard to give specific advice.
@ascobol:
Your best bet is to either enclose it in a function or use an exception. For the function:
def loopfunc():
while 1:
while 1:
if condition:
return
For the exception:
try:
while 1:
while 1:
raise BreakoutException #Not a real exception, invent your own
except BreakoutException:
pass
Using exceptions to do stuff like this may feel a bit awkward if you come from another programming language. But I would argue that if you dislike using exceptions, Python isn't the language for you. :-)
Using Jest, you can do it like this:
test('it calls start logout on button click', () => {
const mockLogout = jest.fn();
const wrapper = shallow(<Component startLogout={mockLogout}/>);
wrapper.find('button').at(0).simulate('click');
expect(mockLogout).toHaveBeenCalled();
});
I do like this for list items in <menu> elements. Consider the following markup:
<menu>
<li><a href="/member/profile">Profile</a></li>
<li><a href="/member/options">Options</a></li>
<li><a href="/member/logout">Logout</a></li>
</menu>
I style it with the following CSS:
menu > li {
display: inline;
}
menu > li::after {
content: ' | ';
}
menu > li:last-child::after {
content: '';
}
This will display:
Profile | Options | Logout
And this is possible because of what Martin Atkins explained on his comment
Note that in CSS 2 you would use :after
, not ::after
. If you use CSS 3, use ::after
(two semi-columns) because ::after
is a pseudo-element (a single semi-column is for pseudo-classes).
Try this function from stringi
package
require(stringi)
> s <- c("Lorem ipsum dolor sit amet, consectetur adipisicing elit.",
+ "nibh augue, suscipit a, scelerisque sed, lacinia in, mi.",
+ "Cras vel lorem. Etiam pellentesque aliquet tellus.",
+ "")
> stri_stats_latex(s)
CharsWord CharsCmdEnvir CharsWhite Words Cmds Envirs
133 0 30 24 0 0
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.
See my other Answer using the industry-leading java.time classes.
Normally we consider it bad form on StackOverflow.com to answer a specific question by suggesting an alternate technology. But in the case of the date, time, and calendar classes bundled with Java 7 and earlier, those classes are so notoriously bad in both design and execution that I am compelled to suggest using a 3rd-party library instead: Joda-Time.
Joda-Time works by creating immutable objects. So rather than alter the time zone of a DateTime object, we simply instantiate a new DateTime with a different time zone assigned.
Your central concern of using both local and UTC time is so very simple in Joda-Time, taking just 3 lines of code.
org.joda.time.DateTime now = new org.joda.time.DateTime();
System.out.println( "Local time in ISO 8601 format: " + now + " in zone: " + now.getZone() );
System.out.println( "UTC (Zulu) time zone: " + now.toDateTime( org.joda.time.DateTimeZone.UTC ) );
Output when run on the west coast of North America might be:
Local time in ISO 8601 format: 2013-10-15T02:45:30.801-07:00
UTC (Zulu) time zone: 2013-10-15T09:45:30.801Z
Here is a class with several examples and further comments. Using Joda-Time 2.5.
/**
* Created by Basil Bourque on 2013-10-15.
* © Basil Bourque 2013
* This source code may be used freely forever by anyone taking full responsibility for doing so.
*/
public class TimeExample {
public static void main(String[] args) {
// Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 8 and earlier.
// http://www.joda.org/joda-time/
// Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
// JSR 310 was inspired by Joda-Time but is not directly based on it.
// http://jcp.org/en/jsr/detail?id=310
// By default, Joda-Time produces strings in the standard ISO 8601 format.
// https://en.wikipedia.org/wiki/ISO_8601
// You may output to strings in other formats.
// Capture one moment in time, to be used in all the examples to follow.
org.joda.time.DateTime now = new org.joda.time.DateTime();
System.out.println( "Local time in ISO 8601 format: " + now + " in zone: " + now.getZone() );
System.out.println( "UTC (Zulu) time zone: " + now.toDateTime( org.joda.time.DateTimeZone.UTC ) );
// You may specify a time zone in either of two ways:
// • Using identifiers bundled with Joda-Time
// • Using identifiers bundled with Java via its TimeZone class
// ----| Joda-Time Zones |---------------------------------
// Time zone identifiers defined by Joda-Time…
System.out.println( "Time zones defined in Joda-Time : " + java.util.Arrays.toString( org.joda.time.DateTimeZone.getAvailableIDs().toArray() ) );
// Specify a time zone using DateTimeZone objects from Joda-Time.
// http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTimeZone.html
org.joda.time.DateTimeZone parisDateTimeZone = org.joda.time.DateTimeZone.forID( "Europe/Paris" );
System.out.println( "Paris France (Joda-Time zone): " + now.toDateTime( parisDateTimeZone ) );
// ----| Java Zones |---------------------------------
// Time zone identifiers defined by Java…
System.out.println( "Time zones defined within Java : " + java.util.Arrays.toString( java.util.TimeZone.getAvailableIDs() ) );
// Specify a time zone using TimeZone objects built into Java.
// http://docs.oracle.com/javase/8/docs/api/java/util/TimeZone.html
java.util.TimeZone parisTimeZone = java.util.TimeZone.getTimeZone( "Europe/Paris" );
System.out.println( "Paris France (Java zone): " + now.toDateTime(org.joda.time.DateTimeZone.forTimeZone( parisTimeZone ) ) );
}
}
if (strstr($_SERVER['REQUEST_URI'],'index.php')){
header('HTTP/1.0 404 Not Found');
echo "<h1>404 Not Found</h1>";
echo "The page that you have requested could not be found.";
exit();
}
If you look at the last two echo lines, that's where you'll see the content. You can customize it however you want.
The m2e plugin uses it's own distribution of Maven, packaged with the plugin.
In order to use Maven from command line, you need to have it installed as a standalone application. Here is an instruction explaining how to do it in Windows
Once Maven is properly installed (i.e. be sure that MAVEN_HOME
, JAVA_HOME
and PATH
variables are set correctly): you must run mvn eclipse:eclipse
from the directory containing the pom.xml
.
Using below query you can remove leading and trailing whitespace in a MySQL.
UPDATE `table_name`
SET `col_name` = TRIM(`col_name`);
Use a slice, not an arrray. Just create it using
reg := []string {"a","b","c"}
An alternative would have been to convert your array to a slice when joining :
fmt.Println(strings.Join(reg[:],","))
Read the Go blog about the differences between slices and arrays.
The method you want is BigInteger#valueOf(long val).
E.g.,
BigInteger bi = BigInteger.valueOf(myInteger.intValue());
Making a String first is unnecessary and undesired.
There is no default database for user. There is default database for current session.
You can get it using DATABASE() function -
SELECT DATABASE();
And you can set it using USE statement -
USE database1;
You should set it manually - USE db_name
, or in the connection string.
I am assuming you are using Eclipse as your developing environment.
Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.
Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.
The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error
Here is sample usage using expect
:
#!/usr/bin/expect
set timeout 360
spawn my_command # Replace with your command.
expect "Do you want to continue?" { send "\r" }
Check: man expect
for further information.
One way of achieving this behaviour is by setting the value to _id
(which is reserved for a primary key in MongoDB) field based on the custom fields you want to treat as primary key.
i.e. If I want employee_id
as the primary key then at the time of creating document in MongoDB; assign _id
value same as that of employee_id
.
1)event.stopPropagation():
=>It is used to stop executions of its corresponding parent handler only.
2) event.stopImmediatePropagation():
=> It is used to stop the execution of its corresponding parent handler and also handler or function attached to itself except the current handler.
=> It also stops all the handler attached to the current element of entire DOM.
Here is the example: Jsfiddle!
Thanks, -Sahil
It's not possible to do multi-shot playing with a single <audio>
element. You need to use multiple elements for this.
You should be aware that values of fields could contain commas and quotation characters, so some of the suggested answers would not work, as the CSV output file would not be correct. To replace quotation characters in a field, and replace it with the double quotation character, you can use the REPLACE function that oracle provides, to change a single quote to double quote.
set echo off
set heading off
set feedback off
set linesize 1024 -- or some other value, big enough
set pagesize 50000
set verify off
set trimspool on
spool output.csv
select trim(
'"' || replace(col1, '"', '""') ||
'","' || replace(col2, '"', '""') ||
'","' || replace(coln, '"', '""') || '"' ) -- etc. for all the columns
from yourtable
/
spool off
Or, if you want the single quote character for the fields:
set echo off
set heading off
set feedback off
set linesize 1024 -- or some other value, big enough
set pagesize 50000
set verify off
set trimspool on
spool output.csv
select trim(
'"' || replace(col1, '''', '''''') ||
'","' || replace(col2, '''', '''''') ||
'","' || replace(coln, '''', '''''') || '"' ) -- etc. for all the columns
from yourtable
/
spool off
In my case, I had to do the following while running with Junit5
@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class
Here abc.class was the class that was being tested
I think it works the other way
<#if object.attribute??>
Do whatever you want....
</#if>
If object.attribute
is NOT NULL, then the content will be printed.
The SQL is somewhat like the syntax of MS SQL.
SELECT * FROM [table$] WHERE *;
It is important that the table name is ended with a $ sign and the whole thing is put into brackets. As conditions you can use any value, but so far Excel didn't allow me to use what I call "SQL Apostrophes" (´), so a column title in one word is recommended.
If you have users listed in a table called "Users", and the id is in a column titled "id" and the name in a column titled "Name", your query will look like this:
SELECT Name FROM [Users$] WHERE id = 1;
Hope this helps.
angle(vector.b,vector.a)=pi/2*((1+sgn(xa))*(1-sgn(ya^2))-(1+sgn(xb))*(1-sgn(yb^2)))
+pi/4*((2+sgn(xa))*sgn(ya)-(2+sgn(xb))*sgn(yb))
+sgn(xa*ya)*atan((abs(xa)-abs(ya))/(abs(xa)+abs(ya)))
-sgn(xb*yb)*atan((abs(xb)-abs(yb))/(abs(xb)+abs(yb)))
xb,yb and xa,ya are the coordinates of the two vectors
You can use this to continue using the type Date and a more legible code, if you preffer:
import org.apache.commons.lang.time.DateUtils;
...
Date yourDate = DateUtils.addDays(new Date(), *days here*);
var boxSummary = from b in boxes
group b by b.Owner into g
let nrBoxes = g.Count()
let totalWeight = g.Sum(w => w.Weight)
let totalVolume = g.Sum(v => v.Volume)
select new { Owner = g.Key, Boxes = nrBoxes,
TotalWeight = totalWeight,
TotalVolume = totalVolume }
Mainly If you are using Linux Based system Like 'Ubuntu' and this is only suggested for localhost user not for the server.
Follow all the steps mentioned in the previous answers. +
Check in Apache configuration for it. (AllowOverride All) If AllowOverride value is none then change it to All and restart apache again.
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
Let me know if this step help anyone. As it can save you time if you find it earlier.
I am adding the exact lines from my htaccess file in localhost. for your reference
Around line number 110
<IfModule mod_rewrite.c>
############################################
## enable rewrites
Options +FollowSymLinks
RewriteEngine on
############################################
## you can put here your magento root folder
## path relative to web root
#RewriteBase /
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
Images are for some user who understand easily from image the from the text:
TextInputLayout til = (TextInputLayout)editText.getParent();
til.setErrorEnabled(true);
til.setError("some error..");
Please try once uninstalling from Help-->Installation details
and try again installing using http://dl-ssl.google.com/android/eclipse/
For using dialogs inside activities, do it this way:
private Context mContext;
private AlertDialog.Builder mBuilder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
//using mContext here refering to activity context
mBuilder = new AlertDialog.Builder(mContext);
//...
//rest of the code
//...
}
For using dialogs inside fragments, do it this way:
private Context mContext;
private AlertDialog.Builder mBuilder;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mRootView = inflater.inflate(R.layout.fragment_layout, container, false);
mContext = getActivity();
//using mContext here refering to fragment's hosting activity context
mBuilder = new AlertDialog.Builder(mContext);
//...
//rest of the code
//...
return mRootView;
}
That's it ^_^
When you create database or create tables
You should add that line at top script create database or table
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=1;
Now you want to delete records from table? then you write as
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=1;
DELETE FROM `jobs` WHERE `job_id` =1 LIMIT 1
Good luck!
you can get all product information from following code
$product_id=6//Suppose
$_product=Mage::getModel('catalog/product')->load($product_id);
$product_data["id"]=$_product->getId();
$product_data["name"]=$_product->getName();
$product_data["short_description"]=$_product->getShortDescription();
$product_data["description"]=$_product->getDescription();
$product_data["price"]=$_product->getPrice();
$product_data["special price"]=$_product->getFinalPrice();
$product_data["image"]=$_product->getThumbnailUrl();
$product_data["model"]=$_product->getSku();
$product_data["color"]=$_product->getAttributeText('color'); //get cusom attribute value
$storeId = Mage::app()->getStore()->getId();
$summaryData = Mage::getModel('review/review_summary')->setStoreId($storeId) ->load($_product->getId());
$product_data["rating"]=($summaryData['rating_summary']*5)/100;
$product_data["shipping"]=Mage::getStoreConfig('carriers/flatrate/price');
if($_product->isSalable() ==1)
$product_data["in_stock"]=1;
else
$product_data["in_stock"]=0;
echo "<pre>";
print_r($product_data);
//echo "</pre>";
To really update just one package install NCU and then run it just for that package. This will bump to the real latest.
npm install -g npm-check-updates
ncu -f your-intended-package-name -u
Set the following registry value:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion!EnableLog] (DWORD) to 1
To disable, set to 0 or delete the value.
[edit ]:Save the following text to a file, e.g FusionEnableLog.reg, in Windows Registry Editor Format:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion]
"EnableLog"=dword:00000001
Then run the file from windows explorer and ignore the warning about possible damage.
This will help:
http://www.w3schools.com/tags/att_hr_width.asp
<hr width="50%">
This creates a horizontal line with a width of 50%, you would need to create/modify the class if you would like to edit the style.
You could use sortBy in underscore js.
http://underscorejs.org/#sortBy
Sample:
var log = [{date: '2016-01-16T05:23:38+00:00', other: 'sample'},
{date: '2016-01-13T05:23:38+00:00',other: 'sample'},
{date: '2016-01-15T11:23:38+00:00', other: 'sample'}];
console.log(_.sortBy(log, 'date'));
First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:
raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it
freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level
Then you need to create a data frame out of it, melt it and plot it:
Names=c("Food","Music","People") # create list of names
data=data.frame(cbind(freq),Names) # combine them into a data frame
data=data[,c(5,3,1,2,4)] # sort columns
# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')
# plot everything
ggplot(data.m, aes(Names, value)) +
geom_bar(aes(fill = variable), position = "dodge", stat="identity")
Is this what you're after?
To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:
> head(df)
ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1 1 A 1980 450 338 154 36 13 9
2 2 A 2000 288 407 212 54 16 23
3 3 A 2020 196 434 246 68 19 36
4 4 B 1980 111 326 441 90 21 11
5 5 B 2000 63 298 443 133 42 21
6 6 B 2020 36 257 462 162 55 30
Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape
and plotted.
For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw))
to get this:
> data
Names Very.Bad Bad Good Very.Good
1 Food 7 6 5 2
2 Music 5 5 7 3
3 People 6 3 7 4
Just imagine you have Very.Bad
, Bad
, Good
and so on instead of X1PCE
, X2PCE
, X3PCE
. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw))
.
Try this :
sp_help 'TableName'
SQL Server 2005 or later gives quite a nice report showing table sizes - including row counts etc. It's in Standard Reports - and it is Disc Usage by Table.
Programmatically, there's a nice solution at: http://www.sqlservercentral.com/articles/T-SQL/67624/
This should work for you. Infact the one which you are thinking will also work:-
.......
DECLARE @returnvalue INT
EXEC @returnvalue = SP_One
.....
You can follow this tutorial on how to use Google Maps for testing on localhost.
- Click this link and follow the process (create new project, API key > Browser key, register 'localhost' domain): https://console.developers.google.com//flows/enableapi?apiid=maps_backend&keyType=CLIENT_SIDE&reusekey=true
- Generate the key
- Deploy Google Maps widget as described here: http://www2.microstrategy.com/producthelp/10/GISHelp/Lang_1033/GIS_Integration.htm
- Add your Google Maps API key to googleConfig.xml (as desribed in the previous link) ENTER_YOUR_KEY_HERE
- Restart Web Server
Check these related SO threads:
Hope this helps!
Use these:
webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setDisplayZoomControls(false);
<?php
/**
* Is Array?
* @param mixed $x
* @return bool
*/
function isArray($x) : bool {
return !isAssociative($x);
}
/**
* Is Associative Array?
* @param mixed $x
* @return bool
*/
function isAssociative($x) : bool {
if (!is_array($array)) {
return false;
}
$i = count($array);
while ($i > 0) {
if (!isset($array[--$i])) {
return true;
}
}
return false;
}
<?php
$arr = [ 'foo', 'bar' ];
$obj = [ 'foo' => 'bar' ];
var_dump(isAssociative($arr));
# bool(false)
var_dump(isAssociative($obj));
# bool(true)
var_dump(isArray($obj));
# bool(false)
var_dump(isArray($arr));
# bool(true)
More Suggestion
JavaScript:
$.ajax({
url: "http://FullUrl",
dataType: 'jsonp',
success: function (data) {
//Data from the server in the in the variable "data"
//In the form of an array
}
});
PHP CallBack:
<?php
$array = array(
'0' => array('fullName' => 'Meni Samet', 'fullAdress' => 'New York, NY'),
'1' => array('fullName' => 'Test 2', 'fullAdress' => 'Paris'),
);
if(isset ($_GET['callback']))
{
header("Content-Type: application/json");
echo $_GET['callback']."(".json_encode($array).")";
}
?>
Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)
/etc/squid3/squid.conf
instead of the super bloated default config file
auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
# Choose the port you want. Below we set it to default 3128.
http_port 3128
Please note the basic_ncsa_auth program instead of the old ncsa_auth
For squid 2.x you need to edit /etc/squid/squid.conf
file and place:
auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
sudo htpasswd -c /etc/squid3/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid3 restart
sudo htpasswd -c /etc/squid/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid restart
For the many people that asked me: the 2 tools produce different file formats:
htdigest
stores the password in plain text.htpasswd
stores the password hashed (various hashing algos are available)Despite this difference in format basic_ncsa_auth
will still be able to parse a password file generated with htdigest
. Hence you can alternatively use:
sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like
Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.
On Ubuntu 14.04 htdigest
and htpasswd
are both available in the [apache2-utils][1]
package.
Similar as above applies, but file paths are different.
Install squid
brew install squid
Start squid service
brew services start squid
Squid config file is stored at /usr/local/etc/squid.conf
.
Comment or remove following line:
http_access allow localnet
Then similar to linux config (but with updated paths) add this:
auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
Note that path to basic_ncsa_auth
may be different since it depends on installed version when using brew
, you can verify this with ls /usr/local/Cellar/squid/
. Also note that you should add the above just bellow the following section:
#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#
Now generate yourself a user:password basic auth credential (note: htpasswd
and htdigest
are also both available on MacOS)
htpasswd -c /usr/local/etc/squid_passwords username_you_like
Restart the squid service
brew services restart squid
We can pass multiple parameters with var_dump like:
var_dump("array1",$array1,"array2",$array2);
If you have boarder field 5*5 for examle, I used next method of checking:
public static boolean checkWin(char symb) {
int SIZE = 5;
for (int i = 0; i < SIZE-1; i++) {
for (int j = 0; j <SIZE-1 ; j++) {
//vertical checking
if (map[0][j] == symb && map[1][j] == symb && map[2][j] == symb && map[3][j] == symb && map[4][j] == symb) return true; // j=0
}
//horisontal checking
if(map[i][0] == symb && map[i][1] == symb && map[i][2] == symb && map[i][3] == symb && map[i][4] == symb) return true; // i=0
}
//diagonal checking (5*5)
if (map[0][0] == symb && map[1][1] == symb && map[2][2] == symb && map[3][3] == symb && map[4][4] == symb) return true;
if (map[4][0] == symb && map[3][1] == symb && map[2][2] == symb && map[1][3] == symb && map[0][4] == symb) return true;
return false;
}
I think, it's more clear, but probably is not the most optimal way.
$(document).ready(function() {
$('meta[property="og:title"]').remove();
$('meta[property="og:description"]').remove();
$('meta[property="og:url"]').remove();
$("head").append('<meta property="og:title" content="blubb1">');
$("head").append('<meta property="og:description" content="blubb2">');
$("head").append('<meta property="og:url" content="blubb3">');
});
It will use to make menu bar in directory format
$pathLen = 0;
function prePad($level)
{
$ss = "";
for ($ii = 0; $ii < $level; $ii++)
{
$ss = $ss . "| ";
}
return $ss;
}
function myScanDir($dir, $level, $rootLen)
{
global $pathLen;
if ($handle = opendir($dir)) {
$allFiles = array();
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
if (is_dir($dir . "/" . $entry))
{
$allFiles[] = "D: " . $dir . "/" . $entry;
}
else
{
$allFiles[] = "F: " . $dir . "/" . $entry;
}
}
}
closedir($handle);
natsort($allFiles);
foreach($allFiles as $value)
{
$displayName = substr($value, $rootLen + 4);
$fileName = substr($value, 3);
$linkName = str_replace(" ", " ", substr($value, $pathLen + 3));
if (is_dir($fileName))
{
echo "<li ><a class='dropdown'><span>" . $displayName . " </span></a><ul>";
myScanDir($fileName, $level + 1, strlen($fileName));
echo "</ul></li>";
}
else {
$newstring = substr($displayName, -3);
if($newstring == "PDF" || $newstring == "pdf" )
echo "<li ><a href=\"" . $linkName . "\" style=\"text-decoration:none;\">" . $displayName . "</a></li>";
}
$t;
if($level != 0)
{
if($level < $t)
{
$r = int($t) - int($level);
for($i=0;$i<$r;$i++)
{
echo "</ul></li>";
}
}
}
$t = $level;
}
}
}
?>
<li style="color: #ffffff">
<?php
// ListFolder('D:\PDF');
$root = 'D:\PDF';
$pathLen = strlen($root);
myScanDir($root, 0, strlen($root));
?>
</li>
If the filenames don't have spaces, this will work:
ls -C1 -t| awk 'NR>5'|xargs rm
If the filenames do have spaces, something like
ls -C1 -t | awk 'NR>5' | sed -e "s/^/rm '/" -e "s/$/'/" | sh
Basic logic:
Simple IE7 and below shim that preserves Line Numbering for other browsers:
/* console shim*/
(function () {
var f = function () {};
if (!window.console) {
window.console = {
log:f, info:f, warn:f, debug:f, error:f
};
}
}());
**EDITED for Swift 4.2:
As @Koen commented, swift 4.2 allows:
guard let self = self else {
return // Could not get a strong reference for self :`(
}
// Now self is a strong reference
self.doSomething()
P.S.: Since I am having some up-votes, I would like to recommend the reading about escaping closures.
EDITED: As @tim-vermeulen has commented, Chris Lattner said on Fri Jan 22 19:51:29 CST 2016, this trick should not be used on self, so please don't use it. Check the non escaping closures info and the capture list answer from @gbk.**
For those who use [weak self] in capture list, note that self could be nil, so the first thing I do is check that with a guard statement
guard let `self` = self else {
return
}
self.doSomething()
If you are wondering what the quote marks are around self
is a pro trick to use self inside the closure without needing to change the name to this, weakSelf or whatever.
You can also pass arguments to getters by returning a function. This is particularly useful when you want to query an array in the store:
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
Note that getters accessed via methods will run each time you call them, and the result is not cached.
That is called Method-Style Access and it is documented on the Vue.js docs.
Use format string
intNum = 123
print "0x%x"%(intNum)
or hex
function.
intNum = 123
print hex(intNum)
//javascript
//teams.Table does not exist
function OnSuccessJSON(data, status) {
var teams = eval('(' + data.d + ')');
var listItems = "";
for (var i = 0; i < teams.length; i++) {
listItems += "<option value='" + teams[i][0]+ "'>" + teams[i][1] + "</option>";
}
$("#<%=ddlTeams.ClientID%>").html(listItems);
}
In WebKit, you can do: -webkit-appearance: textarea;
After trying most of the solutions described in this thread, I accidentally found Calligraphy (https://github.com/chrisjenx/Calligraphy) - a library by Christopher Jenkins that lets you easily add custom fonts to your app. The advantages of his lib comparing to approaches suggested here are:
I was missing the attribute:
[assembly: OwinStartupAttribute(typeof(projectname.Startup))]
Which specifies the startup class. More details: https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-startup-class-detection
this error can be caused due to various reasons. to identify the reason add try/ catch when service is run.
try
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
<span class="skimlinks-unlinked">ServiceBase.Run(ServicesToRun</span>);
}
catch (Exception ex)
{
EventLog.WriteEntry("Application", ex.ToString(), <span class="skimlinks-unlinked">EventLogEntryType.Error</span>);
}
Ok I found out:
You have to put /show
a after the URL you're working on:
http://jsfiddle.net/<your_fiddle_id>/show/
It is the site that shows the results.
And then when you save it as a file. It is all in one HTML-file.
For example:
http://jsfiddle.net/Ua8Cv/show/
for the site http://jsfiddle.net/Ua8Cv
Create a footer view layout consisting of text that you want to set as footer and then try
View footerView = ((LayoutInflater) ActivityContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_layout, null, false);
ListView.addFooterView(footerView);
Layout for footer could be something like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="7dip"
android:paddingBottom="7dip"
android:orientation="horizontal"
android:gravity="center">
<LinearLayout
android:id="@+id/footer_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:layout_gravity="center">
<TextView
android:text="@string/footer_text_1"
android:id="@+id/footer_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14dip"
android:textStyle="bold"
android:layout_marginRight="5dip" />
</LinearLayout>
</LinearLayout>
The activity class could be:
public class MyListActivty extends ListActivity {
private Context context = null;
private ListView list = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = (ListView)findViewById(android.R.id.list);
//code to set adapter to populate list
View footerView = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_layout, null, false);
list.addFooterView(footerView);
}
}
You can make use of the following code incase you want to check the types of primitive data types.
// Returns 0 if the object type is equal to double
strcmp([myNumber objCType], @encode(double))
I presume you only want to reset a single element. Resetting an entire form is simple: call its reset method.
The easiest way to "reset" a select element is to set its selectedIndex
property to the default value. If you know that no option is the default selected option, just set the select elemen'ts selectedIndex property to an appropriate value:
function resetSelectElement(selectElement) {
selecElement.selectedIndex = 0; // first option is selected, or
// -1 for no option selected
}
However, since one option may have the selected attribtue or otherwise be set to the default selected option, you may need to do:
function resetSelectElement(selectElement) {
var options = selectElement.options;
// Look for a default selected option
for (var i=0, iLen=options.length; i<iLen; i++) {
if (options[i].defaultSelected) {
selectElement.selectedIndex = i;
return;
}
}
// If no option is the default, select first or none as appropriate
selectElement.selectedIndex = 0; // or -1 for no option selected
}
And beware of setting attributes rather than properties, they have different effects in different browsers.
<p>tetxetextex</p>
<ol><li>first element</li></ol>
<p>other textetxeettx</p>
Because both <p>
and <ol>
are element rendered as block.
No way to output a message to console when using QT += gui
.
fprintf(stderr, ...)
also can't print output.
Use QMessageBox
instead to show the message.
If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".
Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".
For jQuery (at least version 1.11.2) the following procedure worked for me.
$._data(($0), 'events');
in the 'Console'handler:
value.And it's time to stop re-inventing the wheel and start using vanilla JS events ... :)
if you want to read in lots of data and work on each line separately you could use something like this:
cat myFile | while read x ; do echo $x ; done
if you want to split the lines up into multiple words you can use multiple variables in place of x like this:
cat myFile | while read x y ; do echo $y $x ; done
alternatively:
while read x y ; do echo $y $x ; done < myFile
But as soon as you start to want to do anything really clever with this sort of thing you're better going for some scripting language like perl where you could try something like this:
perl -ane 'print "$F[0]\n"' < myFile
There's a fairly steep learning curve with perl (or I guess any of these languages) but you'll find it a lot easier in the long run if you want to do anything but the simplest of scripts. I'd recommend the Perl Cookbook and, of course, The Perl Programming Language by Larry Wall et al.
The problem with using string literal I find is that it can make your code look a bit "weird" because in order to not get spaces in the string itself, it has to be completely left aligned:
var someString = @"The
quick
brown
fox...";
Yuck.
So the solution I like to use, which keeps everything nicely aligned with the rest of your code is:
var someString = String.Join(
Environment.NewLine,
"The",
"quick",
"brown",
"fox...");
And of course, if you just want to logically split up lines of an SQL statement like you are and don't actually need a new line, you can always just substitute Environment.NewLine
for " "
.
You may want to use:
SELECT Name, 'Unpaid' AS Status FROM table;
The SELECT
clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
Where the expression
can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.
When you killed the session, the session hangs around for a while in "KILLED" status while Oracle cleans up after it.
If you absolutely must, you can kill the OS process as well (look up v$process.spid
), which would release any locks it was holding on to.
See this for more detailed info.
by default, NHibernate uses first level caching which is Session Object based. but if you are running in a multi-server environment, then the first level cache may not very scalable along with some performance issues. it is happens because of the fact that it has to make very frequent trips to the database as the data is distributed over multiple servers. in other words NHibernate provides a basic, not-so-sophisticated in-process L1 cache out of box. However, it doesn’t provide features that a caching solution must have to have a notable impact on the application performance.
so the questions of all these problem is the use of a L2 cache which is associated with the session factory objects. it reduces the time consuming trips to the database so ultimately increases the app response time.
If you want to get a custom window title color on Windows 10, in short going from this
to this (or any other custom color for the window of your Eclipse IDE)
follow the next steps.
Go to C:\Windows\Resources\Themes\
. Duplicate the folder aero
and the file aero.theme
. If you can't duplicate the folder and the file then right click on both, Properties, Security, Modify, add your user to Permissions, and set authorizations to modify, read and write.
Rename the folder C:\Windows\Resources\Themes\aero - copy
and the file C:\Windows\Resources\Themes\aero - copy.theme
to C:\Windows\Resources\Themes\custom
and C:\Windows\Resources\Themes\custom.theme
(you can pick the name you want).
Rename C:\Windows\Resources\Themes\custom\aero.msstyles
to C:\Windows\Resources\Themes\custom.msstyles
.
Rename C:\Windows\Resources\Themes\custom\%your_locale%\aero.msstyles.mui
(%your_locale% is fr-FR in my case) to C:\Windows\Resources\Themes\custom\%your_locale%\custom.msstyles.mui
.
Edit custom.theme
with Notepad and change the PATH
variable of VisualStyles
to your custom.msstyles
.
Set your custom theme (yet unchanged) by double-clicking on custom.theme
. Then right-click on start menu button, go to Parameters -> Customize appearance -> Themes and select the second one. Go to the menu Colors
, select dark mode for every applications. Choose custom color for accent color and put it full black.
Apply your favorite dark theme (here DevStyle - Darkest dark - Deep black) to Eclipse and voilà, you have a full dark theme for Eclipse on Windows 10!
import numpy as np
# ND array list with different size
a = [[1],[2,3,4,5],[6,7,8]]
# stack them
b = np.hstack(a)
print(b)
[1 2 3 4 5 6 7 8]
Here look at the code:
You can simply create a Function and let it do the work for you, kind of functional Style!
Function<Person, List<Object>> compositeKey = personRecord ->
Arrays.<Object>asList(personRecord.getName(), personRecord.getAge());
Now you can use it as a map:
Map<Object, List<Person>> map =
people.collect(Collectors.groupingBy(compositeKey, Collectors.toList()));
Cheers!
Well, it's not a single statement, but it's about as close as you can get with oracle:
BEGIN
FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
END LOOP;
END;
I'm not sure I understand your intent perfectly, but perhaps the following would be close to what you want:
select n1.name, n1.author_id, count_1, total_count
from (select id, name, author_id, count(1) as count_1
from names
group by id, name, author_id) n1
inner join (select id, author_id, count(1) as total_count
from names
group by id, author_id) n2
on (n2.id = n1.id and n2.author_id = n1.author_id)
Unfortunately this adds the requirement of grouping the first subquery by id as well as name and author_id, which I don't think was wanted. I'm not sure how to work around that, though, as you need to have id available to join in the second subquery. Perhaps someone else will come up with a better solution.
Share and enjoy.
I'm not sure about your exact version, but Chrome has a tab "Network" with several items and when I click on them I can see the headers on the right in a tab.
Press F12 on windows or ??I on a mac to bring up the Chrome developer tools.
It's very easy to write that yourself, and that way you have more control over things.. As the other answers say, TypeScript is not aimed at adding runtime types or functionality.
Map:
class Map<T> {
private items: { [key: string]: T };
constructor() {
this.items = {};
}
add(key: string, value: T): void {
this.items[key] = value;
}
has(key: string): boolean {
return key in this.items;
}
get(key: string): T {
return this.items[key];
}
}
List:
class List<T> {
private items: Array<T>;
constructor() {
this.items = [];
}
size(): number {
return this.items.length;
}
add(value: T): void {
this.items.push(value);
}
get(index: number): T {
return this.items[index];
}
}
I haven't tested (or even tried to compile) this code, but it should give you a starting point.. you can of course then change what ever you want and add the functionality that YOU need...
As for your "special needs" from the List, I see no reason why to implement a linked list, since the javascript array lets you add and remove items.
Here's a modified version of the List to handle the get prev/next from the element itself:
class ListItem<T> {
private list: List<T>;
private index: number;
public value: T;
constructor(list: List<T>, value: T, index: number) {
this.list = list;
this.index = index;
this.value = value;
}
prev(): ListItem<T> {
return this.list.get(this.index - 1);
}
next(): ListItem<T> {
return this.list.get(this.index + 1);
}
}
class List<T> {
private items: Array<ListItem<T>>;
constructor() {
this.items = [];
}
size(): number {
return this.items.length;
}
add(value: T): void {
this.items.push(new ListItem<T>(this, value, this.size()));
}
get(index: number): ListItem<T> {
return this.items[index];
}
}
Here too you're looking at untested code..
Hope this helps.
Javascript has a native Map object so there's no need to create your own:
let map = new Map();
map.set("key1", "value1");
console.log(map.get("key1")); // value1
The cross-platform way (not only cross-platform itself, but also working, at the very least, with both *.so
and *.dll
) is using reverse-engineering framework radare2. E.g.:
$ rabin2 -s glew32.dll | head -n 5
[Symbols]
vaddr=0x62afda8d paddr=0x0005ba8d ord=000 fwd=NONE sz=0 bind=GLOBAL type=FUNC name=glew32.dll___GLEW_3DFX_multisample
vaddr=0x62afda8e paddr=0x0005ba8e ord=001 fwd=NONE sz=0 bind=GLOBAL type=FUNC name=glew32.dll___GLEW_3DFX_tbuffer
vaddr=0x62afda8f paddr=0x0005ba8f ord=002 fwd=NONE sz=0 bind=GLOBAL type=FUNC name=glew32.dll___GLEW_3DFX_texture_compression_FXT1
vaddr=0x62afdab8 paddr=0x0005bab8 ord=003 fwd=NONE sz=0 bind=GLOBAL type=FUNC name=glew32.dll___GLEW_AMD_blend_minmax_factor
As a bonus, rabin2
recognizes C++ name mangling, for example (and also with .so
file):
$ rabin2 -s /usr/lib/libabw-0.1.so.1.0.1 | head -n 5
[Symbols]
vaddr=0x00027590 paddr=0x00027590 ord=124 fwd=NONE sz=430 bind=GLOBAL type=FUNC name=libabw::AbiDocument::isFileFormatSupported
vaddr=0x0000a730 paddr=0x0000a730 ord=125 fwd=NONE sz=58 bind=UNKNOWN type=FUNC name=boost::exception::~exception
vaddr=0x00232680 paddr=0x00032680 ord=126 fwd=NONE sz=16 bind=UNKNOWN type=OBJECT name=typeinfoforboost::exception_detail::clone_base
vaddr=0x00027740 paddr=0x00027740 ord=127 fwd=NONE sz=235 bind=GLOBAL type=FUNC name=libabw::AbiDocument::parse
Works with object files too:
$ g++ test.cpp -c -o a.o
$ rabin2 -s a.o | head -n 5
Warning: Cannot initialize program headers
Warning: Cannot initialize dynamic strings
Warning: Cannot initialize dynamic section
[Symbols]
vaddr=0x08000149 paddr=0x00000149 ord=006 fwd=NONE sz=1 bind=LOCAL type=OBJECT name=std::piecewise_construct
vaddr=0x08000149 paddr=0x00000149 ord=007 fwd=NONE sz=1 bind=LOCAL type=OBJECT name=std::__ioinit
vaddr=0x080000eb paddr=0x000000eb ord=017 fwd=NONE sz=73 bind=LOCAL type=FUNC name=__static_initialization_and_destruction_0
vaddr=0x08000134 paddr=0x00000134 ord=018 fwd=NONE sz=21 bind=LOCAL type=FUNC name=_GLOBAL__sub_I__Z4funcP6Animal
function Delete(){
var id = $("#dgetid").val();
debugger
$.ajax({
type: "POST",
url: "Add_NewProduct.aspx/DeleteData",
data: "{id:'" + id + "'}",
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
if (result.d == 1) {
bindData();
setTimeout(function(){ $('#DeleteModal').modal('hide');},1000);
}
}
});
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
notification = (ImageView)v.findViewById(R.id.notification);
notification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.container,new NotificationFragment());
fr.commit();
}
});
return v;
}
Here's my solution, completely different to any else on here. It uses the mouse position to figure out if an option was clicked as oppose to clicking on the select box to open the dropdown. It makes use of the event.screenY position as this is the only reliable cross browser variable. A hover event has to be attached first so it can figure out the controls position relative to the screen before the click event.
var select = $("select");
var screenDif = 0;
select.bind("hover", function (e) {
screenDif = e.screenY - e.clientY;
});
select.bind("click", function (e) {
var element = $(e.target);
var eventHorizon = screenDif + element.offset().top + element.height() - $(window).scrollTop();
if (e.screenY > eventHorizon)
alert("option clicked");
});
Here is my jsFiddle http://jsfiddle.net/sU7EV/4/
The problem may lie in selected null values ??in combination with a CLOB-type column.
select valueVarchar c1 ,
valueClob c2 ,
valueVarchar c3 ,
valueVvarchar c4
of Table_1
union
select valueVarchar c1 ,
valueClob c2 ,
valueVarchar c3 ,
null c4
of table_2
I reworked the cursor. The first cursor is composed of four non-null columns. The second cursor selects three non-null columns. The null values ??were injected into the cursorForLoop .
You're going to want the second field after the colon, not the first.
grep -n "text to find" file.txt | cut -f2 -d:
I had this issue myself, regarding the error message that is received trying to populate a foreign key field. I ended up on this page in hopes of finding the answer. The checked answer on this page is indeed the correct one, unfortunately I feel that the answer is a bit incomplete for people not as familiar with SQL. I am fairly apt at writing code but SQL queries are new to me as well as building database tables.
Despite the checked answer being correct:
Mike M wrote-
"The way a FK works is it cannot have a value in that column that is not also in the primary key column of the referenced table."
What is missing from this answer is simply;
You must build the table containing the Primary Key first.
Another way to say it is;
You must Insert Data into the parent table, containing the Primary Key, before attempting to insert data into the child table containing the Foreign Key.
In short, many of the tutorials seem to be glazing over this fact so that if you were to try on your own and didn't realize there was an order of operations, then you would get this error. Naturally after adding the primary key data, your foreign key data in the child table must conform to the primary key field in the parent table, otherwise, you will still get this error.
If anyone read down this far. I hope this helped make the checked answer more clear. I know there are some of you who may feel that this sort of thing is pretty straight-forward and that opening a book would have answered this question before it was posted, but the truth is that not everyone learns in the same way.
+
characters in the path component is expected to be treated literally.To be explicit: +
is only a special character in the query component.
I had the same problem and, after a day of research, I came up with this solution: http://jsfiddle.net/konstantc/4jkef3a1/
// *** (month and year only) ***_x000D_
$(function() { _x000D_
$('#datepicker1').datepicker( {_x000D_
yearRange: "c-100:c",_x000D_
changeMonth: true,_x000D_
changeYear: true,_x000D_
showButtonPanel: true,_x000D_
closeText:'Select',_x000D_
currentText: 'This year',_x000D_
onClose: function(dateText, inst) {_x000D_
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();_x000D_
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
$(this).val($.datepicker.formatDate('MM yy (M y) (mm/y)', new Date(year, month, 1)));_x000D_
}_x000D_
}).focus(function () {_x000D_
$(".ui-datepicker-calendar").hide();_x000D_
$(".ui-datepicker-current").hide();_x000D_
$("#ui-datepicker-div").position({_x000D_
my: "left top",_x000D_
at: "left bottom",_x000D_
of: $(this)_x000D_
});_x000D_
}).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------_x000D_
_x000D_
_x000D_
_x000D_
// *** (year only) ***_x000D_
$(function() { _x000D_
$('#datepicker2').datepicker( {_x000D_
yearRange: "c-100:c",_x000D_
changeMonth: false,_x000D_
changeYear: true,_x000D_
showButtonPanel: true,_x000D_
closeText:'Select',_x000D_
currentText: 'This year',_x000D_
onClose: function(dateText, inst) {_x000D_
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
$(this).val($.datepicker.formatDate('yy', new Date(year, 1, 1)));_x000D_
}_x000D_
}).focus(function () {_x000D_
$(".ui-datepicker-month").hide();_x000D_
$(".ui-datepicker-calendar").hide();_x000D_
$(".ui-datepicker-current").hide();_x000D_
$(".ui-datepicker-prev").hide();_x000D_
$(".ui-datepicker-next").hide();_x000D_
$("#ui-datepicker-div").position({_x000D_
my: "left top",_x000D_
at: "left bottom",_x000D_
of: $(this)_x000D_
});_x000D_
}).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------_x000D_
_x000D_
_x000D_
_x000D_
// *** (year only, no controls) ***_x000D_
$(function() { _x000D_
$('#datepicker3').datepicker( {_x000D_
dateFormat: "yy",_x000D_
yearRange: "c-100:c",_x000D_
changeMonth: false,_x000D_
changeYear: true,_x000D_
showButtonPanel: false,_x000D_
closeText:'Select',_x000D_
currentText: 'This year',_x000D_
onClose: function(dateText, inst) {_x000D_
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
$(this).val($.datepicker.formatDate('yy', new Date(year, 1, 1)));_x000D_
},_x000D_
onChangeMonthYear : function () {_x000D_
$(this).datepicker( "hide" );_x000D_
}_x000D_
}).focus(function () {_x000D_
$(".ui-datepicker-month").hide();_x000D_
$(".ui-datepicker-calendar").hide();_x000D_
$(".ui-datepicker-current").hide();_x000D_
$(".ui-datepicker-prev").hide();_x000D_
$(".ui-datepicker-next").hide();_x000D_
$("#ui-datepicker-div").position({_x000D_
my: "left top",_x000D_
at: "left bottom",_x000D_
of: $(this)_x000D_
});_x000D_
}).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
<h2 class="font-weight-light text-lg-left mt-4 mb-0"><b>jQuery UI Datepicker</b> custom select</h2>_x000D_
_x000D_
<hr class="mt-2 mb-3">_x000D_
<div class="row text-lg-left">_x000D_
<div class="col-12">_x000D_
_x000D_
<form>_x000D_
_x000D_
<div class="form-label-group">_x000D_
<label for="datepicker1">(month and year only : <code>id="datepicker1"</code> )</label>_x000D_
<input type="text" class="form-control" id="datepicker1" _x000D_
placeholder="(month and year only)" />_x000D_
</div>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<div class="form-label-group">_x000D_
<label for="datepicker2">(year only : <code>input id="datepicker2"</code> )</label>_x000D_
<input type="text" class="form-control" id="datepicker2" _x000D_
placeholder="(year only)" />_x000D_
</div>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<div class="form-label-group">_x000D_
<label for="datepicker3">(year only, no controls : <code>input id="datepicker3"</code> )</label>_x000D_
<input type="text" class="form-control" id="datepicker3" _x000D_
placeholder="(year only, no controls)" />_x000D_
</div>_x000D_
_x000D_
</form>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
I know this question is pretty old but I thought that my solution can be of use to others that encounter this problem. Hope it helps.
You can add in your .bashrc
file:
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")
and it will dynamically change when you update your packages.
In Swift 3.0
let number:NSNumber = 25
let strValue = String(describing: number as NSNumber)
print("As String => \(strValue)")
We can get the number value in String.
There is a crop()
method:
w, h = yourImage.size
yourImage.crop((0, 30, w, h-30)).save(...)
The only solutions that I've seen to organize the external files into sub-folders has required the use of VBA to resolve a full path to the external file in the formulas. Here is a link to a site with several examples others have used:
http://www.teachexcel.com/excel-help/excel-how-to.php?i=415651
Alternatively, if you can place all of the files in the same folder instead of dividing them into sub-folders, then Excel will resolve the external references without requiring the use of VBA even if you move the files to a network location. Your formulas then become simply ='[ComponentsC.xlsx]Sheet1'!A1
with no folder names to traverse.
A very simple example:
SET a=Hello
SET b=World
SET c=%a% %b%!
echo %c%
The result should be:
Hello World!
Emp class needs to implement Comaparable interface so we need to Override its compateTo method.
import java.util.ArrayList;
import java.util.Collections;
class Emp implements Comparable< Emp >{
int empid;
String name;
Emp(int empid,String name){
this.empid = empid;
this.name = name;
}
@Override
public String toString(){
return empid+" "+name;
}
@Override
public int compareTo(Emp o) {
if(this.empid==o.empid){
return 0;
}
else if(this.empid < o.empid){
return 1;
}
else{
return -1;
}
}
}
public class JavaApplication1 {
public static void main(String[] args) {
ArrayList<Emp> a= new ArrayList<Emp>();
a.add(new Emp(10,"Mahadev"));
a.add(new Emp(50,"Ashish"));
a.add(new Emp(40,"Amit"));
Collections.sort(a);
for(Emp id:a){
System.out.println(id);
}
}
}
Another option is to check if it is equal to @""
with isEqualToString:
like so:
if ([myString isEqualToString:@""]) {
NSLog(@"myString IS empty!");
} else {
NSLog(@"myString IS NOT empty, it is: %@", myString);
}
Suppose you have data in A1:A10 and B1:B10 and you want to highlight which values in A1:A10 do not appear in B1:B10.
Try as follows:
Enter the following formula:
=ISERROR(MATCH(A1,$B$1:$B$10,0))
Now select the format you want to highlight the values in col A that do not appear in col B
This will highlight any value in Col A that does not appear in Col B.
This answer is for XAMPP on Ubuntu.
The manual for installation and download is on (site official)
http://www.apachefriends.org/it/xampp-linux.html
After to start XAMPP simply call this command:
sudo /opt/lampp/lampp start
You should now see something like this on your screen:
Starting XAMPP 1.8.1...
LAMPP: Starting Apache...
LAMPP: Starting MySQL...
LAMPP started.
If you have this
Starting XAMPP for Linux 1.8.1...
XAMPP: Another web server daemon is already running.
XAMPP: Another MySQL daemon is already running.
XAMPP: Starting ProFTPD...
XAMPP for Linux started
. The solution is
sudo /etc/init.d/apache2 stop
sudo /etc/init.d/mysql stop
And the restast with sudo //opt/lampp/lampp restart
You to fix most of the security weaknesses simply call the following command:
/opt/lampp/lampp security
After the change this file
sudo kate //opt/lampp/etc/extra/httpd-xampp.conf
Find and replace on
#
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
Order deny,allow
Deny from all
Allow from ::1 127.0.0.0/8
Allow from all
#\
# fc00::/7 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 \
# fe80::/10 169.254.0.0/16
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
Personally, I've used this before to build a JSON to POJO converter. In the case that the JSONObject processed with the function contains an array or nested JSONObjects (implying that the data here isn't of a primitive type or String
), I attempt to invoke the setter method using class.cast()
in this fashion:
public static Object convertResponse(Class<?> clazz, JSONObject readResultObject) {
...
for(Method m : clazz.getMethods()) {
if(!m.isAnnotationPresent(convertResultIgnore.class) &&
m.getName().toLowerCase().startsWith("set")) {
...
m.invoke(returnObject, m.getParameters()[0].getClass().cast(convertResponse(m.getParameters()[0].getType(), readResultObject.getJSONObject(key))));
}
...
}
Not sure if this is extremely helpful, but as said here before, reflection is one of the very few legitimate use case of class.cast()
I can think of, at least you have another example now.
To Hide the Action Bar add the below code in Values/Styles
<style name="CustomActivityThemeNoActionBar" parent="@android:style/Theme.Holo.Light">
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
</style>
Then in your AndroidManifest.xml file add the below code in the required activity
<activity
android:name="com.newbelievers.android.NBMenu"
android:label="@string/title_activity_nbmenu"
android:theme="@style/CustomActivityThemeNoActionBar">
</activity>
Recovering from Repository Corruption is the official answer.
The really short answer is: find uncorrupted objects and copy them.
Solution for the issue: deprecated gradle features were used in this build making it incompatible with gradle 6.0. android studio This provided solution worked for me.
First change the classpath in dependencies of build.gradle of your project
From: classpath 'com.android.tools.build:gradle:3.3.1'
To: classpath 'com.android.tools.build:gradle:3.6.1'
Then make changes in the gradle-wrapper.properties file this file exists in the Project's gradle>wrapper folder
From: distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
To: distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip
Then Sync your gradle.
Don't forget to either include stylesheets using the link tag
http://www.w3schools.com/TAGS/tag_link.asp
Or enclose CSS within a style tag on your webpage.
<style>
a { text-decoration:none; }
p { text-decoration:underline; }
</style>
I wouldn't recommend using the underline on anything apart from links, underline is generally accepted as something that is clickable. If it isn't clickable don't underline it.
CSS basics can be picked up at w3schools
A warning about the Jquery Caret plugin.
It will conflict with the Masked Input plugin (or vice versa). Fortunately the Masked Input plugin includes a caret() function of its own, which you can use very similarly to the Caret plugin for your basic needs - $(element).caret().begin or .end
In case anyone searching for the solution , if you are using express here is the quick solution .
const express = require('express')
const cors = require('cors')
const app = express()
1) install cors using npm npm install cors --save
2) import it [require ] const cors = require('cors')
3) use it as middleware app.use(cors())
for details insatll and usage of cors . That is it, hopefully it works.
Here's a pure CSS solution, similar to DarkBee's answer, but without the need for an extra .wrapper
div:
.dimmed {
position: relative;
}
.dimmed:after {
content: " ";
z-index: 10;
display: block;
position: absolute;
height: 100%;
top: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.5);
}
I'm using rgba here, but of course you can use other transparency methods if you like.
I always write what I would use if there was no interface and I was writing a direct implementation, i.e., I would use public
.
This solution works in all major browsers:
saveSelection()
is attached to the onmouseup
and onkeyup
events of the div and saves the selection to the variable savedRange
.
restoreSelection()
is attached to the onfocus
event of the div and reselects the selection saved in savedRange
.
This works perfectly unless you want the selection to be restored when the user clicks the div aswell (which is a bit unintuitative as normally you expect the cursor to go where you click but code included for completeness)
To achieve this the onclick
and onmousedown
events are canceled by the function cancelEvent()
which is a cross browser function to cancel the event. The cancelEvent()
function also runs the restoreSelection()
function because as the click event is cancelled the div doesn't receive focus and therefore nothing is selected at all unless this functions is run.
The variable isInFocus
stores whether it is in focus and is changed to "false" onblur
and "true" onfocus
. This allows click events to be cancelled only if the div is not in focus (otherwise you would not be able to change the selection at all).
If you wish to the selection to be change when the div is focused by a click, and not restore the selection onclick
(and only when focus is given to the element programtically using document.getElementById("area").focus();
or similar then simply remove the onclick
and onmousedown
events. The onblur
event and the onDivBlur()
and cancelEvent()
functions can also safely be removed in these circumstances.
This code should work if dropped directly into the body of an html page if you want to test it quickly:
<div id="area" style="width:300px;height:300px;" onblur="onDivBlur();" onmousedown="return cancelEvent(event);" onclick="return cancelEvent(event);" contentEditable="true" onmouseup="saveSelection();" onkeyup="saveSelection();" onfocus="restoreSelection();"></div>
<script type="text/javascript">
var savedRange,isInFocus;
function saveSelection()
{
if(window.getSelection)//non IE Browsers
{
savedRange = window.getSelection().getRangeAt(0);
}
else if(document.selection)//IE
{
savedRange = document.selection.createRange();
}
}
function restoreSelection()
{
isInFocus = true;
document.getElementById("area").focus();
if (savedRange != null) {
if (window.getSelection)//non IE and there is already a selection
{
var s = window.getSelection();
if (s.rangeCount > 0)
s.removeAllRanges();
s.addRange(savedRange);
}
else if (document.createRange)//non IE and no selection
{
window.getSelection().addRange(savedRange);
}
else if (document.selection)//IE
{
savedRange.select();
}
}
}
//this part onwards is only needed if you want to restore selection onclick
var isInFocus = false;
function onDivBlur()
{
isInFocus = false;
}
function cancelEvent(e)
{
if (isInFocus == false && savedRange != null) {
if (e && e.preventDefault) {
//alert("FF");
e.stopPropagation(); // DOM style (return false doesn't always work in FF)
e.preventDefault();
}
else {
window.event.cancelBubble = true;//IE stopPropagation
}
restoreSelection();
return false; // false = IE style
}
}
</script>
with a form, just set method
to "post"
<form action="blah.php" method="post">
<input type="text" name="data" value="mydata" />
<input type="submit" />
</form>
All the other answers are correct, however, you might have problems if you're trying to check directory in a user's home directory. Make sure you expand the relative path before checking:
File.exists? '~/exists'
=> false
File.directory? '~/exists'
=> false
File.exists? File.expand_path('~/exists')
=> true
If you are interested in the indexes, the best choice is np.argsort(a)
a = np.random.randint(0, 100, 10)
sorted_idx = np.argsort(a)
I had the same problem and I could not make this answer work on Framework 2.0 so I dug deeper.
You would have to first handle the PreviewKeyDown on the textbox so when ENTER came along you would set IsInputKey so that it could be handled by or forwarded to the keyDown event on the textbox. Like this:
Private Sub txtFiltro_PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles txtFiltro.PreviewKeyDown
Select Case e.KeyCode
Case Keys.Enter
e.IsInputKey = True
End Select
End Sub
and then you would handle the event keydown on the textbox. One of the answer was on the right track but missed setting the e.IsInputKey.
Private Sub txtFiltro_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtFiltro.KeyDown
If e.KeyCode = Keys.Enter Then
e.handled = True
Textbox1.Focus()
End If
End Sub
The argument order seems to matter... to exclude subdirectories, I used
robocopy \\source\folder C:\destinationfolder /XD * /MIR
...and that works for me (Windows 10 copy from Windows Server 2016)
Your error is in resultCode = Activity.RESULT_CANCELED
, you should instance like resultCode == Activity.RESULT_CANCELED
==
Alright, here's the best solution I've found that meets all the requirements:
No need for mouse interaction whatsoever.
If you really need to do it in separate transaction you need to use REQUIRES_NEW
and live with the performance overhead. Watch out for dead locks.
I'd rather do it the other way:
Here's a more readable example of an in-place Insertion sort algorithm.
a = [3, 1, 5, 2, 4]
for i in a[1:]:
j = a.index(i)
while j > 0 and a[j-1] > a[j]:
a[j], a[j-1] = a[j-1], a[j]
j = j - 1
This is how I do it...
public class ThreadA {
public ThreadA(object[] args) {
...
}
public void Run() {
while (true) {
Thread.sleep(1000); // wait 1 second for something to happen.
doStuff();
if(conditionToExitReceived) // what im waiting for...
break;
}
//perform cleanup if there is any...
}
}
Then to run this in its own thread... ( I do it this way because I also want to send args to the thread)
private void FireThread(){
Thread thread = new Thread(new ThreadStart(this.startThread));
thread.start();
}
private void (startThread){
new ThreadA(args).Run();
}
The thread is created by calling "FireThread()"
The newly created thread will run until its condition to stop is met, then it dies...
You can signal the "main" with delegates, to tell it when the thread has died.. so you can then start the second one...
Best to read through : This MSDN Article
Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n
will work.
If you use anything else you will cause issues with cut and paste on Windows platforms.
The line breaks will be canonicalised by windows browsers when the form is submitted, but if you send the form down to the browser with \n
linebreaks, you will find that the text will not copy and paste correctly between for example notepad and the textarea.
Interestingly, in spite of the Unix line end convention being \n
, the standard in most text-based network protocols including HTTP, SMTP, POP3, IMAP, and so on is still \r\n
. Yes, it may not make a lot of sense, but that's history and evolving standards for you!
MySQLi is part of PHP. There should be a php-mysqli type package available, or you can take the PHP source and recompile that mysqli enabled. You may already have it installed, but it's done as a module and is disabled. Check your php.ini for extension=mysqli.so
or similar. it may be commented out, or the .so file is present in your extensions directory but not linked to PHP via that extension= directive.
The whole concept of inversion of control means you are free from a chore to instantiate objects manually and provide all necessary dependencies.
When you annotate class with appropriate annotation (e.g. @Service
) Spring will automatically instantiate object for you. If you are not familiar with annotations you can also use XML file instead. However, it's not a bad idea to instantiate classes manually (with the new
keyword) in unit tests when you don't want to load the whole spring context.
I sugges to use the Apache Commons CSV https://commons.apache.org/proper/commons-csv/
Here is one example:
Path currentRelativePath = Paths.get("");
String currentPath = currentRelativePath.toAbsolutePath().toString();
String csvFile = currentPath + "/pathInYourProject/test.csv";
Reader in;
Iterable<CSVRecord> records = null;
try
{
in = new FileReader(csvFile);
records = CSVFormat.EXCEL.withHeader().parse(in); // header will be ignored
}
catch (IOException e)
{
e.printStackTrace();
}
for (CSVRecord record : records) {
String line = "";
for ( int i=0; i < record.size(); i++)
{
if ( line == "" )
line = line.concat(record.get(i));
else
line = line.concat("," + record.get(i));
}
System.out.println("read line: " + line);
}
It automaticly recognize , and " but not ; (maybe it can be configured...).
My example file is:
col1,col2,col3
val1,"val2",val3
"val4",val5
val6;val7;"val8"
And output is:
read line: val1,val2,val3
read line: val4,val5
read line: val6;val7;"val8"
Last line is considered like one value.
Little late to the game but i found a way to fix this for me that i had not seen anywhere else. Select your connection from Connection Managers. On the right you should see properties. Check to see if there are any expressions there if not add one. In your package explorer add a variable called connection to sql or whatever. Set the variable as a string and set the value as your connection string and include the User Id and password. Back to the connection manager properties and expression. From the drop down select ConnectionString and set the second box as the name of your variable. It should look like this
I could not for the life of me find another solution but this worked!
I think using enumerate on the outer loop and using the index to slice the list on the inner loop is pretty Pythonic:
for index, this in enumerate(mylist):
for that in mylist[index+1:]:
compare(this, that)
Try to convert the BigInteger to a long like this
Long longNumber= bigIntegerNumber.longValue();
Have same error from time to time (when I set install location to "prefer external" in manifest). Just clean and rebuild project. Works for me.
I think there is some confusion about the difference between MVC and Web Api. In short, for MVC you can use a login form and create a session using cookies. For Web Api there is no session. That's why you want to use the token.
You do not need a login form. The Token endpoint is all you need. Like Win described you'll send the credentials to the token endpoint where it is handled.
Here's some client side C# code to get a token:
//using System;
//using System.Collections.Generic;
//using System.Net;
//using System.Net.Http;
//string token = GetToken("https://localhost:<port>/", userName, password);
static string GetToken(string url, string userName, string password) {
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>( "grant_type", "password" ),
new KeyValuePair<string, string>( "username", userName ),
new KeyValuePair<string, string> ( "Password", password )
};
var content = new FormUrlEncodedContent(pairs);
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
using (var client = new HttpClient()) {
var response = client.PostAsync(url + "Token", content).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
In order to use the token add it to the header of the request:
//using System;
//using System.Collections.Generic;
//using System.Net;
//using System.Net.Http;
//var result = CallApi("https://localhost:<port>/something", token);
static string CallApi(string url, string token) {
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
using (var client = new HttpClient()) {
if (!string.IsNullOrWhiteSpace(token)) {
var t = JsonConvert.DeserializeObject<Token>(token);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.access_token);
}
var response = client.GetAsync(url).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
Where Token is:
//using Newtonsoft.Json;
class Token
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
public string userName { get; set; }
[JsonProperty(".issued")]
public string issued { get; set; }
[JsonProperty(".expires")]
public string expires { get; set; }
}
Now for the server side:
In Startup.Auth.cs
var oAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider("self"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// https
AllowInsecureHttp = false
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(oAuthOptions);
And in ApplicationOAuthProvider.cs the code that actually grants or denies access:
//using Microsoft.AspNet.Identity.Owin;
//using Microsoft.Owin.Security;
//using Microsoft.Owin.Security.OAuth;
//using System;
//using System.Collections.Generic;
//using System.Security.Claims;
//using System.Threading.Tasks;
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
private readonly string _publicClientId;
public ApplicationOAuthProvider(string publicClientId)
{
if (publicClientId == null)
throw new ArgumentNullException("publicClientId");
_publicClientId = publicClientId;
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
var user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager);
var propertyDictionary = new Dictionary<string, string> { { "userName", user.UserName } };
var properties = new AuthenticationProperties(propertyDictionary);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
// Token is validated.
context.Validated(ticket);
}
public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
context.AdditionalResponseParameters.Add(property.Key, property.Value);
}
return Task.FromResult<object>(null);
}
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
// Resource owner password credentials does not provide a client ID.
if (context.ClientId == null)
context.Validated();
return Task.FromResult<object>(null);
}
public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
if (context.ClientId == _publicClientId)
{
var expectedRootUri = new Uri(context.Request.Uri, "/");
if (expectedRootUri.AbsoluteUri == context.RedirectUri)
context.Validated();
}
return Task.FromResult<object>(null);
}
}
As you can see there is no controller involved in retrieving the token. In fact, you can remove all MVC references if you want a Web Api only. I have simplified the server side code to make it more readable. You can add code to upgrade the security.
Make sure you use SSL only. Implement the RequireHttpsAttribute to force this.
You can use the Authorize / AllowAnonymous attributes to secure your Web Api. Additionally you can add filters (like RequireHttpsAttribute) to make your Web Api more secure. I hope this helps.
Try new way to set background transparent
android:background="?android:attr/selectableItemBackground"
Assuming your script is something like the below snippet and named testargs.ps1
param ([string]$w)
Write-Output $w
You can call this at the commandline as:
PowerShell.Exe -File C:\scripts\testargs.ps1 "Test String"
This will print "Test String" (w/o quotes) at the console. "Test String" becomes the value of $w in the script.
And if you need to style your form elements according to it's state (modified/not modified) dynamically or to test whether some values has actually changed, you can use the following module, developed by myself: https://github.com/betsol/angular-input-modified
It adds additional properties and methods to the form and it's child elements. With it, you can test whether some element contains new data or even test if entire form has new unsaved data.
You can setup the following watch: $scope.$watch('myForm.modified', handler)
and your handler will be called if some form elements actually contains new data or if it reversed to initial state.
Also, you can use modified
property of individual form elements to actually reduce amount of data sent to a server via AJAX call. There is no need to send unchanged data.
As a bonus, you can revert your form to initial state via call to form's reset()
method.
You can find the module's demo here: http://plnkr.co/edit/g2MDXv81OOBuGo6ORvdt?p=preview
Cheers!
Try using String.format()
:
ed = (EditText) findViewById (R.id.box);
int x = 10;
ed.setText(String.format("%s",x));
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
I think you are getting confused about what the a:active
CSS selector does. This will only change the colour of your link when you click it (and only for the duration of the click i.e. how long your mouse button stays down). What you need to do is introduce a new class e.g. .selected
into your CSS and when you select a link, update the selected menu item with new class e.g.
<div class="menuBar">
<ul>
<li class="selected"><a href="index.php">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
....
</ul>
</div>
// specific CSS for your menu
div.menuBar li.selected a { color: #FF0000; }
// more general CSS
li.selected a { color: #FF0000; }
You will need to update your template page to take in a selectedPage
parameter.
The idiomatic way is to say:
if(rsData["usr.ursrdaystime"] != DBNull.Value) {
strLevel = rsData["usr.ursrdaystime"].ToString();
}
This:
rsData = objCmd.ExecuteReader();
rsData.Read();
Makes it look like you're reading exactly one value. Use IDbCommand.ExecuteScalar
instead.
clacke’s answer is great but I think only works if your source is well-formed XML, not normal HTML.
So to do the same for normal Web content—HTML docs that aren’t necessarily well-formed XML:
echo "<p>foo<div>bar</div><p>baz" | python -c "from sys import stdin; \
from lxml import html; \
print '\n'.join(html.tostring(node) for node in html.parse(stdin).xpath('//p'))"
And to instead use html5lib (to ensure you get the same parsing behavior as Web browsers—because like browser parsers, html5lib conforms to the parsing requirements in the HTML spec).
echo "<p>foo<div>bar</div><p>baz" | python -c "from sys import stdin; \
import html5lib; from lxml import html; \
doc = html5lib.parse(stdin, treebuilder='lxml', namespaceHTMLElements=False); \
print '\n'.join(html.tostring(node) for node in doc.xpath('//p'))
Go to the SQL Server Management Studio, navigate to Security, go to Logins and right click it. A Menu will come up with a button saying "New Login". There you will be able to add users and/or groups from Active Directory to your SQL Server "permissions". Hope this helps
Try following logic:
<script type="text/javascript">
function showHideDiv(id) {
var e = document.getElementById(id);
if(e.style.display == null || e.style.display == "none") {
e.style.display = "block";
} else {
e.style.display = "none";
}
}
</script>
The problem appears to be that despite listing your dependencies in the pom.xml, IntelliJ IDEA does not rebuild those dependencies when you run your project.
What worked for me is this:
Go to 'Run' -> 'Edit Configurations...', find your application, make sure the "Before launch:" section is expanded, click the green plus sign, and select "Build Project".
These might resolve the issue(It did for me). In IIS Express change the project property values, "Anonymous Authentication" and "Windows Authentication". To do this, when project is selected, press F4 and then change these properties.
In case you are deploying it on IIS locally, make sure local machines "Windows Authentication" feature is enabled and "Anonymous Authentication" is disabled.
Refer to
https://grekai.wordpress.com/2011/03/31/httpcontext-current-user-identity-name-is-empty/
You're calling e.nextElement()
twice inside your loop when you're only guaranteed that you can call it once without an exception. Rewrite the loop like so:
while(e.hasMoreElements()){
String param = e.nextElement();
System.out.println(param);
}