Using the base
package:
df <- data.frame(days = c(88, 11, 2, 5, 22, 1, 222, 2), name = c("Lynn", "Tom", "Chris", "Lisa", "Kyla", "Tom", "Lynn", "Lynn"))
# Three lines
target <- c("Tom", "Lynn")
index <- df$name %in% target
df[index, ]
# One line
df[df$name %in% c("Tom", "Lynn"), ]
Output:
days name
1 88 Lynn
2 11 Tom
6 1 Tom
7 222 Lynn
8 2 Lynn
Using sqldf
:
library(sqldf)
# Two alternatives:
sqldf('SELECT *
FROM df
WHERE name = "Tom" OR name = "Lynn"')
sqldf('SELECT *
FROM df
WHERE name IN ("Tom", "Lynn")')
If you need not equal object condition use cross join sequences:
var query = from obj1 in set1
from obj2 in set2
where obj1.key1 == obj2.key2 && obj1.key3.contains(obj2.key5) [...conditions...]
Pass param rot=0
to rotate the xticks:
import matplotlib
matplotlib.style.use('ggplot')
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({ 'celltype':["foo","bar","qux","woz"], 's1':[5,9,1,7], 's2':[12,90,13,87]})
df = df[["celltype","s1","s2"]]
df.set_index(["celltype"],inplace=True)
df.plot(kind='bar',alpha=0.75, rot=0)
plt.xlabel("")
plt.show()
yields plot:
I have been experiencing this issue when debugging using NetBeans, even executing the actual jar file. Antivirus would block sending email. You should temporarily disable your antivirus during debugging or exclude NetBeans and the actual jar file from being scanned. In my case, I'm using Avast.
See this link on how to Exclude : How to Add File/Website Exception into avast! Antivirus 2014
It works for me.
Mostly we need this type of query in migration script
INSERT INTO db1.table1(col1,col2,col3,col4)
SELECT col5,col6,col7,col8
FROM db1.table2
In this query column count must be same in both table
In addition to the solution you accepted, you could also implement the special __lt__()
("less than") method on the class. The sort()
method (and the sorted()
function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.
class Foo(object):
def __init__(self, score):
self.score = score
def __lt__(self, other):
return self.score < other.score
l = [Foo(3), Foo(1), Foo(2)]
l.sort()
Maybe more simple;
var top = window.pageYOffset || document.documentElement.scrollTop,
left = window.pageXOffset || document.documentElement.scrollLeft;
Credits: so.dom.js#L492
In Swift 4 :
let alert=UIAlertController(title:"someAlert", message: "someMessage", preferredStyle:UIAlertControllerStyle.alert )
alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.default, handler: {
_ in print("FOO ")
}))
present(alert, animated: true, completion: nil)
Call clearAnimation()
on whichever View
you called startAnimation()
.
For those trying to trigger the download using a dynamic link it's tricky to get it working consistently across browsers.
I had trouble in IE10+ downloading a PDF and used @dandavis' download
function (https://github.com/rndme/download).
IE10+ needs msSaveBlob
.
Very common mistake was done by me. I copied using clip command xclip -sel clip < ~/.ssh/id_rsa.pub
, but during pasting into github key input box, I removed last newline using backspace, which actually changed the public key.
So, always copy & paste ssh public key as it is without removing last newline.
I Had the same error occurring as I was using the numpy version suggested by the requirements.txt in the repo. When I tried to 'import pandas as pd' this error occurred. Then the solution was to upgrade numpy version to 1.15.2 as the version suggested in the requirements was mismatching with pandas. I uninstalled the existing numpy version with pip and reinstalled the new version.
pip install numpy==1.15.2
Hope this helps someone
The most common advice is wrong, you can't just rely on time()
. That's used for relative timing: ISO C++ doesn't specify that 1970-01-01T00:00Z
is time_t(0)
What's worse is that you can't easily figure it out, either. Sure, you can find the calendar date of time_t(0)
with gmtime
, but what are you going to do if that's 2000-01-01T00:00Z
? How many seconds were there between 1970-01-01T00:00Z
and 2000-01-01T00:00Z
? It's certainly no multiple of 60, due to leap seconds.
>>> unicode_string = u"hello aåbäcö"
>>> unicode_string.encode("ascii", "ignore")
'hello abc'
You can use this site: https://cachedviews.com/ . Cache View or Cached Pages of Any Website - Google Cached Pages of Any Website
Get the name or id of the image you would like to run, with this command:
docker images
The Docker run command is used in the following way:
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Below I have included the dispatch, name, publish, volume and restart options before specifying the image name or id:
docker run -d --name container-name -p localhost:80:80 -v $HOME/myContainer/configDir:/myImage/configDir --restart=always image-name
Where:
--detach , -d Run container in background and print container ID
--name Assign a name to the container
--publish , -p Publish a container’s port(s) to the host
--volume , -v Bind mount a volume
--restart Restart policy to apply when a container exits
For more information, please check out the official Docker run reference.
In your View try like this
<img src= "@Url.Content(Model.ImagePath)" alt="Image" />
The performance of the suggested answer is fine. According to the MongoDB documentation:
When a $sort immediately precedes a $limit, the optimizer can coalesce the $limit into the $sort. This allows the sort operation to only maintain the top n results as it progresses, where n is the specified limit, and MongoDB only needs to store n items in memory.
Changed in version 4.0.
So in the case of
db.collection.find().sort({age:-1}).limit(1)
we get only the highest element WITHOUT sorting the collection because of the mentioned optimization.
As The Tin Man suggests (above) RVM (Ruby Version Manager) is the Standard for upgrading your Ruby installation on OSX: https://rvm.io
To get started, open a Terminal Window and issue the following command:
\curl -L https://get.rvm.io | bash -s stable --ruby
( you will need to trust the RVM Dev Team that the command is not malicious - if you're a paranoid penguin like me, you can always go read the source: https://github.com/wayneeseguin/rvm ) When it's complete you need to restart the terminal to get the rvm
command working.
rvm list known
( shows you the latest available versions of Ruby )
rvm install ruby-2.3.1
For a specific version, followed by
rvm use ruby-2.3.1
or if you just want the latest (current) version:
rvm install current && rvm use current
( installs the current stable release - at time of writing ruby-2.3.1 - please update this wiki when new versions released )
Note on Compiling Ruby: In my case I also had to install Homebrew http://mxcl.github.com/homebrew/ to get the gems I needed (RSpec) which in turn forces you to install Xcode (if you haven't already) https://itunes.apple.com/us/app/xcode/id497799835 AND/OR install the GCC package from: https://github.com/kennethreitz/osx-gcc-installer to avoid errors running "make".
Edit: As of Mavericks you can choose to install only the Xcode command line tools instead of the whole Xcode package, which comes with gcc and lots of other things you might need for building packages. It can be installed by running xcode-select --install
and following the on-screen prompt.
Note on erros: if you get the error "RVM is not a function" while trying this command, visit: How do I change my Ruby version using RVM? for the solution.
Adapting Ijaz Ahmad Khan's answer to only yield lines when they are completely written (lines end with a newline char) gives a pythonic solution with no external dependencies:
def follow(file) -> Iterator[str]:
""" Yield each line from a file as they are written. """
line = ''
while True:
tmp = file.readline()
if tmp is not None:
line += tmp
if line.endswith("\n"):
yield line
line = ''
else:
time.sleep(0.1)
if __name__ == '__main__':
for line in follow(open("test.txt", 'r')):
print(line, end='')
If you want to run a few scripts, you can use Set-executionpolicy -ExecutionPolicy Unrestricted
and then reset with Set-executionpolicy -ExecutionPolicy Default
.
Note that execution policy is only checked when you start its execution (or so it seems) and so you can run jobs in the background and reset the execution policy immediately.
# Check current setting
Get-ExecutionPolicy
# Disable policy
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
# Choose [Y]es
Start-Job { cd c:\working\directory\with\script\ ; ./ping_batch.ps1 example.com | tee ping__example.com.txt }
Start-Job { cd c:\working\directory\with\script\ ; ./ping_batch.ps1 google.com | tee ping__google.com.txt }
# Can be run immediately
Set-ExecutionPolicy -ExecutionPolicy Default
# [Y]es
I was in need of a similar kind of solution, wanted to add data on a wall like facebook, when posted,use prepend()
to add the latest post on top, thought might be useful for others..
$("#statusupdate").submit( function () {
$.post(
'ajax.php',
$(this).serialize(),
function(data){
$("#box").prepend($(data).fadeIn('slow'));
$("#status").val('');
}
);
event.preventDefault();
});
the code in ajax.php is
if (isset($_POST))
{
$feed = $_POST['feed'];
echo "<p id=\"result\" style=\"width:200px;height:50px;background-color:lightgray;display:none;\">$feed</p>";
}
I think there is not similar function like data.shape
in Spark. But I will use len(data.columns)
rather than len(data.dtypes)
Since I found I was doing this in several places in my app, I wrapped it in a plugin:
(function ($) {
$.fn.dialogNoClose = function () {
return this.each(function () {
// hide the close button and prevent ESC key from closing
$(this).closest(".ui-dialog").find(".ui-dialog-titlebar-close").hide();
$(this).dialog("option", "closeOnEscape", false);
});
};
})(jQuery)
Usage Example:
$("#dialog").dialog({ /* lots of options */ }).dialogNoClose();
There are several ways to do a cross join or cartesian product:
SELECT column_names FROM table1 CROSS JOIN table2;
SELECT column_names FROM table1, table2;
SELECT column_names FROM table1 JOIN table2;
Neglecting the on condition in the third case is what results in a cross join.
I know the question was asked 7 years and 9 months ago
but many posted solutions doesn't seem to work, for example using an <iframe>
works only with FireFox
and doesn't work with Chrome
.
Best solution:
The best working solution to open a file download pop-up in JavaScript
is to use a HTML
link element, with no need to append the link element to the document.body
as stated in other answers.
You can use the following function:
function downloadFile(filePath){
var link=document.createElement('a');
link.href = filePath;
link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
link.click();
}
In my application, I am using it this way:
downloadFile('report/xls/myCustomReport.xlsx');
Working Demo:
function downloadFile(filePath) {_x000D_
var link = document.createElement('a');_x000D_
link.href = filePath;_x000D_
link.download = filePath.substr(filePath.lastIndexOf('/') + 1);_x000D_
link.click();_x000D_
}_x000D_
_x000D_
downloadFile("http://www.adobe.com/content/dam/Adobe/en/accessibility/pdfs/accessing-pdf-sr.pdf");
_x000D_
Note:
link.download
attribute so the browser doesn't
open the file in a new tab and fires the download pop-up.first you have to import: import javax.swing.JOptionPane; then you can call it using this:
JOptionPane.showMessageDialog(null,
"ALERT MESSAGE",
"TITLE",
JOptionPane.WARNING_MESSAGE);
the null puts it in the middle of the screen. put whatever in quotes under alert message. Title is obviously title and the last part will format it like an error message. if you want a regular message just replace it with PLAIN_MESSAGE
. it works pretty well in a lot of ways mostly for errors.
The top answer is flawed in my opinion. Hopefully, no one is mass importing all of pandas into their namespace with from pandas import *
. Also, the map
method should be reserved for those times when passing it a dictionary or Series. It can take a function but this is what apply
is used for.
So, if you must use the above approach, I would write it like this
df["A1"], df["A2"] = zip(*df["a"].apply(calculate))
There's actually no reason to use zip here. You can simply do this:
df["A1"], df["A2"] = calculate(df['a'])
This second method is also much faster on larger DataFrames
df = pd.DataFrame({'a': [1,2,3] * 100000, 'b': [2,3,4] * 100000})
DataFrame created with 300,000 rows
%timeit df["A1"], df["A2"] = calculate(df['a'])
2.65 ms ± 92.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit df["A1"], df["A2"] = zip(*df["a"].apply(calculate))
159 ms ± 5.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
60x faster than zip
Apply is generally not much faster than iterating over a Python list. Let's test the performance of a for-loop to do the same thing as above
%%timeit
A1, A2 = [], []
for val in df['a']:
A1.append(val**2)
A2.append(val**3)
df['A1'] = A1
df['A2'] = A2
298 ms ± 7.14 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
So this is twice as slow which isn't a terrible performance regression, but if we cythonize the above, we get much better performance. Assuming, you are using ipython:
%load_ext cython
%%cython
cpdef power(vals):
A1, A2 = [], []
cdef double val
for val in vals:
A1.append(val**2)
A2.append(val**3)
return A1, A2
%timeit df['A1'], df['A2'] = power(df['a'])
72.7 ms ± 2.16 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
You can get even greater speed improvements if you use the direct vectorized operations.
%timeit df['A1'], df['A2'] = df['a'] ** 2, df['a'] ** 3
5.13 ms ± 320 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
This takes advantage of NumPy's extremely fast vectorized operations instead of our loops. We now have a 30x speedup over the original.
apply
The above example should clearly show how slow apply
can be, but just so its extra clear let's look at the most basic example. Let's square a Series of 10 million numbers with and without apply
s = pd.Series(np.random.rand(10000000))
%timeit s.apply(calc)
3.3 s ± 57.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Without apply is 50x faster
%timeit s ** 2
66 ms ± 2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Whenever an UICommand
component (<h:commandXxx>
, <p:commandXxx>
, etc) fails to invoke the associated action method, or an UIInput
component (<h:inputXxx>
, <p:inputXxxx>
, etc) fails to process the submitted values and/or update the model values, and you aren't seeing any googlable exceptions and/or warnings in the server log, also not when you configure an ajax exception handler as per Exception handling in JSF ajax requests, nor when you set below context parameter in web.xml
,
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
and you are also not seeing any googlable errors and/or warnings in browser's JavaScript console (press F12 in Chrome/Firefox23+/IE9+ to open the web developer toolset and then open the Console tab), then work through below list of possible causes.
UICommand
and UIInput
components must be placed inside an UIForm
component, e.g. <h:form>
(and thus not plain HTML <form>
), otherwise nothing can be sent to the server. UICommand
components must also not have type="button"
attribute, otherwise it will be a dead button which is only useful for JavaScript onclick
. See also How to send form input values and invoke a method in JSF bean and <h:commandButton> does not initiate a postback.
You cannot nest multiple UIForm
components in each other. This is illegal in HTML. The browser behavior is unspecified. Watch out with include files! You can use UIForm
components in parallel, but they won't process each other during submit. You should also watch out with "God Form" antipattern; make sure that you don't unintentionally process/validate all other (invisible) inputs in the very same form (e.g. having a hidden dialog with required inputs in the very same form). See also How to use <h:form> in JSF page? Single form? Multiple forms? Nested forms?.
No UIInput
value validation/conversion error should have occurred. You can use <h:messages>
to show any messages which are not shown by any input-specific <h:message>
components. Don't forget to include the id
of <h:messages>
in the <f:ajax render>
, if any, so that it will be updated as well on ajax requests. See also h:messages does not display messages when p:commandButton is pressed.
If UICommand
or UIInput
components are placed inside an iterating component like <h:dataTable>
, <ui:repeat>
, etc, then you need to ensure that exactly the same value
of the iterating component is been preserved during the apply request values phase of the form submit request. JSF will reiterate over it to find the clicked link/button and submitted input values. Putting the bean in the view scope and/or making sure that you load the data model in @PostConstruct
of the bean (and thus not in a getter method!) should fix it. See also How and when should I load the model from database for h:dataTable.
If UICommand
or UIInput
components are included by a dynamic source such as <ui:include src="#{bean.include}">
, then you need to ensure that exactly the same #{bean.include}
value is preserved during the view build time of the form submit request. JSF will reexecute it during building the component tree. Putting the bean in the view scope and/or making sure that you load the data model in @PostConstruct
of the bean (and thus not in a getter method!) should fix it. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).
The rendered
attribute of the component and all of its parents and the test
attribute of any parent <c:if>
/<c:when>
should not evaluate to false
during the apply request values phase of the form submit request. JSF will recheck it as part of safeguard against tampered/hacked requests. Storing the variables responsible for the condition in a @ViewScoped
bean or making sure that you're properly preinitializing the condition in @PostConstruct
of a @RequestScoped
bean should fix it. The same applies to the disabled
and readonly
attributes of the component, which should not evaluate to true
during apply request values phase. See also JSF CommandButton action not invoked, Form submit in conditionally rendered component is not processed, h:commandButton is not working once I wrap it in a <h:panelGroup rendered> and Force JSF to process, validate and update readonly/disabled input components anyway
The onclick
attribute of the UICommand
component and the onsubmit
attribute of the UIForm
component should not return false
or cause a JavaScript error. There should in case of <h:commandLink>
or <f:ajax>
also be no JS errors visible in the browser's JS console. Usually googling the exact error message will already give you the answer. See also Manually adding / loading jQuery with PrimeFaces results in Uncaught TypeErrors.
If you're using Ajax via JSF 2.x <f:ajax>
or e.g. PrimeFaces <p:commandXxx>
, make sure that you have a <h:head>
in the master template instead of the <head>
. Otherwise JSF won't be able to auto-include the necessary JavaScript files which contains the Ajax functions. This would result in a JavaScript error like "mojarra is not defined" or "PrimeFaces is not defined" in browser's JS console. See also h:commandLink actionlistener is not invoked when used with f:ajax and ui:repeat.
If you're using Ajax, and the submitted values end up being null
, then make sure that the UIInput
and UICommand
components of interest are covered by the <f:ajax execute>
or e.g. <p:commandXxx process>
, otherwise they won't be executed/processed. See also Submitted form values not updated in model when adding <f:ajax> to <h:commandButton> and Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes.
If the submitted values still end up being null
, and you're using CDI to manage beans, then make sure that you import the scope annotation from the correct package, else CDI will default to @Dependent
which effectively recreates the bean on every single evaluation of the EL expression. See also @SessionScoped bean looses scope and gets recreated all the time, fields become null and What is the default Managed Bean Scope in a JSF 2 application?
If a parent of the <h:form>
with the UICommand
button is beforehand been rendered/updated by an ajax request coming from another form in the same page, then the first action will always fail in JSF 2.2 or older. The second and subsequent actions will work. This is caused by a bug in view state handling which is reported as JSF spec issue 790 and currently fixed in JSF 2.3. For older JSF versions, you need to explicitly specify the ID of the <h:form>
in the render
of the <f:ajax>
. See also h:commandButton/h:commandLink does not work on first click, works only on second click.
If the <h:form>
has enctype="multipart/form-data"
set in order to support file uploading, then you need to make sure that you're using at least JSF 2.2, or that the servlet filter who is responsible for parsing multipart/form-data requests is properly configured, otherwise the FacesServlet
will end up getting no request parameters at all and thus not be able to apply the request values. How to configure such a filter depends on the file upload component being used. For Tomahawk <t:inputFileUpload>
, check this answer and for PrimeFaces <p:fileUpload>
, check this answer. Or, if you're actually not uploading a file at all, then remove the attribute altogether.
Make sure that the ActionEvent
argument of actionListener
is an javax.faces.event.ActionEvent
and thus not java.awt.event.ActionEvent
, which is what most IDEs suggest as 1st autocomplete option. Having no argument is wrong as well if you use actionListener="#{bean.method}"
. If you don't want an argument in your method, use actionListener="#{bean.method()}"
. Or perhaps you actually want to use action
instead of actionListener
. See also Differences between action and actionListener.
Make sure that no PhaseListener
or any EventListener
in the request-response chain has changed the JSF lifecycle to skip the invoke action phase by for example calling FacesContext#renderResponse()
or FacesContext#responseComplete()
.
Make sure that no Filter
or Servlet
in the same request-response chain has blocked the request fo the FacesServlet
somehow. For example, login/security filters such as Spring Security. Particularly in ajax requests that would by default end up with no UI feedback at all. See also Spring Security 4 and PrimeFaces 5 AJAX request handling.
If you are using a PrimeFaces <p:dialog>
or a <p:overlayPanel>
, then make sure that they have their own <h:form>
. Because, these components are by default by JavaScript relocated to end of HTML <body>
. So, if they were originally sitting inside a <form>
, then they would now not anymore sit in a <form>
. See also p:commandbutton action doesn't work inside p:dialog
Bug in the framework. For example, RichFaces has a "conversion error" when using a rich:calendar
UI element with a defaultLabel
attribute (or, in some cases, a rich:placeholder
sub-element). This bug prevents the bean method from being invoked when no value is set for the calendar date. Tracing framework bugs can be accomplished by starting with a simple working example and building the page back up until the bug is discovered.
In case you still stucks, it's time to debug. In the client side, press F12 in webbrowser to open the web developer toolset. Click the Console tab so see the JavaScript conosle. It should be free of any JavaScript errors. Below screenshot is an example from Chrome which demonstrates the case of submitting an <f:ajax>
enabled button while not having <h:head>
declared (as described in point 7 above).
Click the Network tab to see the HTTP traffic monitor. Submit the form and investigate if the request headers and form data and the response body are as per expectations. Below screenshot is an example from Chrome which demonstrates a successful ajax submit of a simple form with a single <h:inputText>
and a single <h:commandButton>
with <f:ajax execute="@form" render="@form">
.
(warning: when you post screenshots from HTTP request headers like above from a production environment, then make sure you scramble/obfuscate any session cookies in the screenshot to avoid session hijacking attacks!)
In the server side, make sure that server is started in debug mode. Put a debug breakpoint in a method of the JSF component of interest which you expect to be called during processing the form submit. E.g. in case of UICommand
component, that would be UICommand#queueEvent()
and in case of UIInput
component, that would be UIInput#validate()
. Just step through the code execution and inspect if the flow and variables are as per expectations. Below screenshot is an example from Eclipse's debugger.
As it was mentioned above, the answer depends on your case. If you want to escape a string for a regular expression then you should use re.escape(). But if you want to escape a specific set of characters then use this lambda function:
>>> escape = lambda s, escapechar, specialchars: "".join(escapechar + c if c in specialchars or c == escapechar else c for c in s)
>>> s = raw_input()
I'm "stuck" :\
>>> print s
I'm "stuck" :\
>>> print escape(s, "\\", ['"'])
I'm \"stuck\" :\\
Use the keyword size
instead of fontsize
.
like this
\begin{align}
x_{\rm L} & = L \int{\cos\theta\left(\xi\right) d\xi}, \label{eq_1} \\\\
y_{\rm L} & = L \int{\sin\theta\left(\xi\right) d\xi}, \nonumber
\end{align}
In javascript due to the following i++ may be better to use:
var i=1;
alert(i++); // before, 1. current, 1. after, 2.
alert(i); // before, 2. current, 2. after, 2.
alert(++i); // before, 2. current, 3 after, 3.
While arrays (I think all) and some other functions and calls use 0 as a starting point you would have to set i to -1 to make the loop work with the array when using ++i.
When using i++ the following value will use the increased value. You could say i++ is the way humans count, cause you can start with a 0.
Here's a document from Microsoft themselves. Hope that helps..., it's from 2003, but it might still be relevant.
The simplest of them all:
<div onclick="location.href='where.you.want.to.go'" style="cursor:pointer"></div>
- location = location
- location = location.href
- location = window.location
- location = self.location
- location = window.location.href
- location = self.location.href
- location = location['href']
- location = window['location']
- location = window['location'].href
- location = window['location']['href']
You don't need jQuery for this. You can do it with JavaScript.
function _formatDatetime(date: Date, format: string) {
const _padStart = (value: number): string => value.toString().padStart(2, '0');
return format
.replace(/yyyy/g, _padStart(date.getFullYear()))
.replace(/dd/g, _padStart(date.getDate()))
.replace(/mm/g, _padStart(date.getMonth() + 1))
.replace(/hh/g, _padStart(date.getHours()))
.replace(/ii/g, _padStart(date.getMinutes()))
.replace(/ss/g, _padStart(date.getSeconds()));
}
function isValidDate(d: Date): boolean {
return !isNaN(d.getTime());
}
export function formatDate(date: any): string {
var datetime = new Date(date);
return isValidDate(datetime) ? _formatDatetime(datetime, 'yyyy-mm-dd hh:ii:ss') : '';
}
You must to set by this order:
<link rel="stylesheet" href="path/bootstrap.min.css">
<style type="text/css">
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}
</style>
I was experienced this case; I need the react/redux site that should be working perfectly in production.
but there was a 'strict mode'; Shouldn't lunch it with these commands.
yarn global add serve
serve -s build
Should working with only click the build/index.html file. When I used fontawesome with npm font-awesome, it was working in development mode but not working in the 'strict mode'.
Here is my solution:
public/css/font-awesome.min.css
public/fonts/font-awesome.eot
*** other different types of files(4) ***
*** I copied these files for node_module/font-awesome ***
*** after copied then can delete the font-awesome from package.json ***
in public/index.html
<link rel="stylesheet" href="%PUBLIC_URL%/css/font-awesome.min.css">
After all of above steps, the fontawesome works NICELY!!!
With the global configuration that you have defined for the exec-maven-plugin:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.4.0</version>
<configuration>
<mainClass>org.dhappy.test.NeoTraverse</mainClass>
</configuration>
</plugin>
invoking mvn exec:java
on the command line will invoke the plugin which is configured to execute the class org.dhappy.test.NeoTraverse
.
So, to trigger the plugin from the command line, just run:
mvn exec:java
Now, if you want to execute the exec:java
goal as part of your standard build, you'll need to bind the goal to a particular phase of the default lifecycle. To do this, declare the phase
to which you want to bind the goal in the execution
element:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<id>my-execution</id>
<phase>package</phase>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>org.dhappy.test.NeoTraverse</mainClass>
</configuration>
</plugin>
With this example, your class would be executed during the package
phase. This is just an example, adapt it to suit your needs. Works also with plugin version 1.1.
It looks like you want a grid to evaluate your function, in which case you can use numpy.ogrid
(open) or numpy.mgrid
(fleshed out):
import numpy
my_grid = numpy.mgrid[[slice(0,1,0.1)]*6]
You can also simply use the HtmlString
class
@(new HtmlString(Model.Content))
a=1;
b=2;
x=3;
y=4;
answer = a > b ? x : y;
answer=4
since the condition is false it takes y value.
A question mark (?)
. The value to use if the condition is true
A colon (:)
. The value to use if the condition is false
Here's one site that will format your code and spit out html, and it even includes inline styles for syntax coloring. Might not work for all of your needs, but is a good start. I believe he has made the source available if you want to extend it:
Remove:
httpRequest.setRequestHeader( 'Access-Control-Allow-Origin', '*');
... and add:
httpRequest.withCredentials = false;
Unicode and encodings are completely different, unrelated things.
Assigns a numeric ID to each character:
So, Unicode assigns the number 0x41 to A, 0xE1 to á, and 0x414 to ?.
Even the little arrow ? I used has its Unicode number, it's 0x2192. And even emojis have their Unicode numbers, is 0x1F602.
You can look up the Unicode numbers of all characters in this table. In particular, you can find the first three characters above here, the arrow here, and the emoji here.
These numbers assigned to all characters by Unicode are called code points.
The purpose of all this is to provide a means to unambiguously refer to a each character. For example, if I'm talking about , instead of saying "you know, this laughing emoji with tears", I can just say, Unicode code point 0x1F602. Easier, right?
Note that Unicode code points are usually formatted with a leading U+
, then the hexadecimal numeric value padded to at least 4 digits. So, the above examples would be U+0041, U+00E1, U+0414, U+2192, U+1F602.
Unicode code points range from U+0000 to U+10FFFF. That is 1,114,112 numbers. 2048 of these numbers are used for surrogates, thus, there remain 1,112,064. This means, Unicode can assign a unique ID (code point) to 1,112,064 distinct characters. Not all of these code points are assigned to a character yet, and Unicode is extended continuously (for example, when new emojis are introduced).
The important thing to remember is that all Unicode does is to assign a numerical ID, called code point, to each character for easy and unambiguous reference.
Map characters to bit patterns.
These bit patterns are used to represent the characters in computer memory or on disk.
There are many different encodings that cover different subsets of characters. In the English-speaking world, the most common encodings are the following:
Maps 128 characters (code points U+0000 to U+007F) to bit patterns of length 7.
Example:
You can see all the mappings in this table.
Maps 191 characters (code points U+0020 to U+007E and U+00A0 to U+00FF) to bit patterns of length 8.
Example:
You can see all the mappings in this table.
Maps 1,112,064 characters (all existing Unicode code points) to bit patterns of either length 8, 16, 24, or 32 bits (that is, 1, 2, 3, or 4 bytes).
Example:
The way UTF-8 encodes characters to bit strings is very well described here.
Looking at the above examples, it becomes clear how Unicode is useful.
For example, if I'm Latin-1 and I want to explain my encoding of á, I don't need to say:
"I encode that a with an aigu (or however you call that rising bar) as 11100001"
But I can just say:
"I encode U+00E1 as 11100001"
And if I'm UTF-8, I can say:
"Me, in turn, I encode U+00E1 as 11000011 10100001"
And it's unambiguously clear to everybody which character we mean.
It's true that sometimes the bit pattern of an encoding, if you interpret it as a binary number, is the same as the Unicode code point of this character.
For example:
Of course, this has been arranged like this on purpose for convenience. But you should look at it as a pure coincidence. The bit pattern used to represent a character in memory is not tied in any way to the Unicode code point of this character.
Nobody even says that you have to interpret a bit string like 11100001 as a binary number. Just look at it as the sequence of bits that Latin-1 uses to encode the character á.
The encoding used by your Python interpreter is UTF-8.
Here's what's going on in your examples:
The following encodes the character á in UTF-8. This results in the bit string 11000011 10100001, which is saved in the variable a
.
>>> a = 'á'
When you look at the value of a
, its content 11000011 10100001 is formatted as the hex number 0xC3 0xA1 and output as '\xc3\xa1'
:
>>> a
'\xc3\xa1'
The following saves the Unicode code point of á, which is U+00E1, in the variable ua
(we don't know which data format Python uses internally to represent the code point U+00E1 in memory, and it's unimportant to us):
>>> ua = u'á'
When you look at the value of ua
, Python tells you that it contains the code point U+00E1:
>>> ua
u'\xe1'
The following encodes Unicode code point U+00E1 (representing character á) with UTF-8, which results in the bit pattern 11000011 10100001. Again, for output this bit pattern is represented as the hex number 0xC3 0xA1:
>>> ua.encode('utf-8')
'\xc3\xa1'
The following encodes Unicode code point U+00E1 (representing character á) with Latin-1, which results in the bit pattern 11100001. For output, this bit pattern is represented as the hex number 0xE1, which by coincidence is the same as the initial code point U+00E1:
>>> ua.encode('latin1')
'\xe1'
There's no relation between the Unicode object ua
and the Latin-1 encoding. That the code point of á is U+00E1 and the Latin-1 encoding of á is 0xE1 (if you interpret the bit pattern of the encoding as a binary number) is a pure coincidence.
The absolutely best way: Just let your activity implement View.OnClickListener
, and write your onClick
method like this:
public void onClick(View v) {
final int id = v.getId();
switch (id) {
case R.id.button1:
// your code for button1 here
break;
case R.id.button2:
// your code for button2 here
break;
// even more buttons here
}
}
Then, in your XML layout file, you can set the click listeners directly using the attribute android:onClick
:
<Button
android:id="@+id/button1"
android:onClick="onClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1" />
That is the most cleanest way of how to do it. I use it in all of mine projects today, as well.
For those that like to over-use LINQ.
(from f in new DirectoryInfo("C:/Temp").GetFiles()
where f.CreationTime < DateTime.Now.Subtract(TimeSpan.FromDays(90))
select f
).ToList()
.ForEach(f => f.Delete());
More on gdoron's answer, it can also be done this way:
$(window).on("click", "#filter", function() {
alert('clicked!');
});
without the need to place them all into $(function(){...})
long totalSeconds = currentTimeMillis / 1000;
int currentSecond = (int)totalSeconds % 60;
long totalMinutes = totalSeconds / 60;
int currentMinute = (int)totalMinutes % 60;
long totalHours = totalMinutes / 60;
int currentHour = (int)totalHours % 12;
TextView tvTime = findViewById(R.id.tvTime);
tvTime.setText((currentHour + OR - TIME YOU ARE FROM GMT) + ":" + currentMinute + ":" + currentSecond);
Can be achieved also with scriptrunner
ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30
Which also have some features as rollback , timeout and waiting.
You can use DataFrame.loc
:
>>> df.loc[1]
>>> print(df)
result
A B C
1 1 1 6
2 9
2 1 8
2 11
2 1 1 7
2 10
2 1 9
2 12
>>> print(df.loc[1])
result
B C
1 1 6
2 9
2 1 8
2 11
>>> print(df.loc[2, 1])
result
C
1 7
2 10
I wonder why there is no example of stand alone jar project.
In eclipse, we just check "Is Library" box in project setting dialog.
In Android studio, I followed this steps and got a jar file.
Create a project.
open file in the left project menu.(app/build.gradle): Gradle Scripts > build.gradle(Module: XXX)
change one line: apply plugin: 'com.android.application'
-> 'apply plugin: com.android.library'
remove applicationId in the file: applicationId "com.mycompany.testproject"
build project: Build > Rebuild Project
then you can get aar file: app > build > outputs > aar folder
change aar
file extension name into zip
unzip, and you can see classes.jar
in the folder.
rename and use it!
Anyway, I don't know why google makes jar creation so troublesome in android studio.
Your code below is zooming the map to fit the specified bounds:
addMarker(27.703402,85.311668,'New Road');
center = bounds.getCenter();
map.fitBounds(bounds);
If you only have 1 marker and add it to the bounds, that results in the closest zoom possible:
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
}
If you keep track of the number of markers you have "added" to the map (or extended the bounds with), you can only call fitBounds if that number is greater than one. I usually push the markers into an array (for later use) and test the length of that array.
If you will only ever have one marker, don't use fitBounds. Call setCenter
, setZoom
with the marker position and your desired zoom level.
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
map.setCenter(pt);
map.setZoom(your desired zoom);
}
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
}
_x000D_
<html>
<head>
<script src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" type="text/javascript"></script>
<script type="text/javascript">
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png", new google.maps.Size(32, 32), new google.maps.Point(0, 0), new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
map.setCenter(pt);
map.setZoom(5);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
});
addMarker(27.703402, 85.311668, 'New Road');
// center = bounds.getCenter();
// map.fitBounds(bounds);
}
</script>
</head>
<body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
<div id="map"></div>
</body>
</html>
_x000D_
For me it was for removing some credentials from a repo. I tried rebasing and ran into a ton of seemingly unrelated conflicts along the way when trying to rebase --continue. Don't bother attempting to rebase yourself, use the tool called BFG (brew install bfg) on mac.
I guess its speed is worth 16 extra bytes.
static char[] hexes = new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
public static string ToHexadecimal (this byte[] Bytes)
{
char[] Result = new char[Bytes.Length << 1];
int Offset = 0;
for (int i = 0; i != Bytes.Length; i++) {
Result[Offset++] = hexes[Bytes[i] >> 4];
Result[Offset++] = hexes[Bytes[i] & 0x0F];
}
return new string(Result);
}
You need to #include <stdlib.h>
. Otherwise it's defined as int malloc()
which is incompatible with the built-in type void *malloc(size_t)
.
Remove the comma
receipt int(10),
And also AUTO INCREMENT
should be a KEY
double
datatype also requires the precision of decimal places so right syntax is double(10,2)
The biggest PITA of Oracle is that is does not have a default date format!
In your installation of Oracle the combination of Locales and install options has picked (the very sensible!) YYYY-MM-DD as the format for outputting dates. Another installation could have picked "DD/MM/YYYY" or "YYYY/DD/MM".
If you want your SQL to be portable to another Oracle site I would recommend you always wrap a TO_CHAR(datecol,'YYYY-MM-DD')
or similar function around each date column your SQL or alternativly set the defualt format immediatly after you connect with
ALTER SESSION
SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';
or similar.
This is my code:
try {_x000D_
String folderPath = "../" + filePath.trim() + "/";_x000D_
logger.info("Path: " + folderPath);_x000D_
File folder = new File(folderPath);_x000D_
File[] listOfFiles = folder.listFiles();_x000D_
int length = listOfFiles.length;_x000D_
logger.info("So luong files: " + length);_x000D_
ArrayList<CdrFileBO> lstFile = new ArrayList< CdrFileBO>();_x000D_
_x000D_
if (listOfFiles != null && length > 0) {_x000D_
int count = 0;_x000D_
for (int i = 0; i < length; i++) {_x000D_
if (listOfFiles[i].isFile()) {_x000D_
lstFile.add(new CdrFileBO(listOfFiles[i]));_x000D_
}_x000D_
}_x000D_
Collections.sort(lstFile);_x000D_
for (CdrFileBO bo : lstFile) {_x000D_
//String newName = START_NAME + "_" + getSeq(SEQ_START) + "_" + DateSTR + ".s";_x000D_
String newName = START_NAME + DateSTR + getSeq(SEQ_START) + ".DAT";_x000D_
SEQ_START = SEQ_START + 1;_x000D_
bo.getFile().renameTo(new File(folderPath + newName));_x000D_
logger.info("newName: " + newName);_x000D_
logger.info("Next file: " + getSeq(SEQ_START));_x000D_
}_x000D_
_x000D_
}_x000D_
} catch (Exception ex) {_x000D_
logger.error(ex);_x000D_
ex.printStackTrace();_x000D_
}
_x000D_
You should use strftime
static method from datetime
class from datetime
module. Try:
import datetime
dtDate = datetime.datetime.strptime("07/27/2012", "%m/%d/%Y")
Margin="1,2,3,4"
It is also possible to specify just two sizes like this:
Margin="1,2"
Finally you can specify a single size:
Margin="1"
The order is the same as in WinForms.
This will remove the option
tag and just leave the letters in vim:
:%s/<option.*>//g
For those of you who hit this stackoverflow entry because it ranks high for the phrase:
The page cannot be displayed because an internal server error has occurred.
In my personal situation with this exact error message, I had turned on python 2.7 thinking I could use some python with my .NET API. I then had that exact error message when I attempted to deploy a vanilla version of the API or MVC from visual studio pro 2013. I was deploying to an azure cloud webapp.
Hope this helps anyone with my same experience. I didn't even think to turn off python until I found this suggestion.
For external url you have to use "http://www.yahoo.com" as the redirect url.
This is explained in the redirect: prefix of Spring reference documentation.
redirect:/myapp/some/resource
will redirect relative to the current Servlet context, while a name such as
will redirect to an absolute URL
Currently it only works for the .dropdown-menu
:
.dropdown-menu .divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
If you want it for other use, in your own css, following the bootstrap.css create another one:
.divider {
height: 1px;
width:100%;
display:block; /* for use on default inline elements like span */
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
For Debian. Required packages are: m4 automake pkg-config libtool
This was the exact issue I ran into with our client. I created a little jquery plugin that seems to work for iframe readiness. It uses polling to check the iframe document readyState combined with the inner document url combined with the iframe source to make sure the iframe is in fact "ready".
The issue with "onload" is that you need access to the actual iframe being added to the DOM, if you don't then you need to try to catch the iframe loading which if it is cached then you may not. What I needed was a script that could be called anytime, and determine whether or not the iframe was "ready" or not.
Here's the question:
Holy grail for determining whether or not local iframe has loaded
and here's the jsfiddle I eventually came up with.
https://jsfiddle.net/q0smjkh5/10/
In the jsfiddle above, I am waiting for onload to append an iframe to the dom, then checking iframe's inner document's ready state - which should be cross domain because it's pointed to wikipedia - but Chrome seems to report "complete". The plug-in's iready method then gets called when the iframe is in fact ready. The callback tries to check the inner document's ready state again - this time reporting a cross domain request (which is correct) - anyway it seems to work for what I need and hope it helps others.
<script>
(function($, document, undefined) {
$.fn["iready"] = function(callback) {
var ifr = this.filter("iframe"),
arg = arguments,
src = this,
clc = null, // collection
lng = 50, // length of time to wait between intervals
ivl = -1, // interval id
chk = function(ifr) {
try {
var cnt = ifr.contents(),
doc = cnt[0],
src = ifr.attr("src"),
url = doc.URL;
switch (doc.readyState) {
case "complete":
if (!src || src === "about:blank") {
// we don't care about empty iframes
ifr.data("ready", "true");
} else if (!url || url === "about:blank") {
// empty document still needs loaded
ifr.data("ready", undefined);
} else {
// not an empty iframe and not an empty src
// should be loaded
ifr.data("ready", true);
}
break;
case "interactive":
ifr.data("ready", "true");
break;
case "loading":
default:
// still loading
break;
}
} catch (ignore) {
// as far as we're concerned the iframe is ready
// since we won't be able to access it cross domain
ifr.data("ready", "true");
}
return ifr.data("ready") === "true";
};
if (ifr.length) {
ifr.each(function() {
if (!$(this).data("ready")) {
// add to collection
clc = (clc) ? clc.add($(this)) : $(this);
}
});
if (clc) {
ivl = setInterval(function() {
var rd = true;
clc.each(function() {
if (!$(this).data("ready")) {
if (!chk($(this))) {
rd = false;
}
}
});
if (rd) {
clearInterval(ivl);
clc = null;
callback.apply(src, arg);
}
}, lng);
} else {
clc = null;
callback.apply(src, arg);
}
} else {
clc = null;
callback.apply(this, arguments);
}
return this;
};
}(jQuery, document));
</script>
you can use unfactor()
function from "varhandle" package form CRAN:
library("varhandle")
my_iris <- data.frame(Sepal.Length = factor(iris$Sepal.Length),
sample_id = factor(1:nrow(iris)))
my_iris <- unfactor(my_iris)
If you declare it like
int x;
in a header file which is then included in multiple places, you'll end up with multiple instances of x (and potentially compile or link problems).
The correct way to approach this is to have the header file say
extern int x; /* declared in foo.c */
and then in foo.c you can say
int x; /* exported in foo.h */
THen you can include your header file in as many places as you like.
Just as an empty Request body is in keeping with the original purpose of a GET request and empty response body is in keeping with the original purpose of a PUT request.
See the answer to this question on address validating with regex: regex street address match
The problem is, street addresses vary so much in formatting that it's hard to code against them. If you are trying to validate addresses, finding if one isn't valid based on its format is mighty hard to do. This would return the following address (253 N. Cherry St. ), anything with its same format:
\d{1,5}\s\w.\s(\b\w*\b\s){1,2}\w*\.
This allows 1-5 digits for the house number, a space, a character followed by a period (for N. or S.), 1-2 words for the street name, finished with an abbreviation (like st. or rd.).
Because regex is used to see if things meet a standard or protocol (which you define), you probably wouldn't want to allow for the addresses provided above, especially the first one with the dash, since they aren't very standard. you can modify my above code to allow for them if you wish--you could add
(-?)
to allow for a dash but not require one.
In addition, http://rubular.com/ is a quick and interactive way to learn regex. Try it out with the addresses above.
I am using this one. though not yet tested on all browser. just modify this in the way you like,
usage: hlight($("#mydiv"));
function hlight(elementid){
var hlight= "#fe1414"; //set the hightlight color
var aspeed= 2000; //set animation speed
var orig= "#ffffff"; // set default background color
elementid.stop().css("background-color", hlight).animate({backgroundColor: orig}, aspeed);
}
NOTE: you need a jquery UI added to your header.
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
Difficult task. I would normally suggest to grab a debugger/memory profiler like Valgrind and run the programs one after one in it. Soon or later you will find the program that leaks and can tell it the devloper or fix it yourself.
For completeness:
Along the lines of Chase's answer, I usually use as.data.frame
to coerce the matrix to a data.frame:
m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))
EDIT: speed test data.frame
vs. as.data.frame
system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
8.005 0.108 8.165
system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
user system elapsed
3.759 0.048 3.802
Yes, it appears to be faster (by about 2 times).
The "problem" with the tabs is that they indent the text to fixed tab positions, typically multiples of 4 or 8 characters (depending on the console or editor displaying them). Your first filename is 7 chars, so the next tab stop after its end is at position 8. Your subsequent filenames however are 8 chars long, so the next tab stop is at position 12.
If you want to ensure that columns get nicely indented at the same position, you need to take into account the actual length of previous columns, and either modify the number of following tabs, or pad with the required number of spaces instead. The latter can be achieved using e.g. System.out.printf
with an appropriate format specification (e.g. "%1$13s"
specifies a minimum width of 13 characters for displaying the first argument as a string).
Mmh ... there are many ways. I answer another network discovery question, and I write a little getting started.
Some tcpip stacks reply to icmp broadcasts. So you can try a PING to your network broadcast address.
For example, you have ip 192.168.1.1 and subnet 255.255.255.0
Note : on step 3. you get the lists of the MAC-to-IP cached entries, so there are also the hosts in your subnet you exchange data to in the last minutes, even if they don't reply to icmp_get.
Note (2) : now I am on linux. I am not sure, but it can be windows doesn't reply to icm_get via broadcast.
Is it the only one device attached to your pc ? Is it a router or another simple pc ?
Its not possible thats the whole point of hashing. You can however bruteforce by going through all possibilities (using all possible digits characters in every possible order) and hashing them and checking for a collision.
for more information on hashing and MD5 etc see: http://en.wikipedia.org/wiki/MD5 , http://en.wikipedia.org/wiki/Hash_function , http://en.wikipedia.org/wiki/Cryptographic_hash_function and http://onin.com/hhh/hhhexpl.html
I myself created my own app to do this, its open source you can check the link: http://sourceforge.net/projects/jpassrecovery/ and of course the source. Here is the source for easy access it has a basic implementation in the comments:
Bruter.java:
import java.util.ArrayList;
public class Bruter {
public ArrayList<String> characters = new ArrayList<>();
public boolean found = false;
public int maxLength;
public int minLength;
public int count;
long starttime, endtime;
public int minutes, seconds, hours, days;
public char[] specialCharacters = {'~', '`', '!', '@', '#', '$', '%', '^',
'&', '*', '(', ')', '_', '-', '+', '=', '{', '}', '[', ']', '|', '\\',
';', ':', '\'', '"', '<', '.', ',', '>', '/', '?', ' '};
public boolean done = false;
public boolean paused = false;
public boolean isFound() {
return found;
}
public void setPaused(boolean paused) {
this.paused = paused;
}
public boolean isPaused() {
return paused;
}
public void setFound(boolean found) {
this.found = found;
}
public synchronized void setEndtime(long endtime) {
this.endtime = endtime;
}
public int getCounter() {
return count;
}
public long getRemainder() {
return getNumberOfPossibilities() - count;
}
public long getNumberOfPossibilities() {
long possibilities = 0;
for (int i = minLength; i <= maxLength; i++) {
possibilities += (long) Math.pow(characters.size(), i);
}
return possibilities;
}
public void addExtendedSet() {
for (char c = (char) 0; c <= (char) 31; c++) {
characters.add(String.valueOf(c));
}
}
public void addStandardCharacterSet() {
for (char c = (char) 32; c <= (char) 127; c++) {
characters.add(String.valueOf(c));
}
}
public void addLowerCaseLetters() {
for (char c = 'a'; c <= 'z'; c++) {
characters.add(String.valueOf(c));
}
}
public void addDigits() {
for (int c = 0; c <= 9; c++) {
characters.add(String.valueOf(c));
}
}
public void addUpperCaseLetters() {
for (char c = 'A'; c <= 'Z'; c++) {
characters.add(String.valueOf(c));
}
}
public void addSpecialCharacters() {
for (char c : specialCharacters) {
characters.add(String.valueOf(c));
}
}
public void setMaxLength(int i) {
maxLength = i;
}
public void setMinLength(int i) {
minLength = i;
}
public int getPerSecond() {
int i;
try {
i = (int) (getCounter() / calculateTimeDifference());
} catch (Exception ex) {
return 0;
}
return i;
}
public String calculateTimeElapsed() {
long timeTaken = calculateTimeDifference();
seconds = (int) timeTaken;
if (seconds > 60) {
minutes = (int) (seconds / 60);
if (minutes * 60 > seconds) {
minutes = minutes - 1;
}
if (minutes > 60) {
hours = (int) minutes / 60;
if (hours * 60 > minutes) {
hours = hours - 1;
}
}
if (hours > 24) {
days = (int) hours / 24;
if (days * 24 > hours) {
days = days - 1;
}
}
seconds -= (minutes * 60);
minutes -= (hours * 60);
hours -= (days * 24);
days -= (hours * 24);
}
return "Time elapsed: " + days + "days " + hours + "h " + minutes + "min " + seconds + "s";
}
private long calculateTimeDifference() {
long timeTaken = (long) ((endtime - starttime) * (1 * Math.pow(10, -9)));
return timeTaken;
}
public boolean excludeChars(String s) {
char[] arrayChars = s.toCharArray();
for (int i = 0; i < arrayChars.length; i++) {
characters.remove(arrayChars[i] + "");
}
if (characters.size() < maxLength) {
return false;
} else {
return true;
}
}
public int getMaxLength() {
return maxLength;
}
public int getMinLength() {
return minLength;
}
public void setIsDone(Boolean b) {
done = b;
}
public boolean isDone() {
return done;
}
}
HashBruter.java:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import javax.swing.JOptionPane;
public class HashBruter extends Bruter {
/*
* public static void main(String[] args) {
*
* final HashBruter hb = new HashBruter();
*
* hb.setMaxLength(5); hb.setMinLength(1);
*
* hb.addSpecialCharacters(); hb.addUpperCaseLetters();
* hb.addLowerCaseLetters(); hb.addDigits();
*
* hb.setType("sha-512");
*
* hb.setHash("282154720ABD4FA76AD7CD5F8806AA8A19AEFB6D10042B0D57A311B86087DE4DE3186A92019D6EE51035106EE088DC6007BEB7BE46994D1463999968FBE9760E");
*
* Thread thread = new Thread(new Runnable() {
*
* @Override public void run() { hb.tryBruteForce(); } });
*
* thread.start();
*
* while (!hb.isFound()) { System.out.println("Hash: " +
* hb.getGeneratedHash()); System.out.println("Number of Possibilities: " +
* hb.getNumberOfPossibilities()); System.out.println("Checked hashes: " +
* hb.getCounter()); System.out.println("Estimated hashes left: " +
* hb.getRemainder()); }
*
* System.out.println("Found " + hb.getType() + " hash collision: " +
* hb.getGeneratedHash() + " password is: " + hb.getPassword());
*
* }
*/
public String hash, generatedHash, password;
public String type;
public String getType() {
return type;
}
public String getPassword() {
return password;
}
public void setHash(String p) {
hash = p;
}
public void setType(String digestType) {
type = digestType;
}
public String getGeneratedHash() {
return generatedHash;
}
public void tryBruteForce() {
starttime = System.nanoTime();
for (int size = minLength; size <= maxLength; size++) {
if (found == true || done == true) {
break;
} else {
while (paused) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
generateAllPossibleCombinations("", size);
}
}
done = true;
}
private void generateAllPossibleCombinations(String baseString, int length) {
while (paused) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
if (found == false || done == false) {
if (baseString.length() == length) {
if(type.equalsIgnoreCase("crc32")) {
generatedHash = generateCRC32(baseString);
} else if(type.equalsIgnoreCase("adler32")) {
generatedHash = generateAdler32(baseString);
} else if(type.equalsIgnoreCase("crc16")) {
generatedHash=generateCRC16(baseString);
} else if(type.equalsIgnoreCase("crc64")) {
generatedHash=generateCRC64(baseString.getBytes());
}
else {
generatedHash = generateHash(baseString.toCharArray());
}
password = baseString;
if (hash.equals(generatedHash)) {
password = baseString;
found = true;
done = true;
}
count++;
} else if (baseString.length() < length) {
for (int n = 0; n < characters.size(); n++) {
generateAllPossibleCombinations(baseString + characters.get(n), length);
}
}
}
}
private String generateHash(char[] passwordChar) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance(type);
} catch (NoSuchAlgorithmException e1) {
JOptionPane.showMessageDialog(null, "No such algorithm for hashes exists", "Error", JOptionPane.ERROR_MESSAGE);
}
String passwordString = new String(passwordChar);
byte[] passwordByte = passwordString.getBytes();
md.update(passwordByte, 0, passwordByte.length);
byte[] encodedPassword = md.digest();
String encodedPasswordInString = toHexString(encodedPassword);
return encodedPasswordInString;
}
private void byte2hex(byte b, StringBuffer buf) {
char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F'};
int high = ((b & 0xf0) >> 4);
int low = (b & 0x0f);
buf.append(hexChars[high]);
buf.append(hexChars[low]);
}
private String toHexString(byte[] block) {
StringBuffer buf = new StringBuffer();
int len = block.length;
for (int i = 0; i < len; i++) {
byte2hex(block[i], buf);
}
return buf.toString();
}
private String generateCRC32(String baseString) {
//Convert string to bytes
byte bytes[] = baseString.getBytes();
Checksum checksum = new CRC32();
/*
* To compute the CRC32 checksum for byte array, use
*
* void update(bytes[] b, int start, int length)
* method of CRC32 class.
*/
checksum.update(bytes,0,bytes.length);
/*
* Get the generated checksum using
* getValue method of CRC32 class.
*/
return String.valueOf(checksum.getValue());
}
private String generateAdler32(String baseString) {
//Convert string to bytes
byte bytes[] = baseString.getBytes();
Checksum checksum = new Adler32();
/*
* To compute the CRC32 checksum for byte array, use
*
* void update(bytes[] b, int start, int length)
* method of CRC32 class.
*/
checksum.update(bytes,0,bytes.length);
/*
* Get the generated checksum using
* getValue method of CRC32 class.
*/
return String.valueOf(checksum.getValue());
}
/*************************************************************************
* Compilation: javac CRC16.java
* Execution: java CRC16 s
*
* Reads in a string s as a command-line argument, and prints out
* its 16-bit Cyclic Redundancy Check (CRC16). Uses a lookup table.
*
* Reference: http://www.gelato.unsw.edu.au/lxr/source/lib/crc16.c
*
* % java CRC16 123456789
* CRC16 = bb3d
*
* Uses irreducible polynomial: 1 + x^2 + x^15 + x^16
*
*
*************************************************************************/
private String generateCRC16(String baseString) {
int[] table = {
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040,
};
byte[] bytes = baseString.getBytes();
int crc = 0x0000;
for (byte b : bytes) {
crc = (crc >>> 8) ^ table[(crc ^ b) & 0xff];
}
return Integer.toHexString(crc);
}
/*******************************************************************************
* Copyright (c) 2009, 2012 Mountainminds GmbH & Co. KG and Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Marc R. Hoffmann - initial API and implementation
*
*******************************************************************************/
/**
* CRC64 checksum calculator based on the polynom specified in ISO 3309. The
* implementation is based on the following publications:
*
* <ul>
* <li>http://en.wikipedia.org/wiki/Cyclic_redundancy_check</li>
* <li>http://www.geocities.com/SiliconValley/Pines/8659/crc.htm</li>
* </ul>
*/
private static final long POLY64REV = 0xd800000000000000L;
private static final long[] LOOKUPTABLE;
static {
LOOKUPTABLE = new long[0x100];
for (int i = 0; i < 0x100; i++) {
long v = i;
for (int j = 0; j < 8; j++) {
if ((v & 1) == 1) {
v = (v >>> 1) ^ POLY64REV;
} else {
v = (v >>> 1);
}
}
LOOKUPTABLE[i] = v;
}
}
/**
* Calculates the CRC64 checksum for the given data array.
*
* @param data
* data to calculate checksum for
* @return checksum value
*/
public static String generateCRC64(final byte[] data) {
long sum = 0;
for (int i = 0; i < data.length; i++) {
final int lookupidx = ((int) sum ^ data[i]) & 0xff;
sum = (sum >>> 8) ^ LOOKUPTABLE[lookupidx];
}
return String.valueOf(sum);
}
}
you would use it like:
final HashBruter hb = new HashBruter();
hb.setMaxLength(5); hb.setMinLength(1);
hb.addSpecialCharacters(); hb.addUpperCaseLetters();
hb.addLowerCaseLetters(); hb.addDigits();
hb.setType("sha-512");
hb.setHash("282154720ABD4FA76AD7CD5F8806AA8A19AEFB6D10042B0D57A311B86087DE4DE3186A92019D6EE51035106EE088DC6007BEB7BE46994D1463999968FBE9760E");
Thread thread = new Thread(new Runnable() {
@Override public void run() { hb.tryBruteForce(); } });
thread.start();
while (!hb.isFound()) { System.out.println("Hash: " +
hb.getGeneratedHash()); System.out.println("Number of Possibilities: " +
hb.getNumberOfPossibilities()); System.out.println("Checked hashes: " +
hb.getCounter()); System.out.println("Estimated hashes left: " +
hb.getRemainder()); }
System.out.println("Found " + hb.getType() + " hash collision: " +
hb.getGeneratedHash() + " password is: " + hb.getPassword());
In this specific case (there is always a single character at the start you want to remove) you'll want:
str.substring(1)
However, if you want to be able to detect if the comma is there and remove it if it is, then something like:
if (str[0] == ',') {
str = str.substring(1);
}
Implement method to read, and get content from a file (input1.txt)
#include <stdio.h>
#include <stdlib.h>
void testGetFile() {
// open file
FILE *fp = fopen("input1.txt", "r");
size_t len = 255;
// need malloc memory for line, if not, segmentation fault error will occurred.
char *line = malloc(sizeof(char) * len);
// check if file exist (and you can open it) or not
if (fp == NULL) {
printf("can open file input1.txt!");
return;
}
while(fgets(line, len, fp) != NULL) {
printf("%s\n", line);
}
free(line);
}
Hope this help. Happy coding!
Putting the condition in the join seems "semantically wrong" to me, as that's not what JOINs are "for". But that's very qualitative.
Additional problem: if you decide to switch from an inner join to, say, a right join, having the condition be inside the JOIN could lead to unexpected results.
I just want to add that this nearly identical post provides the very useful alternative of using an echo pipe if no force or quiet switch is available. For instance, I think it's the only way to bypass the Y/N prompt in this example.
Echo y|NETDOM COMPUTERNAME WorkComp /Add:Work-Comp
In a general sense you should first look at your command switches for /f, /q, or some variant thereof (for example, Netdom RenameComputer uses /Force, not /f). If there is no switch available, then use an echo pipe.
This can be done with just one line of code using just Dot Net. Below is sample code copied from MSDN
Step 1: Add a reference to System.IO.Compression.FileSystem
Step 2: Follow the code below
static void Main(string[] args)
{
string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
https://docs.python.org/3.8/library/json.html
JSON can solve this problem though its decoder wants double quotes around keys and values. If you don't mind a replace hack...
import json
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
json_acceptable_string = s.replace("'", "\"")
d = json.loads(json_acceptable_string)
# d = {u'muffin': u'lolz', u'foo': u'kitty'}
NOTE that if you have single quotes as a part of your keys or values this will fail due to improper character replacement. This solution is only recommended if you have a strong aversion to the eval solution.
More about json single quote: jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON
In my case, the problem was the protocol. I was trying to call a script url with http
instead of https
.
Here is the code from MSDN and the link - Article Link, which you should check out for more detail.
<ComboBox Text="Is not open">
<ComboBoxItem Name="cbi1">Item1</ComboBoxItem>
<ComboBoxItem Name="cbi2">Item2</ComboBoxItem>
<ComboBoxItem Name="cbi3">Item3</ComboBoxItem>
</ComboBox>
Here's how I do it, the keys are getItemViewType and getViewTypeCount in the Adapter
class. getViewTypeCount
returns how many types of items we have in the list, in this case we have a header item and an event item, so two. getItemViewType
should return what type of View
we have at the input position
.
Android will then take care of passing you the right type of View
in convertView
automatically.
Here what the result of the code below looks like:
First we have an interface that our two list item types will implement
public interface Item {
public int getViewType();
public View getView(LayoutInflater inflater, View convertView);
}
Then we have an adapter that takes a list of Item
public class TwoTextArrayAdapter extends ArrayAdapter<Item> {
private LayoutInflater mInflater;
public enum RowType {
LIST_ITEM, HEADER_ITEM
}
public TwoTextArrayAdapter(Context context, List<Item> items) {
super(context, 0, items);
mInflater = LayoutInflater.from(context);
}
@Override
public int getViewTypeCount() {
return RowType.values().length;
}
@Override
public int getItemViewType(int position) {
return getItem(position).getViewType();
}
@Override public View getView(int position, View convertView, ViewGroup parent) { return getItem(position).getView(mInflater, convertView); }
EDIT Better For Performance.. can be noticed when scrolling
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int rowType = getItemViewType(position);
View View;
if (convertView == null) {
holder = new ViewHolder();
switch (rowType) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.task_details_row, null);
holder.View=getItem(position).getView(mInflater, convertView);
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.task_detail_header, null);
holder.View=getItem(position).getView(mInflater, convertView);
break;
}
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
public static class ViewHolder {
public View View; }
}
Then we have classes the implement Item
and inflate the correct layouts. In your case you'll have something like a Header
class and a ListItem
class.
public class Header implements Item {
private final String name;
public Header(String name) {
this.name = name;
}
@Override
public int getViewType() {
return RowType.HEADER_ITEM.ordinal();
}
@Override
public View getView(LayoutInflater inflater, View convertView) {
View view;
if (convertView == null) {
view = (View) inflater.inflate(R.layout.header, null);
// Do some initialization
} else {
view = convertView;
}
TextView text = (TextView) view.findViewById(R.id.separator);
text.setText(name);
return view;
}
}
And then the ListItem
class
public class ListItem implements Item {
private final String str1;
private final String str2;
public ListItem(String text1, String text2) {
this.str1 = text1;
this.str2 = text2;
}
@Override
public int getViewType() {
return RowType.LIST_ITEM.ordinal();
}
@Override
public View getView(LayoutInflater inflater, View convertView) {
View view;
if (convertView == null) {
view = (View) inflater.inflate(R.layout.my_list_item, null);
// Do some initialization
} else {
view = convertView;
}
TextView text1 = (TextView) view.findViewById(R.id.list_content1);
TextView text2 = (TextView) view.findViewById(R.id.list_content2);
text1.setText(str1);
text2.setText(str2);
return view;
}
}
And a simple Activity
to display it
public class MainActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Item> items = new ArrayList<Item>();
items.add(new Header("Header 1"));
items.add(new ListItem("Text 1", "Rabble rabble"));
items.add(new ListItem("Text 2", "Rabble rabble"));
items.add(new ListItem("Text 3", "Rabble rabble"));
items.add(new ListItem("Text 4", "Rabble rabble"));
items.add(new Header("Header 2"));
items.add(new ListItem("Text 5", "Rabble rabble"));
items.add(new ListItem("Text 6", "Rabble rabble"));
items.add(new ListItem("Text 7", "Rabble rabble"));
items.add(new ListItem("Text 8", "Rabble rabble"));
TwoTextArrayAdapter adapter = new TwoTextArrayAdapter(this, items);
setListAdapter(adapter);
}
}
Layout for R.layout.header
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
style="?android:attr/listSeparatorTextViewStyle"
android:id="@+id/separator"
android:text="Header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#757678"
android:textColor="#f5c227" />
</LinearLayout>
Layout for R.layout.my_list_item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/list_content1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="5dip"
android:clickable="false"
android:gravity="center"
android:longClickable="false"
android:paddingBottom="1dip"
android:paddingTop="1dip"
android:text="sample"
android:textColor="#ff7f1d"
android:textSize="17dip"
android:textStyle="bold" />
<TextView
android:id="@+id/list_content2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="5dip"
android:clickable="false"
android:gravity="center"
android:linksClickable="false"
android:longClickable="false"
android:paddingBottom="1dip"
android:paddingTop="1dip"
android:text="sample"
android:textColor="#6d6d6d"
android:textSize="17dip" />
</LinearLayout>
Layout for R.layout.activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
You can also get fancier and use ViewHolders
, load stuff asynchronously, or whatever you like.
Yes I think You can get it download and separately its Help files from: vbdecompiler.org Site. and there is a Video on YouTube which explains how to Use it to Get the Code from an exe file and Save it. I hope that I helped.
You can configure the connect body parser middleware in a configuration block in your main application file:
/** Form Handling */
app.use(express.bodyParser({
uploadDir: '/tmp/uploads',
keepExtensions: true
}))
app.use(express.limit('5mb'));
Please check this gist.
https://gist.github.com/ecdundar/789660d830d6d40b6c90
#!/bin/bash
# copymysql.sh
# GENERATED WITH USING ARTUR BODERA S SCRIPT
# Source script at: https://gist.github.com/2215200
MYSQLDUMP="/usr/bin/mysqldump"
MYSQL="/usr/bin/mysql"
REMOTESERVERIP=""
REMOTESERVERUSER=""
REMOTESERVERPASSWORD=""
REMOTECONNECTIONSTR="-h ${REMOTESERVERIP} -u ${REMOTESERVERUSER} --password=${REMOTESERVERPASSWORD} "
LOCALSERVERIP=""
LOCALSERVERUSER=""
LOCALSERVERPASSWORD=""
LOCALCONNECTION="-h ${LOCALSERVERIP} -u ${LOCALSERVERUSER} --password=${LOCALSERVERPASSWORD} "
IGNOREVIEWS=""
MYVIEWS=""
IGNOREDATABASES="select schema_name from information_schema.SCHEMATA where schema_name != 'information_schema' and schema_name != 'mysql' and schema_name != 'performance_schema' ;"
# GET A LIST OF DATABASES
databases=`$MYSQL $REMOTECONNECTIONSTR -e "${IGNOREDATABASES}" | tr -d "| " | grep -v schema_name`
# COPY ALL TABLES
for db in $databases; do
# GET LIST OF ITEMS
views=`$MYSQL $REMOTECONNECTIONSTR --batch -N -e "select table_name from information_schema.tables where table_type='VIEW' and table_schema='$db';"
IGNOREVIEWS=""
for view in $views; do
IGNOREVIEWS=${IGNOREVIEWS}" --ignore-table=$db.$view "
done
echo "TABLES "$db
$MYSQL $LOCALCONNECTION --batch -N -e "create database $db; "
$MYSQLDUMP $REMOTECONNECTIONSTR $IGNOREVIEWS --compress --quick --extended-insert --skip-add-locks --skip-comments --skip-disable-keys --default-character-set=latin1 --skip-triggers --single-transaction $db | mysql $LOCALCONNECTION $db
done
# COPY ALL PROCEDURES
for db in $databases; do
echo "PROCEDURES "$db
#PROCEDURES
$MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick --routines --no-create-info --no-data --no-create-db --skip-opt --skip-triggers $db | \
sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION $db
done
# COPY ALL TRIGGERS
for db in $databases; do
echo "TRIGGERS "$db
#TRIGGERS
$MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick --no-create-info --no-data --no-create-db --skip-opt --triggers $db | \
sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION $db
done
# COPY ALL VIEWS
for db in $databases; do
# GET LIST OF ITEMS
views=`$MYSQL $REMOTECONNECTIONSTR --batch -N -e "select table_name from information_schema.tables where table_type='VIEW' and table_schema='$db';"`
MYVIEWS=""
for view in $views; do
MYVIEWS=${MYVIEWS}" "$view" "
done
echo "VIEWS "$db
if [ -n "$MYVIEWS" ]; then
#VIEWS
$MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick -Q -f --no-data --skip-comments --skip-triggers --skip-opt --no-create-db --complete-insert --add-drop-table $db $MYVIEWS | \
sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION $db
fi
done
echo "OK!"
Here is an working example of what you want to do. Read the comments to know what each line in the code does. I've tested it on my pc with gcc 4.6.1; it works fine.
#include <iostream>
#include <fstream>
#include <string>
void f()
{
std::string line;
while(std::getline(std::cin, line)) //input from the file in.txt
{
std::cout << line << "\n"; //output to the file out.txt
}
}
int main()
{
std::ifstream in("in.txt");
std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf
std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt!
std::ofstream out("out.txt");
std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf
std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!
std::string word;
std::cin >> word; //input from the file in.txt
std::cout << word << " "; //output to the file out.txt
f(); //call function
std::cin.rdbuf(cinbuf); //reset to standard input again
std::cout.rdbuf(coutbuf); //reset to standard output again
std::cin >> word; //input from the standard input
std::cout << word; //output to the standard input
}
You could save and redirect in just one line as:
auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save and redirect
Here std::cin.rdbuf(in.rdbuf())
sets std::cin's
buffer to in.rdbuf()
and then returns the old buffer associated with std::cin
. The very same can be done with std::cout
— or any stream for that matter.
Hope that helps.
as long as "lots of stuff" isn't doing something asynchronous this is absolutely unneccessary - the event will call every handler on his way in sequence, so if theres a onklick-event on a parent-element this will fire after the onclik-event of the child has processed completely. javascript doesn't do some kind of "multithreading" here that makes "stopping" the event processing neccessary. conclusion: "pausing" an event just to resume it in the same handler doesn't make any sense.
if "lots of stuff" is something asynchronous this also doesn't make sense as it prevents the asynchonous things to do what they should do (asynchonous stuff) and make them bahave like everything is in sequence (where we come back to my first paragraph)
andig is correct that a common reason for LayoutInflater ignoring your layout_params would be because a root was not specified. Many people think you can pass in null for root. This is acceptable for a few scenarios such as a dialog, where you don't have access to root at the time of creation. A good rule to follow, however, is that if you have root, give it to LayoutInflater.
I wrote an in-depth blog post about this that you can check out here:
https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/
Update
As of docker 0.9, for the steps below to now work, one now has to update the /etc/default/docker
file with the '-e lxc'
to the docker daemon startup option before restarting the daemon (I did this by rebooting the host).
This is all because...
...it [docker 0.9] contains a new "engine driver" abstraction to make possible the use of other API than LXC to start containers. It also provide a new engine driver based on a new API library (libcontainer) which is able to handle Control Groups without using LXC tools. The main issue is that if you are relying on lxc-attach to perform actions on your container, like starting a shell inside the container, which is insanely useful for developpment environment...
Please note that this will prevent the new host only networking optional feature of docker 0.11 from "working" and you will only see the loopback interface. bug report
It turns out that the solution to a different question was also the solution to this one:
...you can use docker
ps -notrunc
to get the full lxc container ID and then uselxc-attach -n <container_id>
run bash in that container as root.
Update: You will soon need to use ps --no-trunc
instead of ps -notrunc
which is being deprecated.
Find the full container ID
Enter the lxc attach command.
Top shows my apache process running that docker started.
tl;dr: baz() { this.foo(); this.bar() }
In ES2015 this construct:
var obj = {
foo() { console.log('foo') }
}
is equal to this ES5 code:
var obj = {
foo : function foo() { console.log('foo') }
}
exports.default = {}
is like creating an object, your default export translates to ES5 code like this:
exports['default'] = {
foo: function foo() {
console.log('foo');
},
bar: function bar() {
console.log('bar');
},
baz: function baz() {
foo();bar();
}
};
now it's kind of obvious (I hope) that baz
tries to call foo
and bar
defined somewhere in the outer scope, which are undefined. But this.foo
and this.bar
will resolve to the keys defined in exports['default']
object. So the default export referencing its own methods shold look like this:
export default {
foo() { console.log('foo') },
bar() { console.log('bar') },
baz() { this.foo(); this.bar() }
}
You also need to change the DataSource
of the connection string. KELVIN-PC
is the name of your local machine and the sql server is running on the default instance.
If you are sure the the server is running as the default instance, you can always use .
in the DataSource, eg.
connectionString="Data Source=.;Initial Catalog=LMS;User ID=sa;Password=temperament"
otherwise, you need to specify the name of the instance of the server,
connectionString="Data Source=.\INSTANCENAME;Initial Catalog=LMS;User ID=sa;Password=temperament"
Eloquent has a method for that (Laravel 4.*/5.*);
Model::whereNotNull('sent_at')
Laravel 3:
Model::where_not_null('sent_at')
You could use the INDIRECT function. This takes a string and converts it into a range
More info here
=INDIRECT("K"&A2)
But it's preferable to use INDEX as it is less volatile.
=INDEX(K:K,A2)
This returns a value or the reference to a value from within a table or range
More info here
Put either function into cell B2 and fill down.
Which one of their Grids are you using? XtraGrid or AspXGrid? Here is a piece taken from one of my app using XtraGrid.
private void grdContactsView_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
_selectedContact = GetSelectedRow((DevExpress.XtraGrid.Views.Grid.GridView)sender);
}
private Contact GetSelectedRow(DevExpress.XtraGrid.Views.Grid.GridView view)
{
return (Contact)view.GetRow(view.FocusedRowHandle);
}
My Grid have a list of Contact objects bound to it. Every time a row is clicked I load the selected row into _selectedContact. Hope this helps. You will find lots of information on using their controls buy visiting their support and documentation sites.
Use the :w
command with a filename:
:w other_filename
You have this option also:
type Configuration struct {
Val string
Proxy
}
type Proxy struct {
Address string
Port string
}
func main() {
c := &Configuration{"test", Proxy{"addr", "port"}}
fmt.Println(c)
}
say you have var arr = [1,0,2]
arr.splice(-1,1)
will return to you array [1,0];
while arr.slice(-1,1)
will return to you array [2];
Simple solution:
document.getElementById("upload-files").value = "";
It is a good question and unfortunately bad answers as var = None
is already assigning a value, and if your script runs multiple times it is overwritten with None
every time.
It is not the same as defining without assignment. I am still trying to figure out how to bypass this issue.
It looks like your syntax for unset is invalid, and the lack of reindexing might cause trouble in the future. See: the section on PHP arrays.
The correct syntax is shown above. Also keep in mind array-values for reindexing, so you don't ever index something you previously deleted.
You can use the .blur()
method. See http://api.jquery.com/blur/
Just use
Dim Cell As Range
Columns("B:B").Select
Set cell = Selection.Find(What:="celda", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If cell Is Nothing Then
'do it something
Else
'do it another thing
End If
You can use jQuery's param
method:
var obj = {_x000D_
param1: 'something',_x000D_
param2: 'somethingelse',_x000D_
param3: 'another'_x000D_
}_x000D_
obj['param4'] = 'yetanother';_x000D_
var str = jQuery.param(obj);_x000D_
alert(str);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
What a great misunderstanding between events and delegates!!! A delegate specifies a TYPE (such as a class
, or an interface
does), whereas an event is just a kind of MEMBER (such as fields, properties, etc). And, just like any other kind of member an event also has a type. Yet, in the case of an event, the type of the event must be specified by a delegate. For instance, you CANNOT declare an event of a type defined by an interface.
Concluding, we can make the following Observation: the type of an event MUST be defined by a delegate. This is the main relation between an event and a delegate and is described in the section II.18 Defining events of ECMA-335 (CLI) Partitions I to VI:
In typical usage, the TypeSpec (if present) identifies a delegate whose signature matches the arguments passed to the event’s fire method.
However, this fact does NOT imply that an event uses a backing delegate field. In truth, an event may use a backing field of any different data structure type of your choice. If you implement an event explicitly in C#, you are free to choose the way you store the event handlers (note that event handlers are instances of the type of the event, which in turn is mandatorily a delegate type---from the previous Observation). But, you can store those event handlers (which are delegate instances) in a data structure such as a List
or a Dictionary
or any other else, or even in a backing delegate field. But don’t forget that it is NOT mandatory that you use a delegate field.
Here's a 2016 adjusted version of Rob's answer, including Microsoft Edge and detection of Blink:
(edit: I updated Rob's answer above with this information.)
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)_x000D_
isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;_x000D_
// Firefox 1.0+_x000D_
isFirefox = typeof InstallTrigger !== 'undefined';_x000D_
// Safari 3.0+_x000D_
isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);_x000D_
// Internet Explorer 6-11_x000D_
isIE = /*@cc_on!@*/false || !!document.documentMode;_x000D_
// Edge 20+_x000D_
isEdge = !isIE && !!window.StyleMedia;_x000D_
// Chrome 1+_x000D_
isChrome = !!window.chrome && !!window.chrome.webstore;_x000D_
// Blink engine detection_x000D_
isBlink = (isChrome || isOpera) && !!window.CSS;_x000D_
_x000D_
/* Results: */_x000D_
console.log("isOpera", isOpera);_x000D_
console.log("isFirefox", isFirefox);_x000D_
console.log("isSafari", isSafari);_x000D_
console.log("isIE", isIE);_x000D_
console.log("isEdge", isEdge);_x000D_
console.log("isChrome", isChrome);_x000D_
console.log("isBlink", isBlink);
_x000D_
The beauty of this approach is that it relies on browser engine properties, so it covers even derivative browsers, such as Yandex or Vivaldi, which are practically compatible with the major browsers whose engines they use. The exception is Opera, which relies on user agent sniffing, but today (i.e. ver. 15 and up) even Opera is itself only a shell for Blink.
To remove all files from staging area use -
git reset
To remove specific file use -
git reset "File path"
IDLE TO VISUAL STUDIO USERS: I ran into this problem as well when moving code directly from IDLE to Visual Studio. When you press tab IDLE adds 4 spaces instead of a tab. In IDLE, hit Ctl+A to select all of the code and go to Format>Tabify Region. Now move the code to visual studio and most errors should be fixed. Every so often there will be code that is off-tab, just fix it manually.
My working solution is:
cd /opt/genymobile/genymotion/tools
./adb shell
You have to use its own adb tool.
Training set: A set of examples used for learning, that is to fit the parameters [i.e., weights] of the classifier.
Validation set: A set of examples used to tune the parameters [i.e., architecture, not weights] of a classifier, for example to choose the number of hidden units in a neural network.
Test set: A set of examples used only to assess the performance [generalization] of a fully specified classifier.
From ftp://ftp.sas.com/pub/neural/FAQ1.txt section "What are the population, sample, training set, design set, validation"
The error surface will be different for different sets of data from your data set (batch learning). Therefore if you find a very good local minima for your test set data, that may not be a very good point, and may be a very bad point in the surface generated by some other set of data for the same problem. Therefore you need to compute such a model which not only finds a good weight configuration for the training set but also should be able to predict new data (which is not in the training set) with good error. In other words the network should be able to generalize the examples so that it learns the data and does not simply remembers or loads the training set by overfitting the training data.
The validation data set is a set of data for the function you want to learn, which you are not directly using to train the network. You are training the network with a set of data which you call the training data set. If you are using gradient based algorithm to train the network then the error surface and the gradient at some point will completely depend on the training data set thus the training data set is being directly used to adjust the weights. To make sure you don't overfit the network you need to input the validation dataset to the network and check if the error is within some range. Because the validation set is not being using directly to adjust the weights of the netowork, therefore a good error for the validation and also the test set indicates that the network predicts well for the train set examples, also it is expected to perform well when new example are presented to the network which was not used in the training process.
Early stopping is a way to stop training. There are different variations available, the main outline is, both the train and the validation set errors are monitored, the train error decreases at each iteration (backprop and brothers) and at first the validation error decreases. The training is stopped at the moment the validation error starts to rise. The weight configuration at this point indicates a model, which predicts the training data well, as well as the data which is not seen by the network . But because the validation data actually affects the weight configuration indirectly to select the weight configuration. This is where the Test set comes in. This set of data is never used in the training process. Once a model is selected based on the validation set, the test set data is applied on the network model and the error for this set is found. This error is a representative of the error which we can expect from absolutely new data for the same problem.
EDIT:
Also, in the case you do not have enough data for a validation set, you can use crossvalidation to tune the parameters as well as estimate the test error.
You cannot use Ctrl+C by jQuery , but you can with another library which is shortcut.js
Live Demo : Abdennour JSFiddle
$(document).ready(function() {
shortcut.add("Ctrl+C", function() {
$('span').html("?????. ??? ???? ??? ???? : Ctrl+C");
});
shortcut.add("Ctrl+V", function() {
$('span').html("?????. ??? ???? ??? ???? : Ctrl+V");
});
shortcut.add("Ctrl+X", function() {
$('span').html("?????. ??? ???? ??? ???? : Ctrl+X");
});
});
You should be aware of the fact that your original attempt
int count = map.containsKey(word) ? map.get(word) : 0;
contains two potentially expensive operations on a map, namely containsKey
and get
. The former performs an operation potentially pretty similar to the latter, so you're doing the same work twice!
If you look at the API for Map, get
operations usually return null
when the map does not contain the requested element.
Note that this will make a solution like
map.put( key, map.get(key) + 1 );
dangerous, since it might yield NullPointerException
s. You should check for a null
first.
Also note, and this is very important, that HashMap
s can contain nulls
by definition. So not every returned null
says "there is no such element". In this respect, containsKey
behaves differently from get
in actually telling you whether there is such an element. Refer to the API for details.
For your case, however, you might not want to distinguish between a stored null
and "noSuchElement". If you don't want to permit null
s you might prefer a Hashtable
. Using a wrapper library as was already proposed in other answers might be a better solution to manual treatment, depending on the complexity of your application.
To complete the answer (and I forgot to put that in at first, thanks to the edit function!), the best way of doing it natively, is to get
into a final
variable, check for null
and put
it back in with a 1
. The variable should be final
because it's immutable anyway. The compiler might not need this hint, but its clearer that way.
final HashMap map = generateRandomHashMap(); final Object key = fetchSomeKey(); final Integer i = map.get(key); if (i != null) { map.put(i + 1); } else { // do something }
If you do not want to rely on autoboxing, you should say something like map.put(new Integer(1 + i.getValue()));
instead.
I had the same issue. I solved it by running the command in a different python version. I tried python3 filename.py
. Earlier i was using Python 2.7.
Another possibility is that the file from which something is imported may contain BOM (Byte Order Mark). It can be solved by opening the file in some editor which supports multiple encoding like VSCode (Notepad++) and saving in a different encoding statndard like ANSI, UTF-8(without BOM).
var start = new Date("2014-05-01"); //yyyy-mm-dd
var end = new Date("2014-05-05"); //yyyy-mm-dd
while(start <= end){
var mm = ((start.getMonth()+1)>=10)?(start.getMonth()+1):'0'+(start.getMonth()+1);
var dd = ((start.getDate())>=10)? (start.getDate()) : '0' + (start.getDate());
var yyyy = start.getFullYear();
var date = dd+"/"+mm+"/"+yyyy; //yyyy-mm-dd
alert(date);
start = new Date(start.setDate(start.getDate() + 1)); //date increase by 1
}
I was also getting same below error:
Unable to connect to the server: dial tcp [::1]:8080: connectex: No connection could be made because the target machine actively refused it.
Then I just execute below command and found everything working fine.
PS C:> .\minikube.exe start
Starting local Kubernetes v1.10.0 cluster... Starting VM... Downloading Minikube ISO 150.53 MB / 150.53 MB [============================================] 100.00% 0s Getting VM IP address... Moving files into cluster... Downloading kubeadm v1.10.0 Downloading kubelet v1.10.0 Finished Downloading kubelet v1.10.0 Finished Downloading kubeadm v1.10.0 Setting up certs... Connecting to cluster... Setting up kubeconfig... Starting cluster components... Kubectl is now configured to use the cluster. Loading cached images from config file. PS C:> .\minikube.exe start Starting local Kubernetes v1.10.0 cluster... Starting VM... Getting VM IP address... Moving files into cluster... Setting up certs... Connecting to cluster... Setting up kubeconfig... Starting cluster components... Kubectl is now configured to use the cluster.
Select count(1) From V$session
where status='ACTIVE'
/
You can also use jQuery('.class-name').attr("href")
, in my case it works better.
Here more information: "jQuery(...)" instead of "$(...)"
You can try this, using apply()
function
> d
name plate value1 value2
1 A P1 1 100
2 B P2 2 200
3 C P3 3 300
> f <- function(x, output) {
wellName <- x[1]
plateName <- x[2]
wellID <- 1
print(paste(wellID, x[3], x[4], sep=","))
cat(paste(wellID, x[3], x[4], sep=","), file= output, append = T, fill = T)
}
> apply(d, 1, f, output = 'outputfile')
Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program's operation if properly and appropriately used
Wikipedia
Link of Lazy Loading from hibernate.org
Any of the below three options works for you:
echo[
echo(
echo.
For example:
@echo off
echo There will be a blank line below
echo[
echo Above line is blank
echo(
echo The above line is also blank.
echo.
echo The above line is also blank.
The nested generics-problem can be avoided with the @Captor annotation:
public class Test{
@Mock
private Service service;
@Captor
private ArgumentCaptor<ArrayList<SomeType>> captor;
@Before
public void init(){
MockitoAnnotations.initMocks(this);
}
@Test
public void shouldDoStuffWithListValues() {
//...
verify(service).doStuff(captor.capture()));
}
}
I also had similar problems when trying to link static compiled fontconfig and expat into a linux shared object:
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/fontconfig/lib/linux-x86_64/libfontconfig.a(fccfg.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/expat/lib/linux-x86_64/libexpat.a(xmlparse.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
[...]
This contrary to the fact that I was already passing -fPIC
flags though CFLAGS
variable, and other compilers/linkers variants (clang/lld) were perfectly working with the same build configuration. It ended up that these dependencies control position-independent code settings through despicable autoconf
scripts and need --with-pic
switch during build configuration on linux gcc/ld combination, and its lack probably overrides same the setting in CFLAGS
. Pass the switch to configure
script and the dependencies will be correctly compiled with -fPIC
.
you can use
style="display:none"
Ex:
<asp:TextBox ID="txbProv" runat="server" style="display:none"></asp:TextBox>
If you plan on using Bootstrap 4 which is required with the angular-ui team's ng-bootstrap that is mentioned in this thread, you'll want to use this instead (NOTE: you don't need to include the JS file):
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
You can also reference this locally after running npm install [email protected] --save
by pointing to the file in your styles.scss
file, assuming you're using SASS:
@import '../../node_modules/bootstrap/dist/css/bootstrap.min.css';
All you have to do is define your result
as a string array, like the following:
const result : string[] = [];
Without defining the array type, it by default will be never
. So when you tried to add a string to it, it was a type mismatch, and so it threw the error you saw.
It is not something obvious, but the caret
package has a function postResample()
that will calculate "A vector of performance estimates" according to the documentation. The "performance estimates" are
and have to be accessed from the vector like this
library(caret)
vect1 <- c(1, 2, 3)
vect2 <- c(3, 2, 2)
res <- caret::postResample(vect1, vect2)
rsq <- res[2]
However, this is using the correlation squared approximation for r-squared as mentioned in another answer. I'm not sure why Max Kuhn didn't just use the conventional 1-SSE/SST.
caret
also has an R2()
method, although it's hard to find in the documentation.
The way to implement the normal coefficient of determination equation is:
preds <- c(1, 2, 3)
actual <- c(2, 2, 4)
rss <- sum((preds - actual) ^ 2)
tss <- sum((actual - mean(actual)) ^ 2)
rsq <- 1 - rss/tss
Not too bad to code by hand of course, but why isn't there a function for it in a language primarily made for statistics? I'm thinking I must be missing the implementation of R^2 somewhere, or no one cares enough about it to implement it. Most of the implementations, like this one, seem to be for generalized linear models.
To throw another potential solution into the mix, I had a settings
folder as well as a settings.py
in my project dir. (I was switching back from environment-based settings files to one file. I have since reconsidered.)
Python was getting confused about whether I wanted to import project/settings.py
or project/settings/__init__.py
. I removed the settings
dir and everything now works fine.
If you want to pass the % as part of your function you should use the following alternative:
<script>
function fpercentStr(quantity, percentString)
{
var percent = new Number(percentString.replace("%", ""));
return fpercent(quantity, percent);
}
function fpercent(quantity, percent)
{
return quantity * percent / 100;
}
document.write("test 1: " + fpercent(10000, 35.873))
document.write("test 2: " + fpercentStr(10000, "35.873%"))
</script>
I came here looking for a solution for extended ascii characters, but couldnt find it. The closest I found is bzlm's solution. But that works only for ASCII Code upto 127(obviously you can replace the encoding type in his code, but i think it was a bit complex to understand. Hence, sharing this version). Here's a solution that works for extended ASCII codes i.e. upto 255 which is the ISO 8859-1
It finds and strips out non-ascii characters(greater than 255)
Dim str1 as String= "â, ??î or ôu? n?i?++$-?!??4?od;/?'®;?:?)///1!@#"
Dim extendedAscii As Encoding = Encoding.GetEncoding("ISO-8859-1",
New EncoderReplacementFallback(String.empty),
New DecoderReplacementFallback())
Dim extendedAsciiBytes() As Byte = extendedAscii.GetBytes(str1)
Dim str2 As String = extendedAscii.GetString(extendedAsciiBytes)
console.WriteLine(str2)
'Output : â, ??î or ôu ni++$-!??4od;/';:)///1!@#$%^yz:
Here's a working fiddle for the code
Replace the encoding as per the requirement, rest should remain the same.
**in create url page**
$data = array(
'car' => 'Suzuki',
'Model' => '1976'
);
$query = http_build_query(array('myArray' => $data));
$url=urlencode($query);
echo" <p><a href=\"index2.php?data=".$url."\"> Send </a><br /> </p>";
**in received page**
parse_str($_GET['data']);
echo $myArray['car'];
echo '<br/>';
echo $myArray['model'];
You haven't defined struct stasher_file
by your first definition. What you have defined is an nameless struct type and a variable stasher_file
of that type. Since there's no definition for such type as struct stasher_file
in your code, the compiler complains about incomplete type.
In order to define struct stasher_file
, you should have done it as follows
struct stasher_file {
char name[32];
int size;
int start;
int popularity;
};
Note where the stasher_file
name is placed in the definition.
When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.
With Basic Auth, the HTTP request from the question will look something like this:
GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk
The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password)
.
To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl
, the username and password will be clearly visible on the process list and might turn up in the bash history file.
When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.
Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.
When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.
Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.
It is originally an answer in the comments from @Mark Rajcok, But I want to place it here as a tested and worked as a solution using ChangeDetectorRef , I see a good point here:
Another alternative is to inject
ChangeDetectorRef
and callcdRef.detectChanges()
instead ofzone.run()
. This could be more efficient, since it will not run change detection over the entire component tree likezone.run()
does. – Mark Rajcok
So code must be like:
import {Component, OnInit, ChangeDetectorRef} from 'angular2/core';
export class RecentDetectionComponent implements OnInit {
recentDetections: Array<RecentDetection>;
constructor(private cdRef: ChangeDetectorRef, // <== added
private recentDetectionService: RecentDetectionService) {
this.recentDetections = new Array<RecentDetection>();
}
getRecentDetections(): void {
this.recentDetectionService.getJsonFromApi()
.subscribe(recent => {
this.recentDetections = recent;
console.log(this.recentDetections[0].macAddress);
this.cdRef.detectChanges(); // <== added
});
}
ngOnInit() {
this.getRecentDetections();
let timer = Observable.timer(2000, 5000);
timer.subscribe(() => this.getRecentDetections());
}
}
Edit:
Using .detectChanges()
inside subscibe could lead to issue Attempt to use a destroyed view: detectChanges
To solve it you need to unsubscribe
before you destroy the component, so the full code will be like:
import {Component, OnInit, ChangeDetectorRef, OnDestroy} from 'angular2/core';
export class RecentDetectionComponent implements OnInit, OnDestroy {
recentDetections: Array<RecentDetection>;
private timerObserver: Subscription;
constructor(private cdRef: ChangeDetectorRef, // <== added
private recentDetectionService: RecentDetectionService) {
this.recentDetections = new Array<RecentDetection>();
}
getRecentDetections(): void {
this.recentDetectionService.getJsonFromApi()
.subscribe(recent => {
this.recentDetections = recent;
console.log(this.recentDetections[0].macAddress);
this.cdRef.detectChanges(); // <== added
});
}
ngOnInit() {
this.getRecentDetections();
let timer = Observable.timer(2000, 5000);
this.timerObserver = timer.subscribe(() => this.getRecentDetections());
}
ngOnDestroy() {
this.timerObserver.unsubscribe();
}
}
I am not sure if I fully understand your problem but since I had similar issue recently I will try to help you out.
Vendor bundle.
You should use CommonsChunkPlugin for that. in the configuration you specify the name of the chunk (e.g. vendor
), and file name that will be generated (vendor.js
).
new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js", Infinity),
Now important part, you have to now specify what does it mean vendor
library and you do that in an entry section. One one more item to entry list with the same name as the name of the newly declared chunk (i.e. 'vendor' in this case). The value of that entry should be the list of all the modules that you want to move to vendor
bundle.
in your case it should look something like:
entry: {
app: 'entry.js',
vendor: ['jquery', 'jquery.plugin1']
}
JQuery as global
Had the same problem and solved it with ProvidePlugin. here you are not defining global object but kind of shurtcuts to modules. i.e. you can configure it like that:
new webpack.ProvidePlugin({
$: "jquery"
})
And now you can just use $
anywhere in your code - webpack will automatically convert that to
require('jquery')
I hope it helped. you can also look at my webpack configuration file that is here
I love webpack, but I agree that the documentation is not the nicest one in the world... but hey.. people were saying same thing about Angular documentation in the begining :)
Edit:
To have entrypoint-specific vendor chunks just use CommonsChunkPlugins multiple times:
new webpack.optimize.CommonsChunkPlugin("vendor-page1", "vendor-page1.js", Infinity),
new webpack.optimize.CommonsChunkPlugin("vendor-page2", "vendor-page2.js", Infinity),
and then declare different extenral libraries for different files:
entry: {
page1: ['entry.js'],
page2: ['entry2.js'],
"vendor-page1": [
'lodash'
],
"vendor-page2": [
'jquery'
]
},
If some libraries are overlapping (and for most of them) between entry points then you can extract them to common file using same plugin just with different configuration. See this example.
sudo killall -9 "process name"
Another consideration is the exit code to return. Just "1
" is pretty standard, although there are a handful of reserved exit codes that bash itself uses, and that same page argues that user-defined codes should be in the range 64-113 to conform to C/C++ standards.
You might also consider the bit vector approach that mount
uses for its exit codes:
0 success
1 incorrect invocation or permissions
2 system error (out of memory, cannot fork, no more loop devices)
4 internal mount bug or missing nfs support in mount
8 user interrupt
16 problems writing or locking /etc/mtab
32 mount failure
64 some mount succeeded
OR
-ing the codes together allows your script to signal multiple simultaneous errors.
I think, the easiest way is to read readme file inside your Eclipse directory at path eclipse/readme/eclipse_readme
.
At the very top of this file it clearly tells the version number:
For My Eclipse Juno; it says version as Release 4.2.0
Hi above solutions didn't work for me. The other way of running a single test is
mocha test/cartcheckout/checkout.js -g 'Test Name Goes here'
This helps to run a test case from a single file and with specific name.
How to deal with Zeros when calculating percentage changes is the researcher's call and requires some domain expertise. If the researcher believes that it would not be distorting the data, s/he may simply add a very small constant to all values to get rid of all zeros. In financial series, when dealing with trading volume, for example, we may not want to do this because trading volume = 0 just means that: the asset did not trade at all. The meaning of volume = 0 may be very different from volume = 0.00000000001. This is my preferred strategy in cases whereby I can not logically add a small constant to all values. Consider the percentage change formula ((New-Old)/Old) *100. If New = 0, then percentage change would be -100%. This number indeed makes financial sense as long as it is the minimum percentage change in the series (This is indeed guaranteed to be the minimum percentage change in the series). Why? Because it shows that trading volume experiences maximum possible decrease, which is going from any number to 0, -100%. So, I'll be fine with this value being in my percentage change series. If I normalize that series, then even better since this (possibly) relatively big number in absolute value will be analyzed on the same scale as other variables are. Now, what if the Old value = 0. That's a trickier case. Percentage change due to going from 0 to 1 will be equal to that due to going from 0 to a million: infinity. The fact that we call both "infinity" percentage change is problematic. In this case, I would set the infinities equal to np.nan and interpolate them.
The following graph shows what I discussed above. Starting from series 1, we get series 4, which is ready to be analyzed, with no Inf or NaNs.
One more thing: a lot of the time, the reason for calculating percentage change is to stationarize the data. So, if your original series contains zero and you wish to convert it to percentage change to achieve stationarity, first make sure it is not already stationary. Because if it is, you don't have to calculate percentage change. The point is that series that take the value of 0 a lot (the problem OP has) are very likely to be already stationary, for example the volume series I considered above. Imagine a series oscillating above and below zero, thus hitting 0 at times. Such a series is very likely already stationary.
When we give any command, the streams of that command are stored in the memory location called buffer(a temporary memory location) in our computer. When all the temporary memory location is full then we use flush(), which flushes all the streams of data and executes them completely and gives a new space to new streams in buffer temporary location. -Hope you will understand
This is my simple solution, adapted from Microsoft (https://code.msdn.microsoft.com/windowsapps/How-to-add-a-hint-text-to-ed66a3c6)
<Grid Background="White" HorizontalAlignment="Right" VerticalAlignment="Top" >
<!-- overlay with hint text -->
<TextBlock Margin="5,2" MinWidth="50" Text="Suche..."
Foreground="LightSteelBlue" Visibility="{Binding ElementName=txtSearchBox, Path=Text.IsEmpty, Converter={StaticResource MyBoolToVisibilityConverter}}" IsHitTestVisible="False"/>
<!-- enter term here -->
<TextBox MinWidth="50" Name="txtSearchBox" Background="Transparent" />
</Grid>
Partition the table monthly.That is the best way to handle tables with large daily influx ,be it oracle or MSSQL.
If you really want something simple and know how to write/run Python, take a look at the script Bas Bosschert: sources
#!/usr/bin/env python
import sys
from Crypto.Cipher import AES
try:
wafile=sys.argv[1]
except:
print "Usage: %s <msgstore.db.crypt>" % __file__
sys.exit(1)
key = "346a23652a46392b4d73257c67317e352e3372482177652c".decode('hex')
cipher = AES.new(key,1)
open('msgstore.db',"wb").write(cipher.decrypt(open(wafile,"rb").read()))
Full run:
(scratch)ehtesh@ackee:/tmp/whatsapp$ mkvirtualenv whatsapp_decrypt
New python executable in whatsapp_decrypt/bin/python
Installing setuptools, pip...done.
(whatsapp_decrypt)ehtesh@ackee:/tmp/whatsapp$ pip install pycrypto >/dev/null
(whatsapp_decrypt)ehtesh@ackee:/tmp/whatsapp$ wget https://gist.githubusercontent.com/shurane/ffa15e959e2d134086c9/raw/bc99a9997123bea0ea0acde185e24c7e89133559/whatsapp_decrypt.py >/dev/null
(whatsapp_decrypt)ehtesh@ackee:/tmp/whatsapp$ ls
msgstore.db.crypt whatsapp_decrypt.py
(whatsapp_decrypt)ehtesh@ackee:/tmp/whatsapp$ python whatsapp_decrypt.py msgstore.db.crypt
(whatsapp_decrypt)ehtesh@ackee:/tmp/whatsapp$ ls
msgstore.db.crypt msgstore.db whatsapp_decrypt.py
(whatsapp_decrypt)ehtesh@ackee:/tmp/whatsapp$ sqlite3 msgstore.db
SQLite version 3.7.17 2013-05-20 00:56:22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> PRAGMA table_info(messages);
0|_id|INTEGER|0||1
1|key_remote_jid|TEXT|1||0
2|key_from_me|INTEGER|0||0
3|key_id|TEXT|1||0
4|status|INTEGER|0||0
5|needs_push|INTEGER|0||0
6|data|TEXT|0||0
7|timestamp|INTEGER|0||0
8|media_url|TEXT|0||0
9|media_mime_type|TEXT|0||0
10|media_wa_type|TEXT|0||0
11|media_size|INTEGER|0||0
12|media_name|TEXT|0||0
13|media_hash|TEXT|0||0
14|media_duration|INTEGER|0||0
15|origin|INTEGER|0||0
16|latitude|REAL|0||0
17|longitude|REAL|0||0
18|thumb_image|TEXT|0||0
19|remote_resource|TEXT|0||0
20|received_timestamp|INTEGER|0||0
21|send_timestamp|INTEGER|0||0
22|receipt_server_timestamp|INTEGER|0||0
23|receipt_device_timestamp|INTEGER|0||0
24|raw_data|BLOB|0||0
25|recipient_count|INTEGER|0||0
sqlite>
Pritam Baral has mentioned an even simpler way:
openssl aes-192-ecb -d -in msgstore.db.crypt -out msgstore.db -K 346a23652a46392b4d73257c67317e352e3372482177652c
Note - You need not have to uninstall/reinstall anything.
If you add the 'radio inline' class to the control label in the solution provided by user1938475 it should line up correctly with the other labels. Or if you're only using 'radio' like your 2nd example just include the 'radio' class.
<label class="radio control-label">Some label</label>
OR for 'radio inline'
<label class="radio-inline control-label">Some label</label>
You can simply use,
import json
json.loads(my_bytes_value)
updated
might be what you're looking for. https://vuejs.org/v2/api/#updated
Why involve Notepad?
Sub ReplaceStringInFile()
Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String
' Edit as needed
sFileName = "C:\Temp\test.txt"
iFileNum = FreeFile
Open sFileName For Input As iFileNum
Do Until EOF(iFileNum)
Line Input #iFileNum, sBuf
sTemp = sTemp & sBuf & vbCrLf
Loop
Close iFileNum
sTemp = Replace(sTemp, "THIS", "THAT")
iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Close iFileNum
End Sub
#if DEBUG
bool bypassCheck=TRUE_OR_FALSE;//i will decide depending on what i am debugging
#else
bool bypassCheck = false; //NEVER bypass it
#endif
Make sure you have the checkbox to define DEBUG checked in your build properties.
In my first answer the logic is shown for those who want to go with the logic only.
I think I was not able to make clear to @chalukya3545, that's why I am adding the whole code to let him know the exact flow of the code.
BluetoothDemo.java
public class BluetoothDemo extends Activity {
ListView listViewPaired;
ListView listViewDetected;
ArrayList<String> arrayListpaired;
Button buttonSearch,buttonOn,buttonDesc,buttonOff;
ArrayAdapter<String> adapter,detectedAdapter;
static HandleSeacrh handleSeacrh;
BluetoothDevice bdDevice;
BluetoothClass bdClass;
ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
private ButtonClicked clicked;
ListItemClickedonPaired listItemClickedonPaired;
BluetoothAdapter bluetoothAdapter = null;
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
ListItemClicked listItemClicked;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listViewDetected = (ListView) findViewById(R.id.listViewDetected);
listViewPaired = (ListView) findViewById(R.id.listViewPaired);
buttonSearch = (Button) findViewById(R.id.buttonSearch);
buttonOn = (Button) findViewById(R.id.buttonOn);
buttonDesc = (Button) findViewById(R.id.buttonDesc);
buttonOff = (Button) findViewById(R.id.buttonOff);
arrayListpaired = new ArrayList<String>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
clicked = new ButtonClicked();
handleSeacrh = new HandleSeacrh();
arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>();
/*
* the above declaration is just for getting the paired bluetooth devices;
* this helps in the removing the bond between paired devices.
*/
listItemClickedonPaired = new ListItemClickedonPaired();
arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
adapter= new ArrayAdapter<String>(BluetoothDemo.this, android.R.layout.simple_list_item_1, arrayListpaired);
detectedAdapter = new ArrayAdapter<String>(BluetoothDemo.this, android.R.layout.simple_list_item_single_choice);
listViewDetected.setAdapter(detectedAdapter);
listItemClicked = new ListItemClicked();
detectedAdapter.notifyDataSetChanged();
listViewPaired.setAdapter(adapter);
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
getPairedDevices();
buttonOn.setOnClickListener(clicked);
buttonSearch.setOnClickListener(clicked);
buttonDesc.setOnClickListener(clicked);
buttonOff.setOnClickListener(clicked);
listViewDetected.setOnItemClickListener(listItemClicked);
listViewPaired.setOnItemClickListener(listItemClickedonPaired);
}
private void getPairedDevices() {
Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();
if(pairedDevice.size()>0)
{
for(BluetoothDevice device : pairedDevice)
{
arrayListpaired.add(device.getName()+"\n"+device.getAddress());
arrayListPairedBluetoothDevices.add(device);
}
}
adapter.notifyDataSetChanged();
}
class ListItemClicked implements OnItemClickListener
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
bdDevice = arrayListBluetoothDevices.get(position);
//bdClass = arrayListBluetoothDevices.get(position);
Log.i("Log", "The dvice : "+bdDevice.toString());
/*
* here below we can do pairing without calling the callthread(), we can directly call the
* connect(). but for the safer side we must usethe threading object.
*/
//callThread();
//connect(bdDevice);
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
//arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
//adapter.notifyDataSetChanged();
getPairedDevices();
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}//connect(bdDevice);
Log.i("Log", "The bond is created: "+isBonded);
}
}
class ListItemClickedonPaired implements OnItemClickListener
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
bdDevice = arrayListPairedBluetoothDevices.get(position);
try {
Boolean removeBonding = removeBond(bdDevice);
if(removeBonding)
{
arrayListpaired.remove(position);
adapter.notifyDataSetChanged();
}
Log.i("Log", "Removed"+removeBonding);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*private void callThread() {
new Thread(){
public void run() {
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//connect(bdDevice);
Log.i("Log", "The bond is created: "+isBonded);
}
}.start();
}*/
private Boolean connect(BluetoothDevice bdDevice) {
Boolean bool = false;
try {
Log.i("Log", "service method is called ");
Class cl = Class.forName("android.bluetooth.BluetoothDevice");
Class[] par = {};
Method method = cl.getMethod("createBond", par);
Object[] args = {};
bool = (Boolean) method.invoke(bdDevice);//, args);// this invoke creates the detected devices paired.
//Log.i("Log", "This is: "+bool.booleanValue());
//Log.i("Log", "devicesss: "+bdDevice.getName());
} catch (Exception e) {
Log.i("Log", "Inside catch of serviceFromDevice Method");
e.printStackTrace();
}
return bool.booleanValue();
};
public boolean removeBond(BluetoothDevice btDevice)
throws Exception
{
Class btClass = Class.forName("android.bluetooth.BluetoothDevice");
Method removeBondMethod = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
public boolean createBond(BluetoothDevice btDevice)
throws Exception
{
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
class ButtonClicked implements OnClickListener
{
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonOn:
onBluetooth();
break;
case R.id.buttonSearch:
arrayListBluetoothDevices.clear();
startSearching();
break;
case R.id.buttonDesc:
makeDiscoverable();
break;
case R.id.buttonOff:
offBluetooth();
break;
default:
break;
}
}
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
Toast.makeText(context, "ACTION_FOUND", Toast.LENGTH_SHORT).show();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
try
{
//device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
//device.getClass().getMethod("cancelPairingUserInput", boolean.class).invoke(device);
}
catch (Exception e) {
Log.i("Log", "Inside the exception: ");
e.printStackTrace();
}
if(arrayListBluetoothDevices.size()<1) // this checks if the size of bluetooth device is 0,then add the
{ // device to the arraylist.
detectedAdapter.add(device.getName()+"\n"+device.getAddress());
arrayListBluetoothDevices.add(device);
detectedAdapter.notifyDataSetChanged();
}
else
{
boolean flag = true; // flag to indicate that particular device is already in the arlist or not
for(int i = 0; i<arrayListBluetoothDevices.size();i++)
{
if(device.getAddress().equals(arrayListBluetoothDevices.get(i).getAddress()))
{
flag = false;
}
}
if(flag == true)
{
detectedAdapter.add(device.getName()+"\n"+device.getAddress());
arrayListBluetoothDevices.add(device);
detectedAdapter.notifyDataSetChanged();
}
}
}
}
};
private void startSearching() {
Log.i("Log", "in the start searching method");
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
BluetoothDemo.this.registerReceiver(myReceiver, intentFilter);
bluetoothAdapter.startDiscovery();
}
private void onBluetooth() {
if(!bluetoothAdapter.isEnabled())
{
bluetoothAdapter.enable();
Log.i("Log", "Bluetooth is Enabled");
}
}
private void offBluetooth() {
if(bluetoothAdapter.isEnabled())
{
bluetoothAdapter.disable();
}
}
private void makeDiscoverable() {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
Log.i("Log", "Discoverable ");
}
class HandleSeacrh extends Handler
{
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 111:
break;
default:
break;
}
}
}
}
Here is the main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/buttonOn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="On"/>
<Button
android:id="@+id/buttonDesc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Make Discoverable"/>
<Button
android:id="@+id/buttonSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Search"/>
<Button
android:id="@+id/buttonOff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bluetooth Off"/>
<ListView
android:id="@+id/listViewPaired"
android:layout_width="match_parent"
android:layout_height="120dp">
</ListView>
<ListView
android:id="@+id/listViewDetected"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
Add this permissions to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
using (var cmd = new SqlCommand("SELECT EmpName FROM [Employee] WHERE EmpID = @id", con))
put []
around table name ;)
// get image from upload-image page
public function postUplodeImage(Request $request)
{
$this->validate($request, [
// check validtion for image or file
'uplode_image_file' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
]);
// rename image name or file name
$getimageName = time().'.'.$request->uplode_image_file->getClientOriginalExtension();
$request->uplode_image_file->move(public_path('images'), $getimageName);
return back()
->with('success','images Has been You uploaded successfully.')
->with('image',$getimageName);
}
I have found that you must be on the latest commit of the git. So these are the steps to take: 1) make sure you have not been working on the same files, otherwise you will run into a DITY_WORK_TREE error. 2) pull the latest changes. 3) commit your updates.
Hope this helps.
You cannot use || operators in between 2 case. But you can use multiple case values without using a break between them. The program will then jump to the respective case and then it will look for code to execute until it finds a "break". As a result these cases will share the same code.
switch(value)
{
case 0:
case 1:
// do stuff for if case 0 || case 1
break;
// other cases
default:
break;
}
(Ubuntu)
If you don’t set a GOPATH, the default will be used.
You have to add $GOPATH/bin to your PATH to execute any binary installed in $GOPATH/bin, or you need to type $GOPATH/bin/the-command. Add this to your ~/.bash_profile
export PATH=$GOPATH/bin:$PATH
Current GOPATH command:
go env GOPATH
Changing the GOPATH command:
export GOPATH=$HOME/your-desired-path
Either use instanceof
or method Class.isAssignableFrom(Class<?> cls)
.
There are several methods, two of which are as follows. Provide a custom installer or a setup project.
Here is how to create a custom installer
[RunInstaller(true)]
public class MyInstaller : Installer
{
public HelloInstaller()
: base()
{
}
public override void Commit(IDictionary mySavedState)
{
base.Commit(mySavedState);
System.IO.File.CreateText("Commit.txt");
}
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
System.IO.File.CreateText("Install.txt");
}
public override void Uninstall(IDictionary savedState)
{
base.Uninstall(savedState);
File.Delete("Commit.txt");
File.Delete("Install.txt");
}
public override void Rollback(IDictionary savedState)
{
base.Rollback(savedState);
File.Delete("Install.txt");
}
}
To add a setup project
Menu file -> New -> Project --> Other Projects Types --> Setup and Deployment
Set properties of the project, using the properties window
The article How to create a Setup package by using Visual Studio .NET provides the details.
Important: Use the
( )
parentheses in your search string
While the previous answer is correct there is an important thing to emphasize! All the matched segments in your search string that you want to use in your replacement string must be enclosed by ( )
parentheses, otherwise these matched segments won't be accessible to defined variables such as $1
, $2
or \1
, \2
etc.
For example we want to replace 'em' with 'px' but preserve the digit values:
margin: 10em; /* Expected: margin: 10px */
margin: 2em; /* Expected: margin: 2px */
margin: $1px
or margin: \1px
margin: ([0-9]*)em
// with parenthesesmargin: [0-9]*em
CORRECT CASE EXAMPLE: Using margin: ([0-9]*)em
search string (with parentheses). Enclose the desired matched segment (e.g. $1
or \1
) by ( )
parentheses as following:
margin: ([0-9]*)em
(with parentheses)margin: $1px
or margin: \1px
margin: 10px;
margin: 2px;
INCORRECT CASE EXAMPLE: Using margin: [0-9]*em
search string (without parentheses). The following regex pattern will match the desired lines but matched segments will not be available in replaced string as variables such as $1
or \1
:
margin: [0-9]*em
(without parentheses)margin: $1px
or margin: \1px
margin: px; /* `$1` is undefined */
margin: px; /* `$1` is undefined */
Try this out.
<iframe src="https://docs.google.com/viewerng/viewer?url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true" frameborder="0" height="100%" width="100%">_x000D_
</iframe>
_x000D_
The proper interval to get one second is 1000. The Interval
property is the time between ticks in milliseconds:
So, it's not the interval that you set that is wrong. Check the rest of your code for something like changing the interval of the timer, or binding the Tick
event multiple times.
If you have error like "ERROR: could not open server file "/file": Permission denied" you can fix it that:
Ran through the same problem, and this is the solution I found: Create a new folder (for instance, tmp) under /home $ cd /home make postgres the owner of that folder $ chown -R postgres:postgres tmp copy in tmp the files you want to write into the database, and make sure they also are owned by postgres. That's it. You should be in business after that.
Toggling USB debugging off and then back on did the trick for me.
Actually if you are waiting for response from a server it should be done programatically. You may create a progress dialog and dismiss it, but then again that is not "the android way".
Currently the recommended method is to use a DialogFragment :
public class MySpinnerDialog extends DialogFragment {
public MySpinnerDialog() {
// use empty constructors. If something is needed use onCreate's
}
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
_dialog = new ProgressDialog(getActivity());
this.setStyle(STYLE_NO_TITLE, getTheme()); // You can use styles or inflate a view
_dialog.setMessage("Spinning.."); // set your messages if not inflated from XML
_dialog.setCancelable(false);
return _dialog;
}
}
Then in your activity you set your Fragment manager and show the dialog once the wait for the server started:
FragmentManager fm = getSupportFragmentManager();
MySpinnerDialog myInstance = new MySpinnerDialog();
}
myInstance.show(fm, "some_tag");
Once your server has responded complete you will dismiss it:
myInstance.dismiss()
Remember that the progressdialog is a spinner or a progressbar depending on the attributes, read more on the api guide
This is the way you should be doing it, and I say this because you are clearly new to C# and should probably try to understand how some basic stuff works!
public int Sum(params int[] customerssalary)
{
int result = 0;
for(int i = 0; i < customerssalary.Length; i++)
{
result += customerssalary[i];
}
return result;
}
with this Sum
function, you can use this to calculate the average too...
public decimal Average(params int[] customerssalary)
{
int sum = Sum(customerssalary);
decimal result = (decimal)sum / customerssalary.Length;
return result;
}
the reason for using a decimal
type in the second function is because the division can easily return a non-integer result
Others have provided a Linq alternative which is what I would use myself anyway, but with Linq there is no point in having your own functions anyway. I have made the assumption that you have been asked to implement such functions as a task to demonstrate your understanding of C#, but I could be wrong.
In addition to answer by Dinesh Prajapati, Use
adb -d logcat <your package name>:<log level>
where -d is for device and you may also choose -e instead for emulator log and log level is a/d/i/v/e/w etc.
Now your command goes like:
adb -d logcat com.example.example:V > logfileName_WithPath.txt
It doesn't look like it's possible to not have the certificate error any more. I'm on Windows XP with IE 8. Group Policy had installed a self-signed certificate as a trusted root certificate for access to an internal site. When I look at MMC with the certificate snap-in I can see the certificate there OK.
When I look at:
Internet Options => Content => certificates
It isn't there!
This behaviour in IE started since our admins let loose with the last lot of Patch-Tuesday updates which installed on my machine on 10th Dec 2009. Prior to that it was quite happy to accept the certificate as valid.
var x = condition || null;
I had this other answer but this one, based on Jack's answer, is significantly faster might be preferred since it works asynchronously, although slightly slower.
public static class StringExtensionMethods
{
public static IEnumerable<string> GetLines(this string str, bool removeEmptyLines = false)
{
using (var sr = new StringReader(str))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (removeEmptyLines && String.IsNullOrWhiteSpace(line))
{
continue;
}
yield return line;
}
}
}
}
Usage:
input.GetLines() // keeps empty lines
input.GetLines(true) // removes empty lines
Test:
Action<Action> measure = (Action func) =>
{
var start = DateTime.Now;
for (int i = 0; i < 100000; i++)
{
func();
}
var duration = DateTime.Now - start;
Console.WriteLine(duration);
};
var input = "";
for (int i = 0; i < 100; i++)
{
input += "1 \r2\r\n3\n4\n\r5 \r\n\r\n 6\r7\r 8\r\n";
}
measure(() =>
input.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None)
);
measure(() =>
input.GetLines()
);
measure(() =>
input.GetLines().ToList()
);
Output:
00:00:03.9603894
00:00:00.0029996
00:00:04.8221971
Robustness diagrams are written after use cases and before class diagrams. They help to identify the roles of use case steps. You can use them to ensure your use cases are sufficiently robust to represent usage requirements for the system you're building.
They involve:
Whereas the Model-View-Controller pattern is used for user interfaces, the Entity-Control-Boundary Pattern (ECB) is used for systems. The following aspects of ECB can be likened to an abstract version of MVC, if that's helpful:
Entities (model)
Objects representing system data, often from the domain model.
Boundaries (view/service collaborator)
Objects that interface with system actors (e.g. a user or external service). Windows, screens and menus are examples of boundaries that interface with users.
Controls (controller)
Objects that mediate between boundaries and entities. These serve as the glue between boundary elements and entity elements, implementing the logic required to manage the various elements and their interactions. It is important to understand that you may decide to implement controllers within your design as something other than objects – many controllers are simple enough to be implemented as a method of an entity or boundary class for example.
Four rules apply to their communication:
Communication allowed:
Entity Boundary Control
Entity X X
Boundary X
Control X X X
After setting the sort expression on the DefaultView (table.DefaultView.Sort = "Town ASC, Cutomer ASC"
) you should loop over the table using the DefaultView not the DataTable instance itself
foreach(DataRowView r in table.DefaultView)
{
//... here you get the rows in sorted order
Console.WriteLine(r["Town"].ToString());
}
Using the Select method of the DataTable instead, produces an array of DataRow. This array is sorted as from your request, not the DataTable
DataRow[] rowList = table.Select("", "Town ASC, Cutomer ASC");
foreach(DataRow r in rowList)
{
Console.WriteLine(r["Town"].ToString());
}
You have to set to element_blank()
in theme()
elements you need to remove
ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
I know there are multiple ways to achieve this as per solutions shared above. I haven't tried all of them but some third party services lack clarity around what are all tasks being run in the background. I have achieved this through a powershell script similar to the one mentioned as windows batch file. I have scheduled it using Windows Tasks Scheduler to run every minute. This has been quite efficient and transparent so far. The advantage I have here is that I am checking the process explicitly before starting it again. This wouldn't cause much overhead to the CPU on the server. Also you don't have to explicitly place the file into the startup folders.
function CheckNodeService ()
{
$node = Get-Process node -ErrorAction SilentlyContinue
if($node)
{
echo 'Node Running'
}
else
{
echo 'Node not Running'
Start-Process "C:\Program Files\nodejs\node.exe" -ArgumentList "app.js" -WorkingDirectory "E:\MyApplication"
echo 'Node started'
}
}
CheckNodeService
The solution to "Cannot Get /" can usually be determined if you do an "ng build" in the command line. You will find most often that one of your "imports" does not have the correct path.
Selects are slow and unnescsaary. The following code will be far faster:
Sub CopyRowsAcross()
Dim i As Integer
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Sheet1")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Sheet2")
For i = 2 To ws1.Range("B65536").End(xlUp).Row
If ws1.Cells(i, 2) = "Your Critera" Then ws1.Rows(i).Copy ws2.Rows(ws2.Cells(ws2.Rows.Count, 2).End(xlUp).Row + 1)
Next i
End Sub
var table = document.getElementById("someTableID");
var totalRows = document.getElementById("someTableID").rows.length;
var totalCol = 3; // enter the number of columns in the table minus 1 (first column is 0 not 1)
//To display all values
for (var x = 0; x <= totalRows; x++)
{
for (var y = 0; y <= totalCol; y++)
{
alert(table.rows[x].cells[y].innerHTML;
}
}
//To display a single cell value enter in the row number and column number under rows and cells below:
var firstCell = table.rows[0].cells[0].innerHTML;
alert(firstCell);
//Note: if you use <th> this will be row 0, so your data will start at row 1 col 0
Make sure there is an namespace definition (xmlns
) for the namespace your control belong to.
xmlns:myControls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"
<myControls:thecontrol/>
\t
will match tabs, rather than spaces and should also be referred to with a double slash: \\t
. You could call s.split( " " )
but that wouldn't count consecutive spaces. By that I mean...
String bar = " ba jfjf jjj j ";
String[] split = bar.split( " " );
System.out.println( split.length ); // Returns 5
So, despite the fact there are seven space characters, there are only five blocks of space. It depends which you're trying to count, I guess.
Commons Lang is your friend for this one.
int count = StringUtils.countMatches( inputString, " " );
Download openSSL -> Install it -> it would usually install in C:\OpenSSL
then open cmd and type
cd../../Program Files (Enter)
java (Enter)
dir (Enter)
cd jdk1.6.0_17 (varies with jdk versions) (Enter)
to check jdk version go to C:/program files/java/jdk_version
cd bin (enter)
keytool -exportcert -alias androiddebugkey -keystore C:Users\Shalini\.android\debug.keystore | "C:\OpenSSL\bin\openssl sha1 -binary | "C:\OpenSSL\bin\openssl base64 (Enter)
It will ask you for password which is android.
I used a third party library called use-force-update to force render my react functional components. Worked like charm. Just use import the package in your project and use like this.
import useForceUpdate from 'use-force-update';
const MyButton = () => {
const forceUpdate = useForceUpdate();
const handleClick = () => {
alert('I will re-render now.');
forceUpdate();
};
return <button onClick={handleClick} />;
};
I had an issue with System.Linq not being recognized. The using
statement had a red squiggly, etc. The way I solved it was to change my website to target dotnet 3.5, then switch back to the original targeted framework (4.0 in my case).
if($_SERVER['REQUEST_METHOD']=='POST'){
$image_no="5";//or Anything You Need
$image = $_POST['image'];
$path = "uploads/".$image_no.".png";
$status = file_put_contents($path,base64_decode($image));
if($status){
echo "Successfully Uploaded";
}else{
echo "Upload failed";
}
}
If you are looking for PERFORMANCE, give where condition inside the db link query. Otherwise it fetch all data from the foreign table and apply the where condition.
INSERT INTO tblA (id,time)
SELECT id, time FROM dblink('dbname=dbname port=5432 host=10.10.90.190 user=postgresuser password=pass123',
'select id, time from tblB where time>'''||1000||'''')
AS t1(id integer, time integer)
I'd use:
var stringNumber = "1234"
var numberFromString = stringNumber.toInt()
println(numberFromString)
Note toInt()
:
If the string represents an integer that fits into an Int, returns the corresponding integer.
If you need this and similar operations more often, it may be more convenient to find the right library instead of implementing it yourself.
Here are one-liners solving your question from Apache Commons Math using Precision, Colt using Functions, and Weka using Utils:
double value = 540.512 / 1978.8 * 100;
// Apache commons math
double rounded1 = Precision.round(value, 1);
double rounded2 = Precision.round(value, 1, BigDecimal.ROUND_HALF_UP);
// Colt
double rounded3 = Functions.round(0.1).apply(value)
// Weka
double rounded4 = Utils.roundDouble(value, 1)
Maven dependencies:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.5</version>
</dependency>
<dependency>
<groupId>colt</groupId>
<artifactId>colt</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>nz.ac.waikato.cms.weka</groupId>
<artifactId>weka-stable</artifactId>
<version>3.6.12</version>
</dependency>
Apart from above correct answer, also make sure that you have set correct Main Interface in General.
this is my working example Java code to encode QR code using ZXing with UTF-8 encoding, please note: you will need to change the path and utf8 data to your path and language characters
package com.mypackage.qr;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Hashtable;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.*;
public class CreateQR {
public static void main(String[] args)
{
Charset charset = Charset.forName("UTF-8");
CharsetEncoder encoder = charset.newEncoder();
byte[] b = null;
try {
// Convert a string to UTF-8 bytes in a ByteBuffer
ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("utf 8 characters - i used hebrew, but you should write some of your own language characters"));
b = bbuf.array();
} catch (CharacterCodingException e) {
System.out.println(e.getMessage());
}
String data;
try {
data = new String(b, "UTF-8");
// get a byte matrix for the data
BitMatrix matrix = null;
int h = 100;
int w = 100;
com.google.zxing.Writer writer = new MultiFormatWriter();
try {
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(2);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
matrix = writer.encode(data,
com.google.zxing.BarcodeFormat.QR_CODE, w, h, hints);
} catch (com.google.zxing.WriterException e) {
System.out.println(e.getMessage());
}
// change this path to match yours (this is my mac home folder, you can use: c:\\qr_png.png if you are on windows)
String filePath = "/Users/shaybc/Desktop/OutlookQR/qr_png.png";
File file = new File(filePath);
try {
MatrixToImageWriter.writeToFile(matrix, "PNG", file);
System.out.println("printing to " + file.getAbsolutePath());
} catch (IOException e) {
System.out.println(e.getMessage());
}
} catch (UnsupportedEncodingException e) {
System.out.println(e.getMessage());
}
}
}
Having <thead>
and <tbody>
with the same numbers of <th>
and <td>
solved my problem.
The existing answers will fail if the string is empty or only has one character. Options:
String substring = str.length() > 2 ? str.substring(str.length() - 2) : str;
or
String substring = str.substring(Math.max(str.length() - 2, 0));
That's assuming that str
is non-null, and that if there are fewer than 2 characters, you just want the original string.
In all of the cases above, the variable is correctly set, but not correctly read! The right way is to use double quotes when referencing:
echo "$var"
This gives the expected value in all the examples given. Always quote variable references!
Why?
When a variable is unquoted, it will:
Undergo field splitting where the value is split into multiple words on whitespace (by default):
Before: /* Foobar is free software */
After: /*
, Foobar
, is
, free
, software
, */
Each of these words will undergo pathname expansion, where patterns are expanded into matching files:
Before: /*
After: /bin
, /boot
, /dev
, /etc
, /home
, ...
Finally, all the arguments are passed to echo, which writes them out separated by single spaces, giving
/bin /boot /dev /etc /home Foobar is free software Desktop/ Downloads/
instead of the variable's value.
When the variable is quoted it will:
This is why you should always quote all variable references, unless you specifically require word splitting and pathname expansion. Tools like shellcheck are there to help, and will warn about missing quotes in all the cases above.
SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.
As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.
More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.
On some apps you need to remove the slashes to make it work.
/(.)\1{9,}/
or this:
(.)\1{9,}
These days, there's a better solution for importing an existing PHP project. The PDT plugin now has an option on the New PHP Project dialog just for this. So:
From File->New->PHP Project:
How about a one-liner in JS ES10 / ES2019 ?
Making use of Object.entries()
and Object.fromEntries()
:
let newObj = Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v * v]));
The same thing written as a function:
function objMap(obj, func) {
return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, func(v)]));
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);
This function uses recursion to square nested objects as well:
function objMap(obj, func) {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) =>
[k, v === Object(v) ? objMap(v, func) : func(v)]
)
);
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);
With ES7 / ES2016 you cant' use Objects.fromEntries
, but you can achieve the same using Object.assign
in combination with spread operators and computed key names syntax:
let newObj = Object.assign(...Object.entries(obj).map(([k, v]) => ({[k]: v * v})));
ES6 / ES2015 Doesn't allow Object.entires
, but you could use Object.keys
instead:
let newObj = Object.assign(...Object.keys(obj).map(k => ({[k]: obj[k] * obj[k]})));
ES6 also introduced for...of
loops, which allow a more imperative style:
let newObj = {}
for (let [k, v] of Object.entries(obj)) {
newObj[k] = v * v;
}
Instead of Object.fromEntries
and Object.assign
you can also use reduce for this:
let newObj = Object.entries(obj).reduce((p, [k, v]) => ({ ...p, [k]: v * v }), {});
In some rare situation you may need to map a class-like object which holds properties of an inherited object on its prototype-chain. In such cases Object.keys()
and Object.entries()
won't work, because these functions do not include the prototype chain.
If you need to map inherited properties, you can use for (key in myObj) {...}
.
Here is an example of such situation:
const obj1 = { 'a': 1, 'b': 2, 'c': 3}
const obj2 = Object.create(obj1); // One of multiple ways to inherit an object in JS.
// Here you see how the properties of obj1 sit on the 'prototype' of obj2
console.log(obj2) // Prints: obj2.__proto__ = { 'a': 1, 'b': 2, 'c': 3}
console.log(Object.keys(obj2)); // Prints: an empty Array.
console.log(Object.entries(obj2)); // Prints: an empty Array.
for (let key in obj2) {
console.log(key); // Prints: 'a', 'b', 'c'
}
However, please do me a favor and avoid inheritance. :-)