If you are fine using a graphical tool this works very well:
gitk <file>
gitk now shows all commits where the file has been updated. Marking a commit will show you the diff against the previous commit in the list. This also works for directories, but then you also get to select the file to diff for the selected commit. Super useful!
This is documented in the 'R Installation and Administration' manual that came with your installation.
On my Linux box:
R> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"
[3] "/usr/lib/R/library"
R>
meaning that the default path is the first of these. You can override that via an argument to both install.packages()
(from inside R) or R CMD INSTALL
(outside R).
You can also override by setting the R_LIBS_USER variable.
You can try in two ways. The detail is in this link.
1) Via pip
pip install --upgrade certifi
2) If it doesn't work, try to run a Cerificates.command that comes bundled with Python 3.* for Mac:(Go to your python installation location and double click the file)
open /Applications/Python\ 3.*/Install\ Certificates.command
foreach($test_package_data as $key=>$data ) {
$category_detail_arr = $test_package_data[$key]['category_detail'];
foreach( $category_detail_arr as $i=>$value ) {
$test_package_data[$key]['category_detail'][$i]['count'] = $some_value;////<----Here
}
}
For python2 and python3 compatibility, you can use:
# Python 2 and 3
from imp import reload
reload(mymodule)
I worked from Misko's code above and this is what I've done with it. This is a more current solution since $defer
has been changed to $timeout
. Substituting $timeout
however will wait for the timeout period (in Misko's code, 1 second), then return the data hoping it's resolved in time. With this way, it returns asap.
function PhoneListCtrl($scope, phones) {
$scope.phones = phones;
$scope.orderProp = 'age';
}
PhoneListCtrl.resolve = {
phones: function($q, Phone) {
var deferred = $q.defer();
Phone.query(function(phones) {
deferred.resolve(phones);
});
return deferred.promise;
}
}
Hard to believe adding a custom icon is so complicated. I found a similar solution to those posted above, but for me, I could not get the icon to display until I added the viewBox info, which I got directly from opening the SVG in a text editor.
//customIcon.js
import React from "react";
import {ReactComponent as ImportedSVG} from "path/to/myIcon.svg";
import { SvgIcon } from '@material-ui/core';
function CustomIcon() {
return(
<SvgIcon component={ImportedSVG} viewBox="0 0 384 512"/>
)
}
export default CustomIcon;
I also ran into an error with namespaces and had to clean up the SVG before it would work, following advice from this post
Consider:
Sub SheetKiller()
Dim s As Worksheet, t As String
Dim i As Long, K As Long
K = Sheets.Count
For i = K To 1 Step -1
t = Sheets(i).Name
If t = "ID Sheet" Or t = "Summary" Then
Application.DisplayAlerts = False
Sheets(i).Delete
Application.DisplayAlerts = True
End If
Next i
End Sub
NOTE:
Because we are deleting, we run the loop backwards.
Alternatively you could use:
if ($('#navigation a').is(".active")) {
$(this).parent().addClass("active");
}
@tableName
Table variables are alive for duration of the script running only i.e. they are only session level objects.
To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName
object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.
There is another type of table object which can be created for temporary use. They are #tableName
objects declared like similar create statement for physical tables:
Create table #test (Id int, Name varchar(50))
This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.
IF OBJECT_ID('tempdb..#test') IS NOT NULL
DROP TABLE #test
Hope this makes sense !
I think the OP's question is solved by deleting the ~/.ssh/known_hosts (which was a folder, not a file). But for other's who might be having this issue, I noticed that one of my servers had weird permissions (400):
-r--------. 1 user user 396 Jan 7 11:12 /home/user/.ssh/known_hosts
So I solved this by adding owner/user PLUS write.
chmod u+w ~/.ssh/known_hosts
Thus. ~/.ssh/known_hosts needs to be a flat file, and must be owned by you, and you need to be able to read and write to it.
You could always declare known_hosts bankruptcy, delete it, and continue doing things as normal, and connecting to things (git / ssh) will regenerate a new known_hosts that should work just fine.
This command works fine:
npm upgrade -g @angular/cli
EMS's SQL Manager is much easier to use and has many more features than either phpPgAdmin or PG Admin III. However, it's windows only and you have to pay for it.
Using map (halfdanrump's answer) is best for me, though haven't timed it...
But if you go for a dictionary, and if you have a big_dict:
so e.g.:
big_dict = {'a':1,'b':2,'c':3,................................................}
req = ['a','c','w']
{k:big_dict.get(k,None) for k in req )
# or
{k:big_dict[k] for k in req if k in big_dict)
Note that in the converse case, that the req is big, but my_dict is small, you should loop through my_dict instead.
In general, we are doing an intersection and the complexity of the problem is O(min(len(dict)),min(len(req))). Python's own implementation of intersection considers the size of the two sets, so it seems optimal. Also, being in c and part of the core library, is probably faster than most not optimized python statements. Therefore, a solution that I would consider is:
dict = {'a':1,'b':2,'c':3,................................................}
req = ['a','c','w',...................]
{k:dic[k] for k in set(req).intersection(dict.keys())}
It moves the critical operation inside python's c code and will work for all cases.
1st method
MyTable.objects.filter(pk=some_value).update(field1='some value')
2nd Method
q = MyModel.objects.get(pk=some_value)
q.field1 = 'some value'
q.save()
3rd method
By using get_object_or_404
q = get_object_or_404(MyModel,pk=some_value)
q.field1 = 'some value'
q.save()
4th Method
if you required if pk=some_value
exist then update
it other wise create
new one by using update_or_create
.
MyModel.objects.update_or_create(pk=some_value,defaults={'field1':'some value'})
Press Ctrl+H (Replace)
Select Extended
from SearchMode
Put \r\n\r\n
in Find What
Put \r\n
in ReplaceWith
Click on Replace All
If you just want to see if it's present, try turning the list into a dict:
# Generate a list
l = [n*n for n in range(1000)]
# Convert to dict - doesn't matter what you map values to
d = dict((x, 1) for x in l)
count = 0
for n in range(1000000):
# Compare with "if n in l"
if n in d:
count += 1
On my machine, "if n in l" took 37 seconds, while "if n in d" took 0.4 seconds.
Better to first compress catalog on remote server:
tar czfP backup.tar.gz /path/to/catalog
Secondly, download from remote:
scp [email protected]:/path/to/backup.tar.gz .
At the end, extract the files:
tar -xzvf backup.tar.gz
a bit of a cheat, but it works:
HTML:
<ol type="A" style="font-weight: bold;">
<li><span>Text</span></li>
<li><span>More text</span></li>
</ol>
CSS:
li span { font-weight: normal; }
Use this code
TextView textView = new TextView(YourActivity.this);
textView.setGravity(Gravity.CENTER | Gravity.TOP);
textView.setText("some text");
Another way is by using items() + dict comprehension.
items() coupled with dict comprehension can also help us achieve the task of key-value pair deletion, but it has the drawback of not being an in place dict technique. Actually a new dict if created except for the key we don’t wish to include.
test_dict = {"sai" : 22, "kiran" : 21, "vinod" : 21, "sangam" : 21}
# Printing dictionary before removal
print ("dictionary before performing remove is : " + str(test_dict))
# Using items() + dict comprehension to remove a dict. pair
# removes vinod
new_dict = {key:val for key, val in test_dict.items() if key != 'vinod'}
# Printing dictionary after removal
print ("dictionary after remove is : " + str(new_dict))
Output:
dictionary before performing remove is : {'sai': 22, 'kiran': 21, 'vinod': 21, 'sangam': 21}
dictionary after remove is : {'sai': 22, 'kiran': 21, 'sangam': 21}
Simple printf() function from O'Reilly's Python Cookbook.
import sys
def printf(format, *args):
sys.stdout.write(format % args)
Example output:
i = 7
pi = 3.14159265359
printf("hi there, i=%d, pi=%.2f\n", i, pi)
# hi there, i=7, pi=3.14
If you want the year from a (unknown) datetime-object:
tijd = datetime.datetime(9999, 12, 31, 23, 59, 59)
>>> tijd.timetuple()
time.struct_time(tm_year=9999, tm_mon=12, tm_mday=31, tm_hour=23, tm_min=59, tm_sec=59, tm_wday=4, tm_yday=365, tm_isdst=-1)
>>> tijd.timetuple().tm_year
9999
Technically not an answer to this, but a good use of the accepted answer (https://stackoverflow.com/a/20928975/82028) to create next and prev buttons for the tabs on jQuery ACF fields:
$('.next').click(function () {
$('#primary li.active').next().find('.acf-tab-button')[0].click();
});
$('.prev').click(function () {
$('#primary li.active').prev().find('.acf-tab-button')[0].click();
});
I just add small detail:
new FileWriter("outfilename", true)
2.nd parameter (true) is a feature (or, interface) called appendable (http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html). It is responsible for being able to add some content to the end of particular file/stream. This interface is implemented since Java 1.5. Each object (i.e. BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer) with this interface can be used for adding content
In other words, you can add some content to your gzipped file, or some http process
Imagine you are the manager of a software company and you just bought a brand new server. Just the hardware.
Think of Dockerfile
as a set of instructions you would tell your system adminstrator what to install on this brand new server. For example:
/var/www
)By contrast, think of docker-compose.yml
as a set of instructions you would tell your system administrator how the server can interact with the rest of the world. For example,
(This is not a precise explanation but good enough to start with.)
c:out
escapes HTML characters so that you can avoid cross-site scripting.
if person.name = <script>alert("Yo")</script>
the script will be executed in the second case, but not when using c:out
Use PHP Document Object Model:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
$DOM = new DOMDocument;
$DOM->loadHTML($str);
//get all H1
$items = $DOM->getElementsByTagName('h1');
//display all H1 text
for ($i = 0; $i < $items->length; $i++)
echo $items->item($i)->nodeValue . "<br/>";
?>
This outputs as:
T1
T2
T3
[EDIT]: After OP Clarification:
If you want the content like Lorem ipsum. etc, you can directly use this regex:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>
this outputs:
Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG
This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.
<input type="date" data-date-inline-picker="true" />
Here is a small demo
At the end of the ~.profile file add::
export GOPATH="$HOME/go"
export PATH="$PATH:/usr/local/go/bin"
export PATH="$PATH:$GOPATH/bin"
Take a look here,
html file
<div class='progress' id="progress_div">
<div class='bar' id='bar1'></div>
<div class='percent' id='percent1'></div>
</div>
<div id="wrapper">
<div id="content">
<h1>Display Progress Bar While Page Loads Using jQuery<p>TalkersCode.com</p></h1>
</div>
</div>
js file
document.onreadystatechange = function(e) {
if (document.readyState == "interactive") {
var all = document.getElementsByTagName("*");
for (var i = 0, max = all.length; i < max; i++) {
set_ele(all[i]);
}
}
}
function check_element(ele) {
var all = document.getElementsByTagName("*");
var totalele = all.length;
var per_inc = 100 / all.length;
if ($(ele).on()) {
var prog_width = per_inc + Number(document.getElementById("progress_width").value);
document.getElementById("progress_width").value = prog_width;
$("#bar1").animate({
width: prog_width + "%"
}, 10, function() {
if (document.getElementById("bar1").style.width == "100%") {
$(".progress").fadeOut("slow");
}
});
} else {
set_ele(ele);
}
}
function set_ele(set_element) {
check_element(set_element);
}
it definitely solve your problem for complete tutorial here is the link http://talkerscode.com/webtricks/display-progress-bar-while-page-loads-using-jquery.php
Here's the same test as above with the modification of calling the toString() method on the StringBuilder. The results below show that the StringBuilder approach is just a bit slower than String concatenation using the + operator.
file: StringTest.java
class StringTest {
public static void main(String[] args) {
String formatString = "Hi %s; Hi to you %s";
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s = String.format(formatString, i, +i * 2);
}
long end = System.currentTimeMillis();
System.out.println("Format = " + ((end - start)) + " millisecond");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
String s = "Hi " + i + "; Hi to you " + i * 2;
}
end = System.currentTimeMillis();
System.out.println("Concatenation = " + ((end - start)) + " millisecond");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
StringBuilder bldString = new StringBuilder("Hi ");
bldString.append(i).append("Hi to you ").append(i * 2).toString();
}
end = System.currentTimeMillis();
System.out.println("String Builder = " + ((end - start)) + " millisecond");
}
}
Shell Commands : (compile and run StringTest 5 times)
> javac StringTest.java
> sh -c "for i in \$(seq 1 5); do echo \"Run \${i}\"; java StringTest; done"
Results :
Run 1
Format = 1290 millisecond
Concatenation = 115 millisecond
String Builder = 130 millisecond
Run 2
Format = 1265 millisecond
Concatenation = 114 millisecond
String Builder = 126 millisecond
Run 3
Format = 1303 millisecond
Concatenation = 114 millisecond
String Builder = 127 millisecond
Run 4
Format = 1297 millisecond
Concatenation = 114 millisecond
String Builder = 127 millisecond
Run 5
Format = 1270 millisecond
Concatenation = 114 millisecond
String Builder = 126 millisecond
Checking in from 2015: We now have native promises in most recent browser (Edge 12, Firefox 40, Chrome 43, Safari 8, Opera 32 and Android browser 4.4.4 and iOS Safari 8.4, but not Internet Explorer, Opera Mini and older versions of Android).
If we want to perform 10 async actions and get notified when they've all finished, we can use the native Promise.all
, without any external libraries:
function asyncAction(i) {
return new Promise(function(resolve, reject) {
var result = calculateResult();
if (result.hasError()) {
return reject(result.error);
}
return resolve(result);
});
}
var promises = [];
for (var i=0; i < 10; i++) {
promises.push(asyncAction(i));
}
Promise.all(promises).then(function AcceptHandler(results) {
handleResults(results),
}, function ErrorHandler(error) {
handleError(error);
});
Use $http_MY_CUSTOM_HEADER
You can write some-thing like
set my_header $http_MY_CUSTOM_HEADER;
if($my_header != 'some-value') {
#do some thing;
}
df = df_try
for i in range(4):
df = df.append(df_try)
# Here, we have df_try times 5
df = df.append(df)
# Here, we have df_try times 10
findByInventoryIdIn(List<Long> inventoryIdList)
should do the trick.
The HTTP request parameter format would be like so:
Yes ?id=1,2,3
No ?id=1&id=2&id=3
The complete list of JPA repository keywords can be found in the current documentation listing. It shows that IsIn
is equivalent – if you prefer the verb for readability – and that JPA also supports NotIn
and IsNotIn
.
Try this:
[ -z "$STATE" ] && echo "Need to set STATE" && exit 1;
In my example i am adding an ImageView to a LinearLayout programatically. I have set top and bottom margins to ImagerView. Then adding the ImageView to the LinearLayout.
ImageView imageView = new ImageView(mContext);
imageView.setImageBitmap(bitmap);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(0, 20, 0, 40);
imageView.setLayoutParams(params);
linearLayout.addView(imageView);
Found these docu on the google docu pages:
In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns
edit
Using the example on the docu:
// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);
The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G
So you come to the range: C2:G8
You can use table proc in database mysql:
mysql> SELECT body FROM mysql.proc
WHERE db = 'yourdb' AND name = 'procedurename' ;
Note that you must have a grant for select to mysql.proc:
mysql> GRANT SELECT ON mysql.proc TO 'youruser'@'yourhost' IDENTIFIED BY 'yourpass' ;
Bassed on the excellent answer of T.J. Crowder: (Off-topic: Avoid cluttering window
)
This is an example of his idea:
Html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="init.js"></script>
<script type="text/javascript">
MYLIBRARY.init(["firstValue", 2, "thirdValue"]);
</script>
<script src="script.js"></script>
</head>
<body>
<h1>Hello !</h1>
</body>
</html>
init.js (Based on this answer)
var MYLIBRARY = MYLIBRARY || (function(){
var _args = {}; // private
return {
init : function(Args) {
_args = Args;
// some other initialising
},
helloWorld : function(i) {
return _args[i];
}
};
}());
script.js
// Here you can use the values defined in the html as if it were a global variable
var a = "Hello World " + MYLIBRARY.helloWorld(2);
alert(a);
Here's the plnkr. Hope it help !
With this you can remove the column
and store variable
into another variable
.
df = subset(data, select = -c(genome) )
Aside from the long list of remove commands in your question, which seems quite comprehensive in my recent experience of exactly this issue, I found mysql.sock running in /private/var and removed that. I used
find / -name mysql -print 2> /dev/null
...to find anything that looked like a mysql directory or file and removed most of what came up (aside from Perl/Python access modules). You may also need to check that the daemon is not still running using Activity Monitor (or at the command line using ps -A
). I found that mysqld was still running even after deleting the files.
import datetime
d = datetime.date(2012, 9, 1)
print type(d) is datetime.date
> True
I'm not sure you have gotten past this yet, but I had to work on something very similar today and I got your fiddle working like you are asking, basically what I did was make another table row under it, and then used the accordion control. I tried using just collapse but could not get it working and saw an example somewhere on SO that used accordion.
Here's your updated fiddle: http://jsfiddle.net/whytheday/2Dj7Y/11/
Since I need to post code here is what each collapsible "section" should look like ->
<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle">
<td>1</td>
<td>05 May 2013</td>
<td>Credit Account</td>
<td class="text-success">$150.00</td>
<td class="text-error"></td>
<td class="text-success">$150.00</td>
</tr>
<tr>
<td colspan="6" class="hiddenRow">
<div class="accordion-body collapse" id="demo1">Demo1</div>
</td>
</tr>
FWIW-- My problem was due to using a really old config file instead of a newer one. Using the new configuration file (and thus tweaked/changed DSL) fixed my problems instantly.
Put the UNIQUE declaration within the column definition section; working example:
CREATE TABLE a (
i INT,
j INT,
UNIQUE(i, j) ON CONFLICT REPLACE
);
This can be useful too
create table #test (id int,name varchar(10))
--use separate inserts on older versions of SQL Server
insert into #test values (1,'Peter'), (1,'Paul'), (1,'Mary'), (2,'Alex'), (3,'Jack')
DECLARE @t VARCHAR(255)
SELECT @t = ISNULL(@t + ',' + name, name) FROM #test WHERE id = 1
select @t
drop table #test
returns
Peter,Paul,Mary
The best way to force the use of a number composed of digits only:
<input type="number" onkeydown="javascript: return event.keyCode === 8 ||_x000D_
event.keyCode === 46 ? true : !isNaN(Number(event.key))" />
_x000D_
To allow number keys only:
isNaN(Number(event.key))
but accept "Backspace" (keyCode: 8) and "Delete" (keyCode: 46) ...
You can use readonly
attribute, if you want your input only to be read. And you can use disabled
attribute, if you want input to be shown, but totally disabled (even processing languages like PHP wont be able to read those).
I had a similar issue thanks @ford04 helped me out.
However, another error occurred.
NB. I am using ReactJS hooks
ndex.js:1 Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.
What causes the error?
import {useHistory} from 'react-router-dom'
const History = useHistory()
if (true) {
history.push('/new-route');
}
return (
<>
<render component />
</>
)
This could not work because despite you are redirecting to new page all state and props are being manipulated on the dom or simply rendering to the previous page did not stop.
What solution I found
import {Redirect} from 'react-router-dom'
if (true) {
return <redirect to="/new-route" />
}
return (
<>
<render component />
</>
)
Very simple to solve this problem.
Just open RUN window(Window+R) and type services.msc
:
Find the SQL within name column and right click on that.
right click on SQL as in screenshot
You will get properties option, click on properties.
One new window will be open and there you have to click on Log On tab. And select the Local System Account. then apply and okay.
Select Local system Account
After that come again in services.msc
window. and right click on sql and click start.
And finally, SQL Server services started successfully. enjoy and keep learning.
Put your duration time in the non-hover selection:
li a {
background-color: #111;
transition:1s;
}
li a:hover {
padding:19px;
}
There are three basic types of join:
INNER
join compares two tables and only returns results where a match exists. Records from the 1st table are duplicated when they match multiple results in the 2nd. INNER joins tend to make result sets smaller, but because records can be duplicated this isn't guaranteed.CROSS
join compares two tables and return every possible combination of rows from both tables. You can get a lot of results from this kind of join that might not even be meaningful, so use with caution.OUTER
join compares two tables and returns data when a match is available or NULL values otherwise. Like with INNER join, this will duplicate rows in the one table when it matches multiple records in the other table. OUTER joins tend to make result sets larger, because they won't by themselves remove any records from the set. You must also qualify an OUTER join to determine when and where to add the NULL values:
LEFT
means keep all records from the 1st table no matter what and insert NULL values when the 2nd table doesn't match. RIGHT
means the opposite: keep all records from the 2nd table no matter what and insert NULL values whent he 1st table doesn't match. FULL
means keep all records from both tables, and insert a NULL value in either table if there is no match.Often you see will the OUTER
keyword omitted from the syntax. Instead it will just be "LEFT JOIN", "RIGHT JOIN", or "FULL JOIN". This is done because INNER and CROSS joins have no meaning with respect to LEFT, RIGHT, or FULL, and so these are sufficient by themselves to unambiguously indicate an OUTER join.
Here is an example of when you might want to use each type:
INNER
: You want to return all records from the "Invoice" table, along with their corresponding "InvoiceLines". This assumes that every valid Invoice will have at least one line.OUTER
: You want to return all "InvoiceLines" records for a particular Invoice, along with their corresponding "InventoryItem" records. This is a business that also sells service, such that not all InvoiceLines will have an IventoryItem.CROSS
: You have a digits table with 10 rows, each holding values '0' through '9'. You want to create a date range table to join against, so that you end up with one record for each day within the range. By CROSS-joining this table with itself repeatedly you can create as many consecutive integers as you need (given you start at 10 to 1st power, each join adds 1 to the exponent). Then use the DATEADD() function to add those values to your base date for the range.if you want it without try and except then there is the solution
what you are trying to do is print 'hello' if 'harry' in a list then the solution is
'hello' if 'harry' in sam else ''
In general, I always put my enums in a struct
. I have seen several guidelines including "prefixing".
enum Color
{
Clr_Red,
Clr_Yellow,
Clr_Blue,
};
Always thought this looked more like C
guidelines than C++
ones (for one because of the abbreviation and also because of the namespaces in C++
).
So to limit the scope we now have two alternatives:
I personally tend to use a struct
because it can be used as parameters for template programming while a namespace cannot be manipulated.
Examples of manipulation include:
template <class T>
size_t number() { /**/ }
which returns the number of elements of enum inside the struct T
:)
You can also use following lines of code to get first and last date of the week:
var curr = new Date;
var firstday = new Date(curr.setDate(curr.getDate() - curr.getDay()));
var lastday = new Date(curr.setDate(curr.getDate() - curr.getDay()+6));
Hope it will be useful..
This query works for me:
SELECT DISTINCT
local_tcp_port
FROM sys.dm_exec_connections
WHERE local_tcp_port IS NOT NULL
What is the newline character in the C language: \r or \n?
The new-line may be thought of a some char
and it has the value of '\n'
. C11 5.2.1
This C new-line comes up in 3 places: C source code, as a single char
and as an end-of-line in file I/O when in text mode.
Many compilers will treat source text as ASCII. In that case, codes 10, sometimes 13, and sometimes paired 13,10 as new-line for source code. Had the source code been in another character set, different codes may be used. This new-line typically marks the end of a line of source code (actually a bit more complicated here), // comment, and # directives.
In source code, the 2 characters \
and n
represent the char
new-line as \n
. If ASCII is used, this char
would have the value of 10.
In file I/O, in text mode, upon reading the bytes of the input file (and stdin), depending on the environment, when bytes with the value(s) of 10 (Unix), 13,10, (*1) (Windows), 13 (Old Mac??) and other variations are translated in to a '\n'. Upon writing a file (or stdout), the reverse translation occurs.
Note: File I/O in binary mode makes no translation.
The '\r'
in source code is the carriage return char
.
(*1) A lone 13 and/or 10 may also translate into \n
.
Almost all Oracle deployments are done through SQL*Plus (that weird little command line tool that your DBA uses). And in SQL*Plus a lone slash basically means "re-execute last SQL or PL/SQL command that I just executed".
See
Rule of thumb would be to use slash with things that do BEGIN .. END
or where you can use CREATE OR REPLACE
.
For inserts that need to be unique use
INSERT INTO my_table ()
SELECT <values to be inserted>
FROM dual
WHERE NOT EXISTS (SELECT
FROM my_table
WHERE <identify data that you are trying to insert>)
If you want to upload the file /Applications/XAMPP/htdocs/keypairfile.pem
to ec2-user@publicdns:/var/www/html
, you can simply do:
scp -Cr /Applications/XAMPP/htdocs/keypairfile.pem/uploads/ ec2-user@publicdns:/var/www/html/
Where:
-C
- Compress data-r
- RecursiveNo.
The content-type should be whatever it is known to be, if you know it. application/octet-stream
is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.
You can combine the use of Content-Disposition
with other content-types, such as image/png
or even text/html
to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html
but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).
RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline
to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename
part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.
Hence:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"
Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"
Means "This is a PNG image. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: inline; filename="picture.png"
Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".
Of those browsers that recognise inline
some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).
From http://www.javaroots.com/2013/02/classnotfoundexception-vs.html:
ClassNotFoundException
: occurs when class loader could not find the required class in class path. So, basically you should check your class path and add the class in the classpath.
NoClassDefFoundError
: this is more difficult to debug and find the reason. This is thrown when at compile time the required classes are present, but at run time the classes are changed or removed or class's static initializes threw exceptions. It means the class which is getting loaded is present in classpath, but one of the classes which are required by this class are either removed or failed to load by compiler. So you should see the classes which are dependent on this class.
Example:
public class Test1
{
}
public class Test
{
public static void main(String[] args)
{
Test1 = new Test1();
}
}
Now after compiling both the classes, if you delete Test1.class file and run Test class, it will throw
Exception in thread "main" java.lang.NoClassDefFoundError: Test
at Test1.main(Test1.java:5)
Caused by: java.lang.ClassNotFoundException: Test
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
ClassNotFoundException
: thrown when an application tries to load in a class through its name, but no definition for the class with the specified name could be found.
NoClassDefFoundError
: thrown if the Java Virtual Machine tries to load in the definition of a class and no definition of the class could be found.
HTML:
<div class="container" id="parent">
<div class="row">
<div class="col-lg-12">text
<div class="row ">
<div class="col-md-4 col-md-offset-4" id="child">TEXT</div>
</div>
</div>
</div>
</div>
CSS:
#parent {
text-align: center;
}
#child {
margin: 0 auto;
display: inline-block;
background: red;
color: white;
}
I ran into this problem whenever running "git repack" or "git gc" on my OS X machines, even when running git with admin privileges, and I finally solved it after coming across this page: http://hints.macworld.com/comment.php?mode=view&cid=1734
The fix is to open a terminal, go to your git repo, cd into the .git folder, and then do:
chflags -R nouchg *
If that was the issue, then after that, your git commands will work as normal.
If you prefer, you can set these options via the commmand line (instead of editing the config file) like so:
$ git config branch.master.remote origin
$ git config branch.master.merge refs/heads/master
Or, if you're like me, and want this to be the default across all of your projects, including those you might work on in the future, then add it as a global config setting:
$ git config --global branch.master.remote origin
$ git config --global branch.master.merge refs/heads/master
To cast a double to an int and have it be rounded to the nearest integer (i.e. unlike the typical (int)(1.8)
and (int)(1.2)
, which will both "round down" towards 0 and return 1
), simply add 0.5 to the double
that you will typecast to an int
.
For example, if we have
double a = 1.2;
double b = 1.8;
Then the following typecasting expressions for x and y and will return the rounded-down values (x = 1
and y = 1
):
int x = (int)(a); // This equals (int)(1.2) --> 1
int y = (int)(b); // This equals (int)(1.8) --> 1
But by adding 0.5 to each, we will obtain the rounded-to-closest-integer result that we may desire in some cases (x = 1
and y = 2
):
int x = (int)(a + 0.5); // This equals (int)(1.8) --> 1
int y = (int)(b + 0.5); // This equals (int)(2.3) --> 2
As a small note, this method also allows you to control the threshold at which the double
is rounded up or down upon (int)
typecasting.
(int)(a + 0.8);
to typecast. This will only round up to (int)a + 1
whenever the decimal values are greater than or equal to 0.2. That is, by adding 0.8 to the double
immediately before typecasting, 10.15 and 10.03 will be rounded down to 10 upon (int)
typecasting, but 10.23 and 10.7 will be rounded up to 11.
Every time you call itr2.next() you are getting a distinct value. Not the same value. You should only call this once in the loop.
Iterator<String> itr2 = keys.iterator();
while(itr2.hasNext()){
String v = itr2.next();
System.out.println("Key: "+v+" ,value: "+m.get(v));
}
On a 3.4 GHz quad core 6 GB of RAM, Windows 7, the emulator was unusably slow!
I downloaded Launcher-Pro.apk
through the emulator, installed it and set it as the default launcher. It doubled my emulation speed! The screens load much smoother and faster. It doesn't seem to download in 2.1 or 2.2, only in 2.0.
This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.
There is a nice tool called DependencyWalker that you can download from http://www.dependencywalker.com . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.
One basic way that comes to mind would be to put the item into a table and have two cells, one with the text, the other with the image, and use style="valign:center" with the tags.
I needed the value of one cell, selected by column and index names. This solution worked for me:
original_conversion_frequency.loc[1,:].values[0]
You need to do 2 things :
1) Call setPreventCornerOverlap(false)
on your CardView.
2) Put rounded Imageview inside CardView
About rounding your imageview, I had the same problem so I made a library that you can set different radii on each corner. Finally I got the result what I wanted like below.
Try this
<input type="checkbox" style="zoom:1.5;" />
/* The value 1.5 i.e., the size of checkbox will be increased by 0.5% */
Check this.
This is a port of Mozilla Universal Charset Detector and you can use it like this...
public static void Main(String[] args)
{
string filename = args[0];
using (FileStream fs = File.OpenRead(filename)) {
Ude.CharsetDetector cdet = new Ude.CharsetDetector();
cdet.Feed(fs);
cdet.DataEnd();
if (cdet.Charset != null) {
Console.WriteLine("Charset: {0}, confidence: {1}",
cdet.Charset, cdet.Confidence);
} else {
Console.WriteLine("Detection failed.");
}
}
}
You can use these links to download Visual Studio 2015
Community Edition:
And for anyone in the future who might be looking for the other editions here are the links for them as well:
Professional Edition:
Enterprise Edition:
The ordinal() function returns the relative position of the identifier in the enum. You can use this to obtain automatic indexing with an offset, as with a C-style enum.
Example:
public class TestEnum {
enum ids {
OPEN,
CLOSE,
OTHER;
public final int value = 100 + ordinal();
};
public static void main(String arg[]) {
System.out.println("OPEN: " + ids.OPEN.value);
System.out.println("CLOSE: " + ids.CLOSE.value);
System.out.println("OTHER: " + ids.OTHER.value);
}
};
Gives the output:
OPEN: 100
CLOSE: 101
OTHER: 102
Edit: just realized this is very similar to ggrandes' answer, but I will leave it here because it is very clean and about as close as you can get to a C style enum.
Wrong syntax. You can't compare a Boolean to a string like "false" or "true". In your case, just test it's inverse:
if(!ValidateForm()) { ...
You could test against the constant false, but it's rather ugly and generally frowned upon:
if(ValidateForm() == false) { ...
The easiest solution I found to this problem was to downgrade the MySql from MySQL Workbench to MySQL Version 1.2.17. I had browsed some MySQL Forums, where it was said that the timeout time in MySQL Workbech has been hard coded to 600 and some suggested methods to change it didn't work for me. If someone is facing the same problem with workbench you could try downgrading too.
Edit: I have just explained logic to pair here. If anybody want to go with the complete code then see my another answer. I have answered here for logic only but I was not able to explain properly, So I have added another answer in the same thread.
Try this to do pairing:
If you are able to search the devices then this would be your next step
ArrayList<BluetoothDevice> arrayListBluetoothDevices = NEW ArrayList<BluetoothDevice>;
I am assuming that you have the list of Bluetooth devices added in the arrayListBluetoothDevices
:
BluetoothDevice bdDevice;
bdDevice = arrayListBluetoothDevices.get(PASS_THE_POSITION_TO_GET_THE_BLUETOOTH_DEVICE);
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
Log.i("Log","Paired");
}
} catch (Exception e)
{
e.printStackTrace();
}
The createBond()
method:
public boolean createBond(BluetoothDevice btDevice)
throws Exception
{
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
Add this line into your Receiver in the ACTION_FOUND
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
arrayListBluetoothDevices.add(device);
}
After you run MySQL Shell and you have seen following:
mysql-js>
Firstly, you should:
mysql-js>\sql
Secondly:
mysql-sql>\connect username@servername (root@localhost)
And finally:
Enter password:*********
It is a cache, ofc it refreshes, that's what cache is ment to do once in a while. So waiting will eventually work but sometimes you need to do that faster. Changing the filename works.
You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.
You should be doing something more like this:
class MyClassTest
{
[TestMethod]
public void MyMethodTest()
{
string action = "test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.Setup(mock => mock.DoSomething());
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
// Explicitly verify each expectation...
mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
// ...or verify everything.
// mockSomeClass.VerifyAll();
}
}
In other words, you are verifying that calling MyClass#MyMethod
, your class will definitely call SomeClass#DoSomething
once in that process. Note that you don't need the Times
argument; I was just demonstrating its value.
Static fields and methods are connected to the class itself and not its instances. If you have a class A
, a 'normal' method b
, and a static method c
, and you make an instance a
of your class A
, the calls to A.c()
and a.b()
are valid. Method c()
has no idea which instance is connected, so it cannot use non-static fields.
The solution for you is that you either make your fields static or your methods non-static. You main could look like this then:
class Programm {
public static void main(String[] args) {
Programm programm = new Programm();
programm.start();
}
public void start() {
// can now access non-static fields
}
}
The simplest solution for this problem:
First make sure your sdk path is currect. Then Please close current project and in android startup menu click on import project and choose your project from explorer. This will always solve my problem
The schema definition should be unique for a collection, it should not be more then one schema for a collection.
When building apps for 32-bit or 64-bit platform (My experience is with Visual Studio 2010), don't rely on the Configuration Manager to set the correct platform for the executable. Even if the CM has x86 selected for the application, check the project properties (Build tab): it might still say "Any CPU" there. And if you run an "Any CPU" executable on a 64-bit platform, it will run in 64-bit mode and refuse to load your accompanying DLLs that were built for the x86 platform.
If you can't use rgba
due to browser support, and you don't want to include a semi-transparent white PNG, you will have to create two positioned elements. One for the white box, with opacity, and one for the overlaid text, solid.
body { background: red; }_x000D_
_x000D_
.box { position: relative; z-index: 1; }_x000D_
.box .back {_x000D_
position: absolute; z-index: 1;_x000D_
top: 0; left: 0; width: 100%; height: 100%;_x000D_
background: white; opacity: 0.75;_x000D_
}_x000D_
.box .text { position: relative; z-index: 2; }_x000D_
_x000D_
body.browser-ie8 .box .back { filter: alpha(opacity=75); }
_x000D_
<!--[if lt IE 9]><body class="browser-ie8"><![endif]-->_x000D_
<!--[if gte IE 9]><!--><body><!--<![endif]-->_x000D_
<div class="box">_x000D_
<div class="back"></div>_x000D_
<div class="text">_x000D_
Lorem ipsum dolor sit amet blah blah boogley woogley oo._x000D_
</div>_x000D_
</div>_x000D_
</body>
_x000D_
@Cody Toombs's answer lead to an issue that brings the layout behind the navigation bar. So what I found is using this solution given by @Kriti
here is the Kotlin code snippet for the same:
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true)
}
if (Build.VERSION.SDK_INT >= 19) {
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
}
if (Build.VERSION.SDK_INT >= 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false)
getWindow().setStatusBarColor(Color.TRANSPARENT)
}
private fun setWindowFlag(activity: Activity, bits: Int, on: Boolean) {
val win: Window = activity.getWindow()
val winParams: WindowManager.LayoutParams = win.getAttributes()
if (on) {
winParams.flags = winParams.flags or bits
} else {
winParams.flags = winParams.flags and bits.inv()
}
win.setAttributes(winParams)
}
You also need to add
android:fitsSystemWindows="false"
root view of your layout.
You can just specify the generic octet-stream MIME type:
public FileResult Download()
{
byte[] fileBytes = System.IO.File.ReadAllBytes(@"c:\folder\myfile.ext");
string fileName = "myfile.ext";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
In the near future you may be able to use the ::marker
psuedo-element to achieve the same result as other solutions in just one line of code.
Remember to check the Browser Compatibility Table as this is still an experimental technology. At the moment of writing only Firefox and Firefox for Android, starting from version 68, support this.
Here is a snippet that will render correctly if tried in a compatible browser:
::marker { content: counters(list-item,'.') ':' }_x000D_
li { padding-left: 0.5em }
_x000D_
<ol>_x000D_
<li>li element_x000D_
<ol>_x000D_
<li>sub li element</li>_x000D_
<li>sub li element</li>_x000D_
<li>sub li element</li>_x000D_
</ol>_x000D_
</li>_x000D_
<li>li element</li>_x000D_
<li>li element_x000D_
<ol>_x000D_
<li>sub li element</li>_x000D_
<li>sub li element</li>_x000D_
<li>sub li element</li>_x000D_
</ol>_x000D_
</li>_x000D_
</ol>
_x000D_
You may also want to check out this great article by smashingmagazine on the topic.
Answer to my question (after several Google searches) revealed the following:
$ curl https://pkgconfig.freedesktop.org/releases/pkg-config-0.29.tar.gz -o pkgconfig.tgz
$ tar -zxf pkgconfig.tgz && cd pkg-config-0.29
$ ./configure && make install
from the following link: Link showing above
Thanks to everyone for their comments, and sorry for my linux/OSX ignorance!
Doing this fixed my issues as mentioned above.
An alternative to using keytool
, you can use the command
openssl x509 -in certificate.pem -text
This should work for any x509 .pem file provided you have openssl
installed.
I had the same error, but I had it fixed by modifying the php.ini and / or editing the PHP file!
There are two different methods to get around the parse error syntax.
Avoid in your PHP file this:
<? } ?>
Make sure you put it like this
<?php ?>
Your code contains
<? ?>
NOTE: The missing
php
after<?
!
There is also a simple way to solve your problem.
Search for the short_open_tag
property value (Use in your text editor with Ctrl + F
!), and apply the following change:
; short_open_tag = Off
to
short_open_tag = On
According to the description of core php.ini directives, short_open_tag
allows you to use the short open tag (<?
) although this might cause issues when used with xml (<?xml
will not work when this is enabled)!
NOTE: Reload your Server (like for example: Apache) and reload your PHP webpage in your browser.
if you are using XDocument.Load(url);
to fetch xml from another domain, it's possible that the host will reject the request and return and unexpected (non-xml) result, which results in the above XmlException
See my solution to this eventuality here: XDocument.Load(feedUrl) returns "Data at the root level is invalid. Line 1, position 1."
If you work in MS Visual Studio just do following
Correct WSDL file like this YourSchemeFile.xsd
Use visual Studio using this great example How to generate service reference with only physical wsdl file
Notice that you have to put the path to your WSDL file manually. There is no way to use Open File dialog box out there.
You can do something just like this.
IF EXISTS ( SELECT * FROM TableName WHERE Column=colval)
BEGIN
select
select name ,Id from TableName WHERE Column=colval
END
ELSE
SELECT 'test' as name,0 as Id
Got the following to work May 2018 with ES6 React Docs as a reference: https://reactjs.org/docs/refs-and-the-dom.html
import React, { Component } from "react";
class AddImage extends Component {
constructor(props) {
super(props);
this.fileUpload = React.createRef();
this.showFileUpload = this.showFileUpload.bind(this);
}
showFileUpload() {
this.fileUpload.current.click();
}
render() {
return (
<div className="AddImage">
<input
type="file"
id="my_file"
style={{ display: "none" }}
ref={this.fileUpload}
/>
<input
type="image"
src="http://www.graphicssimplified.com/wp-content/uploads/2015/04/upload-cloud.png"
width="30px"
onClick={this.showFileUpload}
/>
</div>
);
}
}
export default AddImage;
I just tried to get path of shared preferences below like this.This is work for me.
File f = getDatabasePath("MyPrefsFile.xml");
if (f != null)
Log.i("TAG", f.getAbsolutePath());
Late answer, but I just came on this list today!
CREATE TABLE assignment_20101120 AS SELECT * FROM assignment;
Does the same.
The PowerShell execution policy is default set to Restricted. You can change the PowerShell execution policies with Set-ExecutionPolicy cmdlet. To run outside script set policy to RemoteSigned.
PS C:> Set-ExecutionPolicy RemoteSigned Below is the list of four different execution policies in PowerShell
Restricted – No scripts can be run. AllSigned – Only scripts signed by a trusted publisher can be run. RemoteSigned – Downloaded scripts must be signed by a trusted publisher. Unrestricted – All Windows PowerShell scripts can be run.
Actually the only two strategies you would want to choose are ours if you want to abandon changes brought by branch, but keep the branch in history, and subtree if you are merging independent project into subdirectory of superproject (like 'git-gui' in 'git' repository).
octopus merge is used automatically when merging more than two branches. resolve is here mainly for historical reasons, and for when you are hit by recursive merge strategy corner cases.
PHPSESSID
reveals you are using PHP. If you don't want this you can easily change the name using the session.name
in your php.ini file or using the session_name()
function.
RTM
From the docs for the Python random
module:
Functions for integers:
random.randrange(stop)
random.randrange(start, stop[, step])
Return a randomly selected element from range(start, stop, step).
This is equivalent to choice(range(start, stop, step)), but doesn’t
actually build a range object.
That explains why it only gives you 0, doesn't it. range(0,1)
is [0]
. It is choosing from a list consisting of only that value.
Also from those docs:
random.random()
Return the next random floating point number in the range [0.0, 1.0).
But if your inclusion of the numpy
tag is intentional, you can generate many random floats in that range with one call using a np.random
function.
Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag
This means that you are trying to return multiple sibling JSX elements in an incorrect manner. Remember that you are not writing HTML, but JSX! Your code is transpiled from JSX into JavaScript. For example:
render() {
return (<p>foo bar</p>);
}
will be transpiled into:
render() {
return React.createElement("p", null, "foo bar");
}
Unless you are new to programming in general, you already know that functions/methods (of any language) take any number of parameters but always only return one value. Given that, you can probably see that a problem arises when trying to return multiple sibling components based on how createElement()
works; it only takes parameters for one element and returns that. Hence we cannot return multiple elements from one function call.
So if you've ever wondered why this works...
render() {
return (
<div>
<p>foo</p>
<p>bar</p>
<p>baz</p>
</div>
);
}
but not this...
render() {
return (
<p>foo</p>
<p>bar</p>
<p>baz</p>
);
}
it's because in the first snippet, both <p>
-elements are part of children
of the <div>
-element. When they are part of children
then we can express an unlimited number of sibling elements. Take a look how this would transpile:
render() {
return React.createElement(
"div",
null,
React.createElement("p", null, "foo"),
React.createElement("p", null, "bar"),
React.createElement("p", null, "baz"),
);
}
Depending on which version of React you are running, you do have a few options to address this:
As of React v16.2, React has support for Fragments which is a node-less component that returns its children directly.
Returning the children in an array (see below) has some drawbacks:
- Children in an array must be separated by commas.
- Children in an array must have a key to prevent React’s key warning.
- Strings must be wrapped in quotes.
These are eliminated from the use of fragments. Here's an example of children wrapped in a fragment:
render() {
return (
<>
<ChildA />
<ChildB />
<ChildC />
</>
);
}
which de-sugars into:
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
}
Note that the first snippet requires Babel v7.0 or above.
As of React v16, React Components can return arrays. This is unlike earlier versions of React where you were forced to wrap all sibling components in a parent component.
In other words, you can now do:
render() {
return [<p key={0}>foo</p>, <p key={1}>bar</p>];
}
this transpiles into:
return [React.createElement("p", {key: 0}, "foo"), React.createElement("p", {key: 1}, "bar")];
Note that the above returns an array. Arrays are valid React Elements since React version 16 and later. For earlier versions of React, arrays are not valid return objects!
Also note that the following is invalid (you must return an array):
render() {
return (<p>foo</p> <p>bar</p>);
}
The other solution involves creating a parent component which wraps the sibling components in its children
. This is by far the most common way to address this issue, and works in all versions of React.
render() {
return (
<div>
<h1>foo</h1>
<h2>bar</h2>
</div>
);
}
Note: Take a look again at the top of this answer for more details and how this transpiles.
While your mileage may vary, running npm cache verify
fixed the issue for me.
Possibly a more reliable way to get the up icon from your theme (if not using the toolbar as your action bar):
toolbar.navigationIcon = context.getDrawableFromAttribute(R.attr.homeAsUpIndicator)
In order to turn the theme attribute into a drawable I used an extension function:
fun Context.getDrawableFromAttribute(attributeId: Int): Drawable {
val typedValue = TypedValue().also { theme.resolveAttribute(attributeId, it, true) }
return resources.getDrawable(typedValue.resourceId, theme)
}
Go to you MainActivity.java
and below this code
-> NavigationView navigationView = findViewById(R.id.nav_view);
Add single line of code -> navigationView.setItemIconTintList(null);
i.e. the last line of my code
I hope this might solve your problem.
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setItemIconTintList(null);
You need to include the protocol scheme:
'http://192.168.1.61:8080/api/call'
Without the http://
part, requests
has no idea how to connect to the remote server.
Note that the protocol scheme must be all lowercase; if your URL starts with HTTP://
for example, it won’t find the http://
connection adapter either.
The exception message is actually pretty descriptive. The contract it mentions is transitivity: if A > B
and B > C
then for any A
, B
and C
: A > C
. I checked it with paper and pencil and your code seems to have few holes:
if (card1.getRarity() < card2.getRarity()) {
return 1;
you do not return -1
if card1.getRarity() > card2.getRarity()
.
if (card1.getId() == card2.getId()) {
//...
}
return -1;
You return -1
if ids aren't equal. You should return -1
or 1
depending on which id was bigger.
Take a look at this. Apart from being much more readable, I think it should actually work:
if (card1.getSet() > card2.getSet()) {
return 1;
}
if (card1.getSet() < card2.getSet()) {
return -1;
};
if (card1.getRarity() < card2.getRarity()) {
return 1;
}
if (card1.getRarity() > card2.getRarity()) {
return -1;
}
if (card1.getId() > card2.getId()) {
return 1;
}
if (card1.getId() < card2.getId()) {
return -1;
}
return cardType - item.getCardType(); //watch out for overflow!
Try this:
$keys = array_keys($array, "Completed");
/edit As mentioned by JohnP, this method only works for non-nested arrays.
First, create the new branch you would like to set as your default, for example:
$>git branch main
Next, push that branch to the origin:
$>git push origin main
Now when you login to your GitHub account, you can go to your repository and choose Settings>Default Branch and choose "main."
Then, if you so choose, you can delete the master branch:
$>git push origin :master
A quick, non-elegant but working standalone solution with inline CSS and no jQuery requirements. AFAIK it works from IE9 too.
<body style="overflow:hidden; margin:0">
<form id="form1" runat="server">
<div id="main" style="background-color:red">
<div id="content">
</div>
<div id="footer">
</div>
</div>
</form>
<script language="javascript">
function autoResizeDiv()
{
document.getElementById('main').style.height = window.innerHeight +'px';
}
window.onresize = autoResizeDiv;
autoResizeDiv();
</script>
</body>
Whenever you're analyzing timing issues, debugging often does not help, as freezing the app at a breakpoint will make the problem go away.
Your best bet is to insert lots of logging calls (Log.XXX()) into the app's different threads and callbacks and see where the delay is at. If you need a stacktrace, create a new Exception (just instantiate one) and log it.
Your analysis is correct. However, it is not tight.
It is not really easy to explain why building a heap is a linear operation, you should better read it.
A great analysis of the algorithm can be seen here.
The main idea is that in the build_heap
algorithm the actual heapify
cost is not O(log n)
for all elements.
When heapify
is called, the running time depends on how far an element might move down in tree before the process terminates. In other words, it depends on the height of the element in the heap. In the worst case, the element might go down all the way to the leaf level.
Let us count the work done level by level.
At the bottommost level, there are 2^(h)
nodes, but we do not call heapify
on any of these, so the work is 0. At the next to level there are 2^(h - 1)
nodes, and each might move down by 1 level. At the 3rd level from the bottom, there are 2^(h - 2)
nodes, and each might move down by 2 levels.
As you can see not all heapify operations are O(log n)
, this is why you are getting O(n)
.
Even though the name is immutable, you may still want to have the option of computing it rather than storing it in a field. (I realize this is unlikely for "name", but let's aim for the general case.) For that reason, even constant fields are best wrapped inside of getters:
class Foo {
public:
const std::string& getName() const {return name_;}
private:
const std::string& name_;
};
Note that if you were to change getName()
to return a computed value, it couldn't return const ref. That's ok, because it won't require any changes to the callers (modulo recompilation.)
I store encoded HTML in the database.
Imho you should not store your data html-encoded in the database. Just store in plain text (not encoded) and just display your data like this and your html will be automatically encoded:
<div class='content'>
@Model.Content
</div>
Bit late for an answer but came with following option. It is working for me but not sure if it is the correct way or not.
In my view I'm doing this:
<form name="formName">
<div ng-init="setForm(formName);"></div>
</form>
And in the controller:
$scope.setForm = function (form) {
$scope.myForm = form;
}
Now after doing this I have got my form in my controller variable which is $scope.myForm
The following PHP worked for me (using mysqli extension but queries should be the same for other extensions):
$db = new mysqli( 'localhost', 'user', 'pass', 'dbname' );
// to get the max_allowed_packet
$maxp = $db->query( 'SELECT @@global.max_allowed_packet' )->fetch_array();
echo $maxp[ 0 ];
// to set the max_allowed_packet to 500MB
$db->query( 'SET @@global.max_allowed_packet = ' . 500 * 1024 * 1024 );
So if you've got a query you expect to be pretty long, you can make sure that mysql will accept it with something like:
$sql = "some really long sql query...";
$db->query( 'SET @@global.max_allowed_packet = ' . strlen( $sql ) + 1024 );
$db->query( $sql );
Notice that I added on an extra 1024 bytes to the length of the string because according to the manual,
The value should be a multiple of 1024; nonmultiples are rounded down to the nearest multiple.
That should hopefully set the max_allowed_packet size large enough to handle your query. I haven't tried this on a shared host, so the same caveat as @Glebushka applies.
While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig
takes a bbox_inches
argument that can be used to selectively save only a portion of a figure to an image.
Here's a quick example:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')
ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')
# Save the full figure...
fig.savefig('full_figure.png')
# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)
# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))
The full figure:
Area inside the second subplot:
Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction:
If your signatures differ only in the number of arguments, using default arguments is the right way to do it. If you want to be able to pass in different kinds of argument, I would try to avoid the isinstance
-based approach mentioned in another answer, and instead use keyword arguments.
If using just keyword arguments becomes unwieldy, you can combine it with classmethods (the bzrlib code likes this approach). This is just a silly example, but I hope you get the idea:
class C(object):
def __init__(self, fd):
# Assume fd is a file-like object.
self.fd = fd
@classmethod
def fromfilename(cls, name):
return cls(open(name, 'rb'))
# Now you can do:
c = C(fd)
# or:
c = C.fromfilename('a filename')
Notice all those classmethods still go through the same __init__
, but using classmethods can be much more convenient than having to remember what combinations of keyword arguments to __init__
work.
isinstance
is best avoided because Python's duck typing makes it hard to figure out what kind of object was actually passed in. For example: if you want to take either a filename or a file-like object you cannot use isinstance(arg, file)
, because there are many file-like objects that do not subclass file
(like the ones returned from urllib, or StringIO, or...). It's usually a better idea to just have the caller tell you explicitly what kind of object was meant, by using different keyword arguments.
if x
is numeric, then add scale_x_continuous()
; if x
is character/factor, then add scale_x_discrete()
. This might solve your problem.
The title
attribute works on most HTML tags and is widely supported by modern browsers.
For DD-MM-YY use this code:
var array = ["03-03-2017', '03-10-2017', '03-25-2017"]
$('#datepicker').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
return [ array.indexOf(string) == -1 ]
}
});
function highlightDays(date) {
for (var i = 0; i < dates.length; i++) {
if (new Date(dates[i]).toString() == date.toString()) {
return [true, 'highlight'];
}
}
return [true, ''];
}
in flask using flask.ext.script, you can do it like this:
python manage.py runserver -h 127.0.0.1 -p 8000
LIMIT limit OFFSET offset
will work.
But you need a stable ORDER BY
clause, or the values may be ordered differently for the next call (after any write on the table for instance).
SELECT *
FROM msgtable
WHERE cdate = '2012-07-18'
ORDER BY msgtable_id -- or whatever is stable
LIMIT 10
OFFSET 50; -- to skip to page 6
Use standard-conforming date style (ISO 8601 in my example), which works irregardless of your locale settings.
Paging will still shift if involved rows are inserted or deleted or changed in relevant columns. It has to.
To avoid that shift or for better performance with big tables use smarter paging strategies:
Using ASCII(RIGHT(ProductAlternateKey, 1))
you can see that the right most character in row 2 is a Line Feed or Ascii Character 10.
This can not be removed using the standard LTrim
RTrim
functions.
You could however use (REPLACE(ProductAlternateKey, CHAR(10), '')
You may also want to account for carriage returns and tabs. These three (Line feeds, carriage returns and tabs) are the usual culprits and can be removed with the following :
LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(ProductAlternateKey, CHAR(10), ''), CHAR(13), ''), CHAR(9), '')))
If you encounter any more "white space" characters that can't be removed with the above then try one or all of the below:
--NULL
Replace([YourString],CHAR(0),'');
--Horizontal Tab
Replace([YourString],CHAR(9),'');
--Line Feed
Replace([YourString],CHAR(10),'');
--Vertical Tab
Replace([YourString],CHAR(11),'');
--Form Feed
Replace([YourString],CHAR(12),'');
--Carriage Return
Replace([YourString],CHAR(13),'');
--Column Break
Replace([YourString],CHAR(14),'');
--Non-breaking space
Replace([YourString],CHAR(160),'');
This list of potential white space characters could be used to create a function such as :
Create Function [dbo].[CleanAndTrimString]
(@MyString as varchar(Max))
Returns varchar(Max)
As
Begin
--NULL
Set @MyString = Replace(@MyString,CHAR(0),'');
--Horizontal Tab
Set @MyString = Replace(@MyString,CHAR(9),'');
--Line Feed
Set @MyString = Replace(@MyString,CHAR(10),'');
--Vertical Tab
Set @MyString = Replace(@MyString,CHAR(11),'');
--Form Feed
Set @MyString = Replace(@MyString,CHAR(12),'');
--Carriage Return
Set @MyString = Replace(@MyString,CHAR(13),'');
--Column Break
Set @MyString = Replace(@MyString,CHAR(14),'');
--Non-breaking space
Set @MyString = Replace(@MyString,CHAR(160),'');
Set @MyString = LTRIM(RTRIM(@MyString));
Return @MyString
End
Go
Which you could then use as follows:
Select
dbo.CleanAndTrimString(ProductAlternateKey) As ProductAlternateKey
from DimProducts
Unfortunately, modules aren't supported by many browsers right now.
This feature is only just beginning to be implemented in browsers natively at this time. It is implemented in many transpilers, such as TypeScript and Babel, and bundlers such as Rollup and Webpack.
Found on MDN
Below code will only print files within directory and exclude directories within given directory while traversing.
#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include<string.h>
int main(void)
{
DIR *d;
struct dirent *dir;
char path[1000]="/home/joy/Downloads";
d = opendir(path);
char full_path[1000];
if (d)
{
while ((dir = readdir(d)) != NULL)
{
//Condition to check regular file.
if(dir->d_type==DT_REG){
full_path[0]='\0';
strcat(full_path,path);
strcat(full_path,"/");
strcat(full_path,dir->d_name);
printf("%s\n",full_path);
}
}
closedir(d);
}
return(0);
}
export VAR=value
will set VAR to value. Enclose it in single quotes if you want spaces, like export VAR='my val'
. If you want the variable to be interpolated, use double quotes, like export VAR="$MY_OTHER_VAR"
.
The two functions below I have found to be very useful when dealing with many variable testing cases.
def nz(value, none_value, strict=True):
''' This function is named after an old VBA function. It returns a default
value if the passed in value is None. If strict is False it will
treat an empty string as None as well.
example:
x = None
nz(x,"hello")
--> "hello"
nz(x,"")
--> ""
y = ""
nz(y,"hello")
--> ""
nz(y,"hello", False)
--> "hello" '''
if value is None and strict:
return_val = none_value
elif strict and value is not None:
return_val = value
elif not strict and not is_not_null(value):
return_val = none_value
else:
return_val = value
return return_val
def is_not_null(value):
''' test for None and empty string '''
return value is not None and len(str(value)) > 0
You may also want to check your $PYTHONPATH
. I had changed mine in ~/.bashrc
in order to get another package to work.
To check your path:
echo $PYTHONPATH
To change your path (I use nano but you could edit another way)
nano ~/.bashrc
Look for the line with export PYTHONPATH
...
After making changes, don't forget to
source ~/.bashrc
It's true that if your primary key is just a identity value auto incremented, you would have no real use for ON UPDATE CASCADE.
However, let's say that your primary key is a 10 digit UPC bar code and because of expansion, you need to change it to a 13-digit UPC bar code. In that case, ON UPDATE CASCADE would allow you to change the primary key value and any tables that have foreign key references to the value will be changed accordingly.
In reference to #4, if you change the child ID to something that doesn't exist in the parent table (and you have referential integrity), you should get a foreign key error.
Based on @danijels's answer, dynamically create a class in VB.NET:
Imports System.Reflection
Imports System.Reflection.Emit
Public Class ObjectBuilder
Public Property myType As Object
Public Property myObject As Object
Public Sub New(fields As List(Of Field))
myType = CompileResultType(fields)
myObject = Activator.CreateInstance(myType)
End Sub
Public Shared Function CompileResultType(fields As List(Of Field)) As Type
Dim tb As TypeBuilder = GetTypeBuilder()
Dim constructor As ConstructorBuilder = tb.DefineDefaultConstructor(MethodAttributes.[Public] Or MethodAttributes.SpecialName Or MethodAttributes.RTSpecialName)
For Each field In fields
CreateProperty(tb, field.Name, field.Type)
Next
Dim objectType As Type = tb.CreateType()
Return objectType
End Function
Private Shared Function GetTypeBuilder() As TypeBuilder
Dim typeSignature = "MyDynamicType"
Dim an = New AssemblyName(typeSignature)
Dim assemblyBuilder As AssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run)
Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MainModule")
Dim tb As TypeBuilder = moduleBuilder.DefineType(typeSignature, TypeAttributes.[Public] Or TypeAttributes.[Class] Or TypeAttributes.AutoClass Or TypeAttributes.AnsiClass Or TypeAttributes.BeforeFieldInit Or TypeAttributes.AutoLayout, Nothing)
Return tb
End Function
Private Shared Sub CreateProperty(tb As TypeBuilder, propertyName As String, propertyType As Type)
Dim fieldBuilder As FieldBuilder = tb.DefineField("_" & propertyName, propertyType, FieldAttributes.[Private])
Dim propertyBuilder As PropertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, Nothing)
Dim getPropMthdBldr As MethodBuilder = tb.DefineMethod("get_" & propertyName, MethodAttributes.[Public] Or MethodAttributes.SpecialName Or MethodAttributes.HideBySig, propertyType, Type.EmptyTypes)
Dim getIl As ILGenerator = getPropMthdBldr.GetILGenerator()
getIl.Emit(OpCodes.Ldarg_0)
getIl.Emit(OpCodes.Ldfld, fieldBuilder)
getIl.Emit(OpCodes.Ret)
Dim setPropMthdBldr As MethodBuilder = tb.DefineMethod("set_" & propertyName, MethodAttributes.[Public] Or MethodAttributes.SpecialName Or MethodAttributes.HideBySig, Nothing, {propertyType})
Dim setIl As ILGenerator = setPropMthdBldr.GetILGenerator()
Dim modifyProperty As Label = setIl.DefineLabel()
Dim exitSet As Label = setIl.DefineLabel()
setIl.MarkLabel(modifyProperty)
setIl.Emit(OpCodes.Ldarg_0)
setIl.Emit(OpCodes.Ldarg_1)
setIl.Emit(OpCodes.Stfld, fieldBuilder)
setIl.Emit(OpCodes.Nop)
setIl.MarkLabel(exitSet)
setIl.Emit(OpCodes.Ret)
propertyBuilder.SetGetMethod(getPropMthdBldr)
propertyBuilder.SetSetMethod(setPropMthdBldr)
End Sub
End Class
How can I decrypt MySQL passwords
You can't really because they are hashed and not encrypted.
Here's the essence of the PASSWORD
function that current MySQL uses. You can execute it from the sql terminal:
mysql> SELECT SHA1(UNHEX(SHA1("password")));
+------------------------------------------+
| SHA1(UNHEX(SHA1("password"))) |
+------------------------------------------+
| 2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
+------------------------------------------+
1 row in set (0.00 sec)
How can I change or retrieve these?
If you are having trouble logging in on a debian or ubuntu system, first try this (thanks to tohuwawohu at https://askubuntu.com/questions/120718/cant-log-to-mysql):
$ sudo cat /etc/mysql/debian.conf | grep -i password
...
password: QWERTY12345...
Then, log in with the debian maintenance user:
$ mysql -u debian-sys-maint -p
password:
Finally, change the user's password:
mysql> UPDATE mysql.user SET Password=PASSWORD('new password') WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> quit;
When I look in the PHPmyAdmin the passwords are encrypted
Related, if you need to dump the user database for the relevant information, try:
mysql> SELECT User,Host,Password FROM mysql.user;
+------------------+-----------+----------------------+
| User | Host | Password |
+------------------+-----------+----------------------+
| root | localhost | *0123456789ABCDEF... |
| root | 127.0.0.1 | *0123456789ABCDEF... |
| root | ::1 | *0123456789ABCDEF... |
| debian-sys-maint | localhost | *ABCDEF0123456789... |
+------------------+-----------+----------------------+
And yes, those passwords are NOT salted. So an attacker can prebuild the tables and apply them to all MySQL installations. In addition, the adversary can learn which users have the same passwords.
Needles to say, the folks at mySQL are not following best practices. John Steven did an excellent paper on Password Storage Best Practice at OWASP's Password Storage Cheat Sheet. In fairness to the MySQL folks, they may be doing it because of pain points in the architecture, design or implementation (I simply don't know).
If you use the PASSWORD
and UPDATE
commands and the change does not work, then see http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html. Even though the page is named "resetting permissions", its really about how to change a password. (Its befuddling the MySQL password change procedure is so broken that you have to jump through the hoops, but it is what it is).
Use this css
.close-image {
cursor: pointer;
z-index: 3;
right: 5px;
top: 5px;
position: absolute;
}
The solution from @Default works perfect on Chrome (thanks a lot for that!) but I had a problem with IE.
Here's a solution (works on IE10):
var csvContent=data; //here we load our csv data
var blob = new Blob([csvContent],{
type: "text/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, "filename.csv")
Just right click on that column and select properties and write getdate()
in Default value or binding
.like image:
If you want do it in CodeFirst
in EF
you should add this attributes befor of your column definition:
[Databasegenerated(Databaseoption.computed)]
this attributes can found in System.ComponentModel.Dataannotion.Schema
.
In my opinion first one is better:))
In order to capture deadlock graphs without using a trace (you don't need profiler necessarily), you can enable trace flag 1222. This will write deadlock information to the error log. However, the error log is textual, so you won't get nice deadlock graph pictures - you'll have to read the text of the deadlocks to figure it out.
I would set this as a startup trace flag (in which case you'll need to restart the service). However, you can run it only for the current running instance of the service (which won't require a restart, but which won't resume upon the next restart) using the following global trace flag command:
DBCC TRACEON(1222, -1);
A quick search yielded this tutorial:
http://www.mssqltips.com/sqlservertip/2130/finding-sql-server-deadlocks-using-trace-flag-1222/
Also note that if your system experiences a lot of deadlocks, this can really hammer your error log, and can become quite a lot of noise, drowning out other, important errors.
Have you considered third party monitoring tools? SQL Sentry Performance Advisor, for example, has a much nicer deadlock graph, showing you object / index names as well as the order in which the locks were taken. As a bonus, these are captured for you automatically on monitored servers without having to configure trace flags, run your own traces, etc.:
Disclaimer: I work for SQL Sentry.
The var
keyword is used to declare variables in a class in PHP 4:
class Foo {
var $bar;
}
With PHP 5 property and method visibility (public
, protected
and private
) was introduced and thus var
is deprecated.
This is a solution where you have many fields in your table and don't want to get a finger cramp from typing all the fields, just type the ones needed :)
How to copy some rows into the same table, with some fields having different values:
Your code:
CREATE table temporary_table AS SELECT * FROM original_table WHERE Event_ID="155";
UPDATE temporary_table SET Event_ID="120";
UPDATE temporary_table SET ID=NULL
INSERT INTO original_table SELECT * FROM temporary_table;
DROP TABLE temporary_table
General scenario code:
CREATE table temporary_table AS SELECT * FROM original_table WHERE <conditions>;
UPDATE temporary_table SET <fieldx>=<valuex>, <fieldy>=<valuey>, ...;
UPDATE temporary_table SET <auto_inc_field>=NULL;
INSERT INTO original_table SELECT * FROM temporary_table;
DROP TABLE temporary_table
Simplified/condensed code:
CREATE TEMPORARY TABLE temporary_table AS SELECT * FROM original_table WHERE <conditions>;
UPDATE temporary_table SET <auto_inc_field>=NULL, <fieldx>=<valuex>, <fieldy>=<valuey>, ...;
INSERT INTO original_table SELECT * FROM temporary_table;
As creation of the temporary table uses the TEMPORARY
keyword it will be dropped automatically when the session finishes (as @ar34z suggested).
SELECT TO_DATE(TO_CHAR(date_column,'MM/DD/YYYY'), 'YYYY-MM-DD')
FROM table;
It is about "seed". Same seeds give the same result.
Here is the class you asked for:
namespace AI.Collections {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
/// <summary>
/// Just a simple thread safe collection.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <value>Version 1.5</value>
/// <remarks>TODO replace locks with AsyncLocks</remarks>
[DataContract( IsReference = true )]
public class ThreadSafeList<T> : IList<T> {
/// <summary>
/// TODO replace the locks with a ReaderWriterLockSlim
/// </summary>
[DataMember]
private readonly List<T> _items = new List<T>();
public ThreadSafeList( IEnumerable<T> items = null ) { this.Add( items ); }
public long LongCount {
get {
lock ( this._items ) {
return this._items.LongCount();
}
}
}
public IEnumerator<T> GetEnumerator() { return this.Clone().GetEnumerator(); }
IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); }
public void Add( T item ) {
if ( Equals( default( T ), item ) ) {
return;
}
lock ( this._items ) {
this._items.Add( item );
}
}
public Boolean TryAdd( T item ) {
try {
if ( Equals( default( T ), item ) ) {
return false;
}
lock ( this._items ) {
this._items.Add( item );
return true;
}
}
catch ( NullReferenceException ) { }
catch ( ObjectDisposedException ) { }
catch ( ArgumentNullException ) { }
catch ( ArgumentOutOfRangeException ) { }
catch ( ArgumentException ) { }
return false;
}
public void Clear() {
lock ( this._items ) {
this._items.Clear();
}
}
public bool Contains( T item ) {
lock ( this._items ) {
return this._items.Contains( item );
}
}
public void CopyTo( T[] array, int arrayIndex ) {
lock ( this._items ) {
this._items.CopyTo( array, arrayIndex );
}
}
public bool Remove( T item ) {
lock ( this._items ) {
return this._items.Remove( item );
}
}
public int Count {
get {
lock ( this._items ) {
return this._items.Count;
}
}
}
public bool IsReadOnly { get { return false; } }
public int IndexOf( T item ) {
lock ( this._items ) {
return this._items.IndexOf( item );
}
}
public void Insert( int index, T item ) {
lock ( this._items ) {
this._items.Insert( index, item );
}
}
public void RemoveAt( int index ) {
lock ( this._items ) {
this._items.RemoveAt( index );
}
}
public T this[ int index ] {
get {
lock ( this._items ) {
return this._items[ index ];
}
}
set {
lock ( this._items ) {
this._items[ index ] = value;
}
}
}
/// <summary>
/// Add in an enumerable of items.
/// </summary>
/// <param name="collection"></param>
/// <param name="asParallel"></param>
public void Add( IEnumerable<T> collection, Boolean asParallel = true ) {
if ( collection == null ) {
return;
}
lock ( this._items ) {
this._items.AddRange( asParallel
? collection.AsParallel().Where( arg => !Equals( default( T ), arg ) )
: collection.Where( arg => !Equals( default( T ), arg ) ) );
}
}
public Task AddAsync( T item ) {
return Task.Factory.StartNew( () => { this.TryAdd( item ); } );
}
/// <summary>
/// Add in an enumerable of items.
/// </summary>
/// <param name="collection"></param>
public Task AddAsync( IEnumerable<T> collection ) {
if ( collection == null ) {
throw new ArgumentNullException( "collection" );
}
var produce = new TransformBlock<T, T>( item => item, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount } );
var consume = new ActionBlock<T>( action: async obj => await this.AddAsync( obj ), dataflowBlockOptions: new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount } );
produce.LinkTo( consume );
return Task.Factory.StartNew( async () => {
collection.AsParallel().ForAll( item => produce.SendAsync( item ) );
produce.Complete();
await consume.Completion;
} );
}
/// <summary>
/// Returns a new copy of all items in the <see cref="List{T}" />.
/// </summary>
/// <returns></returns>
public List<T> Clone( Boolean asParallel = true ) {
lock ( this._items ) {
return asParallel
? new List<T>( this._items.AsParallel() )
: new List<T>( this._items );
}
}
/// <summary>
/// Perform the <paramref name="action" /> on each item in the list.
/// </summary>
/// <param name="action">
/// <paramref name="action" /> to perform on each item.
/// </param>
/// <param name="performActionOnClones">
/// If true, the <paramref name="action" /> will be performed on a <see cref="Clone" /> of the items.
/// </param>
/// <param name="asParallel">
/// Use the <see cref="ParallelQuery{TSource}" /> method.
/// </param>
/// <param name="inParallel">
/// Use the
/// <see
/// cref="Parallel.ForEach{TSource}(System.Collections.Generic.IEnumerable{TSource},System.Action{TSource})" />
/// method.
/// </param>
public void ForEach( Action<T> action, Boolean performActionOnClones = true, Boolean asParallel = true, Boolean inParallel = false ) {
if ( action == null ) {
throw new ArgumentNullException( "action" );
}
var wrapper = new Action<T>( obj => {
try {
action( obj );
}
catch ( ArgumentNullException ) {
//if a null gets into the list then swallow an ArgumentNullException so we can continue adding
}
} );
if ( performActionOnClones ) {
var clones = this.Clone( asParallel: asParallel );
if ( asParallel ) {
clones.AsParallel().ForAll( wrapper );
}
else if ( inParallel ) {
Parallel.ForEach( clones, wrapper );
}
else {
clones.ForEach( wrapper );
}
}
else {
lock ( this._items ) {
if ( asParallel ) {
this._items.AsParallel().ForAll( wrapper );
}
else if ( inParallel ) {
Parallel.ForEach( this._items, wrapper );
}
else {
this._items.ForEach( wrapper );
}
}
}
}
/// <summary>
/// Perform the <paramref name="action" /> on each item in the list.
/// </summary>
/// <param name="action">
/// <paramref name="action" /> to perform on each item.
/// </param>
/// <param name="performActionOnClones">
/// If true, the <paramref name="action" /> will be performed on a <see cref="Clone" /> of the items.
/// </param>
/// <param name="asParallel">
/// Use the <see cref="ParallelQuery{TSource}" /> method.
/// </param>
/// <param name="inParallel">
/// Use the
/// <see
/// cref="Parallel.ForEach{TSource}(System.Collections.Generic.IEnumerable{TSource},System.Action{TSource})" />
/// method.
/// </param>
public void ForAll( Action<T> action, Boolean performActionOnClones = true, Boolean asParallel = true, Boolean inParallel = false ) {
if ( action == null ) {
throw new ArgumentNullException( "action" );
}
var wrapper = new Action<T>( obj => {
try {
action( obj );
}
catch ( ArgumentNullException ) {
//if a null gets into the list then swallow an ArgumentNullException so we can continue adding
}
} );
if ( performActionOnClones ) {
var clones = this.Clone( asParallel: asParallel );
if ( asParallel ) {
clones.AsParallel().ForAll( wrapper );
}
else if ( inParallel ) {
Parallel.ForEach( clones, wrapper );
}
else {
clones.ForEach( wrapper );
}
}
else {
lock ( this._items ) {
if ( asParallel ) {
this._items.AsParallel().ForAll( wrapper );
}
else if ( inParallel ) {
Parallel.ForEach( this._items, wrapper );
}
else {
this._items.ForEach( wrapper );
}
}
}
}
}
}
If I wish to submit a http get request using System.Net.HttpClient there seems to be no api to add parameters, is this correct?
Yes.
Is there any simple api available to build the query string that doesn't involve building a name value collection and url encoding those and then finally concatenating them?
Sure:
var query = HttpUtility.ParseQueryString(string.Empty);
query["foo"] = "bar<>&-baz";
query["bar"] = "bazinga";
string queryString = query.ToString();
will give you the expected result:
foo=bar%3c%3e%26-baz&bar=bazinga
You might also find the UriBuilder
class useful:
var builder = new UriBuilder("http://example.com");
builder.Port = -1;
var query = HttpUtility.ParseQueryString(builder.Query);
query["foo"] = "bar<>&-baz";
query["bar"] = "bazinga";
builder.Query = query.ToString();
string url = builder.ToString();
will give you the expected result:
http://example.com/?foo=bar%3c%3e%26-baz&bar=bazinga
that you could more than safely feed to your HttpClient.GetAsync
method.
This is caused by:
So in both cases you have a poorly defined or implemented application protocol.
There is a third reason which I will not document here but which involves the peer taking deliberate action to reset rather than properly close the connection.
Google just released the NDK which allows exactly that.
It can be found here: http://developer.android.com/sdk/ndk/1.5_r1/index.html
Use the config
method to change the value of the label:
top = Tk()
l = Label(top)
l.pack()
l.config(text = "Hello World", width = "50")
A general answer for a general question... Transitions can't animate properties that are auto. If you have a transition not working, check that the starting value of the property is explicitly set. (For example, to make a node collapse, when it's height is auto and must stay that way, put the transition on max-height instead. Give max-height a sensible initial value, then transition it to 0)
$(function() {_x000D_
_x000D_
$("input:disabled").closest("div").click(function() {_x000D_
$(this).find("input:disabled").attr("disabled", false).focus();_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
<input type="text" disabled />_x000D_
</div>
_x000D_
besides str.join
which is the most natural way, a possibility is to use io.StringIO
and abusing writelines
to write all elements in one go:
import io
a = ['a','b','c','d']
out = io.StringIO()
out.writelines(a)
print(out.getvalue())
prints:
abcd
When using this approach with a generator function or an iterable which isn't a tuple
or a list
, it saves the temporary list creation that join
does to allocate the right size in one go (and a list of 1-character strings is very expensive memory-wise).
If you're low in memory and you have a lazily-evaluated object as input, this approach is the best solution.
The conventional way of handling this doesn't play well with ES6. You can do this instead:
$('.delete').on('click', event => {
const clickedElement = $(event.target);
this.delete(clickedElement.data('id'));
});
Note that the event target will be the clicked element, which may not be the element you want (it could be a child that received the event). To get the actual element:
$('.delete').on('click', event => {
const clickedElement = $(event.target);
const targetElement = clickedElement.closest('.delete');
this.delete(targetElement.data('id'));
});
Are you trying to get visitors to old.com/about.htm to go to new.com/about.htm? If so, you can do this with a mod_rewrite rule in .htaccess:
RewriteEngine on
RewriteRule ^(.*)$ http://www.thenewdomain.com/$1 [R=permanent,L]
For Windows
Goto --> C:/Users/user_name/gitconfig
Update gitconfig file with below details
[http]
[https]
proxy = https://your_proxy:your_port
[http]
proxy = http://your_proxy:your_port
How to check your proxy and port number?
Internet Explorer -> Settings -> Internet Options -> Connections -> LAN Settings
-- [why did we write this?]
-- [auto-generated change control info]
A complete example using schedule and multiprocessing, with on and off control and parameter to run_job()
the return codes are simplified and interval is set to 10sec, change to every(2).hour.do()
for 2hours. Schedule is quite impressive it does not drift and I've never seen it more than 100ms off when scheduling. Using multiprocessing instead of threading because it has a termination method.
#!/usr/bin/env python3
import schedule
import time
import datetime
import uuid
from flask import Flask, request
from multiprocessing import Process
app = Flask(__name__)
t = None
job_timer = None
def run_job(id):
""" sample job with parameter """
global job_timer
print("timer job id={}".format(id))
print("timer: {:.4f}sec".format(time.time() - job_timer))
job_timer = time.time()
def run_schedule():
""" infinite loop for schedule """
global job_timer
job_timer = time.time()
while 1:
schedule.run_pending()
time.sleep(1)
@app.route('/timer/<string:status>')
def mytimer(status, nsec=10):
global t, job_timer
if status=='on' and not t:
schedule.every(nsec).seconds.do(run_job, str(uuid.uuid4()))
t = Process(target=run_schedule)
t.start()
return "timer on with interval:{}sec\n".format(nsec)
elif status=='off' and t:
if t:
t.terminate()
t = None
schedule.clear()
return "timer off\n"
return "timer status not changed\n"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
You test this by just issuing:
$ curl http://127.0.0.1:5000/timer/on
timer on with interval:10sec
$ curl http://127.0.0.1:5000/timer/on
timer status not changed
$ curl http://127.0.0.1:5000/timer/off
timer off
$ curl http://127.0.0.1:5000/timer/off
timer status not changed
Every 10sec the timer is on it will issue a timer message to console:
127.0.0.1 - - [18/Sep/2018 21:20:14] "GET /timer/on HTTP/1.1" 200 -
timer job id=b64ed165-911f-4b47-beed-0d023ead0a33
timer: 10.0117sec
timer job id=b64ed165-911f-4b47-beed-0d023ead0a33
timer: 10.0102sec
Here is a great way to build dynamic fields for a pivot query:
--summarize values to a tmp table
declare @STR varchar(1000)
SELECT @STr = COALESCE(@STr +', ', '')
+ QUOTENAME(DateRange)
from (select distinct DateRange, ID from ##pivot)d order by ID
---see the fields generated
print @STr
exec(' .... pivot code ...
pivot (avg(SalesAmt) for DateRange IN (' + @Str +')) AS P
order by Decile')
I was facing the same issue and found here useful steps which saved my time a lot. Hope so below attached image will help you a lot-
Window-> Preferences-> General-> Network Connection
Change Active Provider Native to Manual if problem is not resolved by using the steps mentioned in snapshot. Make sure HTTP/HTTPS should be checked and if any IP is required for your proxy settings then you should provide proxy IP in host and port number as well.
If the values are not unique, the safe way to inverse the map is by using java 8's groupingBy function
Map<String, Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);
Map<Integer, List<String>> mapInversed =
map.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())))
The first 10 directories with the highest number of files.
dir=/ ; for i in $(ls -1 ${dir} | sort -n) ; { echo "$(find ${dir}${i} \
-type f | wc -l) => $i,"; } | sort -nr | head -10
.processList
text-align: center
li
.leftProcess
float: left
.centerProcess
float: none
display: inline-block
.rightProcess
float: right
html
ul.processList.clearfix
li.leftProcess
li.centerProcess
li.rightProcess
Whether encrypted be the same when plain text is encrypted with the same key depends of algorithm and protocol. In cryptography there is initialization vector IV: http://en.wikipedia.org/wiki/Initialization_vector that used with various ciphers makes that the same plain text encrypted with the same key gives various cipher texts.
I advice you to read more about cryptography on Wikipedia, Bruce Schneier http://www.schneier.com/books.html and "Beginning Cryptography with Java" by David Hook. The last book is full of examples of usage of http://www.bouncycastle.org library.
If you are interested in cryptography the there is CrypTool: http://www.cryptool.org/ CrypTool is a free, open-source e-learning application, used worldwide in the implementation and analysis of cryptographic algorithms.
Grave digging... I like a different approach:
elem = $('form')
elem.on('keyup','input', checkStatus)
elem.on('change', 'select', checkStatus)
checkStatus = (e) =>
elems = $('form').find('input:enabled').not('input[type=hidden]').map(-> $(this).val())
filled = $.grep(elems, (n) -> n)
bool = elems.size() != $(filled).size()
$('input:submit').attr('disabled', bool)
At least in case of EclipseLink 10g and 11g differ. Since 11g it is not recommended to use first_rows hint for pagination queries.
See "Is it possible to disable jpa hints per particular query". Such a query should not be used in 11g.
SELECT * FROM (
SELECT /*+ FIRST_ROWS */ a.*, ROWNUM rnum FROM (
SELECT * FROM TABLES INCLUDING JOINS, ORDERING, etc.) a
WHERE ROWNUM <= 10 )
WHERE rnum > 0;
But there can be other nuances.
Yep it is here, using _.reduce
var params = [
{ name: 'foo', input: 'bar' },
{ name: 'baz', input: 'zle' }
];
_.reduce(params , function(obj,param) {
obj[param.name] = param.input
return obj;
}, {});
I'm one of the developers for Twitterrific and to be honest, I can't tell you how many hours have gone into the product. I can tell you everyone who upvoted the estimate of 160 hours for development and 40 hours for design is fricken' high. (I'd use another phrase, but this is my first post on Stack Overflow, so I'm being good.)
Twitterrific has had 4 major releases beginning with the iOS 1.0 (Jailbreak.) That's a lot of code, much of which is in the bit bucket (we refactor a lot with each major release.)
One thing that would be interesting to look at is the amount of time that we had to work on the iPad version. Apple set a product release date that gave us 60 days to do the development. (That was later extended by a week.)
We started the iPad development from scratch, but a lot of our underlying code (mostly models) was re-used. The development was done by two experienced iOS developers. One of them has even written a book: http://appdevmanual.com :-)
With such a short schedule, we worked some pretty long hours. Let's be conservative and say it's 10 hours per day for 6 days a week. That 60 hours for 9 weeks gives us 540 hours. With two developers, that's pretty close to 1,100 hours. Our rate for clients is $150 per hour giving $165,000 just for new code. Remember also that we were reusing a bunch existing code: I'm going to lowball the value of that code at $35,000 giving a total development cost of $200,000.
Anyone who's done serious iPhone development can tell you there's a lot of design work involved with any project. We had two designers working on that aspect of the product. They worked their asses off dealing with completely new interaction mechanics. Don't forget they didn't have any hardware to touch, either (LOTS of printouts!) Combined they spent at least 25 hours per week on the project. So 225 hours at $150/hr is about $34,000.
There are also other costs that many developer neglect to take into account: project management, testing, equipment. Again, if we lowball that figure at $16,000 we're at $250,000. This number falls in line with Jonathan Wight's (@schwa) $50-150K estimate with the 22 day Obama app.
Take another hit, dude.
Now if you want to build backend services for your app, that number's going to go up even more. Everyone seems surprised that Instagram chewed through $500K in venture funding to build a new frontend and backend. I'm not.
First reset
locally:
git reset 23b6772
To see if you're on the right position, verify with:
git status
You will see something like:
On branch master Your branch is behind 'origin/master' by 17 commits, and can be fast-forwarded.
Then rewrite history on your remote tracking branch to reflect the change:
git push --force-with-lease // a useful command @oktober mentions in comments
Using --force-with-lease
instead of --force
will raise an error if others have meanwhile committed to the remote branch, in which case you should fetch first. More info in this article.
Try this one, it will broadcast about a new image created, so your image visible. inside a gallery. photoFile replace with actual file path of the newly created image
private void galleryAddPicBroadCast() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(photoFile);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
To catch the names array, i use that:
$("input[name*='task']")
Here is a tidyverse
option that might work depending on the data, and some caveats on its usage:
library(tidyverse)
starting_df %>%
rownames_to_column() %>%
gather(variable, value, -rowname) %>%
spread(rowname, value)
rownames_to_column()
is necessary if the original dataframe has meaningful row names, otherwise the new column names in the new transposed dataframe will be integers corresponding to the orignal row number. If there are no meaningful row names you can skip rownames_to_column()
and replace rowname
with the name of the first column in the dataframe, assuming those values are unique and meaningful. Using the tidyr::smiths
sample data would be:
smiths %>%
gather(variable, value, -subject) %>%
spread(subject, value)
Using the example starting_df
with the tidyverse
approach will throw a warning message about dropping attributes. This is related to converting columns with different attribute types into a single character column. The smiths
data will not give that warning because all columns except for subject
are doubles.
The earlier answer using as.data.frame(t())
will convert everything to a factor
if there are mixed column types unless stringsAsFactors = FALSE
is added,
whereas the tidyverse
option converts everything to a character by default if
there are mixed column types.
long hours = TimeUnit.MILLISECONDS.toHours(timeInMilliseconds);
long minutes = TimeUnit.MILLISECONDS.toMinutes(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours));
long seconds = TimeUnit.MILLISECONDS
.toSeconds(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours) - TimeUnit.MINUTES.toMillis(minutes));
long milliseconds = timeInMilliseconds - TimeUnit.HOURS.toMillis(hours)
- TimeUnit.MINUTES.toMillis(minutes) - TimeUnit.SECONDS.toMillis(seconds);
return String.format("%02d:%02d:%02d:%d", hours, minutes, seconds, milliseconds);
Create an Android app using Eclipse.
Create a layout that has a <WebView>
control.
Move your HTML code to /assets
folder.
Load webview with your file:///android_asset/ file.
And you have an android app!
If you are using Bootstrap is as simple as this:
<div [class.hidden]="myBooleanValue"></div>
In case you have only one controller and you want to access every action on root you can skip controller name like this
routes.MapRoute(
"Default",
"{action}/{id}",
new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
In the case where the process was spawned by another node process, like:
var child = spawn('gulp', ['watch'], {
stdio: 'inherit',
});
And you try to kill it later, via:
child.kill();
This is how you handle the event [on the child]:
process.on('SIGTERM', function() {
console.log('Goodbye!');
});
Pros:
Cons:
Pros:
Cons:
The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.
Typically, the following are allowed:
Pros:
localStorage
.Cons:
localStorage
, it works on same-origin policy. So, data stored will only be available on the same origin.Checkout across-tabs - how to facilitate easy communication between cross-origin browser tabs.
A class method typically either creates a new instance of the class or retrieves some global properties of the class. Class methods do not operate on an instance or have any access to instance variable.
An instance method operates on a particular instance of the class. For example, the accessors method that you implemented are all instance methods. You use them to set or get the instance variables of a particular object.
To invoke an instance method, you send the message to an instance of the class.
To invoke a class method, you send the message to the class directly.
Source: IOS - Objective-C - Class Methods And Instance Methods
It's not fully cross-browsers solution, but must work well in most modern browser.
<img src="image.jpg" />
<style>
img:hover {
/* Ch 23+, Saf 6.0+, BB 10.0+ */
-webkit-filter: hue-rotate(240deg) saturate(3.3) grayscale(50%);
/* FF 35+ */
filter: hue-rotate(240deg) saturate(3.3) grayscale(50%);
}
</style>
EXTERNAL DEMO PLAYGROUND
IN-HOUSE DEMO SNIPPET (source:simpl.info)
#container {_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.blur {_x000D_
filter: blur(5px)_x000D_
}_x000D_
_x000D_
.grayscale {_x000D_
filter: grayscale(1)_x000D_
}_x000D_
_x000D_
.saturate {_x000D_
filter: saturate(5)_x000D_
}_x000D_
_x000D_
.sepia {_x000D_
filter: sepia(1)_x000D_
}_x000D_
_x000D_
.multi {_x000D_
filter: blur(4px) invert(1) opacity(0.5)_x000D_
}
_x000D_
<div id="container">_x000D_
_x000D_
<h1><a href="https://simpl.info/cssfilters/" title="simpl.info home page">simpl.info</a> CSS filters</h1>_x000D_
_x000D_
<img src="https://simpl.info/cssfilters/balham.jpg" alt="No filter: Balham High Road and a rainbow" />_x000D_
<img class="blur" src="https://simpl.info/cssfilters/balham.jpg" alt="Blur filter: Balham High Road and a rainbow" />_x000D_
<img class="grayscale" src="https://simpl.info/cssfilters/balham.jpg" alt="Grayscale filter: Balham High Road and a rainbow" />_x000D_
<img class="saturate" src="https://simpl.info/cssfilters/balham.jpg" alt="Saturate filter: Balham High Road and a rainbow" />_x000D_
<img class="sepia" src="https://simpl.info/cssfilters/balham.jpg" alt="Sepia filter: Balham High Road and a rainbow" />_x000D_
<img class="multi" src="https://simpl.info/cssfilters/balham.jpg" alt="Blur, invert and opacity filters: Balham High Road and a rainbow" />_x000D_
_x000D_
<p><a href="https://github.com/samdutton/simpl/blob/gh-pages/cssfilters" title="View source for this page on GitHub" id="viewSource">View source on GitHub</a></p>_x000D_
_x000D_
</div>
_x000D_
NOTES
RESOURCES:
select method > right click > References > Workspace/Project (your preferred context )
or
(Ctrl+Shift+G)
This will show you a Search view containing the hierarchy of class and method which using this method.
If you use the vim plugin https://github.com/tpope/vim-surround (or use VSCode Vim plugin, which comes with vim-surround pre-installed), its pretty convinient!
add
ysiw' // surround in word `'`
drop
ds' // drop surround `'`
change
cs'" // change surround from `'` to `"`
It even works for html tags!
cst<em> // change surround from current tag to `<em>`
check out the readme on github for better examples
You can solve this fully in the html:
<div>
<input ng-model=collapse type=checkbox>Title
<div ng-show=collapse>
Only shown when checkbox is clicked
</div>
</div>
This also works well with ng-repeat since it will create a local scope for each member.
<table>
<tbody ng-repeat='m in members'>
<tr>
<td><input type=checkbox ng-model=collapse></td>
<td>{{m.title}}</td>
</tr>
<tr ng-show=collapse>
<td> </td>
<td>{{ m.content }}</td>
</tr>
</tbody>
</table>
Be aware that even though a repeat has its own scope, initially it will inherit the value from collapse from super scopes. This allows you to set the initial value in one place but it can be surprising.
You can of course restyle the checkbox. See http://jsfiddle.net/azD5m/5/
Updated fiddle: http://jsfiddle.net/azD5m/374/ Original fiddle used closing </input>
tags to add the HTML text label instead of using <label>
tags.
You can modify with the following
<li><a href="./Index" class="elements"><span>Clients</span></a></li>
The extra dot means you are in the same controller. If you want change the controller to a different controller then you can write this
<li><a href="../newController/Index" class="elements"><span>Clients</span></a></li>
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
Hashing A Password Using Bcrypt in Laravel
:
$password = Hash::make('yourpassword');
This will create a hashed password. You may use it in your controller or even in a model, for example, if a user submits a password using a form to your controller using POST
method then you may hash it using something like this:
$password = Input::get('passwordformfield'); // password is form field
$hashed = Hash::make($password);
Here, $hashed
will contain the hashed password. Basically, you'll do it when creating/registering a new user, so, for example, if a user submits details such as, name
, email
, username
and password
etc using a form, then before you insert the data into database, you'll hash the password after validating the data. For more information, read the documentation.
Update:
$password = 'JohnDoe';
$hashedPassword = Hash::make($password);
echo $hashedPassword; // $2y$10$jSAr/RwmjhwioDlJErOk9OQEO7huLz9O6Iuf/udyGbHPiTNuB3Iuy
So, you'll insert the $hashedPassword
into database. Hope, it's clear now and if still you are confused then i suggest you to read some tutorials, watch some screen casts on laracasts.com and tutsplus.com and also read a book on Laravel
, this is a free ebook, you may download it.
Update: Since OP
wants to manually encrypt password using Laravel Hash
without any class or form so this is an alternative way using artisan tinker
from command prompt:
Laravel
installation (your project's root directory)cd <directory name>
and press enter from command prompt/terminalphp artisan tinker
and press enterecho Hash::make('somestring');
// Also one can use bcrypt
$password = bcrypt('JohnDoe');
The old versions of JavaScript had no import, include, or require, so many different approaches to this problem have been developed.
But since 2015 (ES6), JavaScript has had the ES6 modules standard to import modules in Node.js, which is also supported by most modern browsers.
For compatibility with older browsers, build tools like Webpack and Rollup and/or transpilation tools like Babel can be used.
ECMAScript (ES6) modules have been supported in Node.js since v8.5, with the --experimental-modules
flag, and since at least Node.js v13.8.0 without the flag. To enable "ESM" (vs. Node.js's previous CommonJS-style module system ["CJS"]) you either use "type": "module"
in package.json
or give the files the extension .mjs
. (Similarly, modules written with Node.js's previous CJS module can be named .cjs
if your default is ESM.)
Using package.json
:
{
"type": "module"
}
Then module.js
:
export function hello() {
return "Hello";
}
Then main.js
:
import { hello } from './module.js';
let val = hello(); // val is "Hello";
Using .mjs
, you'd have module.mjs
:
export function hello() {
return "Hello";
}
Then main.mjs
:
import { hello } from './module.mjs';
let val = hello(); // val is "Hello";
Browsers have had support for loading ECMAScript modules directly (no tools like Webpack required) since Safari 10.1, Chrome 61, Firefox 60, and Edge 16. Check the current support at caniuse. There is no need to use Node.js' .mjs
extension; browsers completely ignore file extensions on modules/scripts.
<script type="module">
import { hello } from './hello.mjs'; // Or it could be simply `hello.js`
hello('world');
</script>
// hello.mjs -- or it could be simply `hello.js`
export function hello(text) {
const div = document.createElement('div');
div.textContent = `Hello ${text}`;
document.body.appendChild(div);
}
Read more at https://jakearchibald.com/2017/es-modules-in-browsers/
Dynamic imports let the script load other scripts as needed:
<script type="module">
import('hello.mjs').then(module => {
module.hello('world');
});
</script>
Read more at https://developers.google.com/web/updates/2017/11/dynamic-import
The older CJS module style, still widely used in Node.js, is the module.exports
/require
system.
// mymodule.js
module.exports = {
hello: function() {
return "Hello";
}
}
// server.js
const myModule = require('./mymodule');
let val = myModule.hello(); // val is "Hello"
There are other ways for JavaScript to include external JavaScript contents in browsers that do not require preprocessing.
You could load an additional script with an AJAX call and then use eval
to run it. This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model. Using eval
also opens the door to bugs, hacks and security issues.
Like Dynamic Imports you can load one or many scripts with a fetch
call using promises to control order of execution for script dependencies using the Fetch Inject library:
fetchInject([
'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js'
]).then(() => {
console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)
})
The jQuery library provides loading functionality in one line:
$.getScript("my_lovely_script.js", function() {
alert("Script loaded but not necessarily executed.");
});
You could add a script tag with the script URL into the HTML. To avoid the overhead of jQuery, this is an ideal solution.
The script can even reside on a different server. Furthermore, the browser evaluates the code. The <script>
tag can be injected into either the web page <head>
, or inserted just before the closing </body>
tag.
Here is an example of how this could work:
function dynamicallyLoadScript(url) {
var script = document.createElement("script"); // create a script DOM node
script.src = url; // set its src to the provided URL
document.head.appendChild(script); // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead)
}
This function will add a new <script>
tag to the end of the head section of the page, where the src
attribute is set to the URL which is given to the function as the first parameter.
Both of these solutions are discussed and illustrated in JavaScript Madness: Dynamic Script Loading.
Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performance. (This applies to both the jQuery method and the manual dynamic script loading method.)
It means that if you use these tricks directly, you won't be able to use your newly loaded code the next line after you asked it to be loaded, because it will be still loading.
For example: my_lovely_script.js
contains MySuperObject
:
var js = document.createElement("script");
js.type = "text/javascript";
js.src = jsFilePath;
document.body.appendChild(js);
var s = new MySuperObject();
Error : MySuperObject is undefined
Then you reload the page hitting F5. And it works! Confusing...
So what to do about it ?
Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses an event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. For example:
function loadScript(url, callback)
{
// Adding the script tag to the head as suggested before
var head = document.head;
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
}
Then you write the code you want to use AFTER the script is loaded in a lambda function:
var myPrettyCode = function() {
// Here, do whatever you want
};
Then you run all that:
loadScript("my_lovely_script.js", myPrettyCode);
Note that the script may execute after the DOM has loaded, or before, depending on the browser and whether you included the line script.async = false;
. There's a great article on Javascript loading in general which discusses this.
As mentioned at the top of this answer, many developers use build/transpilation tool(s) like Parcel, Webpack, or Babel in their projects, allowing them to use upcoming JavaScript syntax, provide backward compatibility for older browsers, combine files, minify, perform code splitting etc.
Actually there is no any cancel()
or dismiss()
method from AlertDialog.Builder Class.
So Instead of AlertDialog.Builder optionDialog
use AlertDialog
instance.
Like,
AlertDialog optionDialog = new AlertDialog.Builder(this).create();
Now, Just call optionDialog.dismiss();
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
// here I want to dismiss it after SetBackground() method
optionDialog.dismiss();
}
});
You may try using ellipsis by adding the following in CSS:
.truncate {
width: 250px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
But it seems like this code just applies to one-line trim. More ways to trim text and show ellipsis can be found in this website: http://blog.sanuker.com/?p=631
Just call array.ToObject<List<SelectableEnumItem>>()
method. It will return what you need.
Documentation: Convert JSON to a Type
@@IDENTITY
Is a system function that returns the last-inserted identity value.
I'm using the /Console
parameter in the Visual Studio project Debug ? Start Options ? Command line arguments:
public static class Program
{
[STAThread]
public static void Main(string[] args)
{
var runMode = args.Contains(@"/Console")
? WindowsService.RunMode.Console
: WindowsService.RunMode.WindowsService;
new WinodwsService().Run(runMode);
}
}
public class WindowsService : ServiceBase
{
public enum RunMode
{
Console,
WindowsService
}
public void Run(RunMode runMode)
{
if (runMode.Equals(RunMode.Console))
{
this.StartService();
Console.WriteLine("Press <ENTER> to stop service...");
Console.ReadLine();
this.StopService();
Console.WriteLine("Press <ENTER> to exit.");
Console.ReadLine();
}
else if (runMode.Equals(RunMode.WindowsService))
{
ServiceBase.Run(new[] { this });
}
}
protected override void OnStart(string[] args)
{
StartService(args);
}
protected override void OnStop()
{
StopService();
}
/// <summary>
/// Logic to Start Service
/// Public accessibility for running as a console application in Visual Studio debugging experience
/// </summary>
public virtual void StartService(params string[] args){ ... }
/// <summary>
/// Logic to Stop Service
/// Public accessibility for running as a console application in Visual Studio debugging experience
/// </summary>
public virtual void StopService() {....}
}
in linux , Just go to "/var/lib/mysql" right click and (open as adminstrator), find the folder corresponding to your database name inside mysql folder and delete it. that's it. Database is dropped.
I found out that it also happens if you uninstalled some packages from your react-native project and there is still packages in your build gradle dependencies in the bottom of page like:
{
project(':react-native-sound-player')
}
First of all, that's a forward slash. And no, you can't have any in regexes unless you escape them. To escape them, put a backslash (\
) in front of it.
someString.replace(/\//g, "-");
This solution is in c# but complete the test with 100% score
public int solution(int[] A) {
// write your code in C# 6.0 with .NET 4.5 (Mono)
var positives = A.Where(x => x > 0).Distinct().OrderBy(x => x).ToArray();
if(positives.Count() == 0) return 1;
int prev = 0;
for(int i =0; i < positives.Count(); i++){
if(positives[i] != prev + 1){
return prev + 1;
}
prev = positives[i];
}
return positives.Last() + 1;
}
The problem for me is that the repo's previous developer had committed the submodules/thing
folder as just a regular folder, meaning when I tried to run git submodule add ...
, it would fail with: 'submodules/thing' already exists in the index
, yet trying to update the submodule would also fail because it saw that the path did not contain a submodule.
To fix, I had to delete the submodules/thing
folder, commit the deletion, then run the git submodule add
command to add it back correctly:
git submodule add --force --name thing https://github.com/person/thing.git submodules/thing
Sorry to dig up an old question but in case someone stumbles onto this thread and wants a quicker solution.
Bulk inserting a unknown width file with \n row terminators into a temp table that is created outside of the EXEC statement.
DECLARE @SQL VARCHAR(8000)
IF OBJECT_ID('TempDB..#BulkInsert') IS NOT NULL
BEGIN
DROP TABLE #BulkInsert
END
CREATE TABLE #BulkInsert
(
Line VARCHAR(MAX)
)
SET @SQL = 'BULK INSERT #BulkInser FROM ''##FILEPATH##'' WITH (ROWTERMINATOR = ''\n'')'
EXEC (@SQL)
SELECT * FROM #BulkInsert
Further support that dynamic SQL within an EXEC statement has access to temp tables outside of the EXEC statement. http://sqlfiddle.com/#!3/d41d8/19343
DECLARE @SQL VARCHAR(8000)
IF OBJECT_ID('TempDB..#BulkInsert') IS NOT NULL
BEGIN
DROP TABLE #BulkInsert
END
CREATE TABLE #BulkInsert
(
Line VARCHAR(MAX)
)
INSERT INTO #BulkInsert
(
Line
)
SELECT 1
UNION SELECT 2
UNION SELECT 3
SET @SQL = 'SELECT * FROM #BulkInsert'
EXEC (@SQL)
Further support, written for MSSQL2000 http://technet.microsoft.com/en-us/library/aa175921(v=sql.80).aspx
Example at the bottom of the link
DECLARE @cmd VARCHAR(1000), @ExecError INT
CREATE TABLE #ErrFile (ExecError INT)
SET @cmd = 'EXEC GetTableCount ' +
'''pubs.dbo.authors''' +
'INSERT #ErrFile VALUES(@@ERROR)'
EXEC(@cmd)
SET @ExecError = (SELECT * FROM #ErrFile)
SELECT @ExecError AS '@@ERROR'
I know this is an old post but I got the same error recently so for what it's worth, here's another solution:
This is usually a connection string error, please check the format of your connection string, you can look up 'entity framework connectionstring' or follow the suggestions above.
However, in my case my connection string was fine and the error was caused by something completely different so I hope this helps someone:
First I had an EDMX error: there was a new database table in the EDMX and the table did not exist in my database (funny thing is the error the error was not very obvious because it was not shown in my EDMX or output window, instead it was tucked away in visual studio in the 'Error List' window under the 'Warnings'). I resolved this error by adding the missing table to my database. But, I was actually busy trying to add a stored procedure and still getting the 'datasource' error so see below how i resolved it:
Stored procedure error: I was trying to add a stored procedure and everytime I added it via the EDMX design window I got a 'datasource' error. The solution was to add the stored procedure as blank (I kept the stored proc name and declaration but deleted the contents of the stored proc and replaced it with 'select 1' and retried adding it to the EDMX). It worked! Presumably EF didn't like something inside my stored proc. Once I'd added the proc to EF I was then able to update the contents of the proc on my database to what I wanted it to be and it works, 'datasource' error resolved.
weirdness
This is solved in my case.
JS
$.ajaxPrefilter(function( options, original_Options, jqXHR ) {
options.async = true;
});
This answer was inserted in this link
https://stackoverflow.com/questions/28322636/synchronous-xmlhttprequest-warning-and-script
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
You can use the for command:
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
Type
for /?
at the command prompt. Also, you can parse ini files!