For programmers who haven't encountered functional programming in depth, and don't care to start now, but are mildly curious:
The Y combinator is a formula which lets you implement recursion in a situation where functions can't have names but can be passed around as arguments, used as return values, and defined within other functions.
It works by passing the function to itself as an argument, so it can call itself.
It's part of the lambda calculus, which is really maths but is effectively a programming language, and is pretty fundamental to computer science and especially to functional programming.
The day to day practical value of the Y combinator is limited, since programming languages tend to let you name functions.
In case you need to identify it in a police lineup, it looks like this:
Y = ?f.(?x.f (x x)) (?x.f (x x))
You can usually spot it because of the repeated (?x.f (x x))
.
The ?
symbols are the Greek letter lambda, which gives the lambda calculus its name, and there's a lot of (?x.t)
style terms because that's what the lambda calculus looks like.
found a solution, in my config file I just changed
$cfg['Servers'][$i]['auth_type'] = 'config';
to
$cfg['Servers'][$i]['auth_type'] = 'HTTP';
assuming you want to have a range between x to y
range(x,y+1)
>>> range(11,17)
[11, 12, 13, 14, 15, 16]
>>>
use list for 3.x support
I countered the same problem and to solve this issue just type the following commands in terminal for Linux clients
sudo apt-get install qemu-kvm
// type your password
sudo chmod 777 -R /dev/kvm
and after that try running simulator it'll work
An alternative to the rather unintuitive [::-1]
syntax is this:
>>> test = "abcba"
>>> test == ''.join(reversed(test))
True
The reversed
function returns a reversed sequence of the characters in test
.
''.join()
joins those characters together again with nothing in between.
I hope this is helpful to you.
Please try this code,
@Html.DropDownListFor(model => model.Items, new List<SelectListItem>
{ new SelectListItem{Text="Deactive", Value="False"},
new SelectListItem{Text="Active", Value="True", Selected = true},
})
cmake
mostly cooks a Makefile
, one could add rm
to the clean PHONY.
For example,
[root@localhost hello]# ls
CMakeCache.txt CMakeFiles cmake_install.cmake CMakeLists.txt hello Makefile test
[root@localhost hello]# vi Makefile
clean:
$(MAKE) -f CMakeFiles/Makefile2 clean
rm -rf *.o *~ .depend .*.cmd *.mod *.ko *.mod.c .tmp_versions *.symvers *.d *.markers *.order CMakeFiles cmake_install.cmake CMakeCache.txt Makefile
Enhancement of Ben Brandt's answer to compensate even if the string starts with space by applying LTRIM(). Tried to edit his answer but rejected, so I am now posting it here separately.
DECLARE @test NVARCHAR(255)
SET @test = 'First Second'
SELECT SUBSTRING(LTRIM(@test),1,(CHARINDEX(' ',LTRIM(@test) + ' ')-1))
To address one possible root of the actual issue, there is a chance you are sourcing a crlf file.
CRLF Example:
.env (crlf)
VARIABLE_A="abc"
VARIABLE_B="def"
run.sh
#!/bin/bash
source .env
echo "$VARIABLE_A"
echo "$VARIABLE_B"
echo "$VARIABLE_A $VARIABLE_B"
Returns:
abc
def
def
If however you convert to LF:
.env (lf)
VARIABLE_A="abc"
VARIABLE_B="def"
run.sh
#!/bin/bash
source .env
echo "$VARIABLE_A"
echo "$VARIABLE_B"
echo "$VARIABLE_A $VARIABLE_B"
Returns:
abc
def
abc def
My personal experience to build website with html, css en javascript is just to stick with plain text editors with ftp support. I am using Espresso or/and Coda on my mac. But Textmate with Cyberduck(ftp client) is also a great combination, imo. For developing in Windows I recommend notepad++.
I have solved a similar problem by first importing the text into an excel spreadsheet, then using the Substitute function to replace both the single and double quotes as required by SQL Server, eg. SUBSTITUTE(SUBSTITUTE(A1, "'", "''"), """", "\""")
In my case, I had many rows (each a line of data to be cleaned then inserted) and had the spreadsheet automatically generate insert queries for the text once the substitution had been done eg. ="INSERT INTO [dbo].[tablename] ([textcolumn]) VALUES ('" & SUBSTITUTE(SUBSTITUTE(A1, "'", "''"), """", "\""") & "')"
I hope that helps.
For Windows do the following:
:e $MYGVIMRC
set guifont=<font name as noted>:h<font size>
Since there can be multiple columns with same name , we should first rename the columns. Here is code for the solution.
df.columns=list(range(0,len(df.columns)))
df.drop(columns=[1,2])#drop second and third columns
Just set the domain
and path
attributes on your cookie, like:
<script type="text/javascript">
var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate
+ ";domain=.example.com;path=/";
</script>
@inoabrian solution above worked for me. I ran into a situation where I would refresh my page and my hidden element would reappear on my page. Here's what I did to resolve it.
export class FooterComponent implements OnInit {
public showJoinTodayBtn: boolean = null;
ngOnInit() {
if (condition is true) {
this.showJoinTodayBtn = true;
} else {
this.showJoinTodayBtn = false;
}
}
I've been trying to just make a simple bash script that emails out html formatted content-type and all these are great but I don't want to be creating local files on the filesystem to be passing into the script and also on our version of mailx(12.5+) the -a parameter for mail doesn't work anymore since it adds an attachment and I couldn't find any replacement parameter for additional headers so the easiest way for me was to use sendmail.
Below is the simplest 1 liner I created to run in our bash script that works for us. It just basically passes the Content-Type: text/html, subject, and the body and works.
printf "Content-Type: text/html\nSubject: Test Email\nHTML BODY<b>test bold</b>" | sendmail <Email Address To>
If you wanted to create an entire html page from a variable an alternative method I used in the bash script was to pass the variable as below.
emailBody="From: <Email Address From>
Subject: Test
Content-Type: text/html; charset=\"us-ascii\"
<html>
<body>
body
<b> test bold</b>
</body>
</html>
"
echo "$emailBody" | sendmail <Email Address To>
You need to use js get better height for body div
<html><body>
<div id="head" style="height:50px; width=100%; font-size:50px;">This is head</div>
<div id="body" style="height:700px; font-size:100px; white-space:pre-wrap; overflow:scroll;">
This is body
T
h
i
s
i
s
b
o
d
y
</div>
</body></html>
import numpy as np
import threading
def threaded_process(items_chunk):
""" Your main process which runs in thread for each chunk"""
for item in items_chunk:
try:
api.my_operation(item)
except Exception:
print('error with item')
n_threads = 20
# Splitting the items into chunks equal to number of threads
array_chunk = np.array_split(input_image_list, n_threads)
thread_list = []
for thr in range(n_threads):
thread = threading.Thread(target=threaded_process, args=(array_chunk[thr]),)
thread_list.append(thread)
thread_list[thr].start()
for thread in thread_list:
thread.join()
ComponentWillReceiveProps()
is going to be deprecated in the future due to bugs and inconsistencies. An alternative solution for re-rendering a component on props change is to use ComponentDidUpdate()
and ShouldComponentUpdate()
.
ComponentDidUpdate()
is called whenever the component updates AND if ShouldComponentUpdate()
returns true (If ShouldComponentUpdate()
is not defined it returns true
by default).
shouldComponentUpdate(nextProps){
return nextProps.changedProp !== this.state.changedProp;
}
componentDidUpdate(props){
// Desired operations: ex setting state
}
This same behavior can be accomplished using only the ComponentDidUpdate()
method by including the conditional statement inside of it.
componentDidUpdate(prevProps){
if(prevProps.changedProp !== this.props.changedProp){
this.setState({
changedProp: this.props.changedProp
});
}
}
If one attempts to set the state without a conditional or without defining ShouldComponentUpdate()
the component will infinitely re-render
if you like to use for URLRequest httpBody
extension Dictionary {
func toString() -> String? {
return (self.compactMap({ (key, value) -> String in
return "\(key)=\(value)"
}) as Array).joined(separator: "&")
}
}
// print: Fields=sdad&ServiceId=1222
A collector can be used for this.
Collectors.partitioningBy()
factory.This will create a Map
from Boolean
to List
, and put items in one or the other list based on a Predicate
.
Note: Since the stream needs to be consumed whole, this can't work on infinite streams. And because the stream is consumed anyway, this method simply puts them in Lists instead of making a new stream-with-memory. You can always stream those lists if you require streams as output.
Also, no need for the iterator, not even in the heads-only example you provided.
Random r = new Random();
Map<Boolean, List<String>> groups = stream
.collect(Collectors.partitioningBy(x -> r.nextBoolean()));
System.out.println(groups.get(false).size());
System.out.println(groups.get(true).size());
Collectors.groupingBy()
factory.Map<Object, List<String>> groups = stream
.collect(Collectors.groupingBy(x -> r.nextInt(3)));
System.out.println(groups.get(0).size());
System.out.println(groups.get(1).size());
System.out.println(groups.get(2).size());
In case the streams are not Stream
, but one of the primitive streams like IntStream
, then this .collect(Collectors)
method is not available. You'll have to do it the manual way without a collector factory. It's implementation looks like this:
[Example 2.0 since 2020-04-16]
IntStream intStream = IntStream.iterate(0, i -> i + 1).limit(100000).parallel();
IntPredicate predicate = ignored -> r.nextBoolean();
Map<Boolean, List<Integer>> groups = intStream.collect(
() -> Map.of(false, new ArrayList<>(100000),
true , new ArrayList<>(100000)),
(map, value) -> map.get(predicate.test(value)).add(value),
(map1, map2) -> {
map1.get(false).addAll(map2.get(false));
map1.get(true ).addAll(map2.get(true ));
});
In this example I initialize the ArrayLists with the full size of the initial collection (if this is known at all). This prevents resize events even in the worst-case scenario, but can potentially gobble up 2*N*T space (N = initial number of elements, T = number of threads). To trade-off space for speed, you can leave it out or use your best educated guess, like the expected highest number of elements in one partition (typically just over N/2 for a balanced split).
I hope I don't offend anyone by using a Java 9 method. For the Java 8 version, look at the edit history.
if you want to add a class to an existing list of classes for an element:
element.Attributes.Add("class", element.Attributes["class"] + " " + sType);
Using fall-through like in your first example is clearly OK, and I would not consider it a real fall-through.
The second example is dangerous and (if not commented extensively) non-obvious. I teach my students not to use such constructs unless they consider it worth the effort to devote a comment block to it, which describes that this is an intentional fall-through, and why this solution is better than the alternatives. This discourages sloppy use, but it still makes it allowed in the cases where it is used to an advantage.
This is more or less equivalent to what we did in space projects when someone wanted to violate the coding standard: they had to apply for dispensation (and I was called on to advise about the ruling).
First, you should disable selinux
, edit file /etc/sysconfig/selinux
so it looks like this:
SELINUX=disabled
SELINUXTYPE=targeted
Save file and restart system.
Then you can add the new rule to iptables
:
iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT
and restart iptables with /etc/init.d/iptables restart
If it doesn't work you should check other network settings.
You can open it in a new window with window.open('https://support.wwf.org.uk/earth_hour/index.php?type=individual');
. If you want to open it in new tab open the current page in two tabs and then alllow the script to run so that both current page and the new page will be obtained.
I don't think you can set any part of the sheet to be editable only by VBA, but you can do something that has basically the same effect -- you can unprotect the worksheet in VBA before you need to make changes:
wksht.Unprotect()
and re-protect it after you're done:
wksht.Protect()
Edit: Looks like this workaround may have solved Dheer's immediate problem, but for anyone who comes across this question/answer later, I was wrong about the first part of my answer, as Joe points out below. You can protect a sheet to be editable by VBA-only, but it appears the "UserInterfaceOnly" option can only be set when calling "Worksheet.Protect" in code.
Is't it just this ....
word_list=['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats',
'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and',
'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.',
'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats',
'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise',
'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle',
'Moon', 'to', 'rise.', '']
from collections import Counter
c = Counter(word_list)
c.most_common(3)
Which should output
[('Jellicle', 6), ('Cats', 5), ('are', 3)]
Here is code based on bestsss' answer:
Enumeration<URL> en = getClass().getClassLoader().getResources(
"META-INF");
List<String> profiles = new ArrayList<>();
while (en.hasMoreElements()) {
URL url = en.nextElement();
JarURLConnection urlcon = (JarURLConnection) (url.openConnection());
try (JarFile jar = urlcon.getJarFile();) {
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
String entry = entries.nextElement().getName();
System.out.println(entry);
}
}
}
Since you have used datepicker as a class I'm assuming you are using a Jquery datepicker or something similar.
There is a way to do what you are intending without using moment.js at all, purely using just datepicker and angularjs directives.
I've given a example here in this Fiddle
Excerpts from the fiddle here:
Datepicker has a different format and angularjs format is different, need to find the appropriate match so that date is preselected in the control and is also populated in the input field while the ng-model is bound. The below format is equivalent to 'mediumDate'
format of AngularJS.
$(element).find(".datepicker")
.datepicker({
dateFormat: 'M d, yy'
});
The date input directive needs to have an interim string variable to represent the human readable form of date.
Refreshing across different sections of page should happen via events, like $broadcast
and $on
.
Using filter to represent date in human readable form is possible in ng-model as well but with a temporary model variable.
$scope.dateValString = $filter('date')($scope.dateVal, 'mediumDate');
In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:
make sure your API is sending the Content-Type
header to tell the client to expect a JSON response:
header('Content-Type: application/json');
echo json_encode($response);
Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.
If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController
with an add()
action/method.
There are a few starting point projects for RESTful APIs on GitHub that are worth a look.
I resolved issue using below steps :
Stop cassandara services
sudo su -
systemctl stop datastax-agent
systemctl stop opscenterd
systemctl stop app-dse
Take backup and Change port from 9042 to 9035
cp /opt/dse/resources/cassandra/conf/cassandra.yaml /opt/dse/resources/cassandra/conf/bkp_cassandra.yaml
Vi /opt/dse/resources/cassandra/conf/cassandra.yaml
native_transport_port: 9035
Start Cassandra services
systemctl start datastax-agent
systemctl start opscenterd
systemctl start app-dse
create cqlshrc file.
vi /root/.cassandra/cqlshrc
[connection]
hostname = 198.168.1.100
port = 9035
Thanks, Mahesh
This will help you.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
This project on github may be your solution
this can also be done like this if you don't want to use prepared statements.
String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"
Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.
It's a bit old post but I recently ran into this issue. All I did was deleted all the nuget packages from packages folder and restored it. I was able to build the solution successfully. Hopefully helpful to someone.
I have tested by making a sample project and all simulators seem to use @3x images , this is confusing.
Create different versions of an image in your asset catalog such that the image itself tells you what version it is:
Now run the app on each simulator in turn. You will see that the 3x image is used only on the iPhone 6 Plus.
The same thing is true if the images are drawn from the app bundle using their names (e.g. one.png, [email protected], and [email protected]) by calling imageNamed:
and assigning into an image view.
(However, there's a difference if you assign the image to an image view in Interface Builder - the 2x version is ignored on double-resolution devices. This is presumably a bug, apparently a bug in pathForResource:ofType:
.)
I can think of a cheeky way to do it, I don't think this will be the best option but it will work.
Create the header as a separate table then place the other in a div and set a max size, then allow the scroll to come in by using overflow
.
table {_x000D_
width: 500px;_x000D_
}_x000D_
_x000D_
.scroll {_x000D_
max-height: 60px;_x000D_
overflow: auto;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<th>head1</th>_x000D_
<th>head2</th>_x000D_
<th>head3</th>_x000D_
<th>head4</th>_x000D_
</tr>_x000D_
</table>_x000D_
<div class="scroll">_x000D_
<table>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>More Text</td><td>More Text</td><td>More Text</td><td>More Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td></tr>_x000D_
</table>_x000D_
</div>
_x000D_
JAXB is an ideal solution. But you do not necessarily need xsd and xjc for that. More often than not you don't have an xsd but you know what your xml is. Simply analyze your xml, e.g.,
<customer id="100">
<age>29</age>
<name>mkyong</name>
</customer>
Create necessary model class(es):
@XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
@XmlAttribute
public void setId(int id) {
this.id = id;
}
}
Try to unmarshal:
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(new File("C:\\file.xml"));
Check results, fix bugs!
@Autowired
annotation is defined in the Spring framework.
@Inject
annotation is a standard annotation, which is defined in the standard "Dependency Injection for Java" (JSR-330). Spring (since the version 3.0) supports the generalized model of dependency injection which is defined in the standard JSR-330. (Google Guice frameworks and Picocontainer framework also support this model).
With @Inject
can be injected the reference to the implementation of the Provider
interface, which allows injecting the deferred references.
Annotations @Inject
and @Autowired
- is almost complete analogies. As well as @Autowired
annotation, @Inject
annotation can be used for automatic binding properties, methods, and constructors.
In contrast to @Autowired
annotation, @Inject
annotation has no required
attribute. Therefore, if the dependencies will not be found - will be thrown an exception.
There are also differences in the clarifications of the binding properties. If there is ambiguity in the choice of components for the injection the @Named
qualifier should be added. In a similar situation for @Autowired
annotation will be added @Qualifier
qualifier (JSR-330 defines it's own @Qualifier
annotation and via this qualifier annotation @Named
is defined).
Try this it works for me,
<style>_x000D_
select{_x000D_
border: 0 !important; /*Removes border*/_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
appearance: none;_x000D_
text-overflow:'';_x000D_
text-indent: 0.01px; /* Removes default arrow from firefox*/_x000D_
text-overflow: ""; /*Removes default arrow from firefox*/_x000D_
}_x000D_
select::-ms-expand {_x000D_
display: none;_x000D_
}_x000D_
.select-wrapper_x000D_
{_x000D_
padding-left:0px;_x000D_
overflow:hidden;_x000D_
}_x000D_
</style>_x000D_
_x000D_
<div class="select-wrapper">_x000D_
<select> ... </select>_x000D_
</div>
_x000D_
You can not hide but using overflow hidden you can actually make it disappear.
I decided to get rid of the $_SESSION
variable all together & wrote a wrapper around memcache to mimic the session.
Check https://github.com/manpreetssethi/utils/blob/master/Session_manager.php
Use-case: The moment a user lands on the app, store the signed request using the Session_manager and since it's in the cache, you may access it on any page henceforth.
Note: This will not work when browsing privately in Safari since the session_id resets every time the page reloads. (Stupid Safari)
It's not exactly an operator, rather a keyword. And no, it doesn't do any runtime-magic.
Update the master branch, which you need to do regardless.
Then, one of:
Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.
Merge your branch into master, and resolve the merge conflicts.
Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.
None of these is better than the other, they just have different trade-off patterns.
I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.
To rebase and keep the branch you would:
git checkout <branch> && git rebase <target>
In your case, check out the old branch, then
git rebase master
to get it rebuilt against master.
The best way to do this is just install the .EXE file into the windows/system32 folder. that way you can run it from any location. This is the same place where .exe's like ping can be found
Tested in Kafka 0.8.2, for the quick-start example: First, Add one line to server.properties file under config folder:
delete.topic.enable=true
then, you can run this command:
bin/kafka-topics.sh --zookeeper localhost:2181 --delete --topic test
What you're looking at is an expression-bodied member not a lambda expression.
When the compiler encounters an expression-bodied property member, it essentially converts it to a getter like this:
public int MaxHealth
{
get
{
return Memory[Address].IsValid ? Memory[Address].Read<int>(Offs.Life.MaxHp) : 0;
}
}
(You can verify this for yourself by pumping the code into a tool called TryRoslyn.)
Expression-bodied members - like most C# 6 features - are just syntactic sugar. This means that they don’t provide functionality that couldn't otherwise be achieved through existing features. Instead, these new features allow a more expressive and succinct syntax to be used
As you can see, expression-bodied members have a handful of shortcuts that make property members more compact:
return
statement because the compiler can infer that you want to return the result of the expressionget
keyword because it is implied by the use of the expression-bodied member syntax.I have made the final point bold because it is relevant to your actual question, which I will answer now.
The difference between...
// expression-bodied member property
public int MaxHealth => x ? y:z;
And...
// field with field initializer
public int MaxHealth = x ? y:z;
Is the same as the difference between...
public int MaxHealth
{
get
{
return x ? y:z;
}
}
And...
public int MaxHealth = x ? y:z;
Which - if you understand properties - should be obvious.
Just to be clear, though: the first listing is a property with a getter under the hood that will be called each time you access it. The second listing is is a field with a field initializer, whose expression is only evaluated once, when the type is instantiated.
This difference in syntax is actually quite subtle and can lead to a "gotcha" which is described by Bill Wagner in a post entitled "A C# 6 gotcha: Initialization vs. Expression Bodied Members".
While expression-bodied members are lambda expression-like, they are not lambda expressions. The fundamental difference is that a lambda expression results in either a delegate instance or an expression tree. Expression-bodied members are just a directive to the compiler to generate a property behind the scenes. The similarity (more or less) starts and end with the arrow (=>
).
I'll also add that expression-bodied members are not limited to property members. They work on all these members:
Added in C# 7.0
However, they do not work on these members:
If you want to control the formatting of the unique identifier you can create your own <FieldType>
in SharePoint. MSDN also has a visual How-To. This basically means that you're creating a custom column.
WSS defines the Counter field type (which is what the ID column above is using). I've never had the need to re-use this or extend it, but it should be possible.
A solution might exist without creating a custom <FieldType>
. For example: if you wanted unique IDs like CUST1, CUST2, ... it might be possible to create a Calculated column and use the value of the ID column in you formula (="CUST" & [ID]
). I haven't tried this, but this should work :)
enclose each argument with backticks( ` )
example:
<button onclick="updateById(`id`, `name`)">update</button>
function updateById(id, name) {
alert(id + name );
...
}
As per W3C: DOM permits programs and scripts to dynamically access and update the content, structure and style of XML or HTML documents.
DOM is composed of:
cheers
One-line solution:
function something_cool(text, callback){
callback && callback();
}
Step 1
Search
→ Find
→ (goto Tab) Mark
Find what
: ^Session.*$ Bookmark line
Regular expression
(under Search Mode
)Mark All
(this will find the regex and highlights all the lines and bookmark them) Step 2
Search
→ Bookmark
→ Remove Bookmarked Lines
I solved it by passing the binding with endpoint.
"http://abcd.net/SampleFileService.svc/basicHttpWSSecurity"
Which app server are you using? Each one puts its logging config in a different place, though most nowadays use Commons-Logging as a wrapper around either Log4J or java.util.logging.
Using Tomcat as an example, this document explains your options for configuring logging using either option. In either case you need to find or create a config file that defines the log level for each package and each place the logging system will output log info (typically console, file, or db).
In the case of log4j this would be the log4j.properties file, and if you follow the directions in the link above your file will start out looking like:
log4j.rootLogger=DEBUG, R
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=${catalina.home}/logs/tomcat.log
log4j.appender.R.MaxFileSize=10MB
log4j.appender.R.MaxBackupIndex=10
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
Simplest would be to change the line:
log4j.rootLogger=DEBUG, R
To something like:
log4j.rootLogger=WARN, R
But if you still want your own DEBUG level output from your own classes add a line that says:
log4j.category.com.mypackage=DEBUG
Reading up a bit on Log4J and Commons-Logging will help you understand all this.
I solve this problem with this code in NugetPackageConsole.and it works.The problem was in the version. i thikn it will help others.
Robert MacLean's answer did not work for me.
This however does work for me:
$("#div").dialog({
open: function() { $(".ui-dialog-titlebar-close").hide(); }
});
Use checked="checked"
attribute if you want your checkbox to be checked.
This works in Linux. Not sure how it behaves in other *nixes.
getent passwd "${OTHER_USER}"|cut -d\: -f 6
I know the post is old but after a 3 months time and with various email combinations I came across, able to make this sql for validating Email IDs.
CREATE FUNCTION [dbo].[isValidEmailFormat]
(
@EmailAddress varchar(500)
)
RETURNS bit
AS
BEGIN
DECLARE @Result bit
SET @EmailAddress = LTRIM(RTRIM(@EmailAddress));
SELECT @Result =
CASE WHEN
CHARINDEX(' ',LTRIM(RTRIM(@EmailAddress))) = 0
AND LEFT(LTRIM(@EmailAddress),1) <> '@'
AND RIGHT(RTRIM(@EmailAddress),1) <> '.'
AND LEFT(LTRIM(@EmailAddress),1) <> '-'
AND CHARINDEX('.',@EmailAddress,CHARINDEX('@',@EmailAddress)) - CHARINDEX('@',@EmailAddress) > 2
AND LEN(LTRIM(RTRIM(@EmailAddress))) - LEN(REPLACE(LTRIM(RTRIM(@EmailAddress)),'@','')) = 1
AND CHARINDEX('.',REVERSE(LTRIM(RTRIM(@EmailAddress)))) >= 3
AND (CHARINDEX('.@',@EmailAddress) = 0 AND CHARINDEX('..',@EmailAddress) = 0)
AND (CHARINDEX('-@',@EmailAddress) = 0 AND CHARINDEX('..',@EmailAddress) = 0)
AND (CHARINDEX('_@',@EmailAddress) = 0 AND CHARINDEX('..',@EmailAddress) = 0)
AND ISNUMERIC(SUBSTRING(@EmailAddress, 1, 1)) = 0
AND CHARINDEX(',', @EmailAddress) = 0
AND CHARINDEX('!', @EmailAddress) = 0
AND CHARINDEX('-.', @EmailAddress)=0
AND CHARINDEX('%', @EmailAddress)=0
AND CHARINDEX('#', @EmailAddress)=0
AND CHARINDEX('$', @EmailAddress)=0
AND CHARINDEX('&', @EmailAddress)=0
AND CHARINDEX('^', @EmailAddress)=0
AND CHARINDEX('''', @EmailAddress)=0
AND CHARINDEX('\', @EmailAddress)=0
AND CHARINDEX('/', @EmailAddress)=0
AND CHARINDEX('*', @EmailAddress)=0
AND CHARINDEX('+', @EmailAddress)=0
AND CHARINDEX('(', @EmailAddress)=0
AND CHARINDEX(')', @EmailAddress)=0
AND CHARINDEX('[', @EmailAddress)=0
AND CHARINDEX(']', @EmailAddress)=0
AND CHARINDEX('{', @EmailAddress)=0
AND CHARINDEX('}', @EmailAddress)=0
AND CHARINDEX('?', @EmailAddress)=0
AND CHARINDEX('<', @EmailAddress)=0
AND CHARINDEX('>', @EmailAddress)=0
AND CHARINDEX('=', @EmailAddress)=0
AND CHARINDEX('~', @EmailAddress)=0
AND CHARINDEX('`', @EmailAddress)=0
AND CHARINDEX('.', SUBSTRING(@EmailAddress, CHARINDEX('@', @EmailAddress)+1, 2))=0
AND CHARINDEX('.', SUBSTRING(@EmailAddress, CHARINDEX('@', @EmailAddress)-1, 2))=0
AND LEN(SUBSTRING(@EmailAddress, 0, CHARINDEX('@', @EmailAddress)))>1
AND CHARINDEX('.', REVERSE(@EmailAddress)) > 2
AND CHARINDEX('.', REVERSE(@EmailAddress)) < 5
THEN 1 ELSE 0 END
RETURN @Result
END
Any suggestions are welcomed!
I wrote a small lib for this. https://www.npmjs.com/package/@inf3rno/promise.exposed
I used the factory method approach others wrote, but I overrode the then
, catch
, finally
methods too, so you can resolve the original promise by those as well.
Resolving Promise without executor from outside:
const promise = Promise.exposed().then(console.log);
promise.resolve("This should show up in the console.");
Racing with the executor's setTimeout from outside:
const promise = Promise.exposed(function (resolve, reject){
setTimeout(function (){
resolve("I almost fell asleep.")
}, 100000);
}).then(console.log);
setTimeout(function (){
promise.resolve("I don't want to wait that much.");
}, 100);
There is a no-conflict mode if you don't want to pollute the global namespace:
const createExposedPromise = require("@inf3rno/promise.exposed/noConflict");
const promise = createExposedPromise().then(console.log);
promise.resolve("This should show up in the console.");
You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you
s = requests.Session()
# all cookies received will be stored in the session object
s.post('http://www...',data=payload)
s.get('http://www...')
Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects
You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:
This is the mysql function using the space technique (tested with mysql 5.0 + 5.5):
CREATE FUNCTION count_str( haystack TEXT, needle VARCHAR(32))
RETURNS INTEGER DETERMINISTIC
RETURN LENGTH(haystack) - LENGTH( REPLACE ( haystack, needle, space(char_length(needle)-1)) );
C++ solution found here (http://www.cplusplus.com/forum/unices/16430/)
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void ouch(int sig)
{
printf("OUCH! - I got signal %d\n", sig);
}
int main()
{
struct sigaction act;
act.sa_handler = ouch;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGINT, &act, 0);
while(1) {
printf("Hello World!\n");
sleep(1);
}
}
If using jQuery is acceptable:
jQuery("#myTextBox").focus( function(){
$(this).val("");
} );
when new props or states being received (like you call setState
here), React will invoked some functions, which are called componentWillUpdate
and componentDidUpdate
in your case, just simply add a componentDidUpdate
function to call this.drawGrid()
here is working code in JS Bin
as I mentioned, in the code, componentDidUpdate
will be invoked after this.setState(...)
then componentDidUpdate
inside is going to call this.drawGrid()
read more about component Lifecycle in React https://facebook.github.io/react/docs/component-specs.html#updating-componentwillupdate
I had a similar problem using Angular js. i had a rewrite all to index.html in my .htaccess. The solution was to add the correct path slashes in . Each situation is unique, but hope this helps someone.
you can just use this code to hit the script using cron job using cpanel:
wget https://www.example.co.uk/unique-code
A string needs no encoding. It is simply a sequence of Unicode characters.
You need to encode when you want to turn a String into a sequence of bytes. The charset the you choose (UTF-8, cp1255, etc.) determines the Character->Byte mapping. Note that a character is not necessarily translated into a single byte. In most charsets, most Unicode characters are translated to at least two bytes.
Encoding of a String is carried out by:
String s1 = "some text";
byte[] bytes = s1.getBytes("UTF-8"); // Charset to encode into
You need to decode when you have ? sequence of bytes and you want to turn them into a String. When y?u d? that you need to specify, again, the charset with which the byt?s were originally encoded (otherwise you'll end up with garbl?d t?xt).
Decoding:
String s2 = new String(bytes, "UTF-8"); // Charset with which bytes were encoded
If you want to understand this better, a great text is "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)"
Create a Pivot Table. It has these features and many more.
If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.
try this
$sql= " INSERT INTO users (username, password) VALUES('test', 'test') ";
mysql_query($sql);
$user_id= mysql_insert_id();
if(!empty($user_id) {
$sql=INSERT INTO profiles (userid, bio, homepage) VALUES($user_id,'Hello world!', 'http://www.stackoverflow.com');
/* or
$sql=INSERT INTO profiles (userid, bio, homepage) VALUES(LAST_INSERT_ID(),'Hello world!', 'http://www.stackoverflow.com'); */
mysql_query($sql);
};
Like this its work if you want to parse some string which is coming from mYearInDB.toString() =[2013] it will give 2013
Matcher n = MY_PATTERN.matcher("FOO[BAR]"+mYearInDB.toString());
while (n.find()) {
extracredYear = n.group(1);
// s now contains "BAR"
}
System.out.println("Extrated output is : "+extracredYear);
Stash is just a convenience method. Since branches are so cheap and easy to manage in git, I personally almost always prefer creating a new temporary branch than stashing, but it's a matter of taste mostly.
The one place I do like stashing is if I discover I forgot something in my last commit and have already started working on the next one in the same branch:
# Assume the latest commit was already done
# start working on the next patch, and discovered I was missing something
# stash away the current mess I made
git stash save
# some changes in the working dir
# and now add them to the last commit:
git add -u
git commit --amend
# back to work!
git stash pop
I solved it this way on a Mac. I used Homebrew to install the latest version of gcc/g++. They land in /usr/local/bin with includes in /usr/local/include.
I CD'd into /usr/local/bin and made a symlink from g++@7whatever to just g++ cause that @ bit is annoying.
Then I went to MyProject -> Properties -> C/C++ Build -> Settings -> GCC C++ Compiler and changed the command from "g++" to "/usr/local/bin/g++". If you decide not to make the symbolic link, you can be more specific.
Do the same thing for the linker.
Apply and Apply and Close. Let it rebuild the index. For a while, it showed a daunting number of errors, but I think that was while building indexes. While I was figuring out the errors, they all disappeared without further action.
I think without verifying that you could also go into Eclipse -> Properties -> C/C++ -> Core Build Toolchains and edit those with different paths, but I'm not sure what that will do.
If you want to respond to an event just one time, the following syntax should be really helpful:
$('.myLink').bind('click', function() {
//do some things
$(this).unbind('click', arguments.callee); //unbind *just this handler*
});
Using arguments.callee, we can ensure that the one specific anonymous-function handler is removed, and thus, have a single time handler for a given event. Hope this helps others.
This will copy the files in a range of commits (C to G) to a tar file. Note: this will only get the files commited. Not the entire repository. Slightly modified from Here
Example Commit History
A --> B --> C --> D --> E --> F --> G --> H --> I
git diff-tree -r --no-commit-id --name-only --diff-filter=ACMRT C~..G | xargs tar -rf myTarFile.tar
-r --> recurse into sub-trees
--no-commit-id --> git diff-tree outputs a line with the commit ID when applicable. This flag suppressed the commit ID output.
--name-only --> Show only names of changed files.
--diff-filter=ACMRT --> Select only these files. See here for full list of files
C..G --> Files in this range of commits
C~ --> Include files from Commit C. Not just files since Commit C.
| xargs tar -rf myTarFile --> outputs to tar
I believe you must add the namespace to your xml document, with, for example, the use of a SAX filter.
That means:
then link the two together:
public static Object unmarshallWithFilter(Unmarshaller unmarshaller,
java.io.File source) throws FileNotFoundException, JAXBException
{
FileReader fr = null;
try {
fr = new FileReader(source);
XMLReader reader = new NamespaceFilterXMLReader();
InputSource is = new InputSource(fr);
SAXSource ss = new SAXSource(reader, is);
return unmarshaller.unmarshal(ss);
} catch (SAXException e) {
//not technically a jaxb exception, but close enough
throw new JAXBException(e);
} catch (ParserConfigurationException e) {
//not technically a jaxb exception, but close enough
throw new JAXBException(e);
} finally {
FileUtil.close(fr); //replace with this some safe close method you have
}
}
try the following query:
SELECT ID,
Name
INTO #tempTable
FROM Table
SELECT *
FROM #tempTable
WHERE ID = 1
It doesn't need to declare table.
You can find details here To Quickly Format XML using Pretty Print (libXML)
Installing the XML Tools
If you run Notepad++ and look in the Plugins menu, you’ll see that the XML Tools aren’t there:
Download the XML tools from here.
Unzip the file and copy the XMLTools.dll to the Notepad++ plugins folder (in the example above: C:\Program Files (x86)\Notepad++\plugins):
Re-start Notepad++ and you should now see the XMLTools appear in the Plugins menu.
Unzip the ext_libs.zip file and then copy the unzipped DLLs to the Notepad++ installation directory (in the example above: C:\Program Files (x86)\Notepad++).
Re-start Notepad++ and you should finally see the proper XML Tools menu.
The feature I use the most is “Pretty print (XML only – with line breaks)”. This will format any piece of XML with all the proper line spacing.
from datetime import date,timedelta
delta = timedelta(days=1)
start = date(2020,1,1)
end=date(2020,9,1)
loop_date = start
while loop_date<=end:
print(loop_date)
loop_date+=delta
Tried every single answer. The only thing that worked for me was:
$("#editUserForm").get(0).reset();
Using:
jquery-validate/1.16.0
jquery-validation-unobtrusive/3.2.6/
In newer versions of Android you have to put all web I/O requests into a new thread. AsyncTask works best for small requests.
A quick way to do it in sql server 2012 is as follows:
SELECT FORMAT(GETDATE() , 'dd/MM/yyyy HH:mm:ss')
I've a workaround for NullPointerException
when remove fragment in on DestoryView
, Just put your code in onStop()
not onDestoryView
. It works fine!
@Override
public void onStop() {
super.onStop();
if (mMap != null) {
MainActivity.fragmentManager.beginTransaction()
.remove(MainActivity.fragmentManager.findFragmentById(R.id.location_map)).commit();
mMap = null;
}
}
In Laravel 5.x there is no paths.php
so you should edit public/index.php
and change this lines in order to to pint to your bootstrap
directory:
require __DIR__.’/../bootstrap/autoload.php’;
$app = require_once __DIR__.’/../bootstrap/app.php’;
for more information you can read this article.
FWIW I had this same issue. Turned out my xsi:schemaLocation entries were incorrect, so I went to the official docs and pasted theirs into mine:
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html section 16.5.6
I had to add a couple more but that was ok. Next up is to find out why this fixed the problem...
You can calculate with Dates.
var birthdate = new Date("1990/1/1");
var cur = new Date();
var diff = cur-birthdate; // This is the difference in milliseconds
var age = Math.floor(diff/31557600000); // Divide by 1000*60*60*24*365.25
By adding 100 to the number, then run a substring function from index 1 to the last position in right.
var dt = new Date();
var month = (100 + dt.getMonth()+1).toString().substr(1, 2);
var day = (100 + dt.getDate()).toString().substr(1, 2);
console.log(month,day);
you will got this result from the date of 2020-11-3
11,03
I hope the answer is useful
You can replace target-action with a closure (block in Objective-C) by adding a helper closure wrapper (ClosureSleeve) and adding it as an associated object to the control so it gets retained. That way you can pass any parameters.
class ClosureSleeve {
let closure: () -> ()
init(attachTo: AnyObject, closure: @escaping () -> ()) {
self.closure = closure
objc_setAssociatedObject(attachTo, "[\(arc4random())]", self, .OBJC_ASSOCIATION_RETAIN)
}
@objc func invoke() {
closure()
}
}
extension UIControl {
func addAction(for controlEvents: UIControlEvents, action: @escaping () -> ()) {
let sleeve = ClosureSleeve(attachTo: self, closure: action)
addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
}
}
Usage:
button.addAction(for: .touchUpInside) {
self.switchToNewsDetails(parameter: i)
}
With my ASP.NET Core Angular project running in Visual Studio 2019, sometimes I get this error message in the Firefox console:
Content Security Policy: The page’s settings blocked the loading of a resource at inline (“default-src”).
In Chrome, the error message is instead:
Failed to load resource: the server responded with a status of 404 ()
In my case it had nothing to do with my Content Security Policy, but instead was simply the result of a TypeScript error on my part.
Check your IDE output window for a TypeScript error, like:
> ERROR in src/app/shared/models/person.model.ts(8,20): error TS2304: Cannot find name 'bool'.
>
> i ?wdm?: Failed to compile.
Note: Since this question is the first result on Google for this error message.
You need to convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);
You can simply use jQuery UI Dialog
Example:
$(function() {_x000D_
$("#dialog").dialog();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>jQuery UI Dialog - Default functionality</title>_x000D_
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />_x000D_
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>_x000D_
<link rel="stylesheet" href="/resources/demos/style.css" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="dialog" title="Basic dialog">_x000D_
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
This works in my case. I hope you can extract meaning out of it.
//div[text()='building1' and @class='wrap']/ancestor::tr/td/div/div[@class='x-grid-row-checker']
You cannot use the VB line-continuation character inside of a string.
SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & _
"','" & txtContractStartDate.Value & _
"','" & txtSeatNo.Value & _
"','" & txtFloor.Value & "','" & txtLeaves.Value & "')"
Try using fake sendmail to send emails in a WAMP enviroment.
You can get some information :
Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production
Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.
Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
Fake: We acquire or build a very lightweight implementation of the same functionality as provided by a component that the SUT depends on and instruct the SUT to use it instead of the real.
Stub : This implementation is configured to respond to calls from the SUT with the values (or exceptions) that will exercise the Untested Code (see Production Bugs on page X) within the SUT. A key indication for using a Test Stub is having Untested Code caused by the inability to control the indirect inputs of the SUT
Mock Object that implements the same interface as an object on which the SUT (System Under Test) depends. We can use a Mock Object as an observation point when we need to do Behavior Verification to avoid having an Untested Requirement (see Production Bugs on page X) caused by an inability to observe side-effects of invoking methods on the SUT.
I try to simplify by using : Mock and Stub. I use Mock when it's an object that returns a value that is set to the tested class. I use Stub to mimic an Interface or Abstract class to be tested. In fact, it doesn't really matter what you call it, they are all classes that aren't used in production, and are used as utility classes for testing.
this fix worked for me:
installed Report Viewer 2008 SP1 Redistributable: http://www.microsoft.com/downloads/details.aspx?familyid=6aaa74bd-a46e-4478-b4e1-2063d18d2d42
took the solution from here: http://blogs.msdn.com/b/brianhartman/archive/2009/10/13/gdi-updated-again.aspx
You need to use the option -f
:
$ grep -f A B
The option -F
does a fixed string search where as -f
is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.
$ grep -Ff A B
You may also want the -w
option for matching whole words only:
$ grep -wFf A B
Read man grep
for a description of all the possible arguments and what they do.
I had the same problem. I am using Phonegap and Jquery mobile, for Adroid devices. To resize properly I had to set a timeout:
$(window).bind('orientationchange',function(e) {
fixOrientation();
});
$(window).bind('resize',function(e) {
fixOrientation();
});
function fixOrientation() {
setTimeout(function() {
var windowWidth = window.innerWidth;
$('div[data-role="page"]').width(windowWidth);
$('div[data-role="header"]').width(windowWidth);
$('div[data-role="content"]').width(windowWidth-30);
$('div[data-role="footer"]').width(windowWidth);
},500);
}
On newer versions of Windows (Windows 10 and Windows Server 2016) the tasks you create are located in C:\Windows\Tasks
. They will have the extension .job
For example if you create the task "DoWork" it will create the task in
C:\Windows\Tasks\DoWork.job
I had the same problem. In my pom.xml i had both
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.28</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
When i deleted the spring-boot-starter-web dependency, problem was solved.
static imports to "enhance" the language, so you can do nice literal things in type safe ways:
List<String> ls = List("a", "b", "c");
(can also do with maps, arrays, sets).
http://gleichmann.wordpress.com/2008/01/13/building-your-own-literals-in-java-lists-and-arrays/
Taking it further:
List<Map<String, String>> data = List(Map( o("name", "michael"), o("sex", "male")));
Although with different code, I experienced the same problem as the OP, because I originally used
fm.beginTransaction()
.add(R.id.fragment_container_main, fragment)
.addToBackStack(null)
.commit();
instead of
fm.beginTransaction()
.replace(R.id.fragment_container_main, fragment)
.addToBackStack(null)
.commit();
With "replace" the first fragment gets recreated when you return from the second fragment and therefore onResume() is also called.
put your javascript at the bottom of the page (ie after the element getting defined..)
length
and dbms_lob.getlength
return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength
will return the number of bytes, which may differ from the number of characters in a multi-byte character set.
As the documentation doesn't specify what happens when you apply length
on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength
.
I've uploaded my simple but fast implementation of a Guid class for ObjC here: obj-c GUID
Guid* guid = [Guid randomGuid];
NSLog("%@", guid.description);
It can parse to and from various string formats as well.
Use this:
SELECT * FROM Table WHERE Column LIKE '%[0-9]%'
Take a look at realpath
which is available on GNU/Linux, FreeBSD and NetBSD, but not OpenBSD 6.8. I use something like:
CONTAININGDIR=$(realpath ${FILEPATH%/*})
to do what it sounds like you're trying to do.
No, you can't, it doesn't support only year, so to do that you need a script, like jQuery or the webshim link you have, which shows year only.
If jQuery would be an option, here is one, borrowed from Sibu:
Javascript
$(function() {
$( "#datepicker" ).datepicker({dateFormat: 'yy'});
});?
CSS
.ui-datepicker-calendar {
display: none;
}
Src: https://stackoverflow.com/a/13528855/2827823
Src fiddle: http://jsfiddle.net/vW8zc/
Here is an updated fiddle, without the month and prev/next buttons
If bootstrap is an option, check this link, they have a layout how you want.
Option 1 using an InputStreamResource
Resource implementation for a given InputStream.
Should only be used if no other specific Resource implementation is > applicable. In particular, prefer ByteArrayResource or any of the file-based Resource implementations where possible.
@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {
// ...
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
Option2 as the documentation of the InputStreamResource suggests - using a ByteArrayResource:
@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {
// ...
Path path = Paths.get(file.getAbsolutePath());
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
There are ways to handle your own signals in certain JVMs -- see this article about the HotSpot JVM for example.
By using the Sun internal sun.misc.Signal.handle(Signal, SignalHandler)
method call you are also able to register a signal handler, but probably not for signals like INT
or TERM
as they are used by the JVM.
To be able to handle any signal you would have to jump out of the JVM and into Operating System territory.
What I generally do to (for instance) detect abnormal termination is to launch my JVM inside a Perl script, but have the script wait for the JVM using the waitpid
system call.
I am then informed whenever the JVM exits, and why it exited, and can take the necessary action.
For jQuery Mobile 1.4.5:
for anchor buttons, the CSS class is: ui-state-disabled
, and for input buttons it is just enough to toggle the disabled
attribute.
function toggleDisableButtons() {_x000D_
$("#link-1").toggleClass("ui-state-disabled", !$("#link-1").hasClass("ui-state-disabled"));_x000D_
$("#button-1").attr("disabled") ? $("#button-1").removeAttr("disabled") : $("#button-1").attr("disabled","");_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">_x000D_
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">_x000D_
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>_x000D_
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<div data-role="page" id="page-1">_x000D_
<div role="main" class="ui-content">_x000D_
<button class="ui-btn" onclick="toggleDisableButtons();">Toggle disabled</button>_x000D_
<a id="link-1" href="#" class="ui-btn ui-state-disabled">Anchor</a>_x000D_
<button id="button-1" disabled="">Button</button>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
BTW, for input buttons, there is an alternate method:
Enable:
$(".class").prop("disabled", false).removeClass("ui-state-disabled");
Disable:
$(".class").prop("disabled", true).addClass("ui-state-disabled");
import { Fragment } from 'react' // react version > 16.0
var thisIsMyCopy = (
<Fragment>
<p>copy copy copy
<strong>strong copy</strong>
</p>
</Fragment>
)
By using '' the sets the value to a string and React has no way of knowing that it is a HTML element. You can do the following to let React know it is a HTML element -
''
and it would work<Fragment>
to return a HTML element.Per the developers, this error is not an actual failure, but rather "misleading error reports". This bug is fixed in version 40, which is available on the canary and dev channels as of 25 Oct.
IMO the best way to accomplish your goal is to display a numeric keyboard rather than the normal keyboard. This restricts which keys are available to the user. This alleviates the need to do validation, and more importantly it prevents the user from making a mistake. The number pad is also much nicer for entering numbers because the keys are substantially larger.
In interface builder select the UITextField, go to the Attributes Inspector and change the "Keyboard Type" to "Decimal Pad".
That'll make the keyboard look like this:
The only thing left to do is ensure the user doesn't enter in two decimal places. You can do this while they're editing. Add the following code to your view controller. This code removes a second decimal place as soon as it is entered. It appears to the user as if the 2nd decimal never appeared in the first place.
- (void)viewDidLoad
{
[super viewDidLoad];
[self.textField addTarget:self
action:@selector(textFieldDidChange:)
forControlEvents:UIControlEventEditingChanged];
}
- (void)textFieldDidChange:(UITextField *)textField
{
NSString *text = textField.text;
NSRange range = [text rangeOfString:@"."];
if (range.location != NSNotFound &&
[text hasSuffix:@"."] &&
range.location != (text.length - 1))
{
// There's more than one decimal
textField.text = [text substringToIndex:text.length - 1];
}
}
a cheap and nasty would be:
jQuery("#myDiv").html().replace("<br>", "\n").replace("<br />", "\n")
EDIT
jQuery("#myTextArea").val(
jQuery("#myDiv").html()
.replace(/\<br\>/g, "\n")
.replace(/\<br \/\>/g, "\n")
);
Also created a jsfiddle if needed: http://jsfiddle.net/2D3xx/
Set the check box after loading the modal window. I think you are setting the check box before loading the page.
$('#fModal').modal('show');
$("#estado_cat").attr("checked","checked");
There's now a simpler way with .NET Standard
or .NET Core
:
var client = new HttpClient();
var response = await client.PostAsync(uri, myRequestObject, new JsonMediaTypeFormatter());
NOTE: In order to use the JsonMediaTypeFormatter
class, you will need to install the Microsoft.AspNet.WebApi.Client
NuGet package, which can be installed directly, or via another such as Microsoft.AspNetCore.App
.
Using this signature of HttpClient.PostAsync
, you can pass in any object and the JsonMediaTypeFormatter
will automatically take care of serialization etc.
With the response, you can use HttpContent.ReadAsAsync<T>
to deserialize the response content to the type that you are expecting:
var responseObject = await response.Content.ReadAsAsync<MyResponseType>();
I think the easiest way (with jQuery) to check if checkbox is checked or NOT is:
if 'checked':
if ($(this).is(':checked')) {
// I'm checked let's do something
}
if NOT 'checked':
if (!$(this).is(':checked')) {
// I'm NOT checked let's do something
}
XCode > 6.0 AND iOS > 8.0 The below script works if you have XCode version > 8.0
I use the below small Script to tail the simulator logs onto the system console.
#!/bin/sh
sim_dir=`xcrun instruments -s | grep "iPhone 6 (8.2 Simulator)" | awk {'print $NF'} | tr -d '[]'`
tail -f ~/Library/Logs/CoreSimulator/$sim_dir/system.log
You can pass in the simulator type used in the Grep as an argument. As mentioned in the above posts, there are simctl and instruments command to view the type of simulators available for use depending on the Xcode version. To View the list of available devices/simulators.
xcrun instruments -s
OR
xcrun simctl list
Now you can pass in the Device code OR Simulator type as an argument to the script and replace the "iPhone 6 (8.2 Simulator)" inside grep to be $1
Just use the max function and group function
select max(taskhistory.id) as id from taskhistory
group by taskhistory.taskid
order by taskhistory.datum desc
You are close already. Just make sure to hide the checkbox and associate it with a label you style via input[checkbox] + label
Complete Code: http://gist.github.com/592332
JSFiddle: http://jsfiddle.net/4huzr/
Sphinx is mainly a tool for formatting docs written independently from the source code, as I understand it.
For generating API docs from Python docstrings, the leading tools are pdoc and pydoctor. Here's pydoctor's generated API docs for Twisted and Bazaar.
Of course, if you just want to have a look at the docstrings while you're working on stuff, there's the "pydoc" command line tool and as well as the help()
function available in the interactive interpreter.
Under the windows feature list, make sure to check the IIS Management Console You also need to check additional check boxes as shown below:
I had the same issue. Turns out, you need the EntityFramework.dll reference (and not System.Data.Entity).
I just pulled it from the MvcMusicStore application which you can download from: http://mvcmusicstore.codeplex.com/
It's also a useful example of how to use entity framework code-first with MVC.
The commands are adduser
and addgroup
.
Here's a template for Docker you can use in busybox environments (alpine) as well as Debian-based environments (Ubuntu, etc.):
ENV USER=docker
ENV UID=12345
ENV GID=23456
RUN adduser \
--disabled-password \
--gecos "" \
--home "$(pwd)" \
--ingroup "$USER" \
--no-create-home \
--uid "$UID" \
"$USER"
Note the following:
--disabled-password
prevents prompt for a password--gecos ""
circumvents the prompt for "Full Name" etc. on Debian-based systems--home "$(pwd)"
sets the user's home to the WORKDIR. You may not want this.--no-create-home
prevents cruft getting copied into the directory from /etc/skel
The usage description for these applications is missing the long flags present in the code for adduser and addgroup.
The following long-form flags should work both in alpine as well as debian-derivatives:
BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.
Usage: adduser [OPTIONS] USER [GROUP]
Create new user, or add USER to GROUP
--home DIR Home directory
--gecos GECOS GECOS field
--shell SHELL Login shell
--ingroup GRP Group (by name)
--system Create a system user
--disabled-password Don't assign a password
--no-create-home Don't create home directory
--uid UID User id
One thing to note is that if --ingroup
isn't set then the GID is assigned to match the UID. If the GID corresponding to the provided UID already exists adduser will fail.
BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.
Usage: addgroup [-g GID] [-S] [USER] GROUP
Add a group or add a user to a group
--gid GID Group id
--system Create a system group
I discovered all of this while trying to write my own alternative to the fixuid project for running containers as the hosts UID/GID.
My entrypoint helper script can be found on GitHub.
The intent is to prepend that script as the first argument to ENTRYPOINT
which should cause Docker to infer UID and GID from a relevant bind mount.
An environment variable "TEMPLATE" may be required to determine where the permissions should be inferred from.
(At the time of writing I don't have documentation for my script. It's still on the todo list!!)
I use this handy function:
By downloading it with a 4094 byte step it will not full your memory
function download($file_source, $file_target) {
$rh = fopen($file_source, 'rb');
$wh = fopen($file_target, 'w+b');
if (!$rh || !$wh) {
return false;
}
while (!feof($rh)) {
if (fwrite($wh, fread($rh, 4096)) === FALSE) {
return false;
}
echo ' ';
flush();
}
fclose($rh);
fclose($wh);
return true;
}
Usage:
$result = download('http://url','path/local/file');
You can then check if everything is ok with:
if (!$result)
throw new Exception('Download error...');
I made modifications on only controller initialization by adding listener on action button:
$(document).on('click', '#action-button', function () {
$timeout(function () {
angular.element($('#input')).triggerHandler('input');
});
});
Other solutions did not work in my case.
You could do this pretty easily with my date-shortcode package:
const dateShortcode = require('date-shortcode')
var startDate = 'Monday, January 9, 2010'
dateShortcode.parse('{M/D/YYYY}', startDate)
//=> '1/9/2010'
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.
this works well for me even though the XML structure is complex.
And please make sure your xmlString is valid for XML, notice the escape character should be added "\" at the front.
The main problem might not come from the attributes.
You can do it with a LIMIT, just not with a LIMIT and an OFFSET.
May be you will not do it explicitly but it will happen.
Now, there are several ways we can try to get precise double
value (where num
and denom
are int
type, and of-course with casting)-
double d = (double) num / denom;
double d = ((double) num) / denom;
double d = num / (double) denom;
double d = (double) num / (double) denom;
but not double d = (double) (num / denom);
double d = num * 1.0 / denom;
double d = num / 1d / denom;
double d = ( num + 0.0 ) / denom;
double d = num; d /= denom;
but not double d = num / denom * 1.0;
and not double d = 0.0 + ( num / denom );
Now if you are asking- Which one is better? explicit? or implicit?
Well, lets not follow a straight answer here. Simply remember- We programmers don't like surprises or magics in a source. And we really hate Easter Eggs.
Also, an extra operation will definitely not make your code more efficient. Right?
You can use:
<asp:textbox id="textBox1" style="text-align:center"></asp:textbox>
Or this:
textbox.Style["text-align"] = "center"; //right, left
OPTION 1: Add this line to ~/.zshrc:
export "PATH=$HOME/pear/bin:$PATH"
After that you need to run source ~/.zshrc
in order your changes to take affect OR close this window and open a new one
OPTION 2: execute it inside the terminal console to add this path only to the current terminal window session. When you close the window/session, it will be lost.
<input type="radio" name="radio" value="creditcard" />
<input type="radio" name="radio" value="cash"/>
<input type="radio" name="radio" value="cheque"/>
<input type="radio" name="radio" value="instore"/>
$("input[name='radio']:checked").val()
If you want very few info like a class in your html for common browsers for instance, you could use:
function get_browser()
{
$browser = '';
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if (preg_match('~(?:msie ?|trident.+?; ?rv: ?)(\d+)~', $ua, $matches)) $browser = 'ie ie'.$matches[1];
elseif (preg_match('~(safari|chrome|firefox)~', $ua, $matches)) $browser = $matches[1];
return $browser;
}
which will return 'safari' or 'firefox' or 'chrome', or 'ie ie8', 'ie ie9', 'ie ie10', 'ie ie11'.
u should add a theme
to ur all activities (u should add theme
for all application in ur <application>
in ur manifest)
but if u have set different theme to ur activity u can use :
android:theme="@style/Theme.AppCompat"
or each kind of AppCompat
theme!
This snippet will:
// the selector will match all input controls of type :checkbox_x000D_
// and attach a click event handler _x000D_
$("input:checkbox").on('click', function() {_x000D_
// in the handler, 'this' refers to the box clicked on_x000D_
var $box = $(this);_x000D_
if ($box.is(":checked")) {_x000D_
// the name of the box is retrieved using the .attr() method_x000D_
// as it is assumed and expected to be immutable_x000D_
var group = "input:checkbox[name='" + $box.attr("name") + "']";_x000D_
// the checked state of the group/box on the other hand will change_x000D_
// and the current value is retrieved using .prop() method_x000D_
$(group).prop("checked", false);_x000D_
$box.prop("checked", true);_x000D_
} else {_x000D_
$box.prop("checked", false);_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<div>_x000D_
<h3>Fruits</h3>_x000D_
<label>_x000D_
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />Kiwi</label>_x000D_
<label>_x000D_
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />Jackfruit</label>_x000D_
<label>_x000D_
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />Mango</label>_x000D_
</div>_x000D_
<div>_x000D_
<h3>Animals</h3>_x000D_
<label>_x000D_
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />Tiger</label>_x000D_
<label>_x000D_
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />Sloth</label>_x000D_
<label>_x000D_
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />Cheetah</label>_x000D_
</div>
_x000D_
You have the alias inside of the case, it needs to be outside of the END
:
Insert into TblStuff (FullName,Address,City,Zip)
Select
Case
When Middle is Null
Then Fname + LName
Else Fname +' ' + Middle + ' '+ Lname
End as FullName,
Case
When Address2 is Null Then Address1
else Address1 +', ' + Address2
End as Address,
City as City,
Zip as Zip
from tblImport
On Windows, I had this issue with static files cropping up under pydev/eclipse with python 2.7, due to an instance of django (1.8.7) that had been installed under cygwin. This caused a conflict between windows style paths and cygwin style paths. So, unfindable static files despite all the above fixes. I removed the extra distribution (so that all packages were installed by pip under windows) and this fixed the issue.
EditText number1 = (EditText) layout.findViewById(R.id.edittext);
number1.setInputType(InputType.TYPE_CLASS_NUMBER);
<?php
$variable1 = "foo";
$variable2 = "bar";
header('Location: http://linkhere.com?fieldname1=$variable1&fieldname2=$variable2&fieldname3=$variable3);
?>
This works without any quotations.
I know this is an old post but just for reference. Here is how to append without the special case check for an empty list, although at the expense of more complex looking code.
void Append(List * l, Node * n)
{
Node ** next = &list->Head;
while (*next != NULL) next = &(*next)->Next;
*next = n;
n->Next = NULL;
}
Yes, it is deprecated. http://docs.jboss.org/hibernate/core/4.0/javadocs/org/hibernate/cfg/Configuration.html#buildSessionFactory() specifically tells you to use the other method you found instead (buildSessionFactory(ServiceRegistry serviceRegistry)
) - so use it.
The documentation is copied over from release to release, and likely just hasn't been updated yet (they don't rewrite the manual with every release) - so trust the Javadocs.
The specifics of this change can be viewed at:
Some additional references:
I had the same problem, I can't figured out how to find the aliases used by Git Bash on Windows.
After searching for a while, I found the aliases.sh file under C:\Program Files\Git\etc\profile.d\aliases.sh
.
This is the path under windows 7, maybe can be different in other installation.
Just open it with your preferred editor in admin mode. After save it, reload your command prompt.
I hope this can help!
Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to
find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;
Just to sum up!
Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.
You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.
Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.
So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".
That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.
SOAP:
SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.
REST:
REST is a design concept.
The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.
It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)
Flickr's REST API goes further and lets you return images as well.
JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.
Use git config --global core.editor mate -w
or git config --global core.editor open
as @dmckee suggests in the comments.
Reference: http://git-scm.com/docs/git-config
1st Step: Add this content in pom.xml
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
2nd Step : Execute this command line by line.
cd /go/to/myApp
mvn clean
mvn compile
mvn package
java -cp target/myApp-0.0.1-SNAPSHOT.jar go.to.myApp.select.file.to.execute
The read_sql
docs say this params
argument can be a list, tuple or dict (see docs).
To pass the values in the sql query, there are different syntaxes possible: ?
, :1
, :name
, %s
, %(name)s
(see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2
in your case I suppose).
In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2
documentation, they support the %(name)s
style (and so not the :name
I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:
df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
index_col=['Timestamp'])
I solved this issue by doing following:
Enter to system preferences -> mysql
Select "Initialize database" and enter a new root password selecting "Use Legacy Password Encryption".
Login into phpmyadmin with the new password.
You have to pass the arguments in the terminal in order to store them in 'argv'. This variable holds the arguments you pass to your Python script when you run it. It later unpacks the arguments and store them in different variables you specify in the program e.g.
script, first, second = argv
print "Your file is:", script
print "Your first entry is:", first
print "Your second entry is:" second
Then in your command line you have to run your code like this,
$python ex14.py Hamburger Pizza
Your output will look like this:
Your file is: ex14.py
Your first entry is: Hamburger
Your second entry is: Pizza
I know than it's a really old question, but if someone is interested in this feature, can check this code http://vim.wikia.com/wiki/Auto_highlight_current_word_when_idle
" Highlight all instances of word under cursor, when idle.
" Useful when studying strange source code.
" Type z/ to toggle highlighting on/off.
nnoremap z/ :if AutoHighlightToggle()<Bar>set hls<Bar>endif<CR>
function! AutoHighlightToggle()
let @/ = ''
if exists('#auto_highlight')
au! auto_highlight
augroup! auto_highlight
setl updatetime=4000
echo 'Highlight current word: off'
return 0
else
augroup auto_highlight
au!
au CursorHold * let @/ = '\V\<'.escape(expand('<cword>'), '\').'\>'
augroup end
setl updatetime=500
echo 'Highlight current word: ON'
return 1
endif
endfunction
I had the same problem on a methood that returns the status of the server. The application is deployed on multiple servers. So the easiest I found is to add
@CrossOrigin(origins = "*")
@RequestMapping(value="/schedulerActive")
public String isSchedulerActive(){
//code goes here
}
This method is not secure but you can add allowCredentials
for that.
although Response::json()
is not getting popular of recent, that does not stop you and Me from using it.
In fact you don't need any facade to use it,
instead of:
$response = Response::json($messages, 200);
Use this:
$response = \Response::json($messages, 200);
with the slash, you are sure good to go.
From MySQL 5.7 Reference Manual.
Syntax :
ALTER TABLE t1 CHANGE a b DATATYPE;
e.g. : for Customer TABLE having COLUMN customer_name, customer_street, customercity.
And we want to change customercity TO customer_city :
alter table customer change customercity customer_city VARCHAR(225);
Use the name of the id with the getElementById
, no #
sign before it. Then you can get the span
child nodes using getElementsByTagName
, and loop through them to find the one with the right class:
var doc = document.getElementById('test');
var c = doc.getElementsByTagName('span');
var e = null;
for (var i = 0; i < c.length; i++) {
if (c[i].className == '4') {
e = c[i];
break;
}
}
if (e != null) {
alert(e.innerHTML);
}
Two ways:
Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned.
Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there.
The answers above have not emphasized enough the importance of locking. I'm not a big fan of cursors because they often result in table level locks.
To add to what joshb has stated already - this works just fine for me. Make sure to add references to Microsoft.Expression.Interactions.dll and System.Windows.Interactivity.dll and in your xaml do:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
I ended up using something like this for my needs. This shows that you can also pass a custom parameter:
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding Path=DataContext.RowSelectedItem, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
CommandParameter="{Binding Path=SelectedItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<script type="text/javascript">
document.getElementById('button1').onChange = function () {
document.getElementById('hidden_field_id').value = document.getElementById('span_id').innerHTML;
}
</script>
I checked some of the methods for speed performance and find that there is no difference! The only difference is that using some methods you must carefully check dimension.
Timing:
|------------|----------------|-------------------|
| | shape (10000) | shape (1,10000) |
|------------|----------------|-------------------|
| np.concat | 0.18280 | 0.17960 |
|------------|----------------|-------------------|
| np.stack | 0.21501 | 0.16465 |
|------------|----------------|-------------------|
| np.vstack | 0.21501 | 0.17181 |
|------------|----------------|-------------------|
| np.array | 0.21656 | 0.16833 |
|------------|----------------|-------------------|
As you can see I tried 2 experiments - using np.random.rand(10000)
and np.random.rand(1, 10000)
And if we use 2d arrays than np.stack
and np.array
create additional dimension - result.shape is (1,10000,10000) and (10000,1,10000) so they need additional actions to avoid this.
Code:
from time import perf_counter
from tqdm import tqdm_notebook
import numpy as np
l = []
for i in tqdm_notebook(range(10000)):
new_np = np.random.rand(10000)
l.append(new_np)
start = perf_counter()
stack = np.stack(l, axis=0 )
print(f'np.stack: {perf_counter() - start:.5f}')
start = perf_counter()
vstack = np.vstack(l)
print(f'np.vstack: {perf_counter() - start:.5f}')
start = perf_counter()
wrap = np.array(l)
print(f'np.array: {perf_counter() - start:.5f}')
start = perf_counter()
l = [el.reshape(1,-1) for el in l]
conc = np.concatenate(l, axis=0 )
print(f'np.concatenate: {perf_counter() - start:.5f}')
It works here:
$ wget -S -O - http://google.com
HTTP request sent, awaiting response...
HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
Date: Sat, 25 Aug 2012 10:15:38 GMT
Expires: Mon, 24 Sep 2012 10:15:38 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 219
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Location: http://www.google.com/ [following]
--2012-08-25 12:20:29-- http://www.google.com/
Resolving www.google.com (www.google.com)... 173.194.69.99, 173.194.69.104, 173.194.69.106, ...
...skipped a few more redirections ...
[<=> ] 0 --.-K/s
<!doctype html><html itemscope="itemscope" itemtype="http://schema.org/WebPage"><head><meta itemprop="image" content="/images/google_favicon_128.png"><ti
... skipped ...
perhaps you need to update your wget (~$ wget --version
GNU Wget 1.14 built on linux-gnu.
)
307 came about because user agents adopted as a de facto behaviour to take POST requests that receive a 302 response and send a GET request to the Location response header.
That is the incorrect behaviour — only a 303 should cause a POST to turn into a GET. User agents should (but don't) stick with the POST method when requesting the new URL if the original POST request returned a 302.
307 was introduced to allow servers to make it clear to the user agent that a method change should not be made by the client when following the Location response header.
Use %0A
(URL encoding) instead of \n
(C encoding).
Another flexible way using classpath containing fat jar (-cp fat.jar) or all jars (-cp "$JARS_DIR/*") and another custom config classpath or folder containing configuration files usually elsewhere and outside jar. So instead of the limited java -jar, use the more flexible classpath way as follows:
java \
-cp fat_app.jar \
-Dloader.path=<path_to_your_additional_jars or config folder> \
org.springframework.boot.loader.PropertiesLauncher
See Spring-boot executable jar doc and this link
If you do have multiple MainApps which is common, you can use How do I tell Spring Boot which main class to use for the executable jar?
You can add additional locations by setting an environment variable LOADER_PATH or loader.path in loader.properties (comma-separated list of directories, archives, or directories within archives). Basically loader.path works for both java -jar or java -cp way.
And as always you can override and exactly specify the application.yml it should pickup for debugging purpose
--spring.config.location=/some-location/application.yml --debug
The precedent answers show you how to handle bit checks, but more often then not, it is all about flags encoded in an integer, which is not well defined in any of the precedent cases.
In a typical scenario, flags are defined as integers themselves, with a bit to 1 for the specific bit it refers to. In the example hereafter, you can check if the integer has ANY flag from a list of flags (multiple error flags concatenated) or if EVERY flag is in the integer (multiple success flags concatenated).
Following an example of how to handle flags in an integer.
Live example available here: https://rextester.com/XIKE82408
//g++ 7.4.0
#include <iostream>
#include <stdint.h>
inline bool any_flag_present(unsigned int value, unsigned int flags) {
return bool(value & flags);
}
inline bool all_flags_present(unsigned int value, unsigned int flags) {
return (value & flags) == flags;
}
enum: unsigned int {
ERROR_1 = 1U,
ERROR_2 = 2U, // or 0b10
ERROR_3 = 4U, // or 0b100
SUCCESS_1 = 8U,
SUCCESS_2 = 16U,
OTHER_FLAG = 32U,
};
int main(void)
{
unsigned int value = 0b101011; // ERROR_1, ERROR_2, SUCCESS_1, OTHER_FLAG
unsigned int all_error_flags = ERROR_1 | ERROR_2 | ERROR_3;
unsigned int all_success_flags = SUCCESS_1 | SUCCESS_2;
std::cout << "Was there at least one error: " << any_flag_present(value, all_error_flags) << std::endl;
std::cout << "Are all success flags enabled: " << all_flags_present(value, all_success_flags) << std::endl;
std::cout << "Is the other flag enabled with eror 1: " << all_flags_present(value, ERROR_1 | OTHER_FLAG) << std::endl;
return 0;
}
[]
denotes a list, ()
denotes a tuple and {}
denotes a dictionary. You should take a look at the official Python tutorial as these are the very basics of programming in Python.
What you have is a list of strings. You can sort it like this:
In [1]: lst = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
In [2]: sorted(lst)
Out[2]: ['Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim', 'constitute']
As you can see, words that start with an uppercase letter get preference over those starting with a lowercase letter. If you want to sort them independently, do this:
In [4]: sorted(lst, key=str.lower)
Out[4]: ['constitute', 'Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim']
You can also sort the list in reverse order by doing this:
In [12]: sorted(lst, reverse=True)
Out[12]: ['constitute', 'Whim', 'Stem', 'Sedge', 'Intrigue', 'Eflux']
In [13]: sorted(lst, key=str.lower, reverse=True)
Out[13]: ['Whim', 'Stem', 'Sedge', 'Intrigue', 'Eflux', 'constitute']
Please note: If you work with Python 3, then str
is the correct data type for every string that contains human-readable text. However, if you still need to work with Python 2, then you might deal with unicode strings which have the data type unicode
in Python 2, and not str
. In such a case, if you have a list of unicode strings, you must write key=unicode.lower
instead of key=str.lower
.
This link contains a good checklist why core dumps are not generated:
exit()
instead of using the core dump handler.Here is a real world example:
String hallostring = "hallo";
String asubstring = hallostring.substring(0, 1);
In the example asubstring would return: h
Just because you declare your struct B
inside class A
does not mean that an instance of class A
automatically has the properties of struct B
as members, nor does it mean that it automatically has an instance of struct B
as a member.
There is no true relation between the two classes (A
and B
), besides scoping.
struct A {
struct B {
int v;
};
B inner_object;
};
int
main (int argc, char *argv[]) {
A object;
object.inner_object.v = 123;
}
I use this extension method:
public static IQueryable<T> Page<T, TResult>(this IQueryable<T> obj, int page, int pageSize, System.Linq.Expressions.Expression<Func<T, TResult>> keySelector, bool asc, out int rowsCount)
{
rowsCount = obj.Count();
int innerRows = rowsCount - (page * pageSize);
if (innerRows < 0)
{
innerRows = 0;
}
if (asc)
return obj.OrderByDescending(keySelector).Take(innerRows).OrderBy(keySelector).Take(pageSize).AsQueryable();
else
return obj.OrderBy(keySelector).Take(innerRows).OrderByDescending(keySelector).Take(pageSize).AsQueryable();
}
public IEnumerable<Data> GetAll(int RowIndex, int PageSize, string SortExpression)
{
int totalRows;
int pageIndex = RowIndex / PageSize;
List<Data> data= new List<Data>();
IEnumerable<Data> dataPage;
bool asc = !SortExpression.Contains("DESC");
switch (SortExpression.Split(' ')[0])
{
case "ColumnName":
dataPage = DataContext.Data.Page(pageIndex, PageSize, p => p.ColumnName, asc, out totalRows);
break;
default:
dataPage = DataContext.vwClientDetails1s.Page(pageIndex, PageSize, p => p.IdColumn, asc, out totalRows);
break;
}
foreach (var d in dataPage)
{
clients.Add(d);
}
return data;
}
public int CountAll()
{
return DataContext.Data.Count();
}
you can use it when you expect a null value in your integer especially when you use CASTING ex:
x= (int)y;
if y = null then you will have an error. you have to use:
x = (int?)y;
To suppress the page number on the first page, add \thispagestyle{empty}
after the \maketitle
command.
The second page of the document will then be numbered "2". If you want this page to be numbered "1", you can add \pagenumbering{arabic}
after the \clearpage
command, and this will reset the page number.
Here's a complete minimal example:
\documentclass[notitlepage]{article}
\title{My Report}
\author{My Name}
\begin{document}
\maketitle
\thispagestyle{empty}
\begin{abstract}
\ldots
\end{abstract}
\clearpage
\pagenumbering{arabic}
\section{First Section}
\ldots
\end{document}
If you're changing the layout of an existing ImageView, you should be able to simply get the current LayoutParams, change the width/height, and set it back:
android.view.ViewGroup.LayoutParams layoutParams = myImageView.getLayoutParams();
layoutParams.width = 30;
layoutParams.height = 30;
myImageView.setLayoutParams(layoutParams);
I don't know if that's your goal, but if it is, this is probably the easiest solution.
var results = list.GroupBy(x => x.Category)
.Select(g => g.OrderBy(x => x.SortByProp).FirstOrDefault());
For those wondering how to do this for groups that are not necessarily sorted correctly, here's an expansion of this answer that uses method syntax to customize the sort order of each group and hence get the desired record from each.
Note: If you're using LINQ-to-Entities you will get a runtime exception if you use First() instead of FirstOrDefault() here as the former can only be used as a final query operation.
You can use !!
, but if you want to do it recursively then below is one way to do it:
dataAt :: Int -> [a] -> a
dataAt _ [] = error "Empty List!"
dataAt y (x:xs) | y <= 0 = x
| otherwise = dataAt (y-1) xs
All modern browsers now support the unprefixed event:
element.addEventListener('transitionend', callback, false);
Works in the latest versions of Chrome, Firefox and Safari. Even IE10+.
Instead of document or $(document) to avoid JQuery, you can add a TimeOut to validate the objects. TimeOut is executed after loading all objects within the page and other events...
setTimeout(function () {
var str = document.getElementById("cal_preview").value;
var str1 = document.getElementById("year").value;
....
....
....
}, 0);
the answer is
Dictionary
take look at my function, its simple add uses most important member functions inside Dictionary
this function return false if the list contain Duplicates items
public static bool HasDuplicates<T>(IList<T> items)
{
Dictionary<T, bool> mp = new Dictionary<T, bool>();
for (int i = 0; i < items.Count; i++)
{
if (mp.ContainsKey(items[i]))
{
return true; // has duplicates
}
mp.Add(items[i], true);
}
return false; // no duplicates
}
New for Postgresql 9.2; PSQL automatically fits records to the width of the screen. previously you only had expanded mode on or off and had to switch between the modes as necessary.
To get this use: \x auto
Postgresql 9.5 Documentation on PSQL command.
Wide screen, normal formatting:
id | time | humanize_time | value
----+-------+---------------------------------+-------
1 | 09:30 | Early Morning - (9.30 am) | 570
2 | 11:30 | Late Morning - (11.30 am) | 690
3 | 13:30 | Early Afternoon - (1.30pm) | 810
4 | 15:30 | Late Afternoon - (3.30 pm) | 930
(4 rows)
Narrow screen, expanded formatting:
-[ RECORD 1 ]-+---------------------------
id | 1
time | 09:30
humanize_time | Early Morning - (9.30 am)
value | 570
-[ RECORD 2 ]-+---------------------------
id | 2
time | 11:30
humanize_time | Late Morning - (11.30 am)
value | 690
-[ RECORD 3 ]-+---------------------------
id | 3
time | 13:30
humanize_time | Early Afternoon - (1.30pm)
value | 810
-[ RECORD 4 ]-+---------------------------
id | 4
time | 15:30
humanize_time | Late Afternoon - (3.30 pm)
value | 930
Configure \x auto
command on startup by adding it to .psqlrc
in your home folder and restarting psql. Look under 'Files' section in the psql doc for more info.
~/.psqlrc
\x auto
You need to use <br>
instead of \r\n
. For this you can use built in function call nl2br
So your code should be like this
$message = nl2br("CCCC\r\nCCCC CCCC \r CCC \n CCC \r\n CCC \n\r CCCC");
for speed you can do this
WHERE date(created_at) ='2019-10-21'
In KitKat and above, you could use evaluateJavascript
method on webview
wvbrowser.evaluateJavascript(
"(function() { return ('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>'); })();",
new ValueCallback<String>() {
@Override
public void onReceiveValue(String html) {
Log.d("HTML", html);
// code here
}
});
See this answer for more examples
Not sure if this counts as an answer - but here is YouTube Video From Google's Course (Developing Android Apps with Kotlin) that explains the difference.
Just for reference if someone is still looking on how to do this for multiple files, see the linked answer to Finding matching lines across many files.
Combining these two answers (ans1 and ans2), I think you can get the result you are needing without sorting the files:
#!/bin/bash
ans="matching_lines"
for file1 in *
do
for file2 in *
do
if [ "$file1" != "$ans" ] && [ "$file2" != "$ans" ] && [ "$file1" != "$file2" ] ; then
echo "Comparing: $file1 $file2 ..." >> $ans
perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/' $file1 $file2 >> $ans
fi
done
done
Simply save it, give it execution rights (chmod +x compareFiles.sh
) and run it. It will take all the files present in the current working directory and will make an all-vs-all comparison leaving in the "matching_lines" file the result.
Things to be improved:
All the above solutions are useful. And they used the line lol = document.getElementById('lolz').value;
inside the function function kk()
.
What I suggest is, you may call that variable from another function fun_inside()
function fun_inside()
{
lol = document.getElementById('lolz').value;
}
function kk(){
fun_inside();
alert(lol);
}
It can be useful when you built complex projects.
In my case GIT was installed on my WIndows 10 OS and there was an entry in PATH variable. But VS CODE 1.52.1 still unable to detect it from terminal window but it was available in CMD console.
Problem was solved by switching terminal from PowerShell to CMD or Shell + VsCode restart.
It sounds like you might just need to use a view. A view allows a query to be represented as a table so it, the view, can be queried.
You can get errors working correctly without hacking global.cs, messing with HandleErrorAttribute, doing Response.TrySkipIisCustomErrors, hooking up Application_Error, or whatever:
In system.web (just the usual, on/off)
<customErrors mode="On">
<error redirect="/error/401" statusCode="401" />
<error redirect="/error/500" statusCode="500" />
</customErrors>
and in system.webServer
<httpErrors existingResponse="PassThrough" />
Now things should behave as expected, and you can use your ErrorController to display whatever you need.
The accepted answer has some gotchas. For example:
>>> a = [{}] * 3
>>> a
[{}, {}, {}]
>>> a[0]['hello'] = 5
>>> a
[{'hello': 5}, {'hello': 5}, {'hello': 5}]
>>>
So each dictionary refers to the same object. Same holds true if you initialize with arrays or objects.
You could do this instead:
>>> b = [{} for i in range(0, 3)]
>>> b
[{}, {}, {}]
>>> b[0]['hello'] = 6
>>> b
[{'hello': 6}, {}, {}]
>>>
The current user's username can be gotten in pure Bash with the ${parameter@operator}
parameter expansion (introduced in Bash 4.4):
$ : \\u
$ printf '%s\n' "${_@P}"
The :
built-in (synonym of true
) is used instead of a temporary variable by setting the last argument, which is stored in $_
. We then expand it (\u
) as if it were a prompt string with the P
operator.
This is better than using $USER
, as $USER
is just a regular environmental variable; it can be modified, unset, etc. Even if it isn't intentionally tampered with, a common case where it's still incorrect is when the user is switched without starting a login shell (su
's default).
This error can occur when you trying to install pycurl
.
In this case you should do
sudo apt-get install libcurl4-gnutls-dev librtmp-dev
(founded here: https://gist.github.com/lxneng/1031014 )
You can also use numpy loadtxt like
from numpy import loadtxt
lines = loadtxt("filename.dat", comments="#", delimiter=",", unpack=False)
Swift 3 & IBInspectable solution:
Inspired by Ade's solution
First, create an UIView extension:
//
// UIView-Extension.swift
//
import Foundation
import UIKit
@IBDesignable
extension UIView {
// Shadow
@IBInspectable var shadow: Bool {
get {
return layer.shadowOpacity > 0.0
}
set {
if newValue == true {
self.addShadow()
}
}
}
fileprivate func addShadow(shadowColor: CGColor = UIColor.black.cgColor, shadowOffset: CGSize = CGSize(width: 3.0, height: 3.0), shadowOpacity: Float = 0.35, shadowRadius: CGFloat = 5.0) {
let layer = self.layer
layer.masksToBounds = false
layer.shadowColor = shadowColor
layer.shadowOffset = shadowOffset
layer.shadowRadius = shadowRadius
layer.shadowOpacity = shadowOpacity
layer.shadowPath = UIBezierPath(roundedRect: layer.bounds, cornerRadius: layer.cornerRadius).cgPath
let backgroundColor = self.backgroundColor?.cgColor
self.backgroundColor = nil
layer.backgroundColor = backgroundColor
}
// Corner radius
@IBInspectable var circle: Bool {
get {
return layer.cornerRadius == self.bounds.width*0.5
}
set {
if newValue == true {
self.cornerRadius = self.bounds.width*0.5
}
}
}
@IBInspectable var cornerRadius: CGFloat {
get {
return self.layer.cornerRadius
}
set {
self.layer.cornerRadius = newValue
}
}
// Borders
// Border width
@IBInspectable
public var borderWidth: CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
// Border color
@IBInspectable
public var borderColor: UIColor? {
set {
layer.borderColor = newValue?.cgColor
}
get {
if let borderColor = layer.borderColor {
return UIColor(cgColor: borderColor)
}
return nil
}
}
}
Then, simply select your UIView in interface builder setting shadow ON and corner radius, like below:
The result!
Changing the ng-src
value is actually very simple. Like this:
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>
Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/
Well for anyone still having the problem and I really feel very dumb after realizing this, but I passed in the url of /items
the default one while adding API. But I kept calling the endpoint with /api
. Special thanks to Carlos Alberto Schneider
, as I realized my problem after reading your post.
If you don't want to make your spring a web application then just add @EnableAsync
or @EnableScheduling
to your Starter
@EnableAsync
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
What exactly is it?
Apache Camel is a lightweight integration framework which implements many Enterprise Integration patterns.You can easily integrate different applications using the required patterns.
You can use Java, Spring XML, Scala or Groovy. Almost every technology you can imagine is available, for example HTTP, FTP, JMS, EJB, JPA, RMI, JMS, JMX, LDAP, Netty etc.
Have a look at this article and EIP pattern article
How does it interact with an application written in Java?
Camel uses a Java Domain Specific Language or DSL for creating Enterprise Integration Patterns or Routes in a variety of domain-specific languages (DSL) as listed below.
Java DSL - A Java based DSL using the fluent builder style.
The story of Enterprise Integration Pattern resolves around these concepts :
Message, End Point, Producer, Consumer, Routing, Bus, Transform and Process.
Have a look at this article By Anirban Konar for one of real time use cases.
Is it something that goes together with the server?
It acts as a bridge across multiple enterprise sub systems.
Is it an independent program?
Apache Camel, an integration framework, integrates different independent applications.
The major advantage of Camel : You can integrate different applications with different technologies (and different protocols) by using same same concepts for every integration.
Other than explicitly copying, another approach is to make the object immutable (no set
or other mutator methods). In this way the question never arises. Immutability becomes more difficult with larger objects, but that other side of that is that it pushes you in the direction of splitting into coherent small objects and composites.
Yes, it is possible. You will need to define 2 FKs for 3rd table. Each FK pointing to the required field(s) of one table (ie 1 FK per foreign table).
if you hava a logback-spring.xml or something like that, add the following code to it
<logger name="org.hibernate.SQL" level="trace" additivity="false">
<appender-ref ref="file" />
</logger>
works for me.
To get bind variables as well:
<logger name="org.hibernate.type.descriptor.sql" level="trace">
<appender-ref ref="file" />
</logger>
List<T>.Remove() and List<T>.RemoveAt() do not return the item that is being removed.
Therefore you have to use this:
var item = list[oldIndex];
list.RemoveAt(oldIndex);
list.Insert(newIndex, item);