There's an Abstract Class Dictionary
http://docs.oracle.com/javase/6/docs/api/java/util/Dictionary.html
However this requires implementation.
Java gives us a nice implementation called a Hashtable
http://docs.oracle.com/javase/6/docs/api/java/util/Hashtable.html
You can select elements with multiple classes like so:
$("element.firstClass.anotherClass");
Simply chain the next class onto the first one, without a space (spaces mean "children of").
there is now (from 1.1.1 version) a 'skip' flag in pit.
So you can do things like :
<profile>
<id>pit</id>
<build>
<plugins>
<plugin>
<groupId>org.pitest</groupId>
<artifactId>pitest-maven</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</profile>
in your module, and pit will skip
[INFO] --- pitest-maven:1.1.3:mutationCoverage (default-cli) @ module-selenium --- [INFO] Skipping project
Use a document.ready()
event around your call.
$(document).ready(function () {
$('#memberModal').modal('show');
});
jsFiddle updated - http://jsfiddle.net/uvnggL8w/1/
The problem here was a typo error in the password used, which was not easily identified due to the characters / letters used in the password.
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
If none of these solutions are clearing an image you've already set (especially setImageResource(0)
or setImageResources(android.R.color.transparent)
, check to make sure the current image isn't set as background using setBackgroundDrawable(...)
or something similar.
Your code will just set the image resource in the foreground to something transparent in front of that background image you've set and will still show.
listOfStuff =([a,b], [c,d], [e,f], [f,g])
for item in listOfStuff[1:3]:
print item
You have to iterate over a slice of your tuple. The 1
is the first element you need and 3
(actually 2+1) is the first element you don't need.
Elements in a list are numerated from 0:
listOfStuff =([a,b], [c,d], [e,f], [f,g])
0 1 2 3
[1:3]
takes elements 1 and 2.
static means it belongs to the class not an instance, this means that there is only one copy of that variable/method shared between all instances of a particular Class.
public class MyClass {
public static int myVariable = 0;
}
//Now in some other code creating two instances of MyClass
//and altering the variable will affect all instances
MyClass instance1 = new MyClass();
MyClass instance2 = new MyClass();
MyClass.myVariable = 5; //This change is reflected in both instances
final is entirely unrelated, it is a way of defining a once only initialization. You can either initialize when defining the variable or within the constructor, nowhere else.
note A note on final methods and final classes, this is a way of explicitly stating that the method or class can not be overridden / extended respectively.
Extra Reading So on the topic of static, we were talking about the other uses it may have, it is sometimes used in static blocks. When using static variables it is sometimes necessary to set these variables up before using the class, but unfortunately you do not get a constructor. This is where the static keyword comes in.
public class MyClass {
public static List<String> cars = new ArrayList<String>();
static {
cars.add("Ferrari");
cars.add("Scoda");
}
}
public class TestClass {
public static void main(String args[]) {
System.out.println(MyClass.cars.get(0)); //This will print Ferrari
}
}
You must not get this confused with instance initializer blocks which are called before the constructor per instance.
I had the same exception on Tomcat.. I found another problem - when i use wsimport over maven plugin to generate stubs for more then 1 WSDLs - class ObjectFactory
(stubs references to this class) contains methods ONLY for one wsdl. So you should merge all methods in one ObjectFactory
class (for each WSDL) or generate each wsdl stubs in different directories (there will be separates ObjectFactory
classes). It solves problem for me with this exception..J
It's a linker error. ld
is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.
The error message tells you that none of the object files you're linking against contains a definition for avergecolumns
. The reason for that is that the function you've defined is called averagecolumns
(in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).
CASCADE will also delete the corresponding field connected with it.
You could make two forms with 2 different actions
<form action="login.php" method="post">
<input type="text" name="user">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
<br />
<form action="register.php" method="post">
<input type="text" name="user">
<input type="password" name="password">
<input type="submit" value="Register">
</form>
Or do this
<form action="doStuff.php" method="post">
<input type="text" name="user">
<input type="password" name="password">
<input type="hidden" name="action" value="login">
<input type="submit" value="Login">
</form>
<br />
<form action="doStuff.php" method="post">
<input type="text" name="user">
<input type="password" name="password">
<input type="hidden" name="action" value="register">
<input type="submit" value="Register">
</form>
Then you PHP file would work as a switch($_POST['action']) ... furthermore, they can't click on both links at the same time or make a simultaneous request, each submit is a separate request.
Your PHP would then go on with the switch logic or have different php files doing a login procedure then a registration procedure
string Location = "C:\\Program Files\\hello.txt";
string FileName = Location.Substring(Location.LastIndexOf('\\') +
1);
I also tried to benchmark the different kinds of loop in C#. I used the same code as Shane, but I also tried with a do-while and found it to be the fastest. This is the code:
using System;
using System.Diagnostics;
public class Program
{
public static void Main()
{
int max = 9999999;
Stopwatch stopWatch = new Stopwatch();
Console.WriteLine("Do While Loop: ");
stopWatch.Start();
DoWhileLoop(max);
stopWatch.Stop();
DisplayElapsedTime(stopWatch.Elapsed);
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("While Loop: ");
stopWatch.Start();
WhileLoop(max);
stopWatch.Stop();
DisplayElapsedTime(stopWatch.Elapsed);
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("For Loop: ");
stopWatch.Start();
ForLoop(max);
stopWatch.Stop();
DisplayElapsedTime(stopWatch.Elapsed);
}
private static void DoWhileLoop(int max)
{
int i = 0;
do
{
//Performe Some Operation. By removing Speed increases
var j = 10 + 10;
j += 25;
i++;
} while (i <= max);
}
private static void WhileLoop(int max)
{
int i = 0;
while (i <= max)
{
//Performe Some Operation. By removing Speed increases
var j = 10 + 10;
j += 25;
i++;
};
}
private static void ForLoop(int max)
{
for (int i = 0; i <= max; i++)
{
//Performe Some Operation. By removing Speed increases
var j = 10 + 10;
j += 25;
}
}
private static void DisplayElapsedTime(TimeSpan ts)
{
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
Console.WriteLine(elapsedTime, "RunTime");
}
}
and these are the results of a live demo on DotNetFiddle:
Do While Loop:
00:00:00.06While Loop:
00:00:00.13For Loop:
00:00:00.27
I'm not sure why none of the previous answers worked for me, but I came up with this solution during a eureka moment. It not only works, but it is also most elegant:
Add to body tag:
onmouseup="down=0;" onmousedown="down=1;"
Then test and execute myfunction()
if down
equals 1
:
onmousemove="if (down==1) myfunction();"
You can utilize the fact that the character encodings for digits are all in order from 48 (for '0') to 57 (for '9'). This holds true for ASCII, UTF-x and practically all other encodings (see comments below for more on this).
Therefore the integer value for any digit is the digit minus '0' (or 48).
char c = '1';
int i = c - '0'; // i is now equal to 1, not '1'
is synonymous to
char c = '1';
int i = c - 48; // i is now equal to 1, not '1'
However I find the first c - '0'
far more readable.
In case you wonder, In Bootstrap templating system (which is very accurate), here is how they divide the columns when you apply the class .col-md-4 (1/3 of the 12 column system)
CSS
.col-md-4{
float: left;
width: 33.33333333%;
}
I'm not a fan of float, but if you really want your element to be perfectly 1/3 of your page, then you don't have a choice because sometimes when you use inline-block element, browser can consider space in your HTML as a 1px space which would break your perfect 1/3. Hope it helped !
File
> Import
> General
> Existing Projects into workspace
.
Select the root folder that has your project(s). It lists all the projects available in the selected folder. Select the ones you would like to import and click Finish
. This should work just fine.
For people that find this question by searching for the error message, you can also see this error if you make a mistake in your @JsonProperty
annotations such that you annotate a List
-typed property with the name of a single-valued field:
@JsonProperty("someSingleValuedField") // Oops, should have been "someMultiValuedField"
public List<String> getMyField() { // deserialization fails - single value into List
return myField;
}
Me, Im using vagrant, yet im executing php artisan outside the box so basically it doesn't have permission
JVM head dump is a snapshot of a JVM heap memory in a given time. So its simply a heap representation of JVM. That is the state of the objects.
JVM thread dump is a snapshot of a JVM threads at a given time. So thats what were threads doing at any given time. This is the state of threads. This helps understanding such as locked threads, hanged threads and running threads.
Head dump has more information of java class level information than a thread dump. For example Head dump is good to analyse JVM heap memory issues and OutOfMemoryError errors. JVM head dump is generated automatically when there is something like OutOfMemoryError has taken place. Heap dump can be created manually by killing the process using kill -3 . Generating a heap dump is a intensive computing task, which will probably hang your jvm. so itsn't a methond to use offetenly. Heap can be analysed using tools such as eclipse memory analyser.
Core dump is a os level memory usage of objects. It has more informaiton than a head dump. core dump is not created when we kill a process purposely.
Use JpaRepository
or CrudRepository
as repository interface:
@Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer> {
@Query("SELECT t from Customer t where LOWER(t.name) LIKE %:name%")
public List<Customer> findByName(@Param("name") String name);
}
@Service(value="customerService")
public class CustomerServiceImpl implements CustomerService {
private CustomerRepository customerRepository;
//...
@Override
public List<Customer> pattern(String text) throws Exception {
return customerRepository.findByName(text.toLowerCase());
}
}
You've simply got it backwards. Specifying a minimum width would make the select menu always be at least that width, so it will continue expanding to 90% no matter what the window size is, also being at least the size of its longest option.
You need to use max-width
instead. This way, it will let the select menu expand to its longest option, but if that expands past your set maximum of 90% width, crunch it down to that width.
You can use the ScriptManager.RegisterStartupScript();
to call any of your javascript event/Client Event from the server. For example, to display a message using javascript's alert();
, you can do this:
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Response.write("<script>alert('This is my message');</script>");
//----or alternatively and to be more proper
ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "alert('This is my message')", true);
}
To be exact for you, do this...
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "CalcTotalAmt();", true);
}
let me answer below question
Is there any difference between using an id attribute and using a name attribute on a <bean> tag,
There is no difference. you will experience same effect when id or name is used on a <bean> tag .
How?
Both id and name attributes are giving us a means to provide identifier value to a bean (For this moment, think id means id but not identifier). In both the cases, you will see same result if you call applicationContext.getBean("bean-identifier");
.
Take @Bean, the java equivalent of <bean> tag, you wont find an id attribute. you can give your identifier value to @Bean only through name attribute.
Let me explain it through an example :
Take this configuration file, let's call it as spring1.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<bean id="foo" class="com.intertech.Foo"></bean>
<bean id="bar" class="com.intertech.Bar"></bean>
</beans>
Spring returns Foo object for, Foo f = (Foo) context.getBean("foo");
. Replace id="foo"
with name="foo"
in the above spring1.xml, You will still see the same result.
Define your xml configuration like,
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<bean id="fooIdentifier" class="com.intertech.Foo"></bean>
<bean name="fooIdentifier" class="com.intertech.Foo"></bean>
</beans>
You will get BeanDefinitionParsingException. It will say, Bean name 'fooIdentifier' is already used in this element. By the way, This is the same exception you will see if you have below config
<bean name="fooIdentifier" class="com.intertech.Foo"></bean>
<bean name="fooIdentifier" class="com.intertech.Foo"></bean>
If you keep both id and name to the bean tag, the bean is said to have 2 identifiers. you can get the same bean with any identifier.
take config as
<?xml version="1.0" encoding="UTF-8"?><br>
<beans ...>
<bean id="fooById" name="fooByName" class="com.intertech.Foo"></bean>
<bean id="bar" class="com.intertech.Bar"></bean>
</beans>
the following code prints true
FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(...);
Foo fooById = (Foo) context.getBean("fooById")// returns Foo object;
Foo fooByName = (Foo) context.getBean("fooByName")// returns Foo object;
System.out.println(fooById == fooByName) //true
another great things is using this rule to disable the input & output paths of the CocoaPods script phases (Copy Frameworks & Copy Resources):
install! 'cocoapods',
:disable_input_output_paths => true
Or you can use the function below for removing non-ascii character from the string. You will get know internal working.
private static String removeNonASCIIChar(String str) {
StringBuffer buff = new StringBuffer();
char chars[] = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (0 < chars[i] && chars[i] < 127) {
buff.append(chars[i]);
}
}
return buff.toString();
}
This is an interesting question and since it isn't explained very explicitly in the documentation I'll answer this by going through the sourcecode of mod_rewrite; demonstrating a big benefit of open-source.
In the top section you'll quickly spot the defines used to name these flags:
#define CONDFLAG_NONE 1<<0
#define CONDFLAG_NOCASE 1<<1
#define CONDFLAG_NOTMATCH 1<<2
#define CONDFLAG_ORNEXT 1<<3
#define CONDFLAG_NOVARY 1<<4
and searching for CONDFLAG_ORNEXT confirms that it is used based on the existence of the [OR] flag:
else if ( strcasecmp(key, "ornext") == 0
|| strcasecmp(key, "OR") == 0 ) {
cfg->flags |= CONDFLAG_ORNEXT;
}
The next occurrence of the flag is the actual implementation where you'll find the loop that goes through all the RewriteConditions a RewriteRule has, and what it basically does is (stripped, comments added for clarity):
# loop through all Conditions that precede this Rule
for (i = 0; i < rewriteconds->nelts; ++i) {
rewritecond_entry *c = &conds[i];
# execute the current Condition, see if it matches
rc = apply_rewrite_cond(c, ctx);
# does this Condition have an 'OR' flag?
if (c->flags & CONDFLAG_ORNEXT) {
if (!rc) {
/* One condition is false, but another can be still true. */
continue;
}
else {
/* skip the rest of the chained OR conditions */
while ( i < rewriteconds->nelts
&& c->flags & CONDFLAG_ORNEXT) {
c = &conds[++i];
}
}
}
else if (!rc) {
return 0;
}
}
You should be able to interpret this; it means that OR has a higher precedence, and your example indeed leads to if ( (A OR B) AND (C OR D) )
. If you would, for example, have these Conditions:
RewriteCond A [or]
RewriteCond B [or]
RewriteCond C
RewriteCond D
it would be interpreted as if ( (A OR B OR C) and D )
.
This is a guess :)
Is it because the ID is a string? What happens if you change it to int?
I mean:
public int Id { get; set; }
%Started Program or Command% | taskkill /F /IM cmd.exe
Example:
notepad.exe | taskkill /F /IM cmd.exe
MySQL uses CONCAT() to concatenate strings
SELECT * FROM tableOne
LEFT JOIN tableTwo
ON tableTwo.query = CONCAT('category_id=', tableOne.category_id)
The problem is in the network layer. Here are the status codes explained:
Connection refused
: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.
Connection timed out
: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.
That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.
Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.
It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.
As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.
To rule out network congestion as a problem you could use a tool like mtr
or traceroute
or even ping
to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.
Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).
If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp
is definetly recommended then.
For me the easiest way to get it to work, is to put the component.requestFocus();
line, after the setVisible(true);
line, at the bottom of your frame or panel constructor.
This probably has something to do with asking for the focus, after all components have been created, because creating a new component, after asking for the focus request, will make your component loose te focus, and make the focus go to your newly created component. At least, that's what I assume.
My application is using Mura CMS and I faced this issue. However the solution was the password mismatch between my mysql local server and the password in the config files. As soon as I synched them it worked.
For fullscreen of browser rendering area there is a simple solution supported by all modern browsers.
div#placeholder {
height: 100vh;
}
The only notable exception is the Android below 4.3 - but ofc only in the system browser/webview element (Chrome works ok).
Browser support chart: http://caniuse.com/viewport-units
For fullscreen of monitor please use HTML5 Fullscreen API
You just CAST()
this way
SELECT cast(yourNumber as varchar(10))
FROM yourTable
Then if you want to JOIN
based on it, you can use:
SELECT *
FROM yourTable t1
INNER JOIN yourOtherTable t2
on cast(t1.yourNumber as varchar(10)) = t2.yourString
On the recent version (from Yosemite or El Capitan I believe... at least from Sierra onward), you need to run brew postinstall python3
after brew install python3
if you use homebrew.
So,
brew install python3 # this only installs python
brew postinstall python3 # this installs pip
According to the official Homebrew page:
On 1st March 2018 the python formula will be upgraded to Python 3.x and a python@2 formula will be added for installing Python 2.7 (although this will be keg-only so neither python nor python2 will be added to the PATH by default without a manual brew link --force). We will maintain python2, python3 and python@3 aliases.
So to install Python 3, run the following command:
brew install python3
Then, the pip
is installed automatically, and you can install any package by pip install <package>
.
There is also a great open source tool called clink, which extends cmd by many features. One of them is being able to use ctrl+v to insert text.
Here's how you get the image size from the given URL in Python 3:
from PIL import Image
import urllib.request
from io import BytesIO
file = BytesIO(urllib.request.urlopen('http://getwallpapers.com/wallpaper/full/b/8/d/32803.jpg').read())
im = Image.open(file)
width, height = im.size
<androidx.appcompat.widget.SwitchCompat
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
app:track="@drawable/track"
android:thumb="@drawable/thumb"
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false"
android:drawable="@drawable/switch_thumb_false"/>
<item android:state_checked="true"
android:drawable="@drawable/switch_thumb_true"/>
</selector>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false">
<shape android:shape="rectangle">
<size android:width="24dp" android:height="12dp" />
<solid android:color="#EFE0BB" />
<corners android:radius="6dp" />
</shape>
</item>
<item android:state_checked="true">
<shape android:shape="rectangle">
<size android:width="24dp" android:height="12dp" />
<solid android:color="@color/colorPrimary" />
<corners android:radius="6dp" />
</shape>
</item>
</selector>
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="#EFE0BB" />
<size
android:width="10dp"
android:height="10dp" />
<stroke
android:width="2dp"
android:color="@color/colorPrimary" />
</shape>
</item>
</layer-list>
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item >
<shape android:shape="oval">
<solid android:color="@color/colorPrimary"/>
<size android:height="12dp"
android:width="12dp"/>
<stroke android:color="#EFE0BB"
android:width="2dp"/>
</shape>
</item>
</layer-list>
The answers that have no less that 2739 upvotes by now are misleading and incorrect.
The question is: "How do you empty your existing array?" E.g. for A = [1,2,3,4]
.
Saying "A = []
is the answer" is ignorant and absolutely incorrect. [] == []
is false.
This is because these two arrays are two separate, individual objects, with their own two identities, taking up their own space in the digital world, each on its own.
Let's say your mother asks you to empty the trash can.
A = [1,2,3,4]; A = [];
Emptying an array object is the easiest thing ever:
A.length = 0;
This way, the can under "A" is not only empty, but also as clean as new!
Furthermore, you are not required to remove the trash by hand until the can is empty! You were asked to empty the existing one, completely, in one turn, not to pick up the trash until the can gets empty, as in:
while(A.length > 0) {
A.pop();
}
Nor, to put your left hand at the bottom of the trash, holding it with your right at the top to be able to pull its content out as in:
A.splice(0, A.length);
No, you were asked to empty it:
A.length = 0;
This is the only code that correctly empties the contents of a given JavaScript array.
Font's don't have a color; only when using the font you can set the color of the component. For example, when using a JTextArea:
JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);
According to this link, the createFont() method creates a new Font object with a point size of 1 and style PLAIN. So, if you want to increase the size of the Font, you need to do this:
Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
return font.deriveFont(12f);
$(document).ready(function() {
var value = $("#unixtime").val(); //this retrieves the unix timestamp
var dateString = moment(value, 'MM/DD/YYYY', false).calendar();
alert(dateString);
});
There is a strict mode and a Forgiving mode.
While strict mode works better in most situations, forgiving mode can be very useful when the format of the string being passed to moment may vary.
In a later release, the parser will default to using strict mode. Strict mode requires the input to the moment to exactly match the specified format, including separators. Strict mode is set by passing true as the third parameter to the moment function.
A common scenario where forgiving mode is useful is in situations where a third party API is providing the date, and the date format for that API could change. Suppose that an API starts by sending dates in 'YYYY-MM-DD' format, and then later changes to 'MM/DD/YYYY' format.
In strict mode, the following code results in 'Invalid Date' being displayed:
moment('01/12/2016', 'YYYY-MM-DD', true).format()
"Invalid date"
In forgiving mode using a format string, you get a wrong date:
moment('01/12/2016', 'YYYY-MM-DD').format()
"2001-12-20T00:00:00-06:00"
another way would be
$(document).ready(function() {
var value = $("#unixtime").val(); //this retrieves the unix timestamp
var dateString = moment.unix(value).calendar();
alert(dateString);
});
A functional way can be achieved using filter
and lambda
operator.
list1 = [1,2,3,4,5,6]
list2 = [2,4,6,9,10]
>>> list(filter(lambda x:x in list1, list2))
[2, 4, 6]
Edit: It filters out x that exists in both list1 and list, set difference can also be achieved using:
>>> list(filter(lambda x:x not in list1, list2))
[9,10]
Edit2: python3 filter
returns a filter object, encapsulating it with list
returns the output list.
Thought to add my solution for this, after spending a few hours on the same error :(
The guys above were correct that the first thing you should check is whether you had missed adding any frameworks, see the steps provided by Pruthvid above.
My problem, it turned out, was a compile class missing after I deleted it, and later added it back in again.
Check your "Compile Sources" as shown for the reported error classes. Add in any missing classes that you created.
$Date = $row['Received_date']->format('d/m/Y');
then it cast date object from given in database
I found this blog post which explains that it's used to record clicks. Without official word from Google it could be used any number of things.
http://mark.koli.ch/2009/03/howto-configure-apache-to-return-a-http-204-no-content-for-ajax.html
You can simply use a property of the page. And the interesting thing is that you can access that property anywhere in your code.
Use this:
HttpContext.Current.User.Identity.Name
For the UI plugin, with jsp page and Spring MVC..
Sample html. Needs to be within a form element with an id attribute of fileupload
<!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
<div class="fileupload-buttonbar">
<div>
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add files</span>
<input id="fileuploadInput" type="file" name="files[]" multiple>
</span>
<%-- https://stackoverflow.com/questions/925334/how-is-the-default-submit-button-on-an-html-form-determined --%>
<button type="button" class="btn btn-primary start">
<i class="glyphicon glyphicon-upload"></i>
<span>Start upload</span>
</button>
<button type="reset" class="btn btn-warning cancel">
<i class="glyphicon glyphicon-ban-circle"></i>
<span>Cancel upload</span>
</button>
<!-- The global file processing state -->
<span class="fileupload-process"></span>
</div>
<!-- The global progress state -->
<div class="fileupload-progress fade">
<!-- The global progress bar -->
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar progress-bar-success" style="width:0%;"></div>
</div>
<!-- The extended global progress state -->
<div class="progress-extended"> </div>
</div>
</div>
<!-- The table listing the files available for upload/download -->
<table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/css/jquery.fileupload.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/css/jquery.fileupload-ui.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/vendor/jquery.ui.widget.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.iframe-transport.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.fileupload.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.fileupload-process.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.fileupload-validate.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.fileupload-ui.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var maxFileSizeBytes = ${maxFileSizeBytes};
if (maxFileSizeBytes < 0) {
//-1 or any negative value means no size limit
//set to undefined
//https://stackoverflow.com/questions/5795936/how-to-set-a-javascript-var-as-undefined
maxFileSizeBytes = void 0;
}
//https://github.com/blueimp/jQuery-File-Upload/wiki/Options
//https://stackoverflow.com/questions/34063348/jquery-file-upload-basic-plus-ui-and-i18n
//https://stackoverflow.com/questions/11337897/how-to-customize-upload-download-template-of-blueimp-jquery-file-upload
$('#fileupload').fileupload({
url: '${pageContext.request.contextPath}/app/uploadResources.do',
fileInput: $('#fileuploadInput'),
acceptFileTypes: /(\.|\/)(jrxml|png|jpe?g)$/i,
maxFileSize: maxFileSizeBytes,
messages: {
acceptFileTypes: '${fileTypeNotAllowedText}',
maxFileSize: '${fileTooLargeMBText}'
},
filesContainer: $('.files'),
uploadTemplateId: null,
downloadTemplateId: null,
uploadTemplate: function (o) {
var rows = $();
$.each(o.files, function (index, file) {
var row = $('<tr class="template-upload fade">' +
'<td><p class="name"></p>' +
'<strong class="error text-danger"></strong>' +
'</td>' +
'<td><p class="size"></p>' +
'<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">' +
'<div class="progress-bar progress-bar-success" style="width:0%;"></div></div>' +
'</td>' +
'<td>' +
(!index && !o.options.autoUpload ?
'<button class="btn btn-primary start" disabled>' +
'<i class="glyphicon glyphicon-upload"></i> ' +
'<span>${startText}</span>' +
'</button>' : '') +
(!index ? '<button class="btn btn-warning cancel">' +
'<i class="glyphicon glyphicon-ban-circle"></i> ' +
'<span>${cancelText}</span>' +
'</button>' : '') +
'</td>' +
'</tr>');
row.find('.name').text(file.name);
row.find('.size').text(o.formatFileSize(file.size));
if (file.error) {
row.find('.error').text(file.error);
}
rows = rows.add(row);
});
return rows;
},
downloadTemplate: function (o) {
var rows = $();
$.each(o.files, function (index, file) {
var row = $('<tr class="template-download fade">' +
'<td><p class="name"></p>' +
(file.error ? '<strong class="error text-danger"></strong>' : '') +
'</td>' +
'<td><span class="size"></span></td>' +
'<td>' +
(file.deleteUrl ? '<button class="btn btn-danger delete">' +
'<i class="glyphicon glyphicon-trash"></i> ' +
'<span>${deleteText}</span>' +
'</button>' : '') +
'<button class="btn btn-warning cancel">' +
'<i class="glyphicon glyphicon-ban-circle"></i> ' +
'<span>${clearText}</span>' +
'</button>' +
'</td>' +
'</tr>');
row.find('.name').text(file.name);
row.find('.size').text(o.formatFileSize(file.size));
if (file.error) {
row.find('.error').text(file.error);
}
if (file.deleteUrl) {
row.find('button.delete')
.attr('data-type', file.deleteType)
.attr('data-url', file.deleteUrl);
}
rows = rows.add(row);
});
return rows;
}
});
});
</script>
Sample upload and delete request handlers
@PostMapping("/app/uploadResources")
public @ResponseBody
Map<String, List<FileUploadResponse>> uploadResources(MultipartHttpServletRequest request,
Locale locale) {
//https://github.com/jdmr/fileUpload/blob/master/src/main/java/org/davidmendoza/fileUpload/web/ImageController.java
//https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#using-jquery-file-upload-ui-version-with-a-custom-server-side-upload-handler
Map<String, List<FileUploadResponse>> response = new HashMap<>();
List<FileUploadResponse> fileList = new ArrayList<>();
String deleteUrlBase = request.getContextPath() + "/app/deleteResources.do?filename=";
//http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/multipart/MultipartRequest.html
Iterator<String> itr = request.getFileNames();
while (itr.hasNext()) {
String htmlParamName = itr.next();
MultipartFile file = request.getFile(htmlParamName);
FileUploadResponse fileDetails = new FileUploadResponse();
String filename = file.getOriginalFilename();
fileDetails.setName(filename);
fileDetails.setSize(file.getSize());
try {
String message = saveFile(file);
if (message != null) {
String errorMessage = messageSource.getMessage(message, null, locale);
fileDetails.setError(errorMessage);
} else {
//save successful
String encodedFilename = URLEncoder.encode(filename, "UTF-8");
String deleteUrl = deleteUrlBase + encodedFilename;
fileDetails.setDeleteUrl(deleteUrl);
}
} catch (IOException ex) {
logger.error("Error", ex);
fileDetails.setError(ex.getMessage());
}
fileList.add(fileDetails);
}
response.put("files", fileList);
return response;
}
@PostMapping("/app/deleteResources")
public @ResponseBody
Map<String, List<Map<String, Boolean>>> deleteResources(@RequestParam("filename") List<String> filenames) {
Map<String, List<Map<String, Boolean>>> response = new HashMap<>();
List<Map<String, Boolean>> fileList = new ArrayList<>();
String templatesPath = Config.getTemplatesPath();
for (String filename : filenames) {
Map<String, Boolean> fileDetails = new HashMap<>();
String cleanFilename = ArtUtils.cleanFileName(filename);
String filePath = templatesPath + cleanFilename;
File file = new File(filePath);
boolean deleted = file.delete();
if (deleted) {
fileDetails.put(cleanFilename, true);
} else {
fileDetails.put(cleanFilename, false);
}
fileList.add(fileDetails);
}
response.put("files", fileList);
return response;
}
Sample class for generating the required json response
public class FileUploadResponse {
//https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#using-jquery-file-upload-ui-version-with-a-custom-server-side-upload-handler
private String name;
private long size;
private String error;
private String deleteType = "POST";
private String deleteUrl;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the size
*/
public long getSize() {
return size;
}
/**
* @param size the size to set
*/
public void setSize(long size) {
this.size = size;
}
/**
* @return the error
*/
public String getError() {
return error;
}
/**
* @param error the error to set
*/
public void setError(String error) {
this.error = error;
}
/**
* @return the deleteType
*/
public String getDeleteType() {
return deleteType;
}
/**
* @param deleteType the deleteType to set
*/
public void setDeleteType(String deleteType) {
this.deleteType = deleteType;
}
/**
* @return the deleteUrl
*/
public String getDeleteUrl() {
return deleteUrl;
}
/**
* @param deleteUrl the deleteUrl to set
*/
public void setDeleteUrl(String deleteUrl) {
this.deleteUrl = deleteUrl;
}
}
See https://pitipata.blogspot.co.ke/2017/01/using-jquery-file-upload-ui.html
In my experience, most often this error message means that you have put an accidental closing brace somewhere, leaving the rest of your statements outside the function.
Example:
function a() {
if (global_block) //syntax error is actually here - missing opening brace
return;
} //this unintentionally ends the function
if (global_somethingelse) {
//Chrome will show the error occurring here,
//but actually the error is in the previous statement
return;
}
//do something
}
What is the difference between char array vs char pointer in C?
C99 N1256 draft
There are two different uses of character string literals:
Initialize char[]
:
char c[] = "abc";
This is "more magic", and described at 6.7.8/14 "Initialization":
An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
So this is just a shortcut for:
char c[] = {'a', 'b', 'c', '\0'};
Like any other regular array, c
can be modified.
Everywhere else: it generates an:
So when you write:
char *c = "abc";
This is similar to:
/* __unnamed is magic because modifying it gives UB. */
static char __unnamed[] = "abc";
char *c = __unnamed;
Note the implicit cast from char[]
to char *
, which is always legal.
Then if you modify c[0]
, you also modify __unnamed
, which is UB.
This is documented at 6.4.5 "String literals":
5 In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence [...]
6 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
6.7.8/32 "Initialization" gives a direct example:
EXAMPLE 8: The declaration
char s[] = "abc", t[3] = "abc";
defines "plain" char array objects
s
andt
whose elements are initialized with character string literals.This declaration is identical to
char s[] = { 'a', 'b', 'c', '\0' }, t[] = { 'a', 'b', 'c' };
The contents of the arrays are modifiable. On the other hand, the declaration
char *p = "abc";
defines
p
with type "pointer to char" and initializes it to point to an object with type "array of char" with length 4 whose elements are initialized with a character string literal. If an attempt is made to usep
to modify the contents of the array, the behavior is undefined.
GCC 4.8 x86-64 ELF implementation
Program:
#include <stdio.h>
int main(void) {
char *s = "abc";
printf("%s\n", s);
return 0;
}
Compile and decompile:
gcc -ggdb -std=c99 -c main.c
objdump -Sr main.o
Output contains:
char *s = "abc";
8: 48 c7 45 f8 00 00 00 movq $0x0,-0x8(%rbp)
f: 00
c: R_X86_64_32S .rodata
Conclusion: GCC stores char*
it in .rodata
section, not in .text
.
If we do the same for char[]
:
char s[] = "abc";
we obtain:
17: c7 45 f0 61 62 63 00 movl $0x636261,-0x10(%rbp)
so it gets stored in the stack (relative to %rbp
).
Note however that the default linker script puts .rodata
and .text
in the same segment, which has execute but no write permission. This can be observed with:
readelf -l a.out
which contains:
Section to Segment mapping:
Segment Sections...
02 .text .rodata
The following is also working for me:
ssh <user>@<host> "cat <filepath>"|pbcopy
You might want to also try this application http://pdfbox.apache.org/. A working example can be found at https://www.jinises.com
The spring data JPA query needs the "%" chars as well as a space char following like
in your query, as in
@Query("Select c from Registration c where c.place like %:place%")
.
Cf. http://docs.spring.io/spring-data/jpa/docs/current/reference/html.
You may want to get rid of the @Query
annotation alltogether, as it seems to resemble the standard query (automatically implemented by the spring data proxies); i.e. using the single line
List<Registration> findByPlaceContaining(String place);
is sufficient.
If the delimiter is /, you will need to escape.
If you go the brew route, the best way to install would be:
brew install macvim --with-override-system-vim
That will provide mvim, vim, vi, view, etc. in /usr/local/bin (all symlinked to the copy in the Cellar). This also removes the need to create any aliases and also changes your vi, vim, etc. to all use the same Vim distribution as your MacVim.
If you know that the value of the XML element is a float number (latitude, longitude, distance), you can use (float)
$value = (float) $xml->code[0]->lat;
Also, (int)
for integer number:
$value = (int) $xml->code[0]->distance;
for others there are a solution for any API level , you can place a item on top of each other example :
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- my firt item with 4 corners radius(8dp)
-->
<item>
<shape>
<solid
android:angle="270.0"
android:color="#3D689A" />
<corners android:topLeftRadius="8dp" />
</shape>
</item>
<!-- my second item is on top right for a fake corner radius(0dp)
-->
<item
android:bottom="30dp"
android:left="50dp">
<shape>
<solid android:color="#5C83AF" />
</shape>
</item>
<!-- my third item is on bottom left for a fake corner radius(0dp)
-->
<item
android:right="50dp"
android:top="30dp">
<shape>
<solid android:color="#5C83AF" />
</shape>
</item>
</layer-list>
the result with light color to show you the three items :
the final result :
Best regards.
Unfortunately strictly none of the above solutions worked for me in 2016 (a couple years after the question)
So here's the aggressive solution I use:
function remake(e){
var val = e.value;
var id = e.id;
e.outerHTML = e.outerHTML;
document.getElementById(id).value = val;
return true;
}
<input id=MustHaveAnId type=text name=email autocomplete=on onblur="remake(this)">
Basically, it deletes the tag while saving the value, and recreates it, then puts back the value.
Alternatively to Link Library Dependencies
in project properties there is another way to link libraries in Visual Studio.
Add Existing Item...
).Item Type
is Library
This will include the other libraries in X as if you ran
lib /out:X.lib X.lib other1.lib other2.lib
I believe you need subexpressions. If I remember right you can use the normal ()
brackets for subexpressions.
This part is From grep manual:
Back References and Subexpressions
The back-reference \n, where n is a single digit, matches the substring
previously matched by the nth parenthesized subexpression of the
regular expression.
Do something like ^[^(abc)]
should do the trick.
It seems you have more than one version of Python on your computer. Try and remove one and leave the only version you used to develop your application.
If need be, you can upgrade your version, but ensure you have only one version of Python on your computer.
I hope this helps.
If you need to increase MySQL Connections without MySQL restart do like below
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 100 |
+-----------------+-------+
1 row in set (0.00 sec)
mysql> SET GLOBAL max_connections = 150;
Query OK, 0 rows affected (0.00 sec)
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 150 |
+-----------------+-------+
1 row in set (0.00 sec)
These settings will change at MySQL Restart.
For permanent changes add below line in my.cnf and restart MySQL
max_connections = 150
Short answer: You can't.
Long answer:
Due to the way generics is implemented in Java, the generic type T is not kept at runtime. Still, you can use a private data member:
public class Foo<T>
{
private Class<T> type;
public Foo(Class<T> type) { this.type = type; }
}
Usage example:
Foo<Integer> test = new Foo<Integer>(Integer.class);
By omitting all parts of the head, the loop can also become infinite:
for (;;) {}
Issue resolved.!!! Below are the solutions.
For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar
Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
Issue is that it is failed to decrypt 256 bits of encryption.
Here's a fairly straight forward and dynamic way. For last month's last day, subtract the current numeric day from today's date. For first day of last month, use the same code, just repeat subtracting the numeric day from the prior result and add 1.
declare @PriorEOM as datetime
declare @PriorFOM as datetime
Set @PriorEOM = dateadd(day,-day(getdate()),getdate())
Set @PriorFOM = dateadd(day,-day(@PriorEOM) + 1,@PriorEOM)
Print @PriorEOM
Print @PriorFOM
Split it by space
and take first part like below. Hope this will help you.
var d = '12/12/1955 12:00:00 AM';
d = d.split(' ')[0];
console.log(d);
public static class DotNetHelper
{
public static Version InstalledVersion
{
get
{
string framework = null;
try
{
using (var ndpKey =
Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\"))
{
if (ndpKey != null)
{
var releaseKey = ndpKey.GetValue("Release");
if (releaseKey != null)
{
framework = CheckFor45PlusVersion(Convert.ToInt32(releaseKey));
}
else
{
string[] versionNames = null;
using (var installedVersions =
Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP"))
{
if (installedVersions != null) versionNames = installedVersions.GetSubKeyNames();
}
try
{
if (versionNames != null && versionNames.Length > 0)
{
framework = versionNames[versionNames.Length - 1].Remove(0, 1);
}
}
catch (FormatException)
{
}
}
}
}
}
catch (SecurityException)
{
}
return framework != null ? new Version(framework) : null;
}
}
private static string CheckFor45PlusVersion(int releaseKey)
{
if (releaseKey >= 460798)
return "4.7";
if (releaseKey >= 394802)
return "4.6.2";
if (releaseKey >= 394254)
return "4.6.1";
if (releaseKey >= 393295)
return "4.6";
if (releaseKey >= 379893)
return "4.5.2";
if (releaseKey >= 378675)
return "4.5.1";
// This code should never execute. A non-null release key should mean
// that 4.5 or later is installed.
return releaseKey >= 378389 ? "4.5" : null;
}
}
The clearInterval() method can be used to clear a timer set with the setInterval() method.
setInterval always returns a ID value. This value can be passed in clearInterval() to stop the timer. Here is an example of timer starting from 30 and stops when it becomes 0.
let time = 30;
const timeValue = setInterval((interval) => {
time = this.time - 1;
if (time <= 0) {
clearInterval(timeValue);
}
}, 1000);
It is common practice in C++. This is because in C++ you can't have same name for the member function and member variable, and getter functions are often named without "get" prefix.
class Person
{
public:
std::string name() const;
private:
std::string name; // This would lead to a compilation error.
std::string m_name; // OK.
};
main.cpp:9:19: error: duplicate member 'name' std::string name; ^ main.cpp:6:19: note: previous declaration is here std::string name() const; ^ 1 error generated.
"m_" states for the "member". Prefix "_" is also common.
You shouldn't use it in programming languages that solve this problem by using different conventions/grammar.
<a href="javascript:alert('Hello');"></a>
is just shorthand for:
<a href="" onclick="alert('Hello'); return false;"></a>
Use
label.setOpaque(true);
Otherwise the background is not painted, since the default of opaque
is false
for JLabel
.
From the JavaDocs:
If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.
For more information, read the Java Tutorial How to Use Labels.
The error log is straightforward. As it suggested,You need to add 198.211.99.20 to your ALLOWED_HOSTS
setting.
In your project settings.py file,set ALLOWED_HOSTS
like this :
ALLOWED_HOSTS = ['198.211.99.20', 'localhost', '127.0.0.1']
For further reading read from here.
In my case i had some problem with opacity transition so this one fix it:
#dropdown {
transition:.6s opacity;
}
#dropdown.ns {
opacity:0;
transition:.6s all;
}
#dropdown.fade {
opacity:1;
}
Mouse Enter
$('#dropdown').removeClass('ns').addClass('fade');
Mouse Leave
$('#dropdown').addClass('ns').removeClass('fade');
Don't forget nullability.
ALTER TABLE <schemaName>.<tableName>
ALTER COLUMN <columnName> nvarchar(200) [NULL|NOT NULL]
As of matplotlib 3.3, you can do this with plt.axline((x1, y1), (x2, y2))
.
This error occurred for me because mod_rewrite was not enabled. Everything worked fine after enabling the rewrite module: https://www.debuntu.org/how-to-enable-apache-modules-under-debian-based-system-page-2/
I know this thread is little old, but would like to add my 2 cents. We had the same "connection reset" error right after our one of the releases.
The root cause was, our apache
server was brought down for deployment. All our third party traffic goes thru apache
and we were getting connection reset error because of it being down.
Just for the record, you can filter on data with jquery (this question is quite old, and jQuery evolved since then, so it's right to write this solution as well):
$('.navlink[data-selected="true"]');
or, better (for performance):
$('.navlink').filter('[data-selected="true"]');
or, if you want to get all the elements with data-selected
set:
$('[data-selected]')
Note that this method will only work with data that was set via html-attributes. If you set or change data with the .data()
call, this method will no longer work.
I always use pseudo elements :before
and :after
for changing the appearance of checkboxes and radio buttons. it's works like a charm.
Refer this link for more info
Steps
visibility:hidden
or opacity:0
or position:absolute;left:-9999px
etc.:before
element and pass either an empty or a non-breaking space '\00a0'
;:checked
state, pass the unicode content: "\2713"
, which is a checkmark;:focus
style to make the checkbox accessible.Here is how I did it.
.box {_x000D_
background: #666666;_x000D_
color: #ffffff;_x000D_
width: 250px;_x000D_
padding: 10px;_x000D_
margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
margin: 1.5em 0;_x000D_
padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
visibility: hidden;_x000D_
}_x000D_
label {_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
border: 1px solid #333;_x000D_
content: "\00a0";_x000D_
display: inline-block;_x000D_
font: 16px/1em sans-serif;_x000D_
height: 16px;_x000D_
margin: 0 .25em 0 0;_x000D_
padding: 0;_x000D_
vertical-align: top;_x000D_
width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
background: #fff;_x000D_
color: #333;_x000D_
content: "\2713";_x000D_
text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
<div class="box">_x000D_
<p>_x000D_
<input type="checkbox" id="c1" name="cb">_x000D_
<label for="c1">Option 01</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c2" name="cb">_x000D_
<label for="c2">Option 02</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c3" name="cb">_x000D_
<label for="c3">Option 03</label>_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
Much more stylish using :before
and :after
body{_x000D_
font-family: sans-serif; _x000D_
}_x000D_
_x000D_
.container {_x000D_
margin-top: 50px;_x000D_
margin-left: 20px;_x000D_
margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
width: 100%;_x000D_
margin: 15px auto;_x000D_
position: relative;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
width: auto;_x000D_
opacity: 0.00000001;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
content: '';_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
margin: 4px;_x000D_
width: 22px;_x000D_
height: 22px;_x000D_
transition: transform 0.28s ease;_x000D_
border-radius: 3px;_x000D_
border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
content: '';_x000D_
display: block;_x000D_
width: 10px;_x000D_
height: 5px;_x000D_
border-bottom: 2px solid #7bbe72;_x000D_
border-left: 2px solid #7bbe72;_x000D_
-webkit-transform: rotate(-45deg) scale(0);_x000D_
transform: rotate(-45deg) scale(0);_x000D_
transition: transform ease 0.25s;_x000D_
will-change: transform;_x000D_
position: absolute;_x000D_
top: 12px;_x000D_
left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
-webkit-transform: rotate(-45deg) scale(1);_x000D_
transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
min-height: 34px;_x000D_
display: block;_x000D_
padding-left: 40px;_x000D_
margin-bottom: 0;_x000D_
font-weight: normal;_x000D_
cursor: pointer;_x000D_
vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
-webkit-transform: translateY(-50%);_x000D_
transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox" name="" value="">_x000D_
<label for="checkbox"><span>Checkbox</span></label>_x000D_
</div>_x000D_
_x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox2" name="" value="">_x000D_
<label for="checkbox2"><span>Checkbox</span></label>_x000D_
</div>_x000D_
</div>
_x000D_
I never considered changing my font, I have always been happy with Courier. This thread has truely opened my eyes, if only I could upvote it!
Went with Droid Sans Mono.
The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.
You can link the table either manually or with VBA like this
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
FileName:="C:\MyData.csv", HasFieldNames:=true
Dim db As DAO.Database
' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next: db.TableDefs.Delete "tblImport": On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh
' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
& "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close: Set db = Nothing
AFAIK there is no way to visually see line endings in the editor space, but in the bottom-right corner of the window there is an indicator that says "CLRF" or "LF" which will let you set the line endings for a particular file. Clicking on the text will allow you to change the line endings as well.
The .cer and .crt file should be interchangable as far as importing them into a keystore.
Take a look at the contents of the .cer file. Erase anything before the -----BEGIN CERTIFICATE-----
line and after the -----END CERTIFICATE-----
line. You'll be left with the BEGIN/END lines with a bunch of Base64-encoded stuff between them.
-----BEGIN CERTIFICATE-----
MIIDQTCCAqqgAwIBAgIJALQea21f1bVjMA0GCSqGSIb3DQEBBQUAMIG1MQswCQYD
...
pfDACIDHTrwCk5OefMwArfEkSBo/
-----END CERTIFICATE-----
Then just import it into your keyfile using keytool.
keytool -import -alias myalias -keystore my.keystore -trustcacerts -file mycert.cer
List is just an interface. The question is: is your actual List implementation serializable? Speaking about the standard List implementations (ArrayList, LinkedList) from the Java run-time, most of them actually are already.
For those of you who just want to allow max. 2 <br>
in a row, you can use this:
let text = text.replace(/(\r?\n){2,}/g, '<br><br>');
text = text.replace(/(\r?\n)/g, '<br>');
First line: Search for \n
OR \r\n
where at least 2 of them are in a row, e.g. \n\n\n\n
. Then replace it with 2 br
Second line: Search for all single \r\n
or \n
and replace them with <br>
String is immutable means that you cannot change the object itself, but you can change the reference to the object.
When you execute a = "ty"
, you are actually changing the reference of a
to a new object created by the String literal "ty"
.
Changing an object means to use its methods to change one of its fields (or the fields are public and not final, so that they can be updated from outside without accessing them via methods), for example:
Foo x = new Foo("the field");
x.setField("a new field");
System.out.println(x.getField()); // prints "a new field"
While in an immutable class (declared as final, to prevent modification via inheritance)(its methods cannot modify its fields, and also the fields are always private and recommended to be final), for example String, you cannot change the current String but you can return a new String, i.e:
String s = "some text";
s.substring(0,4);
System.out.println(s); // still printing "some text"
String a = s.substring(0,4);
System.out.println(a); // prints "some"
I usually read data by data reader this way. just added a small example.
string connectionString = "Data Source=DESKTOP-2EV7CF4;Initial Catalog=TestDB;User ID=sa;Password=tintin11#";
string queryString = "Select * from EMP";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(queryString, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));
}
}
reader.Close();
}
}
You can write
i = 5 + tup()[0]
Tuples can be indexed just like lists.
The main difference between tuples and lists is that tuples are immutable - you can't set the elements of a tuple to different values, or add or remove elements like you can from a list. But other than that, in most situations, they work pretty much the same.
If you want to center it on the frame you are currently in, I would recommend this function:
function popupwindow(url, title, w, h) {
var y = window.outerHeight / 2 + window.screenY - ( h / 2)
var x = window.outerWidth / 2 + window.screenX - ( w / 2)
return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + y + ', left=' + x);
}
Similar to Crazy Tim's answer, but doesn't use window.top. This way, it will work even if the window is embedded in an iframe from a different domain.
Try this: (Completely Dynamic...)
<?php
$host = "localhost";
$user = "username_here";
$pass = "password_here";
$db_name = "database_name_here";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT * FROM products");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
?>
Cloning the objects before adding them. For example, instead of newList.addAll(oldList);
for(Person p : oldList) {
newList.add(p.clone());
}
Assuming clone
is correctly overriden inPerson
.
/* Microsoft Edge Browser 12-18 (All versions before Chromium) - one-liner method */
_:-ms-lang(x), _:-webkit-full-screen, .selector { property:value; }
That works great!
// for instance:
_:-ms-lang(x), _:-webkit-full-screen, .headerClass
{
border: 1px solid brown;
}
https://jeffclayton.wordpress.com/2015/04/07/css-hacks-for-windows-10-and-spartan-browser-preview/
Sometimes you have loops becouse your type class have references to other classes and that classes have references to your type class, thus you have to select the parameters that you need exactly in the json string, like this code.
List<ROficina> oficinas = new List<ROficina>();
oficinas = /*list content*/;
var x = JsonConvert.SerializeObject(oficinas.Select(o => new
{
o.IdOficina,
o.Nombre
}));
By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers:
old 1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new 1: insert into customers (customer_name) values ('Marks Ltd')
1 row created.
SQL> select customer_name from customers;
CUSTOMER_NAME
------------------------------
Marks Ltd
If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off
to switch off the behaviour while running the script:
SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
1 row created.
SQL> select customer_name from customers;
CUSTOMER_NAME
------------------------------
Marks & Spencers Ltd
You might want to add set define on
at the end of the script to restore the default behaviour.
UPDATE totals
SET total = total + 1
WHERE name = 'bill';
If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:
UPDATE totals
SET total = total + 1
WHERE name = 'bill'
AND total = 203;
restarting IIS solved the same issue in my case. Seems like something fails in IIS. Didn't worth my panic, either.
IIS 7.5, btw.
your thinking about this program below
#include <stdio.h>
#include <string.h>
int main ()
{
char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
int n;
puts ("Looking for R2 astromech droids...");
for (n=0 ; n<3 ; n++)
if (strncmp (str[n],"R2xx",2) == 0)
{
printf ("found %s\n",str[n]);
}
return 0;
}
//outputs:
//
//Looking for R2 astromech droids...
//found R2D2
//found R2A6
when you should be thinking about inputting something into an array & then use strcmp functions like the program above ... check out a modified program below
#include <iostream>
#include<cctype>
#include <string.h>
#include <string>
using namespace std;
int main()
{
int Students=2;
int Projects=3, Avg2=0, Sum2=0, SumT2=0, AvgT2=0, i=0, j=0;
int Grades[Students][Projects];
for(int j=0; j<=Projects-1; j++){
for(int i=0; i<=Students; i++) {
cout <<"Please give grade of student "<< j <<"in project "<< i << ":";
cin >> Grades[j][i];
}
Sum2 = Sum2 + Grades[i][j];
Avg2 = Sum2/Students;
}
SumT2 = SumT2 + Avg2;
AvgT2 = SumT2/Projects;
cout << "avg is : " << AvgT2 << " and sum : " << SumT2 << ":";
return 0;
}
change to string except it only reads 1 input and throws the rest out maybe need two for loops and two pointers
#include <cstring>
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
char name[100];
//string userInput[26];
int i=0, n=0, m=0;
cout<<"your name? ";
cin>>name;
cout<<"Hello "<<name<< endl;
char *ptr=name;
for (i = 0; i < 20; i++)
{
cout<<i<<" "<<ptr[i]<<" "<<(int)ptr[i]<<endl;
}
int length = 0;
while(name[length] != '\0')
{
length++;
}
for(n=0; n<4; n++)
{
if (strncmp(ptr, "snit", 4) == 0)
{
cout << "you found the snitch " << ptr[i];
}
}
cout<<name <<"is"<<length<<"chars long";
}
I had the same issue and came across different solutions by implementing which I used to face several different issues. Finally, below is what I put some pieces from different posts together which worked for me as expected.
private void btnCompare_Click(object sender, EventArgs e)
{
ThreadStart threadStart = new ThreadStart(Execution);
Thread thread = new Thread(threadStart);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
Here is the Execution method that also carries invoking the PictureBox control:
private void Execution()
{
btnCompare.Invoke((MethodInvoker)delegate { pictureBox1.Visible = true; });
Application.DoEvents();
// Your main code comes here . . .
btnCompare.Invoke((MethodInvoker)delegate { pictureBox1.Visible = false; });
}
Keep in mind, the PictureBox is invisible from Properties Window or do below:
private void ComparerForm_Load(object sender, EventArgs e)
{
pictureBox1.Visible = false;
}
I prefer to stop the MongoDB server using the port
command itself.
sudo port unload mongodb
And to start it again.
sudo port load mongodb
This may be overkill for what you're looking for, but there is an npm package called marky
that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer.
You just need to install it via npm
and then import the dependency anywhere you'd like to use it.
Here is a link to the npm
package:
https://www.npmjs.com/package/marky
An example of use after installing via npm would be as follows:
import * as _M from 'marky';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
Marky = _M;
}
constructor() {}
ngOnInit() {}
startTimer(key: string) {
this.Marky.mark(key);
}
stopTimer(key: string) {
this.Marky.stop(key);
}
key
is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.
If you’re not averse to using double-dollar scope props and you’re writing a directive whose only content is a repeat, there is a pretty simple solution (assuming you only care about the initial render). In the link function:
const dereg = scope.$watch('$$childTail.$last', last => {
if (last) {
dereg();
// do yr stuff -- you may still need a $timeout here
}
});
This is useful for cases where you have a directive that needs to do DOM manip based on the widths or heights of the members of a rendered list (which I think is the most likely reason one would ask this question), but it’s not as generic as the other solutions that have been proposed.
this is an .htaccess file that forward almost all to index.php
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_URI} !-l
RewriteCond %{REQUEST_FILENAME} !\.(ico|css|png|jpg|gif|js)$ [NC]
# otherwise forward it to index.php
RewriteRule . index.php
then is up to you parse $_SERVER["REQUEST_URI"] and route to picture.php or whatever
<div class="small hidden-xs">
Some Content Here
</div>
This also works for elements not necessarily used in a grid /small column. When it is rendered on larger screens the font-size will be smaller than your default text font-size.
This answer satisfies the question in the OP title (which is how I found this Q/A).
From 6.11. Boolean operations:
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.
The key phrasing here that I think you are misunderstanding is "interpreted as false" or "interpreted as true". This does not mean that any of those values are identical to True or False, or even equal to True or False.
The expression '/bla/bla/bla'
will be treated as true where a Boolean expression is expected (like in an if
statement), but the expressions '/bla/bla/bla' is True
and '/bla/bla/bla' == True
will evaluate to False for the reasons in Ignacio's answer.
It's just as simple as command+s or File
> Save Screen Shot
in iOS Simulator. It will appear on your desktop by default.
Process of generating RPM from source file:
Well, as you are just looking to match the position of a character , regex is possibly overkill.
I presume all you want is, instead of "find first of these this character" , just find first of these characters.
This of course is the simple answer, but does what your question sets out to do, albeit without the regex part ( because you didn't clarify why specifically it had to be a regex )
function mIndexOf( str , chars, offset )
{
var first = -1;
for( var i = 0; i < chars.length; i++ )
{
var p = str.indexOf( chars[i] , offset );
if( p < first || first === -1 )
{
first = p;
}
}
return first;
}
String.prototype.mIndexOf = function( chars, offset )
{
return mIndexOf( this, chars, offset ); # I'm really averse to monkey patching.
};
mIndexOf( "hello world", ['a','o','w'], 0 );
>> 4
mIndexOf( "hello world", ['a'], 0 );
>> -1
mIndexOf( "hello world", ['a','o','w'], 4 );
>> 4
mIndexOf( "hello world", ['a','o','w'], 5 );
>> 6
mIndexOf( "hello world", ['a','o','w'], 7 );
>> -1
mIndexOf( "hello world", ['a','o','w','d'], 7 );
>> 10
mIndexOf( "hello world", ['a','o','w','d'], 10 );
>> 10
mIndexOf( "hello world", ['a','o','w','d'], 11 );
>> -1
This worked for me onchange = setLocation($(this).val())
Here.
@Html.DropDownList("Demo",
new SelectList(ViewBag.locs, "Value", "Text"),
new { Class = "ddlStyle", onchange = "setLocation($(this).val())" });
Last year I used Linblow's answer (2018-Oct-19) to successfully discover my local IP via javascript. However, recent Chrome updates (76?) have wonked this method so that it now returns an obfuscated IP, such as: 1f4712db-ea17-4bcf-a596-105139dfd8bf.local
If you have full control over your browser, you can undo this behavior by turning it off in Chrome Flags, by typing this into your address bar:
chrome://flags
and DISABLING the flag Anonymize local IPs exposed by WebRTC
In my case, I require the IP for a TamperMonkey script to determine my present location and do different things based on my location. I also have full control over my own browser settings (no Corporate Policies, etc). So for me, changing the chrome://flags
setting does the trick.
Sources:
https://groups.google.com/forum/#!topic/discuss-webrtc/6stQXi72BEU
https://codelabs.developers.google.com/codelabs/webrtc-web/index.html
based on the some of above replies i improvised it a bit
create this method and call it by passing your resource
Reusable Method
public String getURLForResource (int resourceId) {
//use BuildConfig.APPLICATION_ID instead of R.class.getPackage().getName() if both are not same
return Uri.parse("android.resource://"+R.class.getPackage().getName()+"/" +resourceId).toString();
}
Sample call
getURLForResource(R.drawable.personIcon)
complete example of loading image
String imageUrl = getURLForResource(R.drawable.personIcon);
// Load image
Glide.with(patientProfileImageView.getContext())
.load(imageUrl)
.into(patientProfileImageView);
you can move the function getURLForResource to a Util file and make it static so it can be reused
If you have a lot of variables to convert in optional, you can use SubimeText with this:
Find: \${([A-Za-z_0-9]*)}
Replace: \$\{${1}!\}
Be sure regex and case-sensitive options are enabled:
Here's a typed/generics version, based on Rodrigo IronMan's implementation:
public static <T> T getSingleResultOrNull(TypedQuery<T> query) {
query.setMaxResults(1);
List<T> list = query.getResultList();
if (list.isEmpty()) {
return null;
}
return list.get(0);
}
Yes we do it all the time. You return a static instance rather than a new Object
static Direction getOppositeDirection(Direction d){
Direction result = null;
if (d != null){
int newCode = -d.getCode();
for (Direction direction : Direction.values()){
if (d.getCode() == newCode){
result = direction;
}
}
}
return result;
}
Thanks for everyone who answered, and thanks for those who gave me the function-format idea, i'll really study it for future using.
But for this explicit case, the 'special yyyymm field' is not to be considered as a date field, but just as a tag, o whatever would be used for matching the exactly year-month researched value; there is already another date field, with the full timestamp, but if i need all the rows of january 2008, i think that is faster a select like
SELECT [columns] FROM table WHERE yearmonth = '200801'
instead of
SELECT [columns] FROM table WHERE date BETWEEN DATE('2008-01-01') AND DATE('2008-01-31')
you can use a stackLayout, inside of this layout you can put a list a frame, for example:
<StackLayout VerticalOptions="FillAndExpand">
<ListView ItemsSource="{Binding YourList}"
CachingStrategy="RecycleElement"
HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell >
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Image, Mode=TwoWay}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Frame BackgroundColor="AliceBlue" HorizontalOptions="FillAndExpand">
<Button Text="More"></Button>
</Frame>
</StackLayout>
this is the result:
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
public class DisplayImage {
public static void main(String avg[]) throws IOException
{
DisplayImage abc=new DisplayImage();
}
public DisplayImage() throws IOException
{
BufferedImage img=ImageIO.read(new File("f://images.jpg"));
ImageIcon icon=new ImageIcon(img);
JFrame frame=new JFrame();
frame.setLayout(new FlowLayout());
frame.setSize(200,300);
JLabel lbl=new JLabel();
lbl.setIcon(icon);
frame.add(lbl);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I use something like this
>>> import datetime
>>> regex = datetime.datetime.strptime
>>>
>>> # TEST
>>> assert regex('2020-08-03', '%Y-%m-%d')
>>>
>>> assert regex('2020-08', '%Y-%m-%d')
ValueError: time data '2020-08' does not match format '%Y-%m-%d'
>>> assert regex('08/03/20', '%m/%d/%y')
>>>
>>> assert regex('08-03-2020', '%m/%d/%y')
ValueError: time data '08-03-2020' does not match format '%m/%d/%y'
A minor point perhaps, but:
import static System.out;
public class Tester
{
public static void main(String[] args)
{
out.println("Hello!");
}
}
...generated a compile time error. I corrected the error by editing the first line to read:
import static java.lang.System.out;
From the oracle documentation, the below query explains it better
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
You can read this link
Your query would be as follows
//just the concept
INSERT INTO quotedb
(COLUMN_NAMES) //seperated by comma
SELECT COLUMN_NAMES FROM tickerdb,quotedb WHERE quotedb.ticker = tickerdb.ticker
Note: Make sure the columns in insert and select are in right position as per your requirement
Hope this helps!
There is a super easy solution with flexbox!
.frame {
display: flex;
align-items: center;
}
If you want to read CSV file with some lines, so this the solution.
while IFS=, read -ra line
do
test $i -eq 1 && ((i=i+1)) && continue
for col_val in ${line[@]}
do
echo -n "$col_val|"
done
echo
done < "$csvFile"
Use:
<a href="wantedText{/*/properties/property[@name='report']/@value)}"></a>
Check if all the parameters of functions are defined before they are called. I faced this problem while practicing Kaggle.
Unfortunately I do not believe it's possible in fully-conforming HTML5 with just HTML and CSS properties. Fortunately however, most browsers do still support the scrolling
property (which was removed from the HTML5 specification).
overflow
isn't a solution for HTML5 as the only modern browser which wrongly supports this is Firefox.
A current solution would be to combine the two:
<iframe src="" scrolling="no"></iframe>
iframe {
overflow: hidden;
}
But this could be rendered obsolete as browsers update. You may want to check this for a JavaScript solution: http://www.christersvensson.com/html-tool/iframe.htm
Edit: I've checked and scrolling="no"
will work in IE10, Chrome 25 and Opera 12.12.
I store encoded HTML in the database.
Imho you should not store your data html-encoded in the database. Just store in plain text (not encoded) and just display your data like this and your html will be automatically encoded:
<div class='content'>
@Model.Content
</div>
It seems the problem is that /
is not floor operation.
int mod(int m, float n)
{
return m - floor(m/n)*n;
}
The answer has been covered, but for simplicity...
# To filter out finished threads
threads = [t for t in threads if t.is_alive()]
# Same thing but for QThreads (if you are using PyQt)
threads = [t for t in threads if t.isRunning()]
First of all you need to include in your project
using System.Diagnostics;
After that you could write a general method that you could use for different .exe files that you want to use. It would be like below:
public void ExecuteAsAdmin(string fileName)
{
Process proc = new Process();
proc.StartInfo.FileName = fileName;
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.Verb = "runas";
proc.Start();
}
If you want to for example execute notepad.exe then all you do is you call this method:
ExecuteAsAdmin("notepad.exe");
I know this is a little late, but I was also having this issue a while ago. This is what worked for me:
REALLY_GEM_UPDATE_SYSTEM=1
sudo gem update --system
sudo gem install rails
Hope this helps anyone else having this issue :)
One thing to note is that not all libraries will use the same meaning for pi, of course, so it never hurts to know what you're using. For example, the symbolic math library Sympy's representation of pi is not the same as math and numpy:
import math
import numpy
import scipy
import sympy
print(math.pi == numpy.pi)
> True
print(math.pi == scipy.pi)
> True
print(math.pi == sympy.pi)
> False
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,
`dateUpdated` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `mobile_UNIQUE` (`mobile`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
Use the flex-grow
property to make a flex item consume free space on the main axis.
This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.
A common example is flex-grow: 1
or, using the shorthand property, flex: 1
.
Hence, instead of width: 96%
on your div, use flex: 1
.
You wrote:
So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.
The squashing of the fixed-width div is related to another flex property: flex-shrink
By default, flex items are set to flex-shrink: 1
which enables them to shrink in order to prevent overflow of the container.
To disable this feature use flex-shrink: 0
.
For more details see The flex-shrink
factor section in the answer here:
Learn more about flex alignment along the main axis here:
Learn more about flex alignment along the cross axis here:
Wildcards aren't expanded inside quoted strings. And when wildcard is expanded, it's returned unchanged if there are no matches, it doesn't expand into an empty string. Try:
output="$(ls home/edward/bank1/fiche/Test* 2>/dev/null)"
if [ -n "$output" ]
then echo "Found one"
else echo "Found none"
fi
If the wildcard expanded to filenames, ls
will list them on stdout
; otherwise it will print an error on stderr
, and nothing on stdout. The contents of stdout
are assigned to output
.
if [ -n "$output" ]
tests whether $output
contains anything.
Another way to write this would be:
if [ $(ls home/edward/bank1/fiche/Test* 2>/dev/null | wc -l) -gt 0 ]
Repository is more abstract domain oriented term that is part of Domain Driven Design, it is part of your domain design and a common language, DAO is a technical abstraction for data access technology, repository is concerns only with managing existing data and factories for creation of data.
check these links:
http://warren.mayocchi.com/2006/07/27/repository-or-dao/ http://fabiomaulo.blogspot.com/2009/09/repository-or-dao-repository.html
Starting with Spring Boot 1.4.0 you can use this in your test:
import org.springframework.boot.context.embedded.LocalServerPort;
@SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyTest {
@LocalServerPort
int randomPort;
// ...
}
RecogniContact is a Windows COM object that parses US and European addresses. You can try it right on http://www.loquisoft.com/index.php?page=8
If you don't want to use a separate JS library to create a custom control for that, you could use two confirm
dialogs to do the checks:
if (confirm("Are you sure you want to quit?") ) {
if (confirm("Save your work before leaving?") ) {
// code here for save then leave (Yes)
} else {
//code here for no save but leave (No)
}
} else {
//code here for don't leave (Cancel)
}
Type this .... SET foreign_key_checks = 0;
delete your table then type SET foreign_key_checks = 1;
MySQL – Temporarily disable Foreign Key Checks or Constraints
Why not using LEFT(string, length) function instead of substring.
LEFT(col,char_length(col)-2)
you can visit here https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_left to know more about Mysql String Functions.
Don't give exact heights, but relative ones, adding up to 100%. For example:
#content {height: 80%;}
#footer {height: 20%;}
Add in
html, body {height: 100%;}
Replace datatype without losing data
alter table tablename modify columnn newdatatype(size);
In my own implementation I found that using classes/interfaces for MI, although "good form", tended to be a massive over complication since you need to set up all that multiple inheritance for only a few necessary function calls, and in my case, needed to be done literally dozens of times redundantly.
Instead it was easier to simply make static "functions that call functions that call functions" in different modular varieties as a sort of OOP replacement. The solution I was working on was the "spell system" for a RPG where effects need to heavily mix-and-match function calling to give an extreme variety of spells without re-writing code, much like the example seems to indicate.
Most of the functions can now be static because I don't necessarily need an instance for spell logic, whereas class inheritance can't even use virtual or abstract keywords while static. Interfaces can't use them at all.
Coding seems way faster and cleaner this way IMO. If you're just doing functions, and don't need inherited properties, use functions.
Is there anything wrong with
new Dictionary<KeyValuePair<object, object>, object>?
I think that you should use rather the following:
data => {
this.results = this.results.concat(data.results);
this._next = data.next;
},
From the concat
doc:
The concat() method returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments.
In okhttp v4.* I got it working that way
// import the extensions!
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
// ...
json : String = "..."
val JSON : MediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody: RequestBody = json.toRequestBody(JSON)
// go on with Request.Builder() etc
Recompile PHP with mbstring.
./configure --enable-http --with-apxs2 --with-mysql --with-gd
--with-curl --with-mbstring
make
make install
You can get width and height of image with BufferedImage object using java.
public void setWidthAndHeightImage(FileUploadEvent event){
byte[] imageTest = event.getFile().getContents();
baiStream = new ByteArrayInputStream(imageTest );
BufferedImage bi = ImageIO.read(baiStream);
//get width and height of image
int imageWidth = bi.getWidth();
int imageHeight = bi.getHeight();
}
Try this instead.
<Window x:Class="BuildAssistantUI.BuildAssistantWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:VM="clr-namespace:BuildAssistantUI.ViewModels">
<Window.DataContext>
<VM:MainViewModel />
</Window.DataContext>
</Window>
You want the NPGSQL library. Your only other alternative is ODBC.
In-place:
public static void DistinctValues<T>(List<T> list)
{
list.Sort();
int src = 0;
int dst = 0;
while (src < list.Count)
{
var val = list[src];
list[dst] = val;
++dst;
while (++src < list.Count && list[src].Equals(val)) ;
}
if (dst < list.Count)
{
list.RemoveRange(dst, list.Count - dst);
}
}
Assuming that you have posted valid JSON,
@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
content = request.json
print content['uuid']
# Return data as JSON
return jsonify(content)
Server.MapPath specifies the relative or virtual path to map to a physical directory.
Server.MapPath(".")
1 returns the current physical directory of the file (e.g. aspx) being executedServer.MapPath("..")
returns the parent directoryServer.MapPath("~")
returns the physical path to the root of the applicationServer.MapPath("/")
returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)An example:
Let's say you pointed a web site application (http://www.example.com/
) to
C:\Inetpub\wwwroot
and installed your shop application (sub web as virtual directory in IIS, marked as application) in
D:\WebApps\shop
For example, if you call Server.MapPath()
in following request:
http://www.example.com/shop/products/GetProduct.aspx?id=2342
then:
Server.MapPath(".")
1 returns D:\WebApps\shop\products
Server.MapPath("..")
returns D:\WebApps\shop
Server.MapPath("~")
returns D:\WebApps\shop
Server.MapPath("/")
returns C:\Inetpub\wwwroot
Server.MapPath("/shop")
returns D:\WebApps\shop
If Path starts with either a forward slash (/
) or backward slash (\
), the MapPath()
returns a path as if Path was a full, virtual path.
If Path doesn't start with a slash, the MapPath()
returns a path relative to the directory of the request being processed.
Note: in C#, @
is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.
Footnotes
Server.MapPath(null)
and Server.MapPath("")
will produce this effect too.UPD 2020: "Open Graph Object Debugger" has been discontinued. Use Sharing Debugger to refresh Facebook cache.
There is some confusion about tons of Facebook Tools and Documentation. So many people probably use the Sharing Debugger tool to check their OpenGraph markup: https://developers.facebook.com/tools/debug/sharing/
But it only retrieves the information about your site from the Facebook cache. This means that after you change the ogp-markup on your site, the Sharing Debugger will still be using the old cached data. Moreover, if there is no cached data on the Facebook server then the Sharing Debugger will show you the error: This URL hasn't been shared on Facebook before.
So, the solution is to use another tool – Open Graph Object Debugger: https://developers.facebook.com/tools/debug/og/object/
It allows you to Fetch new scrape information and refresh the Facebook cache:
Honestly, I don't know how to find this tool exploring the Tools & Support section of developers.facebook.com – I cannot find any links and mentions. I only have this tool in my bookmarks. That's Facebook :)
I also noted that some developers use the name
attribute instead of property
. Many parsers probably will process such tags properly, but according to The Open Graph protocol, we should use property
, not name
:
<meta property="og:url" content="http://www.mywebaddress.com"/>
The last recommendation is to specify full URLs. For example, Facebook complains when you use relative URL in og:image
. So use the full one:
<meta property="og:image" content="http://www.mywebaddress.com/myimage.jpg"/>
I got the error using TFS, my AssemblyInfo wasn't mapped in the branch I was working on.
It can convert by
Convert.ToInt32 method
But it will throw an OverflowException if it the value is outside range of the Int32 Type. A basic test will show us how it works:
long[] numbers = { Int64.MinValue, -1, 0, 121, 340, Int64.MaxValue };
int result;
foreach (long number in numbers)
{
try {
result = Convert.ToInt32(number);
Console.WriteLine("Converted the {0} value {1} to the {2} value {3}.",
number.GetType().Name, number,
result.GetType().Name, result);
}
catch (OverflowException) {
Console.WriteLine("The {0} value {1} is outside the range of the Int32 type.",
number.GetType().Name, number);
}
}
// The example displays the following output:
// The Int64 value -9223372036854775808 is outside the range of the Int32 type.
// Converted the Int64 value -1 to the Int32 value -1.
// Converted the Int64 value 0 to the Int32 value 0.
// Converted the Int64 value 121 to the Int32 value 121.
// Converted the Int64 value 340 to the Int32 value 340.
// The Int64 value 9223372036854775807 is outside the range of the Int32 type.
Here there is a longer explanation.
skipUntil : ignore emitted items until another observable has emitted
last: emit last value from a sequence (i.e. wait until it completes then emit)
Note that anything emitted from the observable passed to skipUntil
will cancel the skipping, which is why we need to add last()
- to wait for the stream to complete.
main$.skipUntil(sequence2$.pipe(last()))
Official: https://rxjs-dev.firebaseapp.com/api/operators/skipUntil
Possible issue: Note that last()
by itself will error if nothing is emitted. The last()
operator does have a default
parameter but only when used in conjunction with a predicate. I think if this situation is a problem for you (if sequence2$
may complete without emitting) then one of these should work (currently untested):
main$.skipUntil(sequence2$.pipe(defaultIfEmpty(undefined), last()))
main$.skipUntil(sequence2$.pipe(last(), catchError(() => of(undefined))
Note that undefined
is a valid item to be emitted, but could actually be any value. Also note that this is the pipe attached to sequence2$
and not the main$
pipe.
Building on Sven's answer, I found using collections.OrderedDict like so helped me accomplish what you want plus allow me to add more items to the dict:
import collections
x=[1,2,20,6,210]
z=collections.OrderedDict.fromkeys(x)
z
OrderedDict([(1, None), (2, None), (20, None), (6, None), (210, None)])
If you want to add items but still treat it like a set you can just do:
z['nextitem']=None
And you can perform an operation like z.keys() on the dict and get the set:
z.keys()
[1, 2, 20, 6, 210]
YUI 2 and 3 has a module stylesheet that will let you do just that (edit stylesheets on the fly with javascript). http://yuilibrary.com/yui/docs/stylesheet/. So I think it is possible. This is not the same as $(".some").css({...}) but really change/add/remove styles definition from stylesheet, just like the user asked.
Heap just guarantees that elements on higher levels are greater (for max-heap) or smaller (for min-heap) than elements on lower levels
I love the above answer and putting my comment just more specific to my need and usage. I had to get the n locations list find the distance from each location to specific point say (0,0) and then return the a m locations having smaller distance. I used Priority Queue which is Heap. For finding distances and putting in heap it took me n(log(n)) n-locations log(n) each insertion. Then for getting m with shortest distances it took m(log(n)) m-locations log(n) deletions of heaping up.
I if would have to do this with BST, it would have taken me n(n) worst case insertion.(Say the first value is very smaller and all other comes sequentially longer and longer and the tree spans to right child only or left child in case of smaller and smaller. The min would have taken O(1) time but again I had to balance. So from my situation and all above answers what I got is when you are only after the values at min or max priority basis go for heap.
Looks like YouTube has updated their JS API so this is available by default! You can use an existing YouTube iframe's ID...
<iframe id="player" src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com" frameborder="0"></iframe>
...in your JS...
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange() {
//...
}
...and the constructor will use your existing iframe instead of replacing it with a new one. This also means you don't have to specify the videoId to the constructor.
java
is part of the JRE, not the JDK.
You need to add the JDK bin to the system PATH, in
"Control Panel" | System | Advanced | "Environment Variables"
As of Typescript 2.9, one can simply add:
"compilerOptions": {
"resolveJsonModule": true
}
to the tsconfig.json
. Thereafter, it's easy to use a json file (and there will be nice type inference in VSCode, too):
data.json
:
{
"cases": [
{
"foo": "bar"
}
]
}
In your Typescript file:
import { cases } from './data.json';
I don't think that x[[1,3]][:,[1,3]]
is hardly readable. If you want to be more clear on your intent, you can do:
a[[1,3],:][:,[1,3]]
I am not an expert in slicing but typically, if you try to slice into an array and the values are continuous, you get back a view where the stride value is changed.
e.g. In your inputs 33 and 34, although you get a 2x2 array, the stride is 4. Thus, when you index the next row, the pointer moves to the correct position in memory.
Clearly, this mechanism doesn't carry well into the case of an array of indices. Hence, numpy will have to make the copy. After all, many other matrix math function relies on size, stride and continuous memory allocation.
It can be that your resources directory is not added to classpath when creating a project via Spring Initializr. So your application is never loading the application.properties file that you have configured.
To make a quick test if this is the case, add the following to your application.properties file:
server.port=8081
Now when running your application you should see in the spring boot console output something like this:
INFO o.s.b.w.e.tomcat.TomcatWebServer - Tomcat started on port(s): **8081** (http) with context path ''
If your port is still default 8080 and not changed to 8081, your application.properties files is obviously not loading.
You can also check if your application runs with gradle bootRun
from command line. Which most likely will be work.
Solution:
See official answer by IntelliJ Support: IDEA-221673
I would do something like this:
;WITH x
AS (SELECT *,
Row_number()
OVER(
partition BY employeeid
ORDER BY datestart) rn
FROM employeehistory)
SELECT *
FROM x x1
LEFT OUTER JOIN x x2
ON x1.rn = x2.rn + 1
Or maybe it would be x2.rn - 1. You'll have to see. In any case, you get the idea. Once you have the table joined on itself, you can filter, group, sort, etc. to get what you need.
As serialization doesn't work generally (only when the order of properties matches: JSON.stringify({a:1,b:2}) !== JSON.stringify({b:2,a:1})
) you have to check the count of properties and compare each property as well:
const objectsEqual = (o1, o2) =>_x000D_
Object.keys(o1).length === Object.keys(o2).length _x000D_
&& Object.keys(o1).every(p => o1[p] === o2[p]);_x000D_
_x000D_
const obj1 = { name: 'John', age: 33};_x000D_
const obj2 = { age: 33, name: 'John' };_x000D_
const obj3 = { name: 'John', age: 45 };_x000D_
_x000D_
console.log(objectsEqual(obj1, obj2)); // true_x000D_
console.log(objectsEqual(obj1, obj3)); // false
_x000D_
If you need a deep comparison, you can call the function recursively:
const obj1 = { name: 'John', age: 33, info: { married: true, hobbies: ['sport', 'art'] } };_x000D_
const obj2 = { age: 33, name: 'John', info: { hobbies: ['sport', 'art'], married: true } };_x000D_
const obj3 = { name: 'John', age: 33 };_x000D_
_x000D_
const objectsEqual = (o1, o2) => _x000D_
typeof o1 === 'object' && Object.keys(o1).length > 0 _x000D_
? Object.keys(o1).length === Object.keys(o2).length _x000D_
&& Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))_x000D_
: o1 === o2;_x000D_
_x000D_
console.log(objectsEqual(obj1, obj2)); // true_x000D_
console.log(objectsEqual(obj1, obj3)); // false
_x000D_
Then it's easy to use this function to compare objects in arrays:
const arr1 = [obj1, obj1];
const arr2 = [obj1, obj2];
const arr3 = [obj1, obj3];
const arraysEqual = (a1, a2) =>
a1.length === a2.length && a1.every((o, idx) => objectsEqual(o, a2[idx]));
console.log(arraysEqual(arr1, arr2)); // true
console.log(arraysEqual(arr1, arr3)); // false
Well, here is my "answer". It uses the fact that String.Split can be told hold many items it should split to (which I found lacking in the other answers):
string theString = "Some Very Large String Here";
var array = theString.Split(new [] { ' ' }, 2); // return at most 2 parts
// note: be sure to check it's not an empty array
string firstElem = array[0];
// note: be sure to check length first
string restOfArray = array[1];
This is very similar to the Substring
method, just by a different means.
Convert binary to its equivalent character.
k=7
dec=0
new=[]
item=[x for x in input("Enter 8bit binary number with , seprator").split(",")]
for i in item:
for j in i:
if(j=="1"):
dec=2**k+dec
k=k-1
else:
k=k-1
new.append(dec)
dec=0
k=7
print(new)
for i in new:
print(chr(i),end="")
Try checking his post. It shows how to implement transitions between web pages using AngularJS's ngRoute and ngAnimate: How to Make iPhone-Style Web Page Transitions Using AngularJS & CSS
In my opinion, the solution proposed by user1965719 is really elegant. In my project, all objects going in to the containing div is dynamically created, so adding the extra hidden button is a breeze:
aspx code:
<asp:Button runat="server" id="btnResponse1" Text=""
style="display: none; width:100%; height:100%"
OnClick="btnResponses_Clicked" />
<div class="circlebuttontext" id="calendarButtonText">Calendar</div>
</div>
C# code behind:
protected void btnResponses_Clicked(object sender, EventArgs e)
{
if(sender == btnResponse1)
{
//Your code behind logic for that button goes here
}
}
After you write to the MemoryStream
and before you read it back, you need to Seek
back to the beginning of the MemoryStream
so you're not reading from the end.
UPDATE
After seeing your update, I think there's a more reliable way to build the stream:
UnicodeEncoding uniEncoding = new UnicodeEncoding();
String message = "Message";
// You might not want to use the outer using statement that I have
// I wasn't sure how long you would need the MemoryStream object
using(MemoryStream ms = new MemoryStream())
{
var sw = new StreamWriter(ms, uniEncoding);
try
{
sw.Write(message);
sw.Flush();//otherwise you are risking empty stream
ms.Seek(0, SeekOrigin.Begin);
// Test and work with the stream here.
// If you need to start back at the beginning, be sure to Seek again.
}
finally
{
sw.Dispose();
}
}
As you can see, this code uses a StreamWriter to write the entire string (with proper encoding) out to the MemoryStream
. This takes the hassle out of ensuring the entire byte array for the string is written.
Update: I stepped into issue with empty stream several time. It's enough to call Flush right after you've finished writing.
the First character of your function should be an Uppercase
I have been doing quite a bit of research and in attempt to resolve a different issue I ended up coming to a good portion of the solution in my other post here:
Angularjs - Form Post Data Not Posted?
The solution does not include uploading images currently but I intend to expand upon and create a clear and well working example. If updating these posts is possible I will keep them up to date all the way until a stable and easy to learn from example is compiled.
IMO, you cannot create an empty Date(java.util)
. You can create a Date
object with null
value and can put a null check.
Date date = new Date(); // Today's date and current time
Date date2 = new Date(0); // Default date and time
Date date3 = null; //Date object with null as value.
if(null != date3) {
// do your work.
}
Alvaros JS free answer was a great start for me, and I really tried to get a truly JS-free answer that still delivered all the functionality expected of a Select with images, but sadly nesting forms was the down-fall. I'm posting two solutions here; my main solution that uses 1 line of JavaScript, and a totally JavaScript-free solution that won't work inside another form, but might be useful for nav menus.
Unfortunately there is a bit of repetition in the code, but when you think about what a Select does it makes sense. When you click on an option it copies that text to the selected area, i.e., clicking 1 of 4 options will not change the 4 options, but the top will now repeat the one you clicked. To do this with images would require JavaScript, orrrr... you duplicate the entries.
In my example we have a list of games (Products), which have versions. Each product may also have Expansions, which can also have versions. For each Product we give the user a list of each version if there's more than one, along with an image and version specific text.
<h4>@Model.Name</h4>
@if (Model.Versions.Count == 1)
{
<div class="rich-select-option-body pl-2">
<img src="@Model.Versions[0].ImageUrl" alt="">@Model.Versions[0].VersionName (@Model.Versions[0].Year)
</div>
}
else
{
<h5>Select the version</h5>
<div class="rich-select custom-select">
<div class="rich-select-dropdown">
@foreach (var version in Model.Versions)
{
<div class="rich-select-option">
<input type="radio" name="game" id="[email protected]@version.VersionId" @if (version == Model.Versions.First()) { @Html.Raw(" checked") ; } />
<div class="rich-select-option-body">
<label tabindex="-1">
<img src="@version.ImageUrl" alt="">@version.VersionName (@version.Year)
</label>
</div>
</div>
}
</div>
<input type="checkbox" id="rich-select-dropdown-button" class="rich-select-dropdown-button" />
<label for="rich-select-dropdown-button"></label>
<div class="rich-select-options">
@foreach (var version in Model.Versions)
{
<div class="rich-select-option">
<div class="rich-select-option-body">
<label for="[email protected]@version.VersionId" tabindex="-1" onclick="document.getElementById('rich-select-dropdown-button').click();">
<img src="@version.ImageUrl" alt=""> @version.VersionName (@version.Year)
</label>
</div>
</div>
}
</div>
</div>
}
Using JS for the checkbox deselection we can have multiple instances on a form. Here I've extended to show a list of Expansions, which also have the same logic around versions.
<h5 class="mt-3">Include Expansions?</h5>
@foreach (var expansion in Model.Expansions)
{
<div class="form-row">
<div class="custom-control custom-checkbox w-100">
<input type="checkbox" class="expansion-checkbox custom-control-input" id="[email protected]">
<label class="custom-control-label w-100" for="[email protected]">
@if (expansion.Versions.Count == 1)
{
<div class="rich-select-option-body pl-2">
<img src="@expansion.ImageUrl" />@expansion.Name: @expansion.Versions[0].VersionName (@expansion.Versions[0].Year)
</div>
}
else
{
<div class="rich-select custom-select">
<div class="rich-select-dropdown">
@foreach (var version in expansion.Versions)
{
<div class="rich-select-option">
<input type="radio" name="[email protected]" id="[email protected]@version.VersionId" @if (version == expansion.Versions.First()) { @Html.Raw(" checked") ; } />
<div class="rich-select-option-body">
<label tabindex="-1">
<img src="@version.ImageUrl" alt="">@expansion.Name: @version.VersionName (@version.Year)
</label>
</div>
</div>
}
</div>
<input type="checkbox" id="[email protected]" class="rich-select-dropdown-button" />
<label for="[email protected]"></label>
<div class="rich-select-options">
@foreach (var version in expansion.Versions)
{
<div class="rich-select-option">
<div class="rich-select-option-body">
<label for="[email protected]@version.VersionId" tabindex="-1" onclick="document.getElementById('[email protected]').click();">
<img src="@version.ImageUrl" alt="">@expansion.Name: @version.VersionName (@version.Year)
</label>
</div>
</div>
}
</div>
</div>
}
</label>
</div>
</div>
Of course this requires a fair bit of CSS, which I've only included in this JSFiddle to reduce the size of this already massive answer. I've used Bootstrap 4 to reduce the amount needed, and also to allow it to fit in with other Bootstrap controls and any site customisations that have been made.
The images are set to 75px, but this can easily be changed in 5 lines in .rich-select
and .rich-select-option-body img
A SHA1 hash is 40 chars long!
Another correct way to get selected value would be using this selector:
$("option[value="0"]:selected")
Best for you!
<input type="text" value="Your value">
Use the value
attribute for the pre filled in values.
As in any unix-based environment, you can use the sudo
command:
$ sudo script-name
It will ask for your password (your own, not a separate root
password).
You can use the createRef to change the state of the child component from the parent component. Here are all the steps.
Create a method to change the state in the child component.
2 - Create a reference for the child component in parent component using React.createRef().
3 - Attach reference with the child component using ref={}.
4 - Call the child component method using this.yor-reference.current.method.
Parent component
class ParentComponent extends Component {
constructor()
{
this.changeChild=React.createRef()
}
render() {
return (
<div>
<button onClick={this.changeChild.current.toggleMenu()}>
Toggle Menu from Parent
</button>
<ChildComponent ref={this.changeChild} />
</div>
);
}
}
Child Component
class ChildComponent extends Component {
constructor(props) {
super(props);
this.state = {
open: false;
}
}
toggleMenu=() => {
this.setState({
open: !this.state.open
});
}
render() {
return (
<Drawer open={this.state.open}/>
);
}
}
You can do :
try :
string_integer = int(string)
except ValueError :
print("This string doesn't contain an integer")
UPDATE: Console/Terminal feature was implemented in IDEA 13, PyCharm 3, RubyMine 6, WebStorm/PhpStorm 7.
There is a related feature request, please vote. Setting up an external tool to run a terminal can be used as a workaround.
Here's my standard implementation. I like the labels to be self-descriptive.
Public Sub DoSomething()
On Error GoTo Catch ' Try
' normal code here
Exit Sub
Catch:
'error code: you can get the specific error by checking Err.Number
End Sub
Or, with a Finally
block:
Public Sub DoSomething()
On Error GoTo Catch ' Try
' normal code here
GoTo Finally
Catch:
'error code
Finally:
'cleanup code
End Sub
I used Keystore Explorer
I believe iteration is equivalent to a single batch forward+backprop in batch SGD. Epoch is going through the entire dataset once (as someone else mentioned).
Few min back i was facing " main method not defined".Now its resolved.I tried all above thing but nothing was working.There was not compilation error in my java file. I followed below things
Now problem solved.Getting required result.
You can use nonzero function. it returns the nonzero indices of the given input.
Easy Way
>>> (e > 15).nonzero()
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
to see the indices more cleaner, use transpose
method:
>>> numpy.transpose((e>15).nonzero())
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
Not Bad Way
>>> numpy.nonzero(e > 15)
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
or the clean way:
>>> numpy.transpose(numpy.nonzero(e > 15))
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
@olegkhuss solution with named UTF-8 Elipsis:
{{ (my.text|length > 50 ? my.text|slice(0, 50) ~ '…' : my.text) }}
In ubuntu 18.04.1 Bionic Beaver, you need to log out and log back in (restart not necessary) to get the proper environment.
$ sudo apt install python-pip
$ pip --version
pip 9.0.1 from /usr/lib/python2.7/dist-packages (python 2.7)
$ pip install --upgrade pip
$ pip --version
Traceback (most recent call last):
File "/usr/bin/pip", line 9, in <module>
from pip import main
ImportError: cannot import name main
$ exit
<login>
$ pip --version
pip 18.1 from /home/test/.local/lib/python2.7/site-packages/pip (python 2.7)
Based on Jürgen Weigert's answer, I have some improvement:
docker build -t xeyes - << __EOF__
FROM debian
RUN apt-get update
RUN apt-get install -qqy x11-apps
ENV DISPLAY :0
CMD xeyes
__EOF__
XSOCK=/tmp/.X11-unix
XAUTH_DIR=/tmp/.docker.xauth
XAUTH=$XAUTH_DIR/.xauth
mkdir -p $XAUTH_DIR && touch $XAUTH
xauth nlist $DISPLAY | sed -e 's/^..../ffff/' | xauth -f $XAUTH nmerge -
docker run -ti -v $XSOCK:$XSOCK -v $XAUTH_DIR:$XAUTH_DIR -e XAUTHORITY=$XAUTH xeyes
The only difference is that it creates a directory $XAUTH_DIR which is used to place $XAUTH file and mount $XAUTH_DIR directory instead of $XAUTH file into docker container.
The benefit of this method is that you can write a command in /etc/rc.local which is to create a empty folder named $XAUTH_DIR in /tmp and change its mode to 777.
tr '\n' '\000' < /etc/rc.local | sudo tee /etc/rc.local >/dev/null
sudo sed -i 's|\x00XAUTH_DIR=.*\x00\x00|\x00|' /etc/rc.local >/dev/null
tr '\000' '\n' < /etc/rc.local | sudo tee /etc/rc.local >/dev/null
sudo sed -i 's|^exit 0.*$|XAUTH_DIR=/tmp/.docker.xauth; rm -rf $XAUTH_DIR; install -m 777 -d $XAUTH_DIR\n\nexit 0|' /etc/rc.local
When system restart, before user login, docker will mount the $XAUTH_DIR directory automatically if container's restart policy is "always". After user login, you can write a command in ~/.profile which is to create $XAUTH file, then the container will automatically use this $XAUTH file.
tr '\n' '\000' < ~/.profile | sudo tee ~/.profile >/dev/null
sed -i 's|\x00XAUTH_DIR=.*-\x00|\x00|' ~/.profile
tr '\000' '\n' < ~/.profile | sudo tee ~/.profile >/dev/null
echo "XAUTH_DIR=/tmp/.docker.xauth; XAUTH=\$XAUTH_DIR/.xauth; touch \$XAUTH; xauth nlist \$DISPLAY | sed -e 's/^..../ffff/' | xauth -f \$XAUTH nmerge -" >> ~/.profile
Afterall, the container will automatically get the Xauthority file every time the system restart and user login.
On MaxOSX there may be perlcc. Type man perlcc. On my system (10.6.8) it's in /usr/bin. YMMV
See http://search.cpan.org/~nwclark/perl-5.8.9/utils/perlcc.PL