When hosting in Amazon Web Services (AWS) using an Elastic Beanstalk (EBS) deployment AND using this stackoverflow answer on how to access configuration values in EBS containers (https://stackoverflow.com/a/47648283/78804)
If NO configuration values have been set within the Elastic Beanstalk -> Environments -> [APP NAME] -> Configuration -> Software
menu, you will probably see this error.
Setting ANY SINGLE VALUE in the EBS config, makes it go away.
This is probably caused by the configuration-loading block failing to do a null check and the entire website failing un-gracefully because the error is happening during the application Startup
phase.
In my case I was using a lock which does not allow the use of await and does not create compiler warning when you don't await an async.
The problem:
lock (someLockObject) {
// do stuff
context.SaveChangesAsync();
}
// some other code somewhere else doing await context.SaveChangesAsync() shortly after the lock gets the concurrency error
The fix: Wait for the async inside the lock by making it blocking with a .Wait()
lock (someLockObject) {
// do stuff
context.SaveChangesAsync().Wait();
}
This is what works for me:
watchman watch-del-all && rm -f yarn.lock && rm -rf node_modules && yarn && yarn start --reset-cache
On a mac, run the following command to find id of the process which is using port 8081
sudo lsof -i :8081
Then run the following to terminate process:
kill -9 23583
Most of us face this problem for the first time, when we start react native project#1.
Few simple steps solved my problem:
I created a sample project using command:
react-native init ReactProject1
Solution
The fix is to help local-cli\runAndroid\adb.js
to find adb.exe
, the same way as local-cli\runAndroid\runAndroid.js
:
find replace statement under projectname(whatever you have given)\node_modules\react-native\local-cli\runAndroid
Replace:
const devicesResult = child_process.execSync('adb devices');
By:
const devicesResult = child_process.execSync( (process.env.ANDROID_HOME ? process.env.ANDROID_HOME + '/platform-tools/' : '') + 'adb devices');
after doing above replacement, just run react-native run-android in your cmd, it will bundle apk and at first try to install js bundle locally in your device. (Got Success)
you can use
<Image source={{uri: 'imagename'}} style={{width: 40, height: 40}} />
to show image.
from:
https://facebook.github.io/react-native/docs/images.html#images-from-hybrid-app-s-resources
There is a packages.config file with the project, it contains the package details.
Also there is a .nuget folder which contains the NuGet.exe and NuGet.targets. if any one of the file is missing it will not restore the missing package and cause "are you missing a using directive or an assembly reference?" error
Removing double-quotes
solve my problem, now its:
DEBUG_STORE_PASSWORD=androiddebug
DEBUG_KEY_ALIAS=androiddebug
DEBUG_KEY_PASSWORD=androiddebug
Restart Netbeans & it solved my problem.
You can find it in the
project -> app (or your main app module) -> build -> outputs -> apk
You could ask your colleague to create a patch, which will collapse all the changes that have been made into a single file that you can apply to your own check out. This will update all of your files appropriately and then you can revert the changes on his side and check yours in.
<c:if test="${ansokanInfo.pSystem eq 'NAT'}">
You can build docker image from a file called docker file and named Dockerfile by default. It has set of command/instruction that you need in your docker container. Below command creates image with tag latest, Dockerfile should present on that location (. means present direcotry)
docker build . -t <image_name>:latest
You can specify the Dockerfile via -f if the file name in not default (Dockerfile) Sameple Docker file contents.
FROM busybox
RUN echo "hello world"
ASP.NET controls should rather be placed in aspx markup file. That is the preferred way of working with them. So add FileUpload
control to your page. Make sure it has all required attributes including ID
and runat
:
<asp:FileUpload ID="FileUpload1" runat="server" />
Instance of FileUpload1
will be automatically created in auto-generated/updated *.designer.cs file which is a partial class for your page. You usually do not have to care about what's in it, just assume that any control on an aspx page is automatically instantiated.
Add a button that will do the post back:
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Then go to your *.aspx.cs file where you have your code and add button click handler. In C# it looks like this:
protected void Button1_Click(object sender, EventArgs e)
{
if (this.FileUpload1.HasFile)
{
this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);
}
}
And that's it. All should work as expected.
Much simpler: use sudo
to run a shell and use a heredoc to feed it commands.
#!/usr/bin/env bash
whoami
sudo -i -u someuser bash << EOF
echo "In"
whoami
EOF
echo "Out"
whoami
(answer originally on SuperUser)
419 error happens when you don`t post csrf_token. in your post method you must add this token along other variables.
Go to file "settings.json" and disable the Python pydocstyle
:
"python.linting.pydocstyleEnabled": false
Use Java's replaceAll(String regex, String replacement)
For example, Use a substitution char for the quotes and then replace that char with \"
String newstring = String.replaceAll("%","\"");
or replace all instances of \"
with \\\"
String newstring = String.replaceAll("\"","\\\"");
Include the four lines written after the info for ellipsis to work
.app a
{
color: #fff;
font: bold 15px/18px Arial;
height: 18px;
margin: 0 5px 0 5px;
padding: 0;
position: relative;
text-align: center;
text-decoration: none;
width: 140px;
/*
Note: The Below 4 Lines are necessary for ellipsis to work.
*/
display: block;/* Change it as per your requirement. */
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
Set the minOccurs
attribute to 0
in the schema like so:
<?xml version="1.0"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="request">
<xs:complexType>
<xs:sequence>
<xs:element name="amenity">
<xs:complexType>
<xs:sequence>
<xs:element name="description" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element> </xs:schema>
I know this is an old question but...
import java.text.*;
public class FormatCurrency
{
public static void main(String[] args)
{
double price = 123.4567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(price));
}
}
From docs:
Assert statements are a convenient way to insert debugging assertions into a program
You can read more here: http://docs.python.org/release/2.5.2/ref/assert.html
If you absolutely only want to store the combined field on the model and not the two seperate fields, you could do something like this:
form
attribute on your ModelAdmin
(https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form)save_formset
method on your ModelAdmin
(https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model)I never done something like this so I'm not completely sure how it will work out.
It's to avoid a stack overflow. The Python interpreter limits the depths of recursion to help you avoid infinite recursions, resulting in stack overflows.
Try increasing the recursion limit (sys.setrecursionlimit
) or re-writing your code without recursion.
From the Python documentation:
sys.getrecursionlimit()
Return the current value of the recursion limit, the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. It can be set by
setrecursionlimit()
.
I've made this code in VB.NET but you can translate. Well pretend you have the variable Client as a TcpClient
Dim ClientRemoteIP As String = Client.Client.RemoteEndPoint.ToString.Remove(Client.Client.RemoteEndPoint.ToString.IndexOf(":"))
Hope it helps! Cheers.
In addition to Windows Task Scheduler you also have 'at' on Windows. I'm not sure how it differs from Task Scheduler besides the fact that it has a command line interface.
SELECT MAX(ID) from bugs WHERE user=Me
str_replace('"', "", $string);
str_replace("'", "", $string);
I assume you mean quotation marks?
Otherwise, go for some regex, this will work for html quotes for example:
preg_replace("/<!--.*?-->/", "", $string);
C-style quotes:
preg_replace("/\/\/.*?\n/", "\n", $string);
CSS-style quotes:
preg_replace("/\/*.*?\*\//", "", $string);
bash-style quotes:
preg-replace("/#.*?\n/", "\n", $string);
Etc etc...
Just for the sake of it, there is of course the possibility to create Void
instance using reflection:
interface B<E>{ E method(); }
class A implements B<Void>{
public Void method(){
// do something
try {
Constructor<Void> voidConstructor = Void.class.getDeclaredConstructor();
voidConstructor.setAccessible(true);
return voidConstructor.newInstance();
} catch (Exception ex) {
// Rethrow, or return null, or whatever.
}
}
}
You probably won't do that in production.
The correct method is #2. You used the section tag to define a section of your document. From the specs http://www.w3.org/TR/html5/sections.html:
The section element is not a generic container element. When an element is needed for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead
Clear your cache. http://support.google.com/chrome/bin/answer.py?hl=en&answer=95582 And test another browser.
Some where able to get an updated favicon by adding an URL parameter: ?v=1
after the link href which changes the resource link and therefore loads the favicon without cache (thanks @Stanislav).
<link rel="icon" type="image/x-icon" href="favicon.ico?v=2" />
How did you import the favicon? How you should add it.
Normal favicon:
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
PNG/GIF favicon:
<link rel="icon" type="image/gif" href="favicon.gif" />
<link rel="icon" type="image/png" href="favicon.png" />
in the <head>
Tag.
Another thing could be the problem that chrome can't display favicons, if it's local (not uploaded to a webserver). Only if the file/icon would be in the downloads directory chrome is allowed to load this data - more information about this can be found here: local (file://) website favicon works in Firefox, not in Chrome or Safari- why?
Try to rename it from favicon.{whatever}
to {yourfaviconname}.{whatever}
but I would suggest you to still have the normal favicon. This has solved my issue on IE.
Found another solution for this which works great! I simply added my favicon as Base64 Encoded Image directly inside the tag like this:
<link href="data:image/x-icon;base64,AAABAAIAEBAAAAEAIABoBAAAJgAAACAgAAABACAAqBAAAI4EAAAoAAAAEAAAACAAAAABACAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AIaDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8A////AP///wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wCGg4L/hoOC/4aDgv+Gg4L/hoOC/4aDgv////8AhoOC/////wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wD///8A////AIaDgv////8A////AP///wD///8A////AP///wCGg4L/////AHCMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/////wCGg4L/////AP///wD///8A////AP///wD///8AhoOC/////wBTlsIAU5bCAFOWwgBTlsIAU5bCM1OWwnP///8AhoOC/////wD///8A////AP///wD///8A////AP///wD///8AU5bCBlOWwndTlsLHU5bC+FOWwv1TlsLR////AP///wD///8A////AP///wD///8A////AP///wD///8A////AFOWwvtTlsLuU5bCu1OWwlc2k9cANpPXqjaT19H///8A////AP///wD///8A////AP///wD///8A////AP///wBTlsIGNpPXADaT1wA2k9dINpPX8TaT1+40ktpDH4r2tB+K9hL///8A////AP///wD///8A////AP///wD///8A////ADaT1wY2k9e7NpPX/TaT16AfivYGH4r23R+K9u4tg/WQLoL1mP///wD///8A////AP///wD///8A////AP///wA2k9fuNpPX5zaT1zMfivYGH4r23R+K9uwjiPYXLoL1+S6C9W7///8A////AP///wD///8A////AP///wD///8ANpPXLjaT1wAfivYGH4r22x+K9usfivYSLoL1oC6C9esugvUA////AP///wD///8A////AP///wD///8A////AP///wD///8AH4r2zx+K9usfivYSLoL1DC6C9fwugvVXLoL1AP///wD///8A////AP///wD///8A////AP///wD///8A////AB+K9kgfivYMH4r2AC6C9bEugvXhLoL1AC6C9QD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAugvXyLoL1SC6C9QAugvUA////AP//AADgBwAA7/cAAOgXAADv9wAA6BcAAO+XAAD4HwAA+E8AAPsDAAD8AQAA/AEAAP0DAAD/AwAA/ycAAP/nAAAoAAAAIAAAAEAAAAABACAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/////wD///8AhISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP8AAAAA////AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/////AP///wCEhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/4SEhP+EhIT/hISE/wAAAAD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP/4+vsA4ujuAOLo7gDi6O4A4ujuAN3k6wDZ4OgA2eDoANng6ADZ4OgA2eDoANng6ADW3uYAJS84APj6+wCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/9Xd5QBwjKgAcIyoRnCMqGRwjKhxcIyogHCMqI9wjKidcIyoq3CMqLlwjKjHcIyo1HCMqLhogpwA/f7+AISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AISEhP+EhIT/xtHcAHCMqABwjKjAcIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo/3CMqP9wjKj/cIyo4EdZawD///8AhISE/4SEhP////8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AhISE/4SEhP+2xNMAcIyoAHCMqJhwjKjPcIyowHCMqLFwjKijcoymlXSMpIh0jKR6co2mbG+OqGFqj61zXZO4AeXv9gCEhIT/hISE/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wCEhIT/hISE/6i5ygDF0dwAIiozACQyPQAoP1AALlBmADhlggBblLkGVJbBPFOWwnxTlsK5U5bC9FOWwv9TlsIp3erzAISEhP+EhIT/////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAALztHAAAAAAAuU2sAU5bCClOWwkNTlsKAU5bCwFOWwvhTlsL/U5bC/1OWwv9TlsL/U5bC/ViVvVcXOFAAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAALDhEALVFoAFOWwjpTlsL6U5bC/1OWwv9TlsL/U5bC/1OWwvxTlsLIV5W+i2CRs0xHi71TKYzUnyuM0gIJHi4AAAAAAAAAAAAAAAAA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAACtNZABTlsIAU5bCD1OWwv1TlsL6U5bCxFOWwoRVlsBHZJKwDCNObAA8icJAKYzUwimM1P8pjNT/KYzUWCaCxgALLUsAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAApS2EAU5bCAFOWwgBTlsIAU5bCNVOWwgg+cJEAIT1QABU/XQA1isg4KYzUuymM1P8pjNT/KYzU/ymM1LAti9E0JYvmDhdouAAAAAAAAAAAAP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AFyk1AE+PuQBTlsIAU5bCAER7nwAmRVoADBojABRFaQAwi80xKYzUsymM1P8pjNT/KYzU/ymM1LgsjNE2MovXFB+K9MUfivbBH4r2BgcdNAARQH8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAQIDABIgKgAPGiIABRMcABdQeQAti9AqKYzUrCmM1P8pjNT/KYzU/ymM1MAqjNM9HmqmACWK7SIfivbZH4r2/x+K9vsuiudAFE2YACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAABhQfABtejgAoitEAKYzUACmM1JQpjNT/KYzU/ymM1MgpjNREH2mgABlosQAfivY0H4r26R+K9v8fivbyKIrtR0CB1SggevTQIHr0Nv///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAACBwsAJX2+ACmM1AApjNQAKYzUGSmM1MYpjNRMInWxABNHdQAcfuEAH4r2Sx+K9vUfivb/H4r25iGK9DE2gt4EIHr0yyB69P8gevTQ////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAOMUsAKYzUACmM1AApjNQAJX6/ABE7WgAUWJwAH4r2AB+K9mYfivb9H4r2/x+K9tYfivYfG27RACB69HsgevT/IHr0+yB69DL///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAfaJ4AJ4XKABVGagAKKkoAG3raAB+K9gEfivaEH4r2/x+K9v8fivbCH4r2EB133wAgevQsIHr0+SB69P8gevSAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAUSGwAFERwAElCOAB+J9QAfivYAH4r2lx+K9v8fivb/H4r2qR+K9gYefuoAIHr0BSB69M4gevT/IHr00CB69AUgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAkqSgAfivYAH4r2AB+K9gAfivZLH4r2/R+K9osfivYBH4PwACB69AAgevSAIHr0/yB69PkgevQwIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAAAAAAAEEiAAB+K9gAfivYAH4r2AB+K9gAfivYsH4r2AB+G8wAge/QAIHr0MCB69PsgevT/IHr0eyB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAXZrYAH4r2AB+K9gAfivYAH4r2AB+K9gAfifUAIHz0ACB69AcgevTQIHr0/yB69MwgevQEIHr0ACB69AAgevQA////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wAAAAAAAAAAAAAAAAAAAAAAAAIDAB6E6gAfivYAH4r2AB+K9gAfivYAH4r2ACB+9QAgevQAIHr0fCB69P8gevT5IHr0LCB69AAgevQAIHr0ACB69AD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AAAAAAAAAAAAAAAAAAAAAAABBAcAEUqDAB6E6wAfivYAH4r2AB+K9gAggPUAIHr0ACB69AAgevQTIHr0qCB69HYgevQAIHr0ACB69AAgevQAIHr0AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP////////////////wAAH/8AAB//P/+f/z//n/8wAZ//MAGf/z//n/8wAZ//MAGf/zAAn/8/gJ//+AD///AAf//wEH//+cA///8AH//8BB///BgH//xwB///4If//4EP//+CD///hh///9w////4P///+H////j////////////" rel="icon" type="image/x-icon" />
Used this page here for this: http://www.motobit.com/util/base64-decoder-encoder.asp
I can really suggest you this page: http://www.favicon-generator.org/ to create all types of favicons you need.
Sorry for digging out an old thread, but I think sunetos' answer isn't correct (or isn't the full answer). I've done some experiments (using ProcessStartInfo in c#) and it seems that the 'arguments' string for a commandline command is limited to 2048 characters in XP and 32768 characters in Win7. I'm not sure what the 8191 limit refers to, but I haven't found any evidence of it yet.
It may work with any character from the HTML Escape character list, but I had the same problem with a Java project. I used StringEscapeUtils.escapeHTML("Testing \" <br> <p>")
and the title was <a href=".." title="Test" <br> <p>">Testing</a>
.
It only worked for me when I changed the StringEscapeUtils to StringEscapeUtils.escapeJavascript("Testing \" <br> <p>")
and it worked in every browser.
You can view this dump from the UNIX console.
The path for the heap dump will be provided as a variable right after where you have placed the mentioned variable.
E.g.:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${DOMAIN_HOME}/logs/mps"
You can view the dump from the console on the mentioned path.
Try this example
String[] formats = new String[] {
"yyyy-MM-dd",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd HH:mmZ",
"yyyy-MM-dd HH:mm:ss.SSSZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
};
for (String format : formats) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
}
and read this http://developer.android.com/reference/java/text/SimpleDateFormat.html
We replace the submit button with this all the time on forms:
<form method="post" action="whatever.asp">
<input type=...n
<input type="image" name="Submit" src="/graphics/continue.gif" align="middle" border="0" alt="Continue">
</form>
Clicking the image submits the form. Hope that helps!
You can first get all the view controllers in the array and then after checking with the corresponding view controller class, you can delete the one you want.
Here is small piece of code:
NSArray* tempVCA = [self.navigationController viewControllers];
for(UIViewController *tempVC in tempVCA)
{
if([tempVC isKindOfClass:[urViewControllerClass class]])
{
[tempVC removeFromParentViewController];
}
}
I think this will make your work easier.
It's possible to modify the code of .CRX extension, because it's a simple .zip archive. You can download extension, extract it's source code, modify it (test and debug it as it's on your side), and package back into .CRX file.
I googled out this tool to simply download .CRX extension and extract the source code and it worked for me: http://crxextractor.com
Everything it does is parses .CRX file format and extracts actual .zip containing the source code.
The recent versions of XAMPP for Windows runs PHP 7.x which are NOT compatible with mbcrypt. If you have a package like Laravel that requires mbcrypt, you will need to install an older version of XAMPP. OR, you can run XAMPP with multiple versions of PHP by downloading a PHP package from Windows.PHP.net, installing it in your XAMPP folder, and configuring php.ini and httpd.conf to use the correct version of PHP for your site.
If you don't mind using your mouse a little bit:
This creates a new tab on the terminal which you can run Vim on. Now use your mouse to shift to/from the terminal. I prefer this instead of always having to type (:shell
and exit).
I would advise, it is slightly better practise to use string model references for ForeignKey
relationships if utilising an app based approach to seperation of logical concerns .
So, expanding on Martijn Pieters' answer:
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
anniversary = models.ForeignKey(
'app_label.Anniversary', on_delete=models.CASCADE)
address = models.ForeignKey(
'app_label.Address', on_delete=models.CASCADE)
class Address(models.Model):
line1 = models.CharField(max_length=150)
line2 = models.CharField(max_length=150)
postalcode = models.CharField(max_length=10)
city = models.CharField(max_length=150)
country = models.CharField(max_length=150)
class Anniversary(models.Model):
date = models.DateField()
again this is all in the link you supplied
to change the text to white all you have to do is change the theme.
use this theme
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_my_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
Am using angular 5 and for an ngif to work for me that is in a ngfor, I had to use animateChild and in the user-detail component I used the *ngIf="user.expanded" to show hide user and it worked for entering a leaving
<div *ngFor="let user of users" @flyInParent>
<ly-user-detail [user]= "user" @flyIn></user-detail>
</div>
//the animation file
export const FLIP_TRANSITION = [
trigger('flyInParent', [
transition(':enter, :leave', [
query('@*', animateChild())
])
]),
trigger('flyIn', [
state('void', style({width: '100%', height: '100%'})),
state('*', style({width: '100%', height: '100%'})),
transition(':enter', [
style({
transform: 'translateY(100%)',
position: 'fixed'
}),
animate('0.5s cubic-bezier(0.35, 0, 0.25, 1)', style({transform: 'translateY(0%)'}))
]),
transition(':leave', [
style({
transform: 'translateY(0%)',
position: 'fixed'
}),
animate('0.5s cubic-bezier(0.35, 0, 0.25, 1)', style({transform: 'translateY(100%)'}))
])
])
];
Powder's comment may go undetected like I missed it so many times,. So with the hope of making it more visible, I will re-iterate his point.
Sometimes using image = array(img).reshape(a,b,c,d)
will reshape alright but from experience, my kernel crashes every time I try to use the new dimension in an operation. The safest to use is
np.expand_dims(img, axis=0)
It works perfect every time. I just can't explain why. This link has a great explanation and examples regarding its usage.
FileNameOnly = Dir(.SelectedItems(1))
Mockito matchers are static methods and calls to those methods, which stand in for arguments during calls to when
and verify
.
Hamcrest matchers (archived version) (or Hamcrest-style matchers) are stateless, general-purpose object instances that implement Matcher<T>
and expose a method matches(T)
that returns true if the object matches the Matcher's criteria. They are intended to be free of side effects, and are generally used in assertions such as the one below.
/* Mockito */ verify(foo).setPowerLevel(gt(9000));
/* Hamcrest */ assertThat(foo.getPowerLevel(), is(greaterThan(9000)));
Mockito matchers exist, separate from Hamcrest-style matchers, so that descriptions of matching expressions fit directly into method invocations: Mockito matchers return T
where Hamcrest matcher methods return Matcher objects (of type Matcher<T>
).
Mockito matchers are invoked through static methods such as eq
, any
, gt
, and startsWith
on org.mockito.Matchers
and org.mockito.AdditionalMatchers
. There are also adapters, which have changed across Mockito versions:
Matchers
featured some calls (such as intThat
or argThat
) are Mockito matchers that directly accept Hamcrest matchers as parameters. ArgumentMatcher<T>
extended org.hamcrest.Matcher<T>
, which was used in the internal Hamcrest representation and was a Hamcrest matcher base class instead of any sort of Mockito matcher.Matchers
calls phrased as intThat
or argThat
wrap ArgumentMatcher<T>
objects that no longer implement org.hamcrest.Matcher<T>
but are used in similar ways. Hamcrest adapters such as argThat
and intThat
are still available, but have moved to MockitoHamcrest
instead.Regardless of whether the matchers are Hamcrest or simply Hamcrest-style, they can be adapted like so:
/* Mockito matcher intThat adapting Hamcrest-style matcher is(greaterThan(...)) */
verify(foo).setPowerLevel(intThat(is(greaterThan(9000))));
In the above statement: foo.setPowerLevel
is a method that accepts an int
. is(greaterThan(9000))
returns a Matcher<Integer>
, which wouldn't work as a setPowerLevel
argument. The Mockito matcher intThat
wraps that Hamcrest-style Matcher and returns an int
so it can appear as an argument; Mockito matchers like gt(9000)
would wrap that entire expression into a single call, as in the first line of example code.
when(foo.quux(3, 5)).thenReturn(true);
When not using argument matchers, Mockito records your argument values and compares them with their equals
methods.
when(foo.quux(eq(3), eq(5))).thenReturn(true); // same as above
when(foo.quux(anyInt(), gt(5))).thenReturn(true); // this one's different
When you call a matcher like any
or gt
(greater than), Mockito stores a matcher object that causes Mockito to skip that equality check and apply your match of choice. In the case of argumentCaptor.capture()
it stores a matcher that saves its argument instead for later inspection.
Matchers return dummy values such as zero, empty collections, or null
. Mockito tries to return a safe, appropriate dummy value, like 0 for anyInt()
or any(Integer.class)
or an empty List<String>
for anyListOf(String.class)
. Because of type erasure, though, Mockito lacks type information to return any value but null
for any()
or argThat(...)
, which can cause a NullPointerException if trying to "auto-unbox" a null
primitive value.
Matchers like eq
and gt
take parameter values; ideally, these values should be computed before the stubbing/verification starts. Calling a mock in the middle of mocking another call can interfere with stubbing.
Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt())
or thenReturn(any(Foo.class))
in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.
Matchers are stored (as Hamcrest-style object matchers) in a stack contained in a class called ArgumentMatcherStorage. MockitoCore and Matchers each own a ThreadSafeMockingProgress instance, which statically contains a ThreadLocal holding MockingProgress instances. It's this MockingProgressImpl that holds a concrete ArgumentMatcherStorageImpl. Consequently, mock and matcher state is static but thread-scoped consistently between the Mockito and Matchers classes.
Most matcher calls only add to this stack, with an exception for matchers like and
, or
, and not
. This perfectly corresponds to (and relies on) the evaluation order of Java, which evaluates arguments left-to-right before invoking a method:
when(foo.quux(anyInt(), and(gt(10), lt(20)))).thenReturn(true);
[6] [5] [1] [4] [2] [3]
This will:
anyInt()
to the stack.gt(10)
to the stack.lt(20)
to the stack.gt(10)
and lt(20)
and add and(gt(10), lt(20))
.foo.quux(0, 0)
, which (unless otherwise stubbed) returns the default value false
. Internally Mockito marks quux(int, int)
as the most recent call.when(false)
, which discards its argument and prepares to stub method quux(int, int)
identified in 5. The only two valid states are with stack length 0 (equality) or 2 (matchers), and there are two matchers on the stack (steps 1 and 4), so Mockito stubs the method with an any()
matcher for its first argument and and(gt(10), lt(20))
for its second argument and clears the stack.This demonstrates a few rules:
Mockito can't tell the difference between quux(anyInt(), 0)
and quux(0, anyInt())
. They both look like a call to quux(0, 0)
with one int matcher on the stack. Consequently, if you use one matcher, you have to match all arguments.
Call order isn't just important, it's what makes this all work. Extracting matchers to variables generally doesn't work, because it usually changes the call order. Extracting matchers to methods, however, works great.
int between10And20 = and(gt(10), lt(20));
/* BAD */ when(foo.quux(anyInt(), between10And20)).thenReturn(true);
// Mockito sees the stack as the opposite: and(gt(10), lt(20)), anyInt().
public static int anyIntBetween10And20() { return and(gt(10), lt(20)); }
/* OK */ when(foo.quux(anyInt(), anyIntBetween10And20())).thenReturn(true);
// The helper method calls the matcher methods in the right order.
The stack changes often enough that Mockito can't police it very carefully. It can only check the stack when you interact with Mockito or a mock, and has to accept matchers without knowing whether they're used immediately or abandoned accidentally. In theory, the stack should always be empty outside of a call to when
or verify
, but Mockito can't check that automatically.
You can check manually with Mockito.validateMockitoUsage()
.
In a call to when
, Mockito actually calls the method in question, which will throw an exception if you've stubbed the method to throw an exception (or require non-zero or non-null values).
doReturn
and doAnswer
(etc) do not invoke the actual method and are often a useful alternative.
If you had called a mock method in the middle of stubbing (e.g. to calculate an answer for an eq
matcher), Mockito would check the stack length against that call instead, and likely fail.
If you try to do something bad, like stubbing/verifying a final method, Mockito will call the real method and also leave extra matchers on the stack. The final
method call may not throw an exception, but you may get an InvalidUseOfMatchersException from the stray matchers when you next interact with a mock.
InvalidUseOfMatchersException:
Check that every single argument has exactly one matcher call, if you use matchers at all, and that you haven't used a matcher outside of a when
or verify
call. Matchers should never be used as stubbed return values or fields/variables.
Check that you're not calling a mock as a part of providing a matcher argument.
Check that you're not trying to stub/verify a final method with a matcher. It's a great way to leave a matcher on the stack, and unless your final method throws an exception, this might be the only time you realize the method you're mocking is final.
NullPointerException with primitive arguments: (Integer) any()
returns null while any(Integer.class)
returns 0; this can cause a NullPointerException
if you're expecting an int
instead of an Integer. In any case, prefer anyInt()
, which will return zero and also skip the auto-boxing step.
NullPointerException or other exceptions: Calls to when(foo.bar(any())).thenReturn(baz)
will actually call foo.bar(null)
, which you might have stubbed to throw an exception when receiving a null argument. Switching to doReturn(baz).when(foo).bar(any())
skips the stubbed behavior.
Use MockitoJUnitRunner, or explicitly call validateMockitoUsage
in your tearDown
or @After
method (which the runner would do for you automatically). This will help determine whether you've misused matchers.
For debugging purposes, add calls to validateMockitoUsage
in your code directly. This will throw if you have anything on the stack, which is a good warning of a bad symptom.
some symbols should be transferred like '%'
<string name="test" formatted="false">95%</string>
If for some reason you cannot escape the apostrophe character and you can't change it into a HTML entity (as it was in my case for a specific Vue.js property) you can use replace to change it into different apostrophe character from the UTF8 characters set, for instance:
' - U+02BC
’ - U+2019
I ran into this when checking on a null or empty string
if (x == NULL || x == '') {
changed it to
if (is.null(x) || x == '') {
You need to new up an instance of EmailData and then add that:
var data = new EmailData { FirstName = "John", LastName = "Smith", Location = "LA" };
List<EmailData> listemail = new List<EmailData>();
listemail.Add(data);
If you want to able to do:
listemail.Add("JOhn","Smith","Los Angeles");
you can create your own custom list, by specializing System.Collections.Generic.List and implementing your own Add method, more or less like this:
public class EmailList : List<EmailData>
{
public void Add(string firstName, string lastName, string location)
{
var data = new EmailData
{
FirstName = firstName,
LastName = lastName,
Location = location
};
this.Add(data);
}
}
I think you get the array from response so you have to assign response to array.
NSError *err = nil; NSArray *array = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err]; NSDictionary *dictionary = [array objectAtIndex:0];
NSString *test = [dictionary objectForKey:@"ID"];
NSLog(@"Test is %@",test);
If you are using System.Web.Script.Serialization
in the .NET framework you can put a ScriptIgnore
attribute on the members that shouldn't be serialized. See the example taken from here:
Consider the following (simplified) case:
public class User { public int Id { get; set; } public string Name { get; set; } [ScriptIgnore] public bool IsComplete { get { return Id > 0 && !string.IsNullOrEmpty(Name); } } }
In this case, only the Id and the Name properties will be serialized, thus the resulting JSON object would look like this:
{ Id: 3, Name: 'Test User' }
PS. Don't forget to add a reference to "System.Web.Extensions
" for this to work
Use the same compiler options for linking also.
Example:
gcc -mfloat-abi=hard fpu=neon -c -o test.cpp test.o
gcc -mfloat-abi=hard fpu=neon -c test1.cpp test1.o
gcc test.o test1.o mfloat-abi=hard fpu=neon HardTest
I recommend something along these lines, even if the image lives inside of your model.
I realize you are asking for a direct way to access it right from the view and many others have answered that and told you what is wrong with that approach so this is just another way that will load the image in an async fashion for you and I think is a better approach.
Sample Model:
[Bind(Exclude = "ID")]
public class Item
{
[Key]
[ScaffoldColumn(false)]
public int ID { get; set; }
public String Name { get; set; }
public byte[] InternalImage { get; set; } //Stored as byte array in the database.
}
Sample Method in the Controller:
public async Task<ActionResult> RenderImage(int id)
{
Item item = await db.Items.FindAsync(id);
byte[] photoBack = item.InternalImage;
return File(photoBack, "image/png");
}
View
@model YourNameSpace.Models.Item
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>Item</h4>
<hr />
<dl class="dl-horizontal">
<img src="@Url.Action("RenderImage", new { id = Model.ID})" />
</dl>
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Name)
</dt>
<dd>
@Html.DisplayFor(model => model.Name)
</dd>
</dl>
</div>
There is a library available through nuget for dealing with pretty much any well formed CSV (.net) - CsvHelper
Example to map to a class:
var csv = new CsvReader( textReader );
var records = csv.GetRecords<MyClass>();
Example to read individual fields:
var csv = new CsvReader( textReader );
while( csv.Read() )
{
var intField = csv.GetField<int>( 0 );
var stringField = csv.GetField<string>( 1 );
var boolField = csv.GetField<bool>( "HeaderName" );
}
Letting the client drive the file format:
,
is the standard field delimiter, "
is the standard value used to escape fields that contain a delimiter, quote, or line ending.
To use (for example) #
for fields and '
for escaping:
var csv = new CsvReader( textReader );
csv.Configuration.Delimiter = "#";
csv.Configuration.Quote = ''';
// read the file however meets your needs
String s1 = "Welcome"; // Does not create a new instance
String s2 = new String("Welcome"); // Creates two objects and one reference variable
projectionScalar=dot(AC,AB)/(mag(AC)*mag(AB));
if(projectionScalar>=0 && projectionScalar<=1) {
D=A+AB*projectionScalar;
CD=D-C;
if(mag(CD)<circle.radius){
// there was a collision
}
}
ArrayList<File> directories = new ArrayList<File>(
Arrays.asList(
new File("your/path/").listFiles(File::isDirectory)
)
);
There is just a caveat that I discovered today.
If you have a function that is calling a plot a lot of times you better use plt.close(fig)
instead of fig.clf()
somehow the first does not accumulate in memory. In short if memory is a concern use plt.close(fig) (Although it seems that there are better ways, go to the end of this comment for relevant links).
So the the following script will produce an empty list:
for i in range(5):
fig = plot_figure()
plt.close(fig)
# This returns a list with all figure numbers available
print(plt.get_fignums())
Whereas this one will produce a list with five figures on it.
for i in range(5):
fig = plot_figure()
fig.clf()
# This returns a list with all figure numbers available
print(plt.get_fignums())
From the documentation above is not clear to me what is the difference between closing a figure and closing a window. Maybe that will clarify.
If you want to try a complete script there you have:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1000)
y = np.sin(x)
for i in range(5):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y)
plt.close(fig)
print(plt.get_fignums())
for i in range(5):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y)
fig.clf()
print(plt.get_fignums())
If memory is a concern somebody already posted a work-around in SO see: Create a figure that is reference counted
I ran into this annoying issue with the Play framework. It would be nice if there was some way of knowing what build errors Eclipse is unhappy about, but it's not going to tell you. With one project, I was able to close the project, rebuild the Eclipse configuration with sbt eclipse
, and reopen. With an almost identical project, that didn't work. But deleting the project, rebuilding the Eclipse configuration with sbt eclipse
, and importing, did the trick.
If someone wants expandable/collapsible version of the treeview from Vitaliy Bychik's answer, you can save some time :)
http://jsfiddle.net/mehmetatas/fXzHS/2/
$(function () {
$('.tree li').hide();
$('.tree li:first').show();
$('.tree li').on('click', function (e) {
var children = $(this).find('> ul > li');
if (children.is(":visible")) children.hide('fast');
else children.show('fast');
e.stopPropagation();
});
});
You are asking about the &&
operator, not the if
statement.
&&
short-circuits, meaning that if while working it meets a condition which results in only one answer, it will stop working and use that answer.
So, 0 && x
will execute 0
, then terminate because there is no way for the expression to evaluate non-zero regardless of what is the second parameter to &&
.
I was encountering this issue when trying to run Mocha + Babel. I had a .babelrc
that worked in development (see the other answers here, they are pretty complete), but my npm run test
command was still complaining about regeneratorRuntime is not defined
. So I modified my package.json
:
"scripts": {
"test": "mocha --require babel-polyfill --require babel-core/register tests/*.js"
}
Read more: https://babeljs.io/en/setup/#mocha-4
You can use Array.push()
for appending elements to an array.
For deleting, it is best to use this.$delete(array, index)
for reactive objects.
Vue.delete( target, key )
: Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.
ok i had the same problem and i fix it like this by removing []
from [{"key":"value"}]
:
- in your php file make shure that you print like this
echo json_encode(array_shift($your_variable));
- in your success function do this
success: function (data) {
var result = $.parseJSON(data);
('.yourclass').append(result['your_key1']);
('.yourclass').append(result['your_key2']);
..
}
and also you can loop it if you want
To get all the artisan command, type...
php artisan
If you want to clear view cache, just use:
php artisan view:clear
If you don't know how to use specific artisan command, just add "help" (see below)
php artisan help view:clear
For simple CRUD operations with a single data access point, I would say go for LINQ if you feel comfortable with the syntax. For more complicated logic I think sprocs are more efficiant performance-wise if you are good at T-SQL and its more advanced operations. You also have the help from Tuning Advisor, SQL Server Profiler, debugging your queries from SSMS etc.
This worked for me
open: function(event, ui) {
$(".ui-dialog-titlebar", $(this).parent())
.hide();
Full
$speedbump.dialog({
dialogClass: 'speedbump-container',
autoOpen: false,
closeOnEscape: false,
modal: true,
resizable: false,
draggable: false,
create: function () {
$speedbump
.closest('.ui-dialog')
.attr('id', 'speedbump-container');
},
open: function(event, ui) {
$(".ui-dialog-titlebar", $(this).parent())
.hide();
}
I got this from EDX use it! its called recursion
public static int factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n-1);
}
}
A pure php example.
<?php
$units = explode(' ', 'B KB MB GB TB PB');
$SIZE_LIMIT = 5368709120; // 5 GB
$disk_used = foldersize("/webData/users/[email protected]");
$disk_remaining = $SIZE_LIMIT - $disk_used;
echo("<html><body>");
echo('diskspace used: ' . format_size($disk_used) . '<br>');
echo( 'diskspace left: ' . format_size($disk_remaining) . '<br><hr>');
echo("</body></html>");
function foldersize($path) {
$total_size = 0;
$files = scandir($path);
$cleanPath = rtrim($path, '/'). '/';
foreach($files as $t) {
if ($t<>"." && $t<>"..") {
$currentFile = $cleanPath . $t;
if (is_dir($currentFile)) {
$size = foldersize($currentFile);
$total_size += $size;
}
else {
$size = filesize($currentFile);
$total_size += $size;
}
}
}
return $total_size;
}
function format_size($size) {
global $units;
$mod = 1024;
for ($i = 0; $size > $mod; $i++) {
$size /= $mod;
}
$endIndex = strpos($size, ".")+3;
return substr( $size, 0, $endIndex).' '.$units[$i];
}
?>
sudo is used for Linux. It looks like you are running this in Windows.
Call this method to change app locale:
public void settingLocale(Context context, String language) {
Locale locale;
Configuration config = new Configuration();
if(language.equals(LANGUAGE_ENGLISH)) {
locale = new Locale("en");
Locale.setDefault(locale);
config.locale = locale;
}else if(language.equals(LANGUAGE_ARABIC)){
locale = new Locale("hi");
Locale.setDefault(locale);
config.locale = locale;
}
context.getResources().updateConfiguration(config, null);
// Here again set the text on view to reflect locale change
// and it will pick resource from new locale
tv1.setText(R.string.one); //tv1 is textview in my activity
}
Note: Put your strings in value and values- folder.
Functionally no difference, Google just changed the name from fill_parent to match_parent, from API level 8 (Android 2.2). FILL_PARENT is still available for compatibility reason.
LayoutParams.FILL_PARENT
and LayoutParams.MATCH_PARENT
both have value -1. Not sure what tempted google to change from Fill Parent to Match Parent :)
Since most of the phones are >= Android 2.2
.. you should use Match Parent for future compatibility... not sure when they will discontinue the older Fill Parent constant!
Slightly off-topic but if you ever needed a class-based component that never renders anything and you are happy to use some yet-to-be-standardised ES syntax, you might want to go:
render = () => null
This is basically an arrow method that currently requires the transform-class-properties Babel plugin. React will not let you define a component without the render
function and this is the most concise form satisfying this requirement that I can think of.
I'm currently using this trick in a variant of ScrollToTop borrowed from the react-router
documentation. In my case, there's only a single instance of the component and it doesn't render anything, so a short form of "render null" fits nice in there.
if ($('#elem')[0]) {
// do stuff
}
This frustrated the heck out of me, and none of the above answers really got me what I wanted. I finally found the answer I was looking for, on a mac if you do ? + option + F it will bring up a Find-Replace bar at the bottom of your editor which is local to the file you have open.
There is an icon option which when hovered over says "In Selection" that you can select to find and replace within a selection. I've pointed to the correct icon in the screenshot below.
Hit replace all, and voila, all instances of '0'
will be replaced with '255'
.
Note: this feature is ONLY available when you use ? + option + F.
It does NOT appear when you use ? + shift + F.
Note: this will replace all instances of '0'
with '255'
. If you wanted to replace 0
(without the quotes) with 255
, then just put 0
(without quotes) and 255
in the Find What:
and Replace With:
fields respectively.
Note:
option key is also labeled as the alt key.
? key is also labeled as the command key.
Using parameter binding is definitely the way to go here. Not only is it very quick to write (just add [Parameter(Mandatory=$true)]
above your mandatory parameters), but it's also the only option that you won't hate yourself for later.
More below:
[Console]::ReadLine
is explicitly forbidden by the FxCop rules for PowerShell. Why? Because it only works in PowerShell.exe, not PowerShell ISE, PowerGUI, etc.
Read-Host is, quite simply, bad form. Read-Host uncontrollably stops the script to prompt the user, which means that you can never have another script that includes the script that uses Read-Host.
You're trying to ask for parameters.
You should use the [Parameter(Mandatory=$true)]
attribute, and correct typing, to ask for the parameters.
If you use this on a [SecureString]
, it will prompt for a password field. If you use this on a Credential type, ([Management.Automation.PSCredential]
), the credentials dialog will pop up, if the parameter isn't there. A string will just become a plain old text box. If you add a HelpMessage to the parameter attribute (that is, [Parameter(Mandatory = $true, HelpMessage = 'New User Credentials')]
) then it will become help text for the prompt.
Booleans in python are subclass of integer. Constructor of booleans is bool
. bool class inherits from int class.
issubclass(bool,int) // will return True
isinstance(True,bool) , isinstance(False,bool) //they both True
True
and False
are singleton objects. they will retain same memory address throughout the lifetime of your app. When you type True
, python memory manager will check its address and will pull the value '1'. for False
its value is '0'.
Comparisons of any boolean expression to True
or False
can be performed using either is
(identity) or ==
(equality) operator.
int(True) == 1
int(False) == 0
But note that True
and '1' are not the same objects. You can check:
id(True) == id(1) // will return False
you can also easily see that
True > False // returns true cause 1>0
any integer operation can work with the booleans.
True + True + True =3
All objects in python have an associated truth value. Every object has True
value except:
None
False
0 in any numeric type (0,0.0,0+0j etc)
empty sequences (list, tuple, string)
empty mapping types (dictionary, set, etc)
custom classes that implement __bool__
or __len__
method that returns False
or 0
.
every class in python has truth values defined by a special instance method:
__bool__(self) OR
__len__
When you call bool(x)
python will actually execute
x.__bool__()
if instance x
does not have this method, then it will execute
x.__len__()
if this does not exist, by default value is True
.
For Example for int
class we can define bool as below:
def __bool__(self):
return self != 0
for bool(100), 100 !=0
will return True
. So
bool(100) == True
you can easily check that bool(0)
will be False
. with this for instances of int class only 0 will return False.
another example= bool([1,2,3])
[1,2,3]
has no __bool__()
method defined but it has __len__()
and since its length is greater than 0, it will return True
. Now you can see why empty lists return False
.
if anyone gets in here again this worked for me...
"aoColumnDefs": [{ "bVisible": false, "aTargets": [0] }]
There is a far easier solution built into Android Studio, and it usually works for me without needing any brute force solution mentioned in other answers - so you should try this first:
click on the "gradle" symbol on the right side of Android Studio, and then on the "Refresh all Gradle projects" tool.
You want the following:
ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);
Columns are nullable by default. As long as the column is not declared UNIQUE
or NOT NULL
, there shouldn't be any problems.
A successful ping on your local network can be trapped using ERRORLEVEL
.
@ECHO OFF
PING 10.0.0.123
IF ERRORLEVEL 1 GOTO NOT-THERE
ECHO IP ADDRESS EXISTS
PAUSE
EXIT
:NOT-THERE
ECHO IP ADDRESS NOT NOT EXIST
PAUSE
EXIT
Try using setInterval
and include jquery library
and just try removing unwrap()
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
var timeout = setInterval(reloadChat, 5000);
function reloadChat () {
$('#links').load('test.php');
}
</script>
UPDATE
you are using a jquery old version so include the latest jquery version
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
There're 3 ways to achieve this in total. Assuming you have a environment named myenv
,
conda env remove --name myenv
, -n
is shortcut for --name
.
conda remove --name myenv --all
.
Delete the env folder directly. (Not recommended)
# list environments and their locations
conda env list
# or
# conda info --envs
# delete the folder listed
rm -rf /Users/username/.local/share/conda/envs/myenv
If you wanna delete the environment without a prompt to let you check again. Use -y
, shortcut for --yes
. (For global use check silent prompt in conda)
conda env remove -n myenv -y
conda remove -n myenv --all -y
conda env --help
conda remove --help
Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).
Anyways, if you're already planning on using MSYS2, there's no need for that installer.
Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).
After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit
or MSYS2 32-bit
in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu
, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).
Install a toolchain
a) for 32-bit:
pacman -S mingw-w64-i686-gcc
b) for 64-bit:
pacman -S mingw-w64-x86_64-gcc
install any libraries/tools you may need. You can search the repositories by doing
pacman -Ss name_of_something_i_want_to_install
e.g.
pacman -Ss gsl
and install using
pacman -S package_name_of_something_i_want_to_install
e.g.
pacman -S mingw-w64-x86_64-gsl
and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!
Open a MinGW-w64 shell:
a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"
b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"
Verify that the compiler is working by doing
gcc -v
If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin
or <MSYS2 root>/mingw64/bin
to your PATH
.
I was trying to write a code that would work on both Mac and Windows. The code was working fine on Windows, but was giving the response as 'Unsupported Media Type' on Mac. Here is the code I used and the following line made the code work on Mac as well:
Request.AddHeader "Content-Type", "application/json"
Here is the snippet of my code:
Dim Client As New WebClient
Dim Request As New WebRequest
Dim Response As WebResponse
Dim Distance As String
Client.BaseUrl = "http://1.1.1.1:8080/config"
Request.AddHeader "Content-Type", "application/json" *** The line that made the code work on mac
Set Response = Client.Execute(Request)
Roll back the most recent migration:
rake db:rollback
Roll back the n
most recent migrations:
rake db:rollback STEP=n
You can find full instructions on the use of Rails migration tasks for rake on the Rails Guide for running migrations.
Here's some more:
rake db:migrate
- Run all migrations that haven't been run alreadyrake db:migrate VERSION=20080906120000
- Run all necessary migrations (up or down) to get to the given versionrake db:migrate RAILS_ENV=test
- Run migrations in the given environmentrake db:migrate:redo
- Roll back one migration and run it againrake db:migrate:redo STEP=n
- Roll back the last n
migrations and run them againrake db:migrate:up VERSION=20080906120000
- Run the up
method for the given migrationrake db:migrate:down VERSION=20080906120000
- Run the down
method for the given migrationAnd to answer your question about where you get a migration's version number from:
The version is the numerical prefix on the migration's filename. For example, to migrate to version 20080906120000 run
$ rake db:migrate VERSION=20080906120000
(From Running Migrations in the Rails Guides)
I liked Arun's answer better but there is a tiny problem and I could not comment or edit the answer. sparkContext does not have createDeataFrame, sqlContext does (as Thiago mentioned). So:
from pyspark.sql import SQLContext
# assuming the spark environemnt is set and sc is spark.sparkContext
sqlContext = SQLContext(sc)
schemaPeople = sqlContext.createDataFrame(RDDName)
schemaPeople.createOrReplaceTempView("RDDName")
I ignore all classes residing in target folder from git. add following line in open .gitignore file:
/.class
OR
*/target/**
It is working perfectly for me. try it.
I found this useful and easy to use, plus it looks pretty: http://maxailloud.github.io/confirm-bootstrap/.
To use it, include the .js file in your page then run:
$('your-link-selector').confirmModal();
There are various options you can apply to it, to make it look better when doing it to confirm a delete, I use:
$('your-link-selector').confirmModal({
confirmTitle: 'Please confirm',
confirmMessage: 'Are you sure you want to delete this?',
confirmStyle: 'danger',
confirmOk: '<i class="icon-trash icon-white"></i> Delete',
confirmCallback: function (target) {
//perform the deletion here, or leave this option
//out to just follow link..
}
});
You need to be in the directory of the file and then type the following into the terminal
git reset HEAD .
Assumption is that you need to reset one file only.
Presumably, you want to convert values before the decimal place to an integer. If so, use case
and check for the right format:
SELECT (case when varcharcol not like '%.%' then cast(varcharcol as int)
else cast(left(varcharcol, chardindex('.', varcharcol) - 1) as int)
end) IntVal
FROM MyTable;
This should work. Make sure each button has a unique ID. (Replace Choose_Yes and Choose_No with the IDs of your two radio buttons)
document.getElementById("Choose_Yes").checked = false;
document.getElementById("Choose_No").checked = false;
An example of how the radio buttons should be named:
<input type="radio" name="Choose" id="Choose_Yes" value="1" /> Yes
<input type="radio" name="Choose" id="Choose_No" value="2" /> No
Why could you not just make a file structure on the Windows file system and populate it with your desired names, then use a screen grabber like HyperSnap (or the ubiquitous Alt-PrtScr) to capture a section of the Explorer window.
I did this when 'demoing' an internet application which would have collapsible sections, I just had to create files that looked like my desired entries.
HyperSnap gives JPGs at least (probably others but I've never bothered to investigate).
Or you could screen capture the icons +/- from Explorer and use them within MS Word Draw itself to do your picture, but I've never been able to get MS Word Draw to behave itself properly.
I made a repository in Github which you can clone, vagrant-node-nginx-boilerplate
basically the node.js app at /var/www/nodeapp
is
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(4570, '127.0.0.1');
console.log('Node Server running at 127.0.0.1:4570/');
and the nginx config at /etc/nginx/sites-available/
is
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/nodeapp;
index index.html index.htm;
server_name localhost;
location / {
proxy_pass http://127.0.0.1:4570;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
If you're using Typescript and want to match on a single property value, this should work based on Craciun Ciprian's answer above.
You could also make this more generic by allowing non-object matching and / or multi-property value matching.
/**
*
* @param arr1 The initial array
* @param arr2 The array to remove
* @param propertyName the key of the object to match on
*/
function differenceByPropVal<T>(arr1: T[], arr2: T[], propertyName: string): T[] {
return arr1.filter(
(a: T): boolean =>
!arr2.find((b: T): boolean => b[propertyName] === a[propertyName])
);
}
In JavaScript you simple test for the cookieEnabled property, which is supported in all major browsers. If you deal with an older browser, you can set a cookie and check if it exists. (borrowed from Modernizer):
if (navigator.cookieEnabled) return true;
// set and read cookie
document.cookie = "cookietest=1";
var ret = document.cookie.indexOf("cookietest=") != -1;
// delete cookie
document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT";
return ret;
In PHP it is rather "complicated" since you have to refresh the page or redirect to another script. Here I will use two scripts:
somescript.php
<?php
session_start();
setcookie('foo', 'bar', time()+3600);
header("location: check.php");
check.php
<?php echo (isset($_COOKIE['foo']) && $_COOKIE['foo']=='bar') ? 'enabled' : 'disabled';
Try this :
SELECT
[First Name], [Last Name]
FROM
[Temp Test Data] AS td EXCEPTION JOIN [Data] AS d ON
(d.[First Name] = td.[First Name] OR d.[Last Name] = td.[Last Name])
Much simpler to read.
Run cat -v file.sh
.
You most likely have a carriage return or no-break space in your file. cat -v
will show them as ^M
and M-BM-
or M-
respectively. It will similarly show any other strange characters you might have gotten into your file.
Remove the Windows line breaks with
tr -d '\r' < file.sh > fixedfile.sh
by splitting with newlines.
for line in wallop_of_a_string_with_many_lines.split('\n'):
#do_something..
if you iterate over a string, you are iterating char by char in that string, not by line.
>>>string = 'abc'
>>>for line in string:
print line
a
b
c
From Resetting SQL Server Identity Columns:
Retrieving the identity for the table Employees
:
DBCC checkident ('Employees')
Repairing the identity seed (if for some reason the database is inserting duplicate identities):
DBCC checkident ('Employees', reseed)
Changing the identity seed for the table Employees
to 1000:
DBCC checkident ('Employees', reseed, 1000)
The next row inserted will begin at 1001.
You can also do it as part of the declaration:
int[] a = new int[] {0, 0, 0, 0};
For passing multiple array data from controller to view, try it. It is working. In this example, I am passing subject details from a table and subject details contain category id, the details like name if category id is fetched from another table category.
$category = Category::all();
$category = Category::pluck('name', 'id');
$item = Subject::find($id);
return View::make('subject.edit')->with(array('item'=>$item, 'category'=>$category));
Easy way:
missingmen.txt
to missingmen.html
.missingmen.html
:<link href="txtstyle.css" rel="stylesheet" type="text/css" />
txtstyle.css
, and add to it a line like this:html, body {font-family:Helvetica, Arial, sans-serif}
It's not magic.
The behavior of this code in C is described in section 6.7.8.21 of the C specification (online draft of C spec): for the elements that don't have a specified value, the compiler initializes pointers to NULL and arithmetic types to zero (and recursively applies this to aggregates).
The behavior of this code in C++ is described in section 8.5.1.7 of the C++ specification (online draft of C++ spec): the compiler aggregate-initializes the elements that don't have a specified value.
Also, note that in C++ (but not C), you can use an empty initializer list, causing the compiler to aggregate-initialize all of the elements of the array:
char array[100] = {};
As for what sort of code the compiler might generate when you do this, take a look at this question: Strange assembly from array 0-initialization
It's mainly a matter of choice most of the time. It's a matter of preference.
Note however that if you have numeric keys for example, that you can't do:
mydict = dict(1="foo", 2="bar")
You have to do:
mydict = {"1":"foo", "2":"bar"}
...but the form is not submitted with any of the POST data it is supposed to include.
Correct. Disabled form element names/values will not be sent to the server. You should set them as readonly elements.
Also, anchors cannot be disabled like that. You will need to either remove their HREFs (not recommended) or prevent their default behaviour (better way), e.g.:
<script type="text/javascript">
$(document).ready(function(){
$("form#my_form").submit(function(){
$('input').attr('readonly', true);
$('input[type=submit]').attr("disabled", "disabled");
$('a').unbind("click").click(function(e) {
e.preventDefault();
// or return false;
});
});
</script>
From what I've seen you should be be shipping a database that already has the tables setup and data. However if you want (and depending on the type of application you have) you can allow "upgrade database option". Then what you do is download the latest sqlite version, get the latest Insert/Create statements of a textfile hosted online, execute the statements and do a data transfer from the old db to the new one.
In my case, I had to put a check mark near Expose daemon on tcp://localhost:2375 without TLS
in docker
setting (on the right side of the task bar, right click on docker
, select setting
)
I know there were lots of answers here, but the TL;DR version is this (If you're using Xamarin Studio):
Options
Android Build
Advanced
tabx86
/ armeabi-v7a
/ armeabi
)You can also use the jquery prop() method for this.
$(function(){
$('yourselector').prop('target', '_blank');
});
If you want to use AngularJs Directive with dynamic template, you can use those answers,But here is more professional and legal syntax of it.You can use templateUrl not only with single value.You can use it as a function,which returns a value as url.That function has some arguments,which you can use.
Here's a quick way to preview a large table without having it run too wide:
Display function:
# display large dataframes in an html iframe
def ldf_display(df, lines=500):
txt = ("<iframe " +
"srcdoc='" + df.head(lines).to_html() + "' " +
"width=1000 height=500>" +
"</iframe>")
return IPython.display.HTML(txt)
Now just run this in any cell:
ldf_display(large_dataframe)
This will convert the dataframe to html then display it in an iframe. The advantage is that you can control the output size and have easily accessible scroll bars.
Worked for my purposes, maybe it will help someone else.
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
console.log(Object.keys(ary)[0]);
Make any Object array (req
), then simply do Object.keys(req)[0]
to pick the first key in the Object array.
Here is a simple one liner
var segment = (arr, n) => arr.reduce((r,e,i) => i%n ? (r[r.length-1].push(e), r)_x000D_
: (r.push([e]), r), []),_x000D_
arr = Array.from({length: 31}).map((_,i) => i+1);_x000D_
console.log(segment(arr,7));
_x000D_
...but what is "seen here" is broken. Here's the fix:
> pwd
/home/me
> x='Om Namah Shivaya'
> mkdir "$x" && cd "$x"
/home/me/Om Namah Shivaya
> parentdir="$(dirname "$(pwd)")"
> echo $parentdir
/home/me
void trim(char* const str)
{
char* begin = str;
char* end = str;
while (isspace(*begin))
{
++begin;
}
char* s = begin;
while (*s != '\0')
{
if (!isspace(*s++))
{
end = s;
}
}
*end = '\0';
const int dist = end - begin;
if (begin > str && dist > 0)
{
memmove(str, begin, dist + 1);
}
}
Modifies string in place, so you can still delete it.
Doesn't use fancy pants library functions (unless you consider memmove fancy).
Handles string overlap.
Trims front and back (not middle, sorry).
Fast if string is large (memmove often written in assembly).
Only moves characters if required (I find this true in most use cases because strings rarely have leading spaces and often don't have tailing spaces)
I would like to test this but I'm running late. Enjoy finding bugs... :-)
You could use regular expressions to count for you.
String subject = "First Line\n Second Line\nThird Line";
Matcher wordM = Pattern.compile("\\b\\S+?\\b").matcher(subject); //matches a word
Matcher charM = Pattern.compile(".").matcher(subject); //matches a character
Matcher newLineM = Pattern.compile("\\r?\\n").matcher(subject); //matches a linebreak
int words=0,chars=0,newLines=1; //newLines is initially 1 because the first line has no corresponding linebreak
while(wordM.find()) words++;
while(charM.find()) chars++;
while(newLineM.find()) newLines++;
System.out.println("Words: "+words);
System.out.println("Chars: "+chars);
System.out.println("Lines: "+newLines);
The only portable way to achieve consistency between rooms and tags and making sure rooms are never returned after they had been deleted is locking them with SELECT FOR UPDATE
.
However in some systems locking is a side effect of concurrency control, and you achieve the same results without specifying FOR UPDATE
explicitly.
To solve this problem, Thread 1 should
SELECT id FROM rooms FOR UPDATE
, thereby preventing Thread 2 from deleting fromrooms
until Thread 1 is done. Is that correct?
This depends on the concurrency control your database system is using.
MyISAM
in MySQL
(and several other old systems) does lock the whole table for the duration of a query.
In SQL Server
, SELECT
queries place shared locks on the records / pages / tables they have examined, while DML
queries place update locks (which later get promoted to exclusive or demoted to shared locks). Exclusive locks are incompatible with shared locks, so either SELECT
or DELETE
query will lock until another session commits.
In databases which use MVCC
(like Oracle
, PostgreSQL
, MySQL
with InnoDB
), a DML
query creates a copy of the record (in one or another way) and generally readers do not block writers and vice versa. For these databases, a SELECT FOR UPDATE
would come handy: it would lock either SELECT
or the DELETE
query until another session commits, just as SQL Server
does.
When should one use
REPEATABLE_READ
transaction isolation versusREAD_COMMITTED
withSELECT ... FOR UPDATE
?
Generally, REPEATABLE READ
does not forbid phantom rows (rows that appeared or disappeared in another transaction, rather than being modified)
In Oracle
and earlier PostgreSQL
versions, REPEATABLE READ
is actually a synonym for SERIALIZABLE
. Basically, this means that the transaction does not see changes made after it has started. So in this setup, the last Thread 1
query will return the room as if it has never been deleted (which may or may not be what you wanted). If you don't want to show the rooms after they have been deleted, you should lock the rows with SELECT FOR UPDATE
In InnoDB
, REPEATABLE READ
and SERIALIZABLE
are different things: readers in SERIALIZABLE
mode set next-key locks on the records they evaluate, effectively preventing the concurrent DML
on them. So you don't need a SELECT FOR UPDATE
in serializable mode, but do need them in REPEATABLE READ
or READ COMMITED
.
Note that the standard on isolation modes does prescribe that you don't see certain quirks in your queries but does not define how (with locking or with MVCC
or otherwise).
When I say "you don't need SELECT FOR UPDATE
" I really should have added "because of side effects of certain database engine implementation".
One good piece which helps me when starting with C (taken from the Expert C Programming by Linden)
The One 'l' nul and the Two 'l' null
Memorize this little rhyme to recall the correct terminology for pointers and ASCII zero:
The one "l" NUL ends an ASCII string,
The two "l" NULL points to no thing.
Apologies to Ogden Nash, but the three "l" nulll means check your spelling.
Using Linq to xml
Add a reference to System.Xml.Linq
and use
XDocument.Parse(string xmlString)
Edit: Sample follows, xml data (TestConfig.xml)..
<?xml version="1.0"?>
<Tests>
<Test TestId="0001" TestType="CMD">
<Name>Convert number to string</Name>
<CommandLine>Examp1.EXE</CommandLine>
<Input>1</Input>
<Output>One</Output>
</Test>
<Test TestId="0002" TestType="CMD">
<Name>Find succeeding characters</Name>
<CommandLine>Examp2.EXE</CommandLine>
<Input>abc</Input>
<Output>def</Output>
</Test>
<Test TestId="0003" TestType="GUI">
<Name>Convert multiple numbers to strings</Name>
<CommandLine>Examp2.EXE /Verbose</CommandLine>
<Input>123</Input>
<Output>One Two Three</Output>
</Test>
<Test TestId="0004" TestType="GUI">
<Name>Find correlated key</Name>
<CommandLine>Examp3.EXE</CommandLine>
<Input>a1</Input>
<Output>b1</Output>
</Test>
<Test TestId="0005" TestType="GUI">
<Name>Count characters</Name>
<CommandLine>FinalExamp.EXE</CommandLine>
<Input>This is a test</Input>
<Output>14</Output>
</Test>
<Test TestId="0006" TestType="GUI">
<Name>Another Test</Name>
<CommandLine>Examp2.EXE</CommandLine>
<Input>Test Input</Input>
<Output>10</Output>
</Test>
</Tests>
C# usage...
XElement root = XElement.Load("TestConfig.xml");
IEnumerable<XElement> tests =
from el in root.Elements("Test")
where (string)el.Element("CommandLine") == "Examp2.EXE"
select el;
foreach (XElement el in tests)
Console.WriteLine((string)el.Attribute("TestId"));
This code produces the following output: 0002 0006
There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX function gettimeofday().
You can use
SELECT SYS_EXTRACT_UTC(TIMESTAMP '2000-03-28 11:30:00.00 -02:00') FROM DUAL;
You may also need to change your timezone
ALTER SESSION SET TIME_ZONE = 'Europe/Berlin';
Or read it
SELECT SESSIONTIMEZONE, CURRENT_TIMESTAMP FROM dual;
This warning is useful for programmers that would mistakenly write 'test'
where they should have written "test"
.
This happen much more often than programmers that do actually want multi-char int constants.
Using CSS3: http://www.w3schools.com/cssref/sel_nth-child.asp
If that's not an option for any reason, you could try giving the list items classes:
<ul>
<li class="one"></li>
<li class="two"></li>
<li class="three"></li>
...
</ul>
Then in your css:
li.one{display:none}/*hide first li*/
li.three{display:none}/*hide third li*/
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
1> Add this namspace. using Newtonsoft.Json.Linq;
2> use this source code.
JObject joResponse = JObject.Parse(response);
JObject ojObject = (JObject)joResponse["response"];
JArray array= (JArray)ojObject ["chats"];
int id = Convert.ToInt32(array[0].toString());
Why don't these questions get answered with the obvious answer?
a = numpy.empty(n, dtype=object)
This creates an array of length n that can store objects. It can't be resized or appended to. In particular, it doesn't waste space by padding its length. This is the Python equivalent of Java's
Object[] a = new Object[n];
If you're really interested in performance and space and know that your array will only store certain numeric types then you can change the dtype argument to some other value like int. Then numpy will pack these elements directly into the array rather than making the array reference int objects.
Instead using entire link we can make as below (solution concerns jsp files)
With JSTL we can make it like: To link resource like css, js:
<link rel="stylesheet" href="${pageContext.request.contextPath}/style/sample.css" />
<script src="${pageContext.request.contextPath}/js/sample.js"></script>
To simply make a link:
<a id=".." class=".." href="${pageContext.request.contextPath}/jsp/sample.jsp">....</a>
It's worth to get familiar with tags
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
There is also jsp method to do it like below, but better way like above:
<link rel="stylesheet" href="<%=request.getContextPath()%>/style/sample.css" />
<script type="text/javascript" src="<%=request.getContextPath()%>/js/sample.js"></script>
To simply make a link:
<a id=".." class=".." href="<%=request.getContextPath()%>/jsp/sample.jsp">....</a>
Thank you everybody support :))
UIDevice+Extensions.swift
import Foundation
import UIKit
extension UIDevice {
static let modelName: String = {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
func mapToDevice(identifier: String) -> String { // swiftlint:disable:this cyclomatic_complexity
#if os(iOS)
switch identifier {
case "iPod5,1": return "iPod Touch 5"
case "iPod7,1": return "iPod Touch 6"
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone9,1", "iPhone9,3": return "iPhone 7"
case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus"
case "iPhone8,4": return "iPhone SE"
case "iPhone10,1", "iPhone10,4": return "iPhone 8"
case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus"
case "iPhone10,3", "iPhone10,6": return "iPhone X"
case "iPhone11,2": return "iPhone XS"
case "iPhone11,4", "iPhone11,6": return "iPhone XS Max"
case "iPhone11,8": return "iPhone XR"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad6,11", "iPad6,12": return "iPad 5"
case "iPad7,5", "iPad7,6": return "iPad 6"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"
case "iPad5,1", "iPad5,2": return "iPad Mini 4"
case "iPad6,3", "iPad6,4": return "iPad Pro 9.7 Inch"
case "iPad6,7", "iPad6,8": return "iPad Pro 12.9 Inch"
case "iPad7,1", "iPad7,2": return "iPad Pro 12.9 Inch 2. Generation"
case "iPad7,3", "iPad7,4": return "iPad Pro 10.5 Inch"
case "AppleTV5,3": return "Apple TV"
case "AppleTV6,2": return "Apple TV 4K"
case "AudioAccessory1,1": return "HomePod"
case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "iOS"))"
default: return identifier
}
#elseif os(tvOS)
switch identifier {
case "AppleTV5,3": return "Apple TV 4"
case "AppleTV6,2": return "Apple TV 4K"
case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "tvOS"))"
default: return identifier
}
#endif
}
return mapToDevice(identifier: identifier)
}()
}
enum DeviceName: String {
case iPod_Touch_5 = "iPod Touch 5"
case pod_Touch_6 = "Pod Touch 6"
case iPhone_4 = "iPhone 4"
case iPhone_4s = "iPhone 4s"
case iPhone_5 = "iPhone 5"
case iPhone_5c = "iPhone 5c"
case iPhone_5s = "iPhone 5s"
case iPhone_6 = "iPhone 6"
case iPhone_6_Plus = "iPhone 6 Plus"
case iPhone_6s = "iPhone 6s"
case iPhone_6s_Plus = "iPhone 6s Plus"
case iPhone_7 = "iPhone 7"
case iPhone_7_Plus = "iPhone 7 Plus"
case iPhone_SE = "iPhone SE"
case iPhone_8 = "iPhone 8"
case iPhone_8_Plus = "iPhone 8 Plus"
case iPhone_X = "iPhone X"
case iPhone_XS = "iPhone XS"
case iPhone_XS_Max = "iPhone XS Max"
case iPhone_XR = "iPhone XR"
case iPad_2 = "iPad 2"
case iPad_3 = "iPad 3"
case iPad_4 = "iPad 4"
case iPad_Air = "iPad Air"
case iPad_Air_2 = "iPad Air 2"
case iPad_5 = "iPad 5"
case iPad_6 = "iPad 6"
case iPad_Mini = "iPad Mini"
case iPad_Mini_2 = "iPad Mini 2"
case iPad_Mini_3 = "iPad Mini 3"
case iPad_Mini_4 = "iPad Mini 4"
case iPad_Pro_9_7_Inch = "iPad Pro 9.7 Inch"
case iPad_Pro_12_9_Inch = "iPad Pro 12.9 Inch"
case iPad_Pro_12_9_Inch_2_Generation = "iPad Pro 12.9 Inch 2. Generation"
case iPad_Pro_10_5_Inch = "iPad Pro 10.5 Inch"
case apple_TV = "Apple TV"
case apple_TV_4K = "Apple TV 4K"
case homePod = "HomePod"
}
SharedFunctions.swift
import Foundation
import UIKit
func isDevice(_ name: DeviceName) -> Bool {
let modelName = UIDevice.modelName.replacingOccurrences(of: "Simulator", with: "").trimmed()
if name.rawValue == modelName {
return true
}
return false
}
String+Whitespace.swift
import Foundation
extension String {
public func trimmed() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
If you use bootstrap 4 Alpha and you have an error with the height of the images in chrome, I have a solution: The documentation of bootstrap 4 says this:
<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
<div class="carousel-item active">
<img class="d-block img-fluid" src="..." alt="First slide">
</div>
<div class="carousel-item">
<img class="d-block img-fluid" src="..." alt="Second slide">
</div>
<div class="carousel-item">
<img class="d-block img-fluid" src="..." alt="Third slide">
</div>
</div>
</div>
Solution:
The solution is to put "div" around the image, with the class ".container", like this:
<div class="carousel-item active">
<div class="container">
<img src="images/proyecto_0.png" alt="First slide" class="d-block img-fluid">
</div>
</div>
this is best solution for me :)
$i=0;
foreach() if ($i < yourlimitnumber) {
$i +=1;
}
Looks like you missed some options, try to add:
position: relative;
top: 25px;
brew upgrade ruby
Should pull latest version of the package and install it.
brew update
updates brew itself, not packages (formulas they call it)
Assuming ASCII strings:
string1 = 'Hello'
string2 = 'hello'
if string1.lower() == string2.lower():
print("The strings are the same (case insensitive)")
else:
print("The strings are NOT the same (case insensitive)")
EDIT: Per other comments, the "Advanced..." button appears to have been removed in more recent versions of Jenkins. If your version doesn't have it, see knorx's answer.
I had the same problem, and even after finding this old pull request I still had trouble finding where to specify the Workspace Root Directory or Build Record Root Directory at the system level, versus specifying a custom workspace for each job.
To set these:
Jenkins
-> Manage Jenkins
-> Configure System
Home directory
, click the Advanced...
button:
This value may include the following variables:
${JENKINS_HOME}
— Absolute path of the Jenkins home directory${ITEM_ROOTDIR}
— Absolute path of the directory where Jenkins stores the configuration and related metadata for a given job${ITEM_FULL_NAME}
— The full name of a given job, which may be slash-separated, e.g. foo/bar for the job bar in folder foo
The value should normally include${ITEM_ROOTDIR}
or${ITEM_FULL_NAME}
, otherwise different jobs will end up sharing the same workspace.
The usual method is to use the NEWID() function, which generates a unique GUID. So,
SELECT * FROM dbo.Foo ORDER BY NEWID();
Unfortunately, there is no :click pseudo selector. If you want to change styling on click, you should use Jquery/Javascript. It certainly is better than the "hack" for pure HTML / CSS. But if you insist...
input {_x000D_
display: none;_x000D_
}_x000D_
span {_x000D_
padding: 20px;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
input:checked + span {_x000D_
background: #444;_x000D_
color: #fff;_x000D_
}
_x000D_
<label for="input">_x000D_
<input id="input" type="radio" />_x000D_
<span>NO JS styling</span>_x000D_
</label>
_x000D_
Or, if you prefer, you can toggle the styling:
input {_x000D_
display: none;_x000D_
}_x000D_
span {_x000D_
padding: 20px;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
input:checked + span {_x000D_
background: #444;_x000D_
color: #fff;_x000D_
}
_x000D_
<label for="input">_x000D_
<input id="input" type="checkbox" />_x000D_
<span>NO JS styling</span>_x000D_
</label>
_x000D_
You can get the path of sdcard from this code:
File extStore = Environment.getExternalStorageDirectory();
Then specify the foldername and file name
for e.g:
"/LazyList/"+serialno.get(position).trim()+".jpg"
First to install your app:
adb install -r path\ProjectName.apk
The great thing about the -r is it works even if it wasn’t already installed.
To launch MainActivity, so you can launch it like:
adb shell am start -n com.other.ProjectName/.MainActivity
In my experience it's best to put as much code as you can into well-named modules, and only put as much code as you need to into the actual worksheet objects.
Example: Any code that uses worksheet events like Worksheet_SelectionChange or Worksheet_Calculate.
Change 1D array into 2D array without using Numpy.
l = [i for i in range(1,21)]
part = 3
new = []
start, end = 0, part
while end <= len(l):
temp = []
for i in range(start, end):
temp.append(l[i])
new.append(temp)
start += part
end += part
print("new values: ", new)
# for uneven cases
temp = []
while start < len(l):
temp.append(l[start])
start += 1
new.append(temp)
print("new values for uneven cases: ", new)
I added the following job to crontab. It is hacky but i think should work.
*/5 * * * * service ntpd stop && ntpdate pool.ntp.org && service ntpd start
It stops ntpd service updates from service and starts ntpd again
This error can be caused by the permissions to the file, which you should check, however recently I noticed that the same is thrown if the file has been transferred and windows has marked the file as 'Encrypt Contents to Secure Data'.
You can find this by bringing up the .bak file properties and clicking the advanced button, it appears as the last check box on the dialog.
Hope that helps someone!
I do know that the account needs to have "Log on as a Service" privileges. Other than that, I'm not sure. A quick reference to Log on as a Service can be found here, and there is a lot of information of specific privileges here.
location.reload();
See this MDN page for more information.
If you are refreshing after an onclick
then you'll need to return false directly after
location.reload();
return false;
Make sure you have your maven bin directory in the path and the JAVA_HOME property set
The problem seems to be that you expect plt.show()
to show the window and then to return. It does not do that. The program will stop at that point and only resume once you close the window. You should be able to test that: If you close the window and then another window should pop up.
To resolve that problem just call plt.show()
once after your loop. Then you get the complete plot. (But not a 'real-time plotting')
You can try setting the keyword-argument block
like this: plt.show(block=False)
once at the beginning and then use .draw()
to update.
The idea that you hope to achieve can be made possible if you tweak the requirement a little bit
The below code is possible if your runtime supports the ES6 specification.
More about async functions
async function myAsynchronousCall(param1) {
// logic for myAsynchronous call
return d;
}
function doSomething() {
var data = await myAsynchronousCall(param1); //'blocks' here until the async call is finished
return data;
}
This is realy helpfull
SET search_path TO schema,public;
I digged this issues more, and found out about how to set this "search_path" by defoult for a new user in current database.
Open DataBase Properties then open Sheet "Variables" and simply add this variable for your user with actual value.
So now your user will get this schema_name by defoult and you could use tableName without schemaName.
In my experience, using System.gc() is effectively a platform-specific form of optimization (where "platform" is the combination of hardware architecture, OS, JVM version and possible more runtime parameters such as RAM available), because its behaviour, while roughly predictable on a specific platform, can (and will) vary considerably between platforms.
Yes, there are situations where System.gc() will improve (perceived) performance. On example is if delays are tolerable in some parts of your app, but not in others (the game example cited above, where you want GC to happen at the start of a level, not during the level).
However, whether it will help or hurt (or do nothing) is highly dependent on the platform (as defined above).
So I think it is valid as a last-resort platform-specific optimization (i.e. if other performance optimizations are not enough). But you should never call it just because you believe it might help(without specific benchmarks), because chances are it will not.
Base on @increddibelly answer, I applied to my query as below.
I share for whom concerned.
My table structure FamilyData(Id, nodeTime, totalEnergy)
select
sum(totalEnergy) as TotalEnergy,
DATEPART ( week, nodeTime ) as weeknr
from FamilyData
group by DATEPART (week, nodeTime)
Not all programs do the same thing or run on the same hardware.
This is usually the answer why various language features exist. Arrays are a core computer science concept. Replacing arrays with lists/matrices/vectors/whatever advanced data structure would severely impact performance, and be downright impracticable in a number of systems. There are any number of cases where using one of these "advanced" data collection objects should be used because of the program in question.
In business programming (which most of us do), we can target hardware that is relatively powerful. Using a List in C# or Vector in Java is the right choice to make in these situations because these structures allow the developer to accomplish the goals faster, which in turn allows this type of software to be more featured.
When writing embedded software or an operating system an array may often be the better choice. While an array offers less functionality, it takes up less RAM, and the compiler can optimize code more efficiently for look-ups into arrays.
I am sure I am leaving out a number of the benefits for these cases, but I hope you get the point.
You can also enable multiple GPU cores, like so:
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0,2,3,4"
Your JDK version: Java 8
Your JRE version: Java 9
Here your JRE version is different than the JDK version that's the case. Here you can compile all the java classes using JDK version 1.8. If you want to compile only one java class just change the *.java
into <yourclassname>.java
javac -source 1.8 -target 1.8 *.java
source: The version that your source code requires to compile.
target: The oldest JRE version you want to support.
Here's a concise universal solution for base64 encoding:
const nodeBtoa = (b) => Buffer.from(b).toString('base64');
export const base64encode = typeof btoa !== 'undefined' ? btoa : nodeBtoa;
Use the not
function instead:
var lastOpenSite = $(this).siblings().not('.closedTab');
hasClass
only tests whether an element has a class, not
will remove elements from the selected set matching the provided selector.
If this is a long calculation then I would go background worker. It has progress support. It also has support for cancel.
http://msdn.microsoft.com/en-us/library/cc221403(v=VS.95).aspx
Here I have a TextBox bound to contents.
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Debug.Write("backgroundWorker_RunWorkerCompleted");
if (e.Cancelled)
{
contents = "Cancelled get contents.";
NotifyPropertyChanged("Contents");
}
else if (e.Error != null)
{
contents = "An Error Occured in get contents";
NotifyPropertyChanged("Contents");
}
else
{
contents = (string)e.Result;
if (contentTabSelectd) NotifyPropertyChanged("Contents");
}
}
This is an answer based on jluckyiv's, but I think it is better and simpler to change Javascript as follows.
browser.loadUrl("javascript:HTMLOUT.processHTML(document.documentElement.outerHTML);");
$destroy
can refer to 2 things: method and event
.directive("colorTag", function(){
return {
restrict: "A",
scope: {
value: "=colorTag"
},
link: function (scope, element, attrs) {
var colors = new App.Colors();
element.css("background-color", stringToColor(scope.value));
element.css("color", contrastColor(scope.value));
// Destroy scope, because it's no longer needed.
scope.$destroy();
}
};
})
See @SunnyShah's answer.
Note this was done on Excel for Mac 2011 but should be same for Windows
Macro:
Sub numberformats()
Dim rng As Range
Set rng = Range("A24:A35")
For Each c In rng
Debug.Print c.NumberFormat
Next c
End Sub
Result:
General General
Number 0
Currency $#,##0.00;[Red]$#,##0.00
Accounting _($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)
Date m/d/yy
Time [$-F400]h:mm:ss am/pm
Percentage 0.00%
Fraction # ?/?
Scientific 0.00E+00
Text @
Special ;;
Custom #,##0_);[Red](#,##0)
(I just picked a random entry for custom)
Use max-width
property of CSS, like this :
img{
max-width:100%;
}
Using the usual grouper recipe, you could do:
Python 2:
d = dict(itertools.izip_longest(*[iter(l)] * 2, fillvalue=""))
Python 3:
d = dict(itertools.zip_longest(*[iter(l)] * 2, fillvalue=""))
Follow this completed solution step by step. it's works for me in VS 2017.
Open Command prompt in administrator mode
Open File explorer and got to .NET Framework folder
Eg:C:\Windows\Microsoft.NET\Framework\v4.0.30319
v4.0.30319 this is my .NET folder. you want to select your relevant folder.
in CMD - Go to .NET folder path
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
Execute below command in CMD
aspnet_regiis.exe -i
You can see this message finally - Finished installing ASP.NET (4.0.30319.0)
iisreset
You can see this message finally - Internet services successfully restarted
Open IIS in your computer (if not config Follow this)
Go to Site and right click
Add WebSite
Fill - Site name and select physical path
Then type port number (you can find port number in .csproj file and port number must equal with (IISUrl)
EG : <IISUrl>http://localhost:15724/</IISUrl> my port is 15724
Note : you cannot create port 80 number. because it used default IIS page
Open visual studio with administrator permission
Then right click and reload your project
Your Problem may be solved.
If you are using Linux I suggest you to use the tee
command. The implementation goes like this:
python python_file.py | tee any_file_name.txt
If you don't want to change anything in the code, I think this might be the best possible solution. You can also implement logger but you need do some changes in the code.
git diff --name-only --diff-filter=U | xargs git checkout --theirs
Seems to do the job. Note that you have to be cd'ed to the root directory of the git repo to achieve this.
You can make it by one line:
mymap := map[string]interface{}{"foo": map[string]interface{}{"first": 1}, "boo": map[string]interface{}{"second": 2}}
for k, v := range mymap {
fmt.Println("k:", k, "v:", v)
}
Output is:
k: foo v: map[first:1]
k: boo v: map[second:2]
returns true if subject is between low and high (inclusive)
$between = function( $low, $high, $subject ) {
if( $subject < $low ) return false;
if( $subject > $high ) return false;
return true;
};
if( $between( 0, 100, $givenNumber )) {
// do whatever...
}
looks cleaner to me
Initialize again select2
by new id or class like below
when the page load
$(".mynames").select2();
call again when came by ajax after success ajax function
$(".names").select2();
Add text-align: center;
to the parent tag of <canvas>
. That's it.
Example:
<div style="text-align: center">
<canvas width="300" height="300">
<!--your canvas code -->
</canvas>
</div>
This cannot be emphasized enough:
Keys only make sense in the context of the surrounding array.
"For example, if you extract a ListItem component, you should keep the key on the <ListItem /> elements in the array rather than on the <li> element in the ListItem itself." -- https://reactjs.org/docs/lists-and-keys.html#extracting-components-with-keys
Potentially for a different question, but I'm providing my version of @Alvero's answer (using unidecode). I want to do a "regular" strip on my strings, i.e. the beginning and end of my string for whitespace characters, and then replace only other whitespace characters with a "regular" space, i.e.
"Ceñía?mañana????"
to
"Ceñía mañana"
,
def safely_stripped(s: str):
return ' '.join(
stripped for stripped in
(bit.strip() for bit in
''.join((c if unidecode(c) else ' ') for c in s).strip().split())
if stripped)
We first replace all non-unicode spaces with a regular space (and join it back again),
''.join((c if unidecode(c) else ' ') for c in s)
And then we split that again, with python's normal split, and strip each "bit",
(bit.strip() for bit in s.split())
And lastly join those back again, but only if the string passes an if
test,
' '.join(stripped for stripped in s if stripped)
And with that, safely_stripped('????Ceñía?mañana????')
correctly returns 'Ceñía mañana'
.
In jQuery 1.2 and newer you no longer have to position the element absolutely; you can use normal relative positioning and use += or -= to add to or subtract from properties, e.g.
$("#startAnimation").click(function(){
$(".toBeAnimated").animate({
marginLeft: "+=250px",
}, 1000 );
});
And to echo the guy who answered first's advice: Javascript is not performant. Don't overuse animations, or expect things than run nice and fast on your high performance PC on Chrome to look good on a bog-standard PC running IE. Test it, and make sure it degrades well!
1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,
2) AbstractTableModel should be useful, where is in the JTable
required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel
,
3) consider using DefaultTableModel
, (if you are not sure about how to works) instead of AbstractTableModel
,
could be generated from simple code:
import javax.swing.*;
import javax.swing.table.*;
public class TableCheckBox extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
public TableCheckBox() {
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50), false},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
{"Sell", "Apple", new Integer(3000), new Double(7.35), true},
{"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
/*@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}*/
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Double.class;
default:
return Boolean.class;
}
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TableCheckBox frame = new TableCheckBox();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
});
}
}
You can also convert by creating a dictionary of elements and then directly converting to a data frame:
import xml.etree.ElementTree as ET
import pandas as pd
# Contents of test.xml
# <?xml version="1.0" encoding="utf-8"?> <tags> <row Id="1" TagName="bayesian" Count="4699" ExcerptPostId="20258" WikiPostId="20257" /> <row Id="2" TagName="prior" Count="598" ExcerptPostId="62158" WikiPostId="62157" /> <row Id="3" TagName="elicitation" Count="10" /> <row Id="5" TagName="open-source" Count="16" /> </tags>
root = ET.parse('test.xml').getroot()
tags = {"tags":[]}
for elem in root:
tag = {}
tag["Id"] = elem.attrib['Id']
tag["TagName"] = elem.attrib['TagName']
tag["Count"] = elem.attrib['Count']
tags["tags"]. append(tag)
df_users = pd.DataFrame(tags["tags"])
df_users.head()
In my case, I had to look for
C++ Standard Library
and make sure that the libc++
was the one selected.
A simple function you can pass around. Uses the modulo operator %
:
var is_even = function(x) {
return !(x % 2);
}
is_even(3)
false
is_even(6)
true
First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:
raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it
freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level
Then you need to create a data frame out of it, melt it and plot it:
Names=c("Food","Music","People") # create list of names
data=data.frame(cbind(freq),Names) # combine them into a data frame
data=data[,c(5,3,1,2,4)] # sort columns
# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')
# plot everything
ggplot(data.m, aes(Names, value)) +
geom_bar(aes(fill = variable), position = "dodge", stat="identity")
Is this what you're after?
To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:
> head(df)
ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1 1 A 1980 450 338 154 36 13 9
2 2 A 2000 288 407 212 54 16 23
3 3 A 2020 196 434 246 68 19 36
4 4 B 1980 111 326 441 90 21 11
5 5 B 2000 63 298 443 133 42 21
6 6 B 2020 36 257 462 162 55 30
Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape
and plotted.
For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw))
to get this:
> data
Names Very.Bad Bad Good Very.Good
1 Food 7 6 5 2
2 Music 5 5 7 3
3 People 6 3 7 4
Just imagine you have Very.Bad
, Bad
, Good
and so on instead of X1PCE
, X2PCE
, X3PCE
. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw))
.
Unfortunately, the above solution did not work for Jython Fiji plugin. I had to use getProperty to construct the relative path dynamically.
Here's what worked for me:
import java.lang.System.getProperty;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
frame = JFrame("Test")
icon = ImageIcon(getProperty('fiji.dir') + '/path/relative2Fiji/icon.png')
frame.setIconImage(icon.getImage());
frame.setVisible(True)
In addition, since c#6 you can also use a static using statement for System.Environment.
So instead of Environment.NewLine, you can just write NewLine.
Concise and much easier on the eye, particularly when there are multiple instances ...
using static System.Environment;
FirmNames = "";
foreach (var item in FirmNameList)
{
if (FirmNames != "")
{
FirmNames += ", " + NewLine;
}
FirmNames += item;
}
If you are doing it in eclipse, there are a few quick notes that if you are hovering your mouse over a class in your script, it will show a focus dialogue that says hit f2 for focus.
for computer apps, use ImageIcon. and for the path say,
ImageIcon thisImage = new ImageIcon("images/youpic.png");
specify the folder( images) then seperate with / and add the name of the pic file.
I hope this is helpful. If someone else posted it, I didn't read through. So...yea.. thought reinforcement.
Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.
If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll
(assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.
If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).
Use this command before to run composer update/install:
git config --global http.sslverify false
You must catch the exception before it escapes the lambda:
s = s.filter(a -> {
try {
return a.isActive();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
Consider the fact that the lambda isn't evaluated at the place you write it, but at some completely unrelated place, within a JDK class. So that would be the point where that checked exception would be thrown, and at that place it isn't declared.
You can deal with it by using a wrapper of your lambda that translates checked exceptions to unchecked ones:
public static <T> T uncheckCall(Callable<T> callable) {
try {
return callable.call();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Your example would be written as
return s.filter(a -> uncheckCall(a::isActive))
.map(Account::getNumber)
.collect(toSet());
In my projects I deal with this issue without wrapping; instead I use a method which effectively defuses compiler's checking of exceptions. Needless to say, this should be handled with care and everybody on the project must be aware that a checked exception may appear where it is not declared. This is the plumbing code:
public static <T> T uncheckCall(Callable<T> callable) {
try {
return callable.call();
} catch (Exception e) {
return sneakyThrow(e);
}
}
public static void uncheckRun(RunnableExc r) {
try {
r.run();
} catch (Exception e) {
sneakyThrow(e);
}
}
public interface RunnableExc {
void run() throws Exception;
}
@SuppressWarnings("unchecked")
private static <T extends Throwable> void sneakyThrow(Throwable t) throws T {
throw (T) t;
}
and you can expect to get an IOException
thrown in your face, even though collect
does not declare it. In most, but not all real-life cases you would want to just rethrow the exception, anyway, and handle it as a generic failure. In all those cases, nothing is lost in clarity or correctness. Just beware of those other cases, where you would actually want to react to the exception on the spot. The developer will not be made aware by the compiler that there is an IOException
to catch there and the compiler will in fact complain if you try to catch it because we have fooled it into believing that no such exception can be thrown.
If you are using Java 8, use the code below.
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
String basicAuth = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
httpConn.setRequestProperty ("Authorization", "Basic "+basicAuth);
This depends if you're using linux/unix:
>>> start = "\033[1m"
>>> end = "\033[0;0m"
>>> print "The" + start + "text" + end + " is bold."
The text is bold.
The word text
should be bold.
SQL Statement:
SELECT * FROM employee WHERE employeeName LIKE 'A%';
Result:
Number of Records: 4
employeeID employeeName employeeName Address City PostalCode Country
1 Alam Wipro Delhi Delhi 11005 India
2 Aditya Wipro Delhi Delhi 11005 India
3 Alok HCL Delhi Delhi 11005 India
4 Ashok IBM Delhi Delhi 11005 India
Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.
This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".
Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
strXls, True, "temp!"
notice, that code is:
std::abs((x - y)/x) <= epsilon
you are requiring that the "relative error" on the var is <= epsilon, not that the absolute difference is
It depends on what you mean by stop. If it's in a function that can return void then:
if(a && b) {
// do something
}else{
// "stop"
return;
}
You can use a heredoc. e.g. from a prompt:
$ sqlplus -s username/password@oracle_instance <<EOF
set feed off
set pages 0
select count(*) from table;
exit
EOF
so sqlplus
will consume everything up to the EOF
marker as stdin.
Another way to do it would be to inspect the url bar in chrome to find the id of the element, have your WebDriver click that element, and then send the keys you use to copy and paste using the keys common function from selenium, and then printing it out or storing it as a variable, etc.
from command line
python -c help('modules')
can be used to view all modules, and for specific modules
python -c help('os')
For Linux below will work
python -c "help('os')"
Try trimming the string to make sure there is no extra white space:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);
Also use c.moveToFirst()
like @thinksteep mentioned.
This is a complete code for select statements.
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
do {
// Passing values
String column1 = c.getString(0);
String column2 = c.getString(1);
String column3 = c.getString(2);
// Do something Here with values
} while(c.moveToNext());
}
c.close();
db.close();
You're walking on uncharted territory here. Here is the Go example for calling C code, perhaps you can do something like that after reading up on C++ name mangling and calling conventions, and lots of trial and error.
If you still feel like trying it, good luck.
no one says that you also have to have mod_headers enabled, so if still not working, try this:
(following tips works on Ubuntu, don't know about other distributions)
you can check list of loaded modules with
apache2ctl -M
to enable mod_headers you can use
a2enmod headers
of course after any changes in Apache you have to restart it:
/etc/init.d/apache2 restart
Then you can use
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
And if mod_headers is not active, this line will do nothing at all. You can try skip if clause and just add Header set Access-Control-Allow-Origin "*"
in your config, then it should throw error during start if mod_headers is not active.
There is now a HDF5 based clone of pickle
called hickle
!
https://github.com/telegraphic/hickle
import hickle as hkl
data = { 'name' : 'test', 'data_arr' : [1, 2, 3, 4] }
# Dump data to file
hkl.dump( data, 'new_data_file.hkl' )
# Load data from file
data2 = hkl.load( 'new_data_file.hkl' )
print( data == data2 )
EDIT:
There also is the possibility to "pickle" directly into a compressed archive by doing:
import pickle, gzip, lzma, bz2
pickle.dump( data, gzip.open( 'data.pkl.gz', 'wb' ) )
pickle.dump( data, lzma.open( 'data.pkl.lzma', 'wb' ) )
pickle.dump( data, bz2.open( 'data.pkl.bz2', 'wb' ) )
Appendix
import numpy as np
import matplotlib.pyplot as plt
import pickle, os, time
import gzip, lzma, bz2, h5py
compressions = [ 'pickle', 'h5py', 'gzip', 'lzma', 'bz2' ]
labels = [ 'pickle', 'h5py', 'pickle+gzip', 'pickle+lzma', 'pickle+bz2' ]
size = 1000
data = {}
# Random data
data['random'] = np.random.random((size, size))
# Not that random data
data['semi-random'] = np.zeros((size, size))
for i in range(size):
for j in range(size):
data['semi-random'][i,j] = np.sum(data['random'][i,:]) + np.sum(data['random'][:,j])
# Not random data
data['not-random'] = np.arange( size*size, dtype=np.float64 ).reshape( (size, size) )
sizes = {}
for key in data:
sizes[key] = {}
for compression in compressions:
if compression == 'pickle':
time_start = time.time()
pickle.dump( data[key], open( 'data.pkl', 'wb' ) )
time_tot = time.time() - time_start
sizes[key]['pickle'] = ( os.path.getsize( 'data.pkl' ) * 10**(-6), time_tot )
os.remove( 'data.pkl' )
elif compression == 'h5py':
time_start = time.time()
with h5py.File( 'data.pkl.{}'.format(compression), 'w' ) as h5f:
h5f.create_dataset('data', data=data[key])
time_tot = time.time() - time_start
sizes[key][compression] = ( os.path.getsize( 'data.pkl.{}'.format(compression) ) * 10**(-6), time_tot)
os.remove( 'data.pkl.{}'.format(compression) )
else:
time_start = time.time()
pickle.dump( data[key], eval(compression).open( 'data.pkl.{}'.format(compression), 'wb' ) )
time_tot = time.time() - time_start
sizes[key][ labels[ compressions.index(compression) ] ] = ( os.path.getsize( 'data.pkl.{}'.format(compression) ) * 10**(-6), time_tot )
os.remove( 'data.pkl.{}'.format(compression) )
f, ax_size = plt.subplots()
ax_time = ax_size.twinx()
x_ticks = labels
x = np.arange( len(x_ticks) )
y_size = {}
y_time = {}
for key in data:
y_size[key] = [ sizes[key][ x_ticks[i] ][0] for i in x ]
y_time[key] = [ sizes[key][ x_ticks[i] ][1] for i in x ]
width = .2
viridis = plt.cm.viridis
p1 = ax_size.bar( x-width, y_size['random'] , width, color = viridis(0) )
p2 = ax_size.bar( x , y_size['semi-random'] , width, color = viridis(.45))
p3 = ax_size.bar( x+width, y_size['not-random'] , width, color = viridis(.9) )
p4 = ax_time.bar( x-width, y_time['random'] , .02, color = 'red')
ax_time.bar( x , y_time['semi-random'] , .02, color = 'red')
ax_time.bar( x+width, y_time['not-random'] , .02, color = 'red')
ax_size.legend( (p1, p2, p3, p4), ('random', 'semi-random', 'not-random', 'saving time'), loc='upper center',bbox_to_anchor=(.5, -.1), ncol=4 )
ax_size.set_xticks( x )
ax_size.set_xticklabels( x_ticks )
f.suptitle( 'Pickle Compression Comparison' )
ax_size.set_ylabel( 'Size [MB]' )
ax_time.set_ylabel( 'Time [s]' )
f.savefig( 'sizes.pdf', bbox_inches='tight' )
-(IBAction)Method
{
UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[panRecognizer setMinimumNumberOfTouches:1];
[panRecognizer setMaximumNumberOfTouches:1];
[ViewMain addGestureRecognizer:panRecognizer];
[panRecognizer release];
}
- (Void)handlePan:(UIPanGestureRecognizer *)recognizer
{
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
if (recognizer.state == UIGestureRecognizerStateEnded) {
CGPoint velocity = [recognizer velocityInView:self.view];
CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));
CGFloat slideMult = magnitude / 200;
NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);
float slideFactor = 0.1 * slideMult; // Increase for more of a slide
CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor),
recognizer.view.center.y + (velocity.y * slideFactor));
finalPoint.x = MIN(MAX(finalPoint.x, 0), self.view.bounds.size.width);
finalPoint.y = MIN(MAX(finalPoint.y, 0), self.view.bounds.size.height);
[UIView animateWithDuration:slideFactor*2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
recognizer.view.center = finalPoint;
} completion:nil];
}
}
This is how I handle iPhone (and similar) devices [not iPad]:
In my CSS file:
@media only screen and (max-width: 480px), only screen and (max-device-width: 480px) {
/* CSS overrides for mobile here */
}
In the head of my HTML document:
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
You can use the directive v-html to show it. like this:
<td v-html="desc"></td>
In Window in new version you can export like this
Or Select range and Format cells > Custom \"@\"
Below Bash Script Deletes all the tags located in registry except the latest.
for D in /registry-data/docker/registry/v2/repositories/*; do
if [ -d "${D}" ]; then
if [ -z "$(ls -A ${D}/_manifests/tags/)" ]; then
echo ''
else
for R in $(ls -t ${D}/_manifests/tags/ | tail -n +2); do
digest=$(curl -k -I -s -H -X GET http://xx.xx.xx.xx:5000/v2/$(basename ${D})/manifests/${R} -H 'accept: application/vnd.docker.distribution.manifest.v2+json' | grep Docker-Content-Digest | awk '{print $2}' )
url="http://xx.xx.xx.xx:5000/v2/$(basename ${D})/manifests/$digest"
url=${url%$'\r'}
curl -X DELETE -k -I -s $url -H 'accept: application/vnd.docker.distribution.manifest.v2+json'
done
fi
fi
done
After this Run
docker exec $(docker ps | grep registry | awk '{print $1}') /bin/registry garbage-collect /etc/docker/registry/config.yml
Changing the image file to drawable-nodpi
folder from drawable
folder worked for me.
If the machine that you want to check has the .NET SDK installed, you can use a SDK command prompt and run the program CLRVer.exe
.
Use an array, not a string, as given as guidance in BashFAQ #50.
Using a string is extremely bad security practice: Consider the case where password
(or a where clause in the query, or any other component) is user-provided; you don't want to eval
a password containing $(rm -rf .)
!
cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig" )
"${cmd[@]}"
cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig" )
printf 'Proposing to run: '
printf '%q ' "${cmd[@]}"
printf '\n'
cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig" )
printf -v cmd_str '%q ' "${cmd[@]}"
ssh other_host 'bash -s' <<<"$cmd_str"
cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig" )
printf -v cmd_str '%q ' "${cmd[@]}"
ssh other_host "bash -c $cmd_str"
Maybe you need "sys." before:
select * from sys.registry$history;