Here's how to do it using default ACLs, at least under Linux.
First, you might need to enable ACL support on your filesystem. If you are using ext4 then it is already enabled. Other filesystems (e.g., ext3) need to be mounted with the acl
option. In that case, add the option to your /etc/fstab
. For example, if the directory is located on your root filesystem:
/dev/mapper/qz-root / ext3 errors=remount-ro,acl 0 1
Then remount it:
mount -oremount /
Now, use the following command to set the default ACL:
setfacl -dm u::rwx,g::rwx,o::r /shared/directory
All new files in /shared/directory
should now get the desired permissions. Of course, it also depends on the application creating the file. For example, most files won't be executable by anyone from the start (depending on the mode argument to the open(2) or creat(2) call), just like when using umask. Some utilities like cp
, tar
, and rsync
will try to preserve the permissions of the source file(s) which will mask out your default ACL if the source file was not group-writable.
Hope this helps!
Just for sake of completeness (maybe someone else won't have to implement it from scratch):
We've implemented our own small library, as everyone else. It's supposed to make things easier, so that our developers don't have to reimplement it each time. It would be great if spring security would provide support of rbac out of the box, as this approach is much better than the default permission based one.
Have a look at Github (OSS, MIT license) to see if it suits your needs. It's basically only addressing the role <-> privileges mapping. The missing piece, you'll have to provide on your own is basically the user <-> roles mapping, e.g. by mapping groups (racf/ad groups) to roles (1:1) or by implementing an additional mapping. That one's different in each project, so it doesn't make sense to provide some implementation.
We've basically used this internally, so that we can start with rbac from the beginning. We can still replace it with some other implementation later on, if the application is growing, but it's important for us to get the setup right at the beginning.
If you don't use rbac, there's a good chance, that the permissions are scattered throughout the codebase and you'll have a hard time to extract/group those (into roles) later on. The generated graphs do also help to reason about it/restructure it later on.
My problem was the system virtualenv
version.
When I created an env with python3 venv everything worked. But when I used virtualenv (by default with python2.7) to create an env I receive those error messages.
In the virtualenv
created the pip version was 1.5.6
, but my system pip version was 10.0.1
Then I ran (outside any env):
pip install virtualenv --upgrade
It upgraded virtualenv
to version 16.0.0
and now my pip install
in the envs created with virtualenv
and python2.7
work flawlessly. Also, the pip
version inside the env is now 10.0.1
.
Before upgrade:
I'm not 100% on why (actually came here to search for the answer), but this also works, and doesn't require replacing all nan values.
import pandas as pd
import numpy as np
df = pd.DataFrame([["foo1"], ["foo2"], ["bar"], [np.nan]], columns=['a'])
newdf = df.loc[df['a'].str.contains('foo') == True]
Works with or without .loc
.
I have no idea why this works, as I understand it when you're indexing with brackets pandas evaluates whatever's inside the bracket as either True
or False
. I can't tell why making the phrase inside the brackets 'extra boolean' has any effect at all.
I use numpy.fromiter to invert a 8-greyscale bitmap, yet no signs of side-effects
import Image
import numpy as np
im = Image.load('foo.jpg')
im = im.convert('L')
arr = np.fromiter(iter(im.getdata()), np.uint8)
arr.resize(im.height, im.width)
arr ^= 0xFF # invert
inverted_im = Image.fromarray(arr, mode='L')
inverted_im.show()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
new Handler().postDelayed(new Runnable() {
public void run() {
/* Create an intent that will start the main activity. */
Intent mainIntent = new Intent(SplashScreen.this,
ConnectedActivity.class);
mainIntent.putExtra("id", "1");
//SplashScreen.this.startActivity(mainIntent);
startActivity(mainIntent);
/* Finish splash activity so user cant go back to it. */
SplashScreen.this.finish();
/* Apply our splash exit (fade out) and main
entry (fade in) animation transitions. */
overridePendingTransition(R.anim.mainfadein,R.anim.splashfadeout);
}
}, SPLASH_DISPLAY_TIME);
}
I found this is working perfectly
str = "count a character occurance"
str = str.replace(' ', '')
print (str)
print (len(str))
It's worth noting these terms have standardized, IEEE definitions, which can be searched at https://pascal.computer.org/.
abstraction
information hiding
encapsulation
Another option:
string strVal = "32.11"; // will return 33
// string strVal = "32.00" // returns 32
// string strVal = "32.98" // returns 33
string[] valStr = strVal.Split('.');
int32 leftSide = Convert.ToInt32(valStr[0]);
int32 rightSide = Convert.ToInt32(valStr[1]);
if (rightSide > 0)
leftSide = leftSide + 1;
return (leftSide);
var Book = {"Titles":[
{
"Book3" : "BULLETIN 3"
}
,
{
"Book1" : "BULLETIN 1"
}
,
{
"Book2" : "BULLETIN 2"
}
]}
var findbystr = function(str) {
var return_val;
Book.Titles.forEach(function(data){
if(typeof data[str] != 'undefined')
{
return_val = data[str];
}
}, str)
return return_val;
}
book = findbystr('Book1');
console.log(book);
Stream stream = new MemoryStream();
you can use MemoryStream
Reference: MemoryStream
The string.isalpha()
function will work for you.
Here's a solution that's part of the standard library:
from distutils.dir_util import copy_tree
copy_tree("/a/b/c", "/x/y/z")
See this similar question.
So to have a specific column come first, then the rest alphabetically, I'd propose this solution:
test[, c("myFirstColumn", sort(setdiff(names(test), "myFirstColumn")))]
This is just torazaburo's answer, updated to use a MouseEvent object.
function click(x, y)
{
var ev = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true,
'screenX': x,
'screenY': y
});
var el = document.elementFromPoint(x, y);
el.dispatchEvent(ev);
}
And if you neither want to use @Autowire nor injecting @Value you can simply do (with fallback included):
System.getProperty("spring.profiles.active", "unknown");
This will return any active profile (or fallback to 'unknown').
This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
headers);
JSONObject jsonObject = null;
try {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.exchange(
"https://url", HttpMethod.POST, entity,
String.class);
if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
try {
jsonObject = new JSONObject(responseEntity.getBody());
} catch (JSONException e) {
throw new RuntimeException("JSONException occurred");
}
}
} catch (final HttpClientErrorException httpClientErrorException) {
throw new ExternalCallBadRequestException();
} catch (HttpServerErrorException httpServerErrorException) {
throw new ExternalCallServerErrorException(httpServerErrorException);
} catch (Exception exception) {
throw new ExternalCallServerErrorException(exception);
}
ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.
Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.
On MySQL 5.5 I have in my.cnf
[mysqld]
init_connect='SET collation_connection = utf8_unicode_ci'
init_connect='SET NAMES utf8'
character-set-server=utf8
collation-server=utf8_unicode_ci
skip-character-set-client-handshake
Result is
mysql> show variables like "%character%";show variables like "%collation%";
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)
+----------------------+-----------------+
| Variable_name | Value |
+----------------------+-----------------+
| collation_connection | utf8_unicode_ci |
| collation_database | utf8_unicode_ci |
| collation_server | utf8_unicode_ci |
+----------------------+-----------------+
3 rows in set (0.00 sec)
Python Extension. From the Python Docs:
The solution chosen by the Perl developers was to use (?...) as the extension syntax. ? immediately after a parenthesis was a syntax error because the ? would have nothing to repeat, so this didn’t introduce any compatibility problems. The characters immediately after the ? indicate what extension is being used, so (?=foo) is one thing (a positive lookahead assertion) and (?:foo) is something else (a non-capturing group containing the subexpression foo).
Python supports several of Perl’s extensions and adds an extension syntax to Perl’s extension syntax.If the first character after the question mark is a P, you know that it’s an extension that’s specific to Python
In casual code I've created lists with millions of elements. I believe that Python's implementation of lists are only bound by the amount of memory on your system.
In addition, the list methods / functions should continue to work despite the size of the list.
If you care about performance, it might be worthwhile to look into a library such as NumPy.
If you're working under your feature and don't want to checkout back to master, you can run:
cd ./myrepo
git worktree add ../myrepo_master master
git worktree remove ../myrepo_master
It will create ../myrepo_master
directory with master
branch commits, where you can continue work
General ternary syntax:
value_true if <test> else value_false
Another way can be:
[value_false, value_true][<test>]
e.g:
count = [0,N+1][count==N]
This evaluates both branches before choosing one. To only evaluate the chosen branch:
[lambda: value_false, lambda: value_true][<test>]()
e.g.:
count = [lambda:0, lambda:N+1][count==N]()
You can use .on()
to bind a function to multiple events:
$('#element').on('keyup keypress blur change', function(e) {
// e.type is the type of event fired
});
Or just pass the function as the parameter to normal event functions:
var myFunction = function() {
...
}
$('#element')
.keyup(myFunction)
.keypress(myFunction)
.blur(myFunction)
.change(myFunction)
I think this should depend on the situation.Take the following container as an example:
# docker run -it -d ubuntu
91262536f7c9a3060641448120bda7af5ca812b0beb8f3c9fe72811a61db07fc
# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
91262536f7c9 ubuntu "/bin/bash" 5 seconds ago Up 4 seconds serene_goldstine
(1) Use "docker attach
" to attach the container:
Since "docker attach
" will not allocate a new tty, but reuse the original running tty, so if you run exit
command, it will cause the running container exit:
# docker attach 91262536f7c9
exit
exit
# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
91262536f7c9 ubuntu "/bin/bash" 39 minutes ago Exited (0) 3 seconds ago serene_goldstine
So unless you really want to make running container exit, you should use Ctrl+p + Ctrl+q.
(2) Use "docker exec
"
Since "docker exec
" will allocate a new tty, so I think you should use exit
instead of Ctrl+p + Ctrl+q.
The following is executing Ctrl+p + Ctrl+q to quit the container:
# docker exec -it 91262536f7c9 bash
root@91262536f7c9:/# ps -aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 18160 1908 ? Ss+ 04:03 0:00 /bin/bash
root 15 0.0 0.0 18164 1892 ? Ss 04:03 0:00 bash
root 28 0.0 0.0 15564 1148 ? R+ 04:03 0:00 ps -aux
root@91262536f7c9:/# echo $$
15
Then login container again, you will see the bash
process in preavious docker exec
command is still alive (PID is 15):
# docker exec -it 91262536f7c9 bash
root@91262536f7c9:/# ps -aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 18160 1908 ? Ss+ 04:03 0:00 /bin/bash
root 15 0.0 0.0 18164 1892 ? Ss+ 04:03 0:00 bash
root 29 0.0 0.0 18164 1888 ? Ss 04:04 0:00 bash
root 42 0.0 0.0 15564 1148 ? R+ 04:04 0:00 ps -aux
root@91262536f7c9:/# echo $$
29
Suposse you have
Class1
public class Class1 {
//Your class code above
}
Class2
public class Class2 {
}
and then you can use Class2 in different ways.
Class Field
public class Class1{
private Class2 class2 = new Class2();
}
Method field
public class Class1 {
public void loginAs(String username, String password)
{
Class2 class2 = new Class2();
class2.invokeSomeMethod();
//your actual code
}
}
Static methods from Class2 Imagine this is your class2.
public class Class2 {
public static void doSomething(){
}
}
from class1 you can use doSomething from Class2 whenever you want
public class Class1 {
public void loginAs(String username, String password)
{
Class2.doSomething();
//your actual code
}
}
In order to give a value in the table, we need to give a command:
php artisan make:migration create_users_table
and after then this command line
php artisan migrate
......
I found a better library
which transform the normal <select> <option>
to bootsrap button dropdown format.
I use method 3 because it's the most understandable for others (whenever you see an <a>
tag, you know it's a link) and when you are part of a team, you have to make simple things ;).
And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.
Here are two approaches you can read raw resources using Kotlin.
You can get it by getting the resource id. Or, you can use string identifier in which you can programmatically change the filename with incrementation.
Cheers mate
// R.raw.data_post
this.context.resources.openRawResource(R.raw.data_post)
this.context.resources.getIdentifier("data_post", "raw", this.context.packageName)
Just do: \d table_name
But I'm not sure what do you mean that the information about columns is not there.
For example:
# \d pg_class
Table "pg_catalog.pg_class"
Column | Type | Modifiers
-----------------+-----------+-----------
relname | name | not null
relnamespace | oid | not null
reltype | oid | not null
reloftype | oid | not null
relowner | oid | not null
relam | oid | not null
relfilenode | oid | not null
reltablespace | oid | not null
relpages | integer | not null
reltuples | real | not null
reltoastrelid | oid | not null
reltoastidxid | oid | not null
relhasindex | boolean | not null
relisshared | boolean | not null
relistemp | boolean | not null
relkind | "char" | not null
relnatts | smallint | not null
relchecks | smallint | not null
relhasoids | boolean | not null
relhaspkey | boolean | not null
relhasexclusion | boolean | not null
relhasrules | boolean | not null
relhastriggers | boolean | not null
relhassubclass | boolean | not null
relfrozenxid | xid | not null
relacl | aclitem[] |
reloptions | text[] |
Indexes:
"pg_class_oid_index" UNIQUE, btree (oid)
"pg_class_relname_nsp_index" UNIQUE, btree (relname, relnamespace)
It clearly shows which columns given index is on this table.
I had read some of the responses and they didn't seem to work for me. I am using Typescript 2.9.2, Angular 6 and trying to import JSON in a Jasmine Unit Test. This is what did the trick for me.
Add:
"resolveJsonModule": true,
To tsconfig.json
Import like:
import * as nameOfJson from 'path/to/file.json';
Stop ng test
, start again.
Reference: https://blogs.msdn.microsoft.com/typescript/2018/05/31/announcing-typescript-2-9/#json-imports
You miss the from
clause
SELECT * from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP
In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.
EDIT
It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.
var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>"
I submitted a pull request to update this.
Recommend to use LINQPad related nuget
package, then you can use exceptionInstance.Dump()
.
LINQPad.Runtime
LINQPad
Sample code:
using System;
using LINQPad;
namespace csharp_Dump_test
{
public class Program
{
public static void Main()
{
try
{
dosome();
}
catch (Exception ex)
{
ex.Dump();
}
}
private static void dosome()
{
throw new Exception("Unable.");
}
}
}
LinqPad nuget package is the most awesome tool for printing exception stack information. May it be helpful for you.
For the replacement portion, Python uses \1
the way sed and vi do, not $1
the way Perl, Java, and Javascript (amongst others) do. Furthermore, because \1
interpolates in regular strings as the character U+0001, you need to use a raw string or \escape it.
Python 3.2 (r32:88445, Jul 27 2011, 13:41:33)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> method = 'images/:id/huge'
>>> import re
>>> re.sub(':([a-z]+)', r'<span>\1</span>', method)
'images/<span>id</span>/huge'
>>>
On compileSdkVersoin 25, you could do this:
styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="android:textColorSecondary">@color/your_color</item>
</style>
When doing a getObject()
from the S3 API, per the docs the contents of your file are located in the Body
property, which you can see from your sample output. You should have code that looks something like the following
const aws = require('aws-sdk');
const s3 = new aws.S3(); // Pass in opts to S3 if necessary
var getParams = {
Bucket: 'abc', // your bucket name,
Key: 'abc.txt' // path to the object you're looking for
}
s3.getObject(getParams, function(err, data) {
// Handle any error and exit
if (err)
return err;
// No error happened
// Convert Body from a Buffer to a String
let objectData = data.Body.toString('utf-8'); // Use the encoding necessary
});
You may not need to create a new buffer from the data.Body
object but if you need you can use the sample above to achieve that.
Try using:
string ap = c.Request["AP"];
That reads from the cookies, form, query string or server variables.
Alternatively:
string ap = c.Request.Form["AP"];
to just read from the form's data.
Looks like anyone, even in this linked question, have proposed this solution, similar to the first part of the answer given by Nick Craver:
$("#dialog").dialog({
width: 480,
height: "auto",
buttons: [
{
id: "button-cancel",
text: "Cancel",
click: function() {
$(this).dialog("close");
}
},
{
id: "button-ok",
text: "Ok",
click: function() {
$(this).dialog("close");
}
}
]
});
Then, elsewhere, you should be able to use the API for the jquery UI button:
$("#button-ok").button("disable");
If you have the tables in a database, you can make a full outer join to get the differences. Example:
select t1.Field1, t1.Field2, t2.Field1, t2.Field2
from Table1 t1
full outer join Table2 t2 on t1.Field1 = t2.Field1 and t1.Field2 = t2.Field2
where t1.Field1 is null or t2.Field2 is null
All records that are identical are filtered out. There is data either in the first two or the last two fields, depending on what table the record comes from.
I needed to know how to get the actual error code number.
I inherited a project from someone else and I had to get the error codes from a .catch
clause that they had previously setup for Alamofire:
} .catch { (error) in
guard let error = error as? AFError else { return }
guard let statusCode = error.responseCode else { return }
print("Alamofire statusCode num is: ", statusCode)
}
Or if you need to get it from the response
value follow @mbryzinski's answer
Alamofire ... { (response) in
guard let error = response.result.error as? AFError else { return }
guard let statusCode = error.responseCode else { return }
print("Alamofire statusCode num is: ", statusCode)
})
On Xamarin.Android, It works for me and need change layout
var layout = recyclerView.GetLayoutManager() as GridLayoutManager;
layout.SpanCount = GetItemPerRow(Context);
recyclerView.SetAdapter(null);
recyclerView.SetAdapter(adapter); //reset
Amit-
I don't believe you can add a column anywhere but at the end of the table once the table is created. One solution might be to try this:
CREATE TABLE MY_TEMP_TABLE AS
SELECT *
FROM TABLE_TO_CHANGE;
Drop the table you want to add columns to:
DROP TABLE TABLE_TO_CHANGE;
It's at the point you could rebuild the existing table from scratch adding in the columns where you wish. Let's assume for this exercise you want to add the columns named "COL2 and COL3".
Now insert the data back into the new table:
INSERT INTO TABLE_TO_CHANGE (COL1, COL2, COL3, COL4)
SELECT COL1, 'Foo', 'Bar', COL4
FROM MY_TEMP_TABLE;
When the data is inserted into your "new-old" table, you can drop the temp table.
DROP TABLE MY_TEMP_TABLE;
This is often what I do when I want to add columns in a specific location. Obviously if this is a production on-line system, then it's probably not practical, but just one potential idea.
-CJ
What you need is a split user-defined function. With that, the solution looks like
With SplitValues As
(
Select T.Name, Z.Position, Z.Value
, Row_Number() Over ( Partition By T.Name Order By Z.Position ) As Num
From Table As T
Cross Apply dbo.udf_Split( T.Name, ' ' ) As Z
)
Select Name
, FirstName.Value
, Case When ThirdName Is Null Then SecondName Else ThirdName End As LastName
From SplitValues As FirstName
Left Join SplitValues As SecondName
On S2.Name = S1.Name
And S2.Num = 2
Left Join SplitValues As ThirdName
On S2.Name = S1.Name
And S2.Num = 3
Where FirstName.Num = 1
Here's a sample split function:
Create Function [dbo].[udf_Split]
(
@DelimitedList nvarchar(max)
, @Delimiter nvarchar(2) = ','
)
RETURNS TABLE
AS
RETURN
(
With CorrectedList As
(
Select Case When Left(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
+ @DelimitedList
+ Case When Right(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
As List
, Len(@Delimiter) As DelimiterLen
)
, Numbers As
(
Select TOP( Coalesce(DataLength(@DelimitedList)/2,0) ) Row_Number() Over ( Order By c1.object_id ) As Value
From sys.columns As c1
Cross Join sys.columns As c2
)
Select CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
, Substring (
CL.List
, CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen
, CharIndex(@Delimiter, CL.list, N.Value + 1)
- ( CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen )
) As Value
From CorrectedList As CL
Cross Join Numbers As N
Where N.Value <= DataLength(CL.List) / 2
And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter
)
You say "I am not using a forms to manipulate the data." But you are doing a POST. Therefore, you are, in fact, using a form, even if it's empty.
$.ajax's dataType tells jQuery what type the server will return, not what you are passing. POST can only pass a form. jQuery will convert data to key/value pairs and pass it as a query string. From the docs:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key i.e. {foo:["bar1", "bar2"]} becomes '&foo=bar1&foo=bar2'.
Therefore:
VSCode is a code editor, not a full IDE. Think of VSCode as a notepad on steroids with IntelliSense code completion, richer semantic code understanding of multiple languages, code refactoring, including navigation, keyboard support with customizable bindings, syntax highlighting, bracket matching, auto indentation, and snippets.
It's not meant to replace Visual Studio, but making "Visual Studio" part of the name in VSCode will of course confuse some people at first.
The answer will vary slightly depending on whether the application or applet is using AWT or Swing.
(Basically, classes that start with J
such as JApplet
and JFrame
are Swing, and Applet
and Frame
are AWT.)
In either case, the basic steps would be:
Image
object.Component
you want to draw the background in.Step 1. Loading the image can be either by using the Toolkit
class or by the ImageIO
class.
The Toolkit.createImage
method can be used to load an Image
from a location specified in a String
:
Image img = Toolkit.getDefaultToolkit().createImage("background.jpg");
Similarly, ImageIO
can be used:
Image img = ImageIO.read(new File("background.jpg");
Step 2. The painting method for the Component
that should get the background will need to be overridden and paint the Image
onto the component.
For AWT, the method to override is the paint
method, and use the drawImage
method of the Graphics
object that is handed into the paint
method:
public void paint(Graphics g)
{
// Draw the previously loaded image to Component.
g.drawImage(img, 0, 0, null);
// Draw sprites, and other things.
// ....
}
For Swing, the method to override is the paintComponent
method of the JComponent
, and draw the Image
as with what was done in AWT.
public void paintComponent(Graphics g)
{
// Draw the previously loaded image to Component.
g.drawImage(img, 0, 0, null);
// Draw sprites, and other things.
// ....
}
Simple Component Example
Here's a Panel
which loads an image file when instantiated, and draws that image on itself:
class BackgroundPanel extends Panel
{
// The Image to store the background image in.
Image img;
public BackgroundPanel()
{
// Loads the background image and stores in img object.
img = Toolkit.getDefaultToolkit().createImage("background.jpg");
}
public void paint(Graphics g)
{
// Draws the img to the BackgroundPanel.
g.drawImage(img, 0, 0, null);
}
}
For more information on painting:
Never fails, once I post the question to SO, I get some enlightening "aha" moment and figure it out. The solution:
.container {_x000D_
border: 1px solid #DDDDDD;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
position: relative;_x000D_
}_x000D_
.tag {_x000D_
float: left;_x000D_
position: absolute;_x000D_
left: 0px;_x000D_
top: 0px;_x000D_
z-index: 1000;_x000D_
background-color: #92AD40;_x000D_
padding: 5px;_x000D_
color: #FFFFFF;_x000D_
font-weight: bold;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="tag">Featured</div>_x000D_
<img src="http://www.placehold.it/200x200">_x000D_
</div>
_x000D_
The key is the container has to be positioned relative and the tag positioned absolute.
Using the and-or trick:
a = get_list()
return a and a[0] or None
I've created a github repo summing up this article basically: https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec
I'll try to explain as good as possible, hope I help some of you out there:
(1) app.js: Creation of authentication constants on app definition
var loginApp = angular.module('loginApp', ['ui.router', 'ui.bootstrap'])
/*Constants regarding user login defined here*/
.constant('USER_ROLES', {
all : '*',
admin : 'admin',
editor : 'editor',
guest : 'guest'
}).constant('AUTH_EVENTS', {
loginSuccess : 'auth-login-success',
loginFailed : 'auth-login-failed',
logoutSuccess : 'auth-logout-success',
sessionTimeout : 'auth-session-timeout',
notAuthenticated : 'auth-not-authenticated',
notAuthorized : 'auth-not-authorized'
})
(2) Auth Service: All following functions are implemented in auth.js service. The $http service is used to communicate with the server for the authentication procedures. Also contains functions on authorization, that is if the user is allowed to perform a certain action.
angular.module('loginApp')
.factory('Auth', [ '$http', '$rootScope', '$window', 'Session', 'AUTH_EVENTS',
function($http, $rootScope, $window, Session, AUTH_EVENTS) {
authService.login() = [...]
authService.isAuthenticated() = [...]
authService.isAuthorized() = [...]
authService.logout() = [...]
return authService;
} ]);
(3) Session: A singleton to keep user data. The implementation here depends on you.
angular.module('loginApp').service('Session', function($rootScope, USER_ROLES) {
this.create = function(user) {
this.user = user;
this.userRole = user.userRole;
};
this.destroy = function() {
this.user = null;
this.userRole = null;
};
return this;
});
(4) Parent controller: Consider this as the "main" function of your application, all controllers inherit from this controller, and it's the backbone of the authentication of this app.
<body ng-controller="ParentController">
[...]
</body>
(5) Access control: To deny access on certain routes 2 steps have to be implemented:
a) Add data of the roles allowed to access each route, on ui router's $stateProvider service as can be seen below (same can work for ngRoute).
.config(function ($stateProvider, USER_ROLES) {
$stateProvider.state('dashboard', {
url: '/dashboard',
templateUrl: 'dashboard/index.html',
data: {
authorizedRoles: [USER_ROLES.admin, USER_ROLES.editor]
}
});
})
b) On $rootScope.$on('$stateChangeStart') add the function to prevent state change if the user is not authorized.
$rootScope.$on('$stateChangeStart', function (event, next) {
var authorizedRoles = next.data.authorizedRoles;
if (!Auth.isAuthorized(authorizedRoles)) {
event.preventDefault();
if (Auth.isAuthenticated()) {
// user is not allowed
$rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
} else {
// user is not logged in
$rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
}
}
});
(6) Auth interceptor: This is implemented, but can't be checked on the scope of this code. After each $http request, this interceptor checks the status code, if one of the below is returned, then it broadcasts an event to force the user to log-in again.
angular.module('loginApp')
.factory('AuthInterceptor', [ '$rootScope', '$q', 'Session', 'AUTH_EVENTS',
function($rootScope, $q, Session, AUTH_EVENTS) {
return {
responseError : function(response) {
$rootScope.$broadcast({
401 : AUTH_EVENTS.notAuthenticated,
403 : AUTH_EVENTS.notAuthorized,
419 : AUTH_EVENTS.sessionTimeout,
440 : AUTH_EVENTS.sessionTimeout
}[response.status], response);
return $q.reject(response);
}
};
} ]);
P.S. A bug with the form data autofill as stated on the 1st article can be easily avoided by adding the directive that is included in directives.js.
P.S.2 This code can be easily tweaked by the user, to allow different routes to be seen, or display content that was not meant to be displayed. The logic MUST be implemented server-side, this is just a way to show things properly on your ng-app.
Yes it makes sense to use angular.js
along with require.js
wherein you can use require.js
for modularizing components.
There is a seed project which uses both angular.js and require.js
.
Using this simple function. Declare function
<?php
function dateDiff($firstDate,$secondDate){
$firstDate = strtotime($firstDate);
$secondDate = strtotime($secondDate);
$datediff = $firstDate - $secondDate;
$output = round($datediff / (60 * 60 * 24));
return $output;
}
?>
and call this function like this where you want
<?php
echo dateDiff("2018-01-01","2018-12-31");
// OR
$firstDate = "2018-01-01";
$secondDate = "2018-01-01";
echo dateDiff($firstDate,$secondDate);
?>
GET Request with JSON Query Param
package com.rest.jersey.jerseyclient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientGET {
public static void main(String[] args) {
try {
String BASE_URI="http://vaquarkhan.net:8080/khanWeb";
Client client = Client.create();
WebResource webResource = client.resource(BASE_URI);
ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
/*if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
*/
String output = webResource.path("/msg/sms").queryParam("search","{\"name\":\"vaquar\",\"surname\":\"khan\",\"ext\":\"2020\",\"age\":\"34\""}").get(String.class);
//String output = response.getEntity(String.class);
System.out.println("Output from Server .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Post Request :
package com.rest.jersey.jerseyclient;
import com.rest.jersey.dto.KhanDTOInput;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
public class JerseyClientPOST {
public static void main(String[] args) {
try {
KhanDTOInput khanDTOInput = new KhanDTOInput("vaquar", "khan", "20", "E", null, "2222", "8308511500");
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
// final HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(username, password);
// client.addFilter(authFilter);
// client.addFilter(new LoggingFilter());
//
WebResource webResource = client
.resource("http://vaquarkhan.net:12221/khanWeb/messages/sms/api/v1/userapi");
ClientResponse response = webResource.accept("application/json")
.type("application/json").put(ClientResponse.class, khanDTOInput);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code :" + response.getStatus());
}
String output = response.getEntity(String.class);
System.out.println("Server response .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Check if string contains specific words?
This means the string has to be resolved into words (see note below).
One way to do this and to specify the separators is using preg_split
(doc):
<?php
function contains_word($str, $word) {
// split string into words
// separators are substrings of at least one non-word character
$arr = preg_split('/\W+/', $str, NULL, PREG_SPLIT_NO_EMPTY);
// now the words can be examined each
foreach ($arr as $value) {
if ($value === $word) {
return true;
}
}
return false;
}
function test($str, $word) {
if (contains_word($str, $word)) {
echo "string '" . $str . "' contains word '" . $word . "'\n";
} else {
echo "string '" . $str . "' does not contain word '" . $word . "'\n" ;
}
}
$a = 'How are you?';
test($a, 'are');
test($a, 'ar');
test($a, 'hare');
?>
A run gives
$ php -f test.php
string 'How are you?' contains word 'are'
string 'How are you?' does not contain word 'ar'
string 'How are you?' does not contain word 'hare'
Note: Here we do not mean word for every sequence of symbols.
A practical definition of word is in the sense the PCRE regular expression engine, where words are substrings consisting of word characters only, being separated by non-word characters.
A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl " word ". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place (..)
Backup/Restore Mongodb with timing.
Backup:
sudo mongodump --db db_name --out /path_of_your_backup/`date +"%m-%d-%y"`
--db
argument for databse name
--out
argument for path of output
Restore:
sudo mongorestore --db db_name --drop /path_of_your_backup/01-01-19/db_name/
--drop
argument for drop databse before restore
Timing:
You can use crontab for timing backup:
sudo crontab -e
It opens with editor(e.g. nano)
3 3 * * * mongodump --out /path_of_your_backup/`date +"%m-%d-%y"`
backup every day at 03:03 AM
Depending on your MongoDB database sizes you may soon run out of disk space with too many backups. That's why it's also recommended to clean the old backups regularly or to compress them. For example, to delete all the backups older than 7 days you can use the following bash command:
3 1 * * * find /path_of_your_backup/ -mtime +7 -exec rm -rf {} \;
delete all the backups older than 7 days
Good Luck.
If you are using AJAX
jQuery
Request this is a must to apply. If not it will throw you 415
Error.
dataType: "json",
contentType:'application/json'
Here are some things that can fix this (in increasing order of difficulty):
Manually paste in
@IBOutlet weak var viewName: UIView!
// or
@IBAction func viewTapped(_ sender: Any) { }
and control drag to it. (Change type as needed.) Also see this.
Completely close Xcode and restart your project.
You can do this with iOS 7's text attachments, which are part of TextKit. Some sample code:
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"MyIcon.png"];
NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment];
NSMutableAttributedString *myString= [[NSMutableAttributedString alloc] initWithString:@"My label text"];
[myString appendAttributedString:attachmentString];
myLabel.attributedText = myString;
No, there's not really any way to control this as a web developer.
Small exceptions are that you can do some fake forcing of anti-aliasing by using Flash through sIFR, and some browsers won't anti-alias bitmap/pixel fonts (as they shouldn't, more info: Anti-Aliasing / Anti-Anti-Aliasing).
Also, as Daniel mentioned, it's ideal to be using em
units for all fonts, see The Incredible Em & Elastic Layouts with CSS for more information about this.
I have had only good experiences working with Meld. I use it when I have to do messy code merges between branches. It is simple to use and has a clean interface.
In Ubuntu, install is as simple as: sudo apt-get install meld
If your xml is written by java.lang.String
you can just using HttpClient
in this way
public void post() throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.baidu.com");
String xml = "<xml>xxxx</xml>";
HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
}
pay attention to the Exceptions.
BTW, the example is written by the httpclient version 4.x
right click on the project create a file with name .ignore, then you can see that file opened.
at the right top of the file you can see install plugins or else you can install using plugins(plugin name - .ignore).
Now when ever you give a right click on the file or project you can see the option call add to .ignore
Try Ctrl+Alt+U
Also check if the UML plugin is activated (settings -> plugin, settings can be opened by Ctrl+Alt+S
If you don't want to use numpy, you could use the list of lists concept. To create any 2D array, just use the following syntax:
mat = [[input() for i in range (col)] for j in range (row)]
and then enter the values you want.
A slight extension to the answer given, so, hopefully useful to the asker and anyone else looking.
You can also SELECT
the values you want to delete. But watch out for the Error 1093 - You can't specify the target table for update in FROM clause.
DELETE FROM
orders_products_history
WHERE
(branchID, action) IN (
SELECT
branchID,
action
FROM
(
SELECT
branchID,
action
FROM
orders_products_history
GROUP BY
branchID,
action
HAVING
COUNT(*) > 10000
) a
);
I wanted to delete all history records where the number of history records for a single action/branch exceed 10,000. And thanks to this question and chosen answer, I can.
Hope this is of use.
Richard.
In my case, I found out by using "mb_convert_encoding" that the previous encoding was iso-8859-1 (which is latin1) then I fixed my problem by using an sql query :
UPDATE myDB.myTable SET myColumn = CAST(CAST(CONVERT(myColumn USING latin1) AS binary) AS CHAR)
However, it is stated in the mysql documentations that conversion may be lossy if the column contains characters that are not in both character sets.
To send to both remote with one command, you can create a alias for it:
git config alias.pushall '!git push origin devel && git push github devel'
With this, when you use the command git pushall
, it will update both repositories.
In bash version 3 you can use the '=~' operator:
if [[ "$date" =~ ^[0-9]{8}$ ]]; then
echo "Valid date"
else
echo "Invalid date"
fi
Reference: http://tldp.org/LDP/abs/html/bashver3.html#REGEXMATCHREF
NOTE: The quoting in the matching operator within the double brackets, [[ ]], is no longer necessary as of Bash version 3.2
Just want to share here some helpful extensions for kotlin
fun BigDecimal.isZero() = compareTo(BigDecimal.ZERO) == 0
fun BigDecimal.isOne() = compareTo(BigDecimal.ONE) == 0
fun BigDecimal.isTen() = compareTo(BigDecimal.TEN) == 0
Swift 3.0 in
one view controller to secondviewcontroller go:
let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MsgViewController") as! MsgViewController
self.navigationController?.pushViewController(loginVC, animated: true)
2nd viewcontroller to 1stviewcontroller(back)for: back button on action event:-
self.navigationController?.popViewController(animated:true)
3rdviewcontroller to 1st viewcontroller jump for
self.navigationController?.popToRootViewController(animated:true)
and most important storyboard in navigation bar unclicked make sure than this back action perform
final Calendar newCalendar = Calendar.getInstance();
final DatePickerDialog StartTime = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
activitydate.setText(dateFormatter.format(newDate.getTime()));
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
btn_checkin.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
StartTime.show():
});
here's a really simple regex for that:
\W|_
and used as you need it (with a forward /
slash delimiter).
preg_replace("/\W|_/", '', $string);
Test it here with this great tool that explains what the regex is doing:
Here's my lazy approach but it works: wrap the CardView in a layout and set a padding/margin on the parent layout to mimic the divider, and force the normal divider to null
list_item.xml
<LinearLayout
android:id="@+id/entry_item_layout_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="<divider_size>" > // this is the divider
<CardView
android:layout_width="<width_size>"
android:layout_height="<height_size>">
...
</CardView>
</LinearLayout
list.xml
<RecyclerView
android:divider="@null"
android:layout_width="<width_size>"
android:layout_height="<height_size>"
...
/>
I will say It 's just shorthand syntax for get reference of html element during debugging time , normaly these kind of task will perform by these method
document.getElementById , document.getElementsByClassName , document.querySelector
so clicking on an html element and getting a reference variable ($0) in console is a huge time saving during the day
A good solution for me was to drop the rows with any null values:
Dataset<Row> filtered = df.filter(row => !row.anyNull);
In case one is interested in the other case, just call row.anyNull
.
(Spark 2.1.0 using Java API)
You can use either jQuery Autocomplete or ASP.NET AJAX Toolkit Autocomplete
If you want a more powerful text preprocessor than LESS, check out PPWizard:
http://dennisbareis.com/ppwizard.htm
Warning the website is truly hideous and there's a small learning curve, but it's perfect for building both CSS and HTML code via macros. I've never understood why more web coders don't use it.
I use WinForms and my way to use File.Exists(string path) is the next one:
public bool FileExists(string fileName)
{
var workingDirectory = Environment.CurrentDirectory;
var file = $"{workingDirectory}\{fileName}";
return File.Exists(file);
}
fileName must include the extension like myfile.txt
Try the RoundUp function:
Dim i As Double
i = Application.WorksheetFunction.RoundUp(Cells(1, 1).Value * Cells(1, 2).Value, 2)
please, be sure your connected to a ubuntu server, I Had the same problem but I was connected to other distro, check the AMI value in your details instance, it should be something like
AMI: ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1
hope it helps
There are some things to change in your code:
0x7634706d
: out = cv2.VideoWriter('output.mp4',0x7634706d , 20.0, (640,480))
I use a hack/workaround to avoid having to build the whole TF library myself (which saves both time (it's set up in 3 minutes), disk space, installing dev dependencies, and size of the resulting binary). It's officially unsupported, but works well if you just want to quickly jump in.
Install TF through pip (pip install tensorflow
or pip install tensorflow-gpu
). Then find its library _pywrap_tensorflow.so
(TF 0.* - 1.0) or _pywrap_tensorflow_internal.so
(TF 1.1+). In my case (Ubuntu) it's located at /usr/local/lib/python2.7/dist-packages/tensorflow/python/_pywrap_tensorflow.so
. Then create a symlink to this library called lib_pywrap_tensorflow.so
somewhere where your build system finds it (e.g. /usr/lib/local
). The prefix lib
is important! You can also give it another lib*.so
name - if you call it libtensorflow.so
, you may get better compatibility with other programs written to work with TF.
Then create a C++ project as you are used to (CMake, Make, Bazel, whatever you like).
And then you're ready to just link against this library to have TF available for your projects (and you also have to link against python2.7
libraries)! In CMake, you e.g. just add target_link_libraries(target _pywrap_tensorflow python2.7)
.
The C++ header files are located around this library, e.g. in /usr/local/lib/python2.7/dist-packages/tensorflow/include/
.
Once again: this way is officially unsupported and you may run in various issues. The library seems to be statically linked against e.g. protobuf, so you may run in odd link-time or run-time issues. But I am able to load a stored graph, restore the weights and run inference, which is IMO the most wanted functionality in C++.
I feel like reinventing the wheel...
public static T[] ConvertToArray<T>(this IEnumerable<T> enumerable)
{
if (enumerable == null)
throw new ArgumentNullException("enumerable");
return enumerable as T[] ?? enumerable.ToArray();
}
you can follow the below command to install using the wheel file at your local
pip install /users/arpansaini/Downloads/h5py-3.0.0-cp39-cp39-macosx_10_9_x86_64.whl
Random AirCoded example of testing "set equality" in jQuery:
$.fn.isEqual = function($otherSet) {
if (this === $otherSet) return true;
if (this.length != $otherSet.length) return false;
var ret = true;
this.each(function(idx) {
if (this !== $otherSet[idx]) {
ret = false; return false;
}
});
return ret;
};
var a=$('#start > div:last-child');
var b=$('#start > div.live')[0];
console.log($(b).isEqual(a));
This script helps you to switch over from a Parent window to a Child window and back cntrl to Parent window
String parentWindow = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
for(String windowHandle : handles)
{
if(!windowHandle.equals(parentWindow))
{
driver.switchTo().window(windowHandle);
<!--Perform your operation here for new window-->
driver.close(); //closing child window
driver.switchTo().window(parentWindow); //cntrl to parent window
}
}
You can use the ??
operator to set the default value but first you must set the Nullable
property to true
in your dbml file in the required field (xx.Online
)
var hht = from x in db.HandheldAssets
join a in db.HandheldDevInfos on x.AssetID equals a.DevName into DevInfo
from aa in DevInfo.DefaultIfEmpty()
select new
{
AssetID = x.AssetID,
Status = xx.Online ?? false
};
You are looking for continue.
If you have access to the delegate method you can do this:
[20] pry(main)> class Foo
[20] pry(main)* def self.bar
[20] pry(main)* "foo bar"
[20] pry(main)* end
[20] pry(main)* delegate :bar, to: 'self.class'
[20] pry(main)* end
=> [:bar]
[21] pry(main)> Foo.new.bar
=> "foo bar"
[22] pry(main)> Foo.bar
=> "foo bar"
Alternatively, and probably cleaner if you have more then a method or two you want to delegate to class & instance:
[1] pry(main)> class Foo
[1] pry(main)* module AvailableToClassAndInstance
[1] pry(main)* def bar
[1] pry(main)* "foo bar"
[1] pry(main)* end
[1] pry(main)* end
[1] pry(main)* include AvailableToClassAndInstance
[1] pry(main)* extend AvailableToClassAndInstance
[1] pry(main)* end
=> Foo
[2] pry(main)> Foo.new.bar
=> "foo bar"
[3] pry(main)> Foo.bar
=> "foo bar"
A word of caution:
Don't just randomly delegate
everything that doesn't change state to class and instance because you'll start running into strange name clash issues. Do this sparingly and only after you checked nothing else is squashed.
From now you can also :
Action<int> action = (o) => Thread.Sleep(o);
int param = 10;
await new TaskFactory().StartNew(action, param)
driver.get()
: It's used to go to the particular website , But it doesn't maintain the browser History and cookies so , we can't use forward and backward button , if we click on that , page will not get schedule
driver.navigate()
: it's used to go to the particular website , but it maintains the browser history and cookies, so we can use forward and backward button to navigate between the pages during the coding of Testcase
Add to AndroidManifest.xml:
android:name="android.support.multidex.MultiDexApplication"
OR
MultiDex.install(this);
in your custom Application's attachBaseContext method
or your custom Application extend MultiDexApplication
add multiDexEnabled = true in your build.gradle
defaultConfig {
multiDexEnabled true
}
dependencies {
compile 'com.android.support:multidex:1.0.0'
}
}
2 options I know of.
These wont give you C# though.
I do get the same information while debugging. Though not while I am checking the stacktrace. Most probably you would have used the optimization flag I think. Check this link - something related.
Try compiling with -g3
remove any optimization flag.
Then it might work.
HTH!
You can also do the following:
var i = 0;
foreach (var itemA in listA)
{
Console.WriteLine(itemA + listB[i++]);
}
Note: the length of
listA
must be the same withlistB
.
/<\/?[^>]*>/.test(str)
Only detect whether it contains html tags, may be a xml
Use the :w
command with a filename:
:w other_filename
You are using an adjacent sibling selector (+
) when the elements are not siblings. The label is the parent of the input, not it's sibling.
CSS has no way to select an element based on it's descendents (nor anything that follows it).
You'll need to look to JavaScript to solve this.
Alternatively, rearrange your markup:
<input id="foo"><label for="foo">…</label>
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
It depends on the behaviour of your "team" object. If it behaves just like a collection, it might be OK to represent it first with a plain List. Then you might start to notice that you keep duplicating code that iterates on the list; at this point you have the option of creating a FootballTeam object that wraps the list of players. The FootballTeam class becomes the home for all the code that iterates on the list of players.
It makes my code needlessly verbose. I must now call my_team.Players.Count instead of just my_team.Count. Thankfully, with C# I can define indexers to make indexing transparent, and forward all the methods of the internal List... But that's a lot of code! What do I get for all that work?
Encapsulation. Your clients need not know what goes on inside of FootballTeam. For all your clients know, it might be implemented by looking the list of players up in a database. They don't need to know, and this improves your design.
It just plain doesn't make any sense. A football team doesn't "have" a list of players. It is the list of players. You don't say "John McFootballer has joined SomeTeam's players". You say "John has joined SomeTeam". You don't add a letter to "a string's characters", you add a letter to a string. You don't add a book to a library's books, you add a book to a library.
Exactly :) you will say footballTeam.Add(john), not footballTeam.List.Add(john). The internal list will not be visible.
Try this:
$NameRegex = "chalmw-dm"
$NameR = "$($NameRegex)*"
Get-ADComputer -Filter {name -like $NameR -and Enabled -eq $True}
all you need is to tie the group to a different item in your model
@Html.RadioButtonFor(x => x.Field1, "Milk")
@Html.RadioButtonFor(x => x.Field1, "Butter")
@Html.RadioButtonFor(x => x.Field2, "Water")
@Html.RadioButtonFor(x => x.Field2, "Beer")
"parser": "babel-eslint"
helped me to fix the issue
{
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true,
"modules": true,
"experimentalObjectRestSpread": true
}
},
"plugins": [
"react"
],
"extends": ["eslint:recommended", "plugin:react/recommended"],
"rules": {
"comma-dangle": 0,
"react/jsx-uses-vars": 1,
"react/display-name": 1,
"no-unused-vars": "warn",
"no-console": 1,
"no-unexpected-multiline": "warn"
},
"settings": {
"react": {
"pragma": "React",
"version": "15.6.1"
}
}
}
Here is an O(n)
and in place alghoritm. It uses <
operator for the elements of the strings. It's not mine of course. I took it from here (The site is in polish. I stumbled upon it once in the past and I couldn't find something like that now in English, so I show what I have :)).
bool equiv_cyc(const string &u, const string &v)
{
int n = u.length(), i = -1, j = -1, k;
if (n != v.length()) return false;
while( i<n-1 && j<n-1 )
{
k = 1;
while(k<=n && u[(i+k)%n]==v[(j+k)%n]) k++;
if (k>n) return true;
if (u[(i+k)%n] > v[(j+k)%n]) i += k; else j += k;
}
return false;
}
You can also try this one.
override fun registerWith( registry: PluginRegistry) {
GeneratedPluginRegistrant.registerWith(registry as FlutterEngine)
//registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")
}
I think this one is far better solution than creating a new class.
If you're trying to install tensorflow in anaconda and it isn't working, then you may need to downgrade python version because only 3.6.x
is currently supported while anaconda has the latest version.
check python version: python --version
if version > 3.6.x
then follow step 3, otherwise stop, the problem may be somewhere else
conda search python
conda install python=3.6.6
Check version again: python --version
If version is correct, install tensorflow (step 7)
pip install tensorflow
Read these:
These articles will help you understand how to pass data between two activities in Android.
Prerequisites :
install antiword : sudo apt-get install antiword
install docx : pip install docx
from subprocess import Popen, PIPE
from docx import opendocx, getdocumenttext
from cStringIO import StringIO
def document_to_text(filename, file_path):
cmd = ['antiword', file_path]
p = Popen(cmd, stdout=PIPE)
stdout, stderr = p.communicate()
return stdout.decode('ascii', 'ignore')
print document_to_text('your_file_name','your_file_path')
Notice – New versions of python-docx removed this function. Make sure to pip install docx and not the new python-docx
pandas provides high level data manipulation tools built on top of NumPy. NumPy by itself is a fairly low-level tool, similar to MATLAB. pandas on the other hand provides rich time series functionality, data alignment, NA-friendly statistics, groupby, merge and join methods, and lots of other conveniences. It has become very popular in recent years in financial applications. I will have a chapter dedicated to financial data analysis using pandas in my upcoming book.
You didn't provide many details, but you could try something like this:
# conn is an ODBC connection to the DB
dbCursor = conn.cursor()
sql = ('select field1, field2 from table')
dbCursor = conn.cursor()
dbCursor.execute(sql)
for row in dbCursor:
# Now you should be able to access the fields as properties of "row"
myVar1 = row.field1
myVar2 = row.field2
conn.close()
All above answers perfectly gives the solution to center the form using Bootstrap 4
. However, if someone wants to use out of the box Bootstrap 4
css classes without help of any additional styles and also not wanting to use flex
, we can do like this.
A sample form
HTML
<div class="container-fluid h-100 bg-light text-dark">
<div class="row justify-content-center align-items-center">
<h1>Form</h1>
</div>
<hr/>
<div class="row justify-content-center align-items-center h-100">
<div class="col col-sm-6 col-md-6 col-lg-4 col-xl-3">
<form action="">
<div class="form-group">
<select class="form-control">
<option>Option 1</option>
<option>Option 2</option>
</select>
</div>
<div class="form-group">
<input type="text" class="form-control" />
</div>
<div class="form-group text-center">
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="optradio">Option 1
</label>
</div>
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="optradio">Option 2
</label>
</div>
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="optradio" disabled>Option 3
</label>
</div>
</div>
<div class="form-group">
<div class="container">
<div class="row">
<div class="col"><button class="col-6 btn btn-secondary btn-sm float-left">Reset</button></div>
<div class="col"><button class="col-6 btn btn-primary btn-sm float-right">Submit</button></div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
Link to CodePen
https://codepen.io/anjanasilva/pen/WgLaGZ
I hope this helps someone. Thank you.
Uncomment the line extension=php_mysql.dll
in your "php.ini" file and restart Apache.
Additionally, "libmysql.dll" file must be available to Apache, i.e., it must be either in available in Windows systems PATH or in Apache working directory.
See more about installing MySQL extension in manual.
P.S. I would advise to consider MySQL extension as deprecated and to use MySQLi or even PDO for working with databases (I prefer PDO).
No, the dataType
option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify
and set the processData
option to false
.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON
object, and although jQuery has .parseJSON
, it has no stringifier included; you'll need another polyfill library.
Use the insort function of the bisect module:
import bisect
a = [1, 2, 4, 5]
bisect.insort(a, 3)
print(a)
Output
[1, 2, 3, 4, 5]
One simple thing that actually worked for me in Jupyter Notebook, was using double backslash instead of a single backslash in the pytesseract.pytesseract.tesseract_cmd path:
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe'
The for-each loop was introduced in Java 1.5 and is used with collections (and to be pedantic, arrays, and anything implementing the Iterable<E>
interface ... which the article notes):
http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html
Include using namespace System.Linq
List<string> stringList = line.Split(',').ToList();
you can make use of it with ease for iterating through each item.
foreach(string str in stringList)
{
}
String.Split()
returns an array, hence convert it to a list using ToList()
You have a lot of type-mismatches in your code such as trying to put an int
value where BigDecimal
is required. The corrected version of your code:
public class Payment
{
BigDecimal itemCost = BigDecimal.ZERO;
BigDecimal totalCost = BigDecimal.ZERO;
public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
{
itemCost = itemPrice.multiply(new BigDecimal(itemQuantity));
totalCost = totalCost.add(itemCost);
return totalCost;
}
}
using (FileStream fs = File.OpenRead(binarySourceFile.Path))
using (BinaryReader reader = new BinaryReader(fs))
{
// Read in all pairs.
while (reader.BaseStream.Position != reader.BaseStream.Length)
{
Item item = new Item();
item.UniqueId = reader.ReadString();
item.StringUnique = reader.ReadString();
result.Add(item);
}
}
return result;
I didn't like that the map would load only after the hidden div had become visible. In a carousel, for example, that doesn't really work.
This my solution is to add class to the hidden element to unhide it and hide it with position absolute instead, then render the map, and remove the class after map load.
Tested in Bootstrap Carousel.
HTML
<div class="item loading"><div id="map-canvas"></div></div>
CSS
.loading { display: block; position: absolute; }
JS
$(document).ready(function(){
// render map //
google.maps.event.addListenerOnce(map, 'idle', function(){
$('.loading').removeClass('loading');
});
}
Get requests should not have content-type because they do not have request entity (that is, a body)
If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):
function hasDuplicates(array) {
return (new Set(array)).size !== array.length;
}
If you only need string values in the array, the following will work:
function hasDuplicates(array) {
var valuesSoFar = Object.create(null);
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (value in valuesSoFar) {
return true;
}
valuesSoFar[value] = true;
}
return false;
}
We use a "hash table" valuesSoFar
whose keys are the values we've seen in the array so far. We do a lookup using in
to see if that value has been spotted already; if so, we bail out of the loop and return true
.
If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).
function hasDuplicates(array) {
var valuesSoFar = [];
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (valuesSoFar.indexOf(value) !== -1) {
return true;
}
valuesSoFar.push(value);
}
return false;
}
The difference is simply that we use an array instead of a hash table for valuesSoFar
, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of in
, instead getting an O(n) lookup time of indexOf
.
x.times do |i|
something(i+1)
end
There are a lot of things to consider when validating a phone number if you really think about it. (especially international) so using a package is better than the accepted answer by far, and if you want something simple like a regex I would suggest using something better than what @SlateEntropy suggested. (something like A comprehensive regex for phone number validation)
Try to run below example in order to feel how the magical variables work.
@echo off
SETLOCAL EnableDelayedExpansion
echo Full path and filename: %~f0
echo Drive: %~d0
echo Path: %~p0
echo Drive and path: %~dp0
echo Filename without extension: %~n0
echo Filename with extension: %~nx0
echo Extension: %~x0
echo date time : %~t0
echo file size: %~z0
ENDLOCAL
The related rules are following.
%~I - expands %I removing any surrounding quotes ("")
%~fI - expands %I to a fully qualified path name
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only
%~nI - expands %I to a file name only
%~xI - expands %I to a file extension only
%~sI - expanded path contains short names only
%~aI - expands %I to file attributes of file
%~tI - expands %I to date/time of file
%~zI - expands %I to size of file
%~$PATH:I - searches the directories listed in the PATH
environment variable and expands %I to the
fully qualified name of the first one found.
If the environment variable name is not
defined or the file is not found by the
search, then this modifier expands to the
empty string
Remove all the properties with null and undefined
let obj = {
"id": 1,
"firstName": null,
"lastName": null,
"address": undefined,
"role": "customer",
"photo": "fb79fd5d-06c9-4097-8fdc-6cebf73fab26/fc8efe82-2af4-4c81-bde7-8d2f9dd7994a.jpg",
"location": null,
"idNumber": null,
};
let result = Object.entries(obj).reduce((a,[k,v]) => (v == null ? a : (a[k]=v, a)), {});
console.log(result)
_x000D_
If you want to do it from the command line and not built into the script itself, use:
.\myscript.ps1 | Out-File c:\output.csv
var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];_x000D_
var data = arrofobject.map(arrofobject => arrofobject);_x000D_
console.log(data)
_x000D_
for more details please look at jQuery.map()
You can use this command:
start /min iexplore http://www.google.com
With the use of /min, it will hit on the URL without opening in the browser.
You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :
BEGIN TRANSACTION
update A
set A.ORG_NAME = @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
COMMIT
An abstract class is like the normal class it contains variables it contains protected variables functions it contains constructor only one thing is different it contains abstract method.
The abstract method means an empty method without definition so only one difference in abstract class we can not create an object of abstract class
Abstract must contains the abstract method and those methods must be defined in its inheriting class.
You are trying to read the set value before Angular is done assigning.
Demo:
var testController = function ($scope, $timeout) {
console.log('test');
$timeout(function(){
console.log($scope.testInput);
},1000);
}
Ideally you should use $watch
as suggested by @Beterraba to get rid of the timer:
var testController = function ($scope) {
console.log('test');
$scope.$watch("testInput", function(){
console.log($scope.testInput);
});
}
A great way of handling this is with regular expressions.
string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");
This will replace any of the 3 legal types of newline with the html tag.
Try this: Adding users to MySQL
You need grant privileges to the user if you want external acess to database(ie. web pages).
The simplest thing to do could be to use dynamics, i.e. you define the simple methods like in Yuval Peled answer:
void Test(WebControl c)
{
...
}
void Test(ComboBox c)
{
...
}
Then you cannot call directly Test(obj), because overload resolution is done at compile time. You have to assign your object to a dynamic and then call the Test method:
dynamic dynObj = obj;
Test(dynObj);
I was trying to install it in kubuntu 18.04, and i was already sure that i had java installed, I confirmed by trying
java -version
I got the output like that
java version "1.8.0_91"
Java(TM) SE Runtime Environment (build 1.8.0_91-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)
Since I already know that my java PATH variables are defined in /etc/environment file, I added that file to the top of /etc/init.d/jenkins file
source /etc/environment
you can even remove the PATH from /etc/init.d/jenkins file, since it's already defined in /etc/environment
after that, i restarted my jenkins server,and it seemed to start working fine from localhost:8080
You can use bubbling in your favor:
$('.foobar').on('click', function(e) {
// do your thing.
}).on('click', 'div', function(e) {
// clicked on descendant div
e.stopPropagation();
});
Personally, I like setting the options directly with an assignment statement as it is easy to find via tab completion thanks to iPython. I find it hard to remember what the exact option names are, so this method works for me.
For instance, all I have to remember is that it begins with pd.options
pd.options.<TAB>
Most of the options are available under display
pd.options.display.<TAB>
From here, I usually output what the current value is like this:
pd.options.display.max_rows
60
I then set it to what I want it to be:
pd.options.display.max_rows = 100
Also, you should be aware of the context manager for options, which temporarily sets the options inside of a block of code. Pass in the option name as a string followed by the value you want it to be. You may pass in any number of options in the same line:
with pd.option_context('display.max_rows', 100, 'display.max_columns', 10):
some pandas stuff
You can also reset an option back to its default value like this:
pd.reset_option('display.max_rows')
And reset all of them back:
pd.reset_option('all')
It is still perfectly good to set options via pd.set_option
. I just find using the attributes directly is easier and there is less need for get_option
and set_option
.
There are multiple ways which can solve the problem of extending a constructor function with a prototype in Javascript. Which of these methods is the 'best' solution is opinion based. However, here are two frequently used methods in order to extend a constructor's function prototype.
class Monster {_x000D_
constructor(health) {_x000D_
this.health = health_x000D_
}_x000D_
_x000D_
growl () {_x000D_
console.log("Grr!");_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
class Monkey extends Monster {_x000D_
constructor (health) {_x000D_
super(health) // call super to execute the constructor function of Monster _x000D_
this.bananaCount = 5;_x000D_
}_x000D_
}_x000D_
_x000D_
const monkey = new Monkey(50);_x000D_
_x000D_
console.log(typeof Monster);_x000D_
console.log(monkey);
_x000D_
The above approach of using ES 2015
classes is nothing more than syntactic sugar over the prototypal inheritance pattern in javascript. Here the first log where we evaluate typeof Monster
we can observe that this is function. This is because classes are just constructor functions under the hood. Nonetheless you may like this way of implementing prototypal inheritance and definitively should learn it. It is used in major frameworks such as ReactJS
and Angular2+
.
Object.create()
:function makeMonkey (bananaCount) {_x000D_
_x000D_
// here we define the prototype_x000D_
const Monster = {_x000D_
health: 100,_x000D_
growl: function() {_x000D_
console.log("Grr!");}_x000D_
}_x000D_
_x000D_
const monkey = Object.create(Monster);_x000D_
monkey.bananaCount = bananaCount;_x000D_
_x000D_
return monkey;_x000D_
}_x000D_
_x000D_
_x000D_
const chimp = makeMonkey(30);_x000D_
_x000D_
chimp.growl();_x000D_
console.log(chimp.bananaCount);
_x000D_
This method uses the Object.create()
method which takes an object which will be the prototype of the newly created object it returns. Therefore we first create the prototype object in this function and then call Object.create()
which returns an empty object with the __proto__
property set to the Monster object. After this we can initialize all the properties of the object, in this example we assign the bananacount to the newly created object.
Use this:
document.getElementById(target).value = newVal.replace(/[^0-9.]/g, '');
You need to get the position of the first underscore (using INSTR) and then get the part of the string from 1st charecter to (pos-1) using substr.
1 select 'ABC_blahblahblah' test_string,
2 instr('ABC_blahblahblah','_',1,1) position_underscore,
3 substr('ABC_blahblahblah',1,instr('ABC_blahblahblah','_',1,1)-1) result
4* from dual
SQL> /
TEST_STRING POSITION_UNDERSCORE RES
---------------- ------------------ ---
ABC_blahblahblah 4 ABC
for(var i = 0; i < BoardMessages.length;i++){
(function(j){
console.log("Loading message %d".green, j);
htmlMessageboardString += MessageToHTMLString(BoardMessages[j]);
})(i);
}
That should work; however, you should never create a function in a loop. Therefore,
for(var i = 0; i < BoardMessages.length;i++){
composeMessage(BoardMessages[i]);
}
function composeMessage(message){
console.log("Loading message %d".green, message);
htmlMessageboardString += MessageToHTMLString(message);
}
I want to change the select element's selected option's both value & textContent (what we see) to 'Mango'.
Simplest code that worked is below:
var newValue1 = 'Mango'
var selectElement = document.getElementById('myselectid');
selectElement.options[selectElement.selectedIndex].value = newValue1;
selectElement.options[selectElement.selectedIndex].textContent = newValue1;
Hope that helps someone. Best of luck.
Up vote if this helped you.
Just wondering why you are using 2 directives?
It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.
Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).
It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.
Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.
Change
mAdapter = new RecordingsListAdapter(this, recordings);
to
mAdapter = new RecordingsListAdapter(getActivity(), recordings);
and also make sure that recordings!=null
at mAdapter = new RecordingsListAdapter(this, recordings);
You can also use unzip to iterate through the columns
for col in zip(*array):
some_function(col)
Use REN
Command
Ren
is for rename
ren ( where the file is located ) ( the new name )
example
ren C:\Users\&username%\Desktop\aaa.txt bbb.txt
it will change aaa.txt to bbb.txt
Your code will be :
ren (file located)AAA_a001.jpg a001.AAA.jpg
ren (file located)BBB_a002.jpg a002.BBB.jpg
ren (file located)CCC_a003.jpg a003.CCC.jpg
and so on
IT WILL NOT WORK IF THERE IS SPACES!
Hope it helps :D
I looked for a solution to this problem, and came across the present page. I implemented the above solution:
$("#testdiv",opener.document) //doesn't work
But it doesn't work. Maybe it did work in previous jQuery versions, but it doesn't seem to work now.
I found this working solution on another stackoverflow page: how to access parent window object using jquery?
From which I got this working solution:
window.opener.$("#testdiv") //This works.
There are overloads of ActionLink which take a fragment parameter. Passing "section12" as your fragment will get you the behavior you're after.
For example, calling LinkExtensions.ActionLink Method (HtmlHelper, String, String, String, String, String, String, Object, Object):
<%= Html.ActionLink("Link Text", "Action", "Controller", null, null, "section12-the-anchor", new { categoryid = "blah"}, null) %>
If you are already using Apache Commons Lang, the RandomUtils
makes this a one-liner:
byte[] randomBytes = RandomUtils.nextBytes(20);
Note: this does not produce cryptographically-secure bytes.
You can convert all elements of id to str
using apply
df.id.apply(str)
0 123
1 512
2 zhub1
3 12354.3
4 129
5 753
6 295
7 610
Edit by OP:
I think the issue was related to the Python version (2.7.), this worked:
df['id'].astype(basestring)
0 123
1 512
2 zhub1
3 12354.3
4 129
5 753
6 295
7 610
Name: id, dtype: object
If You Have Multiple li
elements inside an li
element then this will definitely help you, and i have checked it and it works....
<script>
$("li").on('click', function() {
alert(this.id);
return false;
});
</script>
Unfortunately PHP does not have any kind of native threading capabilities. So I think in this case you have no choice but to use some kind of custom code to do what you want to do.
If you search around the net for PHP threading stuff, some people have come up with ways to simulate threads on PHP.
Why do you consider regex the best tool for this? If your purpose is to detect whether an illegal character is present in a string, testing each character in a loop will be both simpler and more efficient than constructing a regex.
In Node.js, __dirname
is always the directory in which the currently executing script resides (see this). So if you typed __dirname
into /d1/d2/myscript.js
, the value would be /d1/d2
.
By contrast, .
gives you the directory from which you ran the node
command in your terminal window (i.e. your working directory) when you use libraries like path
and fs
. Technically, it starts out as your working directory but can be changed using process.chdir()
.
The exception is when you use .
with require()
. The path inside require
is always relative to the file containing the call to require
.
Let's say your directory structure is
/dir1
/dir2
pathtest.js
and pathtest.js
contains
var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));
and you do
cd /dir1/dir2
node pathtest.js
you get
. = /dir1/dir2
__dirname = /dir1/dir2
Your working directory is /dir1/dir2
so that's what .
resolves to. Since pathtest.js
is located in /dir1/dir2
that's what __dirname
resolves to as well.
However, if you run the script from /dir1
cd /dir1
node dir2/pathtest.js
you get
. = /dir1
__dirname = /dir1/dir2
In that case, your working directory was /dir1
so that's what .
resolved to, but __dirname
still resolves to /dir1/dir2
.
.
inside require
...If inside dir2/pathtest.js
you have a require
call into include a file inside dir1
you would always do
require('../thefile')
because the path inside require
is always relative to the file in which you are calling it. It has nothing to do with your working directory.
I guess you want to use to edit the json text. Then you can use ivarni's way:
{{data | json}}and add an adition attribute to make
editable
<pre contenteditable="true">{{data | json}}</pre>
Hope this can help you.
The answer given by @allen is reasonably generic but can lack in performance for larger dataframes:
Reduce does a lot better:
from functools import reduce
import pandas as pd
# make data
df = pd.DataFrame(index=range(1_000_000))
df['1'] = 'CO'
df['2'] = 'BOB'
df['3'] = '01'
df['4'] = 'BILL'
def reduce_join(df, columns):
assert len(columns) > 1
slist = [df[x].astype(str) for x in columns]
return reduce(lambda x, y: x + '_' + y, slist[1:], slist[0])
def apply_join(df, columns):
assert len(columns) > 1
return df[columns].apply(lambda row:'_'.join(row.values.astype(str)), axis=1)
# ensure outputs are equal
df1 = reduce_join(df, list('1234'))
df2 = apply_join(df, list('1234'))
assert df1.equals(df2)
# profile
%timeit df1 = reduce_join(df, list('1234')) # 733 ms
%timeit df2 = apply_join(df, list('1234')) # 8.84 s
Why be easy when it can be complicated? Why use third-party applications like netdom.exe when correct interogations is the way? Try 2 interogations:
wmic computersystem where caption='%computername%' get caption, UserName, Domain /format:value
wmic computersystem where "caption like '%%%computername%%%'" get caption, UserName, Domain /format:value
or in a batch file use loop
for /f "tokens=2 delims==" %%i in ('wmic computersystem where "Caption like '%%%currentname%%%'" get UserName /format:value') do (echo. UserName- %%i)
Thank you, in PostgreSQL this works for boolean
SELECT
hat,
shoe,
boat,
false as placeholder
FROM
objects
For ssh style urls just add ssh before the url:
yarn add ssh://<whatever>@<xxx>#<branch,tag,commit>
In my case, I modified directory tag.
From
<Directory "D:/Devel/matysart/matysart_dev1">
Allow from all
Order Deny,Allow
</Directory>
To
<Directory "D:/Devel/matysart/matysart_dev1">
Require local
</Directory>
And it seriously worked. It's seems changed with Apache 2.4.2.
If you need form
inside tr
and input
s in every td
, you can add form
in td
tag, and add attribute 'form' that contains id of form
tag to outside input
s.
Something like this:
<tr>
<td>
<form id='f1'>
<input type="text">
</form>
</td>
<td>
<input form='f1' type="text">
</td>
</tr>
I just found this which seems really good.
http://www.dfc-e.com/metiers/multimedia/opensource/jqtransform/
VB6/VBA uses deterministic approach to destoying objects. Each object stores number of references to itself. When the number reaches zero, the object is destroyed.
Object variables are guaranteed to be cleaned (set to Nothing
) when they go out of scope, this decrements the reference counters in their respective objects. No manual action required.
There are only two cases when you want an explicit cleanup:
When you want an object to be destroyed before its variable goes out of scope (e.g., your procedure is going to take long time to execute, and the object holds a resource, so you want to destroy the object as soon as possible to release the resource).
When you have a circular reference between two or more objects.
If objectA
stores a references to objectB
, and objectB
stores a reference to objectA
, the two objects will never get destroyed unless you brake the chain by explicitly setting objectA.ReferenceToB = Nothing
or objectB.ReferenceToA = Nothing
.
The code snippet you show is wrong. No manual cleanup is required. It is even harmful to do a manual cleanup, as it gives you a false sense of more correct code.
If you have a variable at a class level, it will be cleaned/destroyed when the class instance is destructed. You can destroy it earlier if you want (see item 1.
).
If you have a variable at a module level, it will be cleaned/destroyed when your program exits (or, in case of VBA, when the VBA project is reset). You can destroy it earlier if you want (see item 1.
).
Access level of a variable (public vs. private) does not affect its life time.
Inconsolata (http://www.levien.com/type/myfonts/inconsolata.html) is a great monospaced font for programming. Earlier versions tend to act weird on OS X, but the newer versions work out very well.
This would work well especially for those using Bootstrap, tested in latest browser versions:
select {_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
appearance: none;_x000D_
/* Some browsers will not display the caret when using calc, so we put the fallback first */ _x000D_
background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") white no-repeat 98.5% !important; /* !important used for overriding all other customisations */_x000D_
background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") white no-repeat calc(100% - 10px) !important; /* Better placement regardless of input width */_x000D_
}_x000D_
/*For IE*/_x000D_
select::-ms-expand { display: none; }
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-xs-6">_x000D_
<select class="form-control">_x000D_
<option>Option 1</option>_x000D_
<option>Option 2</option>_x000D_
<option>Option 3</option>_x000D_
</select>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
I had the same issue with Visual Studio Community 2013, I fixed it downloading and installing the latest update of Office Developer Tools for Visual Studio 2013. Now I am able to see the whole Microsoft.Office.Interop.* list when I go to
Add References > Assemblies > Extensions
you can download it from here:
https://www.visualstudio.com/en-us/news/vs2013-update4-rtm-vs.aspx#Office
http://aka.ms/OfficeDevToolsForVS2013
The Java system property System.getProperty(...)
to consult is "java.runtime.name"
. This will distinguish between "OpenJDK Runtime Environment" and "Java(TM) SE Runtime Environment". They both have the same vendor - "Oracle Corporation".
This property is also included in the output for java -version
.
Perhaps you are looking for Structs without constructors:
class Sample:
name = ''
average = 0.0
values = None # list cannot be initialized here!
s1 = Sample()
s1.name = "sample 1"
s1.values = []
s1.values.append(1)
s1.values.append(2)
s1.values.append(3)
s2 = Sample()
s2.name = "sample 2"
s2.values = []
s2.values.append(4)
for v in s1.values: # prints 1,2,3 --> OK.
print v
print "***"
for v in s2.values: # prints 4 --> OK.
print v
Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)
/etc/squid3/squid.conf
instead of the super bloated default config file
auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
# Choose the port you want. Below we set it to default 3128.
http_port 3128
Please note the basic_ncsa_auth program instead of the old ncsa_auth
For squid 2.x you need to edit /etc/squid/squid.conf
file and place:
auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
sudo htpasswd -c /etc/squid3/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid3 restart
sudo htpasswd -c /etc/squid/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid restart
For the many people that asked me: the 2 tools produce different file formats:
htdigest
stores the password in plain text.htpasswd
stores the password hashed (various hashing algos are available)Despite this difference in format basic_ncsa_auth
will still be able to parse a password file generated with htdigest
. Hence you can alternatively use:
sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like
Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.
On Ubuntu 14.04 htdigest
and htpasswd
are both available in the [apache2-utils][1]
package.
Similar as above applies, but file paths are different.
Install squid
brew install squid
Start squid service
brew services start squid
Squid config file is stored at /usr/local/etc/squid.conf
.
Comment or remove following line:
http_access allow localnet
Then similar to linux config (but with updated paths) add this:
auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
Note that path to basic_ncsa_auth
may be different since it depends on installed version when using brew
, you can verify this with ls /usr/local/Cellar/squid/
. Also note that you should add the above just bellow the following section:
#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#
Now generate yourself a user:password basic auth credential (note: htpasswd
and htdigest
are also both available on MacOS)
htpasswd -c /usr/local/etc/squid_passwords username_you_like
Restart the squid service
brew services restart squid
I am not sure why no one mentioned this but in C# for things that I cannot assign const, I use static read-only properties.
Example:
public static readonly Dictionary<string, string[]> NewDictionary = new Dictionary<string, string[]>()
{
{ "Reference1", Array1 },
{ "Reference2", Array2 },
{ "Reference3", Array3 },
{ "Reference4", Array4 },
{ "Reference5", Array5 }
};
I hope you find this helpful:
typeof(IList<T>).IsGenericType == true
typeof(IList<T>).GetGenericTypeDefinition() == typeof(IList<>)
typeof(IList<int>).GetGenericArguments()[0] == typeof(int)
I have a different approach from other people here, and it an approach that is guaranteed work without dealing with the CookieSyncManager (where you are at the mercy of semantics like "Note that even sync() happens asynchronously").
Essentially, we browse to the correct domain, then we execute javascript from the page context to set cookies for that domain (the same way the page itself would). Two drawbacks to the method are that may introduce an extra round trip time due to the extra http request you have to make; and if your site does not have the equivalent of a blank page, it may flash whatever URL you load first before taking you to the right place.
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.cookie.Cookie;
import android.annotation.SuppressLint;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewFragment {
private static final String BLANK_PAGE = "/blank.html"
private CookieSyncManager mSyncManager;
private CookieManager mCookieManager;
private String mTargetUrl;
private boolean mInitializedCookies;
private List<Cookie> mAllCookies;
public WebViewFragment(Context ctx) {
// We are still required to create an instance of Cookie/SyncManager.
mSyncManager = CookieSyncManager.createInstance(ctx);
mCookieManager = CookieManager.getInstance();
}
@SuppressLint("SetJavaScriptEnabled") public void loadWebView(
String url, List<Cookie> cookies, String domain) {
final WebView webView = ...
webView.setWebViewClient(new CookeWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
mInitializedCookies = false;
mTargetUrl = url;
mAllCookies = cookies;
// This is where the hack starts.
// Instead of loading the url, we load a blank page.
webView.loadUrl("http://" + domain + BLANK_PAGE);
}
public static String buildCookieString(final Cookie cookie) {
// You may want to add the secure flag for https:
// + "; secure"
// In case you wish to convert session cookies to have an expiration:
// + "; expires=Thu, 01-Jan-2037 00:00:10 GMT"
// Note that you cannot set the HttpOnly flag as we are using
// javascript to set the cookies.
return cookie.getName() + "=" + cookie.getValue()
+ "; path=" + cookie.getPath()
+ "; domain=" + cookie.getDomain()
};
public synchronized String generateCookieJavascript() {
StringBuilder javascriptCode = new StringBuilder();
javascriptCode.append("javascript:(function(){");
for (final Cookie cookie : mAllCookies) {
String cookieString = buildCookieString(cookie);
javascriptCode.append("document.cookie=\"");
javascriptCode.append(
StringEscapeUtils.escapeJavascriptString(cookieString));
javascriptCode.append("\";");
}
// We use javascript to load the next url because we do not
// receive an onPageFinished event when this code finishes.
javascriptCode.append("document.location=\"");
javascriptCode.append(
StringEscapeUtils.escapeJavascriptString(mTargetUrl));
javascriptCode.append("\";})();");
return javascriptCode.toString();
}
private class CookieWebViewClient extends WebViewClient {
@Override public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (!mInitializedCookies) {
mInitializedCookies = true;
// Run our javascript code now that the temp page is loaded.
view.loadUrl(generateCookieJavascript());
return;
}
}
}
}
If you trust the domain the cookies are from, you may be able to get away without apache commons, but you have to understand that this can present a XSS risk if you are not careful.
Just an addition to what Greg said:
$("#whatever").offset().left + $("#whatever").outerWidth()
This code will get the right position relative to the left side. If the intention was to get the right side position relative to the right (like when using the CSS right
property) then an addition to the code is necessary as follows:
$("#parent_container").innerWidth() - ($("#whatever").offset().left + $("#whatever").outerWidth())
This code is useful in animations where you have to set the right side as a fixed anchor when you can't initially set the right
property in CSS.
Update with string interpolation in ES2015.
const num = 07734;
let numStringArr = `${num}`.split('').map(el => parseInt(el)); // [0, 7, 7, 3, 4]
max-device-width is the device rendering width
@media all and (max-device-width: 400px) {
/* styles for devices with a maximum width of 400px and less
Changes only on device orientation */
}
@media all and (max-width: 400px) {
/* styles for target area with a maximum width of 400px and less
Changes on device orientation , browser resize */
}
The max-width is the width of the target display area means the current size of browser.
Just had this problem myself and accepted answer didn't help me but I solved it with:
Add reference > Browse > C: > Windows > assembly > GAC > Microsoft.Office.Interop.Excel > 12.0.0.0_etc > Microsoft.Office.Interop.Excel.dll
Here's a way to do it:
// The method to call
void Foo()
{
}
Action action = Foo;
action.BeginInvoke(ar => action.EndInvoke(ar), null);
Of course you need to replace Action
by another type of delegate if the method has a different signature
To change the default branch in Gitlab 7.7.2:
for entry in "$search_dir"/*
do
echo "$entry"
done
Because by default jQuery serializes objects passed as the data
parameter to $.ajax
. It uses $.param
to convert the data to a query string.
From the jQuery docs for $.ajax
:
[the
data
argument] is converted to a query string, if not already a string
If you want to send JSON, you'll have to encode it yourself:
data: JSON.stringify(arr);
Note that JSON.stringify
is only present in modern browsers. For legacy support, look into json2.js
You have to use HorizontalContentAlignment="Center" and! Width="Auto".
ObjectID
s are objects so if you just compare them with ==
you're comparing their references. If you want to compare their values you need to use the ObjectID.equals
method:
if (results.userId.equals(AnotherMongoDocument._id)) {
...
}
(1) SQLite has a built in rowid
pseudo-column so this works:
sqldf("select min(rowid) rowid, id, string
from test
group by id")
giving:
rowid id string
1 1 1 A
2 3 2 B
3 5 3 C
4 7 4 D
5 9 5 E
(2) Also sqldf
itself has a row.names=
argument:
sqldf("select min(cast(row_names as real)) row_names, id, string
from test
group by id", row.names = TRUE)
giving:
id string
1 1 A
3 2 B
5 3 C
7 4 D
9 5 E
(3) A third alternative which mixes the elements of the above two might be even better:
sqldf("select min(rowid) row_names, id, string
from test
group by id", row.names = TRUE)
giving:
id string
1 1 A
3 2 B
5 3 C
7 4 D
9 5 E
Note that all three of these rely on a SQLite extension to SQL where the use of min
or max
is guaranteed to result in the other columns being chosen from the same row. (In other SQL-based databases that may not be guaranteed.)
Put that file in assets.
For project created in Android Studio project you need to create assets folder under the main folder.
Read that file as:
public String loadJSONFromAsset(Context context) {
String json = null;
try {
InputStream is = context.getAssets().open("file_name.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
and then you can simply read this string
return by this function as
JSONObject obj = new JSONObject(json_return_by_the_function);
For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html
Hope you will get what you want.
I had a similar issue when using AD on CAS , i.e. 52e error, In my case application accepts the Full Name when in the form of CN= instead of the actual username.
For example, if you had a user who's full name is Ross Butler and their login username is rbutler --you would normally put something like, cn=rbutler,ou=Users,dc=domain,dc=com but ours failed everytime. By changing this to cn=Ross Butler,ou=Users,dc=domain,dc=com it passed!!
As paxdiablo said you can use >&
to redirect both stdout and stderr. However if you want them separated you can use the following:
(command > stdoutfile) >& stderrfile
...as indicated the above will redirect stdout to stdoutfile and stderr to stderrfile.
Alternatively, use the manifest to specify the class-path and main-class if you like, so then you don't need to use -cp
or specify the main class. In your case it would contain lines like this:
Main-Class: com.test.App
Class-Path: lib/one.jar lib/two.jar
Unfortunately you need to spell out each jar in the manifest (not a biggie as you only do once, and you can use a script to build the file or use a build tool like ANT or Maven or Gradle). And the reference has to be a relative or absolute directory to where you run the java -jar MyJar.jar
.
Then execute it with
java -jar MyJar.jar
Use:
driver.manage().timeOuts().implicitlyWait(10, TimeUnit.SECONDS);
Which means any search for the elements on the web page could take time to load. The implicitlyWait
is set before throwing an exception.
The TimeUnit
displays whichever way you want to wait in (seconds, minutes, hours and days).
Check if you're referencing jquery.js
BEFORE bootstrap.js
and bootstrap.js
is loaded only once. That fixed the same error for me:
<script type="text/javascript" src="js/jquery-1.8.0.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
If you know that v1
has a value, you can use the Value
property:
v2 = v1.Value;
Using the GetValueOrDefault
method will assign the value if there is one, otherwise the default for the type, or a default value that you specify:
v2 = v1.GetValueOrDefault(); // assigns zero if v1 has no value
v2 = v1.GetValueOrDefault(-1); // assigns -1 if v1 has no value
You can use the HasValue
property to check if v1
has a value:
if (v1.HasValue) {
v2 = v1.Value;
}
There is also language support for the GetValueOrDefault(T)
method:
v2 = v1 ?? -1;
show variables where Variable_name='hostname';
That could help you !!
If you're using ASP.NET MVC, I found Response.AddHeader("X-UA-Compatible", "IE=edge,chrome=1")
in a code block in _Layout to work quite well:
@Code
Response.AddHeader("X-UA-Compatible", "IE=edge,chrome=1")
End Code
<!DOCTYPE html>
everything else
First, regarding this solution:
# -*- coding: utf-8 -*-
print u"åäö".encode('utf-8')
It's not practical to explicitly print with a given encoding every time. That would be repetitive and error-prone.
A better solution is to change sys.stdout
at the start of your program, to encode with a selected encoding. Here is one solution I found on Python: How is sys.stdout.encoding chosen?, in particular a comment by "toka":
import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
Here is my easy solution for this:
Click on Gradle
button, you can find at the right side top. you will see all the gradle files. Now go to android, and double click on signingReport. Once the gradle build finishes, you see the SHA key. Check the below images for step by step guide.
Once you click on Gradle check the below images. Hope this helps someone.
STEP 1:
STEP 2:
The Core KTX module provides extensions for common libraries that are part of the Android framework, androidx.core.view
among them.
dependencies {
implementation "androidx.core:core-ktx:{latest-version}"
}
The following extension functions are handy to deal with margins:
Note: they are all extension functions of
MarginLayoutParams
, so first you need to get and cast thelayoutParams
of your view:val params = (myView.layoutParams as ViewGroup.MarginLayoutParams)
setMargins()
extension function:Sets the margins of all axes in the ViewGroup
's MarginLayoutParams
. (The dimension has to be provided in pixels, see the last section if you want to work with dp)
inline fun MarginLayoutParams.setMargins(@Px size: Int): Unit
// E.g. 16px margins
params.setMargins(16)
updateMargins()
extension function:Updates the margins in the ViewGroup
's ViewGroup.MarginLayoutParams
.
inline fun MarginLayoutParams.updateMargins(
@Px left: Int = leftMargin,
@Px top: Int = topMargin,
@Px right: Int = rightMargin,
@Px bottom: Int = bottomMargin
): Unit
// Example: 8px left margin
params.updateMargins(left = 8)
updateMarginsRelative()
extension function:Updates the relative margins in the ViewGroup
's MarginLayoutParams
(start/end instead of left/right).
inline fun MarginLayoutParams.updateMarginsRelative(
@Px start: Int = marginStart,
@Px top: Int = topMargin,
@Px end: Int = marginEnd,
@Px bottom: Int = bottomMargin
): Unit
// E.g: 8px start margin
params.updateMargins(start = 8)
The following extension properties are handy to get the current margins:
inline val View.marginBottom: Int
inline val View.marginEnd: Int
inline val View.marginLeft: Int
inline val View.marginRight: Int
inline val View.marginStart: Int
inline val View.marginTop: Int
// E.g: get margin bottom
val bottomPx = myView1.marginBottom
dp
instead of px
:If you want to work with dp
(density-independent pixels) instead of px
, you will need to convert them first. You can easily do that with the following extension property:
val Int.px: Int
get() = (this * Resources.getSystem().displayMetrics.density).toInt()
Then you can call the previous extension functions like:
params.updateMargins(start = 16.px, end = 16.px, top = 8.px, bottom = 8.px)
val bottomDp = myView1.marginBottom.dp
Old answer:
In Kotlin you can declare an extension function like:
fun View.setMargins(
leftMarginDp: Int? = null,
topMarginDp: Int? = null,
rightMarginDp: Int? = null,
bottomMarginDp: Int? = null
) {
if (layoutParams is ViewGroup.MarginLayoutParams) {
val params = layoutParams as ViewGroup.MarginLayoutParams
leftMarginDp?.run { params.leftMargin = this.dpToPx(context) }
topMarginDp?.run { params.topMargin = this.dpToPx(context) }
rightMarginDp?.run { params.rightMargin = this.dpToPx(context) }
bottomMarginDp?.run { params.bottomMargin = this.dpToPx(context) }
requestLayout()
}
}
fun Int.dpToPx(context: Context): Int {
val metrics = context.resources.displayMetrics
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), metrics).toInt()
}
Then you can call it like:
myView1.setMargins(8, 16, 34, 42)
Or:
myView2.setMargins(topMarginDp = 8)