This issue happened to me after adding .dae and .png files and converting .dae with XCode Editor to SceneKit scene file format (.scn).
After doing some more research I found the solution here - https://forums.developer.apple.com/thread/109951#336225
Steps to solve the issue:
Use this command to update react npm install --save [email protected]
Don't forget to change 16.12.0 to the latest version or the version you need to setup.
Also, even at the lastest versions of pandas if the column is object type you would have to convert into float first, something like:
df['column_name'].astype(np.float).astype("Int32")
NB: You have to go through numpy float first and then to nullable Int32, for some reason.
The size of the int if it's 32 or 64 depends on your variable, be aware you may loose some precision if your numbers are to big for the format.
Find root build.gradle
file and add google maven repo inside allprojects
tag
repositories {
mavenLocal()
mavenCentral()
maven { // <-- Add this
url 'https://maven.google.com/'
name 'Google'
}
}
It's better to use specific version instead of variable version
compile 'com.android.support:appcompat-v7:27.0.0'
If you're using Android Plugin for Gradle 3.0.0 or latter version
repositories {
mavenLocal()
mavenCentral()
google() //---> Add this
}
and inject dependency in this way :
implementation 'com.android.support:appcompat-v7:27.0.0'
check that your web.php file has this extension
use Illuminate\Support\Facades\Route;
my problem gone fixed by this way.
I was having this same issue while my JAVA_HOME system variable was pointing to C:\Program Files\Java\jdk1.8.0_171\bin and my PATH entry consisted of just %JAVA_HOME%.
I changed my JAVA_HOME variable to exclude the bin folder (C:\Program Files\Java\jdk1.8.0_171), and added the bin folder to the system PATH variable: %JAVA_HOME%\bin,
If you have devtools like auto build dependency remove it. It is automatically build your project and run it. When you build manually it show port in use.
I got the same exception when I locally tested. The problem was a URL schema in my request.
Change https:// to http:// in your client url.
Probably it helps.
If you got any error on your console by saying, “Embedded servlet container failed to start. Port 8080 was already in use.” Then go to application.properties file and add this property “server.port = 8090”.
Actually the default port for spring boot is 8080, if you have something else on that port, the above error will occur. So we are asking spring boot to run on other port by adding “server.port = 8090” in application.properties file.
Working for about 4-5 years with software/firmware development and environment testing of miniaturized satellites*, I would like to share my experience here.
*(miniaturized satellites are a lot more prone to single event upsets than bigger satellites due to its relatively small, limited sizes for its electronic components)
To be very concise and direct: there is no mechanism to recover from detectable, erroneous situation by the software/firmware itself without, at least, one copy of minimum working version of the software/firmware somewhere for recovery purpose - and with the hardware supporting the recovery (functional).
Now, this situation is normally handled both in the hardware and software level. Here, as you request, I will share what we can do in the software level.
...recovery purpose.... Provide ability to update/recompile/reflash your software/firmware in real environment. This is an almost must-have feature for any software/firmware in highly ionized environment. Without this, you could have redundant software/hardware as many as you want but at one point, they are all going to blow up. So, prepare this feature!
...minimum working version... Have responsive, multiple copies, minimum version of the software/firmware in your code. This is like Safe mode in Windows. Instead of having only one, fully functional version of your software, have multiple copies of the minimum version of your software/firmware. The minimum copy will usually having much less size than the full copy and almost always have only the following two or three features:
...copy... somewhere... Have redundant software/firmware somewhere.
You could, with or without redundant hardware, try to have redundant software/firmware in your ARM uC. This is normally done by having two or more identical software/firmware in separate addresses which sending heartbeat to each other - but only one will be active at a time. If one or more software/firmware is known to be unresponsive, switch to the other software/firmware. The benefit of using this approach is we can have functional replacement immediately after an error occurs - without any contact with whatever external system/party who is responsible to detect and to repair the error (in satellite case, it is usually the Mission Control Centre (MCC)).
Strictly speaking, without redundant hardware, the disadvantage of doing this is you actually cannot eliminate all single point of failures. At the very least, you will still have one single point of failure, which is the switch itself (or often the beginning of the code). Nevertheless, for a device limited by size in a highly ionized environment (such as pico/femto satellites), the reduction of the single point of failures to one point without additional hardware will still be worth considering. Somemore, the piece of code for the switching would certainly be much less than the code for the whole program - significantly reducing the risk of getting Single Event in it.
But if you are not doing this, you should have at least one copy in your external system which can come in contact with the device and update the software/firmware (in the satellite case, it is again the mission control centre).
...detectable erroneous situation.. The error must be detectable, usually by the hardware error correction/detection circuit or by a small piece of code for error correction/detection. It is best to put such code small, multiple, and independent from the main software/firmware. Its main task is only for checking/correcting. If the hardware circuit/firmware is reliable (such as it is more radiation hardened than the rests - or having multiple circuits/logics), then you might consider making error-correction with it. But if it is not, it is better to make it as error-detection. The correction can be by external system/device. For the error correction, you could consider making use of a basic error correction algorithm like Hamming/Golay23, because they can be implemented more easily both in the circuit/software. But it ultimately depends on your team's capability. For error detection, normally CRC is used.
...hardware supporting the recovery Now, comes to the most difficult aspect on this issue. Ultimately, the recovery requires the hardware which is responsible for the recovery to be at least functional. If the hardware is permanently broken (normally happen after its Total ionizing dose reaches certain level), then there is (sadly) no way for the software to help in recovery. Thus, hardware is rightly the utmost importance concern for a device exposed to high radiation level (such as satellite).
In addition to the suggestion for above anticipating firmware's error due to single event upset, I would also like to suggest you to have:
Error detection and/or error correction algorithm in the inter-subsystem communication protocol. This is another almost must have in order to avoid incomplete/wrong signals received from other system
Filter in your ADC reading. Do not use the ADC reading directly. Filter it by median filter, mean filter, or any other filters - never trust single reading value. Sample more, not less - reasonably.
In windows first check under services if world wide web publishing services is running. If not start it.
If you cannot find it switch on IIS features of windows: In 7,8,10 it is under control panel , "turn windows features on or off". Internet Information Services World Wide web services and Internet information Services Hostable Core are required. Not sure if there is another way to get it going on windows, but this worked for me for all browsers. You might need to add localhost or http:/127.0.0.1 to the trusted websites also under IE settings.
If I want tranfer only the response variable y instead of a linear model with x specified, eg I wanna transfer/normalize a list of data, I can take 1 for x, then the object becomes a linear model:
library(MASS)
y = rf(500,30,30)
hist(y,breaks = 12)
result = boxcox(y~1, lambda = seq(-5,5,0.5))
mylambda = result$x[which.max(result$y)]
mylambda
y2 = (y^mylambda-1)/mylambda
hist(y2)
right click you project name then open the properties windows. downgrade your Target framework version, build Solution then upgrade your Target framework version to the latest, build Solution .
/* Microsoft Edge Browser 12-18 (All versions before Chromium) - one-liner method */
_:-ms-lang(x), _:-webkit-full-screen, .selector { property:value; }
That works great!
// for instance:
_:-ms-lang(x), _:-webkit-full-screen, .headerClass
{
border: 1px solid brown;
}
https://jeffclayton.wordpress.com/2015/04/07/css-hacks-for-windows-10-and-spartan-browser-preview/
The issue in my case was I included a constructor taking parameters but not an empty constructor with the Inject annotation, like so.
@Inject public VisitorBean() {}
I just tested it without any constructor and this appears to work also.
You should definitely have a look at this answer of mine:
and also have a look at all the links included therein.
Tabula/TabulaPDF is currently the best table extraction tool that is available for PDF scraping.
Make sure you have mod_rewrite enabled.
restart apache
and clear cookies of your browser for read again at .htaccess
I figured out the answer to above problem. Below query will return rows which have even a signle occurrence of characters besides alphabets, numbers, square brackets, curly brackets,s pace and dot. Please note that position of closing bracket ']' in matching pattern is important.
Right ']' has the special meaning of ending a character set definition. It wouldn't make any sense to end the set before you specified any members, so the way to indicate a literal right ']' inside square brackets is to put it immediately after the left '[' that starts the set definition
SELECT * FROM test WHERE REGEXP_LIKE(sampletext, '[^]^A-Z^a-z^0-9^[^.^{^}^ ]' );
This doesn't work because NaN
isn't equal to anything, including NaN
. Use pd.isnull(df.var2)
instead.
Simply put, abstraction is all about making necessary information for interaction with the object visible, while encapsulation enables a developer to implement the desired level of abstraction.
The database registers its service name(s) with the listener when it starts up. If it is unable to do so then it tries again periodically - so if the listener starts after the database then there can be a delay before the service is recognised.
If the database isn't running, though, nothing will have registered the service, so you shouldn't expect the listener to know about it - lsnrctl status
or lsnrctl services
won't report a service that isn't registered yet.
You can start the database up without the listener; from the Oracle account and with your ORACLE_HOME
, ORACLE_SID
and PATH
set you can do:
sqlplus /nolog
Then from the SQL*Plus prompt:
connect / as sysdba
startup
Or through the Grid infrastructure, from the grid account, use the srvctl start database
command:
srvctl start database -d db_unique_name [-o start_options] [-n node_name]
You might want to look at whether the database is set to auto-start in your oratab
file, and depending on what you're using whether it should have started automatically. If you're expecting it to be running and it isn't, or you try to start it and it won't come up, then that's a whole different scenario - you'd need to look at the error messages, alert log, possibly trace files etc. to see exactly why it won't start, and if you can't figure it out, maybe ask on Database Adminsitrators rather than on Stack Overflow.
If the database can't see +DATA
then ASM may not be running; you can see how to start that here; or using srvctl start asm
. As the documentation says, make sure you do that from the grid home, not the database home.
Here's my 2 cents.
I've also had the issue of the scrollIntoView scrolling a bit past the element, so I created a script (native javascript) that prepends an element to the destination, positioned it a bit to the top with css and scrolled to that one. After scrolling, I remove the created elements again.
HTML:
//anchor tag that appears multiple times on the page
<a href="#" class="anchors__link js-anchor" data-target="schedule">
<div class="anchors__text">
Scroll to the schedule
</div>
</a>
//The node we want to scroll to, somewhere on the page
<div id="schedule">
//html
</div>
Javascript file:
(() => {
'use strict';
const anchors = document.querySelectorAll('.js-anchor');
//if there are no anchors found, don't run the script
if (!anchors || anchors.length <= 0) return;
anchors.forEach(anchor => {
//get the target from the data attribute
const target = anchor.dataset.target;
//search for the destination element to scroll to
const destination = document.querySelector(`#${target}`);
//if the destination element does not exist, don't run the rest of the code
if (!destination) return;
anchor.addEventListener('click', (e) => {
e.preventDefault();
//create a new element and add the `anchors__generated` class to it
const generatedAnchor = document.createElement('div');
generatedAnchor.classList.add('anchors__generated');
//get the first child of the destination element, insert the generated element before it. (so the scrollIntoView function scrolls to the top of the element instead of the bottom)
const firstChild = destination.firstChild;
destination.insertBefore(generatedAnchor, firstChild);
//finally fire the scrollIntoView function and make it animate "smoothly"
generatedAnchor.scrollIntoView({
behavior: "smooth",
block: "start",
inline: "start"
});
//remove the generated element after 1ms. We need the timeout so the scrollIntoView function has something to scroll to.
setTimeout(() => {
destination.removeChild(generatedAnchor);
}, 1);
})
})
})();
CSS:
.anchors__generated {
position: relative;
top: -100px;
}
Hope this helps anyone!
sudo lsof -i:8080
By running the above command you can see what are all the jobs running.
kill -9 <PID Number>
Enter the PID (process identification number), so this will terminate/kill the instance.
Fabrício's answer is spot on; but I wanted to complement his answer with something less technical, which focusses on an analogy to help explain the concept of asynchronicity.
Yesterday, the work I was doing required some information from a colleague. I rang him up; here's how the conversation went:
Me: Hi Bob, I need to know how we foo'd the bar'd last week. Jim wants a report on it, and you're the only one who knows the details about it.
Bob: Sure thing, but it'll take me around 30 minutes?
Me: That's great Bob. Give me a ring back when you've got the information!
At this point, I hung up the phone. Since I needed information from Bob to complete my report, I left the report and went for a coffee instead, then I caught up on some email. 40 minutes later (Bob is slow), Bob called back and gave me the information I needed. At this point, I resumed my work with my report, as I had all the information I needed.
Imagine if the conversation had gone like this instead;
Me: Hi Bob, I need to know how we foo'd the bar'd last week. Jim want's a report on it, and you're the only one who knows the details about it.
Bob: Sure thing, but it'll take me around 30 minutes?
Me: That's great Bob. I'll wait.
And I sat there and waited. And waited. And waited. For 40 minutes. Doing nothing but waiting. Eventually, Bob gave me the information, we hung up, and I completed my report. But I'd lost 40 minutes of productivity.
This is exactly what is happening in all the examples in our question. Loading an image, loading a file off disk, and requesting a page via AJAX are all slow operations (in the context of modern computing).
Rather than waiting for these slow operations to complete, JavaScript lets you register a callback function which will be executed when the slow operation has completed. In the meantime, however, JavaScript will continue to execute other code. The fact that JavaScript executes other code whilst waiting for the slow operation to complete makes the behaviorasynchronous. Had JavaScript waited around for the operation to complete before executing any other code, this would have been synchronous behavior.
var outerScopeVar;
var img = document.createElement('img');
// Here we register the callback function.
img.onload = function() {
// Code within this function will be executed once the image has loaded.
outerScopeVar = this.width;
};
// But, while the image is loading, JavaScript continues executing, and
// processes the following lines of JavaScript.
img.src = 'lolcat.png';
alert(outerScopeVar);
In the code above, we're asking JavaScript to load lolcat.png
, which is a sloooow operation. The callback function will be executed once this slow operation has done, but in the meantime, JavaScript will keep processing the next lines of code; i.e. alert(outerScopeVar)
.
This is why we see the alert showing undefined
; since the alert()
is processed immediately, rather than after the image has been loaded.
In order to fix our code, all we have to do is move the alert(outerScopeVar)
code into the callback function. As a consequence of this, we no longer need the outerScopeVar
variable declared as a global variable.
var img = document.createElement('img');
img.onload = function() {
var localScopeVar = this.width;
alert(localScopeVar);
};
img.src = 'lolcat.png';
You'll always see a callback is specified as a function, because that's the only* way in JavaScript to define some code, but not execute it until later.
Therefore, in all of our examples, the function() { /* Do something */ }
is the callback; to fix all the examples, all we have to do is move the code which needs the response of the operation into there!
* Technically you can use eval()
as well, but eval()
is evil for this purpose
You might currently have some code similar to this;
function getWidthOfImage(src) {
var outerScopeVar;
var img = document.createElement('img');
img.onload = function() {
outerScopeVar = this.width;
};
img.src = src;
return outerScopeVar;
}
var width = getWidthOfImage('lolcat.png');
alert(width);
However, we now know that the return outerScopeVar
happens immediately; before the onload
callback function has updated the variable. This leads to getWidthOfImage()
returning undefined
, and undefined
being alerted.
To fix this, we need to allow the function calling getWidthOfImage()
to register a callback, then move the alert'ing of the width to be within that callback;
function getWidthOfImage(src, cb) {
var img = document.createElement('img');
img.onload = function() {
cb(this.width);
};
img.src = src;
}
getWidthOfImage('lolcat.png', function (width) {
alert(width);
});
... as before, note that we've been able to remove the global variables (in this case width
).
I guess anther way, possibly faster, to achieve this is
1) Use dict comprehension to get desired dict (i.e., taking 2nd col of each array)
2) Then use pd.DataFrame
to create an instance directly from the dict without loop over each col and concat.
Assuming your mat
looks like this (you can ignore this since your mat
is loaded from file):
In [135]: mat = {'a': np.random.randint(5, size=(4,2)),
.....: 'b': np.random.randint(5, size=(4,2))}
In [136]: mat
Out[136]:
{'a': array([[2, 0],
[3, 4],
[0, 1],
[4, 2]]), 'b': array([[1, 0],
[1, 1],
[1, 0],
[2, 1]])}
Then you can do:
In [137]: df = pd.DataFrame ({name:mat[name][:,1] for name in mat})
In [138]: df
Out[138]:
a b
0 0 0
1 4 1
2 1 0
3 2 1
[4 rows x 2 columns]
This is more a workaround than a real solution. You can create a new object test_data
with another column name:
left_join("names<-"(test_data, "name"), kantrowitz, by = "name")
name gender
1 john M
2 bill either
3 madison M
4 abby either
5 zzz <NA>
java.util.Date date;
Timestamp timestamp = resultSet.getTimestamp(i);
if (timestamp != null)
date = new java.util.Date(timestamp.getTime()));
Then format it the way you like.
You can track the value of each child input
by creating a separate InputField
component that manages the value of a single input
. For example the InputField
could be:
var InputField = React.createClass({
getInitialState: function () {
return({text: this.props.text})
},
onChangeHandler: function (event) {
this.setState({text: event.target.value})
},
render: function () {
return (<input onChange={this.onChangeHandler} value={this.state.text} />)
}
})
Now the value of each input
can be tracked within a separate instance of this InputField
component without creating separate values in the parent's state to monitor each child component.
add this at the top of file,
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
I had the same problem. Here's what I figured out:
=BDP(A1&"@BGN Corp", "Issuer_parent_eqy_ticker")
A1 being the ISINs. This will return the ticker number. Then just use the ticker number to get the price.
I think I can add something here.
I cannot or not easily use the debug tools or inspection tools like firebug to see which frame I am currently at and want to go to.
The XPATH/CSS selector etc. that the inspection tool told me doesn't work since the current frame is not the target one. e.g. I need to first switch to a sub-frame to be able to access/locate the element from XPATH or any other reference.
In short, the find_element()
or find_elements()
method doesn't apply in my case.
unless we use some fazzy search method.
use
find_elements()
withcontains(@id,"frame")
to filter out the potential frames.
e.g.
driver.find_elements(By.XPATH,'//*[contains(@id,"frame")]')
Then use switchTo()
to switch to that frame and hopefully the underlying XPATH for your target element can be accessed this time.
If you're similar unlucky like me, iteration might need to be done for the found frames and even iterate deeper in more layers.
e.g. This is the piece I use.
try:
elf1 = mydriver.find_elements(By.XPATH,'//*[contains(@id,"rame")]')
mydriver.switch_to_frame(elf1[1])
elf2 = mydriver.find_elements(By.XPATH,'//*[contains(@id,"rame")]')
mydriver.switch_to_frame(elf2[2])
len(mydriver.page_source) ## size of source tell whether I am in the right frame
I try out different switch_to_frame(elf1[x])
/switch_to_frame(elf2[x])
combinations and finally found the wanted element by the XPATH I found from the inspection tool in browser.
try:
element = WebDriverWait(mydriver, 10).until(
EC.presence_of_element_located((By.XPATH, '//*[@id="C4_W16_V17_ZSRV-HOME"]'))
)
#Click the link
element.click()
I had exactly the same problem (always seems to occur when I try to implement a Interface onto a userform. Download and install Code Cleaner from here. This is a freeware utility that has saved me on numerous occasions. With your VBA project open, run the "Clean Code..."
option. Make sure you check the "backup project" and/or "export all code modules" to safe locations before running the clean. As far as I understand it, this utility exports and then re-imports all modules and classes, which eliminates compiler errors that have crept into the code. Worked like a charm for me! Good luck.
I just had a same issue of none of my console message showing. It was simply because I was using the new Edge (Chromium based) browser on Windows 10. It does not show my console messages whereas Chrome does. I guessed it was an issue with Edge because I had another odd issue with Edge because it treated strings with single quotes and double quotes differently.
Visually you can open "SQL Server Configuration Manager" and check properties of "Network Configuration":
So after struggling with this issue for quite some time, this is what could help you:
from PIL import Image
instead of
import Image
Also, if your Image file is not loading and you're getting an error "No file or directory" then you should do this:
path=r'C:\ABC\Users\Pictures\image.jpg'
and then open the file
image=Image.open(path)
Step back: why are you even trying to detect "internet explorer" rather than "my website needs to do X, does this browser support that feature? If so, good browser. If not, then I should warn the user".
You should hit up http://modernizr.com/ instead of continuing what you're doing.
You could use this function I created to find the last instance of a string within a string.
Sure the accepted Excel formula works, but it's much too difficult to read and use. At some point you have to break out into smaller chunks so it's maintainable. My function below is readable, but that's irrelevant because you call it in a formula using named parameters. This makes using it simple.
Public Function FindLastCharOccurence(fromText As String, searchChar As String) As Integer
Dim lastOccur As Integer
lastOccur = -1
Dim i As Integer
i = 0
For i = Len(fromText) To 1 Step -1
If Mid(fromText, i, 1) = searchChar Then
lastOccur = i
Exit For
End If
Next i
FindLastCharOccurence = lastOccur
End Function
I use it like this:
=RIGHT(A2, LEN(A2) - FindLastCharOccurence(A2, "\"))
From version 0.8.0, dplyr
offers a handy function called group_split()
:
# On sample data from @Aus_10
df %>%
group_split(g)
[[1]]
# A tibble: 25 x 3
ran_data1 ran_data2 g
<dbl> <dbl> <fct>
1 2.04 0.627 A
2 0.530 -0.703 A
3 -0.475 0.541 A
4 1.20 -0.565 A
5 -0.380 -0.126 A
6 1.25 -1.69 A
7 -0.153 -1.02 A
8 1.52 -0.520 A
9 0.905 -0.976 A
10 0.517 -0.535 A
# … with 15 more rows
[[2]]
# A tibble: 25 x 3
ran_data1 ran_data2 g
<dbl> <dbl> <fct>
1 1.61 0.858 B
2 1.05 -1.25 B
3 -0.440 -0.506 B
4 -1.17 1.81 B
5 1.47 -1.60 B
6 -0.682 -0.726 B
7 -2.21 0.282 B
8 -0.499 0.591 B
9 0.711 -1.21 B
10 0.705 0.960 B
# … with 15 more rows
To not include the grouping column:
df %>%
group_split(g, keep = FALSE)
Based on quick inspection of google web, this would be CSS path to links in page list
ol[id="rso"] h3[class="r"] a
So you should do something like
String path = "ol[id='rso'] h3[class='r'] a";
driver.findElements(By.cssSelector(path)).get(2).click();
However you could also use xpath
which is not really recommended as a best practice and also JQuery locators but I am not sure if you can use them aynywhere else except inArquillian Graphene
why dont you add a "source" column to each of the queries with a static value like
select 'source 1' as Source, column1, column2...
from table1
UNION ALL
select 'source 2' as Source, column1, column2...
from table2
JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.
$("new").show();
$("new").hide();
start "" "%SYSTEMDRIVE%\Program Files (x86)\Git\bin\sh.exe" --login -i
Git bash will get open.
This answer is based on the title and not the specific case in the original post.
I had an insert procedure that kept throwing this annoying error, and even though the error says, "procedure....has too many arguments specified," the fact is that the procedure did NOT have enough arguments.
The table had an incremental id column, and since it is incremental, I did not bother to add it as a variable/argument to the proc, but it turned out that it is needed, so I added it as @Id and viola like they say...it works.
A simple tcp server I had for serving the flash policy file was causing this. I can now catch the error using a handler:
# serving the flash policy file
net = require("net")
net.createServer((socket) =>
//just added
socket.on("error", (err) =>
console.log("Caught flash policy server socket error: ")
console.log(err.stack)
)
socket.write("<?xml version=\"1.0\"?>\n")
socket.write("<!DOCTYPE cross-domain-policy SYSTEM \"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd\">\n")
socket.write("<cross-domain-policy>\n")
socket.write("<allow-access-from domain=\"*\" to-ports=\"*\"/>\n")
socket.write("</cross-domain-policy>\n")
socket.end()
).listen(843)
I think they are slightly different concepts, but often they are applied together. Encapsulation is a technique for hiding implementation details from the caller, whereas abstraction is more a design philosophy involving creating objects that are analogous to familiar objects/processes, to aid understanding. Encapsulation is just one of many techniques that can be used to create an abstraction.
For example, take "windows". They are not really windows in the traditional sense, they are just graphical squares on the screen. But it's useful to think of them as windows. That's an abstraction.
If the "windows API" hides the details of how the text or graphics is physically rendered within the boundaries of a window, that's encapsulation.
Previous answers assume that the array is a python standard list. As someone who uses numpy often, I'd recommend a very pythonic test of:
if hasattr(N, "__len__")
In entity relationship modeling, solid lines represent strong relationships and dashed lines represent weak relationships.
Open package.json and look under dependencies. You should see:
"dependencies": {
...
"bootstrap-less": "^3.8.8"
...
}
for angular 5 and over
In doubt change your editor to make tabs and spaces visible. It is also a very good idea to have the editor resolve all tabs to 4 spaces.
>>> a = ()
>>> type(a)
<type 'tuple'>
>>> a = []
>>> type(a)
<type 'list'>
>>> a = {}
>>> type(a)
<type 'dict'>
>>> a = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
>>> a.sort()
>>> a
['Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim', 'constitute']
>>>
There is a project on CodeProject that makes it simple to convert an XML file to SQL Script. It uses XSLT. You could probably modify it to generate the DDL too.
And See this question too : Generating SQL using XML and XSLT
Given the following sample
myData <- data.frame(A=rep(1:2, 3), B=rep(1:3, 2), Pulse=20:25)
then
myData$A <-as.factor(myData$A)
myData$B <-as.factor(myData$B)
or you could select your columns altogether and wrap it up nicely:
# select columns
cols <- c("A", "B")
myData[,cols] <- data.frame(apply(myData[cols], 2, as.factor))
levels(myData$A) <- c("long", "short")
levels(myData$B) <- c("1kg", "2kg", "3kg")
To obtain
> myData
A B Pulse
1 long 1kg 20
2 short 2kg 21
3 long 3kg 22
4 short 1kg 23
5 long 2kg 24
6 short 3kg 25
This is what I got from oracle documentation, but it is for oracle 10g release 2:
When you define a NUMBER variable, you can specify its precision (p) and scale (s) so that it is sufficiently, but not unnecessarily, large. Precision is the number of significant digits. Scale can be positive or negative. Positive scale identifies the number of digits to the right of the decimal point; negative scale identifies the number of digits to the left of the decimal point that can be rounded up or down.
The NUMBER data type is supported by Oracle Database standard libraries and operates the same way as it does in SQL. It is used for dimensions and surrogates when a text or INTEGER data type is not appropriate. It is typically assigned to variables that are not used for calculations (like forecasts and aggregations), and it is used for variables that must match the rounding behavior of the database or require a high degree of precision. When deciding whether to assign the NUMBER data type to a variable, keep the following facts in mind in order to maximize performance:
i have check in java version 1.6.0_32 multiple main method is working but there should one main method like public static void main(String []args) of type signature. Ex is here which i had tested.
public class mainoverload
{
public static void main(String a)
{
System.out.println("\nIts "+a);
}
public static void main(String args[])
{
System.out.println("\nIts public static void main\n");
mainoverload.main("Ankit");
mainoverload.main(15,23);
mainoverload.main(15);
}
public static void main(int a)
{
System.out.println("\nIts "+a);
}
public static void main(int a,int b)
{
System.out.println("\nIts "+a+" "+b);
}
}
Consider the easy, lightweight Java library EasyFlow. From their docs:
With EasyFlow you can:
- implement complex logic but keep your code simple and clean
- handle asynchronous calls with ease and elegance
- avoid concurrency by using event-driven programming approach
- avoid StackOverflow error by avoiding recursion
- simplify design, programming and testing of complex java applications
create table a1
(weddingTable INT(3),
tableSeat INT(3),
tableSeatID INT(6),
Name varchar(10));
insert into a1
(weddingTable, tableSeat, tableSeatID, Name)
values (001,001,001001,'Bob'),
(001,002,001002,'Joe'),
(001,003,001003,'Dan'),
(002,001,002001,'Mark');
create table a2
(weddingTable int(3),
tableSeat int(3),
Meal varchar(10));
insert into a2
(weddingTable, tableSeat, Meal)
values
(001,001,'Chicken'),
(001,002,'Steak'),
(001,003,'Salmon'),
(002,001,'Steak');
select x.*, y.Meal
from a1 as x
JOIN a2 as y ON (x.weddingTable = y.weddingTable) AND (x.tableSeat = y. tableSeat);
Try this it's simple and fast
SELECT T.name AS [TABLE NAME], I.rows AS [ROWCOUNT]
FROM sys.tables AS T
INNER JOIN sys.sysindexes AS I ON T.object_id = I.id
AND I.indid < 2 ORDER BY I.rows DESC
We can use splatting for this:
& $command @args
where @args
(automatic variable $args) is splatted into array of parameters.
Under PS, 5.1
Note that the type(numpy.ndarray)
is a type
itself and watch out for boolean and scalar types. Don't be too discouraged if it's not intuitive or easy, it's a pain at first.
See also: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.dtypes.html - https://github.com/machinalis/mypy-data/tree/master/numpy-mypy
>>> import numpy as np
>>> np.ndarray
<class 'numpy.ndarray'>
>>> type(np.ndarray)
<class 'type'>
>>> a = np.linspace(1,25)
>>> type(a)
<class 'numpy.ndarray'>
>>> type(a) == type(np.ndarray)
False
>>> type(a) == np.ndarray
True
>>> isinstance(a, np.ndarray)
True
Fun with booleans:
>>> b = a.astype('int32') == 11
>>> b[0]
False
>>> isinstance(b[0], bool)
False
>>> isinstance(b[0], np.bool)
False
>>> isinstance(b[0], np.bool_)
True
>>> isinstance(b[0], np.bool8)
True
>>> b[0].dtype == np.bool
True
>>> b[0].dtype == bool # python equivalent
True
More fun with scalar types, see: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.scalars.html#arrays-scalars-built-in
>>> x = np.array([1,], dtype=np.uint64)
>>> x[0].dtype
dtype('uint64')
>>> isinstance(x[0], np.uint64)
True
>>> isinstance(x[0], np.integer)
True # generic integer
>>> isinstance(x[0], int)
False # but not a python int in this case
# Try matching the `kind` strings, e.g.
>>> np.dtype('bool').kind
'b'
>>> np.dtype('int64').kind
'i'
>>> np.dtype('float').kind
'f'
>>> np.dtype('half').kind
'f'
# But be weary of matching dtypes
>>> np.integer
<class 'numpy.integer'>
>>> np.dtype(np.integer)
dtype('int64')
>>> x[0].dtype == np.dtype(np.integer)
False
# Down these paths there be dragons:
# the .dtype attribute returns a kind of dtype, not a specific dtype
>>> isinstance(x[0].dtype, np.dtype)
True
>>> isinstance(x[0].dtype, np.uint64)
False
>>> isinstance(x[0].dtype, np.dtype(np.uint64))
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: isinstance() arg 2 must be a type or tuple of types
# yea, don't go there
>>> isinstance(x[0].dtype, np.int_)
False # again, confusing the .dtype with a specific dtype
# Inequalities can be tricky, although they might
# work sometimes, try to avoid these idioms:
>>> x[0].dtype <= np.dtype(np.uint64)
True
>>> x[0].dtype <= np.dtype(np.float)
True
>>> x[0].dtype <= np.dtype(np.half)
False # just when things were going well
>>> x[0].dtype <= np.dtype(np.float16)
False # oh boy
>>> x[0].dtype == np.int
False # ya, no luck here either
>>> x[0].dtype == np.int_
False # or here
>>> x[0].dtype == np.uint64
True # have to end on a good note!
If you are not using jQuery then I would simply write a validation method that you can be fired when the form is submitted. The method can validate the text fields to make sure that they are not empty or the default value. The method will return a bool value and if it is false you can fire off your alert and assign classes to highlight the fields that did not pass validation.
HTML:
<form name="form1" method="" action="" onsubmit="return validateForm(this)">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="addressLine01" value="Address Line 1"/><br />
<input type="submit"/>
</form>
JavaScript:
function validateForm(form) {
var nameField = form.name;
var addressLine01 = form.addressLine01;
if (isNotEmpty(nameField)) {
if(isNotEmpty(addressLine01)) {
return true;
{
{
return false;
}
function isNotEmpty(field) {
var fieldData = field.value;
if (fieldData.length == 0 || fieldData == "" || fieldData == fieldData) {
field.className = "FieldError"; //Classs to highlight error
alert("Please correct the errors in order to continue.");
return false;
} else {
field.className = "FieldOk"; //Resets field back to default
return true; //Submits form
}
}
The validateForm method assigns the elements you want to validate and then in this case calls the isNotEmpty method to validate if the field is empty or has not been changed from the default value. it continuously calls the inNotEmpty method until it returns a value of true or if the conditional fails for that field it will return false.
Give this a shot and let me know if it helps or if you have any questions. of course you can write additional custom methods to validate numbers only, email address, valid URL, etc.
If you use jQuery at all I would look into trying out the jQuery Validation plug-in. I have been using it for my last few projects and it is pretty nice. Check it out if you get a chance. http://docs.jquery.com/Plugins/Validation
If you are running the script as an administrator, then the script can use the wmic command.
FOR /f "tokens=2 delims==" %%f IN ('wmic os get osarchitecture /value ^| find "="') DO SET "OS_ARCH=%%f"
IF "%OS_ARCH%"=="32-bit" GOTO :32bit
IF "%OS_ARCH%"=="64-bit" GOTO :64bit
ECHO OS Architecture %OS_ARCH% is not supported!
EXIT 1
:32bit
ECHO "32 bit Operating System"
GOTO :SUCCESS
:64bit
ECHO "64 bit Operating System"
GOTO :SUCCESS
:SUCCESS
EXIT 0
You can change your Date Format From dd/MM/yyyy
to yyyy-MM-dd
in following way:
string date = DateTime.ParseExact(SourceDate, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
Here, SourceDate
is variable in which you will get selected date.
I know its an old post. but I tried the http://scikit-learn.sourceforge.net/stable/ package. here is my code to find the cosine similarity. The question was how will you calculate the cosine similarity with this package and here is my code for that
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer
f = open("/root/Myfolder/scoringDocuments/doc1")
doc1 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc2")
doc2 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc3")
doc3 = str.decode(f.read(), "UTF-8", "ignore")
train_set = ["president of India",doc1, doc2, doc3]
tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix_train = tfidf_vectorizer.fit_transform(train_set) #finds the tfidf score with normalization
print "cosine scores ==> ",cosine_similarity(tfidf_matrix_train[0:1], tfidf_matrix_train) #here the first element of tfidf_matrix_train is matched with other three elements
Here suppose the query is the first element of train_set and doc1,doc2 and doc3 are the documents which I want to rank with the help of cosine similarity. then I can use this code.
Also the tutorials provided in the question was very useful. Here are all the parts for it part-I,part-II,part-III
the output will be as follows :
[[ 1. 0.07102631 0.02731343 0.06348799]]
here 1 represents that query is matched with itself and the other three are the scores for matching the query with the respective documents.
This question is old, but I wanted to add my two-cents. I read the question as " I want to run a query to my [my]SQL database and store the returned data as Pandas data structure [DataFrame]."
From the code it looks like you mean mysql database and assume you mean pandas DataFrame.
import MySQLdb as mdb
import pandas.io.sql as sql
from pandas import *
conn = mdb.connect('<server>','<user>','<pass>','<db>');
df = sql.read_frame('<query>', conn)
For example,
conn = mdb.connect('localhost','myname','mypass','testdb');
df = sql.read_frame('select * from testTable', conn)
This will import all rows of testTable into a DataFrame.
public Configuration()
{
AutomaticMigrationsEnabled = false;
// register mysql code generator
SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
}
I find out that connector 6.6.4 will not work with Entity Framework 5 but with Entity Framework 4.3. So to downgrade issue the following commands in the package manager console:
Uninstall-Package EntityFramework
Install-Package EntityFramework -Version 4.3.1
Finally I do Update-Database -Verbose again and voila! The schema and tables are created. Wait for the next version of connector to use it with Entity Framework 5.
File [menu] -> Settings -> maven -> importing and uncheck "use maven3 to import project"
ref: http://youtrack.jetbrains.com/issue/IDEA-98425 (which may have a few other ideas too)
Ran into this again, with IntelliJ 15 this time, which has no "use maven3 to import" option available anymore. The cause was that sometimes IntelliJ "doesn't parse maven dependencies right" and if it can't parse one of them right, it gives up on all of them, apparently. You can tell if this is the case by opening the maven projects tool window (View menu -> Tool Windows -> Maven Projects). Then expand one of your maven projects and its dependencies. If the dependencies are all underlined in red, "Houston, we have a problem".
You can actually see the real failure by mousing over the project name itself.
In my instance it said "Problems: No versions available for XXX" or "Failed to read descriptor for artifact org.xy.z" ref: https://youtrack.jetbrains.com/issue/IDEA-128846 and https://youtrack.jetbrains.com/issue/IDEA-152555
It seems in this case I was dealing with a jar that didn't have an associated pom file (in our maven nexus repo, and also my local repository). If this is also your problem, "urrent work around: if you do not actually need to use classes from that jar in your own code (for instance a transitive maven dependency only), you can actually get away with commenting it out from the pom (temporarily), maven project reload, and then uncomment it. Somehow after that point IntelliJ "remembers" its old working dependencies. Adding a maven transitive exclude temporarily might also do it, if you're running into it from transitive chain of dependencies."
Another thing that might help is to use a "newer version" of maven than the bundled 3.0.5. In order to set it up to use this as the default, close all your intellij windows, then open preferences -> build, execution and deployment -> build tools -> maven, and change the maven home directory, it should say "For default project" at the top when you adjust this, though you can adjust it for a particular project as well, as long as you "re import" after adjusting it.
Deleting your intellij cache folders (windows: HOMEPATH/.{IntellijIdea,IdeaC}XXX linux ~/.IdeaIC15) and/or uninstalling and reinstalling IntelliJ itself. This can also be done by going to File [menu] -> Invalidate Caches / Restart...
. Click invalidate and restart
. This will reindex your whole project and solve many hard-to-trace issues with IntelliJ.
The following code will fetch you desired results with duplicate items and their index values.
for i in set(mylist):
if mylist.count(i) > 1:
print(i, mylist.index(i))
You can easily auto-generate the C# code using: http://regexhero.net/tester/.
Its free.
Here is how I did it:
The website then auto-generates the .NET code:
string strRegex = @"\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}\b";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = @" {CD73FAD2-E226-4715-B6FA-14EDF0764162}.Debug|x64.ActiveCfg = Debug|x64";
string strReplace = @"""$0""";
return myRegex.Replace(strTargetString, strReplace);
For spring :
File inputFile = new ClassPathResource("\\chrome\\chromedriver.exe").getFile();
System.setProperty("webdriver.chrome.driver",inputFile.getCanonicalPath());
Try this and don't add anything Order allow,deny
and others:
AddHandler cgi-script .cgi .py
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Require all granted
Allow from all
</Directory>
sudo a2enmod cgi
sudo service apache2 restart
If you want to know the scroll position of a view, then you can use the following extension function on View class:
fun View?.onScroll(callback: (x: Int, y: Int) -> Unit) {
var oldX = 0
var oldY = 0
this?.viewTreeObserver?.addOnScrollChangedListener {
if (oldX != scrollX || oldY != scrollY) {
callback(scrollX, scrollY)
oldX = scrollX
oldY = scrollY
}
}
}
If you are on Windows, here is a PowerShell script that will print the 10 largest files in your repository:
$revision_objects = git rev-list --objects --all;
$files = $revision_objects.Split() | Where-Object {$_.Length -gt 0 -and $(Test-Path -Path $_ -PathType Leaf) };
$files | Get-Item -Force | select fullname, length | sort -Descending -Property Length | select -First 10
You can compare class tokens to each other, so you could use value.getClass() == Integer.class
. However, the simpler and more canonical way is to use instanceof
:
if (value instanceof Integer) {
System.out.println("This is an Integer");
} else if(value instanceof String) {
System.out.println("This is a String");
} else if(value instanceof Float) {
System.out.println("This is a Float");
}
Notes:
instanceof C
matches for subclasses of C
too. However, in this case all the classes listed are final
, so they have no subclasses. Thus instanceof
is probably fine here.as JB Nizet stated, such checks are not OO design. You may be able to solve this problem in a more OO way, e.g.
System.out.println("This is a(n) " + value.getClass().getSimpleName());
//this gets you both the item (myItem.value) and its index (myItem.i)
@foreach (var myItem in Model.Members.Select((value,i) => new {i, value}))
{
<li>The index is @myItem.i and a value is @myItem.value.Name</li>
}
More info on my blog post http://jimfrenette.com/2012/11/razor-foreach-loop-with-index/
Before dealing with the iterables and iterator the major factor that decide the iterable and iterator is sequence
Sequence: Sequence is the collection of data
Iterable: Iterable are the sequence type object that support __iter__
method.
Iter method: Iter method take sequence as an input and create an object which is known as iterator
Iterator: Iterator are the object which call next method and transverse through the sequence. On calling the next method it returns the object that it traversed currently.
example:
x=[1,2,3,4]
x is a sequence which consists of collection of data
y=iter(x)
On calling iter(x)
it returns a iterator only when the x object has iter method otherwise it raise an exception.If it returns iterator then y is assign like this:
y=[1,2,3,4]
As y is a iterator hence it support next()
method
On calling next method it returns the individual elements of the list one by one.
After returning the last element of the sequence if we again call the next method it raise an StopIteration error
example:
>>> y.next()
1
>>> y.next()
2
>>> y.next()
3
>>> y.next()
4
>>> y.next()
StopIteration
There's the TryParse method, which returns a bool indicating if the conversion was successful.
I agree with above answers, the best way to get country from ip address is Maxmind.
If you want to write code in java, you might want to use i.e. geoip-api-1.2.10.jar and geoIP dat files (GeoIPCity.dat), which can be found via google.
Following code may be useful for you to get almost all information related to location, I am also using the same code.
public static String getGeoDetailsUsingMaxmind(String ipAddress, String desiredValue)
{
Location getLocation;
String returnString = "";
try
{
String geoIPCity_datFile = System.getenv("AUTOMATION_HOME").concat("/tpt/GeoIP/GeoIPCity.dat");
LookupService isp = new LookupService(geoIPCity_datFile);
getLocation = isp.getLocation(ipAddress);
isp.close();
//Getting all location details
if(desiredValue.equalsIgnoreCase("latitude") || desiredValue.equalsIgnoreCase("lat"))
{
returnString = String.valueOf(getLocation.latitude);
}
else if(desiredValue.equalsIgnoreCase("longitude") || desiredValue.equalsIgnoreCase("lon"))
{
returnString = String.valueOf(getLocation.longitude);
}
else if(desiredValue.equalsIgnoreCase("countrycode") || desiredValue.equalsIgnoreCase("country"))
{
returnString = getLocation.countryCode;
}
else if(desiredValue.equalsIgnoreCase("countryname"))
{
returnString = getLocation.countryName;
}
else if(desiredValue.equalsIgnoreCase("region"))
{
returnString = getLocation.region;
}
else if(desiredValue.equalsIgnoreCase("metro"))
{
returnString = String.valueOf(getLocation.metro_code);
}
else if(desiredValue.equalsIgnoreCase("city"))
{
returnString = getLocation.city;
}
else if(desiredValue.equalsIgnoreCase("zip") || desiredValue.equalsIgnoreCase("postalcode"))
{
returnString = getLocation.postalCode;
}
else
{
returnString = "";
System.out.println("There is no value found for parameter: "+desiredValue);
}
System.out.println("Value of: "+desiredValue + " is: "+returnString + " for ip address: "+ipAddress);
}
catch (Exception e)
{
System.out.println("Exception occured while getting details from max mind. " + e);
}
finally
{
return returnString;
}
}
By specifying the @JoinColumn
on both models you don't have a two way relationship. You have two one way relationships, and a very confusing mapping of it at that. You're telling both models that they "own" the IDAIRLINE column. Really only one of them actually should! The 'normal' thing is to take the @JoinColumn
off of the @OneToMany
side entirely, and instead add mappedBy to the @OneToMany
.
@OneToMany(cascade = CascadeType.ALL, mappedBy="airline")
public Set<AirlineFlight> getAirlineFlights() {
return airlineFlights;
}
That tells Hibernate "Go look over on the bean property named 'airline' on the thing I have a collection of to find the configuration."
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes
. You set request header Content-Type: multipart/form-data; boundary=HereGoes
. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--
Use xpath selector (here's quick tutorial) instead of id:
#python:
from selenium.webdriver import Firefox
YOUR_PAGE_URL = 'http://mypage.com/'
NEXT_BUTTON_XPATH = '//input[@type="submit" and @title="next"]'
browser = Firefox()
browser.get(YOUR_PAGE_URL)
button = browser.find_element_by_xpath(NEXT_BUTTON_XPATH)
button.click()
Or, if you use "vanilla" Selenium, just use same xpath selector instead of button id:
NEXT_BUTTON_XPATH = '//input[@type="submit" and @title="next"]'
selenium.click(NEXT_BUTTON_XPATH)
Take a look at the following system stored procedures, which you can run in SQLServer Management Studio (SSMS):
Also, in SSMS, you can view locks and processes in different ways:
Different versions of SSMS put the activity monitor in different places. For example, SSMS 2008 and 2012 have it in the context menu when you right-click on a server node.
They way I did it was by selecting all of the data
select * from myTable
and then right-clicking on the result set and chose "Save results as..." a csv file.
Opening the csv file in Notepad++ I saw the LF characters not visible in SQL Server result set.
Check out Pathname and in particular Pathname#exist?
.
File and its FileTest module are perhaps simpler/more direct, but I find Pathname
a nicer interface in general.
LL(1) grammar is Context free unambiguous grammar which can be parsed by LL(1) parsers.
In LL(1)
For Checking grammar is LL(1) you can draw predictive parsing table. And if you find any multiple entries in table then you can say grammar is not LL(1).
Their is also short cut to check if the grammar is LL(1) or not . Shortcut Technique
For the above issue, first of all if suppose tables contains more than 1 primary key then first remove all those primary keys and add first AUTO INCREMENT field as primary key then add another required primary keys which is removed earlier. Set AUTO INCREMENT option for required field from the option area.
If you are working on windows, you can use pywin32
(old link: see update below).
I found an example here:
import win32com.client
wmi = win32com.client.GetObject ("winmgmts:")
for usb in wmi.InstancesOf ("Win32_USBHub"):
print usb.DeviceID
Update Apr 2020:
'pywin32' release versions from 218 and up can be found here at github. Current version 227.
event.target
returns the DOM element, so you can retrieve any property/ attribute that has a value; so, to answer your question more specifically, you will always be able to retrieve nodeName
, and you can retrieve href
and id
, provided the element has a href
and id
defined; otherwise undefined
will be returned.
However, inside an event handler, you can use this
, which is set to the DOM element as well; much easier.
$('foo').bind('click', function () {
// inside here, `this` will refer to the foo that was clicked
});
Very Clever and easy way to detect your string is contains only digits or not is this way:
string s = "12fg";
if(s.All(char.IsDigit))
{
return true; // contains only digits
}
else
{
return false; // contains not only digits
}
Remove element should clear out such errors. The reason behind this is the inherited settings. Your application will inherit some settings from its parent's config file and machine's (server) config files.
You can either remove such duplicates with the remove tag before adding them or make these tags non-inheritable in the upper level config files.
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
It's easy with git add -i
. Type a
(for "add untracked"), then *
(for "all"), then q
(to quit) and you're done.
To do it with a single command: echo -e "a\n*\nq\n"|git add -i
Use fileReader.readAsDataURL( fileObject )
, this will encode it to base64, which you can safely upload to your server.
After learning what it is all about, I thought to write a hopefully simpler explanation via analogy:
Read below for more details:
Think of a Hashcode as us trying to To Uniquely Identify Someone
I am a detective, on the look out for a criminal. Let us call him Mr Cruel. (He was a notorious murderer when I was a kid -- he broke into a house kidnapped and murdered a poor girl, dumped her body and he's still out on the loose - but that's a separate matter). Mr Cruel has certain peculiar characteristics that I can use to uniquely identify him amongst a sea of people. We have 25 million people in Australia. One of them is Mr Cruel. How can we find him?
Bad ways of Identifying Mr Cruel
Apparently Mr Cruel has blue eyes. That's not much help because almost half the population in Australia also has blue eyes.
Good ways of Identifying Mr Cruel
What else can i use? I know: I will use a fingerprint!
Advantages:
The above characteristics generally make for good hash functions.
So what's the deal with 'Collisions'?
So imagine if I get a lead and I find someone matching Mr Cruel's fingerprints. Does this mean I have found Mr Cruel?
........perhaps! I must take a closer look. If i am using SHA256 (a hashing function) and I am looking in a small town with only 5 people - then there is a very good chance I found him! But if I am using MD5 (another famous hashing function) and checking for fingerprints in a town with +2^1000 people, then it is a fairly good possibility that two entirely different people might have the same fingerprint.
So what is the benefit of all this anyways?
The only real benefit of hashcodes is if you want to put something in a hash table - and with hash tables you'd want to find objects quickly - and that's where the hash code comes in. They allow you to find things in hash tables really quickly. It's a hack that massively improves performance, but at a small expense of accuracy.
So let's imagine we have a hash table filled with people - 25 million suspects in Australia. Mr Cruel is somewhere in there..... How can we find him really quickly? We need to sort through them all: to find a potential match, or to otherwise acquit potential suspects. You don't want to consider each person's unique characteristics because that would take too much time. What would you use instead? You'd use a hashcode! A hashcode can tell you if two people are different. Whether Joe Bloggs is NOT Mr Cruel. If the prints don't match then you know it's definitely NOT Mr Cruel. But, if the finger prints do match then depending on the hash function you used, chances are already fairly good you found your man. But it's not 100%. The only way you can be certain is to investigate further: (i) did he/she have an opportunity/motive, (ii) witnesses etc etc.
When you are using computers if two objects have the same hash code value, then you again need to investigate further whether they are truly equal. e.g. You'd have to check whether the objects have e.g. the same height, same weight etc, if the integers are the same, or if the customer_id is a match, and then come to the conclusion whether they are the same. this is typically done perhaps by implementing an IComparer or IEquality interfaces.
Key Summary
So basically a hashcode is a finger print.
It takes a good 3 minutes to get your head around the above. Perhaps read it a few times till it makes sense. I hope this helps someone because it took a lot of grief for me to learn it all!
This also works:
public static Set<Integer> findDuplicates(List<Integer> input) {
List<Integer> copy = new ArrayList<Integer>(input);
for (Integer value : new HashSet<Integer>(input)) {
copy.remove(value);
}
return new HashSet<Integer>(copy);
}
Perhaps this is easier to read:
a2.all? { |e| a1.include?(e) }
You can also use array intersection:
(a1 & a2).size == a1.size
Note that size
is used here just for speed, you can also do (slower):
(a1 & a2) == a1
But I guess the first is more readable. These 3 are plain ruby (not rails).
The following works on SQL2008 and above. Provides a list of both stored procedures and functions.
select distinct [Table Name] = o.Name, [Found In] = sp.Name, sp.type_desc
from sys.objects o inner join sys.sql_expression_dependencies sd on o.object_id = sd.referenced_id
inner join sys.objects sp on sd.referencing_id = sp.object_id
and sp.type in ('P', 'FN')
where o.name = 'YourTableName'
order by sp.Name
Little hack for you:
/**
@method uniqueDeviceIdentifier
@abstract A unique device identifier is a hash value composed from various hardware identifiers such
as the device’s serial number. It is guaranteed to be unique for every device but cannot
be tied to a user account. [UIDevice Class Reference]
@return An 1-way hashed identifier unique to this device.
*/
+ (NSString *)uniqueDeviceIdentifier {
NSString *systemId = nil;
// We collect it as long as it is available along with a randomly generated ID.
// This way, when this becomes unavailable we can map existing users so the
// new vs returning counts do not break.
if (([[[UIDevice currentDevice] systemVersion] floatValue] < 6.0f)) {
SEL udidSelector = NSSelectorFromString(@"uniqueIdentifier");
if ([[UIDevice currentDevice] respondsToSelector:udidSelector]) {
systemId = [[UIDevice currentDevice] performSelector:udidSelector];
}
}
else {
systemId = [NSUUID UUID];
}
return systemId;
}
from collections import Counter
most_common,num_most_common = Counter(L).most_common(1)[0] # 4, 6 times
For older Python versions (< 2.7), you can use this recipe to create the Counter
class.
I first used the JavaScript code, it worked amazingly until a website did not click.
So I've found this solution:
First, import ActionChains for Python & active it:
from selenium.webdriver.common.action_chains import ActionChains
actions = ActionChains(driver)
To click on a specific point in your sessions use this:
actions.move_by_offset(X coordinates, Y coordinates).click().perform()
NOTE: The code above will only work if the mouse has not been touched, to reset the mouse coordinates use this:
actions.move_to_element_with_offset(driver.find_element_by_tag_name('body'), 0,0))
In Full:
actions.move_to_element_with_offset(driver.find_element_by_tag_name('body'), 0,0)
actions.move_by_offset(X coordinates, Y coordinates).click().perform()
If you are using the BackStack...and ONLY if you are using the back stack, then try this:
rivate Fragment returnToPreviousFragment() {
FragmentManager fm = getSupportFragmentManager();
Fragment topFrag = null;
int idx = fm.getBackStackEntryCount();
if (idx > 1) {
BackStackEntry entry = fm.getBackStackEntryAt(idx - 2);
topFrag = fm.findFragmentByTag(entry.getName());
}
fm.popBackStack();
return topFrag;
}
First off, I will second the nomination of python's logging framework. Be a little careful about how you use it, however. Specifically: let the logging framework expand your variables, don't do it yourself. For instance, instead of:
logging.debug("datastructure: %r" % complex_dict_structure)
make sure you do:
logging.debug("datastructure: %r", complex_dict_structure)
because while they look similar, the first version incurs the repr() cost even if it's disabled. The second version avoid this. Similarly, if you roll your own, I'd suggest something like:
def debug_stdout(sfunc):
print(sfunc())
debug = debug_stdout
called via:
debug(lambda: "datastructure: %r" % complex_dict_structure)
which will, again, avoid the overhead if you disable it by doing:
def debug_noop(*args, **kwargs):
pass
debug = debug_noop
The overhead of computing those strings probably doesn't matter unless they're either 1) expensive to compute or 2) the debug statement is in the middle of, say, an n^3 loop or something. Not that I would know anything about that.
If the logic parsing this knows that {"key": "slide0001.html", "value": "Looking Ahead"}
is a key/value pair, then you could transform it in an array and hold a few constants specifying which index maps to which key.
For example:
var data = ["slide0001.html", "Looking Ahead"];
var C_KEY = 0;
var C_VALUE = 1;
var value = data[C_VALUE];
So, now, your data can be:
[
["slide0001.html", "Looking Ahead"],
["slide0008.html", "Forecast"],
["slide0021.html", "Summary"]
]
If your parsing logic doesn't know ahead of time about the structure of the data, you can add some metadata to describe it. For example:
{ meta: { keys: [ "key", "value" ] },
data: [
["slide0001.html", "Looking Ahead"],
["slide0008.html", "Forecast"],
["slide0021.html", "Summary"]
]
}
... which would then be handled by the parser.
Well, there is an array type in recent Postgres versions (not 100% about PG 7.4). You can even index them, using a GIN or GIST index. The syntaxes are:
create table foo (
bar int[] default '{}'
);
select * from foo where bar && array[1] -- equivalent to bar && '{1}'::int[]
create index on foo using gin (bar); -- allows to use an index in the above query
But as the prior answer suggests, it will be better to normalize properly.
I had the same problem and specified CMAKE_MAKE_PROGRAM in a toolchain file, cmake didn't find it. Then I tried adding -D CMAKE_MAKE_PROGRAM=... in the command-line, then it worked. Then I tried changing the generator from "MinGW Makefiles" to "Unix Makefiles" and removed the -D CMAKE_MAKE_PROGRAM from the command-line, and then it worked also!
So for some reason when the generator is set to "MinGW Makefiles" then the CMAKE_MAKE_PROGRAM setting in the toolchain file is not effective, but for the "Unix Makefiles" generator it is.
Removing the web.config
-file from the IIS Directory Folder solves the problem.
If you want to examine elements inside a dataframe you should not be using ls()
which only looks at the names of objects in the current workspace (or if used inside a function in the current environment). Rownames or elements inside such objects are not visible to ls()
(unless of course you add an environment argument to the ls(.)
-call). Try using grep()
which is the workhorse function for pattern matching of character vectors:
result <- a[ grep("blue", a$x) , ] # Note need to use `a$` to get at the `x`
If you want to use subset then consider the closely related function grepl()
which returns a vector of logicals can be used in the subset argument:
subset(a, grepl("blue", a$x))
x
2 blue1
3 blue2
Edit: Adding one "proper" use of glob2rx within subset():
result <- subset(a, grepl(glob2rx("blue*") , x) )
result
x
2 blue1
3 blue2
I don't think I actually understood glob2rx
until I came back to this question. (I did understand the scoping issues that were ar the root of the questioner's difficulties. Anybody reading this should now scroll down to Gavin's answer and upvote it.)
I just created a simple script that will bring back the $_SERVER['REMOTE_ADDR'] and $_SERVER['SERVER_ADDR'] in IIS so you don't have to change every variable. Just paste this text in your php file that is included in every page.
/** IIS IP Check **/
if(!$_SERVER['SERVER_ADDR']){ $_SERVER['SERVER_ADDR'] = $_SERVER['LOCAL_ADDR']; }
if(!$_SERVER['REMOTE_ADDR']){ $_SERVER['REMOTE_ADDR'] = $_SERVER['LOCAL_ADDR']; }
You want:
document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;
As per the RFC 2109, to have a cookie available to all subdomains, you must put a .
in front of your domain.
Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com
).
There are no auto incrementing features in Oracle for a column. You need to create a SEQUENCE object. You can use the sequence like:
insert into table(batch_id, ...) values(my_sequence.nextval, ...)
...to return the next number. To find out the last created sequence nr (in your session), you would use:
my_sequence.currval
This site has several complete examples on how to use sequences.
What about to split the string and strip words punctuation?
w in [ws.strip(',.?!') for ws in p.split()]
Or working the case:
w.lower() in [ws.strip(',.?!') for ws in p.lower().split()]
Maybe that way:
def wsearch(word, phrase):
# Attention about punctuation and about split characters
punctuation = ',.?!'
return word.lower() in [words.strip(punctuation) for words in phrase.lower().split()]
Sample:
print(wsearch('CAr', 'I own a caR.'))
I didn't check performance...
A join statement is unnecessarily complicated in this situation. The original question only deals with deleting records for a given user from multiple tables at the same time. Intuitively, you might expect something like this to work:
DELETE FROM table1,table2,table3,table4 WHERE user_id='$user_id'
Of course, it doesn't. But rather than writing multiple statements (redundant and inefficient), using joins (difficult for novices), or foreign keys (even more difficult for novices and not available in all engines or existing datasets) you could simplify your code with a LOOP!
As a basic example using PHP (where $db is your connection handle):
$tables = array("table1","table2","table3","table4");
foreach($tables as $table) {
$query = "DELETE FROM $table WHERE user_id='$user_id'";
mysqli_query($db,$query);
}
Hope this helps someone!
Matplotlib does this by default.
E.g.:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)
plt.show()
And, as you may already know, you can easily add a legend:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)
plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')
plt.show()
If you want to control the colors that will be cycled through:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
plt.gca().set_color_cycle(['red', 'green', 'blue', 'yellow'])
plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)
plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')
plt.show()
If you're unfamiliar with matplotlib, the tutorial is a good place to start.
Edit:
First off, if you have a lot (>5) of things you want to plot on one figure, either:
Otherwise, you're going to wind up with a very messy plot! Be nice to who ever is going to read whatever you're doing and don't try to cram 15 different things onto one figure!!
Beyond that, many people are colorblind to varying degrees, and distinguishing between numerous subtly different colors is difficult for more people than you may realize.
That having been said, if you really want to put 20 lines on one axis with 20 relatively distinct colors, here's one way to do it:
import matplotlib.pyplot as plt
import numpy as np
num_plots = 20
# Have a look at the colormaps here and decide which one you'd like:
# http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html
colormap = plt.cm.gist_ncar
plt.gca().set_prop_cycle(plt.cycler('color', plt.cm.jet(np.linspace(0, 1, num_plots))))
# Plot several different functions...
x = np.arange(10)
labels = []
for i in range(1, num_plots + 1):
plt.plot(x, i * x + 5 * i)
labels.append(r'$y = %ix + %i$' % (i, 5*i))
# I'm basically just demonstrating several different legend options here...
plt.legend(labels, ncol=4, loc='upper center',
bbox_to_anchor=[0.5, 1.1],
columnspacing=1.0, labelspacing=0.0,
handletextpad=0.0, handlelength=1.5,
fancybox=True, shadow=True)
plt.show()
For Mac OS:
#ifdef __APPLE__
For MingW on Windows:
#ifdef __MINGW32__
For Linux:
#ifdef __linux__
For other Windows compilers, check this thread and this for several other compilers and architectures.
You can use numpy.nonzero to find zero.
>>> import numpy as np
>>> x = np.array([1,0,2,0,3,0,0,4,0,5,0,6]).reshape(4, 3)
>>> np.nonzero(x==0) # this is what you want
(array([0, 1, 1, 2, 2, 3]), array([1, 0, 2, 0, 2, 1]))
>>> np.nonzero(x)
(array([0, 0, 1, 2, 3, 3]), array([0, 2, 1, 1, 0, 2]))
Another option is instanceof:
Object o =...
if (o instanceof Number) {
double d = ((Number)o).doubleValue(); //this cast is safe
}
Removing only decimal part can be done as follows:
number.replace(/(\.\d+)+/,'');
This would convert 13.6667px into 13px (leaving units px untouched).
From at least python >= 3.3:
You can use the field nodename
and avoid using array indexing:
os.uname().nodename
Although, even the documentation of os.uname suggests using socket.gethostname()
I tried {CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;}
but it didn`t work for me, since my UI culture was different from my number/currency culture. So I suggest you to use:
CultureInfo currentCulture = Thread.CurrentThread.CurrentUICulture;
This will give you the culture your UI is (texts on windows, message boxes, etc).
I also faced this issue with Visual Studio(VS) 2010. More interestingly, I had several projects in my solution (Console application, WPF application, Windows Forms application) but it was failing only when, I was setting the "Console Application" type of project as start up project of the solution(Even for those which had literally no code or any additional assemblies referred apart from the default ones which come with project template itself).
Following change finally helped me nail down the issue: Go to project properties of the console application project (Alternatively, select project file in solution explorer and press Alt + Enter key combination) -> Go to Debug
tab -> Scroll to Enable Debuggers
section in right pane -> Check the Enable unmanaged code debugging
check box as shown in the snapshot below -> Click Floppy button in the toolbar to save project properties. Root cause of why it happened is still not known to me. Only thing I observed was that there were lot of windows updates which had got installed on my machine the previous night which mostly constituted of office updates and OS updates (More than a dozen KB articles).
Update: VS 2017 onward the setting name has changed as shown in the screenshot below:
:
is the delimiter of the slice syntax to 'slice out' sub-parts in sequences , [start:end]
[1:5] is equivalent to "from 1 to 5" (5 not included)
[1:] is equivalent to "1 to end"
[len(a):] is equivalent to "from length of a to end"
Watch https://youtu.be/tKTZoB2Vjuk?t=41m40s at around 40:00 he starts explaining that.
Works with tuples and strings, too.
This:
<table id="test">
<tr id="TEST1" >
<td align="left" valign="middle"><div align="right">Contact</div></td>
<td colspan="4" align="left" valign="middle">
<input type="text" id="contact1" size="20" /> Number
<input type="text" id="number1" size="20" />
</td>
<td>
<input type="button" value="Button 1" id="contact1" /></td>
</tr>
<tr id="TEST2" >
<td align="left" valign="middle"><div align="right">Contact</div></td>
<td colspan="4" align="left" valign="middle">
<input type="text" id="contact2" size="20" /> Number
<input type="text" id="number2" size="20" />
</td>
<td>
<input type="button" value="Button 1" id="contact2" />
</td>
</tr>
<tr id="TEST3" >
<td align="left" valign="middle"><div align="right">Contact</div></td>
<td colspan="4" align="left" valign="middle">
<input type="text" id="contact3" size="20" /> Number
<input type="text" id="number3" size="20" />
</td>
<td>
<input type="button" value="Button 1" id="contact2" />
</td>
</tr>
and javascript:
$(function() {
var bid, trid;
$('#test tr').click(function() {
trid = $(this).attr('id'); // table row ID
alert(trid);
});
});
It worked here!
The this Keyword is used to refer the current variable of a block, for example consider the below code(Just a exampple, so dont expect the standard JAVA Code):
Public class test{
test(int a) {
this.a=a;
}
Void print(){
System.out.println(a);
}
Public static void main(String args[]){
test s=new test(2);
s.print();
}
}
Thats it. the Output will be "2". If We not used the this keyword, then the output will be : 0
1) check if service declaration in manifest is nested in application tag
<application>
<service android:name="" />
</application>
2) check if your service.java
is in the same package or diff package as the activity
<application>
<!-- service.java exists in diff package -->
<service android:name="com.package.helper.service" />
</application>
<application>
<!-- service.java exists in same package -->
<service android:name=".service" />
</application>
I normally differentiate these two via this diagram:
Use PrimaryKeyJoinColumn
Use JoinColumn
As "@sarnold", aptly pointed out, any process can send signal to any other process, hence, one process can send SIGABORT to other process & in that case the receiving process is unable to distinguish whether its coming because of its own tweaking of memory etc, or someone else has "unicastly", send to it.
In one of the systems I worked there is one deadlock detector which actually detects if process is coming out of some task by giving heart beat or not. If not, then it declares the process is in deadlock state and sends SIGABORT to it.
I just wanted to share this prospective with reference to question asked.
Another way of doing it is a single listener from activity , like this:
public class MyActivity extends Activity implements OnClickListener {
....... code
//my listener
@Override
public void onClick(View v) {
if (v.getId() == R.id.mybutton) {
DoSomething();
return;
}
if (v.getId() == R.id.mybutton2) {
DoSomething2();
return;
}
}
}
I Like to do it with single IF instead of switch-else, but if you prefer that, then you should do:
//my listener
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.mybutton:
{
DoSomething();
break;
}
case R.id.mybutton2:
{
DoSomething();
break;
}
}
}
This did not work for me when I had done something like develop > release-v1.0.0 > feature-foo
, it would go all the way back to develop, note there was a rebase involved, not sure if that is compounding my issue...
The following did give the correct commit hash for me
git log --decorate \
| grep 'commit' \
| grep 'origin/' \
| head -n 2 \
| tail -n 1 \
| awk '{ print $2 }' \
| tr -d "\n"
Reset your email to the config globally:
git config --global user.email [email protected]
Now reset the author of your commit without edit required:
git commit --amend --reset-author --no-edit
Why not check if for nothing?
if not inputbox("bleh") = nothing then
'Code
else
' Error
end if
This is what i typically use, because its a little easier to read.
As far as the compiler is concerned, those two methods are identical. There will be one implementation of both.
This isn't a problem if the two methods are effectively identical, in that they should have the same implementation. If they are contractually different (as per the documentation for each interface), you'll be in trouble.
Another way to get this error is if you have a null item in a collection.
There would be two ways to define constants - const
and static final
, with the exact same semantics. Furthermore static final
describes the behaviour better than const
some times when you use android:windowSoftInputMode="stateAlwaysHidden"
in manifest activity or xml, that time it will lose keyboard focus. So first check for that property in your xml and manifest,if it is there just remove it. After add these option to manifest file in side activity android:windowSoftInputMode="adjustPan"
and add this property to listview in xml android:descendantFocusability="beforeDescendants"
I think you have not installed these features. see below in picture.
I also suffered from this problem some days ago. After installing this feature then I solved it. If you have not installed this feature then installed it.
Install Process:
If the lines in the file end with \r\n\000 then what works is to delete the \n\000 then replace the \r with \n.
tr -d '\n\000' <infile | tr '\r' '\n' >outfile
But what exactly is O(log n)
What it means precisely is "as n
tends towards infinity
, the time
tends towards a*log(n)
where a
is a constant scaling factor".
Or actually, it doesn't quite mean that; more likely it means something like "time
divided by a*log(n)
tends towards 1
".
"Tends towards" has the usual mathematical meaning from 'analysis': for example, that "if you pick any arbitrarily small non-zero constant k
, then I can find a corresponding value X
such that ((time/(a*log(n))) - 1)
is less than k
for all values of n
greater than X
."
In lay terms, it means that the equation for time may have some other components: e.g. it may have some constant startup time; but these other components pale towards insignificance for large values of n, and the a*log(n) is the dominating term for large n.
Note that if the equation were, for example ...
time(n) = a + blog(n) + cn + dnn
... then this would be O(n squared) because, no matter what the values of the constants a, b, c, and non-zero d, the d*n*n
term would always dominate over the others for any sufficiently large value of n.
That's what bit O notation means: it means "what is the order of dominant term for any sufficiently large n".
This Method to get Google Username:
public String getUsername() {
AccountManager manager = AccountManager.get(this);
Account[] accounts = manager.getAccountsByType("com.google");
List<String> possibleEmails = new LinkedList<String>();
for (Account account : accounts) {
// TODO: Check possibleEmail against an email regex or treat
// account.name as an email address only for certain account.type
// values.
possibleEmails.add(account.name);
}
if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
String email = possibleEmails.get(0);
String[] parts = email.split("@");
if (parts.length > 0 && parts[0] != null)
return parts[0];
else
return null;
} else
return null;
}
simple this method call ....
And Get Google User in Gmail id::
accounts = AccountManager.get(this).getAccounts();
Log.e("", "Size: " + accounts.length);
for (Account account : accounts) {
String possibleEmail = account.name;
String type = account.type;
if (type.equals("com.google")) {
strGmail = possibleEmail;
Log.e("", "Emails: " + strGmail);
break;
}
}
After add permission in manifest;
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
Tiers are nothing but the separation of concerns and in general the presentation layer (the forms or pages that is visible to the user) is separated from the data tier (the class or file interact with the database). This separation is done in order to improve the maintainability, scalability, re-usability, flexibility and performance as well.
A good explanations with demo code of 3-tier and 4-tier architecture can be read at http://www.dotnetfunda.com/articles/article71.aspx
To sort by MULTIPLE COLUMN (Sort by column_1
, and then sort by column_2
)
with open('unsorted.csv',newline='') as csvfile:
spamreader = csv.DictReader(csvfile, delimiter=";")
sortedlist = sorted(spamreader, key=lambda row:(row['column_1'],row['column_2']), reverse=False)
with open('sorted.csv', 'w') as f:
fieldnames = ['column_1', 'column_2', column_3]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for row in sortedlist:
writer.writerow(row)
Use below code gives you IMEI number:
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
System.out.println("IMEI::" + telephonyManager.getDeviceId());
try
{
}
catch (Exception err)
{
if (err is Web2PDFException)
DoWhatever();
}
but there is probably a better way of doing whatever it is you want.
OK, seems this is my final answer. We have 2 actual problems:
1. Print POSIX ID (pthread_t)
You can simply treat pthread_t as array of bytes with hex digits printed for each byte. So you aren't limited by some fixed size type. The only issue is byte order. You probably like if order of your printed bytes is the same as for simple "int" printed. Here is example for little-endian and only order should be reverted (under define?) for big-endian:
#include <pthread.h>
#include <stdio.h>
void print_thread_id(pthread_t id)
{
size_t i;
for (i = sizeof(i); i; --i)
printf("%02x", *(((unsigned char*) &id) + i - 1));
}
int main()
{
pthread_t id = pthread_self();
printf("%08x\n", id);
print_thread_id(id);
return 0;
}
2. Get shorter printable thread ID
In any of proposed cases you should translate real thread ID (posix) to index of some table. But there is 2 significantly different approaches:
2.1. Track threads.
You may track threads ID of all the existing threads in table (their pthread_create() calls should be wrapped) and have "overloaded" id function that get you just table index, not real thread ID. This scheme is also very useful for any internal thread-related debug an resources tracking. Obvious advantage is side effect of thread-level trace / debug facility with future extension possible. Disadvantage is requirement to track any thread creation / destruction.
Here is partial pseudocode example:
pthread_create_wrapper(...)
{
id = pthread_create(...)
add_thread(id);
}
pthread_destruction_wrapper()
{
/* Main problem is it should be called.
pthread_cleanup_*() calls are possible solution. */
remove_thread(pthread_self());
}
unsigned thread_id(pthread_t known_pthread_id)
{
return seatch_thread_index(known_pthread_id);
}
/* user code */
printf("04x", thread_id(pthread_self()));
2.2. Just register new thread ID.
During logging call pthread_self() and search internal table if it know thread. If thread with such ID was created its index is used (or re-used from previously thread, actually it doesn't matter as there are no 2 same IDs for the same moment). If thread ID is not known yet, new entry is created so new index is generated / used.
Advantage is simplicity. Disadvantage is no tracking of thread creation / destruction. So to track this some external mechanics is required.
find /path/to/dir/ -type f -name "*.py" -exec md5sum {} + | awk '{print $1}' | sort | md5sum
The find command lists all the files that end in .py. The md5sum is computed for each .py file. awk is used to pick off the md5sums (ignoring the filenames, which may not be unique). The md5sums are sorted. The md5sum of this sorted list is then returned.
I've tested this by copying a test directory:
rsync -a ~/pybin/ ~/pybin2/
I renamed some of the files in ~/pybin2.
The find...md5sum
command returns the same output for both directories.
2bcf49a4d19ef9abd284311108d626f1 -
Not logging but if you're troubleshooting slow running queries in realtime, you can query the pg_stat_activity
view to see which queries are active, the user/connection they came from, when they started, etc. Eg...
SELECT *
FROM pg_stat_activity
WHERE state = 'active'
See the pg_stat_activity
view docs.
As mentioned in the top ranked post, the following works with the Sizzle engine.
$('input:text[value=""]');
In the comments, it was noted that removing the :text
portion of the selector causes the selector to fail. I believe what's happening is that Sizzle actually relies on the browser's built in selector engine when possible. When :text
is added to the selector, it becomes a non-standard CSS selector and thereby must needs be handled by Sizzle itself. This means that Sizzle checks the current value of the INPUT, instead of the "value" attribute specified in the source HTML.
So it's a clever way to check for empty text fields, but I think it relies on a behavior specific to the Sizzle engine (that of using the current value of the INPUT instead of the attribute defined in the source code). While Sizzle might return elements that match this selector, document.querySelectorAll
will only return elements that have value=""
in the HTML. Caveat emptor.
I would query the information_schema - this has views that are much more readable than the underlying tables.
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%create%'
go to Start->Run
type inetmgr and press OK. If you get an IIS
configuration screen. It is installed, otherwise it isn't.
You can also check ControlPanel->Add Remove Programs
, Click Add Remove Windows Components
and look for IIS in the list of installed components.
EDIT
To Reinstall IIS.
Control Panel -> Add Remove Programs -> Click Add Remove Windows Components
Uncheck IIS box
Click next and follow prompts to UnInstall IIS
.
Insert your windows disc into the appropriate drive.
Control Panel -> Add Remove Programs -> Click Add Remove Windows Components
Check IIS box
Click next and follow prompts to Install IIS
.
Been doing it for years. Never run into a problem.
I usually set up my DB's to have one table that contains all the keys and the modified dates and such. Haven't run into a problem of duplicate keys ever.
The only drawback that it has is when you are writing some queries to find some information quickly you are doing a lot of copying and pasting of the keys. You don't have the short easy to remember ids anymore.
I had this error when the .NET version was wrong - make sure the site is configured to the one you need.
See aspnet_regiis.exe for details.
Just an update to this - I've been having a similar problem updating the action attribute of a form with jQuery.
After some testing it turns out that the command: $('#myForm').attr('action','new_url.html');
silently fails if the action attribute of the form is empty. If i update the action attribute of my form to contain some text, the jquery works.
I assume due diligence here that you confirmed the CPU is actually consumed by SQL process (perfmon Process category counters would confirm this). Normally for such cases you take a sample of the relevant performance counters and you compare them with a baseline that you established in normal load operating conditions. Once you resolve this problem I recommend you do establish such a baseline for future comparisons.
You can find exactly where is SQL spending every single CPU cycle. But knowing where to look takes a lot of know how and experience. Is is SQL 2005/2008 or 2000 ? Fortunately for 2005 and newer there are a couple of off the shelf solutions. You already got a couple good pointer here with John Samson's answer. I'd like to add a recommendation to download and install the SQL Server Performance Dashboard Reports. Some of those reports include top queries by time or by I/O, most used data files and so on and you can quickly get a feel where the problem is. The output is both numerical and graphical so it is more usefull for a beginner.
I would also recommend using Adam's Who is Active script, although that is a bit more advanced.
And last but not least I recommend you download and read the MS SQL Customer Advisory Team white paper on performance analysis: SQL 2005 Waits and Queues.
My recommendation is also to look at I/O. If you added a load to the server that trashes the buffer pool (ie. it needs so much data that it evicts the cached data pages from memory) the result would be a significant increase in CPU (sounds surprising, but is true). The culprit is usually a new query that scans a big table end-to-end.
I created multiple threads in Python, I printed the thread objects, and I printed the id using the ident
variable. I see all the ids are same:
<Thread(Thread-1, stopped 140500807628544)>
<Thread(Thread-2, started 140500807628544)>
<Thread(Thread-3, started 140500807628544)>
I guess this answer will just be lost in between all the other ones, but anyway, here goes.
I ended up on this question via Google because I wanted to check if a string
was numeric
so that I could just use double.Parse("123")
instead of the TryParse()
method.
Why? Because it's annoying to have to declare an out
variable and check the result of TryParse()
before you know if the parse failed or not. I want to use the ternary operator
to check if the string
is numerical
and then just parse it in the first ternary expression or provide a default value in the second ternary expression.
Like this:
var doubleValue = IsNumeric(numberAsString) ? double.Parse(numberAsString) : 0;
It's just a lot cleaner than:
var doubleValue = 0;
if (double.TryParse(numberAsString, out doubleValue)) {
//whatever you want to do with doubleValue
}
I made a couple extension methods
for these cases:
public static bool IsParseableAs<TInput>(this string value) {
var type = typeof(TInput);
var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
new[] { typeof(string), type.MakeByRefType() }, null);
if (tryParseMethod == null) return false;
var arguments = new[] { value, Activator.CreateInstance(type) };
return (bool) tryParseMethod.Invoke(null, arguments);
}
Example:
"123".IsParseableAs<double>() ? double.Parse(sNumber) : 0;
Because IsParseableAs()
tries to parse the string as the appropriate type instead of just checking if the string is "numeric" it should be pretty safe. And you can even use it for non numeric types that have a TryParse()
method, like DateTime
.
The method uses reflection and you end up calling the TryParse()
method twice which, of course, isn't as efficient, but not everything has to be fully optimized, sometimes convenience is just more important.
This method can also be used to easily parse a list of numeric strings into a list of double
or some other type with a default value without having to catch any exceptions:
var sNumbers = new[] {"10", "20", "30"};
var dValues = sNumbers.Select(s => s.IsParseableAs<double>() ? double.Parse(s) : 0);
public static TOutput ParseAs<TOutput>(this string value, TOutput defaultValue) {
var type = typeof(TOutput);
var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
new[] { typeof(string), type.MakeByRefType() }, null);
if (tryParseMethod == null) return defaultValue;
var arguments = new object[] { value, null };
return ((bool) tryParseMethod.Invoke(null, arguments)) ? (TOutput) arguments[1] : defaultValue;
}
This extension method lets you parse a string
as any type
that has a TryParse()
method and it also lets you specify a default value to return if the conversion fails.
This is better than using the ternary operator with the extension method above as it only does the conversion once. It still uses reflection though...
Examples:
"123".ParseAs<int>(10);
"abc".ParseAs<int>(25);
"123,78".ParseAs<double>(10);
"abc".ParseAs<double>(107.4);
"2014-10-28".ParseAs<DateTime>(DateTime.MinValue);
"monday".ParseAs<DateTime>(DateTime.MinValue);
Outputs:
123
25
123,78
107,4
28.10.2014 00:00:00
01.01.0001 00:00:00
A very contentious subject that I seem to have stumbled along here. However sometimes it's nice to head dear little-bobby tables off at the pass and send little Robert to the headmasters office along with his semi-colons and SQL comment lines --.
This REGEX in VB.NET includes regular alphabetic characters and various circumflexed european characters. However poor old James Mc'Tristan-Smythe the 3rd will have to input his pedigree in as the Jim the Third.
<asp:RegularExpressionValidator ID="RegExValid1" Runat="server"
ErrorMessage="ERROR: Please enter a valid surname<br/>" SetFocusOnError="true" Display="Dynamic"
ControlToValidate="txtSurname" ValidationGroup="MandatoryContent"
ValidationExpression="^[A-Za-z'\-\p{L}\p{Zs}\p{Lu}\p{Ll}\']+$">
In the example in the code you have posted there is, in fact, no point in catching the exception as there is nothing done on the catch it is just re-thown, in fact it does more harm than good as the call stack is lost.
You would, however catch an exception to do some logic (for example closing sql connection of file lock, or just some logging) in the event of an exception the throw it back to the calling code to deal with. This would be more common in a business layer than front end code as you may want the coder implementing your business layer to handle the exception.
To re-iterate though the There is NO point in catching the exception in the example you posted. DON'T do it like that!
Non-identifying relationship
A non-identifying relationship means that a child is related to parent but it can be identified by its own.
PERSON ACCOUNT
====== =======
pk(id) pk(id)
name fk(person_id)
balance
The relationship between ACCOUNT and PERSON is non-identifying.
Identifying relationship
An identifying relationship means that the parent is needed to give identity to child. The child solely exists because of parent.
This means that foreign key is a primary key too.
ITEM LANGUAGE ITEM_LANG
==== ======== =========
pk(id) pk(id) pk(fk(item_id))
name name pk(fk(lang_id))
name
The relationship between ITEM_LANG and ITEM is identifying. And between ITEM_LANG and LANGUAGE too.
label
is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center
but since the label is only as wide as the text you don't notice.
The best thing to do is to apply a specific width to the label
that is greater than the width of the content - this will give you the results you want.
SELECT l.*
FROM (
SELECT DISTINCT usr_id
FROM lives
) lo, lives l
WHERE l.ctid = (
SELECT ctid
FROM lives li
WHERE li.usr_id = lo.usr_id
ORDER BY
time_stamp DESC, trans_id DESC
LIMIT 1
)
Creating an index on (usr_id, time_stamp, trans_id)
will greatly improve this query.
You should always, always have some kind of PRIMARY KEY
in your tables.
Edit: Note that this answer is now out of date. See Siarhei Kuchuk's answer below for a better fix
UrlEncoding will do what you are suggesting here. With C#, you simply use HttpUtility
, as mentioned.
You can also Regex the illegal characters and then replace, but this gets far more complex, as you will have to have some form of state machine (switch ... case, for example) to replace with the correct characters. Since UrlEncode
does this up front, it is rather easy.
As for Linux versus windows, there are some characters that are acceptable in Linux that are not in Windows, but I would not worry about that, as the folder name can be returned by decoding the Url string, using UrlDecode
, so you can round trip the changes.
Here is the extension method to load an image from URI:
public static BitmapImage GetBitmapImage(
this Uri imageAbsolutePath,
BitmapCacheOption bitmapCacheOption = BitmapCacheOption.Default)
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = bitmapCacheOption;
image.UriSource = imageAbsolutePath;
image.EndInit();
return image;
}
Sample of use:
Uri _imageUri = new Uri(imageAbsolutePath);
ImageXamlElement.Source = _imageUri.GetBitmapImage(BitmapCacheOption.OnLoad);
Simple as that!
I had the same problem. The only solution that worked for me was adding <property = "defaultEncoding" value = "UTF-8"> to multipartResoler in spring configurations file.
Testers need to focus on the testing pyramid. You will want to understand unit tests, integration tests, and end to end tests. Each of these can be performed both with black box and white box testing. Start small and work your way up learning the different types and when to use each. remember you cant always test everything.
Acoording to RFC 2046 (Multipurpose Internet Mail Extensions):
The recommended action for an implementation that receives an
"application/octet-stream" entity is to simply offer to put the data in a file
So I'd go for that one.
Use this javascript function as an example on how to accomplish this.
function isNoIframeOrIframeInMyHost() {
// Validation: it must be loaded as the top page, or if it is loaded in an iframe
// then it must be embedded in my own domain.
// Info: IF top.location.href is not accessible THEN it is embedded in an iframe
// and the domains are different.
var myresult = true;
try {
var tophref = top.location.href;
var tophostname = top.location.hostname.toString();
var myhref = location.href;
if (tophref === myhref) {
myresult = true;
} else if (tophostname !== "www.yourdomain.com") {
myresult = false;
}
} catch (error) {
// error is a permission error that top.location.href is not accessible
// (which means parent domain <> iframe domain)!
myresult = false;
}
return myresult;
}
It depends which version of oracle you have, for 9i and below Statspack is what you are after, 10g and above, you want awr , both these tools will give you the top sql's and lots of other stuff.
Just a heads up, if you supply a body in your DELETE request and are using a google cloud HTTPS load balancer, it will reject your request with a 400 error. I was banging my head against a wall and came to found out that Google, for whatever reason, thinks a DELETE request with a body is a malformed request.
Strings aren't value types, and never will be ;-)
I'll go into differences at the hardware level, on x86. This is mostly irrelevant unless you're writing a compiler or using assembly language. But it's nice to know.
Firstly, x86 has native support for the two's complement representation of signed numbers. You can use other representations but this would require more instructions and generally be a waste of processor time.
What do I mean by "native support"? Basically I mean that there are a set of instructions you use for unsigned numbers and another set that you use for signed numbers. Unsigned numbers can sit in the same registers as signed numbers, and indeed you can mix signed and unsigned instructions without worrying the processor. It's up to the compiler (or assembly programmer) to keep track of whether a number is signed or not, and use the appropriate instructions.
Firstly, two's complement numbers have the property that addition and subtraction is just the same as for unsigned numbers. It makes no difference whether the numbers are positive or negative. (So you just go ahead and ADD
and SUB
your numbers without a worry.)
The differences start to show when it comes to comparisons. x86 has a simple way of differentiating them: above/below indicates an unsigned comparison and greater/less than indicates a signed comparison. (E.g. JAE
means "Jump if above or equal" and is unsigned.)
There are also two sets of multiplication and division instructions to deal with signed and unsigned integers.
Lastly: if you want to check for, say, overflow, you would do it differently for signed and for unsigned numbers.
Really, what you want to do cannot be done because the protocols do not allow for this. If static IPs were universally used then you might be able to do it. They are not, so you cannot.
If you really want to identify people, have them log in.
Since they will probably be moving around to different pages on your web site, you need a way to keep track of them as they move about.
So long as they are logged in, and you are tracking their session within your site via cookies/link-parameters/beacons/whatever, you can be pretty sure that they are using the same computer during that time.
Ultimately, it is incorrect to say this tells you which computer they are using if your users are not using your own local network and do not have static IP addresses.
If what you want to do is being done with the cooperation of the users and there is only one user per cookie and they use a single web browser, just use a cookie.
Eclipse can show/highlight code that can't be reached. JUnit can show you code coverage, but you'd need some tests and have to decide if the relevant test is missing or the code is really unused.
Depends on a lot of factors... List implementation, CPU architecture, JVM, loop semantics, complexity of equals method, etc... By the time the list gets big enough to effectively benchmark (1000+ elements), Hash-based binary lookups beat linear searches hands-down, and the difference only scales up from there.
Hope this helps!
Chrome Developer Tools has an Audits tab which can show unused CSS selectors.
Run an audit, then, under Web Page Performance see Remove unused CSS rules
Graphs are tough, because most non-trivial graph problems tend to require a decent amount of actual code to implement, if more than a sketch of an algorithm is required. A lot of it tends to come down to whether or not the candidate knows the shortest path and graph traversal algorithms, is familiar with cycle types and detection, and whether they know the complexity bounds. I think a lot of questions about this stuff comes down to trivia more than on the spot creative thinking ability.
I think problems related to trees tend to cover most of the difficulties of graph questions, but without as much code complexity.
I like the Project Euler problem that asks to find the most expensive path down a tree (16/67); common ancestor is a good warm up, but a lot of people have seen it. Asking somebody to design a tree class, perform traversals, and then figure out from which traversals they could rebuild a tree also gives some insight into data structure and algorithm implementation. The Stern-Brocot programming challenge is also interesting and quick to develop on a board (http://online-judge.uva.es/p/v100/10077.html).
You can try use simple command line. bcdedit is what you need, just run cmd as administrator and type bcdedit
or bcdedit \v
, this doesn't work on XP, but hope it is not an issue.
Anyway for XP you can take a look into boot.ini
file.
Encrypting the session value will have zero effect. The session cookie is already an arbitrary value, encrypting it will just generate another arbitrary value that can be sniffed.
The only real solution is HTTPS. If you don't want to do SSL on your whole site (maybe you have performance concerns), you might be able to get away with only SSL protecting the sensitive areas. To do that, first make sure your login page is HTTPS. When a user logs in, set a secure cookie (meaning the browser will only transmit it over an SSL link) in addition to the regular session cookie. Then, when a user visits one of your "sensitive" areas, redirect them to HTTPS, and check for the presence of that secure cookie. A real user will have it, a session hijacker will not.
EDIT: This answer was originally written in 2008. It's 2016 now, and there's no reason not to have SSL across your entire site. No more plaintext HTTP!
If you don't need any empty option at first, try this first line:
<option style="display:none"></option>
/**
* Usage "foo baz".insertInside(4, 0, "bar ") ==> "foo bar baz"
*/
String.prototype.insertInside = function(start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
$('textarea').bind("keydown keypress", function (event) {
var val = $(this).val();
var indexOf = $(this).prop('selectionStart');
if(event.which === 13) {
val = val.insertInside(indexOf, 0, "<br>\n");
$(this).val(val);
$(this).focus();
}
})
If you just want to get your HDFS back to normal state and don't worry much about the data, then
This will list the corrupt HDFS blocks:
hdfs fsck -list-corruptfileblocks
This will delete the corrupted HDFS blocks:
hdfs fsck / -delete
Note that, you might have to use sudo -u hdfs
if you are not the sudo user (assuming "hdfs" is name of the sudo user)
I had installed Python 32 bit version and psycopg2 64 bit version to get this problem. I installed psycopg2 32 bit version and then it worked.
There's no way to initiate a file transfer back to/from local Windows from a SSH session opened in PuTTY window.
Though PuTTY supports connection-sharing.
While you still need to run a compatible file transfer client (pscp
or psftp
), no new login is required, it automatically (if enabled) makes use of an existing PuTTY session.
To enable the sharing see:
Sharing an SSH connection between PuTTY tools.
Even without connection-sharing, you can still use the psftp
or pscp
from Windows command line.
See How to use PSCP to copy file from Unix machine to Windows machine ...?
Note that the scp
is OpenSSH program. It's primarily *nix program, but you can run it via Windows Subsystem for Linux or get a Windows build from Win32-OpenSSH (it is already built-in in the latest versions of Windows 10).
If you really want to download the files to a local desktop, you have to specify a target path as %USERPROFILE%\Desktop
(what typically resolves to a path like C:\Users\username\Desktop
).
Alternative way is to use WinSCP, a GUI SFTP/SCP client. While you browse the remote site, you can anytime open SSH terminal to the same site using Open in PuTTY command.
See Opening Session in PuTTY.
With an additional setup, you can even make PuTTY automatically navigate to the same directory you are browsing with WinSCP.
See Opening PuTTY in the same directory.
(I'm the author of WinSCP)
Put following line into your ".profile" file.
Open .profile file and copy this line
find ~/ -name '.DS_Store' -delete
When you open terminal window it will automatically delete your .DS_Store file for you.
you have defined the public dir in app root/public
app.use(express.static(__dirname + '/public'));
so you have to use:
./css/main.css
Another solution... I find this function more elegant, it will also remove the trailing '?' if the key to remove is the only one in the query string.
/**
* Remove a query string parameter from an URL.
*
* @param string $url
* @param string $varname
*
* @return string
*/
function removeQueryStringParameter($url, $varname)
{
$parsedUrl = parse_url($url);
$query = array();
if (isset($parsedUrl['query'])) {
parse_str($parsedUrl['query'], $query);
unset($query[$varname]);
}
$path = isset($parsedUrl['path']) ? $parsedUrl['path'] : '';
$query = !empty($query) ? '?'. http_build_query($query) : '';
return $parsedUrl['scheme']. '://'. $parsedUrl['host']. $path. $query;
}
Tests:
$urls = array(
'http://www.example.com?test=test',
'http://www.example.com?bar=foo&test=test2&foo2=dooh',
'http://www.example.com',
'http://www.example.com?foo=bar',
'http://www.example.com/test/no-empty-path/?foo=bar&test=test5',
'https://www.example.com/test/test.test?test=test6',
);
foreach ($urls as $url) {
echo $url. '<br/>';
echo removeQueryStringParameter($url, 'test'). '<br/><br/>';
}
Will output:
http://www.example.com?test=test
http://www.example.com
http://www.example.com?bar=foo&test=test2&foo2=dooh
http://www.example.com?bar=foo&foo2=dooh
http://www.example.com
http://www.example.com
http://www.example.com?foo=bar
http://www.example.com?foo=bar
http://www.example.com/test/no-empty-path/?foo=bar&test=test5
http://www.example.com/test/no-empty-path/?foo=bar
https://www.example.com/test/test.test?test=test6
https://www.example.com/test/test.test
Try to comment string "sql-mode=..." in file my.cnf and than restart mysql.
Step 1: Firstly, Go to the Settings in your real device whose device are used to run android app.
Step 2: After that go to the “About phone” if Developer Options is not shown in your device
Step 3: Then Tap 7 times on Build number to create Developer Options.
Step 4: After that go back and Developer options will be created in your device.
Step 5: After that go to Developer options and Enable USB debugging in your device as shown in figure below.
Step 6: Connect your device with your system via data cable and after that allow USB debugging message shown on your device and press OK.
Step 7: After that Go to the menu bar and Run app as shown in figure below.
Step 8: If real device is connected to your system then it will show Online. Now click on your Mobile phone device and you App will be run in real device.
Step 9: After that your Android app run in Real device.
Regards, Guruji Softwares (https://gurujisoftwares.com)
One totally different approach is to put things in a grid, such as ui-grid or Kendo's grid, and have the columns be resizable. A downside is that users would not be able to resize the rows, though the row size could be set programmatically.
This warning tries to improve accessibility of your application.
To disable missing content description warning in the whole project, you can add this to your application module build.gradle
android {
...
lintOptions {
disable 'ContentDescription'
}
}
Unfortunately for MSForms list box looping through the list items and checking their Selected property is the only way. However, here is an alternative. I am storing/removing the selected item in a variable, you can do this in some remote cell and keep track of it :)
Dim StrSelection As String
Private Sub ListBox1_Change()
If ListBox1.Selected(ListBox1.ListIndex) Then
If StrSelection = "" Then
StrSelection = ListBox1.List(ListBox1.ListIndex)
Else
StrSelection = StrSelection & "," & ListBox1.List(ListBox1.ListIndex)
End If
Else
StrSelection = Replace(StrSelection, "," & ListBox1.List(ListBox1.ListIndex), "")
End If
End Sub
Do this:
list(map(chr,[66,53,0,94]))
In Python 3+, many processes that iterate over iterables return iterators themselves. In most cases, this ends up saving memory, and should make things go faster.
If all you're going to do is iterate over this list eventually, there's no need to even convert it to a list, because you can still iterate over the map
object like so:
# Prints "ABCD"
for ch in map(chr,[65,66,67,68]):
print(ch)
You can use this:
response.sendRedirect(String.format("%s%s", request.getContextPath(), "/views/equipment/createEquipment.jsp"));
The last part is your path in your web-app
please use this code for input text
$('#search').on("input",function (e) {});
if you use .on("change",function (e) {});
then you need to blur input
if you use .on("keyup",function (e) {});
then you get value before the last character you typed
In the same way for Chrome Browser below are the things to be considered.
Step 1-->Import files Required for Chrome :
import org.openqa.selenium.chrome.*;
Step 2--> Set the Path and initialize the Chrome Driver:
System.setProperty("webdriver.chrome.driver","S:\\chromedriver_win32\\chromedriver.exe");
Note: In Step 2 the location should point the chromedriver.exe file's storage location in your system drive
step 3--> Create an instance of Chrome browser
WebDriver driver = new ChromeDriver();
Rest will be the same as...
icacls . /grant John:(OI)(CI)F /T
where John is the usernameJust adding this because it seemed supremely easy this way and others may profit - all credit goes to Calin Darie
.
string test = "<body><head>test header</head></body>";
XmlDocument xmltest = new XmlDocument();
xmltest.LoadXml(test);
XmlNodeList elemlist = xmltest.GetElementsByTagName("head");
string result = elemlist[0].InnerXml;
//result -> "test header"
I think what you are looking for is as follows.
cars_by_cylinders_gears <- mtcars %>%
group_by(cyl, gear) %>%
summarise(count = n())
This is using the dplyr package. This is essentially the longhand version of the count () solution provided by docendo discimus.
The system scans the SD card when it is mounted to find any new image (and other) files. If you are programmatically adding a file, then you can use this class:
http://developer.android.com/reference/android/media/MediaScannerConnection.html
.star-light::after {
content: "\f005";
font-family: "FontAwesome";
font-size: 3.2rem;
color: #fff;
font-weight: 900;
background-color: red;
}
Spring Boot uses embedded Tomcat by default, but it handles it differently without using tomcat-maven-plugin
. To change the port use --server.port
parameter for example:
java -jar target/gs-serving-web-content-0.1.0.jar --server.port=8181
Update. Alternatively put server.port=8181
into application.properties
(or application.yml
).
var count = 0;
//Parameters:
// array: []
// fnc: function (the business logic in form of function-,what you want to execute)
// delay: milisecond
function delayLoop(array,fnc,delay){
if(!array || array.legth == 0)return false;
setTimeout(function(data){
var data = array[count++];
fnc && fnc(data);
//recursion...
if(count < array.length)
delayLoop(array,fnc,delay);
else count = 0;
},delay);
}
Just to add up, I did something like this.
<select class="form-control" data-ng-model="itemSelect" ng-change="selectedTemplate(itemSelect)" autofocus>
<option value="undefined" [selected]="itemSelect.Name == undefined" disabled="disabled">Select template...</option>
<option ng-repeat="itemSelect in templateLists" value="{{itemSelect.ID}}">{{itemSelect.Name}}</option></select>
In Python3 You Can use this loop
with open('your_file.txt', 'w') as f:
for item in list:
f.print("", item)
Quite simply: echo str_replace('\'', '\\\'', $myString);
However, I'd suggest use of JSON and json_encode()
function as it will be more reliable (quotes new lines for instance):
<?php $data = array('myString' => '...'); ?>
<script>
var phpData = <?php echo json_encode($data) ?>;
alert(phpData.myString);
</script>
You can create new User library,
On
"Configure Build Paths" page -> Add Library -> User Library (on list) -> User Libraries Button (rigth side of page)
and create your library and (add Jars buttons) include your specific Jars.
I hope this can help you.
What about:
DECLARE @DOB datetime
SET @DOB='19851125'
SELECT Datepart(yy,convert(date,GETDATE())-@DOB)-1900
Wouldn't that avoid all those rounding, truncating and ofsetting issues?
Very easy to use select option submit
<select name="sortby" onchange="this.form.submit()">
<option value="">Featured</option>
<option value="asc" >Price: Low to High</option>
<option value="desc">Price: High to Low</option>
</select>
This code use and enjoy now:
Read More: Go Link
Write the code in your viewDidLoad()
self.view.layer.borderColor = anyColor().CGColor
And you can set Color
with RGB
func anyColor() -> UIColor {
return UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
}
Learn something about CALayer
in UIKit
Can't hurt to post another view since there's still not an official way to do this. Wrote a lightweight jQuery plugin with which you can define a background radial gradient and a transition speed. This basic usage will then let it fade in, optimised with requestAnimationFrame (very smooth) :
$('#element').gradientFade({
duration: 2000,
from: '(20,20,20,1)',
to: '(120,120,120,0)'
});
http://codepen.io/Shikkediel/pen/xbRaZz?editors=001
Keeps original background and all properties intact. Also has highlight tracking as a setting :
There's always the HTML5 download
attribute :
This attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource so that when the user clicks on the link they will be prompted to save it as a local file.
If the attribute has a value, the value will be used as the pre-filled file name in the Save prompt that opens when the user clicks on the link.
var A = [['n','sqrt(n)']];
for(var j=1; j<10; ++j){
A.push([j, Math.sqrt(j)]);
}
var csvRows = [];
for(var i=0, l=A.length; i<l; ++i){
csvRows.push(A[i].join(','));
}
var csvString = csvRows.join("%0A");
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + encodeURIComponent(csvString);
a.target = '_blank';
a.download = 'myFile.csv';
document.body.appendChild(a);
a.click();
Tested in Chrome and Firefox, works fine in the newest versions (as of July 2013).
Works in Opera as well, but does not set the filename (as of July 2013).
Does not seem to work in IE9 (big suprise) (as of July 2013).
An overview over what browsers support the download attribute can be found Here
For non-supporting browsers, one has to set the appropriate headers on the serverside.
Apparently there is a hack for IE10 and IE11, which doesn't support the download
attribute (Edge does however).
var A = [['n','sqrt(n)']];
for(var j=1; j<10; ++j){
A.push([j, Math.sqrt(j)]);
}
var csvRows = [];
for(var i=0, l=A.length; i<l; ++i){
csvRows.push(A[i].join(','));
}
var csvString = csvRows.join("%0A");
if (window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([csvString]);
window.navigator.msSaveOrOpenBlob(blob, 'myFile.csv');
} else {
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + encodeURIComponent(csvString);
a.target = '_blank';
a.download = 'myFile.csv';
document.body.appendChild(a);
a.click();
}
svn revert will undo any local changes you've made
var url = "www.stackoverflow.com"
let str = path.suffix(3)
print(str) //low
update VersionedFields
set Value = replace(replace(value,'<iframe','<a>iframe'), '> </iframe>','</a>')
and you do it in a single pass.
I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.
var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
.Select (m => new
{
UserName = u.UserProfile.UserName,
RoleName = u.Roles.RoleName
});
Query to show a 3-variable boolean expression truth table :
;WITH cteData AS
(SELECT 0 AS A, 0 AS B, 0 AS C
UNION ALL SELECT 0,0,1
UNION ALL SELECT 0,1,0
UNION ALL SELECT 0,1,1
UNION ALL SELECT 1,0,0
UNION ALL SELECT 1,0,1
UNION ALL SELECT 1,1,0
UNION ALL SELECT 1,1,1
)
SELECT cteData.*,
CASE WHEN
(A=1) OR (B=1) AND (C=1)
THEN 'True' ELSE 'False' END AS Result
FROM cteData
Results for (A=1) OR (B=1) AND (C=1)
:
A B C Result
0 0 0 False
0 0 1 False
0 1 0 False
0 1 1 True
1 0 0 True
1 0 1 True
1 1 0 True
1 1 1 True
Results for (A=1) OR ( (B=1) AND (C=1) )
are the same.
Results for ( (A=1) OR (B=1) ) AND (C=1)
:
A B C Result
0 0 0 False
0 0 1 False
0 1 0 False
0 1 1 True
1 0 0 False
1 0 1 True
1 1 0 False
1 1 1 True
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
Copy-and-paste version of the winner answer :)
Create this file with only this content:
$ sudo vi /etc/docker/daemon.json
{
"graph": "/my-docker-images"
}
Tested on Ubuntu 16.04.2 LTS
in docker 1.12.6
I'm successfully using the following to update options dynamically:
$control.select2('destroy').empty().select2({data: [{id: 1, text: 'new text'}]});
Had same problem - it was somewhere in the ca certificate, so I used the ca bundle used for curl, and it worked. You can download the curl ca bundle here: https://curl.haxx.se/docs/caextract.html
For encryption and security issues see this helpful article:
https://www.venditan.com/labs/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/432
Here is the example:
$url = 'https://www.example.com/api/list';
$cn_match = 'www.example.com';
$data = array (
'apikey' => '[example api key here]',
'limit' => intval($limit),
'offset' => intval($offset)
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
, 'ssl' => array(
'verify_peer' => true,
'cafile' => [path to file] . "cacert.pem",
'ciphers' => 'HIGH:TLSv1.2:TLSv1.1:TLSv1.0:!SSLv3:!SSLv2',
'CN_match' => $cn_match,
'disable_compression' => true,
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
Hope that helps
Just single if conditions
<select name="category_type[]" id="category_type" class="select2 m-b-10 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose" tooltip="Select Category Type">
@foreach ($categoryTypes as $categoryType)
<option value="{{ $categoryType->id }}"
**@if(in_array($categoryType->id,
request()->get('category_type')??[]))selected="selected"
@endif**>
{{ ucfirst($categoryType->title) }}</option>
@endforeach
</select>
Yes, this is correct, but it looks like a very basic workflow, where you're just buffering changes before they're ready for integration. You should look into more advanced workflows that git supports. You might like the topic branch approach, which lets you work on multiple features in parallel, or the graduation approach which extends your current workflow a bit.
In okhttp v4.* I got it working that way
// import the extensions!
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
// ...
json : String = "..."
val JSON : MediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody: RequestBody = json.toRequestBody(JSON)
// go on with Request.Builder() etc
Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.
To explain the differences as relevant to your posted example:
a. When you use RegisterStartupScript
, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.
Here is the rendered source of the page when you invoke the RegisterStartupScript
method:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
<form name="form1" method="post" action="StartupScript.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
</div>
<div> <span id="lblDisplayDate">Label</span>
<br />
<input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
<br />
<input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
</div>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
</div>
<!-- Note this part -->
<script language='javascript'>
var lbl = document.getElementById('lblDisplayDate');
lbl.style.color = 'red';
</script>
</form>
<!-- Note this part -->
</body>
</html>
b. When you use RegisterClientScriptBlock
, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.
Here is the rendered source of the page when you invoke the RegisterClientScriptBlock
method:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
<form name="form1" method="post" action="StartupScript.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
</div>
<script language='javascript'>
var lbl = document.getElementById('lblDisplayDate');
// Error is thrown in the next line because lbl is null.
lbl.style.color = 'green';
Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).
Edit after comments:
For instance, the following function would work:
protected void btnPostBack2_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language='javascript'>function ChangeColor() {");
sb.Append("var lbl = document.getElementById('lblDisplayDate');");
sb.Append("lbl.style.color='green';");
sb.Append("}</script>");
//Render the function definition.
if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString());
}
//Render the function invocation.
string funcCall = "<script language='javascript'>ChangeColor();</script>";
if (!ClientScript.IsStartupScriptRegistered("JSScript"))
{
ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall);
}
}
If you set the server output in ON mode before the entire code, it works, otherwise put_line() will not work. Try it!
The code is,
set serveroutput on;
CREATE OR REPLACE PROCEDURE PROC1(invoicenr IN NUMBER, amnt OUT NUMBER)
AS BEGIN
SELECT AMOUNT INTO amnt FROM INVOICE WHERE INVOICE_NR = invoicenr;
END;
And then call the function as it is:
DECLARE
amount NUMBER;
BEGIN
PROC1(1000001, amount);
dbms_output.put_line(amount);
END;
If you are receiving that error even after creating a new user and assigning them the database previledges, then the one last thing to look at is to check if the users have been assigned the preiveledges in the database.
To do this log into to your mysql(This is presumably its the application that has restricted access to the database but you as a root can be ablr to access your database table via mysql -u user -p)
commands to apply
mysql -u root -p
password: (provide your database credentials)
on successful login
type
use mysql;
from this point check each users priveledges if it is enabled from the db table as follows
select User,Grant_priv,Host from db;
if the values of the Grant_priv col for the created user is N update that value to Y with the following command
UPDATE db SET Grant_priv = "Y" WHERE User= "your user";
with that now try accessing the app and making a transaction with the database.
For a side-by-side visual representation, I use git difftool
with openDiff
set to the default viewer.
Example usage:
git difftool tags/<FIRST TAG> tags/<SECOND TAG>
If you are only interested in a specific file, you can use:
git difftool tags/<FIRST TAG>:<FILE PATH> tags/<SECOND TAG>:<FILE PATH>
As a side-note, the tags/<TAG>
s can be replaced with <BRANCH>
es if you are interested in diff
ing branches.
For the OpenSuse comrades out there:
sudo zypper install python3-devel
In java 8 , It's really easy to get timestamp in UTC by using java 8 java.time.Instant library :
Instant.now();
That few word of code will return the UTC Timestamp.
Using bitwise_and, bitwise_or, and bitwise_not you can modify any bit configurations to another bit configurations (i.e. these set of operators are "functionally complete"). However, for operations like modulus, the general formula would be necessarily be quite complicated, I wouldn't even bother trying to recreate it.
I've created a tool recently that does exactly what you want:
https://github.com/jd/git-pull-request
It automates everything in a single command, forking the repo, pushing the PR etc. It also supports updating the PR if you need to edit/fix it!
The clean way is to write your own directive to bind to "change" event. Just to let you know IE9 does not support FormData so you cannot really get the file object from the change event.
You can use ng-file-upload library which already supports IE with FileAPI polyfill and simplify the posting the file to the server. It uses a directive to achieve this.
<script src="angular.min.js"></script>
<script src="ng-file-upload.js"></script>
<div ng-controller="MyCtrl">
<input type="file" ngf-select="onFileSelect($files)" multiple>
</div>
JS:
//inject angular file upload directive.
angular.module('myApp', ['ngFileUpload']);
var MyCtrl = [ '$scope', 'Upload', function($scope, Upload) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
Upload.upload({
url: 'my/upload/url',
data: {file: $file}
}).then(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}
}
}];
You cannot instantiate an interface - you must provide a concrete implementation of IEnumerable.
You need to make your anchor display: block
or display: inline-block;
and then it will accept the width and height values.
timestamp is an object
timestamp= {nanoseconds: 0,_x000D_
seconds: 1562524200}_x000D_
_x000D_
console.log(new Date(timestamp.seconds*1000))
_x000D_
To avoid this error, you should use javac command with .java extension.
Javac DescendingOrder.java <- this work perfectly.
You could ignore SIGINTs after shutdown starts by calling signal.signal(signal.SIGINT, signal.SIG_IGN)
before you start your cleanup code.
Here's my regexp pure JavaScript solution:
function highlight(text) {
document.body.innerHTML = document.body.innerHTML.replace(
new RegExp(text + '(?!([^<]+)?<)', 'gi'),
'<b style="background-color:#ff0;font-size:100%">$&</b>'
);
}
the pom.xml for the project I have doesn't have this "http://repo1.maven.org/myurlhere" anywhere in it
All projects have http://repo1.maven.org/ declared as <repository>
(and <pluginRepository>
) by default. This repository, which is called the central repository, is inherited like others default settings from the "Super POM" (all projects inherit from the Super POM). So a POM is actually a combination of the Super POM, any parent POMs and the current POM. This combination is called the "effective POM" and can be printed using the effective-pom
goal of the Maven Help plugin (useful for debugging).
And indeed, if you run:
mvn help:effective-pom
You'll see at least the following:
<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Maven Repository Switchboard</name>
<url>http://repo1.maven.org/maven2</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Maven Plugin Repository</name>
<url>http://repo1.maven.org/maven2</url>
</pluginRepository>
</pluginRepositories>
it has the absolute url where the maven repo is for the project but maven is still trying to download from the general maven repo
Maven will try to find dependencies in all repositories declared, including in the central one which is there by default as we saw. But, according to the trace you are showing, you only have one repository defined (the central repository) or maven would print something like this:
Reason: Unable to download the artifact from any repository
url.project:project:pom:x.x
from the specified remote repositories:
central (http://repo1.maven.org/),
another-repository (http://another/repository)
So, basically, maven is unable to find the url.project:project:pom:x.x
because it is not available in central.
But without knowing which project you've checked out (it has maybe specific instructions) or which dependency is missing (it can maybe be found in another repository), it's impossible to help you further.
Maybe this will help
http://www.math.utah.edu/docs/info/gawk_5.html
awk '$3 ~ /snow|snowman/' dummy_file
Looks like a server issue (i.e. a "GitHub" issue).
If you look at this thread, it can happen when the git-http-backend
gets a corrupted heap.(and since they just put in place a smart http support...)
But whatever the actual cause is, it may also be related with recent sporadic disruption in one of the GitHub fileserver.
Do you still see this error message? Because if you do:
Note: the Smart HTTP Support is a big deal for those of us behind an authenticated-based enterprise firewall proxy!
From now on, if you clone a repository over the
http://
url and you are using a Git client version 1.6.6 or greater, Git will automatically use the newer, better transport mechanism.
Even more amazing, however, is that you can now push over that protocol and clone private repositories as well. If you access a private repository, or you are a collaborator and want push access, you can put your username in the URL and Git will prompt you for the password when you try to access it.Older clients will also fall back to the older, less efficient way, so nothing should break - just newer clients should work better.
So again, make sure to upgrade your Git client first.
This works for me using the normal wc -l
and sed
to strip any char what is not a number.
wc -l big_file.log | sed -E "s/([a-z\-\_\.]|[[:space:]]*)//g"
# 9249133
Yes, it is. There are better ways to bootstrap Hibernate, like the following ones.
The legacy Configuration
object is less powerful than using the BootstrapServiceRegistryBuilder
, introduced since Hibernate 4:
final BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder()
.enableAutoClose();
Integrator integrator = integrator();
if (integrator != null) {
bsrb.applyIntegrator( integrator );
}
final BootstrapServiceRegistry bsr = bsrb.build();
final StandardServiceRegistry serviceRegistry =
new StandardServiceRegistryBuilder(bsr)
.applySettings(properties())
.build();
final MetadataSources metadataSources = new MetadataSources(serviceRegistry);
for (Class annotatedClass : entities()) {
metadataSources.addAnnotatedClass(annotatedClass);
}
String[] packages = packages();
if (packages != null) {
for (String annotatedPackage : packages) {
metadataSources.addPackage(annotatedPackage);
}
}
String[] resources = resources();
if (resources != null) {
for (String resource : resources) {
metadataSources.addResource(resource);
}
}
final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder()
.enableNewIdentifierGeneratorSupport(true)
.applyImplicitNamingStrategy(ImplicitNamingStrategyLegacyJpaImpl.INSTANCE);
final List<Type> additionalTypes = additionalTypes();
if (additionalTypes != null) {
additionalTypes.stream().forEach(type -> {
metadataBuilder.applyTypes((typeContributions, sr) -> {
if(type instanceof BasicType) {
typeContributions.contributeType((BasicType) type);
} else if (type instanceof UserType ){
typeContributions.contributeType((UserType) type);
} else if (type instanceof CompositeUserType) {
typeContributions.contributeType((CompositeUserType) type);
}
});
});
}
additionalMetadata(metadataBuilder);
MetadataImplementor metadata = (MetadataImplementor) metadataBuilder.build();
final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder();
Interceptor interceptor = interceptor();
if(interceptor != null) {
sfb.applyInterceptor(interceptor);
}
SessionFactory sessionFactory = sfb.build();
You can also bootstrap Hibernate using JPA:
PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName());
Map configuration = properties();
Interceptor interceptor = interceptor();
if (interceptor != null) {
configuration.put(AvailableSettings.INTERCEPTOR, interceptor);
}
Integrator integrator = integrator();
if (integrator != null) {
configuration.put(
"hibernate.integrator_provider",
(IntegratorProvider) () -> Collections.singletonList(integrator));
}
EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder =
new EntityManagerFactoryBuilderImpl(
new PersistenceUnitInfoDescriptor(persistenceUnitInfo),
configuration
);
EntityManagerFactory entityManagerFactory = entityManagerFactoryBuilder.build();
This way, you are building the EntityManagerFactory
instead of a SessionFactory
. However, the SessionFactory
extends the EntityManagerFactory, so the actual object that's built is a
SessionFactoryImpl` too.
These two bootstrapping methods affect Hibernate behavior. When using the native bootstrap, Hibernate behaves in the legacy mode, which predates JPA.
When bootstrapping using JPA, Hibernate will behave according to the JPA specification.
There are several differences between these two modes:
EntityNotFoundException
, therefore demanding a DB check.For more details about these differences, check out the
JpaCompliance
class.
You can't select a sheet in a non-active workbook.
You must first activate the workbook, then you can select the sheet.
workbooks("A").activate
workbooks("A").worksheets("B").select
When you use Activate it automatically activates the workbook.
Note you can select >1 sheet in a workbook:
activeworkbook.sheets(array("sheet1","sheet3")).select
but only one sheet can be Active, and if you activate a sheet which is not part of a multi-sheet selection then those other sheets will become un-selected.
You can have a look on these built-in classes :
When your website is served by only one web server, for each client-server pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.
However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 web servers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.
Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on three independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session.
If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.
To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.
As an example, you may read about Amazon's Elastic Load Balancer and sticky sessions here : http://aws.typepad.com/aws/2010/04/new-elastic-load-balancing-feature-sticky-sessions.html
Declare native count queries for pagination at the query method by using @Query
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1",
countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
nativeQuery = true)
Page<User> findByLastname(String lastname, Pageable pageable);
}
Hope this helps
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods
"<name> <substring>"[/.*<([^>]*)/,1]
=> "substring"
No need to use scan
, if we need only one result.
No need to use Python's match
, when we have Ruby's String[regexp,#]
.
See: http://ruby-doc.org/core/String.html#method-i-5B-5D
Note: str[regexp, capture] ? new_str or nil
The lambda:
() -> { System.out.println("Do nothing!"); };
actually represents an implementation for an interface like:
public interface Something {
void action();
}
which is completely different than the one you've defined. That's why you get an error.
Since you can't extend your @FunctionalInterface
, nor introduce a brand new one, then I think you don't have much options. You can use the Optional<T>
interfaces to denote that some of the values (return type or method parameter) is missing, though. However, this won't make the lambda body simpler.
#include <boost/multi_array.hpp>
int main(){
int rows;
int cols;
boost::multi_array<int, 2> arr(boost::extents[rows][cols] ;
}
Indeed, there is type conversion to int. Also you can force type to char by using %hhx specifier.
printf("%hhX", a);
In most cases you will want to set the minimum length as well to fill the second character with zeroes:
printf("%02hhX", a);
ISO/IEC 9899:201x says:
7 The length modifiers and their meanings are: hh Specifies that a following d, i, o, u, x, or X conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing); or that a following
You can return an object of a Class in Java.
If you are returning more than 1 value that are related, then it makes sense to encapsulate them into a class and then return an object of that class.
If you want to return unrelated values, then you can use Java's built-in container classes like Map, List, Set etc. Check the java.util package's JavaDoc for more details.
Android Studio & Windows :
fn + alt + insert
If you don't have to support old IE versions, using the Option
constructor is clearly the way to go, a readable and efficient solution:
$(new Option('myText', 'val')).appendTo('#mySelect');
It's equivalent in functionality to, but cleaner than:
$("<option></option>").attr("value", "val").text("myText")).appendTo('#mySelect');
You need to type result
to an array of string const result: string[] = [];
.
If you want to create a file and write and append data to it many times, then use the below code, it will create file if not exits and will append data if it exists.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt";//like 2016_01_12.txt
try
{
File root = new File(Environment.getExternalStorageDirectory()+File.separator+"Music_Folder", "Report Files");
//File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, fileName);
FileWriter writer = new FileWriter(gpxfile,true);
writer.append(sBody+"\n\n");
writer.flush();
writer.close();
Toast.makeText(this, "Data has been written to Report File", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
Might just be for Visual Studio '15, if you right-click on source code, there's an option for insert comment
This puts summary
tags around your comment section, but it does give the indentation that you want.
Getting the ball rolling with this community wiki answer. Feel free to edit me with your improvements.
ws WebSocket server and client for node.js. One of the fastest libraries if not the fastest one.
websocket-node WebSocket server and client for node.js
websocket-driver-node WebSocket server and client protocol parser node.js - used in faye-websocket-node
faye-websocket-node WebSocket server and client for node.js - used in faye and sockjs
socket.io WebSocket server and client for node.js + client for browsers + (v0 has newest to oldest fallbacks, v1 of Socket.io uses engine.io) + channels - used in stack.io. Client library tries to reconnect upon disconnection.
sockjs WebSocket server and client for node.js and others + client for browsers + newest to oldest fallbacks
faye WebSocket server and client for node.js and others + client for browsers + fallbacks + support for other server-side languages
deepstream.io clusterable realtime server that handles WebSockets & TCP connections and provides data-sync, pub/sub and request/response
socketcluster WebSocket server cluster which makes use of all CPU cores on your machine. For example, if you were to use an xlarge Amazon EC2 instance with 32 cores, you would be able to handle almost 32 times the traffic on a single instance.
primus Provides a common API for most of the libraries above for easy switching + stability improvements for all of them.
When to use:
use the basic WebSocket servers when you want to use the native WebSocket implementations on the clientside, beware of the browser incompatabilities
use the fallback libraries when you care about browser fallbacks
use the full featured libraries when you care about channels
use primus when you have no idea about what to use, are not in the mood for rewriting your application when you need to switch frameworks because of changing project requirements or need additional connection stability.
Where to test:
Firecamp is a GUI testing environment for SocketIO, WS and all major real-time technology. Debug the real-time events while you're developing it.
Check your route
for the function in which you are using Auth::user()
, For getting Auth::user() data the function should be inside web
middleware Route::group(['middleware' => 'web'], function () {});
.
You can do replace tabs with spaces in all project files by:
Ctrl+Shif+F
^\A(.*)$
Your dir
Replace by \1
This will cause all project files to be opened, with their buffer marked as dirty. With this, you can now optionally enable these next Sublime Text settings, to trim all files trailing white space and ensure a new line at the end of every file.
You can enabled these settings by going on the menu Preferences -> Settings
and adding these contents to your settings file:
"ensure_newline_at_eof_on_save": true,
"trim_trailing_white_space_on_save": true,
View -> Show Console (Ctrl+`)
and run the command:
import threading; threading.Thread( args=(set(),), target=lambda counterset: [ (view.run_command( "expand_tabs", {"set_translate_tabs": True} ), print( "Processing {:>5} view of {:>5}, view id {} {}".format( len( counterset ) + 1, len( window.views() ), view.id(), ( "Finished converting!" if len( counterset ) > len( window.views() ) - 2 else "" ) ) ), counterset.add( len( counterset ) ) ) for view in window.views() ] ).start()
File -> Save All
For me, I forgot to add the default serial id.
private static final long serialVersionUID = 1L;
You can also update from select using alias and join:
UPDATE TOP (500) T
SET T.SomeColumn = 'Value'
FROM SomeTable T
INNER JOIN OtherTable O ON O.OtherTableFK = T.SomeTablePK
WHERE T.SomeOtherColumn = 1
By this code for formating price in product list
echo Mage::helper('core')->currency($_product->getPrice());
I found this old Thread while google'ing for generate_204 as Android seems to use this to determine if the wlan is open (response 204 is received) closed (no response at all) or blocked (redirect to captive portal is present). In that case a notification is shown that a log-in to WiFi is required...
For what it's worth, if you are editing this file, you can probably highlight all the lines and use your un-tab button.
I am not sure if there is some requirement that this must be done from the command line. If so, then :thumbs-up: to the accepted answer! =)
you can easily implement by jQuery
$('input').attr('autocomplete','off');
use "hh:mm a"
instead of "HH:mm a"
. Here hh
for 12 hour format and HH
for 24 hour format.
Live Demo
To set the directory selected path and the retrieve the new directory:
dlgBrowseForLogDirectory.SelectedPath = m_LogDirectory;
if (dlgBrowseForLogDirectory.ShowDialog() == DialogResult.OK)
{
txtLogDirectory.Text = dlgBrowseForLogDirectory.SelectedPath;
}
the input does not have to be a list of records - it can be a single dictionary as well:
pd.DataFrame.from_records({'a':1,'b':2}, index=[0])
a b
0 1 2
Which seems to be equivalent to:
pd.DataFrame({'a':1,'b':2}, index=[0])
a b
0 1 2
echo $pathInPieces = explode(DIRECTORY_SEPARATOR , __FILE__);
echo $pathInPieces[0].DIRECTORY_SEPARATOR;
I faced the same problem,but after hours of efforts i find the solution.It can be without using any external plugin:)
applicantListToExport: function (query, callback) {
this
.find(query).select({'advtId': 0})
.populate({
path: 'influId',
model: 'influencer',
select: { '_id': 1,'user':1},
populate: {
path: 'userid',
model: 'User'
}
})
.populate('campaignId',{'campaignTitle':1})
.exec(callback);
}
I'm using Tomcat through XAMPP which might have been the cause of this problem. When I changed appBase="C:/Java Project/"
, for example, I kept getting "This localhost page can't be found"
in the browser.
I had to add a folder called ROOT inside the Java Project folder and then it worked. Any files you're working on have to be inside this ROOT folder but you need to leave appBase="C:/Java Project/"
as changing it to appBase="C:/Java Project/ROOT"
will cause "This localhost page can't be found"
to be displayed again.
Maybe needing the ROOT folder is obvious to more experienced Java developers but it wasn't for me so hopefully this helps anyone else encountering the same problem.
to reattach this object, you must use merge();
this methode accept in parameter your entity detached and return an entity will be attached and reloaded from Database.
Example :
Lot objAttach = em.merge(oldObjDetached);
objAttach.setEtat(...);
em.persist(objAttach);
In my case it was because of function inside another function! once I moved out the function, error was gone , and everything worked as expected.
This answer explains why you shouldn't use function inside function.
This might help somebody.
Driver manager logs can be used to get console logs from browser and it will help to identify errors appears in console.
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
public List<LogEntry> getBrowserConsoleLogs()
{
LogEntries log= driver.manage().logs().get("browser")
List<LogEntry> logs=log.getAll();
return logs;
}
This has been partially answered here: MySQL Like multiple values
I advise against
$search = explode( ' ', $search );
and input them directly into the SQL query as this makes prone to SQL inject via the search bar. You will have to escape the characters first in case they try something funny like: "--; DROP TABLE name;
$search = str_replace('"', "''", search );
But even that is not completely safe. You must try to use SQL prepared statements to be safer. Using the regular expression is much easier to build a function to prepare and create what you want.
function makeSQL_search_pattern($search) {
search_pattern = false;
//escape the special regex chars
$search = str_replace('"', "''", $search);
$search = str_replace('^', "\\^", $search);
$search = str_replace('$', "\\$", $search);
$search = str_replace('.', "\\.", $search);
$search = str_replace('[', "\\[", $search);
$search = str_replace(']', "\\]", $search);
$search = str_replace('|', "\\|", $search);
$search = str_replace('*', "\\*", $search);
$search = str_replace('+', "\\+", $search);
$search = str_replace('{', "\\{", $search);
$search = str_replace('}', "\\}", $search);
$search = explode(" ", $search);
for ($i = 0; $i < count($search); $i++) {
if ($i > 0 && $i < count($search) ) {
$search_pattern .= "|";
}
$search_pattern .= $search[$i];
}
return search_pattern;
}
$search_pattern = makeSQL_search_pattern($search);
$sql_query = "SELECT name FROM Products WHERE name REGEXP :search LIMIT 6"
$stmt = pdo->prepare($sql_query);
$stmt->bindParam(":search", $search_pattern, PDO::PARAM_STR);
$stmt->execute();
I have not tested this code, but this is what I would do in your case. I hope this helps.
RDD
RDD
is a fault-tolerant collection of elements that can be operated on in parallel.
DataFrame
DataFrame
is a Dataset organised into named columns. It is conceptually equivalent to a table in a relational database or a data frame in R/Python, but with richer optimisations under the hood.
Dataset
Dataset
is a distributed collection of data. Dataset is a new interface added in Spark 1.6 that provides the benefits of RDDs (strong typing, ability to use powerful lambda functions) with the benefits of Spark SQL’s optimized execution engine.
Note:
Dataset of Rows (
Dataset[Row]
) in Scala/Java will often refer as DataFrames.
Q: Can you convert one to the other like RDD to DataFrame or vice-versa?
1. RDD
to DataFrame
with .toDF()
val rowsRdd: RDD[Row] = sc.parallelize(
Seq(
Row("first", 2.0, 7.0),
Row("second", 3.5, 2.5),
Row("third", 7.0, 5.9)
)
)
val df = spark.createDataFrame(rowsRdd).toDF("id", "val1", "val2")
df.show()
+------+----+----+
| id|val1|val2|
+------+----+----+
| first| 2.0| 7.0|
|second| 3.5| 2.5|
| third| 7.0| 5.9|
+------+----+----+
more ways: Convert an RDD object to Dataframe in Spark
2. DataFrame
/DataSet
to RDD
with .rdd()
method
val rowsRdd: RDD[Row] = df.rdd() // DataFrame to RDD
The functionality of creating SQL Agent Jobs is not available in SQL Server Express Edition. An alternative is to execute a batch file that executes a SQL script using Windows Task Scheduler.
In order to do this first create a batch file named sqljob.bat
sqlcmd -S servername -U username -P password -i <path of sqljob.sql>
Replace the servername
, username
, password
and path
with yours.
Then create the SQL Script file named sqljob.sql
USE [databasename]
--T-SQL commands go here
GO
Replace the [databasename]
with your database name. The USE
and GO
is necessary when you write the SQL script.
sqlcmd
is a command-line utility to execute SQL scripts. After creating these two files execute the batch file using Windows Task Scheduler.
NB: An almost same answer was posted for this question before. But I felt it was incomplete as it didn't specify about login information using sqlcmd
.
protected void UpdateButton_Click(object sender, EventArgs e)
{
var values = string.Format("Name={0}&Family={1}&Id={2}", NameToUpdateTextBox.Text, FamilyToUpdateTextBox.Text, IdToUpdateTextBox.Text);
var bytes = Encoding.ASCII.GetBytes(values);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("http://localhost:51436/api/employees"));
request.Method = "PUT";
request.ContentType = "application/x-www-form-urlencoded";
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
var response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
UpdateResponseLabel.Text = "Update completed";
else
UpdateResponseLabel.Text = "Error in update";
}
I'm working just by putting the @Expose
annotation, here my version that I use
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
In Model
class:
@Expose
int number;
public class AdapterRestApi {
In the Adapter
class:
public EndPointsApi connectRestApi() {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(90000, TimeUnit.SECONDS)
.readTimeout(90000,TimeUnit.SECONDS).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ConstantRestApi.ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit.create (EndPointsApi.class);
}
You are asking to replace the character "?" but for me that is coming through as three characters 'ï', '¿' and '½'. This might be your problem... If you are using Java prior to Java 1.5 then you only get the UCS-2 characters, that is only the first 65K UTF-8 characters. Based on other comments, it is most likely that the character that you are looking for is '?', that is the Unicode replacement character. This is the character that is "used to replace an incoming character whose value is unknown or unrepresentable in Unicode".
Actually, looking at the comment from Kathy, the other issue that you might be having is that javac is not interpreting your .java file as UTF-8, assuming that you are writing it in UTF-8. Try using:
javac -encoding UTF-8 xx.java
Or, modify your source code to do:
String.replaceAll("\uFFFD", "");
Using javascript seems to be unnecessary if you choose CSS3.
By using :before
selector, you can do this in two lines of CSS. (no script involved).
Another advantage of this approach is that it does not rely on <label>
tag and works even it is missing.
Note: in browsers without CSS3 support, checkboxes will look normal. (backward compatible).
input[type=checkbox]:before { content:""; display:inline-block; width:12px; height:12px; background:red; }
input[type=checkbox]:checked:before { background:green; }?
You can see a demo here: http://jsfiddle.net/hqZt6/1/
and this one with images:
Just do the following change
echo off
cls
echo Would you like to do a backup?
pause
copy "\\My_Servers_IP\Shared Drive\FolderName\*" C:\TEST_BACKUP_FOLDER
pause
As mentioned above by Vadim Use Jenkins "Project-based Matrix Authorization Strategy" under "Manage Jenkins" => "Configure System". Don't forget to add your admin user there and give all permissions. Now add the restricted user there and give overall read access. Then go to the configuration page of each project, you now have "Enable project-based security" option. Now add each user you want to authorize.
sudo apt-get install nodejs
does not work for me. In order to get it to work, I have to do the following:
sudo apt-get install python-software-properties
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs
Hope this will help someone having the same problem as me.
I also got this error.
I had to add my new controller to routing information. \src\js\app.js
angular.module('Lillan', [
'ngRoute',
'mobile-angular-ui',
'Lillan.controllers.Main'
])
I added my controller to make it look like
angular.module('Lillan', [
'ngRoute',
'mobile-angular-ui',
'Lillan.controllers.Main',
'Lillan.controllers.Growth'
])
Cheers!
I am using Ubuntu and my sessions are stored in /var/lib/php5.
You can also use array-like notation and check for the first element.
The first element of an empty array or collection is simply undefined
, so you get the "normal" javascript truthy/falsy behaviour:
var el = $('body')[0];
if (el) {
console.log('element found', el);
}
if (!el) {
console.log('no element found');
}
I need to do the same thing for a project I am currently working on. Here is how I solved things:
/* Prompt user for input */
printf("Enter a number: ");
/* Read user input */
char input[255]; //Of course, you can choose a different input size
fgets(input, sizeof(input), stdin);
/* Strip trailing newline */
size_t ln = strlen(input) - 1;
if( input[ln] == '\n' ) input[ln] = '\0';
/* Ensure that input is a number */
for( size_t i = 0; i < ln; i++){
if( !isdigit(input[i]) ){
fprintf(stderr, "%c is not a number. Try again.\n", input[i]);
getInput(); //Assuming this is the name of the function you are using
return;
}
}
You need to create new TextNodes as well as td nodes for each column, not reuse them among all of the columns as your code is doing.
Edit: Revise your code like so:
for (var i = 1; i < 4; i++)
{
tr[i] = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
td1.appendChild(document.createTextNode('Text1'));
td2.appendChild(document.createTextNode('Text2'));
tr[i].appendChild(td1);
tr[i].appendChild(td2);
table.appendChild(tr[i]);
}
My problem was using cursor: 'pointer'
mistakenly instead of cursor: pointer
.
So, make sure you are not adding single or double quotes around pointer.
Try this procedure:
def procedure(input):
a=0
print input[a]
ecs = input[a] #ecs stands for each character separately
while ecs != input:
a = a + 1
print input[a]
In order to use it you have to know how to use procedures and although it works, it has an error in the end so you have to work that out too.
I know it's not pretty but it is simple. Try this:
declare @AlpaNumber nvarchar(50) = 'ABC'
declare @MyNumber int = 0
begin Try
select @MyNumber = case when ISNUMERIC(@AlpaNumber) = 1 then cast(@AlpaNumber as int) else 0 end
End Try
Begin Catch
-- Do nothing
End Catch
if exists(select * from mytable where mynumber = @MyNumber)
Begin
print 'Found'
End
Else
Begin
print 'Not Found'
End
Another take based on John Skeet's answer that doesn't return the tags:
void Main()
{
XmlString("Brackets & stuff <> and \"quotes\"").Dump();
}
public string XmlString(string text)
{
return new XElement("t", text).LastNode.ToString();
}
This returns just the value passed in, in XML encoded format:
Brackets & stuff <> and "quotes"
I read a lot of answers but none seems to correctly explain where the word double comes from. I remember a very good explanation given by a University professor I had some years ago.
Recalling the style of VonC's answer, a single precision floating point representation uses a word of 32 bit.
Representation:
S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM
bits: 31 30 23 22 0
(Just to point out, the sign bit is the last, not the first.)
A double precision floating point representation uses a word of 64 bit.
Representation:
S EEEEEEEEEEE MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
bits: 63 62 52 51 0
As you may notice, I wrote that the mantissa has, in both types, one bit more of information compared to its representation. In fact, the mantissa is a number represented without all its non-significative 0
. For example,
This means that the mantissa will always be in the form
0.a1a2...at × ßp
where ß is the base of representation. But since the fraction is a binary number, a1 will always be equal to 1, thus the fraction can be rewritten as 1.a2a3...at+1 × 2p and the initial 1 can be implicitly assumed, making room for an extra bit (at+1).
Now, it's obviously true that the double of 32 is 64, but that's not where the word comes from.
The precision indicates the number of decimal digits that are correct, i.e. without any kind of representation error or approximation. In other words, it indicates how many decimal digits one can safely use.
With that said, it's easy to estimate the number of decimal digits which can be safely used:
I had the same issues but nothing worked. What I did was I added this to the selector:
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
Try using a format like %d.%02d
int iAmount = 10050;
printf("The number with fake decimal point is %d.%02d", iAmount/100, iAmount%100);
Another approach is to type cast it to double before printing it using %f like this:
printf("The number with fake decimal point is %0.2f", (double)(iAmount)/100);
My 2 cents :)
On the server side, just rename the repository with the mv command as usual:
mv oldName.git newName.git
Then on the client side, change the value of the [remote "origin"]
URL into the new one:
url=example.com/newName.git
It worked for me.
You can simply check you log path from phpmyadmin
run this:
now click PHPInfo (top right corner) or you can simply run this url in your browser
now search for "error_log"(without quotes) You will get log path.
Enjoy!
Since I've been looking for this forever, and I found a solution a while ago which is missing here, I'm gonna write it here, for future reference also.
Note: this code was taken directly from Google Android Lollipop dialer a while back, I don't remember If changes were made at the time. Also, I don't know which license is this under, but I have reason to think it is Apache 2.0
.
Class ResizeTextView
, the actual View
public class ResizeTextView extends TextView {
private final int mOriginalTextSize;
private final int mMinTextSize;
private final static int sMinSize = 20;
public ResizeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
mOriginalTextSize = (int) getTextSize();
mMinTextSize = (int) sMinSize;
}
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
ViewUtil.resizeText(this, mOriginalTextSize, mMinTextSize);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
ViewUtil.resizeText(this, mOriginalTextSize, mMinTextSize);
}
This ResizeTextView
class could extend TextView and all its children as I undestand, so EditText as well.
Class ViewUtil
with method resizeText(...)
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.graphics.Paint;
import android.util.TypedValue;
import android.widget.TextView;
public class ViewUtil {
private ViewUtil() {}
public static void resizeText(TextView textView, int originalTextSize, int minTextSize) {
final Paint paint = textView.getPaint();
final int width = textView.getWidth();
if (width == 0) return;
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, originalTextSize);
float ratio = width / paint.measureText(textView.getText().toString());
if (ratio <= 1.0f) {
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
Math.max(minTextSize, originalTextSize * ratio));
}
}
}
You should set your view as
<yourpackage.yourapp.ResizeTextView
android:layout_width="match_parent"
android:layout_height="64dp"
android:gravity="center"
android:maxLines="1"/>
Hope it helps!
ASPX:
<asp:TextBox ID="TextBox1" clientidmode="Static" runat="server" onkeypress="return EnterEvent(event)"></asp:TextBox>
<asp:Button ID="Button1" runat="server" style="display:none" Text="Button" />
JS:
function EnterEvent(e) {
if (e.keyCode == 13) {
__doPostBack('<%=Button1.UniqueID%>', "");
}
}
CS:
protected void Button1_Click1(object sender, EventArgs e)
{
}
This is an example that will work on most browsers.
Basically you use two background colors, the first one starting from 0% and ending at 50% and the second one starting from 51% and ending at 100%
I'm using horizontal orientation:
background: #000000;
background: -moz-linear-gradient(left, #000000 0%, #000000 50%, #ffffff 51%, #ffffff 100%);
background: -webkit-gradient(linear, left top, right top, color-stop(0%,#000000), color-stop(50%,#000000), color-stop(51%,#ffffff), color-stop(100%,#ffffff));
background: -webkit-linear-gradient(left, #000000 0%,#000000 50%,#ffffff 51%,#ffffff 100%);
background: -o-linear-gradient(left, #000000 0%,#000000 50%,#ffffff 51%,#ffffff 100%);
background: -ms-linear-gradient(left, #000000 0%,#000000 50%,#ffffff 51%,#ffffff 100%);
background: linear-gradient(to right, #000000 0%,#000000 50%,#ffffff 51%,#ffffff 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#000000', endColorstr='#ffffff',GradientType=1 );
For different adjustments you could use http://www.colorzilla.com/gradient-editor/
As you're passing true as the second parameter to json_decode
, in the above example you can retrieve data doing something similar to:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
To the delight of font purists everywhere, the iPhone system interface uses Helvetica or a variant thereof.
The original iPhone, iPhone 3G and iPhone 3GS system interface uses Helvetica. As first noted by the always excellent DaringFireball, the iPhone 4 uses a subtly revised font called "Helvetica Neue." DaringFireball also notes that this change is related to the iPhone 4 display rather than the iOS 4 operating system and older iPhone models running iOS 4 still use Helvetica as the system font.
iPod models released prior to the iPhone use either Chicago, Espy Sans, or Myriad and use Helvetica after the release of the iPhone.
From http://www.everyipod.com/iphone-faq/iphone-who-designed-iphone-font-used-iphone-ringtones.html
For iOS9 it has changed to San Fransisco. See http://developer.apple.com/fonts for more info.
Pressing the f
key (or ctrl+f
in 1.2rc1) when focussed on a plot will fullscreen a plot window. Not quite maximising, but perhaps better.
Other than that, to actually maximize, you will need to use GUI Toolkit specific commands (if they exist for your specific backend).
HTH
I faced same issue in android studio 3.2.1, solved the issue by setting git path in System Environment variable
C:\Program Files\Git\bin\,C:\Program Files\Git\bin\
And I imported the project once again and solved the issue!!!
Note : Check your android studio git settings has properly set the correct path to git.exe
Grid.ColumnSpacing, Grid.RowSpacing, StackPanel.Spacing are now on UWP preview, all will allow to better acomplish what is requested here.
These properties are currently only available with the Windows 10 Fall Creators Update Insider SDK, but should make it to the final bits!
Try this:
SELECT REPLACE(RTRIM(REPLACE(REPLACE(RTRIM(REPLACE(CAST(CAST(YOUR_FLOAT_COLUMN_NAME AS DECIMAL(18,9)) AS VARCHAR(20)),'0',' ')),' ','0'),'.',' ')),' ','.') FROM YOUR_TABLE_NAME
The problem is that --exclude="*"
says to exclude (for example) the 1260000000/
directory, so rsync
never examines the contents of that directory, so never notices that the directory contains files that would have been matched by your --include
.
I think the closest thing to what you want is this:
rsync -nrv --include="*/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/
(which will include all directories, and all files matching file_11*.jpg
, but no other files), or maybe this:
rsync -nrv --include="/[0-9][0-9][0-9]0000000/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/
(same concept, but much pickier about the directories it will include).
In your Model Class add a json property annotation, also have a default constructor
@JsonProperty("user_name")
private String userName;
@JsonProperty("first_name")
private String firstName;
@JsonProperty("last_name")
private String lastName;
Check out this blog article from the data platform team.
http://blogs.msdn.com/b/sql_protocols/archive/2006/02/21/536201.aspx
You really need to look at the state part of the error message to find the root cause of the issue.
2, 5 = Invalid userid
6 = Attempt to use a Windows login name with SQL Authentication
7 = Login disabled and password mismatch
8 = Password mismatch
9 = Invalid password
11, 12 = Valid login but server access failure
13 = SQL Server service paused
18 = Change password required
Afterwards, Google how to fix the issue.
Try it: sudo mysql_secure_installation
Work's in Ubuntu 18.04
I cannot quickly reproduce the symptoms: if I try myscript '"test"'
with a batch file myscript.bat
containing just @echo.%1
or even @echo.%~1
, I get all quotes: '"test"'
Perhaps you can try the escape character ^
like this: myscript '^"test^"'
?
Frankly speaking, your case works fine for me!
I'm using Angular 5.
<script type='text/javascript'>
var base = window.location.href.substring(0, window.location.href.toLowerCase().indexOf('index.aspx'))
document.write('<base href="' + base + '" />');
</script>
Check out pyftpdlib from Giampaolo Rodola. It is one of the very best ftp servers out there for python. It's used in google's chromium (their browser) and bazaar (a version control system). It is the most complete implementation on Python for RFC-959 (aka: FTP server implementation spec).
To install:
pip3 install pyftpdlib
From the commandline:
python3 -m pyftpdlib
Alternatively 'my_server.py':
#!/usr/bin/env python3
from pyftpdlib import servers
from pyftpdlib.handlers import FTPHandler
address = ("0.0.0.0", 21) # listen on every IP on my machine on port 21
server = servers.FTPServer(address, FTPHandler)
server.serve_forever()
There's more examples on the website if you want something more complicated.
To get a list of command line options:
python3 -m pyftpdlib --help
Note, if you want to override or use a standard ftp port, you'll need admin privileges (e.g. sudo).
This worked for me:
curl -u $username:$api_token -FSubmit=Build 'http://<jenkins-server>/job/<job-name>/buildWithParameters?environment='
API token can be obtained from Jenkins user configuration.
I don't know of any out-of-the-box way to achieve this. As you say, this is not how SharePoint lists are intended used. It might work to create a custom site column displaying the path to the document, as this might be used in a filter. Have never tried it, though.
This will also work.
$('#test').find("select option:contains('B')").filter(":selected");
Short solution for preventing user from using context menu, copy and cut in jQuery:
jQuery(document).bind("cut copy contextmenu",function(e){
e.preventDefault();
});
Also disabling text selection in CSS might come handy:
.noselect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
echo "<script>
alert('There are no fields to generate a report');
window.location.href='admin/ahm/panel';
</script>";
and get rid of redirect
line below.
You were mixing up two different worlds.
The best thing to do is to create a "print-only" version of the page.
Oh, wait... this isn't 1999 anymore. Use a print CSS with "display: none".
You're importing the module, not the class. So, you must write:
from serial import Serial
You need to install serial
module correctly: pip install pyserial
.
I was in trouble to import an Enum in typescript
error TS2307: Cannot find module...
What I did to make it work was migrate the enum to another file and make this change:
export enum MyEnum{
VALUE = "MY_VALUE"
}
to
export enum MyEnum{
VALUE = 1
}
isset is testing whether or not the key you are checking in the hash (or associative array) is "set". Set in this context just means if it knows the value. Nothing is a value. So it is defined as being an empty string.
For that reason, as long as you have an input field named userName, regardless of if they fill it in, this will be true. What you really want to do is check if the userName is equal to an empty string ''
This is called heredoc format to provide a string into stdin. See https://en.wikipedia.org/wiki/Here_document#Unix_shells for more details.
From man bash
:
Here Documents
This type of redirection instructs the shell to read input from the current source until a line containing only word (with no trailing blanks) is seen.
All of the lines read up to that point are then used as the standard input for a command.
The format of here-documents is:
<<[-]word here-document delimiter
No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. In the latter case, the character sequence
\<newline>
is ignored, and\
must be used to quote the characters\
,$
, and`
.If the redirection operator is
<<-
, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion.
If the numbers you want to choose from are not consecutive, you can use random()
.
Usage:
val list = listOf(3, 1, 4, 5)
val number = list.random()
Returns one of the numbers which are in the list.
For those looking for a plug-and-play solution on UIImage, I wrote CodyMace's answer as an extension.
Usage: let outlined = UIImage(named: "something")?.outline()
extension UIImage {
func outline() -> UIImage? {
let size = CGSize(width: self.size.width, height: self.size.height)
UIGraphicsBeginImageContext(size)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
self.draw(in: rect, blendMode: .normal, alpha: 1.0)
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(red: 0, green: 0, blue: 0, alpha: 1)
context?.stroke(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
please try to do
make clean
(instead of make
), then
make
again.
Step 1: Go to json.org to find the JSON library for whatever technology you're using to call this web service. Download and link to that library.
Step 2: Let's say you're using Java. You would use JSONArray like this:
JSONArray myArray=new JSONArray(queryResponse);
for (int i=0;i<myArray.length;i++){
JSONArray myInteriorArray=myArray.getJSONArray(i);
if (i==0) {
//this is the first one and is special because it holds the name of the query.
}else{
//do your stuff
String stateCode=myInteriorArray.getString(0);
String stateName=myInteriorArray.getString(1);
}
}
Just want to point out that option2 in @Matthias Fripp's answer
(2) I wouldn't necessarily expect DataFrame to work this way, but it does
df[['column_new_1', 'column_new_2', 'column_new_3']] = pd.DataFrame([[np.nan, 'dogs', 3]], index=df.index)
is already documented in pandas' own documentation http://pandas.pydata.org/pandas-docs/stable/indexing.html#basics
You can pass a list of columns to [] to select columns in that order. If a column is not contained in the DataFrame, an exception will be raised. Multiple columns can also be set in this manner. You may find this useful for applying a transform (in-place) to a subset of the columns.
I agree with Justin, and the WhiteSpace CHAR can be referenced using ASCII codes here Character number 32 represents a white space, Therefore:
string.Empty.PadRight(totalLength, (char)32);
An alternative approach: Create all spaces manually within a custom method and call it:
private static string GetSpaces(int totalLength)
{
string result = string.Empty;
for (int i = 0; i < totalLength; i++)
{
result += " ";
}
return result;
}
And call it in your code to create white spaces: GetSpaces(14);
You can add or increase the day of week for the following example and hope this will helpful for you.Lets see....
//Current date
var currentDate = new Date();
//to set Bangladeshi date need to add hour 6
currentDate.setUTCHours(6);
//here 2 is day increament for the date and you can use -2 for decreament day
currentDate.setDate(currentDate.getDate() +parseInt(2));
//formatting date by mm/dd/yyyy
var dateInmmddyyyy = currentDate.getMonth() + 1 + '/' + currentDate.getDate() + '/' + currentDate.getFullYear();
Logical layers are merely a way of organizing your code. Typical layers include Presentation, Business and Data – the same as the traditional 3-tier model. But when we’re talking about layers, we’re only talking about logical organization of code. In no way is it implied that these layers might run on different computers or in different processes on a single computer or even in a single process on a single computer. All we are doing is discussing a way of organizing a code into a set of layers defined by specific function.
Physical tiers however, are only about where the code runs. Specifically, tiers are places where layers are deployed and where layers run. In other words, tiers are the physical deployment of layers.
Source: Rockford Lhotka, Should all apps be n-tier?
Just want to reiterate this will work in pandas >= 0.9.1:
In [2]: read_csv('sample.csv', dtype={'ID': object})
Out[2]:
ID
0 00013007854817840016671868
1 00013007854817840016749251
2 00013007854817840016754630
3 00013007854817840016781876
4 00013007854817840017028824
5 00013007854817840017963235
6 00013007854817840018860166
I'm creating an issue about detecting integer overflows also.
EDIT: See resolution here: https://github.com/pydata/pandas/issues/2247
Update as it helps others:
To have all columns as str, one can do this (from the comment):
pd.read_csv('sample.csv', dtype = str)
To have most or selective columns as str, one can do this:
# lst of column names which needs to be string
lst_str_cols = ['prefix', 'serial']
# use dictionary comprehension to make dict of dtypes
dict_dtypes = {x : 'str' for x in lst_str_cols}
# use dict on dtypes
pd.read_csv('sample.csv', dtype=dict_dtypes)
To keep this question current it is worth highlighting that AssemblyInformationalVersion
is used by NuGet and reflects the package version including any pre-release suffix.
For example an AssemblyVersion of 1.0.3.* packaged with the asp.net core dotnet-cli
dotnet pack --version-suffix ci-7 src/MyProject
Produces a package with version 1.0.3-ci-7 which you can inspect with reflection using:
CustomAttributeExtensions.GetCustomAttribute<AssemblyInformationalVersionAttribute>(asm);
you can do this in different ways:
see here for more details on the second case:
http://msdn.microsoft.com/en-us/library/ff647786.aspx#scalenetchapt10_topic14
and here for details on the last case:
In addition to the suggested,
String Text = mySpinner.getSelectedItem().toString();
You can do,
String Text = String.valueOf(mySpinner.getSelectedItem());
Well things have changed a little bit since 2011! Now there's type hints in Python 3.5 which you can use to annotate arguments and return the type of your function. For example this:
def greeting(name):
return 'Hello, {}'.format(name)
can now be written as this:
def greeting(name: str) -> str:
return 'Hello, {}'.format(name)
As you can now see types, there's some sort of optional static type checking which will help you and your type checker to investigate your code.
for more explanation I suggest to take a look at the blog post on type hints in PyCharm blog.
With Mongo 3.2 and higher just use your connection string as is:
mongo mongodb://username:[email protected]:10011/my_database
import { DOCUMENT } from '@angular/common';
import { Component, Inject } from '@angular/core';
@Component({
selector: 'app-refresh-banner-notification',
templateUrl: './refresh-banner-notification.component.html',
styleUrls: ['./refresh-banner-notification.component.scss']
})
export class RefreshBannerNotificationComponent {
constructor(
@Inject(DOCUMENT) private _document: Document
) {}
refreshPage() {
this._document.defaultView.location.reload();
}
}
this error often occurs when you miss runat="server"
.
That ~~
is a double NOT bitwise operator.
It is used as a faster substitute for Math.floor()
for positive numbers. It does not return the same result as Math.floor()
for negative numbers, as it just chops off the part after the decimal (see other answers for examples of this).
For a more convenient installer, you may want to use
apt-cyg
as your package manager. Its syntax similar to
apt-get
, which is a plus. For this, follow the above
steps and then use Cygwin Bash for the following steps
wget https://raw.githubusercontent.com/transcode-open/apt-cyg/master/apt-cyg
chmod +x apt-cyg
mv apt-cyg /usr/local/bin
Now that apt-cyg
is installed. Here are few examples of
installing some packages
apt-cyg install nano
apt-cyg install git
apt-cyg install ca-certificates
There is a package that converts it for you and returns the svg as a string to implement into your reactJS file.
There is also direct support for white space removal in Bash variable substitution:
testvar=$(wc -l < log.txt)
trailing_space_removed=${testvar%%[[:space:]]}
leading_space_removed=${testvar##[[:space:]]}
The error comes when you try to call sum(x)
and x
is a factor.
What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)
simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:
family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))
For a detailed explanation of why the intermediate as.character
step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?
To use a theme for all the application, and don't use the second parameter to style your Dialog
<style name="MyTheme" parent="Base.Theme.AppCompat.Light">
<item name="alertDialogTheme">@style/dialog</item>
<item name="colorAccent">@color/accent</item>
</style>
<style name="dialog" parent="Base.Theme.AppCompat.Light.Dialog.Alert">
<item name="colorAccent">@color/accent</item>
</style>
On my app using a color accent in theme don't show the alertDialog's buttons with the theme colorAccent I have to add a dialog style in the theme.
Can be done using an identityHashMap, subjected to the condition that the keys comparison will be done by == operator and not equals().
Their is a tool called indent
. You can download it with apt-get install indent
, then run indent my_program.c
.
it worked. Just modified it
global $woocommerce, $post;
$order = new WC_Order($post->ID);
//to escape # from order id
$order_id = trim(str_replace('#', '', $order->get_order_number()));
Below line helped me to fix the issue of scroll bar for a table; the issue was awkward 2 scroll bars in a page. Below style when applied to table worked fine for me.
<table Style="position: absolute; height: 100%; width: 100%";/>
I just wanted to add my experiences with the PATH setup that Steve and timc mentions above: I got permission problems using shell tools (like mv and cp) having Git's shell executables first in the path.
Appending them after the existing PATH instead this solved my problems. Example:
GITPATH='/cygdrive/c/Program Files (x86)/Git/bin'
GITCOREPATH='/cygdrive/c/Program Files (x86)/Git/libexec/git-core'
PATH=${PATH}:${GITPATH}:${GITCOREPATH}
I guess CopSSH doesn't go along well with all of msysgit's shell executables...
PHP has a built-in function implode to assign array values to string. Use it like this:
$str = implode(",", $array);
Modern C, aka C99, has variable length arrays, VLA. Unfortunately, not all compilers support this but if yours does this would be an alternative.
This page keeps references to implementations in various languages, including Java, and compares features: http://kjur.github.io/jsjws/index_mat.html
I am using CDN for my project and as part of fallback handling, i was using below code,
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
if ((typeof jQuery == 'undefined')) {
document.write(unescape("%3Cscript src='/Responsive/Scripts/jquery-1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
Just to verify, i removed CDN reference and execute the code. Its broken and it's never entered into if loop as typeof jQuery is coming as function instead of undefined .
This is because of cached older version of jquery 1.6.1 which return function and break my code because i am using jquery 1.9.1. As i need exact version of jquery, i modified code as below,
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
if ((typeof jQuery == 'undefined') || (jQuery.fn.jquery != "1.9.1")) {
document.write(unescape("%3Cscript src='/Responsive/Scripts/jquery-1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
Try the following way.
Select * from t1 where date(col_name)="8/3/2010"
Late answer, but I just came on this list today!
CREATE TABLE assignment_20101120 AS SELECT * FROM assignment;
Does the same.
I think its better to avoid recursion because its costly.
function padLeft(str,size,padwith) {_x000D_
if(size <= str.length) {_x000D_
// not padding is required._x000D_
return str;_x000D_
} else {_x000D_
// 1- take array of size equal to number of padding char + 1. suppose if string is 55 and we want 00055 it means we have 3 padding char so array size should be 3 + 1 (+1 will explain below)_x000D_
// 2- now join this array with provided padding char (padwith) or default one ('0'). so it will produce '000'_x000D_
// 3- now append '000' with orginal string (str = 55), will produce 00055_x000D_
_x000D_
// why +1 in size of array? _x000D_
// it is a trick, that we are joining an array of empty element with '0' (in our case)_x000D_
// if we want to join items with '0' then we should have at least 2 items in the array to get joined (array with single item doesn't need to get joined)._x000D_
// <item>0<item>0<item>0<item> to get 3 zero we need 4 (3+1) items in array _x000D_
return Array(size-str.length+1).join(padwith||'0')+str_x000D_
}_x000D_
}_x000D_
_x000D_
alert(padLeft("59",5) + "\n" +_x000D_
padLeft("659",5) + "\n" +_x000D_
padLeft("5919",5) + "\n" +_x000D_
padLeft("59879",5) + "\n" +_x000D_
padLeft("5437899",5));
_x000D_
You've got a couple regexes now which will do what you want, so that's adequately covered.
What hasn't been mentioned is why your attempt won't work: Inside a character class, $
(as well as ^
, .
, and /
) has no special meaning, so [/$]
matches either a literal /
or a literal $
rather than terminating the regex (/
) or matching end-of-line ($
).
I guess you're learning how to Python. The other answers are right. But I am going to answer your main question: "how to calculate percentage in python"
Although it works the way you did it, it doesn´t look very pythonic. Also, what happens if you need to add a new subject? You'll have to add another variable, use another input, etc. I guess you want the average of all marks, so you will also have to modify the count of the subjects everytime you add a new one! Seems a mess...
I´ll throw a piece of code where the only thing you'll have to do is to add the name of the new subject in a list. If you try to understand this simple piece of code, your Python coding skills will experiment a little bump.
#!/usr/local/bin/python2.7
marks = {} #a dictionary, it's a list of (key : value) pairs (eg. "Maths" : 34)
subjects = ["Tamil","English","Maths","Science","Social"] # this is a list
#here we populate the dictionary with the marks for every subject
for subject in subjects:
marks[subject] = input("Enter the " + subject + " marks: ")
#and finally the calculation of the total and the average
total = sum(marks.itervalues())
average = float(total) / len(marks)
print ("The total is " + str(total) + " and the average is " + str(average))
Here you can test the code and experiment with it.
There seem to be many answers suggesting:
process.stdout.write
Error logs should be emitted on:
process.stderr
Instead use:
console.error
For anyone who is wonder why process.stdout.write('\033[0G');
wasn't doing anything it's because stdout
is buffered and you need to wait for drain
event (more info).
If write returns false
it will fire a drain
event.
In the Java Options text area append this line:
-XX:MaxPermSize=128m
i was getting error as "This driver is not configured for integrated authentication" while authenticating windows users by following jdbc string
jdbc:sqlserver://host:1433;integratedSecurity=true;domain=myDomain
So the updated connection string to make it work is as below.
jdbc:sqlserver://host:1433;authenticationScheme=NTLM;integratedSecurity=true;domain=myDomain
note: username entered was without domain.
Try out Following:
DataRow rows = DataTable.Select("[Name]<>'n/a'")
For Null check in This:
DataRow rows = DataTable.Select("[Name] <> 'n/a' OR [Name] is NULL" )
puts true ? "true" : "false"
=> "true"
puts false ? "true" : "false"
=> "false"
It is happened to me with laravel 5.1 on php-7 when I was running bunch of unitests.
The solution was - to change memory_limit in php.ini but it should be correct one. So you need one responsible for server, located there:
/etc/php/7.0/cli/php.ini
so you need a line with
memory_limit
After that you need to restart php service
sudo service php7.0-fpm restart
to check if it was changed successfully I used command line to run this:
php -i
the report contained following line
memory_limit => 2048M => 2048M
Now test cases are fine.
You should really check the log. It seems that quite a few components can cause the Windows SDK installer to fail to install with this useless error message. For instance it could be the Visual C++ Redistributable Package as mentioned there.
Sadly, there's no equivalent to the null coalescing operator that works with DBNull; for that, you need to use the ternary operator:
newValue = (oldValue is DBNull) ? null : oldValue;
In order to avoid such error you could use CASE
+ ISNUMERIC
to handle scenarios when you cannot convert to int.
Change
CONVERT(INT, CONVERT(VARCHAR(12), a.value))
To
CONVERT(INT,
CASE
WHEN IsNumeric(CONVERT(VARCHAR(12), a.value)) = 1 THEN CONVERT(VARCHAR(12),a.value)
ELSE 0 END)
Basically this is saying if you cannot convert me to int assign value of 0 (in my example)
Alternatively you can look at this article about creating a custom function that will check if a.value
is number: http://www.tek-tips.com/faqs.cfm?fid=6423
First you need to understand, that both are different things. Stored Procedures
are best used for INSERT-UPDATE-DELETE
statements. Whereas Views
are used for SELECT
statements. You should use both of them.
In views you cannot alter the data. Some databases have updatable Views where you can use INSERT-UPDATE-DELETE
on Views
.
Here is implementation of standard C++ 14 using vectors and tuples to Read and Write Text,Binary and Hex files
.
Snippet code :
try {
if (file_type == BINARY_FILE) {
/*Open the stream in binary mode.*/
std::ifstream bin_file(file_name, std::ios::binary);
if (bin_file.good()) {
/*Read Binary data using streambuffer iterators.*/
std::vector<uint8_t> v_buf((std::istreambuf_iterator<char>(bin_file)), (std::istreambuf_iterator<char>()));
vec_buf = v_buf;
bin_file.close();
}
else {
throw std::exception();
}
}
else if (file_type == ASCII_FILE) {
/*Open the stream in default mode.*/
std::ifstream ascii_file(file_name);
string ascii_data;
if (ascii_file.good()) {
/*Read ASCII data using getline*/
while (getline(ascii_file, ascii_data))
str_buf += ascii_data + "\n";
ascii_file.close();
}
else {
throw std::exception();
}
}
else if (file_type == HEX_FILE) {
/*Open the stream in default mode.*/
std::ifstream hex_file(file_name);
if (hex_file.good()) {
/*Read Hex data using streambuffer iterators.*/
std::vector<char> h_buf((std::istreambuf_iterator<char>(hex_file)), (std::istreambuf_iterator<char>()));
string hex_str_buf(h_buf.begin(), h_buf.end());
hex_buf = hex_str_buf;
hex_file.close();
}
else {
throw std::exception();
}
}
}
Full Source code can be found here
I just fixed this perl bug. See https://rt.perl.org/Ticket/Display.html?id=124232
When we push the buffer layer to PerlIO and do a failing isatty() check which obviously fails on all normal files, ignore the wrong errno ENOTTY.
You need to add your ORACLE_HOME
definition in your listener.ora file. Right now its not registered with any ORACLE_HOME
.
Sample listener.ora
abc =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = abc.kma.com)(PORT = 1521))
)
)
SID_LIST_abc =
(SID_LIST =
(SID_DESC =
(ORACLE_HOME= /abc/DbTier/11.2.0)
(SID_NAME = abc)
)
)