I would do it by creating a variable that points to the nodes that have the proper value in Value1 then referring to t
<xsl:variable name="myVarANode" select="root//DataSet/Data[@Value1='2']" />
<xsl:value-of select="$myVarANode/@Value2"/>
Everyone else's answers are right too - more right in fact since I didn't notice the extra slash in your XPATH that would mess things up. Still, this will also work , and might work for different things, so keep this method in your toolbox.
Disable it in onCreate()
final KeyListener edtTxtMessageKeyListener = edtTxtMessage.getKeyListener();
edtTxtMessage.setCursorVisible(false);
edtTxtMessage.setKeyListener(null);
And finally enable it in onClick() of EditText
edtTxtMessage.setCursorVisible(true);
edtTxtMessage.setKeyListener(edtTxtMessageKeyListener);
But the problem is with we have to click twise to bring OnScreenKeyboard for very first time.
@Workaround
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
Try this also in onClick() :)
You can create a new file, setenv.sh (or setenv.bat) inside tomcats bin directory and add following line there
export CLASSPATH=$CLASSPATH:/XX/xx/PATH_TO_DIR
It's not possible to configure an IIS managed handler to run in classic mode. You should be running IIS in integrated mode if you want to do that.
You can learn more about modules, handlers and IIS modes in the following blog post:
IIS 7.0, ASP.NET, pipelines, modules, handlers, and preconditions
For handlers, if you set preCondition="integratedMode" in the mapping, the handler will only run in integrated mode. On the other hand, if you set preCondition="classicMode" the handler will only run in classic mode. And if you omit both of these, the handler can run in both modes, although this is not possible for a managed handler.
In my case, there was no string on which i was calling appendChild
, the object i was passing on appendChild
argument was wrong, it was an array and i had pass an element object, so i used divel.appendChild(childel[0])
instead of divel.appendChild(childel)
and it worked. Hope it help someone.
Update the apache-maven-3.5.0-bin\apache-maven-3.5.0\conf\settings.xml file.
Check your internet explorer proxy --> Setting --> Internet explorer -->Connection --> LAN Setting
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>user</username>
<password>****</password>
<host>proxy</host>
<port>8080</port>
</proxy>
<div *ngFor="let number of [].constructor(myCollection)">
<div>
Hello World
</div>
</div>
This is a nice and quick way to repeat for the amount of times in myCollection.
So if myCollection was 5, Hello World would be repeated 5 times.
In my case, I was getting this error message because I was changed the service's namespace and services tag was pointed to the older namespace. I refreshed the namespace and the error disapear:
<services>
<service name="My.Namespace.ServiceName"> <!-- Updated name -->
<endpoint address=""
binding="wsHttpBinding"
bindingConfiguration="MyBindingConfiguratioName"
contract="My.Namespace.Interface" <!-- Updated contract -->
/>
</service>
</services>
in ie8 you can try
-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=5, Direction=135, Color='#c0c0c0')";
filter: progid:DXImageTransform.Microsoft.Shadow(Strength=5, Direction=135, Color='#c0c0c0');
caveat: in ie8 you loose smooth fonts for some reason, they will look ragged
Use following code:
UIBarButtonItem *customBtn=[[UIBarButtonItem alloc] initWithTitle:@"Custom" style:UIBarButtonItemStylePlain target:self action:@selector(customBtnPressed)];
[self.navigationItem setRightBarButtonItem:customBtn];
$( 'input[name="testGroup"]:radio' ).on('change', function(e) {_x000D_
console.log(e.type);_x000D_
return false;_x000D_
});
_x000D_
This syntax is a little more flexible to handle events. Not only can you observe "changes", but also other types of events can be controlled here too by using one single event handler. You can do this by passing the list of events as arguments to the first parameter. See jQuery On
Secondly, .change() is a shortcut for .on( "change", handler ). See here. I prefer using .on() rather than .change because I have more control over the events.
Lastly, I'm simply showing an alternative syntax to attach the event to the element.
For my instance i used it as a global and then called its for a time check of when hours of operation.
Below is from my index.js
global.globalDay = new Date().getDay();
global.globalHours = new Date().getHours();
To call the global's value from another file
/*
Days of the Week.
Sunday = 0, Monday = 1, Tuesday = 2, Wensday = 3, Thursday = 4, Friday = 5, Saturday = 6
Hours of the Day.
0 = Midnight, 1 = 1am, 12 = Noon, 18 = 6pm, 23 = 11pm
*/
if (global.globalDay === 6 || global.globalDay === 0) {
console.log('Its the weekend.');
} else if (global.globalDay > 0 && global.globalDay < 6 && global.globalHours > 8 && global.globalHours < 18) {
console.log('During Business Hours!');
} else {
console.log("Outside of Business hours!");
}
Maybe you can download zlib.h from https://dev.w3.org/Amaya/libpng/zlib/zlib.h, and put it in the directory to solve the problem.
Now you can see both the pseudo-class rules and force them on elements.
To see the rules like :hover
in the Styles pane click the small :hov
text in the top right.
To force an element into :hover
state, right click it and select :hover
.
Additional tips on the elements panel in Chrome Developer Tools Shortcuts.
You only have to add group = 1
into the ggplot or geom_line aes().
For line graphs, the data points must be grouped so that it knows which points to connect. In this case, it is simple -- all points should be connected, so group=1. When more variables are used and multiple lines are drawn, the grouping for lines is usually done by variable.
Reference: Cookbook for R, Chapter: Graphs Bar_and_line_graphs_(ggplot2), Line graphs.
Try this:
plot5 <- ggplot(df, aes(year, pollution, group = 1)) +
geom_point() +
geom_line() +
labs(x = "Year", y = "Particulate matter emissions (tons)",
title = "Motor vehicle emissions in Baltimore")
Does it mean that I'm blocking reading any input from the Server/Client for this socket for 2000 millisecond and after this time the socket is ready to read data?
No, it means that if no data arrives within 2000ms a SocketTimeoutException
will be thrown.
What does it mean timeout expire?
It means the 2000ms (in your case) elapses without any data arriving.
What is the option which must be enabled prior to blocking operation?
There isn't one that 'must be' enabled. If you mean 'may be enabled', this is one of them.
Infinite Timeout menas that the socket does't read anymore?
What a strange suggestion. It means that if no data ever arrives you will block in the read forever.
Use path.join http://nodejs.org/docs/v0.4.10/api/path.html#path.join
var path = require("path"),
fs = require("fs");
fs.readFile(path.join(__dirname, '..', '..', 'foo.bar'));
path.join()
will handle leading/trailing slashes for you and just do the right thing and you don't have to try to remember when trailing slashes exist and when they dont.
other than using this.form.submit()
you also submiting by id or name.
example i have form like this : <form action="" name="PostName" id="IdName">
By Name : <select onchange="PostName.submit()">
By Id : <select onchange="IdName.submit()">
I didn't find find the correct jsonpath filter syntax to extract a value from a name-value pair in json.
Here's the syntax and an abbreviated sample twitter document below.
This site was useful for testing:
The jsonpath filter expression:
.events[0].attributes[?(@.name=='screen_name')].value
Test document:
{
"title" : "test twitter",
"priority" : 5,
"events" : [ {
"eventId" : "150d3939-1bc4-4bcb-8f88-6153053a2c3e",
"eventDate" : "2015-03-27T09:07:48-0500",
"publisher" : "twitter",
"type" : "tweet",
"attributes" : [ {
"name" : "filter_level",
"value" : "low"
}, {
"name" : "screen_name",
"value" : "_ziadin"
}, {
"name" : "followers_count",
"value" : "406"
} ]
} ]
}
Changing the web.config generally causes an application restart.
If you really need your application to edit its own settings, then you should consider a different approach such as databasing the settings or creating an xml file with the editable settings.
^[0-9]{1,6}$
should do it. I don't know VB.NET good enough to know if it's the same there.
For examples, have a look at the Wikipedia.
This may not specifically answer your long 3 part question but this thread is old and I found this while searching today. Here is one shorter way to: "Wait until a process has finished." If you know the name of the process such as "EXCEL.EXE"
strProcess = "EXCEL.EXE"
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '"& strProcess &"'")
Do While colProcesses.Count > 0
Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '"& strProcess &"'")
Wscript.Sleep(1000) 'Sleep 1 second
'msgbox colProcesses.count 'optional to show the loop works
Loop
Credit to: http://crimsonshift.com/scripting-check-if-process-or-program-is-running-and-start-it/
when you are using POST method in HTML forms, you need to catch the data from req.body in the server side i.e. Node.js. and also add
var bodyParser = require('body-parser')
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({extended: false}));
OR
use method='GET' in HTML and and catch the data by req.query in the server side i.e. Node.js
The correct syntax is:
FOR EACH ROW SET NEW.bname = CONCAT( UCASE( LEFT( NEW.bname, 1 ) )
, LCASE( SUBSTRING( NEW.bname, 2 ) ) )
There is no show
event in js - you need to bind your button either to the click
event:
$('#id').on('click', function (e) {
//your awesome code here
})
Mind that if your button is inside a form
, you may prefer to bind the whole form to the submit
event.
Fighting whether the code is compiling or not I would say create a array of sixe 5 add 2 values and print them , you will get the two values and others are null. The question is although the size is 5 but there are 2 objects in the array . How to find how many objects are present in the array
Everything is much simpler, use git checkout for that.
Suppose you're on master
branch, to get app.js from new-feature
branch do:
git checkout new-feature path/to/app.js
// note that there is no leading slash in the path!
This will bring you the contents of the desired file. You can, as always, use part of sha1 instead of new-feature branch name to get the file as it was in that particular commit.
Note:new-feature
needs to be a local branch, not a remote one.
The nested class doesn't know about the outer class, and protected
doesn't help. You'll have to pass some actual reference to objects of the nested class type. You could store a foo*
, but perhaps a reference to the integer is enough:
class Outer
{
int n;
public:
class Inner
{
int & a;
public:
Inner(int & b) : a(b) { }
int & get() { return a; }
};
// ... for example:
Inner inn;
Outer() : inn(n) { }
};
Now you can instantiate inner classes like Inner i(n);
and call i.get()
.
Maven working terminology having phases and goals.
Phase:Maven phase is a set of action which is associated with 2 or 3 goals
exmaple:- if you run mvn clean
this is the phase will execute the goal mvn clean:clean
Goal:Maven goal bounded with the phase
for reference http://books.sonatype.com/mvnref-book/reference/lifecycle-sect-structure.html
You would use the os module system method.
You just put in the string form of the command, the return value is the windows enrivonment variable COMSPEC
For example:
os.system('python') opens up the windows command prompt and runs the python interpreter
Just tell request that you are using json:true and forget about header and parse
var options = {
hostname: '127.0.0.1',
port: app.get('port'),
path: '/users',
method: 'GET',
json:true
}
request(options, function(error, response, body){
if(error) console.log(error);
else console.log(body);
});
and the same for post
var options = {
hostname: '127.0.0.1',
port: app.get('port'),
path: '/users',
method: 'POST',
json: {"name":"John", "lastname":"Doe"}
}
request(options, function(error, response, body){
if(error) console.log(error);
else console.log(body);
});
I suggest you use a HiddenField inside template field use FindControl to find this field.
ie:
ASPX
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hfFname" runat="server" Value='<%# Eval("FileName") %>' />
</ItemTemplate>
</asp:TemplateField>
Code behind
protected void gvAttachments_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView gv1 = (GridView)sender;
GridViewRow gvr1 = (GridViewRow)gv1.Rows[e.RowIndex];
//get hidden field value and not directly from the GridviewRow, as that will be null or empty!
HiddenField hf1 = (HiddenField)gvr1.FindControl("hfFname");
if (hf1 != null)
{
..
}
}
My vote is string.Join
No need for lambda evaluations and temporary functions to be created, fewer function calls, less stack pushing and popping.
import random
random.shuffle(array)
Everyone's showing the XML way, except one person showed calling EditText's setMaxLines method. However, when I did that, it didn't work. One thing that did work for me was setting the input type.
EditText editText = new EditText(this);
editText.setInputType(InputType.TYPE_CLASS_TEXT);
This allows A-Z, a-z, 0-9, and special characters, but does not allow enter to be pressed. When you press enter, it'll go to the next GUI component, if applicable in your application.
You may also want to set the maximum number of characters that can be put into that EditText, or else it'll push whatever's to the right of it off the screen, or just start trailing off the screen itself. You can do this like this:
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(8);
editText.setFilters(filters);
This sets the max characters to 8 in that EditText. Hope all this helps you.
There are (at least) three different definitions I'm aware of
in business computing, middleware is messaging and integration software between applications and services
in gaming, middleware is pretty well anything that is provided by a third-party
in (some) embedded software systems, middleware provides services that applications use, which are composed out of the functions provided by the hardware abstraction layer - it sits between the application layer and the hardware abstraction layer.
So the first part of the answer is how to do what the subject asks as this was how I initially interpreted it and a few people seemed to find helpful. The question was since clarified and I've extended the answer to address that.
Setting a timer
First you need to create a Timer (I'm using the java.util
version here):
import java.util.Timer;
..
Timer timer = new Timer();
To run the task once you would do:
timer.schedule(new TimerTask() {
@Override
public void run() {
// Your database code here
}
}, 2*60*1000);
// Since Java-8
timer.schedule(() -> /* your database code here */, 2*60*1000);
To have the task repeat after the duration you would do:
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Your database code here
}
}, 2*60*1000, 2*60*1000);
// Since Java-8
timer.scheduleAtFixedRate(() -> /* your database code here */, 2*60*1000, 2*60*1000);
Making a task timeout
To specifically do what the clarified question asks, that is attempting to perform a task for a given period of time, you could do the following:
ExecutorService service = Executors.newSingleThreadExecutor();
try {
Runnable r = new Runnable() {
@Override
public void run() {
// Database task
}
};
Future<?> f = service.submit(r);
f.get(2, TimeUnit.MINUTES); // attempt the task for two minutes
}
catch (final InterruptedException e) {
// The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
// Took too long!
}
catch (final ExecutionException e) {
// An exception from within the Runnable task
}
finally {
service.shutdown();
}
This will execute normally with exceptions if the task completes within 2 minutes. If it runs longer than that, the TimeoutException will be throw.
One issue is that although you'll get a TimeoutException after the two minutes, the task will actually continue to run, although presumably a database or network connection will eventually time out and throw an exception in the thread. But be aware it could consume resources until that happens.
Modify build.gradle to put your main class in the manifest:
jar {
manifest {
attributes 'Implementation-Title': 'Gradle Quickstart',
'Implementation-Version': version,
'Main-Class': 'hello.helloWorld'
}
}
You need to do a couple of things to use the library:
Make sure that you have both the *.lib and the *.dll from the library you want to use. If you don't have the *.lib, skip #2
Put a reference to the *.lib in the project. Right click the project name in the Solution Explorer and then select Configuration Properties->Linker->Input and put the name of the lib in the Additional Dependencies property.
You have to make sure that VS can find the lib you just added so you have to go to the Tools menu and select Options... Then under Projects and Solutions select VC++ Directories,edit Library Directory option. From within here you can set the directory that contains your new lib by selecting the 'Library Files' in the 'Show Directories For:' drop down box. Just add the path to your lib file in the list of directories. If you dont have a lib you can omit this, but while your here you will also need to set the directory which contains your header files as well under the 'Include Files'. Do it the same way you added the lib.
After doing this you should be good to go and can use your library. If you dont have a lib file you can still use the dll by importing it yourself. During your applications startup you can explicitly load the dll by calling LoadLibrary (see: http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx for more info)
Cheers!
EDIT
Remember to use #include < Foo.h > as opposed to #include "foo.h". The former searches the include path. The latter uses the local project files.
Why not use a library function to validate the ip address?
>>> ip="241.1.1.112343434"
>>> socket.inet_aton(ip)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
socket.error: illegal IP address string passed to inet_aton
Don't forget to go to your device and enable Settings->Developer Options->USB debugging.
I've used CSS Grid to fix that. CSS Grid will make all the elements in the same row, all the same height.
I haven't looked into making all the elements in all the rows the same height though.
Anyway, here's how it can be done:
HTML:
<div class="grid-container">
<div class="card">...</div>
<div class="card">...</div>
</div>
CSS:
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
Here's a complete JSFiddle. https://jsfiddle.net/bluegrounds/owjvhstq/4/
round(number, 1)
I had a similar issue, no videos would play in Chrome. Tried installing beta 64bit, going back to Chrome 32bit release.
The only thing that worked for me was updating my video drivers.
I have the NVIDIA GTS 240. Downloaded, installed the drivers and restarted and Chrome 38.0.2125.77 beta-m (64-bit) starting playing HTML5 videos again on youtube, vimeo and others. Hope this helps anyone else.
Maybe you could use this view, but i'm not sure.
select * from v$database;
But I think It will only show you info about the current db.
Other option, if the db is running in linux... whould be something like this:
SQL>!grep SID $TNS_ADMIN/tnsnames.ora | grep -v PLSExtProc
On Android 5.1 Lollipop for my device, click on the Google Settings
icon > Security
> Scan device for security threats
.
Note that Google Settings
is separated from the Settings
app itself.
just vars(obj)
, it will state the whole values of the object
>>> obj_attrs = vars(obj)
>>> obj_attrs
{'_file_data_cache': <FileData: Data>,
'_state': <django.db.models.base.ModelState at 0x7f5c6733bad0>,
'aggregator_id': 24,
'amount': 5.0,
'biller_id': 23,
'datetime': datetime.datetime(2018, 1, 31, 18, 43, 58, 933277, tzinfo=<UTC>),
'file_data_id': 797719,
}
You can add this also
>>> keys = obj_attrs.keys()
>>> temp = [obj_attrs.pop(key) if key.startswith('_') else None for key in keys]
>>> del temp
>>> obj_attrs
{
'aggregator_id': 24,
'amount': 5.0,
'biller_id': 23,
'datetime': datetime.datetime(2018, 1, 31, 18, 43, 58, 933277, tzinfo=<UTC>),
'file_data_id': 797719,
}
Add the dots to all values:
[[UIColor colorWithRed:222./255. green:227./255. blue: 229./255. alpha:1] CGColor]) ;
Otherwise, you are dividing float by int.
In the command line type service apache2 status
then hit enter. The result should say:
Apache2 is running (pid xxxx)
pseudo-code:
minutes = floor(326.4/60)
seconds = round(326.4 - minutes * 60)
In my case I used sudo mkdir projectFolder
to create folder. It was owned by root user and I was logged in using non root user.
So I changed the folder permission using command sudo chown mynonrootuser:mynonrootuser projectFolder
and then it worked fine.
For OSX:
After opening docker and starting the 'default' machine via the Quickstart Terminal (https://docs.docker.com/engine/installation/mac/), you try docker commands and get this "can't connect to docker daemon" message, it turns out you need some env variables set:
eval "$(docker-machine env default)"
Then try it out with docker run hello-world
to see if everything is peachy.
This isn't necessarily an answer to the original question, but a sharing of some results from my own testing. This:
<<test > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
test
will produce the same file as:
cat <<test > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
test
So, I don't see the point of using the cat command.
if(getResult.Key.Equals(default(T)) && getResult.Value.Equals(default(U)))
This may be old, but... if you change the link in google stock list as below:
It means, starting for row 1 to 30000. It shows all results in one page.
You may automate it using any language or just export the table to excel.
Hope it helps.
I had the same problem but also wanted to get the content of the file (after the YAML front-matter).
This is the best solution I have found:
if (md = contents.match(/^(?<metadata>---\s*\n.*?\n?)^(---\s*$\n?)/m))
self.contents = md.post_match
self.metadata = YAML.load(md[:metadata])
end
Source and discussion: https://practicingruby.com/articles/tricks-for-working-with-text-and-files
The easiest way I found to 'get' what the for/else did, and more importantly, when to use it, was to concentrate on where the break statement jumps to. The For/else construct is a single block. The break jumps out of the block, and so jumps 'over' the else clause. If the contents of the else clause simply followed the for clause, it would never be jumped over, and so the equivalent logic would have to be provided by putting it in an if. This has been said before, but not quite in these words, so it may help somebody else. Try running the following code fragment. I'm wholeheartedly in favour of the 'no break' comment for clarity.
for a in range(3):
print(a)
if a==4: # change value to force break or not
break
else: #no break +10 for whoever thought of this decoration
print('for completed OK')
print('statement after for loop')
Well I was able to install it by :
sudo apt-get install php-curl
on my system. This will install a dependency package, which depends on the default php version.
After that restart apache
sudo service apache2 restart
Older IE and Firefox browsers attach the scrollbar to the documentElement
, or what would be the <html>
tag in HTML.
All other browsers attach the scrollbar to document.body
, or what would be the <body>
tag in HTML.
The correct solution would be to check which one to use, depending on browser
var doc = document.documentElement.clientHeight ? document.documentElement : document.body;
var s = $(doc).scrollTop();
jQuery does make this a little easier, when passing in either window
or document
jQuery's scrollTop
does a similar check and figures it out, so either of these should work cross-browser
var s = $(document).scrollTop();
or
var s = $(window).scrollTop();
Description: Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.
...nothing that works for my div, just the full page
If it's for a DIV, you'd have to target the element that has the scrollbar attached, to get the scrolled amount
$('div').scrollTop();
If you need to get the elements distance from the top of the document, you can also do
$('div').offset().top
You can do it using the Github API
This is the Python example:
import requests
if __name__ == '__main__':
base_api_url = 'https://api.github.com/repos'
git_repository_url = 'https://github.com/garysieling/wikipedia-categorization.git'
github_username, repository_name = git_repository_url[:-4].split('/')[-2:] # garysieling and wikipedia-categorization
res = requests.get(f'{base_api_url}/{github_username}/{repository_name}')
repository_size = res.json().get('size')
print(repository_size)
change:
$("input:text").change(function() {
var value=$("input:text").val();
alert(value);
});
to
$("input:text").change(function() {
var value=$("input[type=text].selector").val();
alert(value);
});
note: selector:id,class..
There is a GitHub project called Xcode Project Renamer
:
It should be executed from inside root of Xcode project directory and called with two string parameters: $OLD_PROJECT_NAME & $NEW_PROJECT_NAME
Script goes through all the files and directories recursively, including Xcode project or workspace file and replaces all occurrences of $OLD_PROJECT_NAME string with $NEW_PROJECT_NAME string (both in each file's name and content).
start-class
doesn't work for me, I fixed it by adding build plugins
to pom.xml
, and executions
is necessary.
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
It seems you can cheat a bit using jetxee's algorithm. He is finding the first three toes fine, and you should be able to guess where the fourth is based off that.
You can just turn on Github Pages. ^_^
Click on "Settings", than go to "GitHub Pages" and click on dropdown under "Source" and choose branch which you want to public (where main html file is located) aaaand vualaa. ^_^
Fix doesn't work.
Exactly as in the example illustration, all these steps only provide access to "system" databases, and no option to select existing user databases that you want to access.
The solution to access a local (not Express Edition) Microsoft SQL server instance resides on the SQL Server side:
Done! Now you can select your local SQL Server from the Server Name list in Connection Properties.
Go to Project | Properties and then Assembly Information and then Assembly Version and put an * in the last or the second-to-last box (you can't auto-increment the Major or Minor components).
Right after you append data to the view add this single line:
yourScrollview.fullScroll(ScrollView.FOCUS_DOWN);
I just add this line exactly as it appears below (if you need a second delay):
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
// Process exception
}
I find the catch IS necessary (Your app can crash due to Android OS as much as your own code).
There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.
Option Explicit
Public Numbers As Variant, Tens As Variant
Sub SetNums()
Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub
Function WordNum(MyNumber As Double) As String
Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
' This macro was written by Chris Mead - www.MeadInKent.co.uk
If Abs(MyNumber) > 999999999 Then
WordNum = "Value too large"
Exit Function
End If
SetNums
' String representation of amount (excl decimals)
NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
For n = 3 To 1 Step -1 'analyse the absolute number as 3 sets of 3 digits
StrNo = Format(ValNo(n), "000")
If ValNo(n) > 0 Then
Temp1 = GetTens(Val(Right(StrNo, 2)))
If Left(StrNo, 1) <> "0" Then
Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
If Temp1 <> "" Then Temp2 = Temp2 & " and "
Else
Temp2 = ""
End If
If n = 3 Then
If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
WordNum = Trim(Temp2 & Temp1)
End If
If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
End If
Next n
NumStr = Trim(Str(Abs(MyNumber)))
' Values after the decimal place
DecimalPosition = InStr(NumStr, ".")
Numbers(0) = "Zero"
If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
Temp1 = " point"
For n = DecimalPosition + 1 To Len(NumStr)
Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
Next n
WordNum = WordNum & Temp1
End If
If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
WordNum = "Zero" & WordNum
End If
End Function
Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
If TensNum <= 19 Then
GetTens = Numbers(TensNum)
Else
Dim MyNo As String
MyNo = Format(TensNum, "00")
GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
End If
End Function
After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)
It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.
Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)
you will see a Words equivalent of the numeric value.
This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel
In this line:
fund = fund * (1 + 0.01 * growthRates) + depositPerYear
I think you mean this:
fund = fund * (1 + 0.01 * i) + depositPerYear
When you try to multiply a float by growthRates (which is a list), you get that error.
In ipython
, I use this to print a part of the dataframe that works quite well (prints the first 100 rows):
print paramdata.head(100).to_string()
I chose System.web.MVC from reference folder and right clicked on it to go property window where I could see version of MVC. This solution works for me. Thanks
Change the query to
"INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ); SELECT SCOPE_IDENTITY()"
This will return the last inserted ID which you can then get with ExecuteScalar
Assuming your dataframe is mydf:
mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
Update:
As noted by @iX3, Typescript 2.4 has support for enum strings.
See:Create an enum with string values in Typescript
Original answer:
For String member values, TypeScript only allows numbers as enum member values. But there are a few solutions/hacks you can implement;
Solution 1:
copied from: https://blog.rsuter.com/how-to-implement-an-enum-with-string-values-in-typescript/
There is a simple solution: Just cast the string literal to any before assigning:
export enum Language {
English = <any>"English",
German = <any>"German",
French = <any>"French",
Italian = <any>"Italian"
}
solution 2:
copied from: https://basarat.gitbooks.io/typescript/content/docs/types/literal-types.html
You can use a string literal as a type. For example:
let foo: 'Hello';
Here we have created a variable called foo that will only allow the literal value 'Hello' to be assigned to it. This is demonstrated below:
let foo: 'Hello';
foo = 'Bar'; // Error: "Bar" is not assignable to type "Hello"
They are not very useful on their own but can be combined in a type union to create a powerful (and useful) abstraction e.g.:
type CardinalDirection =
"North"
| "East"
| "South"
| "West";
function move(distance: number, direction: CardinalDirection) {
// ...
}
move(1,"North"); // Okay
move(1,"Nurth"); // Error!
use if (testString.Equals(testString2))
.
The following hack works:
xmlns:tools="http://schemas.android.com/tools"
line in the
manifest tag tools:replace="android:icon,android:theme,android:allowBackup,label"
in the application tagThere is a better way than having to manually navigate to https://url , knowing what button to click in what browser, knowing where and how to save the "certificate" file and finally knowing the magic incantation for the keytool to install it locally.
Just do this:
javac InstallCert.java
java InstallCert <host>[:port] [passphrase]
(port and passphrase are optional)Here is the code for InstallCert, note the year in header, will need to modify some parts for "later" versions of java:
/*
* Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.*;
import java.net.URL;
import java.security.*;
import java.security.cert.*;
import javax.net.ssl.*;
public class InstallCert {
public static void main(String[] args) throws Exception {
String host;
int port;
char[] passphrase;
if ((args.length == 1) || (args.length == 2)) {
String[] c = args[0].split(":");
host = c[0];
port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
String p = (args.length == 1) ? "changeit" : args[1];
passphrase = p.toCharArray();
} else {
System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
return;
}
File file = new File("jssecacerts");
if (file.isFile() == false) {
char SEP = File.separatorChar;
File dir = new File(System.getProperty("java.home") + SEP
+ "lib" + SEP + "security");
file = new File(dir, "jssecacerts");
if (file.isFile() == false) {
file = new File(dir, "cacerts");
}
}
System.out.println("Loading KeyStore " + file + "...");
InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close();
SSLContext context = SSLContext.getInstance("TLS");
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[] {tm}, null);
SSLSocketFactory factory = context.getSocketFactory();
System.out.println("Opening connection to " + host + ":" + port + "...");
SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
socket.setSoTimeout(10000);
try {
System.out.println("Starting SSL handshake...");
socket.startHandshake();
socket.close();
System.out.println();
System.out.println("No errors, certificate is already trusted");
} catch (SSLException e) {
System.out.println();
e.printStackTrace(System.out);
}
X509Certificate[] chain = tm.chain;
if (chain == null) {
System.out.println("Could not obtain server certificate chain");
return;
}
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
System.out.println();
System.out.println("Server sent " + chain.length + " certificate(s):");
System.out.println();
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
MessageDigest md5 = MessageDigest.getInstance("MD5");
for (int i = 0; i < chain.length; i++) {
X509Certificate cert = chain[i];
System.out.println
(" " + (i + 1) + " Subject " + cert.getSubjectDN());
System.out.println(" Issuer " + cert.getIssuerDN());
sha1.update(cert.getEncoded());
System.out.println(" sha1 " + toHexString(sha1.digest()));
md5.update(cert.getEncoded());
System.out.println(" md5 " + toHexString(md5.digest()));
System.out.println();
}
System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
String line = reader.readLine().trim();
int k;
try {
k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
} catch (NumberFormatException e) {
System.out.println("KeyStore not changed");
return;
}
X509Certificate cert = chain[k];
String alias = host + "-" + (k + 1);
ks.setCertificateEntry(alias, cert);
OutputStream out = new FileOutputStream("jssecacerts");
ks.store(out, passphrase);
out.close();
System.out.println();
System.out.println(cert);
System.out.println();
System.out.println
("Added certificate to keystore 'jssecacerts' using alias '"
+ alias + "'");
}
private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
private static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 3);
for (int b : bytes) {
b &= 0xff;
sb.append(HEXDIGITS[b >> 4]);
sb.append(HEXDIGITS[b & 15]);
sb.append(' ');
}
return sb.toString();
}
private static class SavingTrustManager implements X509TrustManager {
private final X509TrustManager tm;
private X509Certificate[] chain;
SavingTrustManager(X509TrustManager tm) {
this.tm = tm;
}
public X509Certificate[] getAcceptedIssuers() {
throw new UnsupportedOperationException();
}
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
throw new UnsupportedOperationException();
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
this.chain = chain;
tm.checkServerTrusted(chain, authType);
}
}
}
What about this approach:
<head>_x000D_
<style type="text/css">_x000D_
div.gradient {_x000D_
color: #000000;_x000D_
width: 800px;_x000D_
height: 200px;_x000D_
}_x000D_
div.gradient:after {_x000D_
background: url(SOME_BACKGROUND);_x000D_
background-size: cover;_x000D_
content:'';_x000D_
position:absolute;_x000D_
top:0;_x000D_
left:0;_x000D_
width:inherit;_x000D_
height:inherit;_x000D_
opacity:0.1;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div class="gradient">Text</div>_x000D_
</body>
_x000D_
for those who want some official document to confirm the behavior
Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ‘-e’ flag is specified, then values from the environment override assignments in the makefile.
https://www.gnu.org/software/make/manual/html_node/Environment.html
The onclick
property is all lower-case, and accepts a function, not a string.
document.getElementById("test").onclick = foo2;
See also addEventListener
.
$ids = sprintf("'%s'", implode("','", $ids ) );
NamingException's answer worked for me. Except I used
var date = $("#date").dtpicker({ dateFormat: 'dd,MM,yyyy' }).val()
datepicker
didn't work but dtpicker
did.
Well it does this because you are converting a 64 bits pointer to an 32 bits integer so you loose information.
You can use a 64 bits integer instead howerver I usually use a function with the right prototype and I cast the function type : eg.
void thread_func(int arg){
...
}
and I create the thread like this :
pthread_create(&tid, NULL, (void*(*)(void*))thread_func, (void*)arg);
This is an update for the existing answers which used bytearray()
and can not work that way anymore:
>>> st = "hello world"
>>> map(bin, bytearray(st))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string argument without an encoding
Because, as explained in the link above, if the source is a string, you must also give the encoding:
>>> map(bin, bytearray(st, encoding='utf-8'))
<map object at 0x7f14dfb1ff28>
Press Ctrl+,
Then you will see a docked window under name of "Go to all"
This a picture of the "Go to all" in my IDE
you call function on page load time but not call on button event, you will need to call function onclick
event, you may add event inline element style or event bining
function Choice(elem) {_x000D_
var box = document.getElementById("box");_x000D_
if (elem.id == "no") {_x000D_
box.style.backgroundColor = "red";_x000D_
} else if (elem.id == "yes") {_x000D_
box.style.backgroundColor = "green";_x000D_
} else {_x000D_
box.style.backgroundColor = "purple";_x000D_
};_x000D_
};
_x000D_
<div id="box">dd</div>_x000D_
<button id="yes" onclick="Choice(this);">yes</button>_x000D_
<button id="no" onclick="Choice(this);">no</button>_x000D_
<button id="other" onclick="Choice(this);">other</button>
_x000D_
or event binding,
window.onload = function() {_x000D_
var box = document.getElementById("box");_x000D_
document.getElementById("yes").onclick = function() {_x000D_
box.style.backgroundColor = "red";_x000D_
}_x000D_
document.getElementById("no").onclick = function() {_x000D_
box.style.backgroundColor = "green";_x000D_
}_x000D_
}
_x000D_
<div id="box">dd</div>_x000D_
<button id="yes">yes</button>_x000D_
<button id="no">no</button>
_x000D_
Well In my case VS 2017, the lightweight solution load was causing this issue. I disabled it & restarted VS then re-build my solution & the problem gone.
def update(value, nvalue):
if not isinstance(value, dict) or not isinstance(nvalue, dict):
return nvalue
for k, v in nvalue.items():
value.setdefault(k, dict())
if isinstance(v, dict):
v = update(value[k], v)
value[k] = v
return value
use dict
or collections.Mapping
The ~/Library/Developer/Xcode/iOS DeviceSupport
folder is basically only needed to symbolicate crash logs.
You could completely purge the entire folder. Of course the next time you connect one of your devices, Xcode would redownload the symbol data from the device.
I clean out that folder once a year or so by deleting folders for versions of iOS I no longer support or expect to ever have to symbolicate a crash log for.
You need to override the following properties:
Broker Configs($KAFKA_HOME/config/server.properties)
Consumer Configs($KAFKA_HOME/config/consumer.properties)
This step didn't work for me. I add it to the consumer app and it was working fine
Restart the server.
look at this documentation for more info: http://kafka.apache.org/08/configuration.html
You can open the file again using vi helloworld.txt
and then use cat /path/your_file
to view it.
I figured it out through trial and error... the real chink in the armor was a little known setting in IIS in the Configuration Editor
for the website in
Section: system.webServer/security/authentication/windowsAuthentication
From: ApplicationHost.config <locationpath='ServerName/SiteName' />
called useAppPoolCredentials
(which is set to False
by default. Set this to True
and life becomes great again!!! Hope this saves pain for the next guy....
Open up your git bash and type
echo $HOME
This shall be the same folder as you get when you open your command window (cmd) and type
echo %USERPROFILE%
And – of course – the .ssh
folder shall be present on THAT directory.
More compact version working with spaces and newlines in the file name:
find . -iname '*.txt' -exec sh -c 'echo "{}" ; ls -l "{}"' \;
I made a small change to Softlion answer, so all my modals won't refresh on hide. The modals with data-refresh='true' attribute are only refreshed, others work as usual. Here is the modified version.
$(document).on('hidden.bs.modal', function (e) {
if ($(e.target).attr('data-refresh') == 'true') {
// Remove modal data
$(e.target).removeData('bs.modal');
// Empty the HTML of modal
$(e.target).html('');
}
});
Now use the attribute as shown below,
<div class="modal fade" data-refresh="true" id="#modal" tabindex="-1" role="dialog" aria-labelledby="#modal-label" aria-hidden="true"></div>
This will make sure only the modals with data-refresh='true' are refreshed. And i'm also resetting the modal html because the old values are shown until new ones get loaded, making html empty fixes that one.
No.. It is not proper way. Refer the steps,
For Classpath reference:
Right click on project in Eclipse -> Buildpath -> Configure Build path -> Java Build Path (left Pane) -> Libraries(Tab) -> Add External Jars -> Select your jar and select OK.
For Deployment Assembly:
Right click on WAR in eclipse-> Buildpath -> Configure Build path -> Deployment Assembly (left Pane) -> Add -> External file system -> Add -> Select your jar -> Add -> Finish.
This is the proper way! Don't forget to remove environment variable. It is not required now.
Try this. Surely it will work. Try to use Maven, it will simplify you task.
As Uriel says, it is meant for a method in an abstract class that should be implemented in child class, but can be used to indicate a TODO as well.
There is an alternative for the first use case: Abstract Base Classes. Those help creating abstract classes.
Here's a Python 3 example:
class C(abc.ABC):
@abc.abstractmethod
def my_abstract_method(self, ...):
...
When instantiating C
, you'll get an error because my_abstract_method
is abstract. You need to implement it in a child class.
TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method
Subclass C
and implement my_abstract_method
.
class D(C):
def my_abstract_method(self, ...):
...
Now you can instantiate D
.
C.my_abstract_method
does not have to be empty. It can be called from D
using super()
.
An advantage of this over NotImplementedError
is that you get an explicit Exception
at instantiation time, not at method call time.
my example:
companyNamesFirst = this.model.CustomerDisplayList.Where(a => a.CompanyFirst != null ? a.CompanyFirst.StartsWith(typedChars.ToLower())) : false).Select(b => b.CompanyFirst).Distinct().ToList();
The SNIPPETS C Source Code Archive has a CRC32 implementation that is freely usable:
/* Copyright (C) 1986 Gary S. Brown. You may use this program, or
code or tables extracted from it, as desired without restriction.*/
(Unfortunately, c.snippets.org seems to have died. Fortunately, the Wayback Machine has it archived.)
In order to be able to compile the code, you'll need to add typedefs for BYTE
as an unsigned 8-bit integer and DWORD
as an unsigned 32-bit integer, along with the header files crc.h & sniptype.h.
The only critical item in the header is this macro (which could just as easily go in CRC_32.c itself:
#define UPDC32(octet, crc) (crc_32_tab[((crc) ^ (octet)) & 0xff] ^ ((crc) >> 8))
The problem can be PHP configuration:
Please check the setting max_input_vars in the php.ini file.
Try to increase the value of this setting to 5000 as example.
max_input_vars = 5000
Then restart your web-server and try.
SIMPLE. 2018. FlexBox. To Check Browser Support - Can I Use
Minimal Solution:
div#over {
display: flex;
justify-content: center;
align-items: center;
}
To get the widest browser support possible:
div#over {
display: -webkit-flex;
display: -ms-flex;
display: flex;
justify-content: center;
-ms-align-items: center;
align-items: center;
}
Here is a simple example:
ThreadTest.java
public class ThreadTest
{
public static void main(String [] args)
{
MyThread t1 = new MyThread(0, 3, 300);
MyThread t2 = new MyThread(1, 3, 300);
MyThread t3 = new MyThread(2, 3, 300);
t1.start();
t2.start();
t3.start();
}
}
MyThread.java
public class MyThread extends Thread
{
private int startIdx, nThreads, maxIdx;
public MyThread(int s, int n, int m)
{
this.startIdx = s;
this.nThreads = n;
this.maxIdx = m;
}
@Override
public void run()
{
for(int i = this.startIdx; i < this.maxIdx; i += this.nThreads)
{
System.out.println("[ID " + this.getId() + "] " + i);
}
}
}
And some output:
[ID 9] 1
[ID 10] 2
[ID 8] 0
[ID 10] 5
[ID 9] 4
[ID 10] 8
[ID 8] 3
[ID 10] 11
[ID 10] 14
[ID 10] 17
[ID 10] 20
[ID 10] 23
An explanation - Each MyThread
object tries to print numbers from 0 to 300, but they are only responsible for certain regions of that range. I chose to split it by indices, with each thread jumping ahead by the number of threads total. So t1
does index 0, 3, 6, 9, etc.
Now, without IO, trivial calculations like this can still look like threads are executing sequentially, which is why I just showed the first part of the output. On my computer, after this output thread with ID 10 finishes all at once, followed by 9, then 8. If you put in a wait or a yield, you can see it better:
MyThread.java
System.out.println("[ID " + this.getId() + "] " + i);
Thread.yield();
And the output:
[ID 8] 0
[ID 9] 1
[ID 10] 2
[ID 8] 3
[ID 9] 4
[ID 8] 6
[ID 10] 5
[ID 9] 7
Now you can see each thread executing, giving up control early, and the next executing.
Try experimenting with something like this also:
HTML
<ul class="inlineList">
<li>She</li>
<li>Needs</li>
<li>More Padding, Captain!</li>
</ul>
CSS
.inlineList {
display: flex;
flex-direction: row;
/* Below sets up your display method: flex-start|flex-end|space-between|space-around */
justify-content: flex-start;
/* Below removes bullets and cleans white-space */
list-style: none;
padding: 0;
/* Bonus: forces no word-wrap */
white-space: nowrap;
}
/* Here, I got you started.
li {
padding-top: 50px;
padding-bottom: 50px;
padding-left: 50px;
padding-right: 50px;
}
*/
I made a codepen to illustrate: http://codepen.io/agm1984/pen/mOxaEM
Use:
$filelist = @("11", "1", "2")
$filelist | sort @{expression={[int]$_}} | % {$newName = [string]([int]$_ + 1)}
New-Item $newName -ItemType Directory
The correct interpretation of extern is that you tell something to the compiler. You tell the compiler that, despite not being present right now, the variable declared will somehow be found by the linker (typically in another object (file)). The linker will then be the lucky guy to find everything and put it together, whether you had some extern declarations or not.
Another approach would be to extended jquery like this:
$.fn.toggleCheckbox = function() {
this.attr('checked', !this.attr('checked'));
}
Then call:
$('.offer').find(':checkbox').toggleCheckbox();
It depends on whether the question you are asking is:
To find out if they are the same object, compare pointers to the two structs for equality. If you want to find out in general if they have the same value you have to do a deep comparison. This involves comparing all the members. If the members are pointers to other structs you need to recurse into those structs too.
In the special case where the structs do not contain pointers you can do a memcmp to perform a bitwise comparison of the data contained in each without having to know what the data means.
Make sure you know what 'equals' means for each member - it is obvious for ints but more subtle when it comes to floating-point values or user-defined types.
Still, joda-time does only support the extended format: "2015-12-09T00:22:42.930Z" not the basic: "20151209T002242.930Z" ...we might be better off testing a list of formats with java SimpleDateFormat.
This library: Android-Image-Cropper is very powerful to CropImages. It has 3,731 stars on github at this time.
You will crop your images with a few lines of code.
1 - Add the dependecies into buid.gradle (Module: app)
compile 'com.theartofdev.edmodo:android-image-cropper:2.7.+'
2 - Add the permissions into AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
3 - Add CropImageActivity into AndroidManifest.xml
<activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
android:theme="@style/Base.Theme.AppCompat"/>
4 - Start the activity with one of the cases below, depending on your requirements.
// start picker to get image for cropping and then use the image in cropping activity
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
// start cropping activity for pre-acquired image saved on the device
CropImage.activity(imageUri)
.start(this);
// for fragment (DO NOT use `getActivity()`)
CropImage.activity()
.start(getContext(), this);
5 - Get the result in onActivityResult
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
You can do several customizations, as set the Aspect Ratio or the shape to RECTANGLE, OVAL and a lot more.
You can like this...
document.getElementById('my-image').ondragstart = function() { return false; };
See it working (or not working, rather)
It seems you are using jQuery.
$('img').on('dragstart', function(event) { event.preventDefault(); });
In C++ a class with at least one pure virtual function is called abstract class. You can not create objects of that class, but may only have pointers or references to it.
If you are deriving from an abstract class, then make sure you override and define all pure virtual functions for your class.
From your snippet Your class AliceUniversity
seems to be an abstract class. It needs to override and define all the pure virtual functions of the classes Graduate
and UniversityGraduate
.
Pure virtual functions are the ones with = 0;
at the end of declaration.
Example: virtual void doSomething() = 0;
For a specific answer, you will need to post the definition of the class for which you get the error and the classes from which that class is deriving.
The power in dBm is the 10 times the logarithm of the ratio of actual Power/1 milliWatt.
dBm stands for "decibel milliwatts". It is a convenient way to measure power. The exact formula is
P(dBm) = 10 · log10( P(W) / 1mW )
where
P(dBm) = Power expressed in dBm P(W) = the absolute power measured in Watts mW = milliWatts log10 = log to base 10
From this formula, the power in dBm of 1 Watt is 30 dBm. Because the calculation is logarithmic, every increase of 3dBm is approximately equivalent to doubling the actual power of a signal.
There is a conversion calculator and a comparison table here. There is also a comparison table on the Wikipedia english page, but the value it gives for mobile networks is a bit off.
Your actual question was "does the - sign count?"
The answer is yes, it does.
-85 dBm is less powerful (smaller) than -60 dBm. To understand this, you need to look at negative numbers. Alternatively, think about your bank account. If you owe the bank 85 dollars/rands/euros/rupees (-85), you're poorer than if you only owe them 65 (-65), i.e. -85 is smaller than -65. Also, in temperature measurements, -85 is colder than -65 degrees.
Signal strengths for mobile networks are always negative dBm values, because the transmitted network is not strong enough to give positive dBm values.
How will this affect your location finding? I have no idea, because I don't know what technology you are using to estimate the location. The values you quoted correspond roughly to a 5 bar network in GSM, UMTS or LTE, so you shouldn't have be having any problems due to network strength.
In addition to @Ivan's answer, types all need to be included
/* Drop all Types */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sys.types where is_user_defined = 1 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP TYPE [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Type: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sys.types where is_user_defined = 1 AND [name] > @name ORDER BY [name])
END
GO
All these tips did not work for me, what worked was cloning over ssh rather that http
In main project's appsettings.json file, I had set 'Copy to Output directory' to "Copy always" and it worked.
Regular expressions are great, but why not just make sure it's a number before trying to do something with it?
function addemup() {
var n1 = document.getElementById("num1");
var n2 = document.getElementById("num2");
sum = Number(n1.value) + Number(n2.value);
if(Number(sum)) {
alert(sum);
} else {
alert("Numbers only, please!");
};
};
This command can explicitly set the base URL for your rewrites. If you wish to start in the root of your domain, you would include the following line before your RewriteRule:
RewriteBase /
None of the solutions above were working for me. My workaround was to open the on-screen keyboard using the system settings (press Windows key and search for "keyboard" to find them). Once that's open you can click the Insert key on it.
if i understood you can do the following
Right Click on View Name in SQL Server Management Studio -> Script View As ->CREATE To ->New Query Window
Make sure the following:
private static final long serialVersionUID = 1L;
should be there in your class (<servlet-class>MyClass</servlet-class>
).I use the AbsoluteUri and you can get it like this:
string myURI = Request.Url.AbsoluteUri;
if (!WebSecurity.IsAuthenticated) {
Response.Redirect("~/Login?returnUrl="
+ Request.Url.AbsoluteUri );
Then after you login:
var returnUrl = Request.QueryString["returnUrl"];
if(WebSecurity.Login(username,password,true)){
Context.RedirectLocal(returnUrl);
It works well for me.
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
public class MyView extends View
{
Paint paint = null;
public MyView(Context context)
{
super(context);
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
int x = getWidth();
int y = getHeight();
int radius;
radius = 100;
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
// Use Color.parseColor to define HTML colors
paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawCircle(x / 2, y / 2, radius, paint);
}
}
}
Edit if you want to draw circle at centre. You could also translate your entire canvas to center then draw circle at center.using
canvas.translate(getWidth()/2f,getHeight()/2f);
canvas.drawCircle(0,0, radius, paint);
These two link also help
http://www.compiletimeerror.com/2013/09/introduction-to-2d-drawing-in-android.html#.VIg_A5SSy9o
http://android-coding.blogspot.com/2012/04/draw-circle-on-canvas-canvasdrawcirclet.html
public static void main(String[] args)
{
String strDate="Feb 2013";
String[] strArray=strDate.split("\\s+");
Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat("MMM").parse(strArray[0].toString()));
int monthInt = cal.get(Calendar.MONTH);
monthInt++;
cal.set(Calendar.YEAR, Integer.parseInt(strArray[1]));
strDate=strArray[1].toString()+"-"+monthInt+"-"+cal.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println(strDate);
}
This is the method I'm using in a project I am currently working on.
var exec = require('child_process').exec;
function execute(command, callback){
exec(command, function(error, stdout, stderr){ callback(stdout); });
};
Example of retrieving a git user:
module.exports.getGitUser = function(callback){
execute("git config --global user.name", function(name){
execute("git config --global user.email", function(email){
callback({ name: name.replace("\n", ""), email: email.replace("\n", "") });
});
});
};
I've faced this today, and my issue was that my Content-Disposition
tag was wrongly set.
It looks like for both pdf
& application/x-zip-compressed
, you're supposed to set it to inline
instead of attachment
.
So to set your header, Java code would look like this:
...
String fileName = "myFileName.zip";
String contentDisposition = "attachment";
if ("application/pdf".equals(contentType)
|| "application/x-zip-compressed".equals(contentType)) {
contentDisposition = "inline";
}
response.addHeader("Content-Disposition", contentDisposition + "; filename=\"" + fileName + "\"");
...
I forgot to use var
on my item variable
Incorrect code:
var itemCreateInfo = new SP.ListItemCreationInformation();
item = list.addItem(itemCreateInfo);
item.set_item('Title', 'Haytham - Oil Eng');
Correct code:
var itemCreateInfo = new SP.ListItemCreationInformation();
var item = list.addItem(itemCreateInfo);
item.set_item('Title', 'Haytham - Oil Eng');
That is because Java cannot find the Main attribute in the MANIFEST.MF file. The Main attribute is necessary to tell java which class it should use as the application's entry point. Inside the jar file, the MANIFEST.MF file is located in META-INF folder. Wondering how you could look at what's inside a jar file? Open the jar file with WinRAR.
The main attribute inside the MANIFEST.MF looks like this:
Main-Class: <packagename>.<classname>
You get this "no main manifest attribute" error when this line is missing from the MANIFEST.MF file.
It's really a huge mess to specify this attribute inside the MANIFEST.MF file.
Update: I just found a really neat way to specify the Application's entry point in eclipse. When you say Export,
Select Jar and next
[ give it a name in the next window ] and next
and next again
and you'll see " Select the class of the application entry point".
Just pick a class and Eclipse will automatically build a cool MANIFEST.MF for you.
org.json.JSONObject now has a keySet() method which returns a Set<String>
and can easily be looped through with a for-each.
for(String key : jsonObject.keySet())
Check the .aws directory under home directory. Windows: C:\Users<home-name>.aws Linux: ~/.aws
Under this directory, you will find the config as well as credentials file. It will have the information from the aws configure that you may have run before. IF not, then
Run aws configure
Enter the access key -
secret key - enter secret key
region - (ap-southeast-1 or us-east-1 or any other regions)
format - (json or leave it blank, it will pick up default values you may simply hit enter)
From the Step 2, you should see the config file, open it, it should have the region. Please ensure there is region specified.
You may now run the following command to list the buckets
aws s3 ls
It should work fine.
Interpretation of date strings into datetime
and datetime2
can be different too, when using non-US DATEFORMAT
settings. E.g.
set dateformat dmy
declare @d datetime, @d2 datetime2
select @d = '2013-06-05', @d2 = '2013-06-05'
select @d, @d2
This returns 2013-05-06
(i.e. May 6) for datetime
, and 2013-06-05
(i.e. June 5) for datetime2
. However, with dateformat
set to mdy
, both @d
and @d2
return 2013-06-05
.
The datetime
behavior seems at odds with the MSDN documentation of SET DATEFORMAT
which states: Some character strings formats, for example ISO 8601, are interpreted independently of the DATEFORMAT setting. Obviously not true!
Until I was bitten by this, I'd always thought that yyyy-mm-dd
dates would just be handled right, regardless of the language / locale settings.
I did a simple trick. I clone the repo to a new folder. Copied the .git folder from the new folder to repo's old folder, replacing .git there.
you could also use the "block-quote" property in CSS. That would make it so it doesn't effect your individual lines but allows you to set parameters for just the breaks between paragraphs or "block quotes".
UPDATE:
I stand corrected. "blockquote" is actually a html property. You use it just like < p > and < /p > around your work. You could then set the parameters for your block quote in css like
blockquote { margin-top: 20px }
Hope this helps. It is similar to setting the parameters on the br and may or may not be cross browser compatible.
The prefix "Local" in JSR-310 (aka java.time-package in Java-8) does not indicate that there is a timezone information in internal state of that class (here: LocalDateTime
). Despite the often misleading name such classes like LocalDateTime
or LocalTime
have NO timezone information or offset.
You tried to format such a temporal type (which does not contain any offset) with offset information (indicated by pattern symbol Z). So the formatter tries to access an unavailable information and has to throw the exception you observed.
Solution:
Use a type which has such an offset or timezone information. In JSR-310 this is either OffsetDateTime
(which contains an offset but not a timezone including DST-rules) or ZonedDateTime
. You can watch out all supported fields of such a type by look-up on the method isSupported(TemporalField).. The field OffsetSeconds
is supported in OffsetDateTime
and ZonedDateTime
, but not in LocalDateTime
.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
String s = ZonedDateTime.now().format(formatter);
The href property sets or returns the value of the href attribute of a link.
var hello = domains[i].getElementsByTagName('a')[0].getAttribute('href');
var url="https://www.google.com/";
console.log( url+hello);
I know I am late in answering this question, but this helped me:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="10dp"
android:background="@color/fb" >
<Button
android:id="@+id/fbLogin"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="@null"
android:drawableLeft="@drawable/ic_facebook"
android:gravity="center"
android:minHeight="0dp"
android:minWidth="0dp"
android:text="FACEBOOK"
android:textColor="@android:color/white" />
</FrameLayout>
I found this solution from here: Android UI struggles: making a button with centered text and icon
If you go through the npm config documentation, it says:
proxy
Default: HTTP_PROXY or http_proxy environment variable, or null
Type: url
As per this, to disable usage of proxy, proxy
setting must be set to null
. To set proxy value to null, one has to make sure that HTTP_PROXY
or http_proxy
environment variable is not set. So unset these environment variables and make sure that npm config ls -l
shows proxy = null
.
Also, it is important to note that:
It would have been better if npm had made the type of proxy setting to boolean to switch on/off the proxy usage. Or, they can introduce a new setting of sort use_proxy
of type boolean.
This code simply worked for me
System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Mozilla Firefox 54\\firefox.exe");
String Firefoxdriverpath = "C:\\Users\\Hp\\Downloads\\geckodriver-v0.18.0-win64\\geckodriver.exe";
System.setProperty("webdriver.gecko.driver", Firefoxdriverpath);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver(capabilities);
The Date object handles 8601 as it's first parameter:
var d = new Date("2014-04-07T13:58:10.104Z");_x000D_
console.log(d.toString());
_x000D_
You could make use of the Javascript DOM API. In particular, look at the createElement() method.
You could create a re-usable function that will create an image like so...
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
Then you could use it like this...
<button onclick=
"show_image('http://google.com/images/logo.gif',
276,
110,
'Google Logo');">Add Google Logo</button>
If you are not concerned with potential overflow problems this function will perform about 20-30 times faster than using Integer.parseInt()
.
public static boolean isInteger(String str) {
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
For Java:
X, exactly n times: X{n}
X, at least n times: X{n,}
X, at least n but not more than m times: X{n,m}
Until React provides a better way, you can create a helper, useEffectAsync.js
:
import { useEffect } from 'react';
export default function useEffectAsync(effect, inputs) {
useEffect(() => {
effect();
}, inputs);
}
Now you can pass an async function:
useEffectAsync(async () => {
const items = await fetchSomeItems();
console.log(items);
}, []);
Update
If you choose this approach, note that it's bad form. I resort to this when I know it's safe, but it's always bad form and haphazard.
Suspense for Data Fetching, which is still experimental, will solve some of the cases.
In other cases, you can model the async results as events so that you can add or remove a listener based on the component life cycle.
Or you can model the async results as an Observable so that you can subscribe and unsubscribe based on the component life cycle.
To Change the default global installation directory for node.js(npm) modules in Windows, You need to fix 2 paths.
First check the current path where node modules are installing, when you try to install them globally by using following command :
npm list -g --depth=0
It will return you the current path where node modules are installing right now. Example: D:\vsc\typescript
Now visit the following path to see npm and npm-cache folder. C:\Users\username(OR Number)\AppData\Roaming
In Roaming folder of your C drive you will find npm and npm-cache folder. Click on the + npm + folder and select the path[Just click on the bar path will be selected automatically, copy it ].This is a path image which you need to select
Once you copy this path set this to the environment variables, with a variable name Path(anything you can select as a name). Now you have set the path for your npm folder, now this is the time to set prefix. Go inside npm folder and check if node_module folder exist, if not create a new folder named as node_modules. You all global modules will come in this folder after completing all steps.
Final Step: Go to CMD and right the following command:
npm set prefix C:\Users\username(Number)\AppData\Roaming\npm\node_modules
Again this is the same path we selected for environment variable, we are just adding one more folder in the path and that is node_module.
All Set....Try Now...It will work..
Use dict() on a list of tuples, this solution will allow you to have arbitrary values in each list, so long as they are the same length
i_s = range(1, 11)
x_s = range(1, 11)
# x_s = range(11, 1, -1) # Also works
d = dict([(i_s[index], x_s[index], ) for index in range(len(i_s))])
This will let you share your app on whats app etc:
try
{ Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String sAux = "\nLet me recommend you this application\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=Orion.Soft \n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "choose one"));
Scope tag is always use to limit the transitive dependencies and availability of the jar at class path level.If we don't provide any scope then the default scope will work i.e. Compile .
There might be a problem with your DNS servers of the ISP. A computer by default uses the ISP's DNS servers. You can manually configure your DNS servers. It is free and usually better than your ISP.
Preferred DNS server : 8.8.8.8
Alternate DNS server : 8.8.4.4
Preferred DNS server : 208.67.222.222
Alternate DNS server : 208.67.220.220
Quite a bit:
The rank of a row is one plus the number of ranks that come before the row in question.
Row_number is the distinct rank of rows, without any gap in the ranking.
If you are using this path to access parts of the projects which are not code (for example an upload directory, or a SQLite database) then it might be better to turn the path into a parameter, like this:
parameters:
database_path: '%kernel.root_dir%/../var/sqlite3.db'
This parameter can be injected everywhere you need it, so you don't have to mess around with paths in your code any more. Also, the parameter can be overridden at deployment time. Finally, every maintaining programmer will have a better idea what you are using it for.
Update: Fixed kernel.root_dir constant usage.
Rebooting the machine solved the problem for me. I first tried wiping /tmp/
but node was still complaining.
Try getting hold of a URL for your classpath resource:
URL url = this.getClass().getResource("/com/path/to/file.txt")
Then create a file using the constructor that accepts a URI:
File file = new File(url.toURI());
Apparently, document.addEventListener()
is unreliable, and hence, my error. Use window.addEventListener()
with the same parameters, instead.
Let's assume
],
is the character where we wanted to break at
notePad++
Find window
Ctrl+F Replace
TabSearch Mode
to Extended
],
in Find What
field\n
in Replace with
field Replace All
Am I missing something? You can just convert offer_date in the comparison:
SELECT *
FROM offers
WHERE to_char(offer_date, 'YYYYMM') = (SELECT to_date(create_date, 'YYYYMM') FROM customers where id = '12345678') AND
offer_rate > 0
You can put the textboxes inside a grid to do percentage values on the rows or columns of the grid and let the textboxes auto-fill to their parent cells (as they will by default). Example:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" />
<TextBox Grid.Column="1" />
</Grid>
This will make #1 2/5 of the width, and #2 3/5.
In EF 6.2 using FluentAPI, you can use HasIndex()
modelBuilder.Entity<User>().HasIndex(u => u.UserName).IsUnique();
It's always enlightening to do a benchmark on the various suggested answers. Here's what I found out:
#!/usr/bin/ruby require 'benchmark' ary = [] 1000.times { ary << {:bar => rand(1000)} } n = 500 Benchmark.bm(20) do |x| x.report("sort") { n.times { ary.sort{ |a,b| b[:bar] <=> a[:bar] } } } x.report("sort reverse") { n.times { ary.sort{ |a,b| a[:bar] <=> b[:bar] }.reverse } } x.report("sort_by -a[:bar]") { n.times { ary.sort_by{ |a| -a[:bar] } } } x.report("sort_by a[:bar]*-1") { n.times { ary.sort_by{ |a| a[:bar]*-1 } } } x.report("sort_by.reverse!") { n.times { ary.sort_by{ |a| a[:bar] }.reverse } } end user system total real sort 3.960000 0.010000 3.970000 ( 3.990886) sort reverse 4.040000 0.000000 4.040000 ( 4.038849) sort_by -a[:bar] 0.690000 0.000000 0.690000 ( 0.692080) sort_by a[:bar]*-1 0.700000 0.000000 0.700000 ( 0.699735) sort_by.reverse! 0.650000 0.000000 0.650000 ( 0.654447)
I think it's interesting that @Pablo's sort_by{...}.reverse!
is fastest. Before running the test I thought it would be slower than "-a[:bar]
" but negating the value turns out to take longer than it does to reverse the entire array in one pass. It's not much of a difference, but every little speed-up helps.
Please note that these results are different in Ruby 1.9
Here are results for Ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin10.8.0]:
user system total real
sort 1.340000 0.010000 1.350000 ( 1.346331)
sort reverse 1.300000 0.000000 1.300000 ( 1.310446)
sort_by -a[:bar] 0.430000 0.000000 0.430000 ( 0.429606)
sort_by a[:bar]*-1 0.420000 0.000000 0.420000 ( 0.414383)
sort_by.reverse! 0.400000 0.000000 0.400000 ( 0.401275)
These are on an old MacBook Pro. Newer, or faster machines, will have lower values, but the relative differences will remain.
Here's a bit updated version on newer hardware and the 2.1.1 version of Ruby:
#!/usr/bin/ruby
require 'benchmark'
puts "Running Ruby #{RUBY_VERSION}"
ary = []
1000.times {
ary << {:bar => rand(1000)}
}
n = 500
puts "n=#{n}"
Benchmark.bm(20) do |x|
x.report("sort") { n.times { ary.dup.sort{ |a,b| b[:bar] <=> a[:bar] } } }
x.report("sort reverse") { n.times { ary.dup.sort{ |a,b| a[:bar] <=> b[:bar] }.reverse } }
x.report("sort_by -a[:bar]") { n.times { ary.dup.sort_by{ |a| -a[:bar] } } }
x.report("sort_by a[:bar]*-1") { n.times { ary.dup.sort_by{ |a| a[:bar]*-1 } } }
x.report("sort_by.reverse") { n.times { ary.dup.sort_by{ |a| a[:bar] }.reverse } }
x.report("sort_by.reverse!") { n.times { ary.dup.sort_by{ |a| a[:bar] }.reverse! } }
end
# >> Running Ruby 2.1.1
# >> n=500
# >> user system total real
# >> sort 0.670000 0.000000 0.670000 ( 0.667754)
# >> sort reverse 0.650000 0.000000 0.650000 ( 0.655582)
# >> sort_by -a[:bar] 0.260000 0.010000 0.270000 ( 0.255919)
# >> sort_by a[:bar]*-1 0.250000 0.000000 0.250000 ( 0.258924)
# >> sort_by.reverse 0.250000 0.000000 0.250000 ( 0.245179)
# >> sort_by.reverse! 0.240000 0.000000 0.240000 ( 0.242340)
New results running the above code using Ruby 2.2.1 on a more recent Macbook Pro. Again, the exact numbers aren't important, it's their relationships:
Running Ruby 2.2.1
n=500
user system total real
sort 0.650000 0.000000 0.650000 ( 0.653191)
sort reverse 0.650000 0.000000 0.650000 ( 0.648761)
sort_by -a[:bar] 0.240000 0.010000 0.250000 ( 0.245193)
sort_by a[:bar]*-1 0.240000 0.000000 0.240000 ( 0.240541)
sort_by.reverse 0.230000 0.000000 0.230000 ( 0.228571)
sort_by.reverse! 0.230000 0.000000 0.230000 ( 0.230040)
Updated for Ruby 2.7.1 on a Mid-2015 MacBook Pro:
Running Ruby 2.7.1
n=500
user system total real
sort 0.494707 0.003662 0.498369 ( 0.501064)
sort reverse 0.480181 0.005186 0.485367 ( 0.487972)
sort_by -a[:bar] 0.121521 0.003781 0.125302 ( 0.126557)
sort_by a[:bar]*-1 0.115097 0.003931 0.119028 ( 0.122991)
sort_by.reverse 0.110459 0.003414 0.113873 ( 0.114443)
sort_by.reverse! 0.108997 0.001631 0.110628 ( 0.111532)
...the reverse method doesn't actually return a reversed array - it returns an enumerator that just starts at the end and works backwards.
The source for Array#reverse
is:
static VALUE
rb_ary_reverse_m(VALUE ary)
{
long len = RARRAY_LEN(ary);
VALUE dup = rb_ary_new2(len);
if (len > 0) {
const VALUE *p1 = RARRAY_CONST_PTR_TRANSIENT(ary);
VALUE *p2 = (VALUE *)RARRAY_CONST_PTR_TRANSIENT(dup) + len - 1;
do *p2-- = *p1++; while (--len > 0);
}
ARY_SET_LEN(dup, RARRAY_LEN(ary));
return dup;
}
do *p2-- = *p1++; while (--len > 0);
is copying the pointers to the elements in reverse order if I remember my C correctly, so the array is reversed.
In my case, the error was being shown because when I was reading my JSON file using Jackson library, my JSON file contained only 1 object. Hence it started with "{" and ended with "}". But while reading it and storing it in a variable, I was storing it in an Array object (As in my case, there could be more than 1 object).
Hence, I added "[" in the start and "]" in the end of my JSON file to convert it into an array of object and it worked perfectly fine without any error.
In this article I read that frameworks like Underscore.js use this function:
function isUndefined(obj){
return obj === void 0;
}
For a general solution that works regardless of how many digits are in data$anim
, use the sprintf
function. It works like this:
sprintf("%04d", 1)
# [1] "0001"
sprintf("%04d", 104)
# [1] "0104"
sprintf("%010d", 104)
# [1] "0000000104"
In your case, you probably want: data$anim <- sprintf("%06d", data$anim)
Change this key in the Info.plist
I changed from
<key>JVMVersion</key>
<string>1.6*</string>
to
<key>JVMVersion</key>
<string>1.8*</string>
and it worked fine now..
Edited:
Per the official statement as mentioned above by hasternet and aried3r, the solution by Antonio Jose is correct.
Thanks!
If you're using DRF, check if your urlpatterns are correct, maybe you forgot .as_view()
:
So that how mine code looked like:
urlpatterns += path('resource', ResourceView)
And that's how it should like:
urlpatterns += path('resource', ResourceView.as_view())
If you've deleted your root
user by mistake you can do one thing:
mysqld_safe --skip-grant-tables &
mysql -u root -p
and press enter.use mysql;
Then execute this query:
insert into `user` (`Host`, `User`, `Password`, `Select_priv`, `Insert_priv`, `Update_priv`, `Delete_priv`, `Create_priv`, `Drop_priv`, `Reload_priv`, `Shutdown_priv`, `Process_priv`, `File_priv`, `Grant_priv`, `References_priv`, `Index_priv`, `Alter_priv`, `Show_db_priv`, `Super_priv`, `Create_tmp_table_priv`, `Lock_tables_priv`, `Execute_priv`, `Repl_slave_priv`, `Repl_client_priv`, `Create_view_priv`, `Show_view_priv`, `Create_routine_priv`, `Alter_routine_priv`, `Create_user_priv`, `ssl_type`, `ssl_cipher`, `x509_issuer`, `x509_subject`, `max_questions`, `max_updates`, `max_connections`, `max_user_connections`)
values('localhost','root','','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','','0','0','0','0');
then restart the mysqld
EDIT: October 6, 2018
In case anyone else needs this answer, I tried it today using innodb_version 5.6.36-82.0 and 10.1.24-MariaDB and it works if you REMOVE THE BACKTICKS (no single quotes either, just remove them):
insert into user (Host, User, Password, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Show_db_priv, Super_priv, Create_tmp_table_priv, Lock_tables_priv, Execute_priv, Repl_slave_priv, Repl_client_priv, Create_view_priv, Show_view_priv, Create_routine_priv, Alter_routine_priv, Create_user_priv, ssl_type, ssl_cipher, x509_issuer, x509_subject, max_questions, max_updates, max_connections, max_user_connections)
values('localhost','root','','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','','','','','0','0','0','0');
I used if get row value is clicked:
private void dataGridView_Product_CellClick(object sender, DataGridViewCellEventArgs e){
int rowIndex;
//rowIndex = e.RowIndex; //Option 1
//rowIndex= dataGridView_Product.CurrentCell.RowIndex; //Option 2
rowIndex = dataGridView_Product.CurrentRow.Index; //Option 3
}
An authority is a portion of a URI. Your error suggests that it was not expecting one. The authority section is shown below, it is what is known as the website part of the url.
From RFC3986 on URIs:
The following is an example URI and its component parts:
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
| _____________________|__
/ \ / \
urn:example:animal:ferret:nose
So there are two formats, one with an authority and one not. Regarding slashes:
"When authority is not present, the path cannot begin with two slash
characters ("//")."
Source: https://tools.ietf.org/rfc/rfc3986.txt (search for text 'authority is not present, the path cannot begin with two slash')
Try nsiqcppstyle. It's a Python based coding style checker for C/C++. It's easy to extend to add your own rules.
This has been driving me crazy for literally weeks. I found a solution that will work for me that includes:
...but there are a couple of caveats:
The vertical scrollbar is not visible until you scroll all the way to the right. Given that most people have scroll wheels, this was an acceptable sacrifice.
The width of the scrollbar must be known. On my website I set the scrollbar widths (I'm not overly concerned with older, incompatible browsers), so I can then calculate div
and table
widths that adjust based on the scrollbar.
Instead of posting my code here, I'll post a link to the jsFiddle.
When i analyzed your code. I have also faced the same problem but my problem is if i give value for both first and last name means it is working fine. but when i give only one value means it says 400. anyway use the .andDo(print()) method to find out the error
public void testGetUserByName() throws Exception {
String firstName = "Jack";
String lastName = "s";
this.userClientObject = client.createClient();
mockMvc.perform(get("/byName")
.sessionAttr("userClientObject", this.userClientObject)
.param("firstName", firstName)
.param("lastName", lastName)
).andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"))
.andExpect(jsonPath("$[0].id").exists())
.andExpect(jsonPath("$[0].fn").value("Marge"));
}
If your problem is org.springframework.web.bind.missingservletrequestparameterexception
you have to change your code to
@RequestMapping(value = "/byName", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public
@ResponseBody
String getUserByName(
@RequestParam( value="firstName",required = false) String firstName,
@RequestParam(value="lastName",required = false) String lastName,
@ModelAttribute("userClientObject") UserClient userClient)
{
return client.getUserByName(userClient, firstName, lastName);
}
Jquery:
var cookies = $.cookie();
for(var cookie in cookies) {
$.removeCookie(cookie);
}
vanilla JS
function clearListCookies()
{
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
{
var spcook = cookies[i].split("=");
deleteCookie(spcook[0]);
}
function deleteCookie(cookiename)
{
var d = new Date();
d.setDate(d.getDate() - 1);
var expires = ";expires="+d;
var name=cookiename;
//alert(name);
var value="";
document.cookie = name + "=" + value + expires + "; path=/acc/html";
}
window.location = ""; // TO REFRESH THE PAGE
}
You could also use POSIX regular expressions, like
SELECT id FROM groups where name ~* 'administrator'
SELECT 'asd' ~* 'AsD'
returns t
Previous answers are correct but here is one more way of doing this and some tips:
Option #1 Go to you Jenkins job and search for "add build step" and then just copy and paste your script there
Option #2 Go to Jenkins and do the same again "add build step" but this time put the fully qualified path for your script in there example : ./usr/somewhere/helloWorld.sh
things to watch for /tips:
You could try sp_help <Name of object>
you need to add jersey-bundle-1.17.1.jar
to lib of project
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<!-- <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> -->
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<!-- <param-name>jersey.config.server.provider.packages</param-name> -->
<param-value>package.package.test</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Check for
if (predQuery[preId] === undefined)
Use the strict equal to operator. See comparison operators
Drop root privileges after you bind to port 80 (or 443).
This allows port 80/443 to remain protected, while still preventing you from serving requests as root:
function drop_root() {
process.setgid('nobody');
process.setuid('nobody');
}
A full working example using the above function:
var process = require('process');
var http = require('http');
var server = http.createServer(function(req, res) {
res.write("Success!");
res.end();
});
server.listen(80, null, null, function() {
console.log('User ID:',process.getuid()+', Group ID:',process.getgid());
drop_root();
console.log('User ID:',process.getuid()+', Group ID:',process.getgid());
});
See more details at this full reference.
You can use a resource key like this:
<UserControl.Resources>
<SolidColorBrush x:Key="{x:Static local:Foo.MyKey}">Blue</SolidColorBrush>
</UserControl.Resources>
<Grid Background="{StaticResource {x:Static local:Foo.MyKey}}" />
public partial class Foo : UserControl
{
public Foo()
{
InitializeComponent();
var brush = (SolidColorBrush)FindResource(MyKey);
}
public static ResourceKey MyKey { get; } = CreateResourceKey();
private static ComponentResourceKey CreateResourceKey([CallerMemberName] string caller = null)
{
return new ComponentResourceKey(typeof(Foo), caller); ;
}
}
If you have a lot of elements you would like to .hide()
or .show()
, you are going to waste a lot of resources to do what you want - even if use .hide(0)
or .show(0)
- the 0 parameter is the duration of the animation.
As opposed to Prototype.js .hide()
and .show()
methods which only used to manipulate the display attribute of the element, jQuery's implementation is more complex and not recommended for a large number of elements.
In this cases you should probably try .css('display','none')
to hide and .css('display','')
to show
.css('display','block')
should be avoided, especially if you're working with inline elements, table rows (actually any table elements) etc.
Use a Border of height 1 and don't set the Width (i.e. Width = Auto, HorizontalAlignment = Stretch, the default)
From the docs:
The
SimpleHTTPServer
module has been merged intohttp.server
in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.
So, your command is python -m http.server
, or depending on your installation, it can be:
python3 -m http.server
Here's a way with jQuery's element creation method (my preference) and with callback onLoad
:
var css = $("<link>", {
"rel" : "stylesheet",
"type" : "text/css",
"href" : "style.css"
})[0];
css.onload = function(){
console.log("CSS IN IFRAME LOADED");
};
document
.getElementsByTagName("head")[0]
.appendChild(css);
In general, on Unix and Unix-like systems, MySQL/MariaDB programs read config/startup files in the following locations (in the specified order):
/etc/my.cnf
- Global/etc/mysql/my.cnf
- GlobalSYSCONFDIR/my.cnf
- Global
SYSCONFDIR
represents the directory specified with theSYSCONFDIR
option toCMake
when MySQL was built. By default, this is the etc directory located under the compiled-in installation directory.
$MYSQL_HOME/my.cnf
- Server-specific (server only)
MYSQL_HOME
is an environment variable containing the path to the directory in which the server-specificmy.cnf
file resides. IfMYSQL_HOME
is not set and you start the server using themysqld_safe
program,mysqld_safe
sets it toBASEDIR
, the MySQL base installation directory.
file specified with --defaults-extra-file=path
if any
~/.my.cnf
- User-specific~/.mylogin.cnf
- User-specific (clients only)Source: Using Option Files.
Note: On Unix platforms, MySQL ignores configuration files that are world-writable. This is intentional as a security measure.
Additionally on Mac there is a simple way to check it.
Run: sudo fs_usage | grep my.cnf
This will report any filesystem activity in real-time related to that file.
In another Terminal, restart your MySQL/MariaDB, e.g.
brew services restart mysql
or:
brew services restart mariadb
On terminal with fs_usage
, the proper location should be shown, e.g.
15:52:22 access /usr/local/Cellar/mariadb/10.1.14/my.cnf 0.000002 sh
So if the file doesn't exist, create one.
You can place .; in classpath in environmental variables to overcome this problem.
Not entirely related to the question, but if the field injection is null, the constructor based injection will still work fine.
private OrderingClient orderingClient;
private Sales2Client sales2Client;
private Settings2Client settings2Client;
@Autowired
public BrinkWebTool(OrderingClient orderingClient, Sales2Client sales2Client, Settings2Client settings2Client) {
this.orderingClient = orderingClient;
this.sales2Client = sales2Client;
this.settings2Client = settings2Client;
}
I use this and it works right
@Id
@GeneratedValue(generator = "SEC_ODON", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "SEC_ODON", sequenceName = "SO.SEC_ODON",allocationSize=1)
@Column(name="ID_ODON", unique=true, nullable=false, precision=10, scale=0)
public Long getIdOdon() {
return this.idOdon;
}
You're on a 32-bit machine or a 64-bit Windows machine. On my 64-bit machine (running a Unix-derivative O/S, not Windows), sizeof(int) == 4
, but sizeof(long) == 8
.
They're different types — sometimes the same size as each other, sometimes not.
(In the really old days, sizeof(int) == 2
and sizeof(long) == 4
— though that might have been the days before C++ existed, come to think of it. Still, technically, it is a legitimate configuration, albeit unusual outside of the embedded space, and quite possibly unusual even in the embedded space.)
Try with <button type="submit">
you can perform the functionality of submitform()
by doing <form ....... onsubmit="submitform()">
What worked for me was to drag the folder into Visual Studio, then right click the folder and select "Open Folder in File Explorer". Then select all and drag them into the folder in Visual Studio.
Set the digits attribute to true, which will cause it to only allow number inputs.
Then do Integer.valueOf(editText.getText())
to get an int value out.
A little late to the party, but if you are looking for a solution like Yury's the following code will help you identify if the issue is related to a self-sign certificate and, if so ignore the self-sign error. You could obviously check for other SSL errors if you so desired.
The code we use (courtesy of Microsoft - http://msdn.microsoft.com/en-us/library/office/dd633677(v=exchg.80).aspx) is as follows:
private static bool CertificateValidationCallBack(
object sender,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
// If the certificate is a valid, signed certificate, return true.
if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
{
return true;
}
// If there are errors in the certificate chain, look at each error to determine the cause.
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
if (chain != null && chain.ChainStatus != null)
{
foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
{
if ((certificate.Subject == certificate.Issuer) &&
(status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
{
// Self-signed certificates with an untrusted root are valid.
continue;
}
else
{
if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
{
// If there are any other errors in the certificate chain, the certificate is invalid,
// so the method returns false.
return false;
}
}
}
}
// When processing reaches this line, the only errors in the certificate chain are
// untrusted root errors for self-signed certificates. These certificates are valid
// for default Exchange server installations, so return true.
return true;
}
else
{
// In all other cases, return false.
return false;
}
}
Let's assume your model is a collection of objects (or maybe a single object). For each object in the model do the following.
1) Put the object you want to display in the ViewBag. For example:
ViewBag.YourObject = yourObject;
2) Add a using statement at the top of _Layout.cshtml that contains the class definition for your objects. For example:
@using YourApplication.YourClasses;
3) When you reference yourObject in _Layout cast it. You can apply the cast because of what you did in (2).
Try this :
width:auto;
margin-right:50px;
If like me, you are using some micro VM lacking of memory, creating a swap file does the trick:
#Check free memory before
free -m
mkdir -p /var/_swap_
cd /var/_swap_
#Here, 1M * 2000 ~= 2GB of swap memory. Feel free to add MORE
dd if=/dev/zero of=swapfile bs=1M count=2000
chmod 600 swapfile
mkswap swapfile
swapon swapfile
#Automatically mount this swap partition at startup
echo "/var/_swap_/swapfile none swap sw 0 0" >> /etc/fstab
#Check free memory after
free -m
As several comments pointed out, don't forget to add sudo if you don't work as root.
btw, feel free to select another location/filename/size for the file.
/var
is probably not the best place, but I don't know which place would be, and rarely care since tiny servers are mostly used for testing purposes.