I also had similar problems when trying to link static compiled fontconfig and expat into a linux shared object:
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/fontconfig/lib/linux-x86_64/libfontconfig.a(fccfg.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/expat/lib/linux-x86_64/libexpat.a(xmlparse.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
[...]
This contrary to the fact that I was already passing -fPIC
flags though CFLAGS
variable, and other compilers/linkers variants (clang/lld) were perfectly working with the same build configuration. It ended up that these dependencies control position-independent code settings through despicable autoconf
scripts and need --with-pic
switch during build configuration on linux gcc/ld combination, and its lack probably overrides same the setting in CFLAGS
. Pass the switch to configure
script and the dependencies will be correctly compiled with -fPIC
.
The best thing would be to set your own error and exception handlers which will do something usefull like logging it in a file or emailing critical ones. http://www.php.net/set_error_handler
This solution appears better to me, regarding maintainability and design for change:
Create the logging property file embedding it in the resource project folder, to be included in the jar file:
# Logging
handlers = java.util.logging.ConsoleHandler
.level = ALL
# Console Logging
java.util.logging.ConsoleHandler.level = ALL
Load the property file from code:
public static java.net.URL retrieveURLOfJarResource(String resourceName) {
return Thread.currentThread().getContextClassLoader().getResource(resourceName);
}
public synchronized void initializeLogger() {
try (InputStream is = retrieveURLOfJarResource("logging.properties").openStream()) {
LogManager.getLogManager().readConfiguration(is);
} catch (IOException e) {
// ...
}
}
While exporting your source into a jar, make sure you select runnable jar option from the options. Then select if you want to package all the dependency jars or just include them directly in the jar file. It depends on the project that you are working on.
You then run the jar directly by java -jar example.jar.
Try:
s = filter(str.isalnum, s)
in Python3:
s = ''.join(filter(str.isalnum, s))
Edit: realized that the OP wants to replace non-chars with '*'. My answer does not fit
You can simply call setTimeout at the end of the function. This will add it again to the event queue. You can use any kind of logic to vary the delay values. For example,
function multiStep() {
// do some work here
blah_blah_whatever();
var newtime = 60000;
if (!requestStop) {
setTimeout(multiStep, newtime);
}
}
The code below removes remove grid lines from chart area only not the ones in x&y axis labels
Chart.defaults.scale.gridLines.drawOnChartArea = false;
For Python 3:
import urllib.request, urllib.error
url = 'http://www.google.com/asdfsf'
try:
conn = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
# Return code error (e.g. 404, 501, ...)
# ...
print('HTTPError: {}'.format(e.code))
except urllib.error.URLError as e:
# Not an HTTP-specific error (e.g. connection refused)
# ...
print('URLError: {}'.format(e.reason))
else:
# 200
# ...
print('good')
That's not possible. localhost
always defaults to the loopback device on the local operating system.
As your virtual machine runs its own operating system it has its own loopback device which you cannot access from the outside.
If you want to access it e.g. in a browser, connect to it using the local IP instead:
http://192.168.180.1:8000
This is just an example of course, you can find out the actual IP by issuing an ifconfig
command on a shell in the guest operating system.
This works on SQL Server 2005 (edited to reflect your clarification):
select *
from Things t
where t.ThingID in (
select top 10 ThingID
from Things tt
where tt.Section = t.Section and tt.ThingDate = @Date
order by tt.DateEntered desc
)
and t.ThingDate = @Date
order by Section, DateEntered desc
This what helped me:
List<RepositoryFile> fileList = response.getRepositoryFileList();
RepositoryFile file1 = fileList.stream().filter(f -> f.getName().contains("my-file.txt")).findFirst().orElse(null);
Taken from Java 8 Finding Specific Element in List with Lambda
Just add style="table-layout: fixed ; width: 100%;"
inside <table>
tag and also if you do not specify any styles and add just style=" width: 100%;"
inside <table>
You will be able to resolve it.
For Boot 2.0.0+ this works for me: server.servlet.context-path = /api
Your problem stems from a misunderstanding of the or
operator that is common to people learning programming languages like this. Yes, your immediate problem can be solved by writing x ~= 0 and x ~= 1
, but I'll go into a little more detail about why your attempted solution doesn't work.
When you read x ~=(0 or 1)
or x ~= 0 or 1
it's natural to parse this as you would the sentence "x is not equal to zero or one". In the ordinary understanding of that statement, "x" is the subject, "is not equal to" is the predicate or verb phrase, and "zero or one" is the object, a set of possibilities joined by a conjunction. You apply the subject with the verb to each item in the set.
However, Lua does not parse this based on the rules of English grammar, it parses it in binary comparisons of two elements based on its order of operations. Each operator has a precedence which determines the order in which it will be evaluated. or
has a lower precedence than ~=
, just as addition in mathematics has a lower precedence than multiplication. Everything has a lower precedence than parentheses.
As a result, when evaluating x ~=(0 or 1)
, the interpreter will first compute 0 or 1
(because of the parentheses) and then x ~=
the result of the first computation, and in the second example, it will compute x ~= 0
and then apply the result of that computation to or 1
.
The logical operator or
"returns its first argument if this value is different from nil and false; otherwise, or returns its second argument". The relational operator ~=
is the inverse of the equality operator ==
; it returns true if its arguments are different types (x is a number, right?), and otherwise compares its arguments normally.
Using these rules, x ~=(0 or 1)
will decompose to x ~= 0
(after applying the or
operator) and this will return 'true' if x is anything other than 0, including 1, which is undesirable. The other form, x ~= 0 or 1
will first evaluate x ~= 0
(which may return true or false, depending on the value of x). Then, it will decompose to one of false or 1
or true or 1
. In the first case, the statement will return 1
, and in the second case, the statement will return true
. Because control structures in Lua only consider nil
and false
to be false, and anything else to be true, this will always enter the if
statement, which is not what you want either.
There is no way that you can use binary operators like those provided in programming languages to compare a single variable to a list of values. Instead, you need to compare the variable to each value one by one. There are a few ways to do this. The simplest way is to use De Morgan's laws to express the statement 'not one or zero' (which can't be evaluated with binary operators) as 'not one and not zero', which can trivially be written with binary operators:
if x ~= 1 and x ~= 0 then
print( "X must be equal to 1 or 0" )
return
end
Alternatively, you can use a loop to check these values:
local x_is_ok = false
for i = 0,1 do
if x == i then
x_is_ok = true
end
end
if not x_is_ok then
print( "X must be equal to 1 or 0" )
return
end
Finally, you could use relational operators to check a range and then test that x was an integer in the range (you don't want 0.5, right?)
if not (x >= 0 and x <= 1 and math.floor(x) == x) then
print( "X must be equal to 1 or 0" )
return
end
Note that I wrote x >= 0 and x <= 1
. If you understood the above explanation, you should now be able to explain why I didn't write 0 <= x <= 1
, and what this erroneous expression would return!
After "AND" and after "OR" the QUERY has forgotten what it is all about.
I would also not know that it is about in any SQL / programming language.
if(SOMETHING equals "X" or SOMETHING equals "Y")
COLUMN NOT LIKE "A%" AND COLUMN NOT LIKE "B%"
Catch the base exception 'Exception'
try {
//some code
} catch (Exception e) {
//catches exception and all subclasses
}
You can do this in 2 steps:
1: Change the input type(In your EditText
field) in the layout file to android:inputType="number"
2: Use int a = Integer.parseInt(yourEditTextObject.getText().toString());
SELECT datname FROM pg_database WHERE datistemplate = false
#for postgres
Check to see if the Remote Procedure Call (RPC)
service is running. If it is, then it's a firewall issue between your workstation and the server. You can test it by temporary disabling the firewall and retrying the command.
Edit after comment:
Ok, it's a firewall issue. You'll have to either limit the ports WMI/RPC work on, or open a lot of ports in the McAfee firewall.
Here are a few sites that explain this:
You can try _.isUndefined
<% if (!_.isUndefined(date)) { %><span class="date"><%= date %></span><% } %>
nload is a great tool for monitoring bandwidth in real time and easily installed in Ubuntu or Debian with sudo apt-get install nload.
Device eth0 [10.10.10.5] (1/2):
=====================================================================================
Incoming:
. ...|
# ####|
.. |#| ... #####. .. Curr: 2.07 MBit/s
###.### #### #######|. . ## | Avg: 1.41 MBit/s
########|#########################. ### Min: 1.12 kBit/s
........ ################################### .### Max: 4.49 MBit/s
.##########. |###################################|##### Ttl: 1.94 GByte
Outgoing:
########## ########### ###########################
########## ########### ###########################
##########. ########### .###########################
########### ########### #############################
########### ###########..#############################
############ ##########################################
############ ##########################################
############ ########################################## Curr: 63.88 MBit/s
############ ########################################## Avg: 32.04 MBit/s
############ ########################################## Min: 0.00 Bit/s
############ ########################################## Max: 93.23 MBit/s
############## ########################################## Ttl: 2.49 GByte
Another excellent tool is iftop, also easily apt-get'able:
191Mb 381Mb 572Mb 763Mb 954Mb
+--------------------------------------------------------------------------------
box4.local => box-2.local 91.0Mb 27.0Mb 15.1Mb
<= 1.59Mb 761kb 452kb
box4.local => box.local 560b 26.8kb 27.7kb
<= 880b 31.3kb 32.1kb
box4.local => userify.com 0b 11.4kb 8.01kb
<= 1.17kb 2.39kb 1.75kb
box4.local => b.resolvers.Level3.net 0b 58b 168b
<= 0b 83b 288b
box4.local => stackoverflow.com 0b 42b 21b
<= 0b 42b 21b
box4.local => 224.0.0.251 0b 0b 179b
<= 0b 0b 0b
224.0.0.251 => box-2.local 0b 0b 0b
<= 0b 0b 36b
224.0.0.251 => box.local 0b 0b 0b
<= 0b 0b 35b
---------------------------------------------------------------------------------
TX: cum: 37.9MB peak: 91.0Mb rates: 91.0Mb 27.1Mb 15.2Mb
RX: 1.19MB 1.89Mb 1.59Mb 795kb 486kb
TOTAL: 39.1MB 92.6Mb 92.6Mb 27.9Mb 15.6Mb
Don't forget about the classic and powerful sar and netstat utilities on older *nix!
@NoCanDo: You cannot create an array with different data types because java only supports variables with a specific data type or object. When you are creating an array, you are pulling together an assortment of similar variables -- almost like an extended variable. All of the variables must be of the same type therefore. Java cannot differentiate the data type of your variable unless you tell it what it is. Ex: int
tells all your variables declared to it are of data type int
. What you could do is create 3 arrays with corresponding information.
int bookNumber[] = {1, 2, 3, 4, 5};
int bookName[] = {nameOfBook1, nameOfBook2, nameOfBook3, nameOfBook4, nameOfBook5}
// etc.. etc..
Now, a single index number gives you all the info for that book. Ex: All of your arrays with index number 0 ([0]) have information for book 1.
num = 123
dig = 0
sum = 0
while(num > 0):
dig = int(num%10)
sum = sum+dig
num = num/10
print(sum) // make sure to add space above this line
JavaScript project on GitHub - https://github.com/LiosK/UUID.js
UUID.js The RFC-compliant UUID generator for JavaScript.
See RFC 4122 http://www.ietf.org/rfc/rfc4122.txt.
Features Generates RFC 4122 compliant UUIDs.
Version 4 UUIDs (UUIDs from random numbers) and version 1 UUIDs (time-based UUIDs) are available.
UUID object allows a variety of access to the UUID including access to the UUID fields.
Low timestamp resolution of JavaScript is compensated by random numbers.
You can try this: git add * && git reset main/dontcheckmein.txt
Just add class "show" to the collapsing element's class, bootstrap will use js dynamically to remove it to collapse and show
This is because your Page2
class doesn't have a companion object which is similar to static
in Java so to use your class. To pass your class as an argument to Intent
, you will have to do something like this
val changePage = Intent(this, Page2::class.java)
I'd also like to add that if using the three.js editor don't forget to set the background colour to clear as well in the index.html.
background-color:#00000000
You can use the next code:
JS
function showname () {
var name = document.getElementById('fileInput');
alert('Selected file: ' + name.files.item(0).name);
alert('Selected file: ' + name.files.item(0).size);
alert('Selected file: ' + name.files.item(0).type);
};
HTML
<body>
<p>
<input type="file" id="fileInput" multiple onchange="showname()"/>
</p>
</body>
Using lamda, just multiple the result with -1 to get max priority queue.
PriorityQueue<> q = new PriorityQueue<Integer>(
(a,b) -> -1 * Integer.compare(a, b)
);
Use jdbcTemplate.update(String sql, Object... args)
method:
jdbcTemplate.update(
"INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
var1, var2
);
or jdbcTemplate.update(String sql, Object[] args, int[] argTypes)
, if you need to map arguments to SQL types manually:
jdbcTemplate.update(
"INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
new Object[]{var1, var2}, new Object[]{Types.TYPE_OF_VAR1, Types.TYPE_OF_VAR2}
);
I've got a YouTube video on this.
Short answer: Use mock
when you're passing in the thing that you want mocked, and patch
if you're not. Of the two, mock is strongly preferred because it means you're writing code with proper dependency injection.
Silly example:
# Use a mock to test this.
my_custom_tweeter(twitter_api, sentence):
sentence.replace('cks','x') # We're cool and hip.
twitter_api.send(sentence)
# Use a patch to mock out twitter_api. You have to patch the Twitter() module/class
# and have it return a mock. Much uglier, but sometimes necessary.
my_badly_written_tweeter(sentence):
twitter_api = Twitter(user="XXX", password="YYY")
sentence.replace('cks','x')
twitter_api.send(sentence)
I think your question is a bit more general than I originally thought. type()
with one argument returns the type
or class
of the object. So if you have a = 'abc'
and use type(a)
this returns str
because the variable a
is a string. If b = 10
, type(b)
returns int
.
See also python documentation on type().
If you want a comparison you could use: if type(v) == h5py.h5r.Reference
(to check if it is a h5py.h5r.Reference
instance).
But it is recommended that one uses if isinstance(v, h5py.h5r.Reference)
but then also subclasses will evaluate to True
.
If you want to print the class use print v.__class__.__name__
.
More generally: You can compare if two instances have the same class by using type(v) is type(other_v)
or isinstance(v, other_v.__class__)
.
Try something like this one!
Instead of getting the context like:(this works for getting array index's)
$result['context']
try (this work for getting objects)
$result->context
Other Example is: (if $result
has multiple data values)
Array
(
[0] => stdClass Object
(
[id] => 15
[name] => 1 Pc Meal
[context] => 5
[restaurant_id] => 2
[items] =>
[details] => 1 Thigh (or 2 Drums) along with Taters
[nutrition_fact] => {"":""}
[servings] => menu
[availability] => 1
[has_discount] => {"menu":0}
[price] => {"menu":"8.03"}
[discounted_price] => {"menu":""}
[thumbnail] => YPenWSkFZm2BrJT4637o.jpg
[slug] => 1-pc-meal
[created_at] => 1612290600
[updated_at] => 1612463400
)
)
Then try this:
foreach($result as $results)
{
$results->context;
}
/usr/sbin/host `hostname`
should do the trick. Bear in mind that it's a pretty common configuration for a solaris box to have several IP addresses, though, in which case
/usr/sbin/ifconfig -a inet | awk '/inet/ {print $2}'
will list them all
A little math can give you a one-line function:
function zeroFill( number, width ) {
return Array(width - parseInt(Math.log(number)/Math.LN10) ).join('0') + number;
}
That's assuming that number
is an integer no wider than width
. If the calling routine can't make that guarantee, the function will need to make some checks:
function zeroFill( number, width ) {
var n = width - parseInt(Math.log(number)/Math.LN10);
return (n < 0) ? '' + number : Array(n).join('0') + number;
}
I have adapted the answer from @Alex above and wrote the following to fix the code for Java 9.
$ cat ~/.jdk
#!/bin/bash
#list available jdks
alias jdks="/usr/libexec/java_home -V"
# jdk version switching - e.g. `jdk 6` will switch to version 1.6
function jdk() {
echo "Switching java version $1";
requestedVersion=$1
oldStyleVersion=8
# Set the version
if [ $requestedVersion -gt $oldStyleVersion ]; then
export JAVA_HOME=$(/usr/libexec/java_home -v $1);
else
export JAVA_HOME=`/usr/libexec/java_home -v 1.$1`;
fi
echo "Setting JAVA_HOME=$JAVA_HOME"
which java
java -version;
}
$ jdk 8
Switching java version 8
Setting JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home
/usr/bin/java
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
$ jdk 9
Switching java version 9
Setting JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home
/usr/bin/java
java version "9.0.1"
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)
install vim from online, and then you can just do: vim "filename" to edit that file
Many good solutions above but I haven't seen a simple (KISS keep it simple (cause I'm) stupid use of the Python built in/generic bisect function to do a binary search. With a bit of code around the bisect function, I think I have an example below where I have tested all cases for a small string array of names. Some of the above solutions allude to/say this, but hopefully the simple code below will help anyone confused like I was.
Python bisect is used to indicate where to insert an a new value/search item into a sorted list. The below code which uses bisect_left which will return the index of the hit if the search item in the list/array is found (Note bisect and bisect_right will return the index of the element after the hit or match as the insertion point) If not found, bisect_left will return an index to the next item in the sorted list which will not == the search value. The only other case is where the search item would go at the end of the list where the index returned would be beyond the end of the list/array, and which in the code below the early exit by Python with "and" logic handles. (first condition False Python does not check subsequent conditions)
#Code
from bisect import bisect_left
names=["Adam","Donny","Jalan","Zach","Zayed"]
search=""
lenNames = len(names)
while search !="none":
search =input("Enter name to search for or 'none' to terminate program:")
if search == "none":
break
i = bisect_left(names,search)
print(i) # show index returned by Python bisect_left
if i < (lenNames) and names[i] == search:
print(names[i],"found") #return True - if function
else:
print(search,"not found") #return False – if function
##Exhaustive test cases:
##Enter name to search for or 'none' to terminate program:Zayed
##4
##Zayed found
##Enter name to search for or 'none' to terminate program:Zach
##3
##Zach found
##Enter name to search for or 'none' to terminate program:Jalan
##2
##Jalan found
##Enter name to search for or 'none' to terminate program:Donny
##1
##Donny found
##Enter name to search for or 'none' to terminate program:Adam
##0
##Adam found
##Enter name to search for or 'none' to terminate program:Abie
##0
##Abie not found
##Enter name to search for or 'none' to terminate program:Carla
##1
##Carla not found
##Enter name to search for or 'none' to terminate program:Ed
##2
##Ed not found
##Enter name to search for or 'none' to terminate program:Roger
##3
##Roger not found
##Enter name to search for or 'none' to terminate program:Zap
##4
##Zap not found
##Enter name to search for or 'none' to terminate program:Zyss
##5
##Zyss not found
Yes, this is possible. You don't have to be the current process owning the socket to close it. Consider for a moment that the remote machine, the network card, the network cable, and your OS can all cause the socket to close.
Consider also that Fiddler and Desktop VPN software can insert themselves into the network stack and show you all your traffic or reroute all your traffic.
So all you really need is either for Windows to provide an API that allows this directly, or for someone to have written a program that operates somewhat like a VPN or Fiddler and gives you a way to close sockets that pass through it.
There is at least one program (CurrPorts) that does exactly this and I used it today for the purpose of closing specific sockets on a process that was started before CurrPorts was started. To do this you must run it as administrator, of course.
Note that it is probably not easily possible to cause a program to not listen on a port (well, it is possible but that capability is referred to as a firewall...), but I don't think that was being asked here. I believe the question is "how do I selectively close one active connection (socket) to the port my program is listening on?". The wording of the question is a bit off because a port number for the undesired inbound client connection is given and it was referred to as "port" but it's pretty clear that it was a reference to that one socket and not the listening port.
I don't know about best, but this seems pretty simple to me:
Character.isDigit(str.charAt(index))
Character.isLetter(str.charAt(index))
You can define a global alias so you can invoke a short log in a more comfortable way:
git config --global alias.slog "log --pretty=oneline --abbrev-commit"
Then you can call it using git slog
(it even works with autocompletion if you have it enabled).
Use the ieee.numeric_std
library, and the appropriate vector type for the numbers you are working on (unsigned
or signed
).
Then the operators are sla
/sra
for arithmetic shifts (ie fill with sign bit on right shifts and lsb on left shifts) and sll
/srl
for logical shifts (ie fill with '0's).
You pass a parameter to the operator to define the number of bits to shift:
A <= B srl 2; -- logical shift right 2 bits
I have no idea what I was writing above (thanks to Val for pointing that out!)
Of course the correct way to shift signed
and unsigned
types is with the shift_left
and shift_right
functions defined in ieee.numeric_std
.
The shift and rotate operators sll
, ror
etc are for vectors of boolean
, bit
or std_ulogic
, and can have interestingly unexpected behaviour in that the arithmetic shifts duplicate the end-bit even when shifting left.
And much more history can be found here:
http://jdebp.eu./FGA/bit-shifts-in-vhdl.html
However, the answer to the original question is still
sig <= tmp sll number_of_bits;
An Alternative Solution to the above
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20))),
color: Colors.white,
child: ...
)
You can use BorderRadius.only() to customize the corners you wish to manage.
Question was more about XML but as annotation are more popular nowadays and it works similarly I'll show by example.
Let's create class Foo
:
public class Foo {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and two Configuration files (you can't create one):
@Configuration
public class Configuration1 {
@Bean
public Foo foo() {
Foo foo = new Foo();
foo.setName("configuration1");
return foo;
}
}
and
@Configuration
public class Configuration2 {
@Bean
public Foo foo() {
Foo foo = new Foo();
foo.setName("configuration2");
return foo;
}
}
and let's see what happens when calling foo.getName()
:
@SpringBootApplication
public class OverridingBeanDefinitionsApplication {
public static void main(String[] args) {
SpringApplication.run(OverridingBeanDefinitionsApplication.class, args);
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(
Configuration1.class, Configuration2.class);
Foo foo = applicationContext.getBean(Foo.class);
System.out.println(foo.getName());
}
}
in this example result is: configuration2
.
The Spring Container gets all configuration metadata sources and merges bean definitions in those sources. In this example there are two @Bean
s. Order in which they are fed into ApplicationContext
decide. You can flip new AnnotationConfigApplicationContext(Configuration2.class, Configuration1.class);
and result will be configuration1
.
_words = new List<string>(YourText.ToLower().Trim('\n', '\r').Split(' ').
Select(x => new string(x.Where(Char.IsLetter).ToArray())));
Or
_words = new List<string>(YourText.Trim('\n', '\r').Split(' ').
Select(x => new string(x.Where(Char.IsLetterOrDigit).ToArray())));
If you want to print the last 10 lines, use
tail(dataset, 10)
for the first 10, you could also do
head(dataset, 10)
I came across lot of posts searching for the same - "Mongodb Joins" and alternatives or equivalents. So my answer would help many other who are like me. This is the answer I would be looking for.
I am using Mongoose with Express framework. There is a functionality called Population
in place of joins.
As mentioned in Mongoose docs.
There are no joins in MongoDB but sometimes we still want references to documents in other collections. This is where population comes in.
This StackOverflow answer shows a simple example on how to use it.
I had the same problem when I was trying to upgrade from ADT 20.0.x to ADT 23.0.x on Eclipse Indigo.
To fix the issue, I had to uninstall the ADT plugin (remove feature) from Eclipse, then reinstall the newer versions.
This maybe done by going to Help->Install New Software
. Then at the bottom of the page, click What is already installed?
All what is left now is to install the newer versions as usual from help->Install New Software
.
I constantly forget the names of the colors I want to use and keep coming back to this question =)
The previous answers are great, but I find it a bit difficult to get an overview of the available colors from the posted image. I prefer the colors to be grouped with similar colors, so I slightly tweaked the matplotlib answer that was mentioned in a comment above to get a color list sorted in columns. The order is not identical to how I would sort by eye, but I think it gives a good overview.
I updated the image and code to reflect that 'rebeccapurple' has been added and the three sage colors have been moved under the 'xkcd:' prefix since I posted this answer originally.
I really didn't change much from the matplotlib example, but here is the code for completeness.
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
# Sort colors by hue, saturation, value and name.
by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgba(color)[:3])), name)
for name, color in colors.items())
sorted_names = [name for hsv, name in by_hsv]
n = len(sorted_names)
ncols = 4
nrows = n // ncols
fig, ax = plt.subplots(figsize=(12, 10))
# Get height and width
X, Y = fig.get_dpi() * fig.get_size_inches()
h = Y / (nrows + 1)
w = X / ncols
for i, name in enumerate(sorted_names):
row = i % nrows
col = i // nrows
y = Y - (row * h) - h
xi_line = w * (col + 0.05)
xf_line = w * (col + 0.25)
xi_text = w * (col + 0.3)
ax.text(xi_text, y, name, fontsize=(h * 0.8),
horizontalalignment='left',
verticalalignment='center')
ax.hlines(y + h * 0.1, xi_line, xf_line,
color=colors[name], linewidth=(h * 0.8))
ax.set_xlim(0, X)
ax.set_ylim(0, Y)
ax.set_axis_off()
fig.subplots_adjust(left=0, right=1,
top=1, bottom=0,
hspace=0, wspace=0)
plt.show()
Updated 2017-10-25. I merged my previous updates into this section.
If you would like to use additional named colors when plotting with matplotlib, you can use the xkcd crowdsourced color names, via the 'xkcd:' prefix:
plt.plot([1,2], lw=4, c='xkcd:baby poop green')
Now you have access to a plethora of named colors!
The default Tableau colors are available in matplotlib via the 'tab:' prefix:
plt.plot([1,2], lw=4, c='tab:green')
There are ten distinct colors:
You can also plot colors by their HTML hex code:
plt.plot([1,2], lw=4, c='#8f9805')
This is more similar to specifying and RGB tuple rather than a named color (apart from the fact that the hex code is passed as a string), and I will not include an image of the 16 million colors you can choose from...
For more details, please refer to the matplotlib colors documentation and the source file specifying the available colors, _color_data.py
.
edit: As lots of people seem to want to do this, I have written up a short guide with a more general use case here https://www.atlascode.com/bootstrap-fixed-width-sidebars/. Hope it helps.
The bootstrap3 grid system supports row nesting which allows you to adjust the root row to allow fixed width side menus.
You need to put in a padding-left on the root row, then have a child row which contains your normal grid layout elements.
Here is how I usually do this http://jsfiddle.net/u9gjjebj/
html
<div class="container">
<div class="row">
<div class="col-fixed-240">Fixed 240px</div>
<div class="col-fixed-160">Fixed 160px</div>
<div class="col-md-12 col-offset-400">
<div class="row">
Standard grid system content here
</div>
</div>
</div>
</div>
css
.col-fixed-240{
width:240px;
background:red;
position:fixed;
height:100%;
z-index:1;
}
.col-fixed-160{
margin-left:240px;
width:160px;
background:blue;
position:fixed;
height:100%;
z-index:1;
}
.col-offset-400{
padding-left:415px;
z-index:0;
}
Or you can just initialize inline in the controller. If you use an init function internal to the controller, it doesn't need to be defined in the scope. In fact, it can be self executing:
function MyCtrl($scope) {
$scope.isSaving = false;
(function() { // init
if (true) { // $routeParams.Id) {
//get an existing object
} else {
//create a new object
}
})()
$scope.isClean = function () {
return $scope.hasChanges() && !$scope.isSaving;
}
$scope.hasChanges = function() { return false }
}
The problem is twofold:
.
in the routeBy default, IIS treats all URI's with a dot in them as static resource, tries to return it and skip further processing (by Web API) altogether. This is configured in your Web.config in the section system.webServer.handlers
: the default handler handles path="*."
. You won't find much documentation regarding the strange syntax in this path
attribute (regex would have made more sense), but what this apparently means is "anything that doesn't contain a dot" (and any character from point 2 below). Hence the 'Extensionless' in the name ExtensionlessUrlHandler-Integrated-4.0
.
Multiple solutions are possible, in my opinion in the order of 'correctness':
path="*."
attribute to path="*"
. It will then catch everything. Note that from then on, your web api will no longer interpret incoming calls with dots as static resources! If you are hosting static resources on your web api, this is therefor not advised!<system.webserver>
: <modules runAllManagedModulesForAllRequests="true">
:
in the routeAfter you've changed the above, by default, you'd get the following error:
A potentially dangerous Request.Path value was detected from the client (:).
You can change the predefined disallowed/invalid characters in your Web.config. Under <system.web>
, add the following: <httpRuntime requestPathInvalidCharacters="<,>,%,&,*,\,?" />
. I've removed the :
from the standard list of invalid characters.
Although not an answer to your question, a safer and easier solution would be to change the request so that all this is not required. This can be done in two ways:
?date=2012-12-31T22:00:00.000Z
..000
from every request. You'd still need to allow :
's (cfr point 2).A one liner shell script to remove a file if it already exist (based on Jindra Helcl's answer):
[ -f file ] && rm file
or with a variable:
#!/bin/bash
file="/path/to/file.ext"
[ -f $file ] && rm $file
I recently stumbled upon this great Gist that gives a working implementation of a drag sort ListView
, with no external dependencies needed.
Basically it consists on creating your custom Adapter extending ArrayAdapter
as an inner class to the activity containing your ListView
. On this adapter one then sets an onTouchListener
to your List Items that will signal the start of the drag.
In that Gist they set the listener to a specific part of the layout of the List Item (the "handle" of the item), so one does not accidentally move it by pressing any part of it. Personally, I preferred to go with an onLongClickListener
instead, but that is up to you to decide. Here an excerpt of that part:
public class MyArrayAdapter extends ArrayAdapter<String> {
private ArrayList<String> mStrings = new ArrayList<String>();
private LayoutInflater mInflater;
private int mLayout;
//constructor, clear, remove, add, insert...
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View view = convertView;
//inflate, etc...
final String string = mStrings.get(position);
holder.title.setText(string);
// Here the listener is set specifically to the handle of the layout
holder.handle.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
startDrag(string);
return true;
}
return false;
}
});
// change color on dragging item and other things...
return view;
}
}
This also involves adding an onTouchListener
to the ListView
, which checks if an item is being dragged, handles the swapping and invalidation, and stops the drag state. An excerpt of that part:
mListView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
if (!mSortable) { return false; }
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
break;
}
case MotionEvent.ACTION_MOVE: {
// get positions
int position = mListView.pointToPosition((int) event.getX(),
(int) event.getY());
if (position < 0) {
break;
}
// check if it's time to swap
if (position != mPosition) {
mPosition = position;
mAdapter.remove(mDragString);
mAdapter.insert(mDragString, mPosition);
}
return true;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_OUTSIDE: {
//stop drag state
stopDrag();
return true;
}
}
return false;
}
});
Finally, here is how the stopDrag
and startDrag
methods look like, which handle the enabling and disabling of the drag process:
public void startDrag(String string) {
mPosition = -1;
mSortable = true;
mDragString = string;
mAdapter.notifyDataSetChanged();
}
public void stopDrag() {
mPosition = -1;
mSortable = false;
mDragString = null;
mAdapter.notifyDataSetChanged();
}
I think you mean to update it back to the OLD
password, when the NEW one is not supplied.
DROP TRIGGER IF EXISTS upd_user;
DELIMITER $$
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
IF (NEW.password IS NULL OR NEW.password = '') THEN
SET NEW.password = OLD.password;
ELSE
SET NEW.password = Password(NEW.Password);
END IF;
END$$
DELIMITER ;
However, this means a user can never blank out a password.
DELIMITER $$
CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
FOR EACH ROW BEGIN
IF (NEW.password IS NULL OR NEW.password = '' OR NEW.password = OLD.password) THEN
SET NEW.password = OLD.password;
ELSE
SET NEW.password = Password(NEW.Password);
END IF;
END$$
DELIMITER ;
You could use the following to replace the first occurrence of a word within the body of the page:
var replaced = $("body").html().replace('-9o0-9909','The new string');
$("body").html(replaced);
If you wanted to replace all occurrences of a word, you need to use regex and declare it global /g
:
var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string');
$("body").html(replaced);
If you wanted a one liner:
$("body").html($("body").html().replace(/12345-6789/g,'<b>abcde-fghi</b>'));
You are basically taking all of the HTML within the <body>
tags of the page into a string variable, using replace() to find and change the first occurrence of the found string with a new string. Or if you want to find and replace all occurrences of the string introduce a little regex to the mix.
See a demo here - look at the HTML top left to see the original text, the jQuery below, and the output to the bottom right.
I found a bit different cause of the error. It seems like SQLite wants to use correct primary key class property name. So...
Wrong PK name
public class Client
{
public int SomeFieldName { get; set; } // It is the ID
...
}
Correct PK name
public class Client
{
public int Id { get; set; } // It is the ID
...
}
public class Client
{
public int ClientId { get; set; } // It is the ID
...
}
It still posible to use wrong PK name but we have to use [Key] attribute like
public class Client
{
[Key]
public int SomeFieldName { get; set; } // It is the ID
...
}
This is the fastest& clean way to do that :
I'm using Jquery-->
$('selector').on('change', function () {
console.log(this.id+": "+ this.value);
});
It is working pretty fine for me.
You can create an anchor like the one showed below to download the base64 pdf:
<a download=pdfTitle href=pdfData title='Download pdf document' />
where pdfData is your base64 encoded pdf like "data:application/pdf;base64,JVBERi0xLjQKJcOkw7zDtsOfCjIgMCBvYmoKPDwvTGVuZ3RoIDMgMCBSL0ZpbHRlci9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nO1cyY4ktxG911fUWUC3kjsTaBTQ1Ytg32QN4IPgk23JMDQ2LB/0+2YsZAQzmZk1PSPIEB..."
Here's a category on SequenceType
which preserves the original order of the array, but uses a Set
to do the contains
lookups to avoid the O(n)
cost on Array's contains(_:)
method.
public extension Sequence where Element: Hashable {
/// Return the sequence with all duplicates removed.
///
/// i.e. `[ 1, 2, 3, 1, 2 ].uniqued() == [ 1, 2, 3 ]`
///
/// - note: Taken from stackoverflow.com/a/46354989/3141234, as
/// per @Alexander's comment.
func uniqued() -> [Element] {
var seen = Set<Element>()
return self.filter { seen.insert($0).inserted }
}
}
If you aren't Hashable or Equatable, you can pass in a predicate to do the equality check:
extension Sequence {
/// Return the sequence with all duplicates removed.
///
/// Duplicate, in this case, is defined as returning `true` from `comparator`.
///
/// - note: Taken from stackoverflow.com/a/46354989/3141234
func uniqued(comparator: @escaping (Element, Element) throws -> Bool) rethrows -> [Element] {
var buffer: [Element] = []
for element in self {
// If element is already in buffer, skip to the next element
if try buffer.contains(where: { try comparator(element, $0) }) {
continue
}
buffer.append(element)
}
return buffer
}
}
Now, if you don't have Hashable, but are Equatable, you can use this method:
extension Sequence where Element: Equatable {
/// Return the sequence with all duplicates removed.
///
/// i.e. `[ 1, 2, 3, 1, 2 ].uniqued() == [ 1, 2, 3 ]`
///
/// - note: Taken from stackoverflow.com/a/46354989/3141234
func uniqued() -> [Element] {
return self.uniqued(comparator: ==)
}
}
Finally, you can add a key path version of uniqued like this:
extension Sequence {
/// Returns the sequence with duplicate elements removed, performing the comparison usinig the property at
/// the supplied keypath.
///
/// i.e.
///
/// ```
/// [
/// MyStruct(value: "Hello"),
/// MyStruct(value: "Hello"),
/// MyStruct(value: "World")
/// ].uniqued(\.value)
/// ```
/// would result in
///
/// ```
/// [
/// MyStruct(value: "Hello"),
/// MyStruct(value: "World")
/// ]
/// ```
///
/// - note: Taken from stackoverflow.com/a/46354989/3141234
///
func uniqued<T: Equatable>(_ keyPath: KeyPath<Element, T>) -> [Element] {
self.uniqued { $0[keyPath: keyPath] == $1[keyPath: keyPath] }
}
}
You can stick both of these into your app, Swift will choose the right one depending on your sequence's Iterator.Element
type.
You likely want to use gpg
instead of openssl
so see "Additional Notes" at the end of this answer. But to answer the question using openssl
:
To Encrypt:
openssl enc -aes-256-cbc -in un_encrypted.data -out encrypted.data
To Decrypt:
openssl enc -d -aes-256-cbc -in encrypted.data -out un_encrypted.data
Note: You will be prompted for a password when encrypting or decrypt.
Your best source of information for openssl enc
would probably be: https://www.openssl.org/docs/man1.1.1/man1/enc.html
Command line:
openssl enc
takes the following form:
openssl enc -ciphername [-in filename] [-out filename] [-pass arg]
[-e] [-d] [-a/-base64] [-A] [-k password] [-kfile filename]
[-K key] [-iv IV] [-S salt] [-salt] [-nosalt] [-z] [-md] [-p] [-P]
[-bufsize number] [-nopad] [-debug] [-none] [-engine id]
Explanation of most useful parameters with regards to your question:
-e
Encrypt the input data: this is the default.
-d
Decrypt the input data.
-k <password>
Only use this if you want to pass the password as an argument.
Usually you can leave this out and you will be prompted for a
password. The password is used to derive the actual key which
is used to encrypt your data. Using this parameter is typically
not considered secure because your password appears in
plain-text on the command line and will likely be recorded in
bash history.
-kfile <filename>
Read the password from the first line of <filename> instead of
from the command line as above.
-a
base64 process the data. This means that if encryption is taking
place the data is base64 encoded after encryption. If decryption
is set then the input data is base64 decoded before being
decrypted.
You likely DON'T need to use this. This will likely increase the
file size for non-text data. Only use this if you need to send
data in the form of text format via email etc.
-salt
To use a salt (randomly generated) when encrypting. You always
want to use a salt while encrypting. This parameter is actually
redundant because a salt is used whether you use this or not
which is why it was not used in the "Short Answer" above!
-K key
The actual key to use: this must be represented as a string
comprised only of hex digits. If only the key is specified, the
IV must additionally be specified using the -iv option. When
both a key and a password are specified, the key given with the
-K option will be used and the IV generated from the password
will be taken. It probably does not make much sense to specify
both key and password.
-iv IV
The actual IV to use: this must be represented as a string
comprised only of hex digits. When only the key is specified
using the -K option, the IV must explicitly be defined. When a
password is being specified using one of the other options, the
IV is generated from this password.
-md digest
Use the specified digest to create the key from the passphrase.
The default algorithm as of this writing is sha-256. But this
has changed over time. It was md5 in the past. So you might want
to specify this parameter every time to alleviate problems when
moving your encrypted data from one system to another or when
updating openssl to a newer version.
Though you have specifically asked about OpenSSL you might want to consider using GPG instead for the purpose of encryption based on this article OpenSSL vs GPG for encrypting off-site backups?
To use GPG to do the same you would use the following commands:
To Encrypt:
gpg --output encrypted.data --symmetric --cipher-algo AES256 un_encrypted.data
To Decrypt:
gpg --output un_encrypted.data --decrypt encrypted.data
Note: You will be prompted for a password when encrypting or decrypt.
You also might want to check if the file already exists to avoid replacing the file by accident (unless that is the idea of course:
Dim filepath as String = "C:\my files\2010\SomeFileName.txt"
If Not System.IO.File.Exists(filepath) Then
System.IO.File.Create(filepath).Dispose()
End If
I manage to solve it by hitting a update button
I generally use a small jQuery snippet globally to open any external links in a new tab / window. I've added the selector for a form for my own site and it works fine so far:
// URL target
$('a[href*="//"]:not([href*="'+ location.hostname +'"]),form[action*="//"]:not([href*="'+ location.hostname +'"]').attr('target','_blank');
In a more functional programming style, you could use array_reduce
$groupedById = array_reduce($data, function (array $accumulator, array $element) {
$accumulator[$element['id']][] = $element;
return $accumulator;
}, []);
Just right click on the Visual Studio icon and then select "New Window" from the contextual toolbar that appears on the bottom in Windows 8. A new instance of Visual Studio will launch and then you can open your second project.
You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.
I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).
To install it, you can either download it from the linked website or use the command:
pip install pyinstaller
...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:
pyinstaller myscript.py
You can find more information about how to use Pyinstaller and customize the build process via the documentation.
You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.
Database licences are not cheep and are often charged per CPU, therefore by separating out your web-servers you can reduce the cost of your database licences.
E.g if you have 1 server doing both web and database that contains 8 CPUs you will have to pay for an 8 cpu licence. However if you have two servers each with 4 CPUs and runs the database on one server you will only have to pay for a 4 cpu licences
In a git bash session, you can add a script to ~/.profile
or ~/.bashrc
(with ~
being usually set to %USERPROFILE%
), in order for said session to launch automatically the ssh-agent
. If the file doesn't exist, just create it.
This is what GitHub describes in "Working with SSH key passphrases".
The "Auto-launching ssh-agent on Git for Windows" section of that article has a robust script that checks if the agent is running or not. Below is just a snippet, see the GitHub article for the full solution.
# This is just a snippet. See the article above.
if ! agent_is_running; then
agent_start
ssh-add
elif ! agent_has_keys; then
ssh-add
fi
Other Resources:
"Getting ssh-agent to work with git run from windows command shell" has a similar script, but I'd refer to the GitHub article above primarily, which is more robust and up to date.
Apologies in advance for this lo-tech suggestion, but another option, which finally worked for me after battling NuGet for several hours, is to re-create a new empty project, Web API in my case, and just copy the guts of your old, now-broken project into the new one. Took me about 15 minutes.
base but probably slow:
n <- 1
for(i in strsplit(as.character(before$type),'_and_')){
before[n, 'type_1'] <- i[[1]]
before[n, 'type_2'] <- i[[2]]
n <- n + 1
}
## attr type type_1 type_2
## 1 1 foo_and_bar foo bar
## 2 30 foo_and_bar_2 foo bar_2
## 3 4 foo_and_bar foo bar
## 4 6 foo_and_bar_2 foo bar_2
tl;dr: Use a host fragment that is responsible for replacing its hosted content and keeps track of a back navigation history (like in a browser).
As your use case consists of a fixed amount of tabs my solution works well: The idea is to fill the ViewPager with instances of a custom class HostFragment
, that is able to replace its hosted content and keeps its own back navigation history. To replace the hosted fragment you make a call to the method hostfragment.replaceFragment()
:
public void replaceFragment(Fragment fragment, boolean addToBackstack) {
if (addToBackstack) {
getChildFragmentManager().beginTransaction().replace(R.id.hosted_fragment, fragment).addToBackStack(null).commit();
} else {
getChildFragmentManager().beginTransaction().replace(R.id.hosted_fragment, fragment).commit();
}
}
All that method does is to replace the frame layout with the id R.id.hosted_fragment
with the fragment provided to the method.
Check my tutorial on this topic for further details and a complete working example on GitHub!
According to official documentation, you can set or remove the "executable" flag on any tracked file using update-index
sub-command.
To set the flag, use following command:
git update-index --chmod=+x path/to/file
To remove it, use:
git update-index --chmod=-x path/to/file
Under the hood
While this looks like the regular unix files permission system, actually it is not. Git maintains a special "mode" for each file in its internal storage:
100644
for regular files100755
for executable onesYou can visualize it using ls-file
subcommand, with --stage
option:
$ git ls-files --stage
100644 aee89ef43dc3b0ec6a7c6228f742377692b50484 0 .gitignore
100755 0ac339497485f7cc80d988561807906b2fd56172 0 my_executable_script.sh
By default, when you add a file to a repository, Git will try to honor its filesystem attributes and set the correct filemode accordingly. You can disable this by setting core.fileMode
option to false:
git config core.fileMode false
Troubleshooting
If at some point the Git filemode is not set but the file has correct filesystem flag, try to remove mode and set it again:
git update-index --chmod=-x path/to/file
git update-index --chmod=+x path/to/file
Bonus
Starting with Git 2.9, you can stage a file AND set the flag in one command:
git add --chmod=+x path/to/file
To list all of the packages in the active environment, use:
conda list
To list all of the packages in a deactivated environment, use:
conda list -n myenv
The parameters that you are passing into the DrawImage method should be the size you want the image on the paper rather than the size of the image itself, the DrawImage command will then take care of the scaling for you. Probably the easiest way is to use the following override of the DrawImage command.
args.Graphics.DrawImage(i, args.MarginBounds);
Note: This will skew the image if the proportions of the image are not the same as the rectangle. Some simple math on the size of the image and paper size will allow you to create a new rectangle that fits in the bounds of the paper without skewing the image.
In some cases, Jason's answer is overkill. And $('.ui-widget-overlay').click(function(){ $("#dialog").dialog("close"); });
doesn't always work with dynamic content.
The solution that I find works in all cases is:
$('body').on('click','.ui-widget-overlay',function(){ $('#dialog').dialog('close'); });
If you want to convert a single VARBINARY
value into VARCHAR
(STRING
) you can do by declaring a variable like this:
DECLARE @var VARBINARY(MAX)
SET @var = 0x21232F297A57A5A743894A0E4A801FC3
SELECT CAST(@var AS VARCHAR(MAX))
If you are trying to select from table column then you can do like this:
SELECT CAST(myBinaryCol AS VARCHAR(MAX))
FROM myTable
Probably the most efficient method, if you're using the bash
shell (and you appear to be, based on your comments), is to use the sub-string variant of parameter expansion:
pax> long="USCAGol.blah.blah.blah"
pax> short="${long:0:2}" ; echo "${short}"
US
This will set short
to be the first two characters of long
. If long
is shorter than two characters, short
will be identical to it.
This in-shell method is usually better if you're going to be doing it a lot (like 50,000 times per report as you mention) since there's no process creation overhead. All solutions which use external programs will suffer from that overhead.
If you also wanted to ensure a minimum length, you could pad it out before hand with something like:
pax> long="A"
pax> tmpstr="${long}.."
pax> short="${tmpstr:0:2}" ; echo "${short}"
A.
This would ensure that anything less than two characters in length was padded on the right with periods (or something else, just by changing the character used when creating tmpstr
). It's not clear that you need this but I thought I'd put it in for completeness.
Having said that, there are any number of ways to do this with external programs (such as if you don't have bash
available to you), some of which are:
short=$(echo "${long}" | cut -c1-2)
short=$(echo "${long}" | head -c2)
short=$(echo "${long}" | awk '{print substr ($0, 0, 2)}'
short=$(echo "${long}" | sed 's/^\(..\).*/\1/')
The first two (cut
and head
) are identical for a single-line string - they basically both just give you back the first two characters. They differ in that cut
will give you the first two characters of each line and head
will give you the first two characters of the entire input
The third one uses the awk
sub-string function to extract the first two characters and the fourth uses sed
capture groups (using ()
and \1
) to capture the first two characters and replace the entire line with them. They're both similar to cut
- they deliver the first two characters of each line in the input.
None of that matters if you are sure your input is a single line, they all have an identical effect.
You can pass data as the third argument to call()
. Or, depending on your API, it's possible you may want to use the sixth parameter.
From the docs:
$this->call($method, $uri, $parameters, $files, $server, $content);
Here is a general SQL query syntax to join three or more table. This SQL query should work in all major relation database e.g. MySQL, Oracle, Microsoft SQLServer, Sybase and PostgreSQL :
SELECT t1.col, t3.col FROM table1 join table2 ON table1.primarykey = table2.foreignkey
join table3 ON table2.primarykey = table3.foreignkey
We first join table 1 and table 2 which produce a temporary table with combined data from table1 and table2, which is then joined to table3. This formula can be extended for more than 3 tables to N tables, You just need to make sure that SQL query should have N-1 join statement in order to join N tables. like for joining two tables we require 1 join statement and for joining 3 tables we need 2 join statement.
Compress your .sql
file, and make sure to name it .[format].[compression]
, i.e.
database.sql.zip
.
As noted above, PhpMyAdmin throws this error if your .sql
file is larger than the Maximum allowed upload size -- but, in my case the maximum was 50MiB despite that I had set all options noted in previous answers (look for the "Max: 50MiB" next to the upload button in PhpMyAdmin).
Use css calc()
Super simple and awesome.
input {
width: -moz-calc(100% - 15px);
width: -webkit-calc(100% - 15px);
width: calc(100% - 15px);
}?
As seen here: Div width 100% minus fixed amount of pixels
By webvitaly (https://stackoverflow.com/users/713523/webvitaly)
Original source: http://web-profile.com.ua/css/dev/css-width-100prc-minus-100px/
Just copied this over here, because I almost missed it in the other thread.
I think this is very easy to do with very few lines. here is my solution
.buttonToLink{
background: none;
border: none;
color: red
}
.buttonToLink:hover{
background: none;
text-decoration: underline;
}
_x000D_
<button class="buttonToLink">A simple link button</button>
_x000D_
Just for reference if anyone is still struggling with mongorestore.
You have to run monogorestore in terminal/command prompt and not in mongo console.
$ mongorestore -d db_name /path_to_mongo_dump/
for more details you can visit official documentations
https://docs.mongodb.com/manual/reference/program/mongorestore/
The most important part about $ is that it has the lowest operator precedence.
If you type info you'll see this:
?> :info ($)
($) :: (a -> b) -> a -> b
-- Defined in ‘GHC.Base’
infixr 0 $
This tells us it is an infix operator with right-associativity that has the lowest possible precedence. Normal function application is left-associative and has highest precedence (10). So $ is something of the opposite.
So then we use it where normal function application or using () doesn't work.
So, for example, this works:
?> head . sort $ "example"
?> e
but this does not:
?> head . sort "example"
because . has lower precedence than sort and the type of (sort "example") is [Char]
?> :type (sort "example")
(sort "example") :: [Char]
But . expects two functions and there isn't a nice short way to do this because of the order of operations of sort and .
Update: Angular 1.1.5 added a ternary operator, so now we can simply write
<li ng-class="$first ? 'firstRow' : 'nonFirstRow'">
If you are using an earlier version of Angular, your two choices are:
(condition && result_if_true || !condition && result_if_false)
{true: 'result_if_true', false: 'result_if_false'}[condition]
item 2. above creates an object with two properties. The array syntax is used to select either the property with name true or the property with name false, and return the associated value.
E.g.,
<li class="{{{true: 'myClass1 myClass2', false: ''}[$first]}}">...</li>
or
<li ng-class="{true: 'myClass1 myClass2', false: ''}[$first]">...</li>
$first is set to true inside an ng-repeat for the first element, so the above would apply class 'myClass1' and 'myClass2' only the first time through the loop.
With ng-class there is an easier way though: ng-class takes an expression that must evaluate to one of the following:
An example of 1) was given above. Here is an example of 3, which I think reads much better:
<li ng-class="{myClass: $first, anotherClass: $index == 2}">...</li>
The first time through an ng-repeat loop, class myClass is added. The 3rd time through ($index starts at 0), class anotherClass is added.
ng-style takes an expression that must evaluate to a map/object of CSS style names to CSS values. E.g.,
<li ng-style="{true: {color: 'red'}, false: {}}[$first]">...</li>
Take a look at the documentation for HttpServletRequest
.
In order to build the URL in your example you will need to use:
getScheme()
getServerName()
getServerPort()
getContextPath()
Here is a method that will return your example:
public static String getURLWithContextPath(HttpServletRequest request) {
return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
}
You are looking for the __getitem__
method. See http://docs.python.org/reference/datamodel.html, section 3.4.6
In regards Jared's response, having Windows 2000 or better will not necessarily fix the issue at hand. Rob's response does work, however it is possible that this fix introduces security issues, as Windows updates will not be able to patch applications built as such.
In another post, Nick Guerrera suggests packaging the Visual C++ Runtime Redistributable with your applications, which installs quickly, and is independent of Visual Studio.
When you add a foreign key constraint to a table using ALTER TABLE, remember to create the required indexes first.
Here's a nice article that shows many ways of hiding files from search engines:
JavaScript isn't a good way not to index a page; it won't prevent users from linking directly to your files (and thus revealing it to crawlers), and as Rob mentioned, wouldn't work for all users.
An easy fix is to add the rel="nofollow"
attribute, though again, it's not complete without robots.txt.
<a href="uploads/file.doc" rel="nofollow">Download Here</a>
The following solution worked for me in Bootstrap 3.3.4:
CSS:
/*no collapse*/
.navbar-collapse.collapse.off {
display: block!important;
}
.navbar-collapse.collapse.off ul {
margin: 0;
padding: 0;
}
.navbar-nav.no-collapse>li,
.navbar-nav.no-collapse {
float: left !important;
}
.navbar-right.no-collapse {
float: right!important;
}
then add the .no-collapse class to each of the lists and the .off class to the main container. Here is an example written in jade:
nav.navbar.navbar-default.navbar-fixed-top
.container-fluid
.collapse.navbar-collapse.off
ul.nav.navbar-nav.no-collapse
li
a(href='#' class='glyph')
i(class='glyphicon glyphicon-info-sign')
ul.nav.navbar-nav.navbar-right.no-collapse
li.dropdown
a.dropdown-toggle(href='#', data-toggle='dropdown' role='button' aria-expanded='false')
| Tools
span.caret
ul.dropdown-menu(role='menu')
li
a(href='#') Tool #1
li
a(href='#')
| Logout
please have look at compressImage method i have used for compressing image.
public static String compressImage(String imageUri, Activity activity) {
String filename = "";
try {
String filePath = getRealPathFromURI(imageUri, activity);
Bitmap scaledBitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
float maxHeight = 816.0f;
float maxWidth = 612.0f;
float imgRatio = actualWidth / actualHeight;
float maxRatio = maxWidth / maxHeight;
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
options.inJustDecodeBounds = false;
options.inDither = false;
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
try {
bmp = BitmapFactory.decodeFile(filePath, options);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
try {
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float) options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas;
if (scaledBitmap != null) {
canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
}
ExifInterface exif;
try {
exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
} else if (orientation == 3) {
matrix.postRotate(180);
} else if (orientation == 8) {
matrix.postRotate(270);
}
if (scaledBitmap != null) {
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
}
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream out;
filename = getFilename(activity);
try {
out = new FileOutputStream(filename);
if (scaledBitmap != null) {
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return filename;
}
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
final float totalPixels = width * height;
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}
private static String getRealPathFromURI(String contentURI, Activity activity) {
Uri contentUri = Uri.parse(contentURI);
Cursor cursor = activity.getContentResolver().query(contentUri, null, null, null, null);
if (cursor == null) {
return contentUri.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
I would use the Windows Scheduler to schedule a restart of your service. The problem is that you can't restart yourself, but you can stop yourself. (You've essentially sawed off the branch that you're sitting on... if you get my analogy) You need a separate process to do it for you. The Windows Scheduler is an appropriate one. Schedule a one-time task to restart your service (even from within the service itself) to execute immediately.
Otherwise, you'll have to create a "shepherding" process that does it for you.
If you want to have access to the id
attribute of the button in angular 6 follow this code
`@Component({
selector: 'my-app',
template: `
<button (click)="clicked($event)" id="myId">Click Me</button>
`
})
export class AppComponent {
clicked(event) {
const target = event.target || event.srcElement || event.currentTarget;
const idAttr = target.attributes.id;
const value = idAttr.nodeValue;
}
}`
your id
in the value,
the value of value
is myId
.
This will do it for you:
=IF(OR(ISNUMBER(SEARCH("Gingrich",C3)),ISNUMBER(SEARCH("Obama",C3))),"1","")
Given this function in the column to the right of the names (which are in column C), the result is:
Romney
Gingrich 1
Obama 1
I got the same problem, the height of my menu bar provided by bootstrap was too big, actually i downloaded some wrong bootstrap, finally get rid of it by downloading the orignal bootstrap from this site.. http://getbootstrap.com/2.3.2/ want to use bootstrap in yii( netbeans) follow this tutorial, https://www.youtube.com/watch?v=XH_qG8gphaw... The voice is not present but the steps are slow you can easily understand and implement them. Thanks
Type in nc -h and see if You have -e option available. If yes, You can create a script, for example:
script.sh
echo -e "HTTP/1.1 200 OK\n\n $(date)"
and run it like this:
while true ; do nc -l -p 1500 -e script.sh; done
Note that -e option needs to be enabled at compilation to be available.
The java.util.logging
package is standard in Java SE. Its Logger
includes an overloaded log method that accepts Throwable
objects.
It will log stacktraces of exceptions and their cause for you.
For example:
import java.util.logging.Level;
import java.util.logging.Logger;
[...]
Logger logger = Logger.getAnonymousLogger();
Exception e1 = new Exception();
Exception e2 = new Exception(e1);
logger.log(Level.SEVERE, "an exception was thrown", e2);
Will log:
SEVERE: an exception was thrown
java.lang.Exception: java.lang.Exception
at LogStacktrace.main(LogStacktrace.java:21)
Caused by: java.lang.Exception
at LogStacktrace.main(LogStacktrace.java:20)
Internally, this does exactly what @philipp-wendler suggests, by the way.
See the source code for SimpleFormatter.java
. This is just a higher level interface.
(function() {
var ev = new $.Event('display'),
orig = $.fn.css;
$.fn.css = function() {
orig.apply(this, arguments);
$(this).trigger(ev);
}
})();
$('#element').bind('display', function(e) {
alert("display has changed to :" + $(this).attr('style') );
});
$('#element').css("display", "none")// i change the style in this line !!
$('#element').css("display", "block")// i change the style in this line !!
http://fiddle.jshell.net/prollygeek/gM8J2/3/
changes will be alerted.
I'm positive it would require SMTP authentication credentials as well.
First, some similarities that have not been mentioned yet. Ruby supports open classes, but modules as open too. After all, Class inherits from Module in the Class inheritance chain and so Class and Module do have some similar behavior.
But you need to ask yourself what is the purpose of having both a Class and a Module in a programming language? A class is intended to be a blueprint for creating instances, and each instance is a realized variation of the blueprint. An instance is just a realized variation of a blueprint (the Class). Naturally then, Classes function as object creation. Furthermore, since we sometimes want one blueprint to derive from another blueprint, Classes are designed to support inheritance.
Modules cannot be instantiated, do not create objects, and do not support inheritance. So remember one module does NOT inherit from another!
So then what is the point of having Modules in a language? One obvious usage of Modules is to create a namespace, and you will notice this with other languages too. Again, what's cool about Ruby is that Modules can be reopened (just as Classes). And this is a big usage when you want to reuse a namespace in different Ruby files:
module Apple
def a
puts 'a'
end
end
module Apple
def b
puts 'b'
end
end
class Fruit
include Apple
end
> f = Fruit.new
=> #<Fruit:0x007fe90c527c98>
> f.a
=> a
> f.b
=> b
But there is no inheritance between modules:
module Apple
module Green
def green
puts 'green'
end
end
end
class Fruit
include Apple
end
> f = Fruit.new
=> #<Fruit:0x007fe90c462420>
> f.green
NoMethodError: undefined method `green' for #<Fruit:0x007fe90c462420>
The Apple module did not inherit any methods from the Green module and when we included Apple in the Fruit class, the methods of the Apple module are added to the ancestor chain of Apple instances, but not methods of the Green module, even though the Green module was defined in the Apple module.
So how do we gain access to the green method? You have to explicitly include it in your class:
class Fruit
include Apple::Green
end
=> Fruit
> f.green
=> green
But Ruby has another important usage for Modules. This is the Mixin facility, which I describe in another answer on SO. But to summarize, mixins allow you to define methods into the inheritance chain of objects. Through mixins, you can add methods to the inheritance chain of object instances (include) or the singleton_class of self (extend).
Source: https://github.com/codepath/android_guides/wiki/Understanding-the-Android-Application-Class
In many apps, there's no need to work with an application class directly. However, there are a few acceptable uses of a custom application class:
- Specialized tasks that need to run before the creation of your first activity
- Global initialization that needs to be shared across all components (crash reporting, persistence)
- Static methods for easy access to static immutable data such as a shared network client object
You should never store mutable instance data inside the Application object because if you assume that your data will stay there, your application will inevitably crash at some point with a NullPointerException. The application object is not guaranteed to stay in memory forever, it will get killed. Contrary to popular belief, the app won’t be restarted from scratch. Android will create a new Application object and start the activity where the user was before to give the illusion that the application was never killed in the first place.
I rather use Virtualenv to install such packages rather than the entire system, saves time and effort rather than building from source.
I use virtualenvwrapper
Windows user can download
pip install virtualenvwrapper-win
https://pypi.org/project/virtualenvwrapper-win/
Linux follow
pip install opencv-python
If processing a video is required
pip install opencv-contrib-python
If you do not need GUI in Opencv
pip install opencv-contrib-python-headless
Your PFX file should contain the private key within it. Export the private key and certificate directly from your PFX file (e.g. using OpenSSL) and import them into your Java keystore.
Edit
Further information:
openssl pkcs12 -in filename.pfx -nocerts -out key.pem
openssl pkcs12 -in filename.pfx -clcerts -nokeys -out cert.pem
keytool
.In Swift 4.2 and Xcode 10
var spinnerView: UIView? //This is your view
spinnerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
//Based on your requirement change width and height like self.view.bounds.size.width
spinnerView?.backgroundColor = UIColor.black.withAlphaComponent(0.6)
// self.view.addSubview(spinnerView)
let currentWindow: UIWindow? = UIApplication.shared.keyWindow
currentWindow?.addSubview(spinnerView!)
In Objective C
UIView *spinnerView;//This is your view
self.spinnerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height)];
//Based on your requirement change width and height like self.view.bounds.size.width
self.spinnerView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
// [self.view addSubview:self.spinnerView];
UIWindow *currentWindow = [UIApplication sharedApplication].keyWindow;
[currentWindow addSubview:self.spinnerView];
This can work either Portrait OR Landscape mode only.
One more simple code is:
yourViewName.layer.zPosition = 1//Change you view name
I've played around with it and I think I have a solution. The following example shows how to set Box-Shadow so that it will only show a shadow for the inset top and bottom of an element.
Legend: insetOption leftPosition topPosition blurStrength spreadStrength color
Description
The key to accomplishing this is to set the blur value to <= the negative of the spread value (ex. inset 0px 5px -?px 5px #000; the blur value should be -5 and lower) and to also keep the blur value > 0 when subtracted from the primary positioning value (ex. using the example from above, the blur value should be -9 and up, thus giving us an optimal value for the the blur to be between -5 and -9).
Solution
.styleName {
/* for IE 8 and lower */
background-color:#888; filter: progid:DXImageTransform.Microsoft.dropShadow(color=#FFFFCC, offX=0, offY=0, positive=true);
/* for IE 9 */
box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7);
/* for webkit browsers */
-webkit-box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7);
/* for firefox 3.6+ */
-moz-box-shadow: inset 0px 2px -2px 2px rgba(255,255,204,0.7), inset 0px -2px -2px 2px rgba(255,255,204,0.7);
}
Related answer, but if you want to run clean up a user inputting values into a form, here's what you can do:
const numFormatter = new Intl.NumberFormat('en-US', {
style: "decimal",
maximumFractionDigits: 2
})
// Good Inputs
parseFloat(numFormatter.format('1234').replace(/,/g,"")) // 1234
parseFloat(numFormatter.format('123').replace(/,/g,"")) // 123
// 3rd decimal place rounds to nearest
parseFloat(numFormatter.format('1234.233').replace(/,/g,"")); // 1234.23
parseFloat(numFormatter.format('1234.239').replace(/,/g,"")); // 1234.24
// Bad Inputs
parseFloat(numFormatter.format('1234.233a').replace(/,/g,"")); // NaN
parseFloat(numFormatter.format('$1234.23').replace(/,/g,"")); // NaN
// Edge Cases
parseFloat(numFormatter.format(true).replace(/,/g,"")) // 1
parseFloat(numFormatter.format(false).replace(/,/g,"")) // 0
parseFloat(numFormatter.format(NaN).replace(/,/g,"")) // NaN
Use the international date local via format
. This cleans up any bad inputs, if there is one it returns a string of NaN
you can check for. There's no way currently of removing commas as part of the locale (as of 10/12/19), so you can use a regex command to remove commas using replace
.
ParseFloat
converts the this type definition from string to number
If you use React, this is what your calculate function could look like:
updateCalculationInput = (e) => {
let value;
value = numFormatter.format(e.target.value); // 123,456.78 - 3rd decimal rounds to nearest number as expected
if(value === 'NaN') return; // locale returns string of NaN if fail
value = value.replace(/,/g, ""); // remove commas
value = parseFloat(value); // now parse to float should always be clean input
// Do the actual math and setState calls here
}
There are two storage areas involved: the stack and the heap.The stack is where the current state of a method call is kept (ie local variables and references), and the heap is where objects are stored. recursion and memory
I gues there are too many keys in the counter
dict that will consume too much memory of the heap region, so the Python runtime will raise a OutOfMemory exception.
To save it, don't create a giant object, e.g. the counter.
1.StackOverflow
a program that create too many local variables.
Python 2.7.9 (default, Mar 1 2015, 12:57:24)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('stack_overflow.py','w')
>>> f.write('def foo():\n')
>>> for x in xrange(10000000):
... f.write('\tx%d = %d\n' % (x, x))
...
>>> f.write('foo()')
>>> f.close()
>>> execfile('stack_overflow.py')
Killed
2.OutOfMemory
a program that creats a giant dict
includes too many keys.
>>> f = open('out_of_memory.py','w')
>>> f.write('def foo():\n')
>>> f.write('\tcounter = {}\n')
>>> for x in xrange(10000000):
... f.write('counter[%d] = %d\n' % (x, x))
...
>>> f.write('foo()\n')
>>> f.close()
>>> execfile('out_of_memory.py')
Killed
Collections by themselves do not have a predefined order, therefore you must convert them to
a java.util.List
. Then you can use one form of java.util.Collections.sort
Collection< T > collection = ...;
List< T > list = new ArrayList< T >( collection );
Collections.sort( list );
// or
Collections.sort( list, new Comparator< T >( ){...} );
// list now is sorted
To rename a table in SQL Server, use the sp_rename
command:
exec sp_rename 'schema.old_table_name', 'new_table_name'
Here is another solution:
>>>list1=["C:\\","D:\\","E:\\","C:\\"]
>>>set1=set(list1)
>>>set1
set(['E:\\', 'D:\\', 'C:\\'])
In this code I have used the set method in order to turn it into a set and then it removed all duplicate values from the list
First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:
global $db;
And I guess, when you wrote:
if($result->num_rows){
return (mysqli_result($query, 0) == 1) ? true : false;
what you really wanted was:
if ($result->num_rows==1) { return true; } else { return false; }
I'm an Excel developer, and I definitely felt the pain when this happened. Fortunately, I was able to find a workaround by renaming the MSForms.exd files in VBA even when Excel is running, which also can fix the issue. Excel developers who need to distribute their spreadsheets can add the following VBA code to their spreadsheets to make them immune to the MS update.
Place this code in any module.
Public Sub RenameMSFormsFiles()
Const tempFileName As String = "MSForms - Copy.exd"
Const msFormsFileName As String = "MSForms.exd"
On Error Resume Next
'Try to rename the C:\Users\[user.name]\AppData\Local\Temp\Excel8.0\MSForms.exd file
RenameFile Environ("TEMP") & "\Excel8.0\" & msFormsFileName, Environ("TEMP") & "\Excel8.0\" & tempFileName
'Try to rename the C:\Users\[user.name]\AppData\Local\Temp\VBE\MSForms.exd file
RenameFile Environ("TEMP") & "\VBE\" & msFormsFileName, Environ("TEMP") & "\VBE\" & tempFileName
End Sub
Private Sub RenameFile(fromFilePath As String, toFilePath As String)
If CheckFileExist(fromFilePath) Then
DeleteFile toFilePath
Name fromFilePath As toFilePath
End If
End Sub
Private Function CheckFileExist(path As String) As Boolean
CheckFileExist = (Dir(path) <> "")
End Function
Private Sub DeleteFile(path As String)
If CheckFileExist(path) Then
SetAttr path, vbNormal
Kill path
End If
End Sub
The RenameMSFormsFiles subroutine tries to rename the MSForms.exd files in the C:\Users\[user.name]\AppData\Local\Temp\Excel8.0\
and C:\Users\[user.name]\AppData\Local\Temp\VBE\
folders to MSForms - Copy.exd.
Then call the RenameMSFormsFiles subroutine at the very beginning of the Workbook_Open event.
Private Sub Workbook_Open()
RenameMSFormsFiles
End Sub
The spreadsheet will try to rename the MSForms.exd files when it opens. Obviously, this is not a perfect fix:
At least for now, Excel developers can continue to distribute their work with this workaround until Microsoft releases a fix.
I've posted this solution here.
How I solve this problem? Use git fsck
and logging!
First create a file containing lost (unreachable) commits and blobs. (NOTE: if you did something like git gc
then it will garbage collect all of they commits and you won't find them here!)
$git fsck --lost-found > lost_found.commits
That gives you a file like this:
dangling commit dec2c5e72a81ef06963397a49c4b068540fc0dc3
dangling blob f8c2579e6cbfe022f08345fa7553feb08d60a975
dangling blob 0eb3e86dc112332ceadf9bc826c49bd371acc194
dangling blob 11cbd8eba79e01f4fd7f496b1750953146a09502
dangling commit 18733e44097d2c7a800650cea442febc5344f9b3
dangling blob 1e53a5cdb3ecdde27081ec6e8b31e4070106ee05
You can then open this file with you favorite text editor to copy the commit/blog hashes from there. (*cough* vim macros works great for this *cough*)
Now you can log back from this commit with something like git log --oneline <commit hash>
.
Alternatively, gitk, tig, or any other git viewer should work.
In your case if you find the hash for commit F the log will show you something like this,
A---B---E---F
Quick and easy! Now you can find the context behind all of those dangling commits.
P.S. Yes, I know, late post, but oh well, somebody might find it here and find it useful. (Mostly likely me in 6 months when I google this again)
Look into android.util.Log
. It lets you write to the log with various log levels, and you can specify different tags to group the output.
For example
Log.w("myApp", "no network");
will output a warning with the tag myApp and the message no network.
I'm assuming mysql_fetch_array() perfroms a loop, so I'm interested in if using a while() in conjunction with it, if it saves a nested loop.
No. mysql_fetch_array
just returns the next row of the result and advances the internal pointer. It doesn't loop. (Internally it may or may not use some loop somewhere, but that's irrelevant.)
while ($row = mysql_fetch_array($result)) {
...
}
This does the following:
mysql_fetch_array
retrieves and returns the next row$row
true
, the contents of the loop are executed$row = mysql_fetch_array($result); foreach($row as $r) { ... }
This does the following:
mysql_fetch_array
retrieves and returns the next row$row
foreach
loops over the contents of the array and executes the contents of the loop as many times as there are items in the arrayIn both cases mysql_fetch_array
does exactly the same thing. You have only as many loops as you write. Both constructs do not do the same thing though. The second will only act on one row of the result, while the first will loop over all rows.
import csv
hello = [['Me','You'],['293', '219'],['13','15']]
length = len(hello[0])
with open('test1.csv', 'wb') as testfile:
csv_writer = csv.writer(testfile)
for y in range(length):
csv_writer.writerow([x[y] for x in hello])
will produce an output like this
Me You
293 219
13 15
Hope this helps
Instead of doing findElement, do findElements and check the length of the returned elements is 0. This is how I'm doing using WebdriverJS and I expect the same will work in Java
The one mahesh posted is not working because the attribute name is missing:
So instead of
<input id="list" class="required" />
You can use:
<input id="list" name="list" class="required" />
You can use
start "" "%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"
or
start "" /D "%USERPROFILE%\Desktop\BGInfo" bginfo.exe dc_bginfo.bgi
or
"%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"
or
cd /D "%USERPROFILE%\Desktop\BGInfo"
bginfo.exe dc_bginfo.bgi
Help on commands start and cd is output by executing in a command prompt window help start
or start /?
and help cd
or cd /?
.
But I do not understand why you need a batch file at all for starting the application with the additional parameter. Create a shortcut (*.lnk) on your desktop for this application. Then right click on the shortcut, left click on Properties and append after a space character "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"
as parameter.
How about print (x, y)
at once.
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54
plt.plot(A,B)
for xy in zip(A, B): # <--
ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--
plt.grid()
plt.show()
In C++11 and above, you can also initialize std::vector
with an initializer list. For example:
using namespace std; // for example only
for (auto s : vector<string>{"one","two","three"} )
cout << s << endl;
So, your example would become:
void foo(vector<string> strArray){
// some code
}
vector<string> s {"hi", "there"}; // Works
foo(s); // Works
foo(vector<string> {"hi", "there"}); // also works
I have experienced the GUIDs not being unique during multi-threaded/multi-process unit-testing (too?). I guess that has to do with, all other tings being equal, the identical seeding (or lack of seeding) of pseudo random generators. I was using it for generating unique file names. I found the OS is much better at doing that :)
You ask if GUIDs are 100% unique. That depends on the number of GUIDs it must be unique among. As the number of GUIDs approach infinity, the probability for duplicate GUIDs approach 100%.
Typically async method returns Task class. If you use Wait()
method or Result
property and code throws exception - exception type gets wrapped up into AggregateException
- then you need to query Exception.InnerException
to locate correct exception.
But it's also possible to use .GetAwaiter().GetResult()
instead -
it will also wait async task, but will not wrap exception.
So here is short example:
public async Task MyMethodAsync()
{
}
public string GetStringData()
{
MyMethodAsync().GetAwaiter().GetResult();
return "test";
}
You might want also to be able to return some parameter from async function - that can be achieved by providing extra Action<return type>
into async function, for example like this:
public string GetStringData()
{
return MyMethodWithReturnParameterAsync().GetAwaiter().GetResult();
}
public async Task<String> MyMethodWithReturnParameterAsync()
{
return "test";
}
Please note that async methods typically have ASync
suffix naming, just to be able to avoid collision between sync functions with same name. (E.g. FileStream.ReadAsync
) - I have updated function names to follow this recommendation.
Just provide another implementation of Jason's answer by C.
After discussing with my classmates, based on Jason's explanation, I like the recursive version more if you don't care about the performance very much:
For example:
#include<stdio.h>
int mypow( int base, int pow, int mod ){
if( pow == 0 ) return 1;
if( pow % 2 == 0 ){
int tmp = mypow( base, pow >> 1, mod );
return tmp * tmp % mod;
}
else{
return base * mypow( base, pow - 1, mod ) % mod;
}
}
int main(){
printf("%d", mypow(5,55,221));
return 0;
}
As a note, depending upon the property you may be able to set it to auto.
In case the file your variable holds doesn't actually exist the FOR
approach won't work. One trick you could use, if you know the length of the extension, is taking a substring:
%var:~0,-4%
the -4
means that the last 4 digits (presumably .ext) will be truncated.
This would be work very fine
<a href="<%:Url.Action("Edit","Account",new { id=item.UserId }) %>"><img src="../../Content/ThemeNew/images/edit_notes_delete11.png" alt="Edit" width="25px" height="25px" /></a>
Page 2 is in a new tab/window ? If it's this, use the code bellow :
try {
String winHandleBefore = driver.getWindowHandle();
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
String act = driver.getCurrentUrl();
}
}catch(Exception e){
System.out.println("fail");
}
It's entirely likely that a large portion of the developer base comes from a Java background where using ==
to compare strings is wrong and doesn't work.
In C# there's no (practical) difference (for strings) as long as they are typed as string.
If they are typed as object
or T
then see other answers here that talk about generic methods or operator overloading as there you definitely want to use the Equals method.
<?php
include "db_conn.php";//connection file
require "PHPMailerAutoload.php";// it will be in PHPMailer
require "class.smtp.php";// it will be in PHPMailer
require "class.phpmailer.php";// it will be in PHPMailer
$response = array();
$params = json_decode(file_get_contents("php://input"));
if(!empty($params->email_id)){
$email_id = $params->email_id;
$flag=false;
echo "something";
if(!filter_var($email_id, FILTER_VALIDATE_EMAIL))
{
$response['ERROR']='EMAIL address format error';
echo json_encode($response,JSON_UNESCAPED_SLASHES);
return;
}
$sql="SELECT * from sales where email_id ='$email_id' ";
$result = mysqli_query($conn,$sql);
$count = mysqli_num_rows($result);
$to = "[email protected]";
$subject = "DEMO Subject";
$messageBody ="demo message .";
if($count ==0){
$response["valid"] = false;
$response["message"] = "User is not registered yet";
echo json_encode($response);
return;
}
else {
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true; // authentication enabled
$mail->IsHTML(true);
$mail->SMTPSecure = 'ssl';//turn on to send html email
// $mail->Host = "ssl://smtp.zoho.com";
$mail->Host = "p3plcpnl0749.prod.phx3.secureserver.net";//you can use gmail
$mail->Port = 465;
$mail->Username = "[email protected]";
$mail->Password = "demopassword";
$mail->SetFrom("[email protected]", "Any demo alert");
$mail->Subject = $subject;
$mail->Body = $messageBody;
$mail->AddAddress($to);
echo "yes";
if(!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
else {
echo "Message has been sent successfully";
}
}
}
else{
$response["valid"] = false;
$response["message"] = "Required field(s) missing";
echo json_encode($response);
}
?>
The above code is working for me.
Apart from what Andy mentioned, there is another difference which could be important - write-host directly writes to the host and return nothing, meaning that you can't redirect the output, e.g., to a file.
---- script a.ps1 ----
write-host "hello"
Now run in PowerShell:
PS> .\a.ps1 > someFile.txt
hello
PS> type someFile.txt
PS>
As seen, you can't redirect them into a file. This maybe surprising for someone who are not careful.
But if switched to use write-output instead, you'll get redirection working as expected.
With Windows 10 / Powershell ctrl + c did not work; Powershell tried to gracefully stop the app.
Used normal cmd and had no issues stopping the ng serve with ctrl + c.
You do not need to type SQL Query for this in SQL Server 2008.
In SSMS Object Explorer choose Databases or Tables of the required database (if you need to search in one database), open menu View--> Object Explorer Details (alternatively press F7), type %CreatedDate% in Search textbox, ENTER, enjoy
The following bit of code does what you ask for. Just make sure that you assign enough space so that the text on the button becomes visible
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(4,4,4,4));
for(int i=0 ; i<16 ; i++){
JButton btn = new JButton(String.valueOf(i));
btn.setPreferredSize(new Dimension(40, 40));
panel.add(btn);
}
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
The X and Y (two first parameters of the GridLayout constructor) specify the number of rows and columns in the grid (respectively). You may leave one of them as 0 if you want that value to be unbounded.
Edit
I've modified the provided code and I believe it now conforms to what is desired:
JFrame frame = new JFrame("Colored Trails");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(4, 4));
firstPanel.setMaximumSize(new Dimension(400, 400));
JButton btn;
for (int i=1; i<=4; i++) {
for (int j=1; j<=4; j++) {
btn = new JButton();
btn.setPreferredSize(new Dimension(100, 100));
firstPanel.add(btn);
}
}
JPanel secondPanel = new JPanel();
secondPanel.setLayout(new GridLayout(5, 13));
secondPanel.setMaximumSize(new Dimension(520, 200));
for (int i=1; i<=5; i++) {
for (int j=1; j<=13; j++) {
btn = new JButton();
btn.setPreferredSize(new Dimension(40, 40));
secondPanel.add(btn);
}
}
mainPanel.add(firstPanel);
mainPanel.add(secondPanel);
frame.setContentPane(mainPanel);
frame.setSize(520,600);
frame.setMinimumSize(new Dimension(520,600));
frame.setVisible(true);
Basically I now set the preferred size of the panels and a minimum size for the frame.
My .env file configuration is like this for laravel 5.1
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=****************
MAIL_ENCRYPTION=tls
here most important thing is that I created gmail application specific password(16 digit).
I need to reveal one more thing since no luck for any of configuration. That is, whenever I changed .env file need to run this command
php artisan config:cache
And this is most most most important because without this command laravel executes previous settings from it's cache. It's required me more than 10 hours to figure out.
For each iteration of the ng-repeat loop, line
is a reference to an object in your array. Therefore, to preview the value, use {{line.text}}
.
Similarly, to databind to the text, databind to the same: ng-model="line.text"
. You don't need to use value
when using ng-model (actually you shouldn't).
For a more in-depth look at scopes and ng-repeat, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?, section ng-repeat.
Non VBA Solution:
Use Conditional Formatting rule with formula: =ISNA(A1)
(to highlight cells with all errors - not only #N/A
, use =ISERROR(A1)
)
VBA Solution:
Your code loops through 50 mln cells. To reduce number of cells, I use .SpecialCells(xlCellTypeFormulas, 16)
and .SpecialCells(xlCellTypeConstants, 16)
to return only cells with errors (note, I'm using If cell.Text = "#N/A" Then
)
Sub ColorCells()
Dim Data As Range, Data2 As Range, cell As Range
Dim currentsheet As Worksheet
Set currentsheet = ActiveWorkbook.Sheets("Comparison")
With currentsheet.Range("A2:AW" & Rows.Count)
.Interior.Color = xlNone
On Error Resume Next
'select only cells with errors
Set Data = .SpecialCells(xlCellTypeFormulas, 16)
Set Data2 = .SpecialCells(xlCellTypeConstants, 16)
On Error GoTo 0
End With
If Not Data2 Is Nothing Then
If Not Data Is Nothing Then
Set Data = Union(Data, Data2)
Else
Set Data = Data2
End If
End If
If Not Data Is Nothing Then
For Each cell In Data
If cell.Text = "#N/A" Then
cell.Interior.ColorIndex = 4
End If
Next
End If
End Sub
Note, to highlight cells witn any error (not only "#N/A"
), replace following code
If Not Data Is Nothing Then
For Each cell In Data
If cell.Text = "#N/A" Then
cell.Interior.ColorIndex = 3
End If
Next
End If
with
If Not Data Is Nothing Then Data.Interior.ColorIndex = 3
UPD: (how to add CF rule through VBA)
Sub test()
With ActiveWorkbook.Sheets("Comparison").Range("A2:AW" & Rows.Count).FormatConditions
.Delete
.Add Type:=xlExpression, Formula1:="=ISNA(A1)"
.Item(1).Interior.ColorIndex = 3
End With
End Sub
KLSingleton is:
- Subclassible (to the n-th degree)
- ARC compatible
- Safe with
alloc
andinit
- Loaded lazily
- Thread-safe
- Lock-free (uses +initialize, not @synchronize)
- Macro-free
- Swizzle-free
- Simple
I am currently researching this exact topic in the many (MANY) threads at GameDev.net and found the following two solutions to be good candidates on what I will develop for my game:
Solution native Javascript :
document.getElementById("theSelectId").insertBefore(new Option('', ''), document.getElementById("theSelectId").firstChild);
example : http://codepen.io/anon/pen/GprybL
In this particular example, it makes no difference. However, the {}
in ${}
are useful if you want to expand the variable foo
in the string
"${foo}bar"
since "$foobar"
would instead expand the variable identified by foobar
.
Curly braces are also unconditionally required when:
${array[42]}
${filename%.*}
(remove extension)"$8 $9 ${10} ${11}"
Doing this everywhere, instead of just in potentially ambiguous cases, can be considered good programming practice. This is both for consistency and to avoid surprises like $foo_$bar.jpg
, where it's not visually obvious that the underscore becomes part of the variable name.
You could create a function that checks every input in an input class like below
function validateForm() {
var anyFieldIsEmpty = jQuery(".myclass").filter(function () {
return $.trim(this.value).length === 0;
}).length > 0
if (anyFieldIsEmpty) {
alert("Fill all the necessary fields");
var empty = $(".myclass").filter(function () {
return $.trim(this.value).length === 0;
})
empty.css("border", "1px solid red");
return false;
} else {
return true;
}
}
What this does is it checks every input in 'myclass' and if empty it gives alert and colour the border of the input and user will recognize which input is not filled.
You need to link with the math library, libm:
$ gcc -Wall foo.c -o foo -lm
I had this problem too. It turned out I forgot to include one of the components in app.module.ts
If your base class is called Base
, and your function is called FooBar()
you can call it directly using Base::FooBar()
void Base::FooBar()
{
printf("in Base\n");
}
void ChildOfBase::FooBar()
{
Base::FooBar();
}
Idk if you guys solved it but I recommend another way to do it, and it works :)
ServiceUtil = ig.Class.extend({
base_url : 'someurl',
sendRequest: function(request)
{
var url = this.base_url + request;
var requestVar = new XMLHttpRequest();
dataGet = false;
$.ajax({
url: url,
async: false,
type: "get",
success: function(data){
ServiceUtil.objDataReturned = data;
}
});
return ServiceUtil.objDataReturned;
}
})
So the main idea here is that, by adding async: false, then you make everything waits until the data is retrieved. Then you assign it to a static variable of the class, and everything magically works :)
Got the fix in css.
td.disabledAnchor a{
pointer-events: none !important;
cursor: default;
color:Gray;
}
Above css when applied to the anchor tag will disable the click event.
For details checkout this link
The MultiByteToWideChar
answer that Charles Bailey gave is the correct one. Because LPCWSTR
is just a typedef for const WCHAR*
, widestr
in the example code there can be used wherever a LPWSTR
is expected or where a LPCWSTR
is expected.
One minor tweak would be to use std::vector<WCHAR>
instead of a manually managed array:
// using vector, buffer is deallocated when function ends
std::vector<WCHAR> widestr(bufferlen + 1);
::MultiByteToWideChar(CP_ACP, 0, instr.c_str(), instr.size(), &widestr[0], bufferlen);
// Ensure wide string is null terminated
widestr[bufferlen] = 0;
// no need to delete; handled by vector
Also, if you need to work with wide strings to start with, you can use std::wstring
instead of std::string
. If you want to work with the Windows TCHAR
type, you can use std::basic_string<TCHAR>
. Converting from std::wstring
to LPCWSTR
or from std::basic_string<TCHAR>
to LPCTSTR
is just a matter of calling c_str
. It's when you're changing between ANSI and UTF-16 characters that MultiByteToWideChar
(and its inverse WideCharToMultiByte
) comes into the picture.
Process text to and from Unicode at the I/O boundaries of your program using open
with the encoding
parameter. Make sure to use the (hopefully documented) encoding of the file being read. The default encoding varies by OS (specifically, locale.getpreferredencoding(False)
is the encoding used), so I recommend always explicitly using the encoding
parameter for portability and clarity (Python 3 syntax below):
with open(filename, 'r', encoding='utf8') as f:
text = f.read()
# process Unicode text
with open(filename, 'w', encoding='utf8') as f:
f.write(text)
If still using Python 2 or for Python 2/3 compatibility, the io
module implements open
with the same semantics as Python 3's open
and exists in both versions:
import io
with io.open(filename, 'r', encoding='utf8') as f:
text = f.read()
# process Unicode text
with io.open(filename, 'w', encoding='utf8') as f:
f.write(text)
I use to have that problem, but the simples way to fix it is this (this works for me):
on the CSS file type:
body{overflow-y:scroll;}
as that simple! :)
The difference between Func
and Action
is simply whether you want the delegate to return a value (use Func
) or not (use Action
).
Func
is probably most commonly used in LINQ - for example in projections:
list.Select(x => x.SomeProperty)
or filtering:
list.Where(x => x.SomeValue == someOtherValue)
or key selection:
list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)
Action
is more commonly used for things like List<T>.ForEach
: execute the given action for each item in the list. I use this less often than Func
, although I do sometimes use the parameterless version for things like Control.BeginInvoke
and Dispatcher.BeginInvoke
.
Predicate
is just a special cased Func<T, bool>
really, introduced before all of the Func
and most of the Action
delegates came along. I suspect that if we'd already had Func
and Action
in their various guises, Predicate
wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func
and Action
are used for widely disparate purposes.
Predicate
is mostly used in List<T>
for methods like FindAll
and RemoveAll
.
I had the same problem but finally I found the way.
Here is the walk through:
1- Install VLC on your computer (SERVER) and go to Media->Streaming (Ctrl+S)
2- Select a file to stream or if you want to stream your webcam or... click on "Capture Device" tab and do the configuration and finally click on "Stream" button.
3- Here you should do the streaming server configuration, just go to "Option" tab and paste the following command:
:sout=#transcode{vcodec=mp4v,vb=400,fps=10,width=176,height=144,acodec=mp4a,ab=32,channels=1,samplerate=22050}:rtp{sdp=rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/}
NOTE: Replace YOURCOMPUTER_SERVER_IP_ADDR with your computer IP address or any server which is running VLC...
NOTE: You can see, the video codec is MP4V which is supported by android.
4- go to eclipse and create a new project for media playbak. create a VideoView object and in the OnCreate() function write some code like this:
mVideoView = (VideoView) findViewById(R.id.surface_view);
mVideoView.setVideoPath("rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/");
mVideoView.setMediaController(new MediaController(this));
5- run the apk on the device (not simulator, i did not check it) and wait for the playback to be started. please consider the buffering process will take about 10 seconds...
Question: Anybody know how to reduce buffering time and play video almost live ?
Just use not
:
if not your_variable:
print("your_variable is empty")
and for your 0 as string
use:
if your_variable == "0":
print("your_variable is 0 (string)")
combine them:
if not your_variable or your_variable == "0":
print("your_variable is empty")
Python is about simplicity, so is this answer :)
Python installation folder > Lib > idlelib > idle.pyw
send a shortcut to desktop.
From the desktop shortcut you can add it to taskbar too for quickaccess.
Hope this helps.
I believe this is what you're looking for:
var press = jQuery.Event("keypress");
press.ctrlKey = false;
press.which = 40;
$("whatever").trigger(press);
From here.
If You are on another branch, You need first "check to this commit" for commit you want to delete, and only then "reset current branch to this commit" choosing previous wright commit, will work.
For Kotlin, we can use the following method. You can paste this method inside an activity or fragment.
fun copyToClipBoard(context: Context, message: String) {
val clipBoard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clipData = ClipData.newPlainText("label",message)
clipBoard.setPrimaryClip(clipData)
}
I meant in the template()
call..
You just need to pass the results as an object. So instead of calling
var html = template(data);
do
var html = template({apidata: data});
and use {{#each apidata}}
in your template code
demo at http://jsfiddle.net/KPCh4/4/
(removed some leftover if
code that crashed)
Just do like below, it helped me after doing like this.
To load existing Eclipse projects in the IDE, you need to import them into the Eclipse workspace.
Look at this below link for reference. https://www.microfocus.com/documentation/enterprise-developer/ed30/Eclipse/GUID-773A19C7-98B2-442D-9D36-240E20E3F2CE.html
use only org.hibernate.dialect.OracleDialect Remove 10g,9 etc.
When installing the SDK I used this method:
curl https://sdk.cloud.google.com | bash
When using this method from the original author make sure you have accepted the security preferences in your mac settings to allow apps downloaded from app store and identified developers.
Now days I believe it's preferred to use a function form of typeof() so...
if(filename === undefined || typeof(filename) !== "string" || filename === "") {
console.log("no filename aborted.");
return;
}
I typically have a secrets.py
that is stored separately from my other python scripts and is not under version control. Then whenever required, you can do from secrets import <required_pwd_var>
. This way you can rely on the operating systems in-built file security system without re-inventing your own.
Using Base64
encoding/decoding is also another way to obfuscate the password though not completely secure
More here - Hiding a password in a python script (insecure obfuscation only)
I wrote quick test program to demonstrate one difference:
#include <stdio.h>
enum {ENUM_DEFINED=16};
enum {ENUM_DEFINED=32};
#define DEFINED_DEFINED 16
#define DEFINED_DEFINED 32
int main(int argc, char *argv[]) {
printf("%d, %d\n", DEFINED_DEFINED, ENUM_DEFINED);
return(0);
}
This compiles with these errors and warnings:
main.c:6:7: error: redefinition of enumerator 'ENUM_DEFINED'
enum {ENUM_DEFINED=32};
^
main.c:5:7: note: previous definition is here
enum {ENUM_DEFINED=16};
^
main.c:9:9: warning: 'DEFINED_DEFINED' macro redefined [-Wmacro-redefined]
#define DEFINED_DEFINED 32
^
main.c:8:9: note: previous definition is here
#define DEFINED_DEFINED 16
^
Note that enum gives an error when define gives a warning.
Handling key events consistently is not at all easy.
Firstly, there are two different types of codes: keyboard codes (a number representing the key on the keyboard the user pressed) and character codes (a number representing a Unicode character). You can only reliably get character codes in the keypress
event. Do not try to get character codes for keyup
and keydown
events.
Secondly, you get different sets of values in a keypress
event to what you get in a keyup
or keydown
event.
I recommend this page as a useful resource. As a summary:
If you're interested in detecting a user typing a character, use the keypress
event. IE bizarrely only stores the character code in keyCode
while all other browsers store it in which
. Some (but not all) browsers also store it in charCode
and/or keyCode
. An example keypress handler:
function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
alert(charStr);
}
If you're interested in detecting a non-printable key (such as a cursor key), use the keydown
event. Here keyCode
is always the property to use. Note that keyup
events have the same properties.
function(evt) {
evt = evt || window.event;
var keyCode = evt.keyCode;
// Check for left arrow key
if (keyCode == 37) {
alert("Left arrow");
}
}
I have faced a similar problem when there were millions of useless log files created by an application which filled up all inodes. I resorted to "locate", got all the files "located"d into a text file and then removed them one by one. Took a while but did the job!
For me none of the solutions above worked. What worked for me was to select all the code in the class, then convert it to a comment, save, then convert it back to normal text, the error was gone.
You could use a div
with a background image instead and this CSS3 property:
background-size: contain
You can check out an example on:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Scaling_background_images#contain
To quote Mozilla:
The contain value specifies that regardless of the size of the containing box, the background image should be scaled so that each side is as large as possible while not exceeding the length of the corresponding side of the container.
However, keep in mind that your image will be upscaled if the div
is larger than your original image.
You can do this using System.IO.BinaryWriter
which takes a Stream so:
var bw = new BinaryWriter(File.Open("path",FileMode.OpenOrCreate);
bw.Write(byteArray);
Try winhttpjs.bat. It uses a winhttp request object that should be faster than
Msxml2.XMLHTTP as there isn't any DOM parsing of the response. It is capable to do requests with body and all HTTP methods.
call winhttpjs.bat http://somelink.com/something.html -saveTo c:\something.html
Ran into this exact problem.
What I ended up doing:
# starting with date string
sdt = "20190901"
std_format = '%Y%m%d'
# create naive datetime object
from datetime import datetime
dt = datetime.strptime(sdt, sdt_format)
# extract the relevant date time items
dt_formatters = ['%Y','%m','%d']
dt_vals = tuple(map(lambda formatter: int(datetime.strftime(dt,formatter)), dt_formatters))
# set timezone
import pendulum
tz = pendulum.timezone('utc')
dt_tz = datetime(*dt_vals,tzinfo=tz)
Just use .contains
. For example, if you were checking if an ArrayList arr
contains a value val
, you would simply run arr.contains(val)
, which would return a boolean representing if the value is contained. For more information, see the docs for .contains
.
Well, tempnam() will do it for you.
http://us2.php.net/manual/en/function.tempnam.php
but that creates an entirely new name.
To sanitize an existing string just restrict what your users can enter and make it letters, numbers, period, hyphen and underscore then sanitize with a simple regex. Check what characters need to be escaped or you could get false positives.
$sanitized = preg_replace('/[^a-zA-Z0-9\-\._]/','', $filename);
I don't think there's any way to get width of texts in variable-width fonts, especially in javascript.
The only way I can think is to make a hidden element that has variable width set by css, put text in its innerHTML, and get the width of that element. So you may be able to apply this method to cope with textarea auto-sizing problem.
It's an attribute designed to help assistive technology (e.g. screen readers) attach a label to an otherwise anonymous HTML element.
So there's the <label>
element:
<label for="fmUserName">Your name</label>
<input id="fmUserName">
The <label>
explicitly tells the user to type their name into the input
box where id="fmUserName"
.
aria-label
does much the same thing, but it's for those cases where it isn't practical or desirable to have a label
on screen. Take the MDN example:
<button aria-label="Close" onclick="myDialog.close()">X</button>`
Most people would be able to infer visually that this button will close the dialog. A blind person using assistive technology might just hear "X" read aloud, which doesn't mean much without the visual clues. aria-label
explicitly tells them what the button will do.
If you click on the title CSS (SCSS)
in CodePen (don't change the pre-processor with the gear) it will switch to the compiled CSS view.
As Google gives this answer for the search netlogo pdf, here's the netlogo version of the above python code
;; Normal distribution cumulative density function to-report normcdf [x mu sigma] let t x - mu let y 0.5 * erfcc [ - t / ( sigma * sqrt 2.0)] if ( y > 1.0 ) [ set y 1.0 ] report y end ;; Normal distribution probability density function to-report normpdf [x mu sigma] let u = (x - mu) / abs sigma let y = 1 / ( sqrt [2 * pi] * abs sigma ) * exp ( - u * u / 2.0) report y end ;; Complementary error function to-report erfcc [x] let z abs x let t 1.0 / (1.0 + 0.5 * z) let r t * exp ( - z * z -1.26551223 + t * (1.00002368 + t * (0.37409196 + t * (0.09678418 + t * (-0.18628806 + t * (.27886807 + t * (-1.13520398 +t * (1.48851587 +t * (-0.82215223 + t * .17087277 ))))))))) ifelse (x >= 0) [ report r ] [report 2.0 - r] end
More than one Element with the same ID is not allowed, getElementById Returns the Element whose ID is given by elementId. If no such element exists, returns null. Behavior is not defined if more than one element has this ID.
First, to describe dynamic cast in C terms, we have to represent classes in C. Classes with virtual functions use a "VTABLE" of pointers to the virtual functions. Comments are C++. Feel free to reformat and fix compile errors...
// class A { public: int data; virtual int GetData(){return data;} };
typedef struct A { void**vtable; int data;} A;
int AGetData(A*this){ return this->data; }
void * Avtable[] = { (void*)AGetData };
A * newA() { A*res = malloc(sizeof(A)); res->vtable = Avtable; return res; }
// class B : public class A { public: int moredata; virtual int GetData(){return data+1;} }
typedef struct B { void**vtable; int data; int moredata; } B;
int BGetData(B*this){ return this->data + 1; }
void * Bvtable[] = { (void*)BGetData };
B * newB() { B*res = malloc(sizeof(B)); res->vtable = Bvtable; return res; }
// int temp = ptr->GetData();
int temp = ((int(*)())ptr->vtable[0])();
Then a dynamic cast is something like:
// A * ptr = new B();
A * ptr = (A*) newB();
// B * aB = dynamic_cast<B>(ptr);
B * aB = ( ptr->vtable == Bvtable ? (B*) aB : (B*) 0 );
System.exit(0)
terminates the JVM. In simple examples like this it is difficult to percieve the difference. The parameter is passed back to the OS and is normally used to indicate abnormal termination (eg some kind of fatal error), so if you called java from a batch file or shell script you'd be able to get this value and get an idea if the application was successful.
It would make a quite an impact if you called System.exit(0)
on an application deployed to an application server (think about it before you try it).
var array = searchTerms.split(",");
for (var i in array){
alert(array[i]);
}
You should definitely use tput over raw ANSI control sequences.
Because there's a large number of different terminal control languages, usually a system has an intermediate communication layer. The real codes are looked up in a database for the currently detected terminal type and you give standardized requests to an API or (from the shell) to a command.
One of these commands is
tput
.tput
accepts a set of acronyms called capability names and any parameters, if appropriate, then looks up the correct escape sequences for the detected terminal in the terminfo database and prints the correct codes (the terminal hopefully understands).
from http://wiki.bash-hackers.org/scripting/terminalcodes
That said, I wrote a small helper library called bash-tint, which adds another layer on top of tput, making it even simpler to use (imho):
Example:
tint "white(Cyan(T)Magenta(I)Yellow(N)Black(T)) is bold(really) easy to use."
Let's start by describing DOM elements' event handling.
First of all you wouldn't want to work with DOM node directly. Instead you probably would want to utilize Ext.Element
interface. For the purpose of assigning event handlers, Element.addListener
and Element.on
(these are equivalent) were created. So, for example, if we have html:
<div id="test_node"></div>
and we want add click
event handler.
Let's retrieve Element
:
var el = Ext.get('test_node');
Now let's check docs for click
event. It's handler may have three parameters:
click( Ext.EventObject e, HTMLElement t, Object eOpts )
Knowing all this stuff we can assign handler:
// event name event handler
el.on( 'click' , function(e, t, eOpts){
// handling event here
});
Widgets event handling is pretty much similar to DOM nodes event handling.
First of all, widgets event handling is realized by utilizing Ext.util.Observable
mixin. In order to handle events properly your widget must containg Ext.util.Observable
as a mixin. All built-in widgets (like Panel, Form, Tree, Grid, ...) has Ext.util.Observable
as a mixin by default.
For widgets there are two ways of assigning handlers. The first one - is to use on method (or addListener
). Let's for example create Button
widget and assign click
event to it. First of all you should check event's docs for handler's arguments:
click( Ext.button.Button this, Event e, Object eOpts )
Now let's use on
:
var myButton = Ext.create('Ext.button.Button', {
text: 'Test button'
});
myButton.on('click', function(btn, e, eOpts) {
// event handling here
console.log(btn, e, eOpts);
});
The second way is to use widget's listeners config:
var myButton = Ext.create('Ext.button.Button', {
text: 'Test button',
listeners : {
click: function(btn, e, eOpts) {
// event handling here
console.log(btn, e, eOpts);
}
}
});
Notice that Button
widget is a special kind of widgets. Click event can be assigned to this widget by using handler
config:
var myButton = Ext.create('Ext.button.Button', {
text: 'Test button',
handler : function(btn, e, eOpts) {
// event handling here
console.log(btn, e, eOpts);
}
});
First of all you need to register an event using addEvents method:
myButton.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);
Using the addEvents
method is optional. As comments to this method say there is no need to use this method but it provides place for events documentation.
To fire your event use fireEvent method:
myButton.fireEvent('myspecialevent1', arg1, arg2, arg3, /* ... */);
arg1, arg2, arg3, /* ... */
will be passed into handler. Now we can handle your event:
myButton.on('myspecialevent1', function(arg1, arg2, arg3, /* ... */) {
// event handling here
console.log(arg1, arg2, arg3, /* ... */);
});
It's worth mentioning that the best place for inserting addEvents method call is widget's initComponent
method when you are defining new widget:
Ext.define('MyCustomButton', {
extend: 'Ext.button.Button',
// ... other configs,
initComponent: function(){
this.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);
// ...
this.callParent(arguments);
}
});
var myButton = Ext.create('MyCustomButton', { /* configs */ });
To prevent bubbling you can return false
or use Ext.EventObject.preventDefault()
. In order to prevent browser's default action use Ext.EventObject.stopPropagation()
.
For example let's assign click event handler to our button. And if not left button was clicked prevent default browser action:
myButton.on('click', function(btn, e){
if (e.button !== 0)
e.preventDefault();
});
It does it:
myString.substr(-1);
This returns a substring of myString starting at one character from the end: the last character.
This also works:
myString.charAt(myString.length-1);
And this too:
myString.slice(-1);
Long time reader, first time helper ;)
I'm going through the same hellish
experience here with a Prolific USB <> Serial adapter and so far Linux is the easiest to get it to work.
On CentOS, I didn't need to install any drivers etc.. That said,
dmesg | grep -i tty
or dmesg | grep -i usb
showed me /dev/ttyUSB0. screen ttyUSB0 9600
didn't do the trick for me like it did in OSXHowever, this helped: https://www.centos.org/forums/viewtopic.php?t=21271
So install minicom (yum install minicom
) then enter its settings (minicom -s
).
Then select Serial Port Setup
and change the Serial Device (Option A) to /dev/ttyUSB0, or whatever your device file is as it slightly differs per distro.
Then change the Bps (Option E) to 9600 and the rest should be default (8N1 Y N)
Save as default, then simply minicom
and Bob's your uncle.
HTH.
you need to store the token while creating for 1st registration. When you retrieve data from login table you need to differentiate entered date with current date if it is more than 1 day (24 hours) you need to display message like your token is expired.
To generate key refer here
Please find example below, it might help you
package jersey.rest.test;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
@Path("/hello")
public class SimpleService {
@GET
@Path("/{param}")
public Response getMsg(@PathParam("param") String msg) {
String output = "Get:Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
@POST
@Path("/{param}")
public Response postMsg(@PathParam("param") String msg) {
String output = "POST:Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
@POST
@Path("/post")
//@Consumes(MediaType.TEXT_XML)
public Response postStrMsg( String msg) {
String output = "POST:Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
@PUT
@Path("/{param}")
public Response putMsg(@PathParam("param") String msg) {
String output = "PUT: Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
@DELETE
@Path("/{param}")
public Response deleteMsg(@PathParam("param") String msg) {
String output = "DELETE:Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
@HEAD
@Path("/{param}")
public Response headMsg(@PathParam("param") String msg) {
String output = "HEAD:Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
}
for testing you can use any tool like RestClient (http://code.google.com/p/rest-client/)
One can directly store the returned output of a function in a file.
print(output statement, file=open("filename", "a"))
That is the mode with which you are opening the file. "wb" means that you are writing to the file (w), and that you are writing in binary mode (b).
Check out the documentation for more: clicky
In my case it was a copy/paste problem. I somehow ended up with a PRIVATE constructor for my mapping profile:
using AutoMapper;
namespace Your.Namespace
{
public class MappingProfile : Profile
{
MappingProfile()
{
CreateMap<Animal, AnimalDto>();
}
}
}
(take note of the missing "public" in front of the ctor)
which compiled perfectly fine, but when AutoMapper tries to instantiate the profile it can't (of course!) find the constructor!
I know one aspect: Although CBC gives better security by changing the IV for each block, it's not applicable to randomly accessed encrypted content (like an encrypted hard disk).
So, use CBC (and the other sequential modes) for sequential streams and ECB for random access.
You need to add a reference to System.Windows.Forms.dll, then use the System.Windows.Forms.FolderBrowserDialog
class.
Adding using WinForms = System.Windows.Forms;
will be helpful.
Simply use:
var util = require('util');
var value = 15;
var s = util.format("The variable value is: %s", value)