The Java for-each idiom can only be applied to arrays or objects of type *Iterable. This idiom is implicit as it truly backed by an Iterator. The Iterator is programmed by the programmer and often uses an integer index or a node (depending on the data structure) to keep track of its position. On paper it is slower than a regular for-loop, a least for "linear" structures like arrays and Lists but it provides greater abstraction.
try the following snippet
const renObjData = this.props.data.map(function(data, idx) {
return <ul key={idx}>{$.map(data,(val,ind) => {
return (<li>{val}</li>);
}
}</ul>;
});
I hacked together another way to do it without having to manipulate list view. Unfortunately, regular Android Animations seem to manipulate the contents of the row, but are ineffectual at actually shrinking the view. So, first consider this handler:
private Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
Bundle bundle = message.getData();
View view = listView.getChildAt(bundle.getInt("viewPosition") -
listView.getFirstVisiblePosition());
int heightToSet;
if(!bundle.containsKey("viewHeight")) {
Rect rect = new Rect();
view.getDrawingRect(rect);
heightToSet = rect.height() - 1;
} else {
heightToSet = bundle.getInt("viewHeight");
}
setViewHeight(view, heightToSet);
if(heightToSet == 1)
return;
Message nextMessage = obtainMessage();
bundle.putInt("viewHeight", (heightToSet - 5 > 0) ? heightToSet - 5 : 1);
nextMessage.setData(bundle);
sendMessage(nextMessage);
}
Add this collection to your List adapter:
private Collection<Integer> disabledViews = new ArrayList<Integer>();
and add
public boolean isEnabled(int position) {
return !disabledViews.contains(position);
}
Next, wherever it is that you want to hide a row, add this:
Message message = handler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putInt("viewPosition", listView.getPositionForView(view));
message.setData(bundle);
handler.sendMessage(message);
disabledViews.add(listView.getPositionForView(view));
That's it! You can change the speed of the animation by altering the number of pixels that it shrinks the height at once. Not real sophisticated, but it works!
You can mix C++ in with Objectiv-C (Objective C++). Write a C++ method in your Objective C++ class that simply calls [context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer*)self.layer];
and call it from your C++.
I haven't tried it before my self, but give it a shot, and share the results with us.
time_point
objects only support arithmetic with other time_point
or duration
objects.
You'll need to convert your long
to a duration
of specified units, then your code should work correctly.
Example URL: /rest/{keyword}
This URL is an example for path parameters. We can get this URL data by using @PathParam
.
Example URL: /rest?keyword=java&limit=10
This URL is an example for query parameters. We can get this URL data by using @Queryparam
.
As you said, you want hash to contain only numbers.
var reg = new RegExp('^[0-9]+$');
or
var reg = new RegExp('^\\d+$');
\d
and [0-9]
both mean the same thing.
The + used means that search for one or more occurring of [0-9].
This can be archived by adding code on the onchange event of the select control.
For Example:
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
<option value="http://gmail.com">Gmail</option>
<option value="http://youtube.com">Youtube</option>
</select>
The problem is in your main.ts
file.
const platform = platformBrowserDynamic();
platform.bootstrapModule(App);
You are trying to bootstrap App
, which is not a real module.
Delete these two lines and replace with the following line:
platformBrowserDynamic().bootstrapModule(AppModule);
and it will fix your error.
If you use Linux, you can try the following approach.
Suppose you have a text file named animal.txt
:
$ cat animal.txt
dog
pig
cat
monkey
elephant
Delete the first line:
>>> import subprocess
>>> subprocess.call(['sed','-i','/.*dog.*/d','animal.txt'])
then
$ cat animal.txt
pig
cat
monkey
elephant
Add w-auto native bootstrap 4 class to the table element and your table will fit its content.
If you want to send your data inside the body, then you have to make a POST
or PUT
instead of GET
.
For me, it looks like you're trying to send the query with uri parameters, which is not related to GET
, you can also put these parameters on POST
, PUT
and so on.
The query is an optional part, separated by a question mark ("?"), that contains additional identification information that is not hierarchical in nature. The query string syntax is not generically defined, but it is commonly organized as a sequence of = pairs, with the pairs separated by a semicolon or an ampersand.
For example:
curl http://server:5050/a/c/getName?param0=foo¶m1=bar
You need to uninstall IIS (Internet Information Services) but the key thing here is to make sure you uninstall the Windows Process Activation Service or otherwise your ApplicationHost.config will be still around. When you uninstall WAS then your configuration will be cleaned up and you will truly start with a fresh new IIS (and all data/configuration will be lost).
Try this:
<html>
<head>
<style>
select {
height: 30px;
color: #0000ff;
}
</style>
</head>
<body>
<table>
<tbody>
<tr>
<td>
<select name="test">
<option value="Basic">Basic : $30.00 USD - yearly</option>
<option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
<option value="Supporting">Supporting : $120.00 USD - yearly</option>
</select>
</td>
</tr>
</tbody>
</table>
</body>
</html>
This example does not swap two int pointers. It swaps the value of the integers that pa
and pb
are pointing to. Here's an example of what's going on when you call this:
void Swap1 (int *pa, int *pb){
int temp = *pa;
*pa = *pb;
*pb = temp;
}
int main()
{
int a = 42;
int b = 17;
int *pa = &a;
int *pb = &b;
printf("--------Swap1---------\n");
printf("a = %d\n b = %d\n", a, b);
swap1(pa, pb);
printf("a = %d\n = %d\n", a, a);
printf("pb address = %p\n", pa);
printf("pa address = %p\n", pb);
}
The output here is:
a = 42
b = 17
pa address = 0x7fffdf933228
pb address = 0x7fffdf93322c
--------Swap---------
pa = 17
pb = 42
a = 17
b = 42
pa address = 0x7fffdf933228
pb address = 0x7fffdf93322c
Note that the values swapped, but the pointer's addresses did not swap!
In order to swap addresses we need to do this:
void swap2 (int **pa, int **pb){
int temp = *pa;
*pa = *pb;
*pb = temp;
}
and in main call the function like swap2(&pa, &pb);
Now the addresses are swapped, as well as the values for the pointers. a
and b
have the same values that the are initialized with The integers a and b did not swap because it swap2
swaps the addresses being being pointed to by the pointers!:
a = 42
b = 17
pa address = 0x7fffddaa9c98
pb address = 0x7fffddaa9c9c
--------Swap---------
pa = 17
pb = 42
a = 42
b = 17
pa address = 0x7fffddaa9c9c
pb address = 0x7fffddaa9c98
Since Strings in C are char pointers, and you want to swap Strings, you are really swapping a char pointer. As in the examples with an int, you need a double pointer to swap addresses.
The values of integers can be swapped even if the address isn't, but Strings are by definition a character pointer. You could swap one char with single pointers as the parameter, but a character pointer needs to be a double pointer in order to swap the strings.
Add @JsonInclude(JsonInclude.Include.NON_NULL)
(forces Jackson to serialize null values) to the class as well as @JsonIgnore
to the password field.
You could of course set @JsonIgnore
on createdBy and updatedBy as well if you always want to ignore then and not just in this specific case.
UPDATE
In the event that you do not want to add the annotation to the POJO itself, a great option is Jackson's Mixin Annotations. Check out the documentation
Smutje is correct and Chad HedgeCock offered a great layman's example. Id like to build on Chad's example by offering a way to find/delete those records. We will use Customer as the Parent and Order as the child. CustomerId is the common field.
select * from Order Child
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null
if you are reading this thread... you will get results. These are orphaned children. select * from Order Child left join Customer Parent on Child.CustomerId = Parent.CustomerId where Parent.CustomerId is null Note the row count in the bottom right.
Go verify w/ whomever you need to that you are going to delete these rows!
begin tran
delete Order
from Order Child
left join Customer Parent on Child.CustomerId = Parent.CustomerId
where Parent.CustomerId is null
Run the first bit. Check that row count = what you expected
commit the tran
commit tran
Be careful. Someone's sloppy programming got you into this mess. Make sure you understand the why before you delete the orphans. Maybe the parent needs to be restored.
So you have committed your local changes to your local repository. Then in order to get remote changes to your local repository without making changes to your local files, you can use git fetch
. Actually git pull
is a two step operation: a non-destructive git fetch
followed by a git merge
. See What is the difference between 'git pull' and 'git fetch'? for more discussion.
Detailed example:
Suppose your repository is like this (you've made changes test2
:
* ed0bcb2 - (HEAD, master) test2
* 4942854 - (origin/master, origin/HEAD) first
And the origin
repository is like this (someone else has committed test1
):
* 5437ca5 - (HEAD, master) test1
* 4942854 - first
At this point of time, git will complain and ask you to pull first if you try to push your test2
to remote repository. If you want to see what test1 is without modifying your local repository, run this:
$ git fetch
Your result local repository would be like this:
* ed0bcb2 - (HEAD, master) test2
| * 5437ca5 - (origin/master, origin/HEAD) test1
|/
* 4942854 - first
Now you have the remote changes in another branch, and you keep your local files intact.
Then what's next? You can do a git merge
, which will be the same effect as git pull
(when combined with the previous git fetch
), or, as I would prefer, do a git rebase origin/master
to apply your change on top of origin/master
, which gives you a cleaner history.
Assuming the underlying data types are date/time/datetime types:
SELECT CONVERT(DATETIME, CONVERT(CHAR(8), CollectionDate, 112)
+ ' ' + CONVERT(CHAR(8), CollectionTime, 108))
FROM dbo.whatever;
This will convert CollectionDate
and CollectionTime
to char sequences, combine them, and then convert them to a datetime
.
The parameters to CONVERT
are data_type
, expression
and the optional style
(see syntax documentation).
The date and time style
value 112
converts to an ISO yyyymmdd
format. The style
value 108
converts to hh:mi:ss
format. Evidently both are 8 characters long which is why the data_type
is CHAR(8)
for both.
The resulting combined char sequence is in format yyyymmdd hh:mi:ss
and then converted to a datetime
.
$data =array();
$data['user_code'] = 'JOY' ;
$data['user_name'] = 'JOY' ;
$data['user_email'] = '[email protected]';
Another alternative:
# Is there anything in this row non-zero?
# df != 0 --> which entries are non-zero? T/F
# (df != 0).any(axis=1) --> are there 'any' entries non-zero row-wise? T/F of rows that return true to this statement.
# df.loc[all_zero_mask,:] --> mask your rows to only show the rows which contained a non-zero entry.
# df.shape to confirm a subset.
all_zero_mask=(df != 0).any(axis=1) # Is there anything in this row non-zero?
df.loc[all_zero_mask,:].shape
In the interpreter its easy to restart it and fix such problems. If you don't want to restart the interpreter, there is another way to fix it:
Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [1,2,3]
>>> sum(l)
6
>>> sum = 0 # oops! shadowed a builtin!
>>> sum(l)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> import sys
>>> sum = sys.modules['__builtin__'].sum # -- fixing sum
>>> sum(l)
6
This also comes in handy if you happened to assign a value to any other builtin, like dict
or list
Since Java 8:
List<String> myList = map.keySet().stream().collect(Collectors.toList());
Full admin rights for the whole server, or a specific database? I think the others answered for a database, but for the server:
USE [master];
GO
CREATE LOGIN MyNewAdminUser
WITH PASSWORD = N'abcd',
CHECK_POLICY = OFF,
CHECK_EXPIRATION = OFF;
GO
EXEC sp_addsrvrolemember
@loginame = N'MyNewAdminUser',
@rolename = N'sysadmin';
You may need to leave off the CHECK_ parameters depending on what version of SQL Server Express you are using (it is almost always useful to include this information in your question).
In PowerShell you should do this:
(Get-ChildItem C:\TEMP\file1.txt).Length
I had to struggle for a little bit but I found a solution, I added
-Dsonar.coverage.exclusions=**/*.*
and the coverage metric was cancelled from the dashboard at all, so I realized that the problem was the path I was passing, not the property. In my case the path to exclude was java/org/acme/exceptions, so I used :
`-Dsonar.coverage.exclusions=**/exceptions/**/*.*`
and it worked, but since I don't have sub-folders it also works with
-Dsonar.coverage.exclusions=**/exceptions/*.*
When i will getting this error on my site .it will stop some functionality on my site, after research i find the solution for this problem ,
$colorpicker_inputs.live('focus', function(e) {
jQuery(this).next('.farb-popup').show();
jQuery(this).parents('li').css( {
position : 'relative',
zIndex : '9999'
})
jQuery('#tabber').css( {
overflow : 'visible'
});
});
$colorpicker_inputs.live('blur', function(e) {
jQuery(this).next('.farb-popup').hide();
jQuery(this).parents('li').css( {
zIndex : '0'
})
});
Should be replace 'live' to 'on' check below
$colorpicker_inputs.on('focus', function(e) {
jQuery(this).next('.farb-popup').show();
jQuery(this).parents('li').css( {
position : 'relative',
zIndex : '9999'
})
jQuery('#tabber').css( {
overflow : 'visible'
});
});
$colorpicker_inputs.on('blur', function(e) {
jQuery(this).next('.farb-popup').hide();
jQuery(this).parents('li').css( {
zIndex : '0'
})
});
One more basic exmaple below :
.live(event, selector, function)
Change it to :
.on(event, selector, function)
This is a simple solution which solved the problem for me:
label
{
/* for firefox */
vertical-align:middle;
/*for internet explorer */
*bottom:3px;
*position:relative;
padding-bottom:7px;
}
In CakePHP 1.3, use 'default'=>value
to select the default value in a select input:
$this->Form->input('Leaf.id', array('type'=>'select', 'label'=>'Leaf', 'options'=>$leafs, 'default'=>'3'));
Either of the following SQL will return all schema in Oracle DB.
select owner FROM all_tables group by owner;
select distinct owner FROM all_tables;
Getting the ball rolling with this community wiki answer. Feel free to edit me with your improvements.
ws WebSocket server and client for node.js. One of the fastest libraries if not the fastest one.
websocket-node WebSocket server and client for node.js
websocket-driver-node WebSocket server and client protocol parser node.js - used in faye-websocket-node
faye-websocket-node WebSocket server and client for node.js - used in faye and sockjs
socket.io WebSocket server and client for node.js + client for browsers + (v0 has newest to oldest fallbacks, v1 of Socket.io uses engine.io) + channels - used in stack.io. Client library tries to reconnect upon disconnection.
sockjs WebSocket server and client for node.js and others + client for browsers + newest to oldest fallbacks
faye WebSocket server and client for node.js and others + client for browsers + fallbacks + support for other server-side languages
deepstream.io clusterable realtime server that handles WebSockets & TCP connections and provides data-sync, pub/sub and request/response
socketcluster WebSocket server cluster which makes use of all CPU cores on your machine. For example, if you were to use an xlarge Amazon EC2 instance with 32 cores, you would be able to handle almost 32 times the traffic on a single instance.
primus Provides a common API for most of the libraries above for easy switching + stability improvements for all of them.
When to use:
use the basic WebSocket servers when you want to use the native WebSocket implementations on the clientside, beware of the browser incompatabilities
use the fallback libraries when you care about browser fallbacks
use the full featured libraries when you care about channels
use primus when you have no idea about what to use, are not in the mood for rewriting your application when you need to switch frameworks because of changing project requirements or need additional connection stability.
Where to test:
Firecamp is a GUI testing environment for SocketIO, WS and all major real-time technology. Debug the real-time events while you're developing it.
In this code we define a method and then we can simply call it. we give it two parameters. first one is text and the second one should be count of characters that you wanna display.
function the_excerpt(string $text,int $length){
if(strlen($text) > $length){$text = substr($text,0,$length);}
return $text;
}
You will not be able to find out the password he chose. However, you may create a new user or set a new password to the existing user.
Usually, you can login as the postgres user:
Open a Terminal and do sudo su postgres
.
Now, after entering your admin password, you are able to launch psql
and do
CREATE USER yourname WITH SUPERUSER PASSWORD 'yourpassword';
This creates a new admin user. If you want to list the existing users, you could also do
\du
to list all users and then
ALTER USER yourusername WITH PASSWORD 'yournewpass';
It's not exactly clear how you want to search the array. Here are some alternatives:
Find all items containing the exact string "Ra" (returns items 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.Contains("Ra"))
Find all items starting with the exact string "Ra" (returns items 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.StartsWith("Ra"))
Find all items containing any case version of "ra" (returns items 0, 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().Contains("ra"))
Find all items starting with any case version of "ra" (retuns items 0, 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))
-
If you are not using VB 9+ then you don't have anonymous functions, so you have to create a named function.
Example:
Function ContainsRa(s As String) As Boolean
Return s.Contains("Ra")
End Function
Usage:
Dim result As String() = Array.FindAll(arr, ContainsRa)
Having a function that only can compare to a specific string isn't always very useful, so to be able to specify a string to compare to you would have to put it in a class to have somewhere to store the string:
Public Class ArrayComparer
Private _compareTo As String
Public Sub New(compareTo As String)
_compareTo = compareTo
End Sub
Function Contains(s As String) As Boolean
Return s.Contains(_compareTo)
End Function
Function StartsWith(s As String) As Boolean
Return s.StartsWith(_compareTo)
End Function
End Class
Usage:
Dim result As String() = Array.FindAll(arr, New ArrayComparer("Ra").Contains)
My work uses Winnovative's PDF generator (We've used it mainly to convert HTML to PDF, but you can generate it other ways as well)
In case someone needs a CSS background with different color repeating horizontal stripes, here is how I managed to achieve this:
body {_x000D_
font-family: 'Lucida Grande', 'Helvetica Neue', Helvetica, Arial, sans-serif;_x000D_
font-size: 13px;_x000D_
}_x000D_
_x000D_
.css-stripes {_x000D_
margin: 0 auto;_x000D_
width: 200px;_x000D_
padding: 100px;_x000D_
text-align: center;_x000D_
/* For browsers that do not support gradients */_x000D_
background-color: #F691FF;_x000D_
/* Safari 5.1 to 6.0 */_x000D_
background: -webkit-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
/* Opera 11.1 to 12.0 */_x000D_
background: -o-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
/* Firefox 3.6 to 15 */_x000D_
background: -moz-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
/* Standard syntax */_x000D_
background-image: repeating-linear-gradient(to top, #F691FF, #EC72A8);_x000D_
background-size: 1px 2px;_x000D_
}
_x000D_
<div class="css-stripes">Hello World!</div>
_x000D_
You should create an exclude file for this. Check out this gist which is pretty self explanatory.
To address your question though, you may need to either de-index the .tmproj
file (if you've already added it to the index) with git rm --cached path/to/.tmproj
, or git add
and commit
your .gitignore
file.
You can use sprintf(str_replace('?', '"%s"', $sql), ...$params);
Here is an example:
function mysqli_prepared_query($link, $sql, $types='', $params=array()) {
echo sprintf(str_replace('?', '"%s"', $sql), ...$params);
//prepare, bind, execute
}
$link = new mysqli($server, $dbusername, $dbpassword, $database);
$sql = "SELECT firstname, lastname FROM users WHERE userage >= ? AND favecolor = ?";
$types = "is"; //integer and string
$params = array(20, "Brown");
if(!$qry = mysqli_prepared_query($link, $sql, $types, $params)){
echo "Failed";
} else {
echo "Success";
}
Note this only works for PHP >= 5.6
You can use mysqli_connect($mysql_hostname , $mysql_username)
instead of mysql_connect($mysql_hostname , $mysql_username)
.
mysql_*
functions were removed as of PHP 7. You now have two alternatives: MySQLi and PDO.
I have the same issue, but I use GitLab instead of Jenkins. The steps I had to do to get over the issue:
I realize that is more specific to my setup. But without doing all of the steps above I would still continue to get this error message
Return code is: 501 , ReasonPhrase:HTTPS Required
You can use java System.properties
, for using them from eclipse you could:
-Dlabel="label_value"
in the VM arguments of the test Run Configuration
like this:Then run the test:
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Main {
@Test
public void test(){
System.out.println(System.getProperty("label"));
assertEquals("label_value", System.getProperty("label"));
}
}
Finally it should pass the test and output this in the console:
label_value
In my case, issue was occured even after all these configurations have done (@Pekka has mentioned changes in httpd.conf & .htaccess files). It was resolved only after I add
<Directory "project/path">
Order allow,deny
Allow from all
AllowOverride All
</Directory>
to virtual host configuration in vhost file
Edit on 29/09/2017 (For Apache 2.4 <) Refer this answer
<VirtualHost dropbox.local:80>
DocumentRoot "E:/Documenten/Dropbox/Dropbox/dummy-htdocs"
ServerName dropbox.local
ErrorLog "logs/dropbox.local-error.log"
CustomLog "logs/dropbox.local-access.log" combined
<Directory "E:/Documenten/Dropbox/Dropbox/dummy-htdocs">
# AllowOverride All # Deprecated
# Order Allow,Deny # Deprecated
# Allow from all # Deprecated
# --New way of doing it
Require all granted
</Directory>
You can check if jQuery is loaded or not by many ways such as:
if (typeof jQuery == 'undefined') {
// jQuery IS NOT loaded, do stuff here.
}
if (typeof jQuery == 'function')
//or
if (typeof $== 'function')
if (jQuery) {
// This will throw an error in STRICT MODE if jQuery is not loaded, so don't use if using strict mode
alert("jquery is loaded");
} else {
alert("Not loaded");
}
if( 'jQuery' in window ) {
// Do Stuff
}
Now after checking if jQuery is not loaded, you can load jQuery like this:
Although this part has been answered by many in this post but still answering for the sake of completeness of the code
// This part should be inside your IF condition when you do not find jQuery loaded
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "http://code.jquery.com/jquery-3.3.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
from jquery api
Added to jQuery in version 1.4, the .delay()
method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue. Only subsequent events in a queue are delayed; for example this will not delay the no-arguments forms of .show()
or .hide()
which do not use the effects queue.
Preview in OS X seems to be able to do this out of the box. Adobe Reader shows the doc as "data typed can't be saved" but Preview was able to save my changes without hassle.
One aspect of Turing completeness is the halting problem.
This means that, if CSS is Turing complete, then there's no general algorithm for determining whether a CSS program will finish running or loop forever.
But we can derive such an algorithm for CSS! Here it is:
If the stylesheet doesn't declare any animations, then it will halt.
If it does have animations, then:
If any animation-iteration-count
is infinite
, and the containing selector is matched in the HTML, then it will not halt.
Otherwise, it will halt.
That's it. Since we just solved the halting problem for CSS, it follows that CSS is not Turing complete.
(Other people have mentioned IE 6, which allows for embedding arbitrary JavaScript expressions in CSS; that will obviously add Turing completeness. But that feature is non-standard, and nobody in their right mind uses it anyway.)
Daniel Wagner brought up a point that I missed in the original answer. He notes that while I've covered animations, other parts of the style engine such as selector matching or layout can lead to Turing completeness as well. While it's difficult to make a formal argument about these, I'll try to outline why Turing completeness is still unlikely to happen.
First: Turing complete languages have some way of feeding data back into itself, whether it be through recursion or looping. But the design of the CSS language is hostile to this feedback:
@media
queries can only check properties of the browser itself, such as viewport size or pixel resolution. These properties can change via user interaction or JavaScript code (e.g. resizing the browser window), but not through CSS alone.
::before
and ::after
pseudo-elements are not considered part of the DOM, and cannot be matched in any other way.
Selector combinators can only inspect elements above and before the current element, so they cannot be used to create dependency cycles.
It's possible to shift an element away when you hover over it, but the position only updates when you move the mouse.
That should be enough to convince you that selector matching, on its own, cannot be Turing complete. But what about layout?
The modern CSS layout algorithm is very complex, with features such as Flexbox and Grid muddying the waters. But even if it were possible to trigger an infinite loop with layout, it would be hard to leverage this to perform useful computation. That's because CSS selectors inspect only the internal structure of the DOM, not how these elements are laid out on the screen. So any Turing completeness proof using the layout system must depend on layout alone.
Finally – and this is perhaps the most important reason – browser vendors have an interest in keeping CSS not Turing complete. By restricting the language, vendors allow for clever optimizations that make the web faster for everyone. Moreover, Google dedicates a whole server farm to searching for bugs in Chrome. If there were a way to write an infinite loop using CSS, then they probably would have found it already
If you simply want to see the column names this one line should provide it without changing any settings:
describe database.tablename;
However, if that doesn't work for your version of hive this code will provide it, but your default database will now be the database you are using:
use database;
describe tablename;
I think you can get this error if your database model is not correct and the underlying data contains a null which the model is attempting to map to a non-null object.
For example, some auto-generated models can attempt to map nvarchar(1) columns to char rather than string and hence if this column contains nulls it will throw an error when you attempt to access the data.
Note, LinqPad has a compatibility option if you want it to generate a model like that, but probably doesn't do this by default, which might explain it doesn't give you the error.
If you don't see the "Browse With..." option stop debugging first. =)
Date#parse
is deprecated . The alternative is :
java.text.DateFormat#parse
thereFore :
new SimpleDateFormat("E MMM dd H:m:s z yyyy", Locale.ARABIC).parse(testDate)
std::vector<int> return_vector(void)
{
std::vector<int> tmp {1,2,3,4,5};
return tmp;
}
std::vector<int> &&rval_ref = return_vector();
The first example returns a temporary which is caught by rval_ref
. That temporary will have its life extended beyond the rval_ref
definition and you can use it as if you had caught it by value. This is very similar to the following:
const std::vector<int>& rval_ref = return_vector();
except that in my rewrite you obviously can't use rval_ref
in a non-const manner.
std::vector<int>&& return_vector(void)
{
std::vector<int> tmp {1,2,3,4,5};
return std::move(tmp);
}
std::vector<int> &&rval_ref = return_vector();
In the second example you have created a run time error. rval_ref
now holds a reference to the destructed tmp
inside the function. With any luck, this code would immediately crash.
std::vector<int> return_vector(void)
{
std::vector<int> tmp {1,2,3,4,5};
return std::move(tmp);
}
std::vector<int> &&rval_ref = return_vector();
Your third example is roughly equivalent to your first. The std::move
on tmp
is unnecessary and can actually be a performance pessimization as it will inhibit return value optimization.
The best way to code what you're doing is:
std::vector<int> return_vector(void)
{
std::vector<int> tmp {1,2,3,4,5};
return tmp;
}
std::vector<int> rval_ref = return_vector();
I.e. just as you would in C++03. tmp
is implicitly treated as an rvalue in the return statement. It will either be returned via return-value-optimization (no copy, no move), or if the compiler decides it can not perform RVO, then it will use vector's move constructor to do the return. Only if RVO is not performed, and if the returned type did not have a move constructor would the copy constructor be used for the return.
Well,
$xml = "l
vv";
Works.
You can also use the following:
$xml = "l\nvv";
or
$xml = <<<XML
l
vv
XML;
You can concatenate strings using the .=
operator.
$str = "Hello";
$str .= " World";
echo $str; //Will echo out "Hello World";
A simple method involves using the get and set functions on the variable
using System;
public string Name{
get{
return name;
}
set{
name= value;
OnVarChange?.Invoke();
}
}
private string name;
public event System.Action OnVarChange;
I have wrote a generic function in which you can pass context, icon is id drawable/mipmap image icon and new color which you need for that icon.
This function returns a drawable.
public static Drawable changeDrawableColor(Context context,int icon, int newColor) {
Drawable mDrawable = ContextCompat.getDrawable(context, icon).mutate();
mDrawable.setColorFilter(new PorterDuffColorFilter(newColor, PorterDuff.Mode.SRC_IN));
return mDrawable;
}
changeDrawableColor(getContext(),R.mipmap.ic_action_tune, Color.WHITE);
I think you're not using GROUP BY properly.
The point of GROUP BY is to organize your table into sections based off a certain column or columns before performing math/aggregate functions.
For example, in this table:
Name Age Salary
Bob 25 20000
Sally 42 40000
John 42 90000
A SELECT statement could GROUP BY name (Bob, Sally, and John would each be separate groups), Age (Bob would be one group, Sally and John would be another), or Salary (pretty much same result as name).
Grouping by "1" doesn't make any sense because "1" is not a column name.
To generate a shared library you need first to compile your C code with the -fPIC
(position independent code) flag.
gcc -c -fPIC hello.c -o hello.o
This will generate an object file (.o), now you take it and create the .so file:
gcc hello.o -shared -o libhello.so
EDIT: Suggestions from the comments:
You can use
gcc -shared -o libhello.so -fPIC hello.c
to do it in one step. – Jonathan Leffler
I also suggest to add -Wall
to get all warnings, and -g
to get debugging information, to your gcc
commands. – Basile Starynkevitch
Try this:
df[['id']] = df[['id']].astype(pd.Int64Dtype())
If you print it's dtypes
, you will get id Int64
instead of normal one int64
if (Build.BRAND.equalsIgnoreCase("generic")) {
// Is the emulator
}
All BUILD references are build.prop values, so you have to consider that if you are going to put this into release code, you may have some users with root that have modified theirs for whatever reason. There are virtually no modifications that require using generic as the brand unless specifically trying to emulate the emulator.
Fingerprint is the build compile and kernel compile signature. There are builds that use generic, usually directly sourced from Google.
On a device that has been modified, the IMEI has a possibility of being zeroed out as well, so that is unreliable unless you are blocking modified devices altogether.
Goldfish is the base android build that all other devices are extended from. EVERY Android device has an init.goldfish.rc unless hacked and removed for unknown reasons.
The accepted answer is correct but I will rewrite complete steps for java
.
I am currently using Swagger V2
with Spring Boot 2
and it's straightforward 3 step process.
Step 1: Add required dependencies in pom.xml
file. The second dependency is optional use it only if you need Swagger UI
.
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
Step 2: Add configuration class
@Configuration
@EnableSwagger2
public class SwaggerConfig {
public static final Contact DEFAULT_CONTACT = new Contact("Usama Amjad", "https://stackoverflow.com/users/4704510/usamaamjad", "[email protected]");
public static final ApiInfo DEFAULT_API_INFO = new ApiInfo("Article API", "Article API documentation sample", "1.0", "urn:tos",
DEFAULT_CONTACT, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList<VendorExtension>());
@Bean
public Docket api() {
Set<String> producesAndConsumes = new HashSet<>();
producesAndConsumes.add("application/json");
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(DEFAULT_API_INFO)
.produces(producesAndConsumes)
.consumes(producesAndConsumes);
}
}
Step 3: Setup complete and now you need to document APIs in controllers
@ApiOperation(value = "Returns a list Articles for a given Author", response = Article.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Success"),
@ApiResponse(code = 404, message = "The resource you were trying to reach is not found") })
@GetMapping(path = "/articles/users/{userId}")
public List<Article> getArticlesByUser() {
// Do your code
}
Usage:
You can access your Documentation from http://localhost:8080/v2/api-docs
just copy it and paste in Postman to import collection.
Optional Swagger UI: You can also use standalone UI without any other rest client via http://localhost:8080/swagger-ui.html
and it's pretty good, you can host your documentation without any hassle.
To extend the given answer with few useful tricks:
var markers = //some array;
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
bounds.extend(markers[i].getPosition());
}
//center the map to a specific spot (city)
map.setCenter(center);
//center the map to the geometric center of all markers
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
//remove one zoom level to ensure no marker is on the edge.
map.setZoom(map.getZoom()-1);
// set a minimum zoom
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if(map.getZoom()> 15){
map.setZoom(15);
}
//Alternatively this code can be used to set the zoom for just 1 marker and to skip redrawing.
//Note that this will not cover the case if you have 2 markers on the same address.
if(count(markers) == 1){
map.setMaxZoom(15);
map.fitBounds(bounds);
map.setMaxZoom(Null)
}
UPDATE:
Further research in the topic show that fitBounds() is a asynchronic
and it is best to make Zoom manipulation with a listener defined before calling Fit Bounds.
Thanks @Tim, @xr280xr, more examples on the topic : SO:setzoom-after-fitbounds
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
this.setZoom(map.getZoom()-1);
if (this.getZoom() > 15) {
this.setZoom(15);
}
});
map.fitBounds(bounds);
for me, prepared statements is a must-have feature. more exactly, parameter binding (which only works on prepared statements). it's the only really sane way to insert strings into SQL commands. i really don't trust the 'escaping' functions. the DB connection is a binary protocol, why use an ASCII-limited sub-protocol for parameters?
you can use JsonConvert.SerializeObject()
JsonConvert.SerializeObject(myObject) // myObject is returned by JObject.Parse() method
git remote add origin <remote_repo_url>
git push --all origin
If you want to set all of your branches to automatically use this remote repo when you use git pull
, add --set-upstream
to the push:
git push --all --set-upstream origin
Simple example: Form with textbox and Search button.
If you write "name" into the textbox
and submit form, it will brings you patients with "name" in table.
View:
@using (Ajax.BeginForm("GetPatients", "Patient", new AjaxOptions {//GetPatients is name of method in PatientController
InsertionMode = InsertionMode.Replace, //target element(#patientList) will be replaced
UpdateTargetId = "patientList",
LoadingElementId = "loader" // div with .gif loader - that is shown when data are loading
}))
{
string patient_Name = "";
@Html.EditorFor(x=>patient_Name) //text box with name and id, that it will pass to controller
<input type="submit" value="Search" />
}
@* ... *@
<div id="loader" class=" aletr" style="display:none">
Loading...<img src="~/Images/ajax-loader.gif" />
</div>
@Html.Partial("_patientList") @* this is view with patient table. Same view you will return from controller *@
_patientList.cshtml:
@model IEnumerable<YourApp.Models.Patient>
<table id="patientList" >
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Number)
</th>
</tr>
@foreach (var patient in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => patient.Name)
</td>
<td>
@Html.DisplayFor(modelItem => patient.Number)
</td>
</tr>
}
</table>
Patient.cs
public class Patient
{
public string Name { get; set; }
public int Number{ get; set; }
}
PatientController.cs
public PartialViewResult GetPatients(string patient_Name="")
{
var patients = yourDBcontext.Patients.Where(x=>x.Name.Contains(patient_Name))
return PartialView("_patientList", patients);
}
And also as TSmith said in comments, don´t forget to install jQuery Unobtrusive Ajax library through NuGet.
When I got this error I wasn't even trying to sign the app. I was writing a test app and didn't care about signing. In order to get rid of this message I had to select "Don't Code Sign" from Build Settings under Code Signing.
If you want to use jquery in a web application (e.g. React) and jquery is already loaded with <script src="jquery-3.3.1.js"...
On the webpage you can do:
npm install --save-dev @types/query
and the use it with:
let $: JQueryStatic = (window as any)["jQuery"];
so, you don't need to load jquery a second time (with npm install --save jquery
)
but have all the advantages of Typescript
If you want to pass a parameter to the delayed function:
setTimeout(setTimer, 3000, param1, param2);
numba
module for speed up.On big datasets (500k >
) pd.cut
can be quite slow for binning data.
I wrote my own function in numba
with just in time compilation, which is roughly 16x
faster:
from numba import njit
@njit
def cut(arr):
bins = np.empty(arr.shape[0])
for idx, x in enumerate(arr):
if (x >= 0) & (x < 1):
bins[idx] = 1
elif (x >= 1) & (x < 5):
bins[idx] = 2
elif (x >= 5) & (x < 10):
bins[idx] = 3
elif (x >= 10) & (x < 25):
bins[idx] = 4
elif (x >= 25) & (x < 50):
bins[idx] = 5
elif (x >= 50) & (x < 100):
bins[idx] = 6
else:
bins[idx] = 7
return bins
cut(df['percentage'].to_numpy())
# array([5., 5., 7., 5.])
Optional: you can also map it to bins as strings:
a = cut(df['percentage'].to_numpy())
conversion_dict = {1: 'bin1',
2: 'bin2',
3: 'bin3',
4: 'bin4',
5: 'bin5',
6: 'bin6',
7: 'bin7'}
bins = list(map(conversion_dict.get, a))
# ['bin5', 'bin5', 'bin7', 'bin5']
Speed comparison:
# create dataframe of 8 million rows for testing
dfbig = pd.concat([df]*2000000, ignore_index=True)
dfbig.shape
# (8000000, 1)
%%timeit
cut(dfbig['percentage'].to_numpy())
# 38 ms ± 616 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
pd.cut(dfbig['percentage'], bins=bins, labels=labels)
# 215 ms ± 9.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Swift 3.0 Version of Jake's Answer
// Create the alert controller
let alertController = UIAlertController(title: "Alert!", message: "There is no items for the current user", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
// Add the actions
alertController.addAction(okAction)
alertController.addAction(cancelAction)
// Present the controller
self.present(alertController, animated: true, completion: nil)
To Method onBindViewHolder
Write This Code
holder.remove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Cursor del=dbAdapter.ExecuteQ("delete from TblItem where Id="+values.get(position).getId());
values.remove(position);
notifyDataSetChanged();
}
});
If you don't want to change the authentication method (ident) and mess with pg_hba.conf use this:
First login as the default user
sudo su - posgres
then access psql and create a user with the same name as the one you are login in
postgres=# CREATE USER userOS WITH PASSWORD 'garbage' CREATEDB;
you can verify your user with the corresponding roles with
postgres=# \du
Afer this you can create your database and verify it with
psql -d dbName
\l
\q
In IE9+, Chrome or Firefox you can do:
var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');
Only use WOFF2, or if you need legacy support, WOFF. Do not use any other format
(svg
and eot
are dead formats, ttf
and otf
are full system fonts, and should not be used for web purposes)
In short, font-face is very old, but only recently has been supported by more than IE.
eot
is needed for Internet Explorers that are older than IE9 - they invented the spec, but eot was a proprietary solution.
ttf
and otf
are normal old fonts, so some people got annoyed that this meant anyone could download expensive-to-license fonts for free.
Time passes, SVG 1.1 adds a "fonts" chapter that explains how to model a font purely using SVG markup, and people start to use it. More time passes and it turns out that they are absolutely terrible compared to just a normal font format, and SVG 2 wisely removes the entire chapter again.
Then, woff
gets invented by people with quite a bit of domain knowledge, which makes it possible to host fonts in a way that throws away bits that are critically important for system installation, but irrelevant for the web (making people worried about piracy happy) and allows for internal compression to better suit the needs of the web (making users and hosts happy). This becomes the preferred format.
2019 edit A few years later, woff2
gets drafted and accepted, which improves the compression, leading to even smaller files, along with the ability to load a single font "in parts" so that a font that supports 20 scripts can be stored as "chunks" on disk instead, with browsers automatically able to load the font "in parts" as needed, rather than needing to transfer the entire font up front, further improving the typesetting experience.
If you don't want to support IE 8 and lower, and iOS 4 and lower, and android 4.3 or earlier, then you can just use WOFF (and WOFF2, a more highly compressed WOFF, for the newest browsers that support it.)
@font-face {
font-family: 'MyWebFont';
src: url('myfont.woff2') format('woff2'),
url('myfont.woff') format('woff');
}
Support for woff
can be checked at http://caniuse.com/woff
Support for woff2
can be checked at http://caniuse.com/woff2
From all of the above, I came up with this version. This version also works for me in the mac recovery terminal.
find ./ -name '*.xsl' -exec cp -prv '{}' '/path/to/targetDir/' ';'
It will look in the current directory and recursively in all of the sub directories for files with the xsl extension. It will copy them all to the target directory.
cp flags are:
You can't delete a foreign key if it still references another table. First delete the reference
delete from kontakty
where id_osoby = 1;
DELETE FROM osoby
WHERE id_osoby = 1;
You can try adding:
#aboutDescription
{
height: 100px;
max-height: 100px;
}
I wrote a little 2,2kb library of saving image in localStorage JQueryImageCaching Usage:
<img data-src="path/to/image">
<script>
$('img').imageCaching();
</script>
or if you have a function(string text,string color) and you need to pass the Resource Color String you can do as follow
String.valueOf(getResources().getColor(R.color.enurse_link_color)
Here's another option for those not using heatmap.2
(aheatmap
is good!)
Make a sequential vector of 100 values from min to max of your input matrix, find value closest to 0 in that, make two vector of colours to and from desired midpoint, combine and use them:
breaks <- seq(from=min(range(inputMatrix)), to=max(range(inputMatrix)), length.out=100)
midpoint <- which.min(abs(breaks - 0))
rampCol1 <- colorRampPalette(c("forestgreen", "darkgreen", "black"))(midpoint)
rampCol2 <- colorRampPalette(c("black", "darkred", "red"))(100-(midpoint+1))
rampCols <- c(rampCol1,rampCol2)
To check for local differences:
git diff myfile.txt
or you can use a diff tool (in case you'd like to revert some changes):
git difftool myfile.txt
To use git difftool
more efficiently, install and use your favourite GUI tool such as Meld, DiffMerge or OpenDiff.
Note: You can also use .
(instead of filename) to see current dir changes.
In order to check changes per each line, use: git blame
which will display which line was commited in which commit.
To view the actual file before the commit (where master
is your branch), run:
git show master:path/my_file
If you want it to check explicit for it to not be false (boolean value) you have to use
if(borrar() !== false)
But in JavaScript we usually use falsy and truthy and you could use
if(!borrar())
but then values 0, '', null, undefined, null and NaN would not generate the alert.
The following values are always falsy:
false,
,0 (zero)
,'' or "" (empty string)
,null
,undefined
,NaN
Everything else is truthy. That includes:
'0' (a string containing a single zero)
,'false' (a string containing the text “false”)
,[] (an empty array)
,{} (an empty object)
,function(){} (an “empty” function)
Source: https://www.sitepoint.com/javascript-truthy-falsy/
As an extra perk to convert any value to true or false (boolean type), use double exclamation mark:
!![] === true
!!'false' === true
!!false === false
!!undefined === false
If you use Android default action bar then. If you change from java then some time show previous color.
Example
Then your action bar code inside "app_bar_main". So go inside app_bar_main.xml and just add Background.
Example
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#33691e" <!--use your color -->
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main1" />
You can use a jQuery plugin: jQuery Array Utilities
For example the code below
$.union([1, 2, 2, 3], [2, 3, 4, 5, 5])
will return [1,2,3,4,5]
NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"name" forKey:@"email"];
[contentDictionary setValue:@"name" forKey:@"username"];
[contentDictionary setValue:@"name" forKey:@"password"];
[contentDictionary setValue:@"name" forKey:@"firstName"];
[contentDictionary setValue:@"name" forKey:@"lastName"];
NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(@"%@",jsonStr);
NSString *urlString = [NSString stringWithFormat:@"http://testgcride.com:8081/v1/users"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"moinsam" password:@"cheese"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];
Look at the traceback:
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
out = iter(out)
TypeError: 'bool' object is not iterable
Your code isn't iterating the value, but the code receiving it is.
The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)
) or enclose it in a tuple ((False,)
).
Always read the traceback: it's correct, and it's helpful.
@gerrit_hoekstra wrote: "However, the value of an auto-increment field is only available to an "AFTER-INSERT" trigger - it defaults to 0 in the BEFORE-case."
That is correct but you can select the auto-increment field value that will be inserted by the subsequent INSERT quite easily. This is an example that works:
CREATE DEFINER = CURRENT_USER TRIGGER `lgffin`.`variable_BEFORE_INSERT` BEFORE INSERT
ON `variable` FOR EACH ROW
BEGIN
SET NEW.prefixed_id = CONCAT(NEW.fixed_variable, (SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'lgffin'
AND TABLE_NAME = 'variable'));
END
It's not safe, not recommended, but it's possible.
I have experience in an application using the auto-update option in production.
Well, the main problems and risks found in this solution are:
So, I will not recommend to use auto-update in production.
If you really want to use auto-update in production, I recommend:
And, different of the another posts, I don't think the auto-update enabled it's related with "very well paid" DBAs (as mentioned in other posts). DBAs have more important things to do than write SQL statements to create/change/delete tables and columns. These simple everyday tasks can be done and automated by developers and only passed for DBA team to review, not needing Hibernate and DBAs "very well paid" to write them.
Sometimes using only the line below throws me an Exception,
String text = listView1.SelectedItems[0].Text;
so I use this code below:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedIndices.Count <= 0)
{
return;
}
int intselectedindex = listView1.SelectedIndices[0];
if (intselectedindex >= 0)
{
String text = listView1.Items[intselectedindex].Text;
//do something
//MessageBox.Show(listView1.Items[intselectedindex].Text);
}
}
This is one way of doing it:
document.getElementById("mytext").value = "My value";
In a Chrome extension, you can use
chrome.webRequest.onHeadersReceived.addListener
to rewrite the server response headers. You can either replace an existing header or add an additional header. This is the header you want:
Access-Control-Allow-Origin: *
https://developers.chrome.com/extensions/webRequest#event-onHeadersReceived
I was stuck on CORB issues, and this fixed it for me.
You can also use the jquery prop() method for this.
$(function(){
$('yourselector').prop('target', '_blank');
});
C does not and never has had a native string type. By convention, the language uses arrays of char
terminated with a null char, i.e., with '\0'
. Functions and macros in the language's standard libraries provide support for the null-terminated character arrays, e.g., strlen iterates over an array of char
until it encounters a '\0'
character and strcpy copies from the source string until it encounters a '\0'
.
The use of null-terminated strings in C reflects the fact that C was intended to be only a little more high-level than assembly language. Zero-terminated strings were already directly supported at that time in assembly language for the PDP-10 and PDP-11.
It is worth noting that this property of C strings leads to quite a few nasty buffer overrun bugs, including serious security flaws. For example, if you forget to null-terminate a character string passed as the source argument to strcpy
, the function will keep copying sequential bytes from whatever happens to be in memory past the end of the source string until it happens to encounter a 0
, potentially overwriting whatever valuable information follows the destination string's location in memory.
In your code example, the string literal "Hello, world!" will be compiled into a 14-byte long array of char
. The first 13 bytes will hold the letters, comma, space, and exclamation mark and the final byte will hold the null-terminator character '\0'
, automatically added for you by the compiler. If you were to access the array's last element, you would find it equal to 0
. E.g.:
const char foo[] = "Hello, world!";
assert(foo[12] == '!');
assert(foo[13] == '\0');
However, in your example, message
is only 10 bytes long. strcpy
is going to write all 14 bytes, including the null-terminator, into memory starting at the address of message
. The first 10 bytes will be written into the memory allocated on the stack for message
and the remaining four bytes will simply be written on to the end of the stack. The consequence of writing those four extra bytes onto the stack is hard to predict in this case (in this simple example, it might not hurt a thing), but in real-world code it usually leads to corrupted data or memory access violation errors.
You can use the target
argument in the Thread
constructor to directly pass in a function that gets called instead of run
.
You can do this by subsetting the data you pass into your merge:
merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)
Or you can simply delete the column after your current merge :)
In python3, there is a bytes()
method that is in the same format as encode()
.
str1 = b'hello world'
str2 = bytes("hello world", encoding="UTF-8")
print(str1 == str2) # Returns True
I didn't read anything about this in the docs, but perhaps I wasn't looking in the right place. This way you can explicitly turn strings into byte streams and have it more readable than using encode
and decode
, and without having to prefex b
in front of quotes.
is that what you are looking for:
URI uri = new URI("http://example.com/foo/bar/42?param=true");
String path = uri.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
int id = Integer.parseInt(idStr);
alternatively
URI uri = new URI("http://example.com/foo/bar/42?param=true");
String[] segments = uri.getPath().split("/");
String idStr = segments[segments.length-1];
int id = Integer.parseInt(idStr);
Here is the code for Right click on a webelement.
Actions actions = new Actions(driver);
Action action=actions.contextClick(WebElement).build(); //pass WebElement as an argument
action.perform();
To answer the question literally (since GitHub is not in the question title), also be aware of this post over on superuser. EDIT: Answer copied here in relevant part, slightly modified for clarity in square brackets:
You're getting rejected because you're trying to delete the branch that your origin has currently "checked out".
If you have direct access to the repo, you can just open up a shell [in the bare repo] directory and use good old
git branch
to see what branch origin is currently on. To change it to another branch, you have to usegit symbolic-ref HEAD refs/heads/another-branch
.
`DECLARE
c_id customers.id%type := &c_id;
c_name customers.name%type;
c_add customers.address%type;
c_sal customers.salary%type;
a integer := &a`
Here c_id customers.id%type := &c_id; statement inputs the c_id with type already defined in the table and statement a integer := &a just input integer in variable a.
Yes, use the rendered
attribute.
<h:form rendered="#{some boolean condition}">
You usually tie it to the model rather than letting the model grab the component and manipulate it.
E.g.
<h:form rendered="#{bean.booleanValue}" />
<h:form rendered="#{bean.intValue gt 10}" />
<h:form rendered="#{bean.objectValue eq null}" />
<h:form rendered="#{bean.stringValue ne 'someValue'}" />
<h:form rendered="#{not empty bean.collectionValue}" />
<h:form rendered="#{not bean.booleanValue and bean.intValue ne 0}" />
<h:form rendered="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />
Note the importance of keyword based EL operators such as gt
, ge
, le
and lt
instead of >
, >=
, <=
and <
as angle brackets <
and >
are reserved characters in XML. See also this related Q&A: Error parsing XHTML: The content of elements must consist of well-formed character data or markup.
As to your specific use case, let's assume that the link is passing a parameter like below:
<a href="page.xhtml?form=1">link</a>
You can then show the form as below:
<h:form rendered="#{param.form eq '1'}">
(the #{param}
is an implicit EL object referring to a Map
representing the request parameters)
Right. Better to use a function:
CREATE OR REPLACE FUNCTION yyyymm() RETURNS text
LANGUAGE 'plpgsql' AS $$
DECLARE
retval text;
m integer;
BEGIN
retval := EXTRACT(year from current_timestamp);
m := EXTRACT(month from current_timestamp);
IF m < 10 THEN retval := retval || '0'; END IF;
RETURN retval || m;
END $$;
SELECT yyyymm();
DROP TABLE foo;
CREATE TABLE foo (
key int PRIMARY KEY,
colname text DEFAULT yyyymm()
);
INSERT INTO foo (key) VALUES (0);
SELECT * FROM FOO;
This gives me
key | colname
-----+---------
0 | 200905
Make sure you run createlang plpgsql
from the Unix command line, if necessary.
app.use()
is intended for binding middleware to your application. The path
is a "mount" or "prefix" path and limits the middleware to only apply to any paths requested that begin with it. It can even be used to embed another application:
// subapp.js
var express = require('express');
var app = modules.exports = express();
// ...
// server.js
var express = require('express');
var app = express();
app.use('/subapp', require('./subapp'));
// ...
By specifying /
as a "mount" path, app.use()
will respond to any path that starts with /
, which are all of them and regardless of HTTP verb used:
GET /
PUT /foo
POST /foo/bar
app.get()
, on the other hand, is part of Express' application routing and is intended for matching and handling a specific route when requested with the GET
HTTP verb:
GET /
And, the equivalent routing for your example of app.use()
would actually be:
app.all(/^\/.*/, function (req, res) {
res.send('Hello');
});
(Update: Attempting to better demonstrate the differences.)
The routing methods, including app.get()
, are convenience methods that help you align responses to requests more precisely. They also add in support for features like parameters and next('route')
.
Within each app.get()
is a call to app.use()
, so you can certainly do all of this with app.use()
directly. But, doing so will often require (probably unnecessarily) reimplementing various amounts of boilerplate code.
Examples:
For simple, static routes:
app.get('/', function (req, res) {
// ...
});
vs.
app.use('/', function (req, res, next) {
if (req.method !== 'GET' || req.url !== '/')
return next();
// ...
});
With multiple handlers for the same route:
app.get('/', authorize('ADMIN'), function (req, res) {
// ...
});
vs.
const authorizeAdmin = authorize('ADMIN');
app.use('/', function (req, res, next) {
if (req.method !== 'GET' || req.url !== '/')
return next();
authorizeAdmin(req, res, function (err) {
if (err) return next(err);
// ...
});
});
With parameters:
app.get('/item/:id', function (req, res) {
let id = req.params.id;
// ...
});
vs.
const pathToRegExp = require('path-to-regexp');
function prepareParams(matches, pathKeys, previousParams) {
var params = previousParams || {};
// TODO: support repeating keys...
matches.slice(1).forEach(function (segment, index) {
let { name } = pathKeys[index];
params[name] = segment;
});
return params;
}
const itemIdKeys = [];
const itemIdPattern = pathToRegExp('/item/:id', itemIdKeys);
app.use('/', function (req, res, next) {
if (req.method !== 'GET') return next();
var urlMatch = itemIdPattern.exec(req.url);
if (!urlMatch) return next();
if (itemIdKeys && itemIdKeys.length)
req.params = prepareParams(urlMatch, itemIdKeys, req.params);
let id = req.params.id;
// ...
});
Note: Express' implementation of these features are contained in its
Router
,Layer
, andRoute
.
Updated for Swift 3
Create two View Controllers with a button on each. For the second view controller, set the class name to SecondViewController
and the storyboard ID to secondVC
.
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBAction func presentButtonTapped(_ sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myModalViewController = storyboard.instantiateViewController(withIdentifier: "secondVC")
myModalViewController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
myModalViewController.modalTransitionStyle = UIModalTransitionStyle.coverVertical
self.present(myModalViewController, animated: true, completion: nil)
}
}
SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
@IBAction func dismissButtonTapped(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
Source:
Here you go with:
from b in _dbContext.Burden
join bl in _dbContext.BurdenLookups on
new { Organization_Type = b.Organization_Type_ID, Cost_Type = b.Cost_Type_ID } equals
new { Organization_Type = bl.Organization_Type_ID, Cost_Type = bl.Cost_Type_ID }
This is a simple circle as a drawable in Android.
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="#666666"/>
<size
android:width="120dp"
android:height="120dp"/>
</shape>
The following simply returns 4 as an answer. When you replace the add expressions for strings it returns the first string.
Function StartingMain {
$a = 1 + 3
$b = 2 + 5
$c = 3 + 7
Return $a
}
Function StartingEnd($b) {
Write-Host $b
}
StartingEnd(StartingMain)
This can also be done for an array. The example below will return "Text 2"
Function StartingMain {
$a = ,@("Text 1","Text 2","Text 3")
Return $a
}
Function StartingEnd($b) {
Write-Host $b[1]
}
StartingEnd(StartingMain)
Note that you have to call the function below the function itself. Otherwise, the first time it runs it will return an error that it doesn't know what "StartingMain" is.
I'm not sure if I'm answering the question right, but here's a familiar example:
The return type of GetLastError()
in Windows is nonzero if there was an error, or zero otherwise. The reverse is usually true of the return value of the function you called.
Try this small example:
Code:
try {
Path tmpDir = Files.createTempDirectory("tmpDir");
System.out.println(tmpDir.toString());
Files.delete(tmpDir);
} catch (IOException e) {
e.printStackTrace();
}
Imports:
java.io.IOException
java.nio.file.Files
java.nio.file.Path
Console output on Windows machine:
C:\Users\userName\AppData\Local\Temp\tmpDir2908538301081367877
Comment:
Files.createTempDirectory generates unique ID atomatically - 2908538301081367877.
Note:
Read the following for deleting directories recursively:
Delete directories recursively in Java
This is probably not a solution to your problem, but a suggestion just in case (I know I ran into a similar problem before but not with a .NET application).
If you are on a 64-bit machine, there are 2 regsvr32.exe
files;
One is in \Windows\System32
and the other one is in \Windows\SysWOW64
.
You cannot register 64-bit COM-objects with the 32-bit version, but you can do it vice versa. I'd try registering your DLL with both regsvr32.exe
files explicitly (i.e. typing "C:\Windows\System32\regsvr32.exe /i mydll.dll
" and then "C:\Windows\SysWOW64\regsvr32.exe /i mydll.dll
") and seeing if that helps...
With Hash::select
:
params = params.select { |key, value| /^choice\d+$/.match(key.to_s) }
If you have a list of lists, you only needed to use ...
import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)
per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.
try this it uses the underlying C.
timeval = struct.pack('ll', 2, 100)
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeval)
Tags and Elements are not the same.
Elements
They are the pieces themselves, i.e. a paragraph is an element, or a header is an element, even the body is an element. Most elements can contain other elements, as the body element would contain header elements, paragraph elements, in fact pretty much all of the visible elements of the DOM.
Eg:
<p>This is the <span>Home</span> page</p>
Tags
Tags are not the elements themselves, rather they're the bits of text you use to tell the computer where an element begins and ends. When you 'mark up' a document, you generally don't want those extra notes that are not really part of the text to be presented to the reader. HTML borrows a technique from another language, SGML, to provide an easy way for a computer to determine which parts are "MarkUp" and which parts are the content. By using '<' and '>' as a kind of parentheses, HTML can indicate the beginning and end of a tag, i.e. the presence of '<' tells the browser 'this next bit is markup, pay attention'.
The browser sees the letters '
' and decides 'A new paragraph is starting, I'd better start a new line and maybe indent it'. Then when it sees '
' it knows that the paragraph it was working on is finished, so it should break the line there before going on to whatever is next.- Opening tag.
- Closing tagselect table_name
from information_schema.columns
where COLUMN_NAME = 'MyColumn'
Still nothing good enough using native stuff. Here is what I ended up with:
public static string GetAbsoluteUrl(string url)
{
//VALIDATE INPUT
if (String.IsNullOrEmpty(url))
{
return String.Empty;
}
//VALIDATE INPUT FOR ALREADY ABSOLUTE URL
if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
return url;
}
//GET CONTEXT OF CURRENT USER
HttpContext context = HttpContext.Current;
//RESOLVE PATH FOR APPLICATION BEFORE PROCESSING
if (url.StartsWith("~/"))
{
url = (context.Handler as Page).ResolveUrl(url);
}
//BUILD AND RETURN ABSOLUTE URL
string port = (context.Request.Url.Port != 80 && context.Request.Url.Port != 443) ? ":" + context.Request.Url.Port : String.Empty;
return context.Request.Url.Scheme + Uri.SchemeDelimiter + context.Request.Url.Host + port + "/" + url.TrimStart('/');
}
Opposite up is children(), but opposite in position is prepend(). Here a very good tutorial.
I have come up with a simpler solution.
Get the returned value of the page name from wp_title(). If empty, print homepage name, otherwise echo the wp_title() value.
<?php $title = wp_title('', false); ?>
Remember to remove the separation with the first argument and then set display to false to use as an input to the variable. Then just bung the code between your heading, etc. tags.
<?php if ( $title == "" ) : echo "Home"; else : echo $title; endif; ?>
It worked a treat for me and ensuring that the first is declared in the section where you wish to extract the $title
, this can be tuned to return different variables.
And here is my solution, that always works for me
StringBuffer buf = new StringBuffer();
String temp;
BufferedReader bufReader = new BufferedReader(new InputStreamReader(myBlob.getBinaryStream()));
while ((temp=bufReader.readLine())!=null) {
bufappend(temp);
}
$().live(function(){}); and jQuery.browser is undefined in jquery 1.9.0 - $.browser was deprecated in jquery update
sounds like you are using a different version of jquery 1.9 in godaddy so either change your code or include the migrate plugin http://code.jquery.com/jquery-migrate-1.0.0.js
Let consider that your data are in the file values.txt
and that you want to import them in the database table myTable
then the following query does the job
COPY myTable FROM 'value.txt' (DELIMITER('|'));
https://www.postgresql.org/docs/current/static/sql-copy.html
Refer to RFC 6266 (Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)) http://tools.ietf.org/html/rfc6266
How about using the INSERT ALL statement ?
INSERT ALL
INTO table_name VALUES ()
INTO table_name VALUES ()
...
SELECT Statement;
I remember that the last select statement is mandatory in order to make this request succeed. Don't remember why though. You might consider using PreparedStatement instead as well. lots of advantages !
Farid
I had a situation where I needed two 'if' statements that could both go true and an 'else' or default if neither were true, not sure if this is an improvement on Jossef's answer but it seemed cleaner to me:
ng-class="{'class-one' : value.one , 'class-two' : value.two}" class="else-class"
Where value.one and value.two are true, they take precedent over the .else-class
In case performance is more important than readability and as long as your condition consists of simple arithmetic operations, you can use aggregation pipeline. First, use $project to calculate the left hand side of the condition (take all fields to left hand side). Then use $match to compare with a constant and filter. This way you avoid javascript execution. Below is my test in python:
import pymongo
from random import randrange
docs = [{'Grade1': randrange(10), 'Grade2': randrange(10)} for __ in range(100000)]
coll = pymongo.MongoClient().test_db.grades
coll.insert_many(docs)
Using aggregate:
%timeit -n1 -r1 list(coll.aggregate([
{
'$project': {
'diff': {'$subtract': ['$Grade1', '$Grade2']},
'Grade1': 1,
'Grade2': 1
}
},
{
'$match': {'diff': {'$gt': 0}}
}
]))
1 loop, best of 1: 192 ms per loop
Using find and $where:
%timeit -n1 -r1 list(coll.find({'$where': 'this.Grade1 > this.Grade2'}))
1 loop, best of 1: 4.54 s per loop
If you want this for a Single Class, you can use the PropertyNamingStrategy with the @JsonNaming, something like this:
@JsonNaming(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy.class)
public static class Request {
String businessName;
String businessLegalName;
}
Will serialize to:
{
"business_name" : "",
"business_legal_name" : ""
}
Since Jackson 2.7
the LowerCaseWithUnderscoresStrategy
in deprecated in favor of SnakeCaseStrategy
, so you should use:
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public static class Request {
String businessName;
String businessLegalName;
}
Here very simple method
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
Just to add to roya's answer. In c# 6.0 you can now use string interpolation:
Console.WriteLine($"{customer[DisplayPos],10}" +
$"{salesFigures[DisplayPos],10}" +
$"{feePayable[DisplayPos],10}" +
$"{seventyPercentValue,10}" +
$"{thirtyPercentValue,10}");
This can actually be one line without all the extra dollars, I just think it makes it a bit easier to read like this.
And you could also use a static import on System.Console, allowing you to do this:
using static System.Console;
WriteLine(/* write stuff */);
This is the easiest way I found
background: black;
opacity: 0.5;
Like @Travis and @Mari, I wanted to autoselect when the user clicked in, which means preventing the default behaviour of a mouseup
event, but not prevent the user from clicking around. The solution I came up with, which works in IE11, Chrome 45, Opera 32 and Firefox 29 (these are the browsers I currently have installed), is based on the sequence of events involved in a mouse click.
When you click on a text input that does not have focus, you get these events (among others):
mousedown
: In response to your click. Default handling raises focus
if necessary and sets selection start.focus
: As part of the default handling of mousedown
.mouseup
: The completion of your click, whose default handling will set the selection end.When you click on a text input that already has focus, the focus
event is skipped. As @Travis and @Mari both astutely noticed, the default handling of mouseup
needs to be prevented only if the focus
event occurs. However, as there is no "focus
didn't happen" event, we need to infer this, which we can do within the mousedown
handler.
@Mari's solution requires that jQuery be imported, which I want to avoid. @Travis's solution does this by inspecting document.activeElement
. I don't know why exactly his solution doesn't work across browsers, but there is another way to track whether the text input has focus: simply follow its focus
and blur
events.
Here is the code that works for me:
var blockMouseUp = false;
var customerInputFocused = false;
txtCustomer.onfocus =
function ()
{
try
{
txtCustomer.selectionStart = 0;
txtCustomer.selectionEnd = txtCustomer.value.length;
}
catch (error)
{
txtCustomer.select();
}
customerInputFocused = true;
};
txtCustomer.onblur =
function ()
{
customerInputFocused = false;
};
txtCustomer.onmousedown =
function ()
{
blockMouseUp = !customerInputFocused;
};
txtCustomer.onmouseup =
function ()
{
if (blockMouseUp)
return false;
};
I hope this is of help to someone. :-)
Use django-phonenumber-field: https://github.com/stefanfoulis/django-phonenumber-field
pip install django-phonenumber-field
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2)
To turn off axes for all subplots, do either:
[axi.set_axis_off() for axi in ax.ravel()]
or
map(lambda axi: axi.set_axis_off(), ax.ravel())
function update() {
$("#notice_div").html('Loading..');
$.ajax({
type: 'GET',
url: 'jbede.php',
timeout: 2000,
success: function(data) {
$("#some_div").html(data);
$("#notice_div").html('');
window.setTimeout(update, 10000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#notice_div").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
});
}
$(document).ready(function() {
update();
});
This is Better Code
You can use subList(int fromIndex, int toIndex)
method on your integers arr, something like this:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);
List<Integer> partialArr = arr.subList(1, 3);
// print the subArr
for (Integer i: partialArr)
System.out.println(i + " ");
}
}
Output will be: 2 3
.
Note that subList(int fromIndex, int toIndex)
method performs minus 1 on the 2nd variable it receives (var2 - 1), i don't know exactly why, but that's what happens, maybe to reduce the chance of exceeding the size of the array.
I had the same issues. I have followed @ThomasReggi and @CoolAJ86 solution and worked well but I'm not satisfied with the solution.
Because "UNABLE_TO_VERIFY_LEAF_SIGNATURE" issue is happened due to certification configuration level.
I accept @thirdender solution but its partial solution.As per the nginx official website, they clearly mentioned certificate should be combination of The server certificate and chained certificates.
android:text="Previous Line Next Line"
This will work.
for china GFW:
sudo iptables -I INPUT -s 173.194.0.0/16 -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s 173.194.0.0/16 -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"
sudo iptables -I INPUT -s 64.233.0.0/16 -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s 64.233.0.0/16 -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"
sudo iptables -I INPUT -s 74.125.0.0/16 -p tcp --tcp-flags RST RST -j DROP
sudo iptables -I INPUT -s 74.125.0.0/16 -p tcp --tcp-flags RST RST -j LOG --log-prefix "drop rst"
If you have thousands of lines, I guess the easiest way is like this:
-select the line that is the start point for your cursor
-while you are holding alt + shift select the line that is endpoint for your cursor
That's it. Now you have a giant cursor. You can write anything to all of these lines.
If you're using 0
and an empty string ''
and null
to designate undefined you've got a data problem. Just update the columns and fix your schema.
UPDATE pt.incentive_channel
SET pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';
UPDATE pt.incentive_channel
SET pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';
UPDATE pt.incentive_channel
SET pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';
This will make joining and selecting substantially easier moving forward.
Give it a display:inline-block
in CSS - that should let it do what you want.
In terms of compatibility: IE6/7 will work with this, as quirks mode suggests:
IE 6/7 accepts the value only on elements with a natural display: inline.
gacutil.exe is the .NET utility used to work with the GAC.
One can check the availability of a shared assembly in GAC by using the command:
gacutil.exe /l "assemblyName"
One can register a shared assembly in the GAC by using the command:
gacutil.exe /i "assemblyName"
Or by dropping an assembly file into the following location using the GUI:
%windir%\assembly\
Other options for this utility will be briefly described if you use the /?
flag, that is:
gacutil.exe /?
background-image:url('image/img2.jpg');
background-repeat:repeat-x;
Use some image for internal image and use this.
Here is a quick DOM example that shows how to read and write a simple xml file with its dtd:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE roles SYSTEM "roles.dtd">
<roles>
<role1>User</role1>
<role2>Author</role2>
<role3>Admin</role3>
<role4/>
</roles>
and the dtd:
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT roles (role1,role2,role3,role4)>
<!ELEMENT role1 (#PCDATA)>
<!ELEMENT role2 (#PCDATA)>
<!ELEMENT role3 (#PCDATA)>
<!ELEMENT role4 (#PCDATA)>
First import these:
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.xml.sax.*;
import org.w3c.dom.*;
Here are a few variables you will need:
private String role1 = null;
private String role2 = null;
private String role3 = null;
private String role4 = null;
private ArrayList<String> rolev;
Here is a reader (String xml is the name of your xml file):
public boolean readXML(String xml) {
rolev = new ArrayList<String>();
Document dom;
// Make an instance of the DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// use the factory to take an instance of the document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// parse using the builder to get the DOM mapping of the
// XML file
dom = db.parse(xml);
Element doc = dom.getDocumentElement();
role1 = getTextValue(role1, doc, "role1");
if (role1 != null) {
if (!role1.isEmpty())
rolev.add(role1);
}
role2 = getTextValue(role2, doc, "role2");
if (role2 != null) {
if (!role2.isEmpty())
rolev.add(role2);
}
role3 = getTextValue(role3, doc, "role3");
if (role3 != null) {
if (!role3.isEmpty())
rolev.add(role3);
}
role4 = getTextValue(role4, doc, "role4");
if ( role4 != null) {
if (!role4.isEmpty())
rolev.add(role4);
}
return true;
} catch (ParserConfigurationException pce) {
System.out.println(pce.getMessage());
} catch (SAXException se) {
System.out.println(se.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
return false;
}
And here a writer:
public void saveToXML(String xml) {
Document dom;
Element e = null;
// instance of a DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// use factory to get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// create instance of DOM
dom = db.newDocument();
// create the root element
Element rootEle = dom.createElement("roles");
// create data elements and place them under root
e = dom.createElement("role1");
e.appendChild(dom.createTextNode(role1));
rootEle.appendChild(e);
e = dom.createElement("role2");
e.appendChild(dom.createTextNode(role2));
rootEle.appendChild(e);
e = dom.createElement("role3");
e.appendChild(dom.createTextNode(role3));
rootEle.appendChild(e);
e = dom.createElement("role4");
e.appendChild(dom.createTextNode(role4));
rootEle.appendChild(e);
dom.appendChild(rootEle);
try {
Transformer tr = TransformerFactory.newInstance().newTransformer();
tr.setOutputProperty(OutputKeys.INDENT, "yes");
tr.setOutputProperty(OutputKeys.METHOD, "xml");
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tr.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
// send DOM to file
tr.transform(new DOMSource(dom),
new StreamResult(new FileOutputStream(xml)));
} catch (TransformerException te) {
System.out.println(te.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
} catch (ParserConfigurationException pce) {
System.out.println("UsersXML: Error trying to instantiate DocumentBuilder " + pce);
}
}
getTextValue is here:
private String getTextValue(String def, Element doc, String tag) {
String value = def;
NodeList nl;
nl = doc.getElementsByTagName(tag);
if (nl.getLength() > 0 && nl.item(0).hasChildNodes()) {
value = nl.item(0).getFirstChild().getNodeValue();
}
return value;
}
Add a few accessors and mutators and you are done!
No, they are not 0 by default. The simplest way to ensure that all values or defaulted to 0 is to define a constructor
Snapshot() : x(0), y(0) {
}
This ensures that all uses of Snapshot will have initialized values.
This function handles also the invalid 29.2.2001 date.
function parseDate(str) {
var dateParts = str.split(".");
if (dateParts.length != 3)
return null;
var year = dateParts[2];
var month = dateParts[1];
var day = dateParts[0];
if (isNaN(day) || isNaN(month) || isNaN(year))
return null;
var result = new Date(year, (month - 1), day);
if (result == null)
return null;
if (result.getDate() != day)
return null;
if (result.getMonth() != (month - 1))
return null;
if (result.getFullYear() != year)
return null;
return result;
}
There is no way to get the first element, seeing as "hashes" (objects) in JavaScript have unordered properties. Your best bet is to store the keys in an array:
var keys = ["foo", "bar", "baz"];
Then use that to get the proper value:
object[keys[0]]
Since the Fetch API is supported by Chrome (and most other browsers), it is now quite easy to make HTTP requests from the devtools console.
To GET a JSON file for instance:
fetch('https://jsonplaceholder.typicode.com/posts/1')_x000D_
.then(res => res.json())_x000D_
.then(console.log)
_x000D_
Or to POST a new resource:
fetch('https://jsonplaceholder.typicode.com/posts', {_x000D_
method: 'POST',_x000D_
body: JSON.stringify({_x000D_
title: 'foo',_x000D_
body: 'bar',_x000D_
userId: 1_x000D_
}),_x000D_
headers: {_x000D_
'Content-type': 'application/json; charset=UTF-8'_x000D_
}_x000D_
})_x000D_
.then(res => res.json())_x000D_
.then(console.log)
_x000D_
Chrome Devtools actually also support new async/await syntax (even though await normally only can be used within an async function):
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1')
console.log(await response.json())
Notice that your requests will be subject to the same-origin policy, just like any other HTTP-request in the browser, so either avoid cross-origin requests, or make sure the server sets CORS-headers that allow your request.
Using a plugin (old answer)
As an addition to previously posted suggestions I've found the Postman plugin for Chrome to work very well. It allow you to set headers and URL parameters, use HTTP authentication, save request you execute frequently and so on.
If you are looking for a modern >1.7 Dojo way of destroying all node's children this is the way:
// Destroys all domNode's children nodes
// domNode can be a node or its id:
domConstruct.empty(domNode);
Safely empty the contents of a DOM element. empty() deletes all children but keeps the node there.
Check "dom-construct" documentation for more details.
// Destroys domNode and all it's children
domConstruct.destroy(domNode);
Destroys a DOM element. destroy() deletes all children and the node itself.
I ran into the same problem.
In most scenarios using the hack-ish setTimeout(() => { }, 0)
in componentDidMount()
worked.
But not in a special case; and I didn't want to use the ReachDOM findDOMNode
since the documentation says:
Note: findDOMNode is an escape hatch used to access the underlying DOM node. In most cases, use of this escape hatch is discouraged because it pierces the component abstraction.
(Source: findDOMNode)
So in that particular component I had to use the componentDidUpdate()
event, so my code ended up being like this:
componentDidMount() {
// feel this a little hacky? check this: http://stackoverflow.com/questions/26556436/react-after-render-code
setTimeout(() => {
window.addEventListener("resize", this.updateDimensions.bind(this));
this.updateDimensions();
}, 0);
}
And then:
componentDidUpdate() {
this.updateDimensions();
}
Finally, in my case, I had to remove the listener created in componentDidMount
:
componentWillUnmount() {
window.removeEventListener("resize", this.updateDimensions.bind(this));
}
In the DOM, the class of an element is just each class separated by a space. You would just need to implement the parsing logic to insert / remove the classes as necesary.
I wonder though... why wouldn't you want to use jQuery? It makes this kind of problem trivially easy.
To give examples of REST-style resources:
POST /books
with a bunch of book information might create a new book, and respond with the new URL identifying that book: /books/5
.
PUT /books/5
would have to either create a new book with the id of 5, or replace the existing book with ID 5.
In non-resource style, POST
can be used for just about anything that has a side effect. One other difference is that PUT
should be idempotent - multiple PUTs
of the same data to the same URL should be fine, whereas multiple POSTs
might create multiple objects or whatever it is your POST
action does.
Use only this
$("input[type=checkbox]").change(function () {
if ($(this).prop("checked")) {
$(this).val(true);
} else {
$(this).val(false);
}
});
Reproducing tim_yates answer on current hardware and adding leftShift() and concat() method to check the finding:
'String leftShift' {
foo << bar << baz
}
'String concat' {
foo.concat(bar)
.concat(baz)
.toString()
}
The outcome shows concat() to be the faster solution for a pure String, but if you can handle GString somewhere else, GString template is still ahead, while honorable mention should go to leftShift() (bitwise operator) and StringBuffer() with initial allocation:
Environment
===========
* Groovy: 2.4.8
* JVM: OpenJDK 64-Bit Server VM (25.191-b12, Oracle Corporation)
* JRE: 1.8.0_191
* Total Memory: 238 MB
* Maximum Memory: 3504 MB
* OS: Linux (4.19.13-300.fc29.x86_64, amd64)
Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On
user system cpu real
String adder 453 7 460 469
String leftShift 287 2 289 295
String concat 169 1 170 173
GString template 24 0 24 24
Readable GString template 32 0 32 32
GString template toString 400 0 400 406
Readable GString template toString 412 0 412 419
StringBuilder 325 3 328 334
StringBuffer 390 1 391 398
StringBuffer with Allocation 259 1 260 265
<input type="radio" name="radio" value="creditcard" />
<input type="radio" name="radio" value="cash"/>
<input type="radio" name="radio" value="cheque"/>
<input type="radio" name="radio" value="instore"/>
$("input[name='radio']:checked").val()
http://jsfiddle.net/mpalpha/71Lhcb5q/
.container {
display: flex;
background: blue;
padding: 10px;
max-height: 200px;
max-width: 200px;
}
img {
object-fit: contain;
max-height: 100%;
max-width: 100%;
}
_x000D_
<div class="container">
<img src="http://placekitten.com/400/500" />
</div>
_x000D_
use map method we can get input values that stored in array.
var values = $("input[name='pages_title[]']").map(function(){return $(this).val();}).get();
jQuery: you think a lot about 'QUERYing the DOM' for DOM elements and doing something.
AngularJS: THE model is the truth, and you always think from that ANGLE.
For example, when you get data from THE server which you intend to display in some format in the DOM, in jQuery, you need to '1. FIND' where in the DOM you want to place this data, the '2. UPDATE/APPEND' it there by creating a new node or just setting its innerHTML. Then when you want to update this view, you then '3. FIND' the location and '4. UPDATE'. This cycle of find and update all done within the same context of getting and formatting data from server is gone in AngularJS.
With AngularJS you have your model (JavaScript objects you are already used to) and the value of the model tells you about the model (obviously) and about the view, and an operation on the model automatically propagates to the view, so you don't have to think about it. You will find yourself in AngularJS no longer finding things in the DOM.
To put in another way, in jQuery, you need to think about CSS selectors, that is, where is the div
or td
that has a class or attribute, etc., so that I can get their HTML or color or value, but in AngularJS, you will find yourself thinking like this: what model am I dealing with, I will set the model's value to true. You are not bothering yourself of whether the view reflecting this value is a checked box or resides in a td
element (details you would have often needed to think about in jQuery).
And with DOM manipulation in AngularJS, you find yourself adding directives and filters, which you can think of as valid HTML extensions.
One more thing you will experience in AngularJS: in jQuery you call the jQuery functions a lot, in AngularJS, AngularJS will call your functions, so AngularJS will 'tell you how to do things', but the benefits are worth it, so learning AngularJS usually means learning what AngularJS wants or the way AngularJS requires that you present your functions and it will call it accordingly. This is one of the things that makes AngularJS a framework rather than a library.
I can't comment on the accepted answer, due to low reputation. However, I would like to add, this behavior is by design. The NodeManager is killing your container. It sounds like you are trying to use hadoop streaming which is running as a child process of the map-reduce task. The NodeManager monitors the entire process tree of the task and if it eats up more memory than the maximum set in mapreduce.map.memory.mb or mapreduce.reduce.memory.mb respectively, we would expect the Nodemanager to kill the task, otherwise your task is stealing memory belonging to other containers, which you don't want.
Compilation from jonearles' answer, http://kishantha.blogspot.com/2010/03/oracle-enterprise-manager-console.html and http://blog.flimatech.com/2011/07/17/changing-oracle-password-in-11g-using-alter-user-identified-by-values/ (Oracle 11g):
To stop this happening in the future do the following.
ALTER PROFILE DEFAULT LIMIT FAILED_LOGIN_ATTEMPTS UNLIMITED PASSWORD_LIFE_TIME UNLIMITED;
To reset users' status, run the query:
select
'alter user ' || su.name || ' identified by values'
|| ' ''' || spare4 || ';' || su.password || ''';'
from sys.user$ su
join dba_users du on ACCOUNT_STATUS like 'EXPIRED%' and su.name = du.username;
and execute some or all of the result set.
Try downloading and installing the zipped version rather than the .exe installer.
I have seen that happening several times, with broken links (symlinks that point to files that do not exist), grep tries to search on the target file, which does not exist (hence the correct and accurate error message).
I normally don't bother while doing sysadmin tasks over the console, but from within scripts I do look for text files with "find", and then grep each one:
find /etc -type f -exec grep -nHi -e "widehat" {} \;
Instead of:
grep -nRHi -e "widehat" /etc
I was also stuck on the same kind of problem and I followed the simple steps below.
Just get the exact url of the file to which you want to copy, for example:
http://www.test.com/test.txt (file to copy)
Then pass the exact absolute folder path with filename where you do want to write that file.
If you are on a Windows machine then
d:/xampp/htdocs/upload/test.txt
If you are on a Linux machine then
/var/www/html/upload/test.txt
You can get the document root with the PHP function $_SERVER['DOCUMENT_ROOT']
.
Try this:
<script>
var myWindow = window.open("ANYURL", "MyWindowName", "width=700,height=700");
this.window.close();
</script>
This worked for me in some cases in Google Chrome 50. It does not seem to work when put inside a javascript function, though.
This worked for me, no delayed expansion necessary:
@echo off
(
echo ^<html^>
echo ^<body^>
echo Hello
echo ^</body^>
echo ^</html^>
)
pause
It writes output like this:
<html>
<body>
Hello
</body>
</html>
Press any key to continue . . .
The problem I run into is I have an existing IIS machine. I then deploy a static React app to it. When you use router, the URL that displays is actually virtual, not real. If you hit F5 it goes to IIS, not index.js, and your return will be 404 file not found. How I resolved it was simple. I have a public folder in my react app. In that public folder I created the same folder name as the virtual routing. In this folder, I have an index.html with the following code:
<script>
{
localStorage.setItem("redirect", "/ansible/");
location.href = "/";
}
</script>
Now what this does is for this session, I'm adding the "routing" path I want it to go. Then inside my App.js I do this (Note ... is other code but too much to put here for a demo):
import React, { Component } from "react";
import { Route, Link } from "react-router-dom";
import { BrowserRouter as Router } from "react-router-dom";
import { Redirect } from 'react-router';
import Ansible from "./Development/Ansible";
import Code from "./Development/Code";
import Wood from "./WoodWorking";
import "./App.css";
class App extends Component {
render() {
const redirect = localStorage.getItem("redirect");
if(redirect) {
localStorage.removeItem("redirect");
}
return (
<Router>
{redirect ?<Redirect to={redirect}/> : ""}
<div className="App">
...
<Link to="/">
<li>Home</li>
</Link>
<Link to="/dev">
<li>Development</li>
</Link>
<Link to="/wood">
<li>Wood Working</li>
</Link>
...
<Route
path="/"
exact
render={(props) => (
<Home {...props} />
)}
/>
<Route
path="/dev"
render={(props) => (
<Code {...props} />
)}
/>
<Route
path="/wood"
render={(props) => (
<Wood {...props} />
)}
/>
<Route
path="/ansible/"
exact
render={(props) => (
<Ansible {...props} checked={this.state.checked} />
)}
/>
...
</Router>
);
}
}
export default App;
Actual usage: chizl.com
To find the minimum value of a list, you might just as well use min
:
x = min(float(s) for s in l) # min of a generator
Or, if you want the result as a string, rather than a float, use a key function:
x = min(l, key=float)
The problem is with your line
x=np.array ([x0*n])
Here you define x as a single-item array of -200.0. You could do this:
x=np.array ([x0,]*n)
or this:
x=np.zeros((n,)) + x0
Note: your imports are quite confused. You import numpy modules three times in the header, and then later import pylab (that already contains all numpy modules). If you want to go easy, with one single
from pylab import *
line in the top you could use all the modules you need.
Here is the function I use to prevent chrome and opera from showing the invalid input dialog even when using novalidate.
window.submittingForm = false;
$('input[novalidate]').bind('invalid', function(e) {
if(!window.submittingForm){
window.submittingForm = true;
$(e.target.form).submit();
setTimeout(function(){window.submittingForm = false;}, 100);
}
e.preventDefault();
return false;
});
Private functions cannot access the public variables using module pattern
Make sure your antivirus program isn't interfering and be sure to add an exclusion to your firewall.
Use sorted()
with a key
as follows -
>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
The lambda
returns the fourth element of each of the inner lists and the sorted
function uses that to sort those list. This assumes that int(elem)
will not fail for the list.
Or use itemgetter
(As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)
>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
For me was php version from mac instead of MAMP, PATH variable on .bash_profile was wrong. I just prepend the MAMP PHP bin folder to the $PATH env variable. For me was:
/Applications/mampstack-7.1.21-0/php/bin
In terminal run vim ~/.bash_profile
to open ~/.bash_profile
Type i to be able to edit the file, add the bin directory as PATH variable on the top to the file:
export PATH="/Applications/mampstack-7.1.21-0/php/bin/:$PATH"
Hit ESC
, Type :wq
, and hit Enter
source ~/.bash_profile
which php
, output should be the path to MAMP PHP install.System call fork() is used to create processes. It takes no arguments and returns a process ID. The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call. Therefore, we have to distinguish the parent from the child. This can be done by testing the returned value of fork()
Fork is a system call and you shouldnt think of it as a normal C function. When a fork() occurs you effectively create two new processes with their own address space.Variable that are initialized before the fork() call store the same values in both the address space. However values modified within the address space of either of the process remain unaffected in other process one of which is parent and the other is child. So if,
pid=fork();
If in the subsequent blocks of code you check the value of pid.Both processes run for the entire length of your code. So how do we distinguish them. Again Fork is a system call and here is difference.Inside the newly created child process pid will store 0 while in the parent process it would store a positive value.A negative value inside pid indicates a fork error.
When we test the value of pid to find whether it is equal to zero or greater than it we are effectively finding out whether we are in the child process or the parent process.
You can't really customise <select>
or <option>
much. The only way (cross-browser) would be to manually create a drop down with divs and css/js to create something similar.
I found an easy way to get the dictionary value, and its name as well! I'm not sure yet about reading it back, I'm going to continue to do research and see if I can figure that out.
Here is the code:
your_dict = {'one': 1, 'two': 2}
variables = [var for var in dir() if var[0:2] != "__" and var[-1:-2] != "__"]
file = open("your_file","w")
for var in variables:
if isinstance(locals()[var], dict):
file.write(str(var) + " = " + str(locals()[var]) + "\n")
file.close()
Only problem here is this will output every dictionary in your namespace to the file, maybe you can sort them out by values? locals()[var] == your_dict
for reference.
You can also remove if isinstance(locals()[var], dict):
to output EVERY variable in your namespace, regardless of type.
Your output looks exactly like your decleration your_dict = {'one': 1, 'two': 2}
.
Hopefully this gets you one step closer! I'll make an edit if I can figure out how to read them back into the namespace :)
---EDIT---
Got it! I've added a few variables (and variable types) for proof of concept. Here is what my "testfile.txt" looks like:
string_test = Hello World
integer_test = 42
your_dict = {'one': 1, 'two': 2}
And here is the code the processes it:
import ast
file = open("testfile.txt", "r")
data = file.readlines()
file.close()
for line in data:
var_name, var_val = line.split(" = ")
for possible_num_types in range(3): # Range is the == number of types we will try casting to
try:
var_val = int(var_val)
break
except (TypeError, ValueError):
try:
var_val = ast.literal_eval(var_val)
break
except (TypeError, ValueError, SyntaxError):
var_val = str(var_val).replace("\n","")
break
locals()[var_name] = var_val
print("string_test =", string_test, " : Type =", type(string_test))
print("integer_test =", integer_test, " : Type =", type(integer_test))
print("your_dict =", your_dict, " : Type =", type(your_dict))
This is what that outputs:
string_test = Hello World : Type = <class 'str'>
integer_test = 42 : Type = <class 'int'>
your_dict = {'two': 2, 'one': 1} : Type = <class 'dict'>
I really don't like how the casting here works, the try-except block is bulky and ugly. Even worse, you cannot accept just any type! You have to know what you are expecting to take in. This wouldn't be nearly as bad if you only cared about dictionaries, but I really wanted something a bit more universal.
If anybody knows how to better cast these input vars I would LOVE to hear about it!
Regardless, this should still get you there :D I hope I've helped out!
Use The Below code:
func filterContentForSearchText(searchText:NSString, scopes scope:NSString)
{
//var searchText = ""
var resultPredicate : NSPredicate = NSPredicate(format: "name contains[c]\(searchText)", nil)
//var recipes : NSArray = NSArray()
var searchResults = recipes.filteredArrayUsingPredicate(resultPredicate)
}
server
w/ hardcoded server_name
Best practice with nginx is to use a separate server
for a redirect like this (not shared with the server
of your main configuration), to hardcode everything, and not use regular expressions at all.
It may also be necessary to hardcode the domains if you're using HTTPS, because you have to know upfront which certificates you'll be providing.
server {
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}
server {
server_name www.example.org;
return 301 $scheme://example.org$request_uri;
}
server {
server_name example.com example.org;
# real configuration goes here
}
server_name
If you have a number of sites, and don't care for the most ultimate performance, but want every single one of them to have the same policy in regards to the www.
prefix, then you can use regular expressions. The best practice of using a separate server
would still stand.
Note that this solution gets tricky if you use https, as you must then have a single certificate to cover all of your domain names if you want this to work properly.
www
to www
w/ regex in a dedicated single server
for all sites:server {
server_name ~^(?!www\.)(?<domain>.+)$;
return 301 $scheme://www.$domain$request_uri;
}
www
to non-www
w/ regex in a dedicated single server
for all sites:server {
server_name ~^www\.(?<domain>.+)$;
return 301 $scheme://$domain$request_uri;
}
www
to non-www
w/ regex in a dedicated server
for some sites only:It may be necessary to restrict the regex to cover only a couple of domains, then you can use something like this to only match www.example.org
, www.example.com
and www.subdomain.example.net
:
server {
server_name ~^www\.(?<domain>(?:example\.org|example\.com|subdomain\.example\.net))$;
return 301 $scheme://$domain$request_uri;
}
You can test that the regex works as expected with pcretest
on your system, which is the exact same pcre
library that your nginx will be using for regular expressions:
% pcretest
PCRE version 8.35 2014-04-04
re> #^www\.(?<domain>(?:example\.org|example\.com|subdomain\.example\.net))$#
data> test
No match
data> www.example.org
0: www.example.org
1: example.org
data> www.test.example.org
No match
data> www.example.com
0: www.example.com
1: example.com
data> www.subdomain.example.net
0: www.subdomain.example.net
1: subdomain.example.net
data> subdomain.example.net
No match
data> www.subdomain.example.net.
No match
data>
Note that you don't have to worry about trailing dots or case, as nginx already takes care of it, as per nginx server name regex when "Host" header has a trailing dot.
if
within existing server
/ HTTPS:This final solution is generally not considered to be the best practice, however, it still works and does the job.
In fact, if you're using HTTPS, then this final solution may end up easier to maintain, as you wouldn't have to copy-paste a whole bunch of ssl directives between the different server
definitions, and could instead place the snippets only into the needed servers, making it easier to debug and maintain your sites.
www
to www
:if ($host ~ ^(?!www\.)(?<domain>.+)$) {
return 301 $scheme://www.$domain$request_uri;
}
www
to non-www
:if ($host ~ ^www\.(?<domain>.+)$) {
return 301 $scheme://$domain$request_uri;
}
If you want a little bit more performance, as well as consistency between multiple domains a single server
may use, it might still make sense to explicitly hardcode a single preferred domain:
if ($host != "example.com") {
return 301 $scheme://example.com$request_uri;
}
If you have an Instance of the EditText available at the point in your code where you want add whitespace, then this code below will work. There may be some things to consider, for example the code below may trigger any TextWatcher you have set to this EditText, idk for sure, just saying, but this will work when trying to append blank space like this: " ", hasn't worked.
messageInputBox.dispatchKeyEvent(new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_SPACE, 0, 0, 0, 0,
KeyEvent.KEYCODE_ENDCALL));
Thank you so much! <%Response.Buffer = False%> worked like a charm! My asp/HTML table that was returning a blank page at about 2700 records. The following debugging lines helped expose the buffering problem: I replace the Do While loop as follows and played with my limit numbers to see what was happening:
Replace
Do While not rs.EOF
'etc .... your block of code that writes the table rows
rs.moveNext
Loop
with
Do While reccount < 2500
if rs.EOF then recount = 2501
'etc .... your block of code that writes the table rows
rs.moveNext
Loop
response.write "recount = " & recount
raise or lower the 2500 and 2501 to see if it is a buffer problem. for my record set, I could see that the blank page return, blank table, was happening at about 2700 records, good luck to all and thank you again for solving this problem! Such a simple great solution!
Generally, labels and textboxes that appear in front of an image is best organized in a panel. When rendering, if labels need to be transparent to an image within the panel, you can switch to image as parent of labels in Form initiation like this:
var oldParent = panel1;
var newParent = pictureBox1;
foreach (var label in oldParent.Controls.OfType<Label>())
{
label.Location = newParent.PointToClient(label.Parent.PointToScreen(label.Location));
label.Parent = newParent;
label.BackColor = Color.Transparent;
}
Linked-list are especially useful when the collection is constantly growing & shrinking. For example, it's hard to imagine trying to implement a Queue (add to the end, remove from the front) using an array -- you'd be spending all your time shifting things down. On the other hand, it's trivial with a linked-list.
Chunking shouldn't always be the first port of call for this problem.
Is the file large due to repeated non-numeric data or unwanted columns?
If so, you can sometimes see massive memory savings by reading in columns as categories and selecting required columns via pd.read_csv usecols
parameter.
Does your workflow require slicing, manipulating, exporting?
If so, you can use dask.dataframe to slice, perform your calculations and export iteratively. Chunking is performed silently by dask, which also supports a subset of pandas API.
If all else fails, read line by line via chunks.
Chunk via pandas or via csv library as a last resort.
You can pass the container by reference in order to modify it in the function. What other answers haven’t addressed is that std::vector
does not have a push_front
member function. You can use the insert()
member function on vector
for O(n) insertion:
void do_something(int el, std::vector<int> &arr){
arr.insert(arr.begin(), el);
}
Or use std::deque
instead for amortised O(1) insertion:
void do_something(int el, std::deque<int> &arr){
arr.push_front(el);
}
We've had similar problem and it was not enough to only remove commit and force push to GitLab.
It was still available in GitLab interface using url:
https://gitlab.example.com/<group>/<project>/commit/<commit hash>
We've had to remove project from GitLab and recreate it to get rid of this commit in GitLab UI.
There is no simple command available to find out the largest files/directories on a Linux/UNIX/BSD filesystem. However, combination of following three commands (using pipes) you can easily find out list of largest files:
# du -a /var | sort -n -r | head -n 10
If you want more human readable output try:
$ cd /path/to/some/var
$ du -hsx * | sort -rh | head -10
Where,
The algorithm you are using, "AES", is a shorthand for "AES/ECB/NoPadding". What this means is that you are using the AES algorithm with 128-bit key size and block size, with the ECB mode of operation and no padding.
In other words: you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException
exception.
If you want to encrypt data in sizes that are not multiple of 16 bytes, you are either going to have to use some kind of padding, or a cipher-stream. For instance, you could use CBC mode (a mode of operation that effectively transforms a block cipher into a stream cipher) by specifying "AES/CBC/NoPadding" as the algorithm, or PKCS5 padding by specifying "AES/ECB/PKCS5", which will automatically add some bytes at the end of your data in a very specific format to make the size of the ciphertext multiple of 16 bytes, and in a way that the decryption algorithm will understand that it has to ignore some data.
In any case, I strongly suggest that you stop right now what you are doing and go study some very introductory material on cryptography. For instance, check Crypto I on Coursera. You should understand very well the implications of choosing one mode or another, what are their strengths and, most importantly, their weaknesses. Without this knowledge, it is very easy to build systems which are very easy to break.
Update: based on your comments on the question, don't ever encrypt passwords when storing them at a database!!!!! You should never, ever do this. You must HASH the passwords, properly salted, which is completely different from encrypting. Really, please, don't do what you are trying to do... By encrypting the passwords, they can be decrypted. What this means is that you, as the database manager and who knows the secret key, you will be able to read every password stored in your database. Either you knew this and are doing something very, very bad, or you didn't know this, and should get shocked and stop it.
You can just look for the value that corresponds with the key and then check if the input is equal to the key.
for key in PIX0:
NUM = input("Which standard has a resolution of %s " % PIX0[key])
if NUM == key:
Also, you will have to change the last line to fit in, so it will print the key instead of the value if you get the wrong answer.
print("I'm sorry but thats wrong. The correct answer was: %s." % key )
Also, I would recommend using str.format
for string formatting instead of the %
syntax.
Your full code should look like this (after adding in string formatting)
PIX0 = {"QVGA":"320x240", "VGA":"640x480", "SVGA":"800x600"}
for key in PIX0:
NUM = input("Which standard has a resolution of {}".format(PIX0[key]))
if NUM == key:
print ("Nice Job!")
count = count + 1
else:
print("I'm sorry but that's wrong. The correct answer was: {}.".format(key))
You can add a method in Float Class, I learnt this from stackoverflow:
class Float
def precision(p)
# Make sure the precision level is actually an integer and > 0
raise ArgumentError, "#{p} is an invalid precision level. Valid ranges are integers > 0." unless p.class == Fixnum or p < 0
# Special case for 0 precision so it returns a Fixnum and thus doesn't have a trailing .0
return self.round if p == 0
# Standard case
return (self * 10**p).round.to_f / 10**p
end
end
import pyautogui
import keyboard
import time
import os
import pyperclip
os.chdir("target directory")
# get the current directory
cwd=os.getcwd()
files=[]
for i in os.walk(cwd):
for j in i[2]:
files.append(os.path.abspath(j))
os.startfile("C:\Program Files (x86)\Adobe\Acrobat 11.0\Acrobat\Acrobat.exe")
time.sleep(1)
for i in files:
print(i)
pyperclip.copy(i)
keyboard.press('ctrl')
keyboard.press_and_release('o')
keyboard.release('ctrl')
time.sleep(1)
keyboard.press('ctrl')
keyboard.press_and_release('v')
keyboard.release('ctrl')
time.sleep(1)
keyboard.press_and_release('enter')
keyboard.press('ctrl')
keyboard.press_and_release('p')
keyboard.release('ctrl')
keyboard.press_and_release('enter')
time.sleep(3)
keyboard.press('ctrl')
keyboard.press_and_release('w')
keyboard.release('ctrl')
pyperclip.copy('')
BundleConfig
is nothing more than bundle configuration moved to separate file. It used to be part of app startup code (filters, bundles, routes used to be configured in one class)
To add this file, first you need to add the Microsoft.AspNet.Web.Optimization
nuget package to your web project:
Install-Package Microsoft.AspNet.Web.Optimization
Then under the App_Start folder create a new cs file called BundleConfig.cs
. Here is what I have in my mine (ASP.NET MVC 5, but it should work with MVC 4):
using System.Web;
using System.Web.Optimization;
namespace CodeRepository.Web
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
Then modify your Global.asax and add a call to RegisterBundles()
in Application_Start()
:
using System.Web.Optimization;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
A closely related question: How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app
On MacOS I also had problems trying to install fbprophet
which had gcc
as one of its dependencies.
After trying several steps as recommended by @Boris the command below from the Facebook Prophet project page worked for me in the end.
conda install -c conda-forge fbprophet
It installed all the needed dependencies for fbprophet
. Make sure you have anaconda installed.
There was made some changes to the select2 events names (I think on v. 4 and later) so the '-' is changed into this ':'.
See the next examples:
$('#select').on("select2:select", function(e) {
//Do stuff
});
You can check all the events at the 'select2' plugin site: select2 Events
You can call javascript functions from c# using Jering.Javascript.NodeJS, an open-source library by my organization:
string javascriptModule = @"
module.exports = (callback, x, y) => { // Module must export a function that takes a callback as its first parameter
var result = x + y; // Your javascript logic
callback(null /* If an error occurred, provide an error object or message */, result); // Call the callback when you're done.
}";
// Invoke javascript
int result = await StaticNodeJSService.InvokeFromStringAsync<int>(javascriptModule, args: new object[] { 3, 5 });
// result == 8
Assert.Equal(8, result);
The library supports invoking directly from .js files as well. Say you have file C:/My/Directory/exampleModule.js
containing:
module.exports = (callback, message) => callback(null, message);
You can invoke the exported function:
string result = await StaticNodeJSService.InvokeFromFileAsync<string>("C:/My/Directory/exampleModule.js", args: new[] { "test" });
// result == "test"
Assert.Equal("test", result);
UPDATE table1 SET col_a = 'newvalue'
Add a WHERE
condition if you want to only update some of the rows.
just like pure js do preventdefault : in class you should like this create a handler method :
handler(event) {
event.preventDefault();
console.log(event);
}
Rather than create 2 temporary dfs you can just pass these as params within a dict using the DataFrame constructor:
pd.DataFrame({'email':sf.index, 'list':sf.values})
There are lots of ways to construct a df, see the docs
Ok what you probably want will be provide to you by result of:
in CSS:
div { column-count: 2; }
in html:
<div> some text, bla bla bla </div>
In CSS you make div to split your paragraph on to column, you can make them 3, 4...
If you want to have many differend paragraf like that, then put id or class in your div:
Maybe, this approach is better, https://saucelabs.com/mobile, mobile testing in the cloud with selenium
I can show you how I used it
function GetDenierValue() {
var denierid = $("#productDenierid").val() == '' ? 0 : $("#productDenierid").val();
var param = { 'productDenierid': denierid };
$.ajax({
url: "/Admin/ProductComposition/GetDenierValue",
dataType: "json",
contentType: "application/json;charset=utf-8",
type: "POST",
data: JSON.stringify(param),
success: function (msg) {
if (msg != null) {
return msg.URL;
}
}
});
}