You can use ICU4J, Just need to add POM entry and code is below for any Number, Country and Language.
POM Entry
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>64.2</version>
</dependency>
Code is
public class TranslateNumberToWord {
/**
* Translate
*
* @param ctryCd
* @param lang
* @param reqStr
* @param fractionUnitName
* @return
*/
public static String translate(String ctryCd, String lang, String reqStr, String fractionUnitName) {
StringBuffer result = new StringBuffer();
Locale locale = new Locale(lang, ctryCd);
Currency crncy = Currency.getInstance(locale);
String inputArr[] = StringUtils.split(new BigDecimal(reqStr).abs().toPlainString(), ".");
RuleBasedNumberFormat rule = new RuleBasedNumberFormat(locale, RuleBasedNumberFormat.SPELLOUT);
int i = 0;
for (String input : inputArr) {
CurrencyAmount crncyAmt = new CurrencyAmount(new BigDecimal(input), crncy);
if (i++ == 0) {
result.append(rule.format(crncyAmt)).append(" " + crncy.getDisplayName() + " and ");
} else {
result.append(rule.format(crncyAmt)).append(" " + fractionUnitName + " ");
}
}
return result.toString();
}
public static void main(String[] args) {
String ctryCd = "US";
String lang = "en";
String input = "95.17";
String result = translate(ctryCd, lang, input, "Cents");
System.out.println("Input: " + input + " result: " + result);
}}
Tested with quite a big number and output would be
Input: 95.17 result: ninety-five US Dollar and seventeen Cents
Input: 999999999999999999.99 result: nine hundred ninety-nine quadrillion nine hundred ninety-nine trillion nine hundred ninety-nine billion nine hundred ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine US Dollar and ninety-nine Cents
While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this
mkdir -p {main,test}/{resources,scala/com/company}
It will create following directory structure under the directory from where it is invoked
+-- main
¦ +-- resources
¦ +-- scala
¦ +-- com
¦ +-- company
+-- test
+-- resources
+-- scala
+-- com
+-- company
The example was taken from this link for creating SBT directory structure
A span tag is only as wide as its contents, so there is no 'center' of a span tag. There is no extra space on either side of the content.
A div tag, however, is as wide as its containing element, so the content of that div can be centered using any extra space that the content doesn't take up.
So if your div is 100px width and your content only takes 50px, the browser will divide the remaining 50px by 2 and pad 25px on each side of your content to center it.
The parenthesis are superfluous in your example. The pointer doesn't care whether there's an array involved - it only knows that its pointing to an int
int g[] = {9,8};
int (*j) = g;
could also be rewritten as
int g[] = {9,8};
int *j = g;
which could also be rewritten as
int g[] = {9,8};
int *j = &g[0];
a pointer-to-an-array would look like
int g[] = {9,8};
int (*j)[2] = &g;
//Dereference 'j' and access array element zero
int n = (*j)[0];
There's a good read on pointer declarations (and how to grok them) at this link here: http://www.codeproject.com/Articles/7042/How-to-interpret-complex-C-C-declarations
Don't join like that. It's a really really bad practice!!! It will slow down the performance in fetching with massive data. For example, if there were 100 rows in each tables, database server have to fetch 100x100x100 = 1000000
times. It had to fetch for 1 million
times. To overcome that problem, join the first two table that can fetch result in minimum possible matching(It's up to your database schema). Use that result in Subquery and then join it with the third table and fetch it. For the very first join --> 100x100= 10000
times and suppose we get 5 matching result. And then we join the third table with the result --> 5x100 = 500.
Total fetch = 10000+500 = 10200
times only. And thus, the performance went up!!!
If you're using Python 2.5, this won't work, but for people using 2.6 or 2.7, try
from __future__ import print_function
print("abcd", end='')
print("efg")
results in
abcdefg
For those using 3.x, this is already built-in.
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
// fired when a mutation occurs
console.log(mutations, observer);
// ...
});
// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
subtree: true,
attributes: true
//...
});
Complete explanations: https://stackoverflow.com/a/11546242/6569224
No need to start, it would automatically executed while you startup your mac terminal / bash. Whenever you do a change, you may need to restart the terminal.
~ is the default path for .bash_profile
If you are using Windows, open up a command prompt and type 'netstat -an'.
If your server is running, you should be able to see the port 1883.
If you cannot go to Task Manager > Services and start/restart the Mosquitto server from there. If you cannot find it here too, your installation of Mosquitto has not been successful.
A more detailed tutorial for setting up Mosquitto with Windows / is linked here.
Personally I extract the POST array and then have if(!$login || !$password) then echo fill out the form :)
There is another solution for this.
Consider the quotes as part of the fields delimiter, by editing the fmt file.
You can check this out for more information:
An extract of the link above:
The only way to remove the quotation marks would be to modify the column delimiters specified during the import operation. The only drawback here is that if you inspect the data to be inserted, you will very quickly realize that the column delimiters are different for each column (Delimiters highlighted above).
So to specify different column delimiters for each column, you would need to use a format file if you plan to use Bulk Insert or BCP. If you generate a format file for the above table structure, it would be as follows:
9.0
3
1 SQLCHAR 0 5 "\t" 1 FName SQL_Latin1_General_CP1_CI_AS
2 SQLCHAR 0 5 "\t" 2 LName SQL_Latin1_General_CP1_CI_AS
3 SQLCHAR 0 50 "\r\n" 3 Company SQL_Latin1_General_CP1_CI_AS
Modify the format file to represent the correct column delimiters for each column. The new format file to be used will look like this:
9.0
4
1 SQLCHAR 0 0 "\"" 0 FIRST_QUOTE SQL_Latin1_General_CP1_CI_AS
2 SQLCHAR 0 5 "\",\"" 1 FNAME SQL_Latin1_General_CP1_CI_AS
3 SQLCHAR 0 5 "\",\"" 2 LNAME SQL_Latin1_General_CP1_CI_AS
4 SQLCHAR 0 50 "\"\r\n" 3 COMPANY SQL_Latin1_General_CP1_CI_AS
How to update in codeignitor?
whenever you want to update same status with multiple rows you use where_in insteam of where or if you want to change only single record can use where.
below is my code
$conditionArray = array(1, 3, 4, 6);
$this->db->where_in("ip_id", $conditionArray);
$this->db->update($this->table, array("status" => 'active'));
its working perfect.
Try this:
import tkinter as tk
from PIL import ImageTk, Image
#This creates the main window of an application
window = tk.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')
path = "Aaron.jpg"
#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img = ImageTk.PhotoImage(Image.open(path))
#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
panel = tk.Label(window, image = img)
#The Pack geometry manager packs widgets in rows or columns.
panel.pack(side = "bottom", fill = "both", expand = "yes")
#Start the GUI
window.mainloop()
Related docs: ImageTk Module, Tkinter Label Widget, Tkinter Pack Geometry Manager
num1 = 10 + 10*(someBoolValue is True)
That's my new final answer.
Prior answer was as follows and was overkill for the stated problem. Getting_too_clever == not Good
. Here's the prior answer... still good if you want add one thing for True
cond and another for False
:
num1 = 10 + (0,10)[someBoolValue is True]
You mentioned num1
would already have a value that should be left alone. I assumed num1 = 10
since that's the first statement of the post, so the operation to get to 20
is to add 10
.
num1 = 10
someBoolValue = True
num1 = 10 + (0,10)[someBoolValue is True]
print(f'num1 = {num1}\nsomeBoolValue = {someBoolValue}')
produced this output
num1 = 20
someBoolValue = True
I had a similar issue and ended up hooking and event
ng-change="changeCount()"
then:
self.changeCount = function () {
if (!self.info.itemcount) {
self.info.itemcount = 1;
}
};
So the user is defaulted to 1 if a invalid number is inserted.
Well, another working solution based on Cody's answer but a little more general can be something like this:
function timedAlert(msg, timing){
setTimeout(function(){
alert(msg);
}, timing);
}
function yourFunction(time, counter){
for (var i = 1; i <= counter; i++) {
var msg = i, timing = i * time * 1000; //this is in seconds
timedAlert (msg, timing);
};
}
yourFunction(timeInSeconds, counter); // well here are the values of your choice.
Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.
Stumbled upon this question while checking for correct code for duplicate record.
Pardon my ignorance but I don't understand why everyone is ignoring the code "300" which clearly says "multiple choice" or "Ambiguous"
In my opinion this would be the perfect code for building a non standard or a particular system for your own use. I could be wrong as well!
Try this code:
function logErr($data){
$logPath = __DIR__. "/../logs/logs.txt";
$mode = (!file_exists($logPath)) ? 'w':'a';
$logfile = fopen($logPath, $mode);
fwrite($logfile, "\r\n". $data);
fclose($logfile);
}
I always use it like this, and it works...
You need to parse the string you are sending from javascript object to the JSON object
var json=$.parseJSON(data);
Run "cmd.exe" as administrator and then run "sc.exe" to add a new Windows service.
for example:
sc.exe create MongoDB binPath= "c:\program files\mongodb\server\3.2\bin\mongod.exe"
After a long Google, I came to know that javac.exe will be inside JDK(C:\Program Files\Java\jdk(version number)\bin) not inside JRE (C:\Program Files (x86)\Java\jre7\bin) "JRE doesn't come with a compiler. It(JRE) is simply a java runtime environment. What you need is the Java development kit." in order to use compiler javac
javac will not work if you are pointing bin inside jre
In order to use javac in cmd , JDK must be installed in your system...
For javac path
path = C:\Program Files (x86)\Java\jre7\bin this is wrong
path = C:\Program Files\Java\jdk(version number)\bin this is correct
Make sure that "javac.exe" is inside your "C:\Program Files\Java\jdk(version number)\bin"
Don't get confused with JRE and JDK both are totally different
if you don't have JDK pls download from this link
or
http://www.oracle.com/technetwork/java/javase/downloads/index.html
reference thread for JDK VS JRE What is the difference between JDK and JRE?
Maybe you should better use a case
for such lists:
case "$cms" in
wordpress|meganto|typo3)
do_your_else_case
;;
*)
do_your_then_case
;;
esac
I think for long such lists this is better readable.
If you still prefer the if
you can do it with single brackets in two ways:
if [ "$cms" != wordpress -a "$cms" != meganto -a "$cms" != typo3 ]; then
or
if [ "$cms" != wordpress ] && [ "$cms" != meganto ] && [ "$cms" != typo3 ]; then
Its simple one line code for get current Date in this yyyy-MM-dd format you can use your format that you want :
String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
JQuery can't append elements to <svg>
(it does seem to add them in the DOM explorer, but not on the screen).
One workaround is to append an <svg>
with all of the elements that you need to the page, and then modify the attributes of the elements using .attr()
.
$('body')
.append($('<svg><circle id="c" cx="10" cy="10" r="10" fill="green" /></svg>'))
.mousemove( function (e) {
$("#c").attr({
cx: e.pageX,
cy: e.pageY
});
});
The feedback you get on the interactive interpreter uses repr
too. When you type in an expression (let it be expr
), the interpreter basically does result = expr; if result is not None: print repr(result)
. So the second line in your example is formatting the string foo
into the representation you want ('foo'
). And then the interpreter creates the repr
esentation of that, leaving you with double quotes.
Why when I combine %r with double-quote and single quote escapes and print them out, it prints it the way I'd write it in my .py file but not the way I'd like to see it?
I'm not sure what you're asking here. The text single ' and double " quotes
, when run through repr
, includes escapes for one kind of quote. Of course it does, otherwise it wouldn't be a valid string literal by Python rules. That's precisely what you asked for by calling repr
.
Also note that the eval(repr(x)) == x
analogy isn't meant literal. It's an approximation and holds true for most (all?) built-in types, but the main thing is that you get a fairly good idea of the type and logical "value" from looking the the repr
output.
Use:
$first = array_slice($array, 0, 1);
$val= $first[0];
By default, array_slice
does not preserve keys, so we can safely use zero as the index.
After looking into many answers (most of them are correct for their scenarios) and none of them fix my problem I realized that my case is a bit different:
In my weird scenario my component was being rendered inside the state and therefore couldn't be updated. Below is a simple example:
constructor() {
this.myMethod = this.myMethod.bind(this);
this.changeTitle = this.changeTitle.bind(this);
this.myMethod();
}
changeTitle() {
this.setState({title: 'I will never get updated!!'});
}
myMethod() {
this.setState({body: <div>{this.state.title}</div>});
}
render() {
return <>
{this.state.body}
<Button onclick={() => this.changeTitle()}>Change Title!</Button>
</>
}
After refactoring the code to not render the body from state it worked fine :)
Currently, I know about the following three ways:
1. The @Value
annotation
@Value("${<property.name>}")
private static final <datatype> PROPERTY_NAME;
null
.
For instance,
when you try to set it in a preConstruct()
method or an init()
method.
This happens because the value injection happens after the class is fully constructed.
This is why it is better to use the 3'rd option.2. The @PropertySource
annotation
<pre>@PropertySource("classpath:application.properties")
//env is an Environment variable
env.getProperty(configKey);</pre>
PropertySouce
sets values from the property source file in an Environment
variable (in your class) when the class is loaded.
So you able to fetch easily afterword.
3. The @ConfigurationProperties
annotation.
It initializes an entity based on property data.
@ConfigurationProperties
identifies the property file to load.@Configuration
creates a bean based on configuration file variables.@ConfigurationProperties(prefix = "user") @Configuration("UserData") class user { //Property & their getter / setter } @Autowired private UserData userData; userData.getPropertyName();
At least in C++, I think of thread-safe as a bit of a misnomer in that it leaves a lot out of the name. To be thread-safe, code typically has to be proactive about it. It's not generally a passive quality.
For a class to be thread-safe, it has to have "extra" features that add overhead. These features are part of the implementation of the class and generally speaking, hidden from the interface. That is, different threads can access any of the class' members without ever having to worry about conflicting with a concurrent access by a different thread AND can do so in a very lazy manner, using some plain old regular human coding style, without having to do all that crazy synchronization stuff that is already rolled into the guts of the code being called.
And this is why some people prefer to use the term internally synchronized.
There are three main sets of terminology for these ideas I have encountered. The first and historically more popular (but worse) is:
The second (and better) is:
A third is:
thread safe ~ thread proof ~ internally synchronized
An example of an internally synchronized (aka. thread-safe or thread proof) system is a restaurant where a host greets you at the door, and disallows you from queueing yourself. The host is part of the mechanism of the restaurant for dealing with multiple customers, and can use some rather tricky tricks for optimizing the seating of waiting customers, like taking the size of their party into account, or how much time they look like they have, or even taking reservations over the phone. The restaurant is internally synchronized because all of this is included "behind the scenes" when you interact with it. You, the customer, don't do any of it. The host does all of it for you.
not thread-safe (but nice) ~ thread compatible ~ externally synchronized ~ free-threaded
Suppose that you go to the bank. There is a line, i.e. contention for the bank tellers. Because you're not a savage, you recognize that the best thing to do in the midst of contention for a resource is to queue like a civilized being. No one technically makes you do this. We hope you have the necessary social programming to do it on your own. In this sense, the bank lobby is externally synchronized. Should we say that it's thread-unsafe? that's what the implication is if you go with the thread-safe, thread-unsafe bipolar terminology set. It's not a very good set of terms. The better terminology is externally synchronized, The bank lobby is not hostile to being accessed by multiple customers, but it doesn't do the work of synchronizing them either. The customers do that themselves.
This is also called "free threaded," where "free" is as in "free from lice"--or in this case, locks. Well, more accurately, synchronization primitives. That doesn't mean the code can run on multiple threads without those primitives. It just means it doesn't come with them already installed and it's up to you, the user of the code, to install them yourself however you see fit. Installing your own synchronization primitives can be difficult and requires thinking hard about the code, but also can lead to the fastest possible program by allowing you to customize how the program executes on today's hyperthreaded CPUs.
not thread safe (and bad) ~ thread hostile ~ unsynchronizable
An example everyday analogy of a thread-hostile system is some jerk with a sports car refusing to use their blinkers and changing lanes willy-nilly. Their driving style is thread hostile or unsychronizable because you have no way to coordinate with them, and this can lead to contention for the same lane, without resolution, and thus an accident as two cars attempt to occupy the same space, without any protocol to prevent this. This pattern can also be thought of more broadly as anti-social, which I prefer because it's less specific to threads and so more generally applicable to many areas of programming.
The first and oldest terminology set fails to make the finer distinction between thread hostility and thread compatibility. Thread compatibility is more passive than so-called thread safety, but that doesn't mean the called code is unsafe for concurrent thread use. It just means it's passive about the synchronization that would allow this, putting it off to the calling code, instead of providing it as part of its internal implementation. Thread compatible is how code should probably be written by default in most cases but this is also sadly often erroneously thought of as thread unsafe, as if it's inherently anti safety, which is a major point of confusion for programmers.
NOTE: Many software manuals actually use the term "thread-safe" to refer to "thread-compatible," adding even more confusion to what was already a mess! I avoid the term "thread-safe" and "thread-unsafe" at all costs for this very reason, as some sources will call something "thread-safe" while others will call it "thread-unsafe" because they can't agree on whether you have to meet some extra standards for safety (synchronization primitives), or just NOT be hostile to be considered "safe". So avoid those terms and use the smarter terms instead, to avoid dangerous miscommunications with other engineers.
Essentially, our goal is to subvert chaos.
We do that by creating deterministic systems we can rely on. Determinism is expensive, mostly due to the opportunity costs of losing parallelism, pipelining, and reordering. We try to minimize the amount of determinism we need to keep our costs low, while also avoiding making decisions that will further erode what little determinism we can afford.
Synchronization of threads is about increasing the order and decreasing the chaos. The levels at which you do this correspond to the terms mentioned above. The highest level means that a system behaves in an entirely predictable manner every time. The second level means that the system behaves well enough that calling code can reliably detect unpredictability. For example, a spurious wakeup in a condition variable or a failure to lock a mutex because it's not ready. The third level means that the system doesn't behave well enough to play with anyone else and can only EVER be run single-threaded without incurring chaos.
The default date format depends on the language setting for the database server. You can also change it per session, like:
set language french
select cast(getdate() as varchar(50))
-->
févr 8 2013 9:45AM
Could not find stored procedure?---- means when you get this.. our code like this
String sp="{call GetUnitReferenceMap}";
stmt=conn.prepareCall(sp);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
currencyMap.put(rs.getString(1).trim(), rs.getString(2).trim());
I have 4 DBs(sample1, sample2, sample3) But stmt
will search location is master
Default DB then we will get Exception.
we should provide DB name then problem resolves::
String sp="{call sample1..GetUnitReferenceMap}";
The answer is yes. In short, it is a subject alternative name (SAN) certificate that contains IPs where you would typically see DNS entries. The certificate type is not limited to Public IPs - that restriction is only imposed by a signing authority rather than the technology. I just wanted to clarify that point. I suspect you really just want to get rid of that pesky insecure prompt on your internal websites and devices without the cost and hassle of giving them DNS names then paying for a CA to issue a cert every year or two. You should NOT be trying to convince the world that your IP address is a reputable website and folks should feel comfortable providing their payment information. Now that we have established why no reputable organization wants to issue this type of certificate, lets just do it ourselves with a self signed SAN certificate. Internally I have a trusted certificate that is deployed to all of our hosts, then I sign this type of certificate with it and all devices become trusted. Doing that here is beyond the scope of the question but I think it relevant to the discussion as the question and solution go hand in hand. To be concise, here is how to generate an individual self signed SAN certificate with IP addresses. Expand the IP list to include your entire subnet and use one cert for everything.
#!/bin/bash
#using: OpenSSL 1.1.1c FIPS 28 May 2019 / CentOS Linux release 8.2.2004
C=US ; ST=Confusion ; L=Anywhere ; O=Private\ Subnet ; [email protected]
BITS=2048
CN=RFC1918
DOM=company.com
SUBJ="/C=$C/ST=$ST/L=$L/O=$O/CN=$CN.$DOM"
openssl genrsa -out ip.key $BITS
SAN='\n[SAN]\nsubjectAltName=IP:192.168.1.0,IP:192.168.1.1,IP:192.168.1.2,IP:192.168.1.3,IP:192.168.1.4,IP:192.168.1.5,IP:192.168.1.6,IP:192.168.1.7,IP:192.168.1.8,IP:192.168.1.9,IP:192.168.1.10'
cp /etc/pki/tls/openssl.cnf /tmp/openssl.cnf
echo -e "$SAN" >> /tmp/openssl.cnf
openssl req -subj "$SUBJ" -new -x509 -days 10950 \
-key ip.key -out ip.crt -batch \
-set_serial 168933982 \
-config /tmp/openssl.cnf \
-extensions SAN
openssl x509 -in ip.crt -noout -text
The accepted answer works quite well. An alternative method that I have used is to create a FormClosing method for the main Form. This is very similar to the override. My example is for an application that minimizes to the system tray when clicking the close button on the Form.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.ApplicationExitCall)
{
return;
}
else
{
e.Cancel = true;
WindowState = FormWindowState.Minimized;
}
}
This will allow ALT+F4 or anything in the Application calling Application.Exit(); to act as normal while clicking the (X) will minimize the Application.
You could pass an object as attribute and read it into the directive like this:
<div my-directive="{id:123,name:'teo',salary:1000,color:red}"></div>
app.directive('myDirective', function () {
return {
link: function (scope, element, attrs) {
//convert the attributes to object and get its properties
var attributes = scope.$eval(attrs.myDirective);
console.log('id:'+attributes.id);
console.log('id:'+attributes.name);
}
};
});
No, unfortunately this will not be possible because ConverterParameter
is not a DependencyProperty
so you won't be able to use bindings
But perhaps you could cheat and use a MultiBinding
with IMultiValueConverter
to pass in the 2 Tag
properties.
I have also used the SimpleViewPagerIndicator from @JROD. It also crashes as described by @manuelJ.
According to his documentation:
SimpleViewPagerIndicator pageIndicator = (SimpleViewPagerIndicator) findViewById(R.id.page_indicator);
pageIndicator.setViewPager(pager);
Make sure you add this line as well:
pageIndicator.notifyDataSetChanged();
It crashes with an array out of bounds exception because the SimpleViewPagerIndicator is not getting instantiated properly and the items are empty. Calling the notifyDataSetChanged results in all the values being set properly or rather reset properly.
try this query below:
Insert into tab1 (tab1.column1,tab1.column2)
select tab2.column1, 'hard coded value'
from tab2
where tab2.column='value';
you can simply do this..
<img src={"http://img.example.com/test/" + this.props.url +"/1.jpg"}/>
When eclipse runs the test case it will look for the file in target/classes not src/test/resources. When the resource is saved eclipse should copy it from src/test/resources to target/classes if it has changed but if for some reason this has not happened then you will get this error. Check that the file exists in target/classes to see if this is the problem.
Working Query:
SELECT replace(col_name , ' ','') FROM table_name;
While this doesn't :
SELECT trim(col_name) FROM table_name;
Backout restores or undoes our changes. The way it does this is that, P4 undoes the changes in a changelist (default or new) on our local workspace. We then have to submit/commit this backedout changelist as we do other changeslists. The second part is important here, as it doesn't automatically backout the changelist on the server, we have to submit the backedout changelist (which makes sense after you do it, but i was initially assuming it does that automatically).
As pointed by others, Rollback has greater powers - It can restore changes to a specific date, changelist or a revision#
In my case, I forgot to add my IP address in firewall rules in Azure, basically as I was unable to connect to the database I was getting this error. So specifically for my case, I added my IP address in database firewall rules in Azure and it all worked well. Apart from this, it could be the issue of proxy/internet connection/DB username password/DB connection string etc. OR obviously, you might have pending migrations for which you need to run Update-Database command.
public ActionResult CreatePerson(int id) //controller
window.location.href = '@Url.Action("CreatePerson", "Person")?id=' + id;
Or
var id = 'some value';
window.location.href = '@Url.Action("CreatePerson", "Person", new {id = id})';
Thanks Philip this helped me - my use case was I had a form with lot of input fields so I maintained initial state as object and I was not able to update the object state.The above post helped me :)
const [projectGroupDetails, setProjectGroupDetails] = useState({
"projectGroupId": "",
"projectGroup": "DDD",
"project-id": "",
"appd-ui": "",
"appd-node": ""
});
const inputGroupChangeHandler = (event) => {
setProjectGroupDetails((prevState) => ({
...prevState,
[event.target.id]: event.target.value
}));
}
<Input
id="projectGroupId"
labelText="Project Group Id"
value={projectGroupDetails.projectGroupId}
onChange={inputGroupChangeHandler}
/>
Using @joran's sample data,
ggplot(dat, aes(x=xx, fill=yy)) + geom_histogram(alpha=0.2, position="identity")
note that the default position of geom_histogram
is "stack."
see "position adjustment" of this page:
Extend the TextView
class and override the onDraw()
method. Make sure the parent view is large enough to handle the rotated button without clipping it.
@Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.rotate(45,<appropriate x pivot value>,<appropriate y pivot value>);
super.onDraw(canvas);
canvas.restore();
}
If you're googling this, and don't want the event listener to be an attribute, use:
document.getElementById('my-select').addEventListener('change', function() {_x000D_
console.log('You selected: ', this.value);_x000D_
});
_x000D_
<select id="my-select">_x000D_
<option value="1">One</option>_x000D_
<option value="2">Two</option>_x000D_
<option value="3">Three</option>_x000D_
</select>
_x000D_
Gradle:
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
Maven:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
Gson jar downloads are available from Maven Central.
It accepts only a string value of "true"
to represent boolean true
. Best what you can do is
boolean uses_votes = "1".equals(o.get("uses_votes"));
Or if the Map
actually represents an "entitiy", I think a Javabean is way much better. Or if it represents configuration settings, you may want to take a look into Apache Commons Configuration.
perl -ne 'print if 16224..16482' file.txt > new_file.txt
Just escape the dashes to prevent them from being interpreted (I don't think underscore needs escaping, but it can't hurt). You don't say which regex you are using.
([A-Za-z0-9\-\_]+)
This worked at least in matplotlib version 2.2.2:
plt.axis([None, None, 0, 100])
Probably this is a nice way to set up for example xmin and ymax only, etc.
Another solution is to use an Oracle Collection as a Hashmap:
declare
-- create a type for your "Array" - it can be of any kind, record might be useful
type hash_map is table of varchar2(1000) index by varchar2(30);
my_hmap hash_map ;
-- i will be your iterator: it must be of the index's type
i varchar2(30);
begin
my_hmap('a') := 'apple';
my_hmap('b') := 'box';
my_hmap('c') := 'crow';
-- then how you use it:
dbms_output.put_line (my_hmap('c')) ;
-- or to loop on every element - it's a "collection"
i := my_hmap.FIRST;
while (i is not null) loop
dbms_output.put_line(my_hmap(i));
i := my_hmap.NEXT(i);
end loop;
end;
For serializable deep clone, with Type Information is,
export function clone<T>(a: T): T {
return JSON.parse(JSON.stringify(a));
}
"We usually put ' (space)' after the first sentence before a new line, but it doesn't work in Jupyter."
That inspired me to try using two spaces instead of just one - and it worked!!
(Of course, that functionality could possibly have been introduced between when the question was asked in January 2017, and when my answer was posted in March 2018.)
I'd say that the main rule of thumb is not to roll your own. Try to use something that has been thoroughly tested, e.g., SHA-1 or something along those lines.
You can put conditionals inside tags. Try:
ng-class="{true:'active',false:'disable'}[list_status=='show']"
that because you calling toggle inside the render method which will cause to re-render and toggle will call again and re-rendering again and so on
this line at your code
{<td><span onClick={this.toggle()}>Details</span></td>}
you need to make onClick
refer to this.toggle
not calling it
to fix the issue do this
{<td><span onClick={this.toggle}>Details</span></td>}
Turns out it needs to be specified via escaped unicode. This question is related and contains the answer.
The solution:
h2:after {
content: "\00a0";
}
I have something different stuff for you which is easy and effective.
<style>
.case-after:after { // set your properties here like eg:
color:#3fd309 !important;
}
.case-before:before { // set your properties here like eg:
color:#151715 !important;
}
</style>
// case for after
$('#button-id').on('click', function() {
$(".target-div").toggleClass('case-after');
});
// case for before
$('#button-id').on('click', function() {
$(".target-div").toggleClass('case-before');
});
What about support for border radius AND background gradient. Yes IE9 is to support them both seperately but if you mix the two the gradient bleeds out of the rounded corner. Below is a link to a poor example but i have seen it in my own testing as well. Should of taken a screen shot :(
Maybe the real question is when will IE support CSS standards without MS-FILTER proprietary hacks.
http://frugalcoder.us/post/2010/09/15/ie9-corner-plus-gradient-fail.aspx
Try formatting the date in the kendo grid as:
columns.Bound(x => x.LastUpdateDate).ClientTemplate("#= kendo.toString(LastUpdateDate, \"MM/dd/yyyy hh:mm tt\") #");
Okay, Probably I am late but I have faced this issue after upgrading to 3.0.1 from 3.0. And this problem because I am working in restricted network.
The solution which worked for me is as follow:
Solution
Step 1: Get Certificate
jcenter()
equals to https://bintray.com/bintray/jcenter
You need import jcenter's cerficate into your java keystore.
Visit jcenter using your browser and export the certificate as .cer file. (lock icon on the left of Firefox address bar, or Chrome developer tool secuity tab. Internet Explorer and Edge do not support saving of Website certificates, though.)
Step 2: Import Certificate
In Android Studio, go to File -> Settings -> Tools -> Server Certificates
.
Under Accept certificates click on +
. Select the exported certificate.
Step 3: Refresh Keystore In Android Studio, go to File -> Invalidate Caches/Restart...
. Select Invalidate and Restart
from the message box that appears.
it will work fine for me
Change Following.
Step 1: Make sure ApplicationId And PackageName will Same. example :
android {
defaultConfig {
applicationId "com.example.myapplication"
}
}
and package name the same. package="com.example.myapplication"
Step 2 delete iml file in my case :
Go To Project> >C:\Users\ashif\Documents\MyApplication .iml file // delete
if you forget Project Path Then Go To android Studio Right Click on app and go to Show in Explorer you get your Project and remove .iml file
Step 3 Close Project
Step 4 Now Copy Your old Project and Paste Any other Root or copy Project Folder and paste Any other Dir.
Example C:\Users\ashif\Documents/MyApplication
Step 5
Now open Android Studio and open Existing Project
C:\Users\ashif\Documents/MyApplication
Try it will work
This will capture requests for files like version
,
release
, and README.md
, etc. which should be
treated either as endpoints, if defined (as in the
case of /release), or as "not found."
html, body{
width:100%;
}
This tells the html to be 100% wide. But 100% refers to the whole browser window width, so no more than that.
You may want to set a min width instead.
html, body{
min-width:100%;
}
So it will be 100% as a minimum, bot more if needed.
You don't need usebackq:
FOR /F delims^= %%A IN ('DIR/AD/B/S^|SORT/R') DO RD "%%A"
If you already know the indices:
list1 = ['x','y','z','a','b','c','d','e','f','g']
indices = [(0, 4), (5, 9)]
print [list1[s:e+1] for s,e in indices]
Note that we're adding +1 to the end to make the range inclusive...
In my case it was because I was using a port other than the default port 80. I was able to access the site locally using localhost but not on another machine using the IP address.
To solve the issue I had to add a firewall inbound rule to allow the port.
if you want to save the selection to file or any else and call it later, here what I do
string[] lines = new string[1];
lines[0] = groupBoxTes.Controls.OfType<RadioButton>()
.FirstOrDefault(r => r.Checked).Text;
File.WriteAllLines("Config.ini", lines);
then call it with
string[] ini = File.ReadAllLines("Config.ini");
groupBoxTes.Controls.OfType<RadioButton>()
.FirstOrDefault(r => (r.Text == ini[0])).Checked = true;
For visual learners, when defining the function without .prototype
ExampleClass = function(){};
ExampleClass.method = function(customString){
console.log((customString !== undefined)?
customString :
"called from func def.");}
ExampleClass.method(); // >> output: `called from func def.`
var someInstance = new ExampleClass();
someInstance.method('Called from instance');
// >> error! `someInstance.method is not a function`
With same code, if .prototype
is added,
ExampleClass.prototype.method = function(customString){
console.log((customString !== undefined)?
customString :
"called from func def.");}
ExampleClass.method();
// > error! `ExampleClass.method is not a function.`
var someInstance = new ExampleClass();
someInstance.method('Called from instance');
// > output: `Called from instance`
To make it clearer,
ExampleClass = function(){};
ExampleClass.directM = function(){} //M for method
ExampleClass.prototype.protoM = function(){}
var instanceOfExample = new ExampleClass();
ExampleClass.directM(); ? works
instanceOfExample.directM(); x Error!
ExampleClass.protoM(); x Error!
instanceOfExample.protoM(); ? works
****Note for the example above, someInstance.method() won't be executed as,
ExampleClass.method() causes error & execution cannot continue.
But for the sake of illustration & easy understanding, I've kept this sequence.****
Results generated from chrome developer console
& JS Bin
Click on the jsbin link above to step through the code.
Toggle commented section with ctrl+/
Adding Json.stringfy
around the json that fixed the issue
There's a niche case where git mv
remains very useful: when you want to change the casing of a file name on a case-insensitive file system. Both APFS (mac) and NTFS (windows) are, by default, case-insensitive (but case-preserving).
greg.kindel mentions this in a comment on CB Bailey's answer.
Suppose you are working on a mac and have a file Mytest.txt
managed by git. You want to change the file name to MyTest.txt
.
You could try:
$ mv Mytest.txt MyTest.txt
overwrite MyTest.txt? (y/n [n]) y
$ git status
On branch master
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
Oh dear. Git doesn't acknowledge there's been any change to the file.
You could work around this with by renaming the file completely then renaming it back:
$ mv Mytest.txt temp.txt
$ git rm Mytest.txt
rm 'Mytest.txt'
$ mv temp.txt MyTest.txt
$ git add MyTest.txt
$ git status
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
renamed: Mytest.txt -> MyTest.txt
Hurray!
Or you could save yourself all that bother by using git mv
:
$ git mv Mytest.txt MyTest.txt
$ git status
On branch master
Your branch is up to date with 'origin/master'.
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
renamed: Mytest.txt -> MyTest.txt
Add below to your gradle file:
plugins {
`id "com.github.ManifestClasspath" version "0.1.0-RELEASE"
}
See https://plugins.gradle.org/plugin/com.github.ManifestClasspath
The other answers explain how to produce a string formatted like in your example, but if all you need to do is to print
that stuff you could simply write:
first = 10
second = 20
print "First number is", first, "and second number is", second
static void Main()
{
// A.
// Example strings with multiple whitespaces.
string s1 = "He saw a cute\tdog.";
string s2 = "There\n\twas another sentence.";
// B.
// Create the Regex.
Regex r = new Regex(@"\s+");
// C.
// Strip multiple spaces.
string s3 = r.Replace(s1, @" ");
Console.WriteLine(s3);
// D.
// Strip multiple spaces.
string s4 = r.Replace(s2, @" ");
Console.WriteLine(s4);
Console.ReadLine();
}
OUTPUT:
He saw a cute dog. There was another sentence. He saw a cute dog.
Simply use the administrative shares to copy files between systems. It's much easier this way.
Copy-Item -Path \\serverb\c$\programs\temp\test.txt -Destination \\servera\c$\programs\temp\test.txt;
By using UNC paths instead of local filesystem paths, you help to ensure that your script is executable from any client system with access to those UNC paths. If you use local filesystem paths, then you are cornering yourself into running the script on a specific computer.
This only works when a PowerShell session runs under the user who has rights to both administrative shares.
I suggest to use regular network share on server B with read-only access to everyone and simply call (from Server A):
Copy-Item -Path "\\\ServerB\SharedPathToSourceFile" -Destination "$Env:USERPROFILE" -Force -PassThru -Verbose
Oracle optimizer chooses join order of tables for inner join. Optimizer chooses the join order of tables only in simple FROM clauses . U can check the oracle documentation in their website. And for the left, right outer join the most voted answer is right. The optimizer chooses the optimal join order as well as the optimal index for each table. The join order can affect which index is the best choice. The optimizer can choose an index as the access path for a table if it is the inner table, but not if it is the outer table (and there are no further qualifications).
The optimizer chooses the join order of tables only in simple FROM clauses. Most joins using the JOIN keyword are flattened into simple joins, so the optimizer chooses their join order.
The optimizer does not choose the join order for outer joins; it uses the order specified in the statement.
When selecting a join order, the optimizer takes into account: The size of each table The indexes available on each table Whether an index on a table is useful in a particular join order The number of rows and pages to be scanned for each table in each join order
If you are using bash, you might as well write
echo -n "hello" >/dev/udp/localhost/8000
and avoid all the idiosyncrasies and incompatibilities of netcat.
This also works sending to other hosts, ex:
echo -n "hello" >/dev/udp/remotehost/8000
These are not "real" devices on the file system, but bash "special" aliases. There is additional information in the Bash Manual.
If you are looking for exact words and don't want it to match things like "nightmare" (which is probably what you need), you can use a regex:
/\bare\b/gi
\b = word boundary
g = global
i = case insensitive (if needed)
If you just want to find the characters "are", then use indexOf
.
If you want to match arbitrary words, you have to programatically construct a RegExp (regular expression) object itself based on the word string and use test
.
[solved]
#copy all the code below:
#save file as .ps1 run and see the magic
Get-WmiObject -Class Win32_OperatingSystem | ForEach-Object -MemberName Caption
(Get-CimInstance Win32_OperatingSystem).version
#-------------comment-------------#
#-----finding windows version-----#
$version= (Get-CimInstance Win32_OperatingSystem).version
$length= $version.Length
$index= $version.IndexOf(".")
[int]$windows= $version.Remove($index,$length-2)
$windows
#-----------end------------------#
#-----------comment-----------------#
You can extend jQuery functionality like this :
Extend :
(function($){
jQuery.fn.checkEmpty = function() {
return !$.trim(this.html()).length;
};
}(jQuery));
Use :
<div id="selector"></div>
if($("#selector").checkEmpty()){
console.log("Empty");
}else{
console.log("Not Empty");
}
The wait for the document.ready event is not the entire fix to this problem, because this code is still in a race condition: Sometimes this code is fired before the click event is processed so this directly returns, since the browser hasn't started loading the new page yet.
After some searching I found a post on Obay the testing goat, which has a solution for this problem. The c# code for that solution is something like this:
IWebElement page = null;
...
public void WaitForPageLoad()
{
if (page != null)
{
var waitForCurrentPageToStale = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
waitForCurrentPageToStale.Until(ExpectedConditions.StalenessOf(page));
}
var waitForDocumentReady = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
waitForDocumentReady.Until((wdriver) => (driver as IJavaScriptExecutor).ExecuteScript("return document.readyState").Equals("complete"));
page = driver.FindElement(By.TagName("html"));
}
` I fire this method directly after the driver.navigate.gotourl, so that it gets a reference of the page as soon as possible. Have fun with it!
I just encountered this. You may be accessing a method/type from within the same package using the package name itself.
Here is an example to illustrate what I mean:
In foo.go:
// foo.go
package foo
func Foo() {...}
In foo_test.go:
// foo_test.go
package foo
// try to access Foo()
foo.Foo() // WRONG <== This was the issue. You are already in package foo, there is no need to use foo.Foo() to access Foo()
Foo() // CORRECT
This may be coming in Late but I think I figured out a better way to load external configurations especially when you run your spring-boot app using java jar myapp.war
instead of @PropertySource("classpath:some.properties")
The configuration would be loaded form the root of the project or from the location the war/jar file is being run from
public class Application implements EnvironmentAware {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
@Override
public void setEnvironment(Environment environment) {
//Set up Relative path of Configuration directory/folder, should be at the root of the project or the same folder where the jar/war is placed or being run from
String configFolder = "config";
//All static property file names here
List<String> propertyFiles = Arrays.asList("application.properties","server.properties");
//This is also useful for appending the profile names
Arrays.asList(environment.getActiveProfiles()).stream().forEach(environmentName -> propertyFiles.add(String.format("application-%s.properties", environmentName)));
for (String configFileName : propertyFiles) {
File configFile = new File(configFolder, configFileName);
LOGGER.info("\n\n\n\n");
LOGGER.info(String.format("looking for configuration %s from %s", configFileName, configFolder));
FileSystemResource springResource = new FileSystemResource(configFile);
LOGGER.log(Level.INFO, "Config file : {0}", (configFile.exists() ? "FOund" : "Not Found"));
if (configFile.exists()) {
try {
LOGGER.info(String.format("Loading configuration file %s", configFileName));
PropertiesFactoryBean pfb = new PropertiesFactoryBean();
pfb.setFileEncoding("UTF-8");
pfb.setLocation(springResource);
pfb.afterPropertiesSet();
Properties properties = pfb.getObject();
PropertiesPropertySource externalConfig = new PropertiesPropertySource("externalConfig", properties);
((ConfigurableEnvironment) environment).getPropertySources().addFirst(externalConfig);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
} else {
LOGGER.info(String.format("Cannot find Configuration file %s... \n\n\n\n", configFileName));
}
}
}
}
Hope it helps.
In engineering data, it is common to see the #
symbol in the first column used to signal a comment.
I use the ostermiller CSV parsing library for Java to read and process such files. That library allows you to set the comment character. After the parse operation you get an array just containing the real data, no comments.
I had the same issue, and it turned out to be that MariaDB was set to allow only root to log in locally via the unix_socket plug-in, so clearing that setting allowed successfully logging in with the user specified on the command line, provided a correct password is entered, of course. See this answer on Ask Ubuntu
What worked for me is I:
Note about restarting Firefox: When I do start it very soon after closing it, it often has a file access problem, which requires me to delete places.sqlite and places.sqlite-journal in C:\WINDOWS\Application Data\Mozilla\Firefox\Profiles\n18091xv.default. This causes me to lose my history, plus bookmarks have to be restored from a backup each time this happens. I wait from five to ten minutes or more to avoid this hassle.
Running Firefox v3.5.1 on WinMe
If you have zgrep
you can use
zgrep -a string file.tar.gz
You might have pressed 0
(also used for insert, shortcut INS
) key, which is on the right side of your right scroll button. To solve the problem, just press it again or double click on 'overwrite'.
Technically you could do it with a straight TCP socket. I wouldn't recommend it however. I would highly recommend you use Apache HttpClient instead. In its simplest form:
GetMethod get = new GetMethod("http://httpcomponents.apache.org");
// execute method and handle any error responses.
...
InputStream in = get.getResponseBodyAsStream();
// Process the data from the input stream.
get.releaseConnection();
and here is a more complete example.
Java 9 offers a Matcher.replaceAll()
that accepts a replacement function:
resultString = regexMatcher.replaceAll(
m -> String.valueOf(Integer.parseInt(m.group()) * 3));
To list down the indices
curl -L localhost:9200/_cat/indices
9200
default port[change the port if using some other port]
You will likely find all indices starting with logstash-yyyy-mm-dd
format(logstash-*)
You can see all the indices and use
To delete the indices and data trigger following command.
curl -XDELETE localhost:9200/index_name
(Which will remove the data and indices both).
TLDR;
Transpile to es6
Transpile to es5
For the readers:
tsconfig.json:
{
"compilerOptions": {
"target": "es6",
"module": "system",
"moduleResolution": "node",
...
},
"exclude": [
"node_modules",
"jspm_packages"
]
}
Keep in mind uglifyjs does not support es6 at the moment. This could affect you making production bundles.
tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"module": "system",
"moduleResolution": "node",
...
},
"exclude": [
"node_modules",
"jspm_packages"
]
}
Install typings, then install es6-shim:
npm install typings --saveDev
typings install dt~es6-shim --global --save
If you go this route, you need to make sure that the typescript compiler can find the .d.ts file.
You have two options:
a. Make sure your tsconfig.json is at the same level as the typings folder.
b. Include a reference in your main.ts file where your angular2 application is bootstrapped.
Note: DO NOT use the exclude flag to exclude typings folder.
project
|-- src
|-- node_modules
|-- package.json
|-- typings
|-- tsconfig.json
As shown in other answers, this file is no longer included by Angular
main.ts:
/// <reference path="../../typings/globals/es6-shim/index.d.ts" />
This worked for me:
& 'D:\Server\PSTools\PsExec.exe' @('\\1.1.1.1', '-accepteula', '-d', '-i', $id, '-h', '-u', 'domain\user', '-p', 'password', '-w', 'C:\path\to\the\app', 'java', '-jar', 'app.jar')
Just put paths or connection strings in one array item and split the other things in one array item each.
There are a lot of other options here: https://social.technet.microsoft.com/wiki/contents/articles/7703.powershell-running-executables.aspx
Microsoft should make this way simpler and compatible with command prompt syntax.
Use the menu selection Navigate -> Test, or Ctrl+Shift+T (Shift+?+T on Mac). This will go to the existing test class, or offer to generate it for you through a little wizard.
Works for me. You probably want to multiplz it with 1000, since what you get are the seconds from 1970 and you have to pass the milliseconds from jan 1 1970
Open the file for 'append' rather than 'write'.
with open('file.txt', 'a') as file:
file.write('input')
I've tested various solutions with perfplot (a small project of mine) and found that
numpy.prod(lst)
is by far the fastest solution (if the list isn't very short).
Code to reproduce the plot:
import perfplot
import numpy
import math
from operator import mul
from functools import reduce
from itertools import accumulate
def reduce_lambda(lst):
return reduce(lambda x, y: x * y, lst)
def reduce_mul(lst):
return reduce(mul, lst)
def forloop(lst):
r = 1
for x in lst:
r *= x
return r
def numpy_prod(lst):
return numpy.prod(lst)
def math_prod(lst):
return math.prod(lst)
def itertools_accumulate(lst):
for value in accumulate(lst, mul):
pass
return value
perfplot.show(
setup=numpy.random.rand,
kernels=[reduce_lambda, reduce_mul, forloop, numpy_prod, itertools_accumulate, math_prod],
n_range=[2 ** k for k in range(15)],
xlabel="len(a)",
logx=True,
logy=True,
)
What you are looking for is this:
SHOW VARIABLES;
You can modify it further like any query:
SHOW VARIABLES LIKE '%max%';
Macintosh HD/Library/WebServer/Documents
Macintosh HD is the name of your HD
If you can't find it: Open Finder > click "Go" at the very top > Computer > Your HD should be there. You can drag and drop the HD to favorites on the left.
Below is a simple way of accessing the response as a String using Apache HTTP Client library.
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
//...
HttpGet get;
HttpClient httpClient;
// initialize variables above
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(get, responseHandler);
I was getting this error:
The type com.ibm.portal.state.exceptions.StateException cannot be resolved. It is indirectly referenced from required .class files
Doing the following fixed it for me:
Properties -> Java build path -> Libraries -> Server Library[wps.base.v61]unbound -> Websphere Portal v6.1 on WAS 7 -> Finish -> OK
Same here. I had this error when running an import command from terminal without activating python3 shell through manage.py in a django project (yes, I am a newbie yet). As one must expect, activating shell allowed the command to be interpreted correctly.
./manage.py shell
and only then
>>> from django.contrib.sites.models import Site
You should add the no cache directive to your header:
<?php
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' );
?>
Without time than try like this:
TimeSpan ts = new TimeSpan(23, 59, 59);
toDate = toDate.Add(ts);
List<AuditLog> resultLogs =
_dbContext.AuditLogs
.Where(al => al.Log_Date >= fromDate && al.Log_Date <= toDate)
.ToList();
return resultLogs;
I came here because I was trying to use ifconfig on the container to find its IPAaddress and there was no ifconfig. If you really need ifconfig on the container go with @vishnu-narayanan answer above, however you may be able to get the information you need by using docker inspect on the host:
docker inspect <containerid>
There is lots of good stuff in the output including IPAddress of container:
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "12345FAKEID",
"EndpointID": "12345FAKEENDPOINTID",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.3",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "01:02:03:04:05:06",
"DriverOpts": null
}
}
You may also be interested in the write-up from Sun, as part of the standard JSSE documentation:
http://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#Stores
Typically, the trust store is used to store only public keys, for verification purposes, such as with X.509 authentication. For manageability purposes, it's quite common for admins or developers to simply conflate the two into a single store.
Slightly modified answer of @Ty Le:
no changes in files were required for me - I had a branch named 'Feature/...' and while pushing upstream I changed the title to 'feature/...' (the case of the first letter was changed to the lower one).
i solved this by following
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
datePickerDialog = new DatePickerDialog(getActivity(), this, year, month, day);
datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis());
hope it will help you
After mid-2018:
1:) Invite @getidsbot or @RawDataBot
to your group and get your group id from the chat id field.
Message
+ message_id: 338
+ from
? + id: *****
? + is_bot: false
? + first_name: ???
? + username: ******
? + language_code: en
+ chat
? + id: -1001118554477 // This is Your Group id
? + title: Test Group
? + type: supergroup
+ date: 1544948900
+ text: A
2:) use an unofficial Messenger like Plus Messenger and see your group id in group/channel info.
Before mid-2018: (don't Use)
1: Goto (https://web.telegram.org)
2: Goto your Gorup and Find your link of Gorup(https://web.telegram.org/#/im?p=g154513121)
3: Copy That number after g and put a (-) Before That -154513121
4: Send Your Message to Gorup
bot.sendMessage(-154513121, "Hi")
I Tested Now and Work like a Charm
Indexing a list is done using double bracket, i.e. hypo_list[[1]]
(e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table
does not return a table but a dataframe (see value section in ?read.table
). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.
Note: In R, the index for the first entry is a 1
(not 0
like in some other languages).
Dataframes
l <- list(anscombe, iris) # put dfs in list
l[[1]] # returns anscombe dataframe
anscombe[1:2, 2] # access first two rows and second column of dataset
[1] 10 8
l[[1]][1:2, 2] # the same but selecting the dataframe from the list first
[1] 10 8
Table objects
tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2) # put tables in a list
tbl1[1:2] # access first two elements of table 1
Now with the list
l[[1]] # access first table from the list
1 2 3 4 5
9 11 12 9 9
l[[1]][1:2] # access first two elements in first table
1 2
9 11
Yes, here you can use LIMIT
.
You can try it by the below query:
SELECT * FROM employee_list SORT BY salary DESC LIMIT 2
If the suggested solutions above didn't solve your issue (as for me), this could also help:
My problem was that I was returning a json string in my response using Springs @ResponseBody
. If you're doing this as well this might help.
Add the following bean to your dispatcher servlet.
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
(Found here: http://forum.spring.io/forum/spring-projects/web/74209-responsebody-and-utf-8)
On a semi-related note, if you want to start a process that has more privileges than your current process (say, launching an admin app, which requires Administrator rights, from the main app running as a normal user), you can't do so using CreateProcess() on Vista since it won't trigger the UAC dialog (assuming it is enabled). The UAC dialog is triggered when using ShellExecute(), though.
I had a similar problem with getting the COUNTA formula to count non-blank cells, it was counting all of them (even the blank one's as non-blank), I tried =CODE() but they had no spaces or new lines.
I found that when I clicked in the cell and then clicked out of it then the formula would count the cell. I had thousands of cells so could not do this manually. I wrote this VBA statement to literally check all the cells and if they were blank then to make them blank. Ignore the pointlessness of this macro and trust me that it actually worked by forcing Excel to recognize the empty cells as actually being empty.
'This checks all the cells in a table so will need to be changed if you're using a range
Sub CreateBlanks()
Dim clientTable As ListObject
Dim selectedCell As Range
Set clientTable = Worksheets("Client Table").ListObjects("ClientTable")
For Each selectedCell In clientTable.DataBodyRange.Cells
If selectedCell = "" Then
selectedCell = ""
End If
Next selectedCell
End Sub
MATLAB is a fantastic tool for
You can really play with, visualize and test your ideas on a data set very effectively. It should not be regarded as an alternative to other software languages used for product development. I highly recommend it for the above tasks, though it is expensive - free alternatives like Octave and Python are catching up.
"foo is bar".replace(/ /g, '')
Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000
or Access-Control-Allow-Origin: *
on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true
on the POST response as well.
Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept
to match the requested header.
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
String header = dataGridView1.Columns[i].HeaderText;
//String cellText = row.Cells[i].Text;
DataGridViewColumn column = dataGridView1.Columns[i]; // column[1] selects the required column
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; // sets the AutoSizeMode of column defined in previous line
int colWidth = column.Width; // store columns width after auto resize
colWidth += 50; // add 30 pixels to what 'colWidth' already is
this.dataGridView1.Columns[i].Width = colWidth; // set the columns width to the value stored in 'colWidth'
}
}
The answers above are still using the old Python 3.4 style coroutines. Here is what you would write if you got Python 3.5+.
aiohttp
supports http proxy now
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
'http://python.org',
'https://google.com',
'http://yifei.me'
]
tasks = []
async with aiohttp.ClientSession() as session:
for url in urls:
tasks.append(fetch(session, url))
htmls = await asyncio.gather(*tasks)
for html in htmls:
print(html[:100])
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
I'm not familiar with paramiko, but this may work:
ssh_stdin.write('input value')
ssh_stdin.flush()
For information on stdin:
http://docs.python.org/library/sys.html?highlight=stdin#sys.stdin
function removeLocationHash(){
var noHashURL = window.location.href.replace(/#.*$/, '');
window.history.replaceState('', document.title, noHashURL)
}
window.addEventListener("load", function(){
removeLocationHash();
});
After reading several suggestions here and combining the ideas, for me following changes in /etc/ImageMagick-6/policy.xml were necessary:
<policy domain="coder" rights="read|write" pattern="PDF" />
... rights="none" did not help. ...pattern="LABEL" was not neccessary. Although I do not work with big png files (only ~1 Mb) some changes in memory limits were also necessary:
<policy domain="resource" name="memory" value="2GiB"/>
(instead of 256Mib), and
<policy domain="resource" name="area" value="2GB"/>
(instead of 128 MB)
Its just that you need multiple When
for a single case to behave it like if.. Elseif else..
Case when 1=1 //if
Then
When 1=1 //else if
Then....
When ..... //else if
Then
Else //else
.......
End
nslookup google.com
is the easiest way. Works on Linux and Windows.
If your issue is that your DNS server is not returning a response for google.com, use a different DNS server, such as a public one. For instance, you could do:
nslookup
>server 8.8.8.8
>google.com
For a more thorough solution to getting around annoying Internet filters, look into using Tor.
In my case DockerFile contained the image name in mixed case instead of lower case.
Earlier line in my DockerFile
FROM CentOs
and when I changed above to FROM centos
, it worked smoothly.
Check the character set of both projects in Configuration Properties ? General ? Character Set.
My UnitTest project was using the default character set Multi-Byte while my libraries were in Unicode.
My function was using a TCHAR as a parameter.
As a result, in my library my TCHAR was transformed into a WCHAR, but it was a char* in my UnitTest: the symbol was different because the parameters were really not the same in the end.
You can resize images using CSS just fine if you're modifying an image tag:
<img src="example.png" style="width:2em; height:3em;" />
You cannot scale a background-image property using CSS2, although you can try the CSS3 property background-size
.
What you can do, on the other hand, is to nest an image inside a span. See the answer to this question: Stretch and scale CSS background
import cookielib
import urllib
import urllib2
url = 'http://www.someserver.com/auth/login'
values = {'email-email' : '[email protected]',
'password-clear' : 'Combination',
'password-password' : 'mypassword' }
data = urllib.urlencode(values)
cookies = cookielib.CookieJar()
opener = urllib2.build_opener(
urllib2.HTTPRedirectHandler(),
urllib2.HTTPHandler(debuglevel=0),
urllib2.HTTPSHandler(debuglevel=0),
urllib2.HTTPCookieProcessor(cookies))
response = opener.open(url, data)
the_page = response.read()
http_headers = response.info()
# The login cookies should be contained in the cookies variable
For more information visit: https://docs.python.org/2/library/urllib2.html
When you want keep colorful icon - Workaround
Add pixel with slightly different color into icon.
In my case a have black icon with shades and light. When added dark blue pixel it works.
Just for the most popular linux Ubuntu
& it's bash
:
Check which shell are you using? Mostly below works, else see this:
echo $0
If above prints bash
, then below will work:
printf "hello with no new line printed at end"
OR
echo -n "hello with no new line printed at end"
Here is an example of how you can do it in Spring 4.0+
application.properties
content:some.key=yes,no,cancel
@Autowire
private Environment env;
...
String[] springRocks = env.getProperty("some.key", String[].class);
//Response being your httpwebresponse
Dim str_StatusCode as String = CInt(Response.StatusCode)
Console.Writeline(str_StatusCode)
You want to get an element from an empty array. That's why the Size: 0
from the exception
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
So you cant do lstpp.get(0)
until you fill the array.
@zhutoulala -- FWIW your links worked for me with Hadoop 2.4.0 with one exception I had to tell maven not to build the javadocs. I also used the patch in the first link for 2.4.0 and it worked fine. Here's the maven command I had to issue
mvn package -Dmaven.javadoc.skip=true -Pdist,native -DskipTests -Dtar
After building this and moving the libraries, don't forget to update hadoop-env.sh :)
Thought this might help someone who ran into the same roadblocks as me
Or you can use a for-each loop:
Collection<X> items = ...;
X last = null;
for (X x : items) last = x;
Check the encoding in which you are generating the file, to make excel display the file correctly you must use the system default codepage.
Wich language are you using? if it's .Net you only need to use Encoding.Default while generating the file.
In this scenario, I prefer to create new branches for each issue. I use a prefix temp/ so I know that I can delete these branches later.
git checkout -b temp/bug1
Stage the files that fix bug1 and commit them.
git checkout -b temp/bug2
You can then cherry pick the commits from the respective branches as require and submit a pull request.
Assume B and C are overriding inherited method and their own implementation. Now D inherits both B & C using multiple inheritance. D should inherit the overridden method.The Question is which overridden method will be used? Will it be from B or C? Here we have an ambiguity. To exclude such situation multiple inheritance was not used in Java.
Yes, I couldn't see how to use 'default' in the migration generator command either but was able to specify a default value for a new string column as follows by amending the generated migration file before applying "rake db:migrate":
class AddColumnToWidgets < ActiveRecord::Migration
def change
add_column :widgets, :colour, :string, default: 'red'
end
end
This adds a new column called 'colour' to my 'Widget' model and sets the default 'colour' of new widgets to 'red'.
You can use robocopy to copy files with an archive flag and reset the attribute. Use /M command line, this is my backup script with few extra tricks.
This script needs NirCmd tool to keep mouse moving so that my machine won't fall into sleep. Script is using a lockfile to tell when backup script is completed and mousemove.bat script is closed. You may leave this part out.
Another is 7-Zip tool for splitting virtualbox files smaller than 4GB files, my destination folder is still FAT32 so this is mandatory. I should use NTFS disk but haven't converted backup disks yet.
backup-robocopy.bat
@REM https://technet.microsoft.com/en-us/library/cc733145.aspx
@REM http://www.skonet.com/articles_archive/robocopy_job_template.aspx
set basedir=%~dp0
del /Q %basedir%backup-robocopy-log.txt
set dt=%date%_%time:~0,8%
echo "%dt% robocopy started" > %basedir%backup-robocopy-lock.txt
start "Keep system awake" /MIN /LOW cmd.exe /C %basedir%backup-robocopy-movemouse.bat
set dest=E:\backup
call :BACKUP "Program Files\MariaDB 5.5\data"
call :BACKUP "projects"
call :BACKUP "Users\Myname"
:SPLIT
@REM Split +4GB file to multiple files to support FAT32 destination disk,
@REM splitted files must be stored outside of the robocopy destination folder.
set srcfile=C:\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile=%dest%\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile2=%dest%\non-robocopy\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
IF NOT EXIST "%dstfile%" (
IF NOT EXIST "%dstfile2%.7z.001" attrib +A "%srcfile%"
dir /b /aa "%srcfile%" && (
del /Q "%dstfile2%.7z.*"
c:\apps\commands\7za.exe -mx0 -v4000m u "%dstfile2%.7z" "%srcfile%"
attrib -A "%srcfile%"
@set dt=%date%_%time:~0,8%
@echo %dt% Splitted %srcfile% >> %basedir%backup-robocopy-log.txt
)
)
del /Q %basedir%backup-robocopy-lock.txt
GOTO :END
:BACKUP
TITLE Backup %~1
robocopy.exe "c:\%~1" "%dest%\%~1" /JOB:%basedir%backup-robocopy-job.rcj
GOTO :EOF
:END
@set dt=%date%_%time:~0,8%
@echo %dt% robocopy completed >> %basedir%backup-robocopy-log.txt
@echo %dt% robocopy completed
@pause
backup-robocopy-job.rcj
:: Robocopy Job Parameters
:: robocopy.exe "c:\projects" "E:\backup\projects" /JOB:backup-robocopy-job.rcj
:: Source Directory (this is given in command line)
::/SD:c:\examplefolder
:: Destination Directory (this is given in command line)
::/DD:E:\backup\examplefolder
:: Include files matching these names
/IF
*.*
/M :: copy only files with the Archive attribute and reset it.
/XJD :: eXclude Junction points for Directories.
:: Exclude Directories
/XD
C:\projects\bak
C:\projects\old
C:\project\tomcat\logs
C:\project\tomcat\work
C:\Users\Myname\.eclipse
C:\Users\Myname\.m2
C:\Users\Myname\.thumbnails
C:\Users\Myname\AppData
C:\Users\Myname\Favorites
C:\Users\Myname\Links
C:\Users\Myname\Saved Games
C:\Users\Myname\Searches
:: Exclude files matching these names
/XF
C:\Users\Myname\ntuser.dat
*.~bpl
:: Exclude files with any of the given Attributes set
:: S=System, H=Hidden
/XA:SH
:: Copy options
/S :: copy Subdirectories, but not empty ones.
/E :: copy subdirectories, including Empty ones.
/COPY:DAT :: what to COPY for files (default is /COPY:DAT).
/DCOPY:T :: COPY Directory Timestamps.
/PURGE :: delete dest files/dirs that no longer exist in source.
:: Retry Options
/R:0 :: number of Retries on failed copies: default 1 million.
/W:1 :: Wait time between retries: default is 30 seconds.
:: Logging Options (LOG+ append)
/NDL :: No Directory List - don't log directory names.
/NP :: No Progress - don't display percentage copied.
/TEE :: output to console window, as well as the log file.
/LOG+:c:\apps\commands\backup-robocopy-log.txt :: append to logfile
backup-robocopy-movemouse.bat
@echo off
@REM Move mouse to prevent maching from sleeping
@rem while running a backup script
echo Keep system awake while robocopy is running,
echo this script moves a mouse once in a while.
set basedir=%~dp0
set IDX=0
:LOOP
IF NOT EXIST "%basedir%backup-robocopy-lock.txt" GOTO :EOF
SET /A IDX=%IDX% + 1
IF "%IDX%"=="240" (
SET IDX=0
echo Move mouse to keep system awake
c:\apps\commands\nircmdc.exe sendmouse move 5 5
c:\apps\commands\nircmdc.exe sendmouse move -5 -5
)
c:\apps\commands\nircmdc.exe wait 1000
GOTO :LOOP
// you can send full url here
function getExtension(filename) {
return filename.split('.').pop();
}
If you are using express please add the following line when configuring middleware (bodyParser)
app.use(express.bodyParser({ keepExtensions: true}));
Try:
this.deleteDatabase(path);
or
context.deleteDatabase(path);
One way, using regular expressions:
>>> s = "how much for the maple syrup? $20.99? That's ridiculous!!!"
>>> re.sub(r'[^\w]', ' ', s)
'how much for the maple syrup 20 99 That s ridiculous '
\w
will match alphanumeric characters and underscores
[^\w]
will match anything that's not alphanumeric or underscore
First Way:
You didn't create the directory. Also, you are passing an absolute path to openFileOutput()
, which is wrong.
Second way:
You created an empty file with the desired name, which then prevented you from creating the directory. Also, you are passing an absolute path to openFileOutput()
, which is wrong.
Third way:
You didn't create the directory. Also, you are passing an absolute path to openFileOutput()
, which is wrong.
Fourth Way:
You didn't create the directory. Also, you are passing an absolute path to openFileOutput()
, which is wrong.
Fifth way:
You didn't create the directory. Also, you are passing an absolute path to openFileOutput()
, which is wrong.
Correct way:
File
for your desired directory (e.g., File path=new File(getFilesDir(),"myfolder");
)mkdirs()
on that File
to create the directory if it does not existFile
for the output file (e.g., File mypath=new File(path,"myfile.txt");
)File
(e.g., using new BufferedWriter(new FileWriter(mypath))
)Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines
Depending on where you look, you'll get slightly different answers. I've read about the subject a lot, and here's my distillation; again, these are slightly wooly and others may disagree.
Unit Tests
Tests the smallest unit of functionality, typically a method/function (e.g. given a class with a particular state, calling x method on the class should cause y to happen). Unit tests should be focussed on one particular feature (e.g., calling the pop method when the stack is empty should throw an InvalidOperationException
). Everything it touches should be done in memory; this means that the test code and the code under test shouldn't:
Any kind of dependency that is slow / hard to understand / initialise / manipulate should be stubbed/mocked/whatevered using the appropriate techniques so you can focus on what the unit of code is doing, not what its dependencies do.
In short, unit tests are as simple as possible, easy to debug, reliable (due to reduced external factors), fast to execute and help to prove that the smallest building blocks of your program function as intended before they're put together. The caveat is that, although you can prove they work perfectly in isolation, the units of code may blow up when combined which brings us to ...
Integration Tests
Integration tests build on unit tests by combining the units of code and testing that the resulting combination functions correctly. This can be either the innards of one system, or combining multiple systems together to do something useful. Also, another thing that differentiates integration tests from unit tests is the environment. Integration tests can and will use threads, access the database or do whatever is required to ensure that all of the code and the different environment changes will work correctly.
If you've built some serialization code and unit tested its innards without touching the disk, how do you know that it'll work when you are loading and saving to disk? Maybe you forgot to flush and dispose filestreams. Maybe your file permissions are incorrect and you've tested the innards using in memory streams. The only way to find out for sure is to test it 'for real' using an environment that is closest to production.
The main advantage is that they will find bugs that unit tests can't such as wiring bugs (e.g. an instance of class A unexpectedly receives a null instance of B) and environment bugs (it runs fine on my single-CPU machine, but my colleague's 4 core machine can't pass the tests). The main disadvantage is that integration tests touch more code, are less reliable, failures are harder to diagnose and the tests are harder to maintain.
Also, integration tests don't necessarily prove that a complete feature works. The user may not care about the internal details of my programs, but I do!
Functional Tests
Functional tests check a particular feature for correctness by comparing the results for a given input against the specification. Functional tests don't concern themselves with intermediate results or side-effects, just the result (they don't care that after doing x, object y has state z). They are written to test part of the specification such as, "calling function Square(x) with the argument of 2 returns 4".
Acceptance Tests
Acceptance testing seems to be split into two types:
Standard acceptance testing involves performing tests on the full system (e.g. using your web page via a web browser) to see whether the application's functionality satisfies the specification. E.g. "clicking a zoom icon should enlarge the document view by 25%." There is no real continuum of results, just a pass or fail outcome.
The advantage is that the tests are described in plain English and ensures the software, as a whole, is feature complete. The disadvantage is that you've moved another level up the testing pyramid. Acceptance tests touch mountains of code, so tracking down a failure can be tricky.
Also, in agile software development, user acceptance testing involves creating tests to mirror the user stories created by/for the software's customer during development. If the tests pass, it means the software should meet the customer's requirements and the stories can be considered complete. An acceptance test suite is basically an executable specification written in a domain specific language that describes the tests in the language used by the users of the system.
Conclusion
They're all complementary. Sometimes it's advantageous to focus on one type or to eschew them entirely. The main difference for me is that some of the tests look at things from a programmer's perspective, whereas others use a customer/end user focus.
You reference a Linux distribution, so you need to install the readline development libraries
On Debian based platforms, like Ubuntu, you can run:
sudo apt-get install libreadline-dev
and that should install the correct headers in the correct places,.
If you use a platform with yum
, like SUSE, then the command should be:
yum install readline-devel
You don't need those imports. The only thing you need in your urls.py (to start) is:
from django.conf.urls.defaults import *
# This two if you want to enable the Django Admin: (recommended)
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
# ... your url patterns
)
NOTE: This solution was intended for Django <1.6. This was actually the code generated by Django itself. For newer version, see Jacob Hume's answer.
We can also use the String constructor. According to this benchmark it's the fastest way to convert a Number to String in Firefox 58 even though it's slower than
" + num
in the popular browser Google Chrome.
This code should work for you:
Comment.find(:all, :conditions => {:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day})
For more info have a look at Time calculations
Note: This code is deprecated. Use the code from the answer if you are using Rails 3.1/3.2
Take a look at "using WCF Services with PHP". It explains the basics of what you need.
As a theory summary:
WCF or Windows Communication Foundation is a technology that allow to define services abstracted from the way - the underlying communication method - they'll be invoked.
The idea is that you define a contract about what the service does and what the service offers and also define another contract about which communication method is used to actually consume the service, be it TCP, HTTP or SOAP.
You have the first part of the article here, explaining how to create a very basic WCF Service.
More resources:
Aslo take a look to NuSOAP. If you now NuSphere this is a toolkit to let you connect from PHP to an WCF service.
An iOS/Android pure javascript react-native component that renders your HTML into 100% native views. It's made to be extremely customizable and easy to use and aims at being able to render anything you throw at it.
use above library to improve your app performance level and easy to use.
Install
npm install react-native-render-html --save or yarn add react-native-render-html
Basic usage
import React, { Component } from 'react';
import { ScrollView, Dimensions } from 'react-native';
import HTML from 'react-native-render-html';
const htmlContent = `
<h1>This HTML snippet is now rendered with native components !</h1>
<h2>Enjoy a webview-free and blazing fast application</h2>
<img src="https://i.imgur.com/dHLmxfO.jpg?2" />
<em style="textAlign: center;">Look at how happy this native cat is</em>
`;
export default class Demo extends Component {
render () {
return (
<ScrollView style={{ flex: 1 }}>
<HTML html={htmlContent} imagesMaxWidth={Dimensions.get('window').width} />
</ScrollView>
);
}
}
you may user it's different different types of props (see above link) for the designing and customizable also using below link refer.
You can use the DataFrame apply
method:
order_df['Value'] = order_df.apply(lambda row: (row['Prices']*row['Amount']
if row['Action']=='Sell'
else -row['Prices']*row['Amount']),
axis=1)
It is usually faster to use these methods rather than over for loops.
The port you are listening to is already being listened by another process.
When I faced to this error I killed the process using Windows PowerShell (because I used Windows)
ps
and then you can get list of processesStop-process <Id>
I think that it is help for windows usersI was solving same problem recently. I was designing a write cmdlet for my Subtitle module. I had six different user stories:
I end up in the big frustration because I though that 4 parameters will be enough. Like most of the times, the frustration was pointless because it was my fault. I didn't know enough about parameter sets.
After some research in documentation, I realized where is the problem. With knowledge how the parameter sets should be used, I developed a general and simple approach how to solve this problem. A pencil and a sheet of paper is required but a spreadsheet editor is better:
Example:
The practical example could be seen over here.
BTW: The parameter uniqueness within parameter sets is the reason why the ParameterSetName
property doesn't support [String[]]
. It doesn't really make any sense.
Check the apache User and Group setting in the httpd.conf. It should default to apache on AMI/RedHat or www-data on Debian.
grep '^Group\|^User' /etc/httpd/conf/httpd.conf
Then add the apache user to the group setting of your site's root directory.
sudo usermod -a -G <your-site-root-dir-group> apache
Use simple and easy code
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let myCell = tableView.dequeueReusableCellWithIdentifier("mannaCustumCell") as! CustomCell
let heightForCell = myCell.bounds.size.height;
return heightForCell;
}
I used the timezone-js package.
var timezoneJS = require('timezone-js');
var tzdata = require('tzdata');
createDate(dateObj) {
if ( dateObj == null ) {
return null;
}
var nativeTimezoneOffset = new Date().getTimezoneOffset();
var offset = this.getTimeZoneOffset();
// use the native Date object if the timezone matches
if ( offset == -1 * nativeTimezoneOffset ) {
return dateObj;
}
this.loadTimeZones();
// FIXME: it would be better if timezoneJS.Date was an instanceof of Date
// tried jquery $.extend
// added hack to Fiterpickr to look for Dater.getTime instead of "d instanceof Date"
return new timezoneJS.Date(dateObj,this.getTimeZoneName());
},
1- Comment out bind 127.0.0.1
2- set requirepass yourpassword
then check if the firewall blocked your port
iptables -L -n
service iptables stop
It gets very simple if you think it as two vectors, one from point P1 to P2 and one from P1 to P3
so:
a = (p1.x - p2.x, p1.y - p2.y)
b = (p1.x - p3.x, p1.y - p3.y)
You can then invert the dot product formula:
to get the angle:
Remember that just means: a1*b1 + a2*b2 (just 2 dimensions here...)
Rails 4 has been updated, so the change method can be used in the migration to drop a column and the migration will successfully rollback. Please read the following warning for Rails 3 applications:
Rails 3 Warning
Please note that when you use this command:
rails generate migration RemoveFieldNameFromTableName field_name:datatype
The generated migration will look something like this:
def up
remove_column :table_name, :field_name
end
def down
add_column :table_name, :field_name, :datatype
end
Make sure to not use the change method when removing columns from a database table (example of what you don't want in the migration file in Rails 3 apps):
def change
remove_column :table_name, :field_name
end
The change method in Rails 3 is not smart when it comes to remove_column, so you will not be able to rollback this migration.
From the javadoc of java.rmi.registry.Registry
Therefore, a registry's remote object implementation is typically exported with a well-known address, such as with a well-known
ObjID
and TCP port number (default is1099
).
See more in the javadoc of java.rmi.registry.LocateRegistry
.
When you have three columns : first_name, last_name, mid_name:
SELECT CASE
WHEN mid_name IS NULL OR TRIM(mid_name) ='' THEN
CONCAT_WS( " ", first_name, last_name )
ELSE
CONCAT_WS( " ", first_name, mid_name, last_name )
END
FROM USER;
You can use the with_entities()
method to restrict which columns you'd like to return in the result. (documentation)
result = SomeModel.query.with_entities(SomeModel.col1, SomeModel.col2)
Depending on your requirements, you may also find deferreds useful. They allow you to return the full object but restrict the columns that come over the wire.
It's easy. Here is the full code.
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("Your URL")
driver.set_window_size(480, 320)
Make sure chrome driver is in your system path.
Many people call this a Protocol Relative URL.
You cannot get a generic parameter from a variable. But you can from a method or field declaration:
Method method = getClass().getDeclaredMethod("chill", List.class);
Type[] params = method.getGenericParameterTypes();
ParameterizedType firstParam = (ParameterizedType) params[0];
Type[] paramsOfFirstGeneric = firstParam.getActualTypeArguments();
If you are looking for a direct approach and using a local
File in that case.
Try
<div
style={{ background-image: 'url(' + Image + ')', background-size: 'auto' }}
/>
This is the case of JS
with inline styling where Image
is a local file that you must have imported with a path.
Another NS lookup utility that can be used for reversed lookup is dig
with the -x
option:
$ dig -x 72.51.34.34
; <<>> DiG 9.9.2-P1 <<>> -x 72.51.34.34
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 12770
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1460
;; QUESTION SECTION:
;34.34.51.72.in-addr.arpa. IN PTR
;; ANSWER SECTION:
34.34.51.72.in-addr.arpa. 42652 IN PTR sb.lwn.net.
;; Query time: 4 msec
;; SERVER: 192.168.178.1#53(192.168.178.1)
;; WHEN: Fri Jan 25 21:23:40 2013
;; MSG SIZE rcvd: 77
or
$ dig -x 127.0.0.1
; <<>> DiG 9.9.2-P1 <<>> -x 127.0.0.1
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 11689
;; flags: qr aa ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;1.0.0.127.in-addr.arpa. IN PTR
;; ANSWER SECTION:
1.0.0.127.in-addr.arpa. 10 IN PTR localhost.
;; Query time: 2 msec
;; SERVER: 192.168.178.1#53(192.168.178.1)
;; WHEN: Fri Jan 25 21:23:49 2013
;; MSG SIZE rcvd: 63
Quoting from the dig manpage:
Reverse lookups -- mapping addresses to names -- are simplified by the -x option. addr is an IPv4 address in dotted-decimal notation, or a colon-delimited IPv6 address. When this option is used, there is no need to provide the name, class and type arguments. dig automatically performs a lookup for a name like 11.12.13.10.in-addr.arpa and sets the query type and class to PTR and IN respectively.
Change
@RequestMapping(value = "/test", method = RequestMethod.POST)
To
@RequestMapping(value = "/test", method = RequestMethod.GET)
There are potential problems if you write your own recursive implementation or the iterative equivalent with stack. See this example:
dic = {}
dic["key1"] = {}
dic["key1"]["key1.1"] = "value1"
dic["key2"] = {}
dic["key2"]["key2.1"] = "value2"
dic["key2"]["key2.2"] = dic["key1"]
dic["key2"]["key2.3"] = dic
In the normal sense, nested dictionary will be a n-nary tree like data structure. But the definition doesn't exclude the possibility of a cross edge or even a back edge (thus no longer a tree). For instance, here key2.2 holds to the dictionary from key1, key2.3 points to the entire dictionary(back edge/cycle). When there is a back edge(cycle), the stack/recursion will run infinitely.
root<-------back edge
/ \ |
_key1 __key2__ |
/ / \ \ |
|->key1.1 key2.1 key2.2 key2.3
| / | |
| value1 value2 |
| |
cross edge----------|
If you print this dictionary with this implementation from Scharron
def myprint(d):
for k, v in d.items():
if isinstance(v, dict):
myprint(v)
else:
print "{0} : {1}".format(k, v)
You would see this error:
RuntimeError: maximum recursion depth exceeded while calling a Python object
The same goes with the implementation from senderle.
Similarly, you get an infinite loop with this implementation from Fred Foo:
def myprint(d):
stack = list(d.items())
while stack:
k, v = stack.pop()
if isinstance(v, dict):
stack.extend(v.items())
else:
print("%s: %s" % (k, v))
However, Python actually detects cycles in nested dictionary:
print dic
{'key2': {'key2.1': 'value2', 'key2.3': {...},
'key2.2': {'key1.1': 'value1'}}, 'key1': {'key1.1': 'value1'}}
"{...}" is where a cycle is detected.
As requested by Moondra this is a way to avoid cycles (DFS):
def myprint(d):
stack = list(d.items())
visited = set()
while stack:
k, v = stack.pop()
if isinstance(v, dict):
if k not in visited:
stack.extend(v.items())
else:
print("%s: %s" % (k, v))
visited.add(k)
Hash code is used for hash-based collections like Dictionary, Hashtable, HashSet etc. The purpose of this code is to very quickly pre-sort specific object by putting it into specific group (bucket). This pre-sorting helps tremendously in finding this object when you need to retrieve it back from hash-collection because code has to search for your object in just one bucket instead of in all objects it contains. The better distribution of hash codes (better uniqueness) the faster retrieval. In ideal situation where each object has a unique hash code, finding it is an O(1) operation. In most cases it approaches O(1).
When you try to set text in Edittext
or textview
you
should pass only String format.
dateTime.setText(app.getTotalDl());
to
dateTime.setText(String.valueOf(app.getTotalDl()));
>>> class new_class():
... def __init__(self, number):
... self.multi = int(number) * 2
... self.str = str(number)
...
>>> a = new_class(2)
>>> a.__dict__
{'multi': 4, 'str': '2'}
>>> a.__dict__.keys()
dict_keys(['multi', 'str'])
You may also find pprint helpful.
if you want to set value than you can do the same in some function on click or on some event fire.
also you can get value using ViewChild
using local variable like this
<input type='text' id='loginInput' #abc/>
and get value like this
this.abc.nativeElement.value
okay got it , you have to use ngAfterViewInit
method of angualr2 for the same like this
ngAfterViewInit(){
document.getElementById('loginInput').value = '123344565';
}
ngAfterViewInit
will not throw any error because it will render after template loading
See answer from Gary Makin. And you need change the format or data. Because the data that you have do not fit under the chosen format. For example this code works correct:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let dateObj = dateFormatter.dateFromString("10 10 2001")
print("Dateobj: \(dateObj)")
Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction()
function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!
You are supposed to download the jar files that contain these libraries. Libraries may be used by adding them to the classpath.
For Commons Net you need to download the binary files from Commons Net download page. Then you have to extract the file and add the commons-net-2-2.jar file to some location where you can access it from your application e.g. to /lib.
If you're running your application from the command-line you'll have to define the classpath in the java command: java -cp .;lib/commons-net-2-2.jar myapp
. More info about how to set the classpath can be found from Oracle documentation. You must specify all directories and jar files you'll need in the classpath excluding those implicitely provided by the Java runtime. Notice that there is '.' in the classpath, it is used to include the current directory in case your compiled class is located in the current directory.
For more advanced reading, you might want to read about how to define the classpath for your own jar files, or the directory structure of a war file when you're creating a web application.
If you are using an IDE, such as Eclipse, you have to remember to add the library to your build path before the IDE will recognize it and allow you to use the library.
Make sure you have a jdk setup. To do this, create a new project and then go to file -> project structure. From there you can add a new jdk. Once that is setup, go back to your gradle project and you should have a jdk to select in the 'Gradle JVM' field.
OP's question is windows related and I could not use others without going to the directory or even running file in Notepad++ as administrator did not work.. So had to go this route:
C:\Program Files (x86)\Git\etc>git config --global core.autocrlf false
Using Backtick
Backticks are commonly used for multi-line strings or when you want to interpolate an expression within your string
let title = 'John';_x000D_
let address = 'address';_x000D_
let address2 = 'address2222';_x000D_
let address3 = 'address33333';_x000D_
let address4 = 'address44444';_x000D_
document.getElementById("address_box").innerText = `${title} _x000D_
${address}_x000D_
${address2}_x000D_
${address3} _x000D_
${address4}`;
_x000D_
<div id="address_box">_x000D_
</div>
_x000D_
What is a unique index?
A unique index on a column is an index on that column that also enforces the constraint that you cannot have two equal values in that column in two different rows. Example:
CREATE TABLE table1 (foo int, bar int); CREATE UNIQUE INDEX ux_table1_foo ON table1(foo); -- Create unique index on foo. INSERT INTO table1 (foo, bar) VALUES (1, 2); -- OK INSERT INTO table1 (foo, bar) VALUES (2, 2); -- OK INSERT INTO table1 (foo, bar) VALUES (3, 1); -- OK INSERT INTO table1 (foo, bar) VALUES (1, 4); -- Fails! Duplicate entry '1' for key 'ux_table1_foo'
The last insert fails because it violates the unique index on column foo
when it tries to insert the value 1 into this column for a second time.
In MySQL a unique constraint allows multiple NULLs.
It is possible to make a unique index on mutiple columns.
Primary key versus unique index
Things that are the same:
Things that are different:
using static System.Console;
namespace IntToBits
{
class Program
{
static void Main()
{
while (true)
{
string s = Console.ReadLine();
Clear();
uint i;
bool b = UInt32.TryParse(s, out i);
if (b) IntPrinter(i);
}
}
static void IntPrinter(uint i)
{
int[] iarr = new int [32];
Write("[");
for (int j = 0; j < 32; j++)
{
uint tmp = i & (uint)Math.Pow(2, j);
iarr[j] = (int)(tmp >> j);
}
for (int j = 32; j > 0; j--)
{
if(j%8==0 && j != 32)Write("|");
if(j%4==0 && j%8 !=0) Write("'");
Write(iarr[j-1]);
}
WriteLine("]");
}
}
}```
For whose have a problem with installing rabbitmqadmin, You should firstly install python.
UNIX-like operating system users need to copy rabbitmqadmin to a directory in PATH, e.g. /usr/local/bin.
Windows users will need to ensure Python is on their PATH, and invoke rabbitmqadmin as python.exe rabbitmqadmin.
Then
http://{hostname}:15672/cli/rabbitmqadmin
to download. To list Queues
python rabbitmqadmin list queues
.
To delete Queue
python rabbitmqadmin delete queue name=Name_of_queue
To Delete all Queues
1- Declare Policy
python rabbitmqadmin declare policy name='expire_all_policies' pattern=.* definition={\"expires\":1} apply-to=queues
2- Remove the policy
python rabbitmqadmin delete policy name='expire_all_policies'
Provided the windows box is in the same subnet:
for /L %a in (1,1,254) do start ping 192.168.0.%a
This will complete in less than 15 seconds and
arp -a
will return any alive host.
Fastest native way I know of in Windows.
For what it's worth I was having the same issue when passing app
into onRequest
. I realized the issue was a trailing slash on the request url for the firebase function. Express was looking for '/'
but I didn't have the trailing slash on the function [project-id].cloudfunctions.net/[function-name]
. The CORS error was a false negative. When I added the trailing slash, I got the response I was expecting.
You need to declare the type of the protocol as AnyObject
.
protocol ProtocolNameDelegate: AnyObject {
// Protocol stuff goes here
}
class SomeClass {
weak var delegate: ProtocolNameDelegate?
}
Using AnyObject
you say that only classes can conform to this protocol, whereas structs or enums can't.
First install node-static server via npm install node-static -g
-g is to install it global on your system, then navigate to the directory where your files are located, start the server with static
it listens on port 8080, naviaget to the browser and type localhost:8080/yourhtmlfilename.
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date1 = null;
Date date2 = null;
try {
date1 = dateFormat.parse(t1);
date2 = dateFormat.parse(t2);
} catch (ParseException e) {
e.printStackTrace();
}
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String StDate = formatter.format(date1);
String edDate = formatter.format(date2);
System.out.println("ST "+ StDate);
System.out.println("ED "+ edDate);
In case you want to initialize a fixed array of pre-initialized equal (non-null
or other than default
) elements, use this:
var array = Enumerable.Repeat(string.Empty, 37).ToArray();
Also please take part in this discussion.
Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.
http://www.rgagnon.com/javadetails/java-0542.html
Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.
package filesendtest;
import java.io.*;
import java.net.*;
class TCPServer {
private final static String fileToSend = "C:\\test1.pdf";
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File( fileToSend );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
package filesendtest;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
private final static String serverIP = "127.0.0.1";
private final static int serverPort = 3248;
private final static String fileOutput = "C:\\testout.pdf";
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket( serverIP , serverPort );
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream( fileOutput );
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
Related
Byte array of unknown length in java
Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):
public static String md5String(File file) {
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0) {
md5er.update(buffer, 0, read);
}
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null) {
return null;
}
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
} catch (Exception e) {
return null;
}
}
HTML CODE:
<table class="table table-hover">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>[email protected]</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>[email protected]</td>
</tr>
</tbody>
CSS CODE
.table-hover thead tr:hover th, .table-hover tbody tr:hover td {
background-color: #D1D119;
}
The css code indicate that:
mouse over row:
.table-hover > thead > tr:hover
background color of th will change to #D1D119
th
Same action will happen for tbody
.table-hover tbody tr:hover td
Unless you're really worried about older browsers, you could just use the new html5 placeholder
attribute like so:
<input type="text" name="email" placeholder="Email address" class="input" />
When I was to get yesterday with just the date in the format Year/Month/Day
I use:
$Variable = Get-Date((get-date ).AddDays(-1)) -Format "yyyy-MM-dd"