As of PowerShell 5.1 there cmdlet New-LocalUser
which could create local user account.
Example of usage:
Create a user account
New-LocalUser -Name "User02" -Description "Description of this account." -NoPassword
or Create a user account that has a password
$Password = Read-Host -AsSecureString
New-LocalUser "User03" -Password $Password -FullName "Third User" -Description "Description of this account."
or Create a user account that is connected to a Microsoft account
New-LocalUser -Name "MicrosoftAccount\usr [email protected]" -Description "Description of this account."
You could try this:
SELECT * INTO foo FROM foo_bk
Perhps this is what you are looking for.
var pos = 0;
window.onload = function start() {
setTimeout(slide, 3000);
}
function slide() {
pos -= 600;
if (pos === -2400)
pos = 0;
document.getElementById('container').style.marginLeft= pos + "px";
setTimeout(slide, 3000);
}
Another option, not necesarily more elegant, but does not require to refer to a specific column:
mtcars %>%
group_by(cyl, gear) %>%
do(data.frame(nrow=nrow(.)))
Content insets solve the problem of having content that goes underneath other parts of the User Interface and yet still remains reachable using scroll bars. In other words, the purpose of the Content Inset is to make the interaction area smaller than its actual area.
Consider the case where we have three logical areas of the screen:
TOP BUTTONS
TEXT
BOTTOM TAB BAR
and we want the TEXT to never appear transparently underneath the TOP BUTTONS, but we want the Text to appear underneath the BOTTOM TAB BAR and yet still allow scrolling so we could update the text sitting transparently under the BOTTOM TAB BAR.
Then we would set the top origin to be below the TOP BUTTONS, and the height to include the bottom of BOTTOM TAB BAR. To gain access to the Text sitting underneath the BOTTOM TAB BAR content we would set the bottom inset to be the height of the BOTTOM TAB BAR.
Without the inset, the scroller would not let you scroll up the content enough to type into it. With the inset, it is as if the content had extra "BLANK CONTENT" the size of the content inset. Blank text has been "inset" into the real "content" -- that's how I remember the concept.
res.status(500).jsonp(dataRes);
I realize this is an old question, but here is an approach which might be slightly more elegant (and may or may not have been available before)...
using System;
using System.Windows;
using System.Windows.Forms;
// ...
/// <summary>
/// Utilities for easier integration with WinForms.
/// </summary>
public static class WinFormsCompatibility {
/// <summary>
/// Gets a handle of the given <paramref name="window"/> and wraps it into <see cref="IWin32Window"/>,
/// so it can be consumed by WinForms code, such as <see cref="FolderBrowserDialog"/>.
/// </summary>
/// <param name="window">
/// The WPF window whose handle to get.
/// </param>
/// <returns>
/// The handle of <paramref name="window"/> is returned as <see cref="IWin32Window.Handle"/>.
/// </returns>
public static IWin32Window GetIWin32Window(this Window window) {
return new Win32Window(new System.Windows.Interop.WindowInteropHelper(window).Handle);
}
/// <summary>
/// Implementation detail of <see cref="GetIWin32Window"/>.
/// </summary>
class Win32Window : IWin32Window { // NOTE: This is System.Windows.Forms.IWin32Window, not System.Windows.Interop.IWin32Window!
public Win32Window(IntPtr handle) {
Handle = handle; // C# 6 "read-only" automatic property.
}
public IntPtr Handle { get; }
}
}
Then, from your WPF window, you can simply...
public partial class MainWindow : Window {
void Button_Click(object sender, RoutedEventArgs e) {
using (var dialog = new FolderBrowserDialog()) {
if (dialog.ShowDialog(this.GetIWin32Window()) == System.Windows.Forms.DialogResult.OK) {
// Use dialog.SelectedPath.
}
}
}
}
Actually, does it matter?
I'm not sure if it matters in this case, but generally, you should tell Windows what is your window hierarchy, so if a parent window is clicked while child window is modal, Windows can provide a visual (and possibly audible) clue to the user.
Also, it ensures the "right" window is on top when there are multiple modal windows (not that I'm advocating such UI design). I've seen UIs designed by a certain multi-billion dollar corporation (which shell remain unnamed), that hanged simply because one modal dialog got "stuck" underneath another, and user had no clue it was even there, let alone how to close it.
I had mysterious SIGTERM shutdowns in our L.A.M.P. server, and it turned out to be an error in a custom PHP module, which was caused by mismatched versions. It was found by looking in the apache access/error logs at the time of malfunction. Don't forget to turn error logging on.
If you're having issues compiling the binary extension, or on a platform where you cant, you can try using the pure python PyMySQL
bindings.
Simply pip install pymysql
and switch your SQLAlchemy URI to start like this:
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://.....'
There are some other drivers you could also try.
As it appears, Graphviz2.37 is known to have problems with the PATH variable on windows. I uninstalled it, removed the environment variables associated with it and instead downloaded and installed the newer beta version 2.39 and it now works like a charm.
In a nutshell:
// Instantiate the Shell object and invoke its execute method.
var oShell = new ActiveXObject("Shell.Application");
var commandtoRun = "C:\\Winnt\\Notepad.exe";
if (inputparms != "") {
var commandParms = document.Form1.filename.value;
}
// Invoke the execute method.
oShell.ShellExecute(commandtoRun, commandParms, "", "open", "1");
I saw this error when a colleague was trying to connect to a database that was protected behind a VPN. The user had unknownling switched to a wireless network that did not have VPN access. One way to test this scenario is to see if you can establish a connection in another means, such as SSMS, and see if that fails as well.
I suppose https://get-ytt.io/ would be an acceptable solution to your problem
Handle added.
Added Host header.
Added linux / windows support, tested (XP,WIN7).
WARNING: ERROR : "segmentation fault" if no host,path or port as argument.
#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#ifdef __linux__
#include <sys/socket.h> /* socket, connect */
#include <netdb.h> /* struct hostent, gethostbyname */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#elif _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
#else
#endif
void error(const char *msg) { perror(msg); exit(0); }
int main(int argc,char *argv[])
{
int i;
struct hostent *server;
struct sockaddr_in serv_addr;
int bytes, sent, received, total, message_size;
char *message, response[4096];
int portno = atoi(argv[2])>0?atoi(argv[2]):80;
char *host = strlen(argv[1])>0?argv[1]:"localhost";
char *path = strlen(argv[4])>0?argv[4]:"/";
if (argc < 5) { puts("Parameters: <host> <port> <method> <path> [<data> [<headers>]]"); exit(0); }
/* How big is the message? */
message_size=0;
if(!strcmp(argv[3],"GET"))
{
printf("Process 1\n");
message_size+=strlen("%s %s%s%s HTTP/1.0\r\nHost: %s\r\n"); /* method */
message_size+=strlen(argv[3]); /* path */
message_size+=strlen(path); /* headers */
if(argc>5)
message_size+=strlen(argv[5]); /* query string */
for(i=6;i<argc;i++) /* headers */
message_size+=strlen(argv[i])+strlen("\r\n");
message_size+=strlen("\r\n"); /* blank line */
}
else
{
printf("Process 2\n");
message_size+=strlen("%s %s HTTP/1.0\r\nHost: %s\r\n");
message_size+=strlen(argv[3]); /* method */
message_size+=strlen(path); /* path */
for(i=6;i<argc;i++) /* headers */
message_size+=strlen(argv[i])+strlen("\r\n");
if(argc>5)
message_size+=strlen("Content-Length: %d\r\n")+10; /* content length */
message_size+=strlen("\r\n"); /* blank line */
if(argc>5)
message_size+=strlen(argv[5]); /* body */
}
printf("Allocating...\n");
/* allocate space for the message */
message=malloc(message_size);
/* fill in the parameters */
if(!strcmp(argv[3],"GET"))
{
if(argc>5)
sprintf(message,"%s %s%s%s HTTP/1.0\r\nHost: %s\r\n",
strlen(argv[3])>0?argv[3]:"GET", /* method */
path, /* path */
strlen(argv[5])>0?"?":"", /* ? */
strlen(argv[5])>0?argv[5]:"",host); /* query string */
else
sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
strlen(argv[3])>0?argv[3]:"GET", /* method */
path,host); /* path */
for(i=6;i<argc;i++) /* headers */
{strcat(message,argv[i]);strcat(message,"\r\n");}
strcat(message,"\r\n"); /* blank line */
}
else
{
sprintf(message,"%s %s HTTP/1.0\r\nHost: %s\r\n",
strlen(argv[3])>0?argv[3]:"POST", /* method */
path,host); /* path */
for(i=6;i<argc;i++) /* headers */
{strcat(message,argv[i]);strcat(message,"\r\n");}
if(argc>5)
sprintf(message+strlen(message),"Content-Length: %d\r\n",(int)strlen(argv[5]));
strcat(message,"\r\n"); /* blank line */
if(argc>5)
strcat(message,argv[5]); /* body */
}
printf("Processed\n");
/* What are we going to send? */
printf("Request:\n%s\n",message);
/* lookup the ip address */
total = strlen(message);
/* create the socket */
#ifdef _WIN32
WSADATA wsa;
SOCKET s;
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
return 1;
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}
printf("Socket created.\n");
server = gethostbyname(host);
serv_addr.sin_addr.s_addr = inet_addr(server->h_addr);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
//Connect to remote server
if (connect(s , (struct sockaddr *)&serv_addr , sizeof(serv_addr)) < 0)
{
printf("connect failed with error code : %d" , WSAGetLastError());
return 1;
}
puts("Connected");
if( send(s , message , strlen(message) , 0) < 0)
{
printf("Send failed with error code : %d" , WSAGetLastError());
return 1;
}
puts("Data Send\n");
//Receive a reply from the server
if((received = recv(s , response , 2000 , 0)) == SOCKET_ERROR)
{
printf("recv failed with error code : %d" , WSAGetLastError());
}
puts("Reply received\n");
//Add a NULL terminating character to make it a proper string before printing
response[received] = '\0';
puts(response);
closesocket(s);
WSACleanup();
#endif
#ifdef __linux__
int sockfd;
server = gethostbyname(host);
if (server == NULL) error("ERROR, no such host");
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) error("ERROR opening socket");
/* fill in the structure */
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
/* connect the socket */
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
/* send the request */
sent = 0;
do {
bytes = write(sockfd,message+sent,total-sent);
if (bytes < 0)
error("ERROR writing message to socket");
if (bytes == 0)
break;
sent+=bytes;
} while (sent < total);
/* receive the response */
memset(response, 0, sizeof(response));
total = sizeof(response)-1;
received = 0;
printf("Response: \n");
do {
printf("%s", response);
memset(response, 0, sizeof(response));
bytes = recv(sockfd, response, 1024, 0);
if (bytes < 0)
printf("ERROR reading response from socket");
if (bytes == 0)
break;
received+=bytes;
} while (1);
if (received == total)
error("ERROR storing complete response from socket");
/* close the socket */
close(sockfd);
#endif
free(message);
return 0;
}
To drop duplicate indices, use
df = df.loc[df.index.drop_duplicates()]
. C.f. pandas.pydata.org/pandas-docs/stable/generated/… – BallpointBen Apr 18 at 15:25
This is wrong but I can't reply directly to BallpointBen's comment due to low reputation. The reason its wrong is that df.index.drop_duplicates()
returns a list of unique indices, but when you index back into the dataframe using those the unique indices it still returns all records. I think this is likely because indexing using one of the duplicated indices will return all instances of the index.
Instead, use df.index.duplicated()
, which returns a boolean list (add the ~
to get the not-duplicated records):
df = df.loc[~df.index.duplicated()]
CSS:
.headercss {
width: 100%;
height: 320px;
background-color: #000000;
position: fixed;
}
Attribute position: fixed
will keep it stuck, while other content will be scrollable. Don't forget to set width:100%
to make it fill fully to the right.
Adding public key is the solution.For generating ssh keys: https://help.github.com/articles/generating-ssh-keys has step by step instructions.
However, the problem can persist if key is not generated in the correct way. I found this to be a useful link too: https://help.github.com/articles/error-permission-denied-publickey
In my case the problem was that I was generating the ssh-key without using sudo but when using git commands I needed to use sudo. This comment in the above link "If you generate SSH keys without sudo, then when you try to use a command like sudo git push, you won't be using the SSH key you generated." helped me.
So, the solution was that I had to use sudo with both key generating commands and git commands. Or for others, when they don't need sudo anywhere, do not use it in any of the two steps. (key generating and git commands).
for item in array: array2.append (item)
Or, in this case:
array2 += array
If you pull down the "Tools" menu and choose "Compatibility View Settings" On that dialog at the bottom is a setting "Display intranet sites in compatibility mode". If you uncheck this that should resolve the problem and IE will use the mode based on the DOCTYPE.
meda's answer is completely legit, but when I copied the code I got an error!
Somewhere in the "php://input"
there's an invalid character (maybe one of the quotes?).
When I typed the "php://input"
code manually, it worked.
Took me a while to figure out!
Yes, you can use System.Reflection.Emit
namespace for this. It is not straight forward if you have no experience with it, but it is certainly possible.
Edit: This code might be flawed, but it will give you the general idea and hopefully off to a good start towards the goal.
using System;
using System.Reflection;
using System.Reflection.Emit;
namespace TypeBuilderNamespace
{
public static class MyTypeBuilder
{
public static void CreateNewObject()
{
var myType = CompileResultType();
var myObject = Activator.CreateInstance(myType);
}
public static Type CompileResultType()
{
TypeBuilder tb = GetTypeBuilder();
ConstructorBuilder constructor = tb.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
// NOTE: assuming your list contains Field objects with fields FieldName(string) and FieldType(Type)
foreach (var field in yourListOfFields)
CreateProperty(tb, field.FieldName, field.FieldType);
Type objectType = tb.CreateType();
return objectType;
}
private static TypeBuilder GetTypeBuilder()
{
var typeSignature = "MyDynamicType";
var an = new AssemblyName(typeSignature);
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
TypeBuilder tb = moduleBuilder.DefineType(typeSignature,
TypeAttributes.Public |
TypeAttributes.Class |
TypeAttributes.AutoClass |
TypeAttributes.AnsiClass |
TypeAttributes.BeforeFieldInit |
TypeAttributes.AutoLayout,
null);
return tb;
}
private static void CreateProperty(TypeBuilder tb, string propertyName, Type propertyType)
{
FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);
PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
MethodBuilder getPropMthdBldr = tb.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
ILGenerator getIl = getPropMthdBldr.GetILGenerator();
getIl.Emit(OpCodes.Ldarg_0);
getIl.Emit(OpCodes.Ldfld, fieldBuilder);
getIl.Emit(OpCodes.Ret);
MethodBuilder setPropMthdBldr =
tb.DefineMethod("set_" + propertyName,
MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig,
null, new[] { propertyType });
ILGenerator setIl = setPropMthdBldr.GetILGenerator();
Label modifyProperty = setIl.DefineLabel();
Label exitSet = setIl.DefineLabel();
setIl.MarkLabel(modifyProperty);
setIl.Emit(OpCodes.Ldarg_0);
setIl.Emit(OpCodes.Ldarg_1);
setIl.Emit(OpCodes.Stfld, fieldBuilder);
setIl.Emit(OpCodes.Nop);
setIl.MarkLabel(exitSet);
setIl.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getPropMthdBldr);
propertyBuilder.SetSetMethod(setPropMthdBldr);
}
}
}
If you're inserting text from a database or such (which one usually do), convert all "<br />
"'s to &vbCrLf. Works great for me :)
>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'
In pre-2.5 Python, you can replace datetime.strptime
with time.strptime
, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))
public class LocalUtils {
private static final String LANGUAGE_CODE_ENGLISH = "en";
// returns application language eg: en || fa ...
public static String getAppLanguage() {
return Locale.getDefault().getLanguage();
}
// returns device language eg: en || fa ...
public static String getDeviceLanguage() {
return ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration()).get(0).getLanguage();
}
public static boolean isDeviceEnglish() {
return getDeviceLanguage().equals(new Locale(LANGUAGE_CODE_ENGLISH).getLanguage());
}
public static boolean isAppEnglish() {
return getAppLanguage().equals(new Locale(LANGUAGE_CODE_ENGLISH).getLanguage());
}
}
Log.i("AppLanguage: ", LocalUtils.getAppLanguage());
Log.i("DeviceLanguage: ", LocalUtils.getDeviceLanguage());
Log.i("isDeviceEnglish: ", String.valueOf(LocalUtils.isDeviceEnglish()));
Log.i("isAppEnglish: ", String.valueOf(LocalUtils.isAppEnglish()));
CURRENT_DATE
and CURRENT_TIMESTAMP
return the current date and time in the session time zone.
SYSDATE
and SYSTIMESTAMP
return the system date and time - that is, of the system on which the database resides.
If your client session isn't in the same timezone as the server the database is on (or says it isn't anyway, via your NLS settings), mixing the SYS*
and CURRENT_*
functions will return different values. They are all correct, they just represent different things. It looks like your server is (or thinks it is) in a +4:00 timezone, while your client session is in a +4:30 timezone.
You might also see small differences in the time if the clocks aren't synchronised, which doesn't seem to be an issue here.
You simply can't.
Code inspectors are designed for debugging HTML and Javascript. They do so by showing the live DOM object of the web page. That means it reveals HTML code of everything you see on the page, even if they're generated by Javascript. Some inspectors even shows the code inside iframes.
There are some javascript tricks to disable some keyboard, mouse interaction on the page. But there always are work around to those tricks. For instance, you can use the browser top menu to enable DOM inspector without a problem.
Try theses:
They are outside the control of Javascripts.
Think about this:
Basically, browsers are god to your Javascript. And they want to grant the web developer super power with code inspectors. Even if your trick works for a while, the browsers would want to undo it in the future.
You're waging war against god and you're doomed to fail.
To put it simple, if you do not want people to get something in their browser, you should never send it to their browser in the first place.
You can do it inline, but you have to be careful with spaces in the column data. Better to use datalength()
SELECT
ColName,
DATALENGTH(ColName) -
DATALENGTH(REPLACE(Col, 'A', '')) AS NumberOfLetterA
FROM ColName;
-OR- Do the replace with 2 characters
SELECT
ColName,
-LEN(ColName)
+LEN(REPLACE(Col, 'A', '><')) AS NumberOfLetterA
FROM ColName;
The getDay()
method returns a number to indicate the day in week (0=Sun, 1=Mon, ... 6=Sat). Use getDate()
to return a number for the day in month:
var day = convertedStartDate.getDate();
If you like, you can try to add a custom format function to the prototype of the Date
object:
Date.prototype.formatMMDDYYYY = function(){
return (this.getMonth() + 1) +
"/" + this.getDate() +
"/" + this.getFullYear();
}
After doing this, you can call formatMMDDYYY()
on any instance of the Date
object. Of course, this is just a very specific example, and if you really need it, you can write a generic formatting function that would do this based on a formatting string, kinda like java's SimpleDateeFormat (http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html)
(tangent: the Date
object always confuses me... getYear()
vs getFullYear()
, getDate()
vs getDay()
, getDate()
ranges from 1..31, but getMonth()
from 0..11
It's a mess, and I always need to take a peek. http://www.w3schools.com/jsref/jsref_obj_date.asp)
No, there is no better way.
Actually you have an error in your pattern. What you want is:
DecimalFormat df = new DecimalFormat("#.00");
Note the "00"
, meaning exactly two decimal places.
If you use "#.##"
(#
means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d);
prints just "3"
, not "3.00"
.
You can try below query,
select * from players
where
us_reg_date between '2000-07-05'
and
DATE_ADD('2011-11-10',INTERVAL 1 DAY)
The method which you are using is rendering login button from the Facebook Javascript code. However, you can write your own Javascript code function to mimic the functionality. Here is how to do it -
onclick
method on anchor tag which would actually do the real job.<a href="#" onclick="fb_login();"><img src="images/fb_login_awesome.jpg" border="0" alt=""></a>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID',
oauth : true,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
function fb_login(){
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
//console.log(response); // dump complete info
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api('/me', function(response) {
user_email = response.email; //get user email
// you can store this data into your database
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'public_profile,email'
});
}
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
Please note that the above function is fully tested and works. You just need to put your facebook APP ID and it will work.
MySQL way:
SHOW TABLES LIKE 'pattern';
There's also a deprecated PHP function for listing all db tables, take a look at http://php.net/manual/en/function.mysql-list-tables.php
Checkout that link, there are plenty of useful insight on the comments over there.
Figured it out... it's a little cumbersome, but here it is.
FROM_DAYS(TO_DAYS(TIMESTAMP) -MOD(TO_DAYS(TIMESTAMP) -1, 7))
And, if your business rules say your weeks start on Mondays, change the -1
to -2
.
Edit
Years have gone by and I've finally gotten around to writing this up. http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/
[StringLength(16, ErrorMessageResourceName= "PasswordMustBeBetweenMinAndMaxCharacters", ErrorMessageResourceType = typeof(Resources.Resource), MinimumLength = 6)]
[Display(Name = "Password", ResourceType = typeof(Resources.Resource))]
public string Password { get; set; }
Save resource like this
"ThePasswordMustBeAtLeastCharactersLong" | "The password must be {1} at least {2} characters long"
You can use ymd
from lubridate
lubridate::ymd(v)
#[1] "2008-11-01"
Or anytime::anydate
anytime::anydate(v)
#[1] "2008-11-01"
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
Right now, it has not been exposed at API level yet. However you can achieve it using something similar to this
<ng-container cdkColumnDef="userId" >
<md-header-cell *cdkHeaderCellDef [ngClass]="'customWidthClass'"> ID </md-header-cell>
<md-cell *cdkCellDef="let row" [ngClass]="'customWidthClass'"> {{row.id}} </md-cell>
</ng-container>
In css, you need to add this custom class -
.customWidthClass{
flex: 0 0 75px;
}
Feel free to enter the logic to append class or custom width in here. It will apply custom width for the column.
Since md-table uses flex
, we need to give fixed width in flex manner. This simply explains -
0 = don't grow (shorthand for flex-grow)
0 = don't shrink (shorthand for flex-shrink)
75px = start at 75px (shorthand for flex-basis)
Plunkr here - https://plnkr.co/edit/v7ww6DhJ6zCaPyQhPRE8?p=preview
You can use the following as extension method
public static void RemoveByValue<T,T1>(this Dictionary<T,T1> src , T1 Value)
{
foreach (var item in src.Where(kvp => kvp.Value.Equals( Value)).ToList())
{
src.Remove(item.Key);
}
}
First off you need to download and install ODP from this site http://www.oracle.com/technetwork/topics/dotnet/index-085163.html
After installation add a reference of the assembly Oracle.DataAccess.dll.
Your are good to go after this.
using System;
using Oracle.DataAccess.Client;
class OraTest
{
OracleConnection con;
void Connect()
{
con = new OracleConnection();
con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
}
void Close()
{
con.Close();
con.Dispose();
}
static void Main()
{
OraTest ot= new OraTest();
ot.Connect();
ot.Close();
}
}
I know this is an old question, but this is still a problem I keep walking into, and yet there is still no clear solution to do this correctly when using async/await in an async void signature method.
However, I noticed that .Wait() is working properly inside the void method.
and since async void and void have the same signature, you might need to do the following.
void LoadBlahBlah()
{
blah().Wait(); //this blocks
}
Confusingly enough async/await does not block on the next code.
async void LoadBlahBlah()
{
await blah(); //this does not block
}
When you decompile your code, my guess is that async void creates an internal Task (just like async Task), but since the signature does not support to return that internal Tasks
this means that internally the async void method will still be able to "await" internally async methods. but externally unable to know when the internal Task is complete.
So my conclusion is that async void is working as intended, and if you need feedback from the internal Task, then you need to use the async Task signature instead.
hopefully my rambling makes sense to anybody also looking for answers.
Edit: I made some example code and decompiled it to see what is actually going on.
static async void Test()
{
await Task.Delay(5000);
}
static async Task TestAsync()
{
await Task.Delay(5000);
}
Turns into (edit: I know that the body code is not here but in the statemachines, but the statemachines was basically identical, so I didn't bother adding them)
private static void Test()
{
<Test>d__1 stateMachine = new <Test>d__1();
stateMachine.<>t__builder = AsyncVoidMethodBuilder.Create();
stateMachine.<>1__state = -1;
AsyncVoidMethodBuilder <>t__builder = stateMachine.<>t__builder;
<>t__builder.Start(ref stateMachine);
}
private static Task TestAsync()
{
<TestAsync>d__2 stateMachine = new <TestAsync>d__2();
stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
stateMachine.<>1__state = -1;
AsyncTaskMethodBuilder <>t__builder = stateMachine.<>t__builder;
<>t__builder.Start(ref stateMachine);
return stateMachine.<>t__builder.Task;
}
neither AsyncVoidMethodBuilder or AsyncTaskMethodBuilder actually have any code in the Start method that would hint of them to block, and would always run asynchronously after they are started.
meaning without the returning Task, there would be no way to check if it is complete.
as expected, it only starts the Task running async, and then it continues in the code. and the async Task, first it starts the Task, and then it returns it.
so I guess my answer would be to never use async void, if you need to know when the task is done, that is what async Task is for.
Using the same approach of Philip Wallace, we can do like this:
public Control GetControlByName(Control ParentCntl, string NameToSearch)
{
if (ParentCntl.Name == NameToSearch)
return ParentCntl;
foreach (Control ChildCntl in ParentCntl.Controls)
{
Control ResultCntl = GetControlByName(ChildCntl, NameToSearch);
if (ResultCntl != null)
return ResultCntl;
}
return null;
}
Example:
public void doSomething()
{
TextBox myTextBox = (TextBox) this.GetControlByName(this, "mytextboxname");
myTextBox.Text = "Hello!";
}
I hope it help! :)
It is certainly a good thing to complain the more stringent the compiler is the better, as far as it allows you to do what you need. Usually the small price to pay is to comment the code out, the gain is that when you compile your code works. A general example is Haskell about which people screams until they realize that their test/debugging is main test only and short one. I personally in Java do almost no debugging while being ( in fact on purpose) not attentive.
I have to manually sign the app. Created new certificate and new profile. Set code signing to Manual. Only then i was able to upload. Moreover select Manual sign in from organizer while uploading build.
How I did this in Swift (including the string formatting to show it as "01:23"):
let totalSeconds: Double = someTimeInterval
let minutes = Int(floor(totalSeconds / 60))
let seconds = Int(round(totalSeconds % 60))
let timeString = String(format: "%02d:%02d", minutes, seconds)
NSLog(timeString)
If you are using Postgres and you have data like '2000 - some sample text' then try substring and position combination, otherwise if in your scenario there is no delimiter, you need to write regex:
SUBSTRING(Column_name from 0 for POSITION('-' in column_name) - 1) as
number_column_name
After spending a good bit of time today trying to wrap my brain around the (significant but powerful) paradigm shift between old ways of processing web form data and how it is done with WebAPI, I thought I'd add my 2 cents to this discussion.
What I wanted to do (which is pretty common for web form processing of a POST) is to be able to grab any of the form values I want, in any order. Say like you can do if you have your data in a System.Collections.Specialized.NameValueCollection
. But turns out, in WebAPI, the data from a POST comes back at you as a stream. So you can't directly do that.
But there is a cool little class named FormDataCollection
(in System.Net.Http.Formatting) and what it will let you do is iterate through your collection once.
So I wrote a simple utility method that will run through the FormDataCollection
once and stick all the values into a NameValueCollection
. Once this is done, you can jump all around the data to your hearts content.
So in my ApiController derived class, I have a post method like this:
public void Post(FormDataCollection formData)
{
NameValueCollection valueMap = WebAPIUtils.Convert(formData);
... my code that uses the data in the NameValueCollection
}
The Convert method in my static WebAPIUtils class looks like this:
/// <summary>
/// Copy the values contained in the given FormDataCollection into
/// a NameValueCollection instance.
/// </summary>
/// <param name="formDataCollection">The FormDataCollection instance. (required, but can be empty)</param>
/// <returns>The NameValueCollection. Never returned null, but may be empty.</returns>
public static NameValueCollection Convert(FormDataCollection formDataCollection)
{
Validate.IsNotNull("formDataCollection", formDataCollection);
IEnumerator<KeyValuePair<string, string>> pairs = formDataCollection.GetEnumerator();
NameValueCollection collection = new NameValueCollection();
while (pairs.MoveNext())
{
KeyValuePair<string, string> pair = pairs.Current;
collection.Add(pair.Key, pair.Value);
}
return collection;
}
Hope this helps!
A slightly simpler syntax (in Robomongo at least) worked for me:
db.database.save({ Year : NumberInt(2015) });
Mac OS X 10.12 with Java 1.8:
$JAVA_HOME/jre/lib/security
cd $JAVA_HOME
/Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home
From there it's in:
./jre/lib/security
I have a cacerts keystore in there.
To specify this as a VM option:
-Djavax.net.ssl.trustStore=/Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home/jre/lib/security/cacerts -Djavax.net.ssl.trustStorePassword=changeit
I'm not saying this is the correct way (Why doesn't java know to look within JAVA_HOME?), but this is what I had to do to get it working.
Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate
now has second parameter values
, which is being used for new record, but not for search
$user = User::firstOrCreate([
'email' => '[email protected]'
], [
'firstName' => 'Taylor',
'lastName' => 'Otwell'
]);
There's also a really useful discussion about converting the array in place, In-place type conversion of a NumPy array. If you're concerned about copying your array (which is whatastype()
does) definitely check out the link.
Am I missing something? Somebody correct me if I'm wrong.
list.RemoveAll(s => s.Name == "Fred");
If you're developing in Flutter, there's a new experimental option as of 5/1/2018 that allows you to format code on save.
Also happened to me while trying to run the project inside of another directory.
Worked by using the root directory of the main project
Yes.
Constructors are nothing more than special methods, and can throw exceptions like any other method.
SQLAlchemy overloads the bitwise operators &
, |
and ~
so instead of the ugly and hard-to-read prefix syntax with or_()
and and_()
(like in Bastien's answer) you can use these operators:
.filter((AddressBook.lastname == 'bulger') | (AddressBook.firstname == 'whitey'))
Note that the parentheses are not optional due to the precedence of the bitwise operators.
So your whole query could look like this:
addr = session.query(AddressBook) \
.filter(AddressBook.city == "boston") \
.filter((AddressBook.lastname == 'bulger') | (AddressBook.firstname == 'whitey'))
It's actually very easy in jQuery:
$("#ddl_1").clone().attr("id",newId).appendTo("body");
Change .appendTo() of course...
I landed up on this page when searching for a solution for “Could not open input file” error. Here's my 2 cents for this error.
I faced this same error while because I was using parameters in my php file path like this:
/usr/bin/php -q /home/**/public_html/cron/job.php?id=1234
But I found out that this is not the proper way to do it. The proper way of sending parameters is like this:
/usr/bin/php -q /home/**/public_html/cron/job.php id=1234
Just replace the "?"
with a space " "
.
printf is a fair bit more complicated than that. You have to supply a format string, and then the variables to apply to the format string. If you just supply one variable, C will assume that is the format string and try to print out all the bytes it finds in it until it hits a terminating nul (0x0).
So if you just give it an integer, it will merrily march through memory at the location your integer is stored, dumping whatever garbage is there to the screen, until it happens to come across a byte containing 0.
For a Java programmer, I'd imagine this is a rather rude introduction to C's lack of type checking. Believe me, this is only the tip of the iceberg. This is why, while I applaud your desire to expand your horizons by learning C, I highly suggest you do whatever you can to avoid writing real programs in it.
(This goes for everyone else reading this too.)
To delete content without a folder you can use the following:
Remove-Item "foldertodelete\*" -Force -Recurse
Two examples with expat and libxml2. The second one is, IMHO, much easier to use since it creates a tree in memory, a data structure which is easy to work with. expat, on the other hand, does not build anything (you have to do it yourself), it just allows you to call handlers at specific events during the parsing. But expat may be faster (I didn't measure).
With expat, reading a XML file and displaying the elements indented:
/*
A simple test program to parse XML documents with expat
<http://expat.sourceforge.net/>. It just displays the element
names.
On Debian, compile with:
gcc -Wall -o expat-test -lexpat expat-test.c
Inspired from <http://www.xml.com/pub/a/1999/09/expat/index.html>
*/
#include <expat.h>
#include <stdio.h>
#include <string.h>
/* Keep track of the current level in the XML tree */
int Depth;
#define MAXCHARS 1000000
void
start(void *data, const char *el, const char **attr)
{
int i;
for (i = 0; i < Depth; i++)
printf(" ");
printf("%s", el);
for (i = 0; attr[i]; i += 2) {
printf(" %s='%s'", attr[i], attr[i + 1]);
}
printf("\n");
Depth++;
} /* End of start handler */
void
end(void *data, const char *el)
{
Depth--;
} /* End of end handler */
int
main(int argc, char **argv)
{
char *filename;
FILE *f;
size_t size;
char *xmltext;
XML_Parser parser;
if (argc != 2) {
fprintf(stderr, "Usage: %s filename\n", argv[0]);
return (1);
}
filename = argv[1];
parser = XML_ParserCreate(NULL);
if (parser == NULL) {
fprintf(stderr, "Parser not created\n");
return (1);
}
/* Tell expat to use functions start() and end() each times it encounters
* the start or end of an element. */
XML_SetElementHandler(parser, start, end);
f = fopen(filename, "r");
xmltext = malloc(MAXCHARS);
/* Slurp the XML file in the buffer xmltext */
size = fread(xmltext, sizeof(char), MAXCHARS, f);
if (XML_Parse(parser, xmltext, strlen(xmltext), XML_TRUE) ==
XML_STATUS_ERROR) {
fprintf(stderr,
"Cannot parse %s, file may be too large or not well-formed XML\n",
filename);
return (1);
}
fclose(f);
XML_ParserFree(parser);
fprintf(stdout, "Successfully parsed %i characters in file %s\n", size,
filename);
return (0);
}
With libxml2, a program which displays the name of the root element and the names of its children:
/*
Simple test with libxml2 <http://xmlsoft.org>. It displays the name
of the root element and the names of all its children (not
descendents, just children).
On Debian, compiles with:
gcc -Wall -o read-xml2 $(xml2-config --cflags) $(xml2-config --libs) \
read-xml2.c
*/
#include <stdio.h>
#include <string.h>
#include <libxml/parser.h>
int
main(int argc, char **argv)
{
xmlDoc *document;
xmlNode *root, *first_child, *node;
char *filename;
if (argc < 2) {
fprintf(stderr, "Usage: %s filename.xml\n", argv[0]);
return 1;
}
filename = argv[1];
document = xmlReadFile(filename, NULL, 0);
root = xmlDocGetRootElement(document);
fprintf(stdout, "Root is <%s> (%i)\n", root->name, root->type);
first_child = root->children;
for (node = first_child; node; node = node->next) {
fprintf(stdout, "\t Child is <%s> (%i)\n", node->name, node->type);
}
fprintf(stdout, "...\n");
return 0;
}
Note: this doen't sanitize arrays:
import { isPlainObject } from 'lodash';
export const sanitize = (obj: {}) => {
if (isPlainObject(obj)) {
const sanitizedObj = {};
for (const key in obj) {
if (obj[key]) {
sanitizedObj[key] = sanitize(obj[key]);
}
}
return sanitizedObj;
} else {
return obj;
}
};
Test:
describe('sanitize', () => {
it('should keep an object if there are no empty fields', () => {
expect(sanitize({})).toEqual({});
expect(sanitize({ foo: 'bar' })).toEqual({ foo: 'bar' });
expect(sanitize({ content: { foo: 'bar' } })).toEqual({
content: { foo: 'bar' },
});
});
it('should remove empty fields from top level', () => {
expect(sanitize({ foo: '', bar: 'baz' })).toEqual({ bar: 'baz' });
expect(sanitize({ foo: null, bar: 'baz' })).toEqual({ bar: 'baz' });
expect(sanitize({ foo: undefined, bar: 'baz' })).toEqual({ bar: 'baz' });
});
it('should remove nested empty fields', () => {
expect(sanitize({ content: { foo: '', bar: 'baz' } })).toEqual({
content: { bar: 'baz' },
});
expect(sanitize({ content: { foo: null, bar: 'baz' } })).toEqual({
content: { bar: 'baz' },
});
expect(sanitize({ content: { foo: undefined, bar: 'baz' } })).toEqual({
content: { bar: 'baz' },
});
});
});
If one is using Maven Build from the command prompt one can use the following command as well:
mvn -Dproject.build.sourceEncoding=UTF-8
Add an onChange
handler to each of your TextField
and DropDownMenu
elements. When it is called, save the new value of these inputs in the state
of your Content
component. In render, retrieve these values from state
and pass them as the value
prop. See Controlled Components.
var Content = React.createClass({
getInitialState: function() {
return {
textFieldValue: ''
};
},
_handleTextFieldChange: function(e) {
this.setState({
textFieldValue: e.target.value
});
},
render: function() {
return (
<div>
<TextField value={this.state.textFieldValue} onChange={this._handleTextFieldChange} />
</div>
)
}
});
Now all you have to do in your _handleClick
method is retrieve the values of all your inputs from this.state
and send them to the server.
You can also use the React.addons.LinkedStateMixin
to make this process easier. See Two-Way Binding Helpers. The previous code becomes:
var Content = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {
textFieldValue: ''
};
},
render: function() {
return (
<div>
<TextField valueLink={this.linkState('textFieldValue')} />
</div>
)
}
});
In this situation implode($array,','); will works, becasue you want the values only. In PHP 5.6 working for me.
If you want to implode the keys and the values in one like :
blogTags_id: 1
tag_name: google
$toImplode=array();
foreach($array as $key => $value) {
$toImplode[]= "$key: $value".'<br>';
}
$imploded=implode('',$toImplode);
Sorry, I understand wrong, becasue the title "Implode data from a multi-dimensional array". Well, my answer still answer it somehow, may help someone, so will not delete it.
try this
http://www.ehow.com/how_6613143_convert-xml-code-sql.html
for downloading the tool http://www.xml-converter.com/
You can achieve this by using a spy (use the latest version of Mockito 1.8+ though).
public abstract class MyAbstract {
public String concrete() {
return abstractMethod();
}
public abstract String abstractMethod();
}
public class MyAbstractImpl extends MyAbstract {
public String abstractMethod() {
return null;
}
}
// your test code below
MyAbstractImpl abstractImpl = spy(new MyAbstractImpl());
doReturn("Blah").when(abstractImpl).abstractMethod();
assertTrue("Blah".equals(abstractImpl.concrete()));
I will give you a better idea
for(decltype(things.size()) i = 0; i < things.size(); i++){
//...
}
decltype
is
Inspects the declared type of an entity or the type and value category of an expression.
So, It deduces type of things.size()
and i
will be a type as same as things.size()
. So,
i < things.size()
will be executed without any warning
You can use File.WriteAllBytes
Sometimes the columns will have commas within themselves, such as:
"Some item", "Another Item", "Also, One more item"
In these cases, splitting on "," will break some columns. Maybe an easier way, but I just made my own method (as a bonus, handles spaces after commas and returns an IList):
private IList<string> GetColumns(string columns)
{
IList<string> list = new List<string>();
if (!string.IsNullOrWhiteSpace(columns))
{
if (columns[0] != '\"')
{
// treat as just one item
list.Add(columns);
}
else
{
bool gettingItemName = true;
bool justChanged = false;
string itemName = string.Empty;
for (int index = 1; index < columns.Length; index++)
{
justChanged = false;
if (subIndustries[index] == '\"')
{
gettingItemName = !gettingItemName;
justChanged = true;
}
if ((gettingItemName == false) &&
(justChanged == true))
{
list.Add(itemName);
itemName = string.Empty;
justChanged = false;
}
if ((gettingItemName == true) && (justChanged == false))
{
itemName += columns[index];
}
}
}
}
return list;
}
The simplest way I found was:
mylist[:x] + mylist[x+1:]
that will produce your mylist
without the element at index x
.
mylist = [0, 1, 2, 3, 4, 5]
x = 3
mylist[:x] + mylist[x+1:]
Result produced
mylist = [0, 1, 2, 4, 5]
The getPosts()
function seems to be expecting $con
to be global, but you're not declaring it as such.
A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.
Cast abc to an integer.
(int)(Math.random()*100);
On more recent versions (win 7 onwards) you can have powershell do the job for you.
for /F %%i in ('powershell -command "& {$([System.Environment]::OSVersion.Version.Major),$([System.Environment]::OSVersion.Version.Minor) -join '.' }"') do set VER=%%i
goto %VER%
:6.1
REM specific code for windows 7
:10.0
REM specific code for windows 10
see this table for version numbers
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
System.out.println(sdf.format(date));
Use command "php artisan migrate:rollback --step=1" to rollback migration to 1 step back.
For more info check the link :- https://laravel.com/docs/master/migrations#running-migrations
An updated version of the correct answer for .NET 4.5 would be.
if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxImage.Question)
== MessageBoxResult.Yes)
{
// If yes
}
else
{
// If no
}
Additionally, if you wanted to bind the button to a command in a view model you could use the following. This is compatible with MvvmLite:
public RelayCommand ShowPopUpCommand
{
get
{
return _showPopUpCommand ??
(_showPopUpCommand = new RelayCommand(
() =>
{
// Put if statement here
}
}));
}
}
ephemeral is just another name of root volume when you launch Instance from AMI backed from Amazon EC2 instance store
So Everything will be stored on ephemeral.
if you have launched your instance from AMI backed by EBS volume then your instance does not have ephemeral.
Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.
There are available Extension methods to parse them into other primitive types.
"10".toInt()
"10".toLong()
"true".toBoolean()
"10.0".toFloat()
"10.0".toDouble()
"10".toByte()
"10".toShort()
String num = "10";
Integer.parseInt(num );
If you are trying to share a project in SVN with Eclipse for the first time, you might want to avoid certain files to be commited. In order to do so, go to Preferences->Team->Ignored Resources. In this screen you just need to add a pattern to ignore the kind of files you don't want to commit.
Yes it stops execution so this is generally preferable to HAVING COUNT(*) > 0
which often won't.
With EXISTS
if you look at the execution plan you will see that the actual number of rows coming out of table1
will not be more than 1 irrespective of number of matching records.
In some circumstances SQL Server can convert the tree for the COUNT
query to the same as the one for EXISTS
during the simplification phase (with a semi join and no aggregate operator in sight) an example of that is discussed in the comments here.
For more complicated sub trees than shown in the question you may occasionally find the COUNT
performs better than EXISTS
however. Because the semi join needs only retrieve one row from the sub tree this can encourage a plan with nested loops for that part of the tree - which may not work out optimal in practice.
I use the following format and works well.
robocopy \\SourceServer\Path \\TargetServer\Path filename.txt
to copy everything you can replace filename.txt
with *.*
and there are plenty of other switches to copy subfolders etc... see here: http://ss64.com/nt/robocopy.html
After carefully going through the thread here and checking all the solutions proposed by people, I can confidently claim this, after following the steps mentioned on Apple developer docs for creating CSR and mobile provision file, just do this!,
http://img.skitch.com/20100820-1ngm8an14c6fm3dt7g6j51d2nx.jpg
Trust me, you only have to do this. There is no need to repeat the process again and again to make sure that you doing it the right way. Just press Refresh, enter your login credentials and it's done.
having dignosed the problem I was able to use the existing system default CA file, on debian6 this is:
/etc/ssl/certs/ca-certificates.crt
as root this can be done like:
echo curl.cainfo=/etc/ssl/certs/ca-certificates.crt >> /etc/php5/mods-available/curl.ini
then re-start the web-server.
The main (very interesting) difference for me is that:
"string" & Null
-> "string"
while
"string" + Null
-> Null
But that's probably more useful in database apps like Access.
cmd.exe /c '\my-app\my-file.bat'
<router-outlet [node]="..."></router-outlet>
is just invalid. The component added by the router is added as sibling to <router-outlet>
and does not replace it.
See also https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service
@Injectable()
export class NodeService {
private node:Subject<Node> = new BehaviorSubject<Node>([]);
get node$(){
return this.node.asObservable().filter(node => !!node);
}
addNode(data:Node) {
this.node.next(data);
}
}
@Component({
selector : 'node-display',
providers: [NodeService],
template : `
<router-outlet></router-outlet>
`
})
export class NodeDisplayComponent implements OnInit {
constructor(private nodeService:NodeService) {}
node: Node;
ngOnInit(): void {
this.nodeService.getNode(path)
.subscribe(
node => {
this.nodeService.addNode(node);
},
err => {
console.log(err);
}
);
}
}
export class ChildDisplay implements OnInit{
constructor(nodeService:NodeService) {
nodeService.node$.subscribe(n => this.node = n);
}
}
If you're trying to just count how many of your cells in a range are not blank try this:
=COUNTA(range)
Example: (assume that it starts from A1 downwards):
---------
Something
---------
Something
---------
---------
Something
---------
---------
Something
---------
=COUNTA(A1:A6)
returns 4
since there are two blank cells in there.
On 32-bit machine sizeof pointer is 32 bits ( 4 bytes), while on 64 bit machine it's 8 byte. Regardless of what data type they are pointing to, they have fixed size.
I've faced same problem and came across to this thread but my problem was with upstream
. Below git command worked for me.
git checkout {remoteName}/{branch} -- {../path/file.js}
git checkout upstream/develop -- public/js/index.js
Swift 3
func getTime() -> (hour: Int, minute: Int,second: Int) {
let hour = 1
let minute = 20
let second = 55
return (hour, minute, second)
}
To use :
let(hour, min,sec) = self.getTime()
print(hour,min,sec)
If you are using this for Angular, then export a function via a named export. Such as:
function someFunc(){}
export { someFunc as someFuncName }
otherwise, Angular will complain that object is not a function.
Use Hosts Commander. It's simple and powerful. Translated description (from russian) here.
hosts add another.dev 192.168.1.1 # Remote host
hosts add test.local # 127.0.0.1 used by default
hosts set myhost.dev # new comment
hosts rem *.local
hosts enable local*
hosts disable localhost
...and many others...
Usage:
hosts - run hosts command interpreter
hosts <command> <params> - execute hosts command
Commands:
add <host> <aliases> <addr> # <comment> - add new host
set <host|mask> <addr> # <comment> - set ip and comment for host
rem <host|mask> - remove host
on <host|mask> - enable host
off <host|mask> - disable host
view [all] <mask> - display enabled and visible, or all hosts
hide <host|mask> - hide host from 'hosts view'
show <host|mask> - show host in 'hosts view'
print - display raw hosts file
format - format host rows
clean - format and remove all comments
rollback - rollback last operation
backup - backup hosts file
restore - restore hosts file from backup
recreate - empty hosts file
open - open hosts file in notepad
In the most shared hosts you can't set it.
On a VPS or dedicated server, you can set it, but everything has its price.
On shared hosts, in general you receive a Linux account, something such as /home/(your username)/, and the equivalent of /var/www/html turns to /home/(your username)/public_html/ (or something similar, such as /home/(your username)/www)
If you're accessing your account via FTP, you automatically has accessing the your */home/(your username)/ folder, just find the www or public_html and put your site in it.
If you're using absolute path in the code, bad news, you need to refactor it to use relative paths in the code, at least in a shared host.
Another trick you can use WebBrowser control, below is my full working code
Assigning Url to text box control in my case
protected void Page_Load(object sender, EventArgs e)
{
txtweburl.Text = "https://www.google.com/";
}
Below is code for generate screeen using thread
protected void btnscreenshot_click(object sender, EventArgs e)
{
// btnscreenshot.Visible = false;
allpanels.Visible = true;
Thread thread = new Thread(GenerateThumbnail);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}
private void GenerateThumbnail()
{
// btnscreenshot.Visible = false;
WebBrowser webrowse = new WebBrowser();
webrowse.ScrollBarsEnabled = false;
webrowse.AllowNavigation = true;
string url = txtweburl.Text.Trim();
webrowse.Navigate(url);
webrowse.Width = 1400;
webrowse.Height = 50000;
webrowse.DocumentCompleted += webbrowse_DocumentCompleted;
while (webrowse.ReadyState != WebBrowserReadyState.Complete)
{
System.Windows.Forms.Application.DoEvents();
}
}
In below code I am saving the pdf file after download
private void webbrowse_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// btnscreenshot.Visible = false;
string folderPath = Server.MapPath("~/ImageFiles/");
WebBrowser webrowse = sender as WebBrowser;
//Bitmap bitmap = new Bitmap(webrowse.Width, webrowse.Height);
Bitmap bitmap = new Bitmap(webrowse.Width, webrowse.Height, PixelFormat.Format16bppRgb565);
webrowse.DrawToBitmap(bitmap, webrowse.Bounds);
string Systemimagedownloadpath = System.Configuration.ConfigurationManager.AppSettings["Systemimagedownloadpath"].ToString();
string fullOutputPath = Systemimagedownloadpath + Request.QueryString["VisitedId"].ToString() + ".png";
MemoryStream stream = new MemoryStream();
bitmap.Save(fullOutputPath, System.Drawing.Imaging.ImageFormat.Jpeg);
//generating pdf code
Document pdfDoc = new Document(new iTextSharp.text.Rectangle(1100f, 20000.25f));
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(fullOutputPath);
img.ScaleAbsoluteHeight(20000);
img.ScaleAbsoluteWidth(1024);
pdfDoc.Add(img);
pdfDoc.Close();
//Download the PDF file.
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=ImageExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
}
You can also refer my oldest post for more information: Navigation to the webpage was canceled getting message in asp.net web form
I had the same problem, but non of the asweres worked for me. I am using bootstap and the following css code helped me:
label {
display: contents!important;
}
A Bin file is a pure binary file with no memory fix-ups or relocations, more than likely it has explicit instructions to be loaded at a specific memory address. Whereas....
ELF files are Executable Linkable Format which consists of a symbol look-ups and relocatable table, that is, it can be loaded at any memory address by the kernel and automatically, all symbols used, are adjusted to the offset from that memory address where it was loaded into. Usually ELF files have a number of sections, such as 'data', 'text', 'bss', to name but a few...it is within those sections where the run-time can calculate where to adjust the symbol's memory references dynamically at run-time.
If you don't know how to enable php_mbstring extension in windows, open your php.ini and remove the semicolon before the extension:
change this
;extension=php_mbstring.dll
to this
extension=php_mbstring.dll
after modification, you need to reset your php server.
What about the css opacity
attribute? 0
to 1
values.
But then you probably need to use a more explicit dom element than "font". For instance:
<html><body><span style=\"opacity: 0.5;\"><font color=\"black\" face=\"arial\" size=\"4\">THIS IS MY TEXT</font></span></body></html>
As an additional information I would of course suggest you use CSS declarations outside of your html elements, but as well try to use the font css style instead of the font html tag.
For cross browser css3 styles generator, have a look at http://css3please.com/
Just come across it and got an answer somewhere. you can use below annotation since 2.7.0
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class Point {
final private double x;
final private double y;
@ConstructorProperties({"x", "y"})
public Point(double x, double y) {
this.x = x;
this.y = y;
}
}
.Net Core Class Library is built upon the .Net Standard. .NET Standard you can make only class-library project that cannot be executed standalone and should be referenced by another .NET Core or .NET Framework executable project.If you want to implement a library that is portable to the .Net Framework, .Net Core and Xamarin, choose a .Net Standard Library
(You can make executable project (like Console application, or ASP.NET application) with .NET Framework
It is the new open-source and cross-platform framework to build applications for all operating system including Windows, Mac, and Linux.
Implementation support of .NET Standard[blue] and minimum viable platform for full support of .NET Standard (latest: [https://docs.microsoft.com/en-us/dotnet/standard/net-standard#net-implementation-support])
No package.json is necessery to change.
For me it works using:
ng serve --host=0.0.0.0 --port=5999 --disable-host-check
Host: http://localhost:5999/
1.Add arm64
to Build settings
-> Exclude Architecture
in all the targets.
2.Close Xcode and follow the steps below to open
You can try adding:
#aboutDescription
{
height: 100px;
max-height: 100px;
}
You need to perform the action from the thread that owns the control.
That's how I'm doing that without adding too much code noise:
control.Invoke(() => textBox1.Text += "hi");
Where Invoke overload is a simple extension from Lokad Shared Libraries:
/// <summary>
/// Invokes the specified <paramref name="action"/> on the thread that owns
/// the <paramref name="control"/>.</summary>
/// <typeparam name="TControl">type of the control to work with</typeparam>
/// <param name="control">The control to execute action against.</param>
/// <param name="action">The action to on the thread of the control.</param>
public static void Invoke<TControl>(this TControl control, Action action)
where TControl : Control
{
if (!control.InvokeRequired)
{
action();
}
else
{
control.Invoke(action);
}
}
I've been playing with this code for a while now and I have something that works well for me. Log files are numbered with leading '0' but retain their file extension. And I know everyone likes to make functions for everything but I started to remove functions that performed 1 simple task. Why use many word when few do trick? Will likely remove other functions and perhaps create functions out of other blocks. I keep the logger script in a central share and make a local copy if it has changed, or load it from the central location if needed.
First I import the logger:
#Change directory to the script root
cd $PSScriptRoot
#Make a local copy if changed then Import logger
if(test-path "D:\Scripts\logger.ps1"){
if (Test-Path "\\<server>\share\DCS\Scripts\logger.ps1") {
if((Get-FileHash "\\<server>\share\DCS\Scripts\logger.ps1").Hash -ne (Get-FileHash "D:\Scripts\logger.ps1").Hash){
rename-Item -path "..\logger.ps1" -newname "logger$(Get-Date -format 'yyyyMMdd-HH.mm.ss').ps1" -force
Copy-Item "\\<server>\share\DCS\Scripts\logger.ps1" -destination "..\" -Force
}
}
}else{
Copy-Item "\\<server>\share\DCS\Scripts\logger.ps1" -destination "..\" -Force
}
. "..\logger.ps1"
Define the log file:
$logfile = (get-location).path + "\Log\" + $QProfile.replace(" ","_") + "-$metricEnv-$ScriptName.log"
What I log depends on debug levels that I created:
if ($Debug -ge 1){
$message = "<$pid>Debug:$Debug`-Adding tag `"MetricClass:temp`" to $host_name`:$metric_name"
Write-Log $message $logfile "DEBUG"
}
I would probably consider myself a bit of a "hack" when it comes to coding so this might not be the prettiest but here is my version of logger.ps1
:
# all logging settins are here on top
param(
[Parameter(Mandatory=$false)]
[string]$logFile = "$(gc env:computername).log",
[Parameter(Mandatory=$false)]
[string]$logLevel = "DEBUG", # ("DEBUG","INFO","WARN","ERROR","FATAL")
[Parameter(Mandatory=$false)]
[int64]$logSize = 10mb,
[Parameter(Mandatory=$false)]
[int]$logCount = 25
)
# end of settings
function Write-Log-Line ($line, $logFile) {
$logFile | %{
If (Test-Path -Path $_) { Get-Item $_ }
Else { New-Item -Path $_ -Force }
} | Add-Content -Value $Line -erroraction SilentlyCOntinue
}
function Roll-logFile
{
#function checks to see if file in question is larger than the paramater specified if it is it will roll a log and delete the oldes log if there are more than x logs.
param(
[string]$fileName = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")+".log",
[int64]$maxSize = $logSize,
[int]$maxCount = $logCount
)
$logRollStatus = $true
if(test-path $filename) {
$file = Get-ChildItem $filename
# Start the log-roll if the file is big enough
#Write-Log-Line "$Stamp INFO Log file size is $($file.length), max size $maxSize" $logFile
#Write-Host "$Stamp INFO Log file size is $('{0:N0}' -f $file.length), max size $('{0:N0}' -f $maxSize)"
if($file.length -ge $maxSize) {
Write-Log-Line "$Stamp INFO Log file size $('{0:N0}' -f $file.length) is larger than max size $('{0:N0}' -f $maxSize). Rolling log file!" $logFile
#Write-Host "$Stamp INFO Log file size $('{0:N0}' -f $file.length) is larger than max size $('{0:N0}' -f $maxSize). Rolling log file!"
$fileDir = $file.Directory
$fbase = $file.BaseName
$fext = $file.Extension
$fn = $file.name #this gets the name of the file we started with
function refresh-log-files {
Get-ChildItem $filedir | ?{ $_.Extension -match "$fext" -and $_.name -like "$fbase*"} | Sort-Object lastwritetime
}
function fileByIndex($index) {
$fileByIndex = $files | ?{($_.Name).split("-")[-1].trim("$fext") -eq $($index | % tostring 00)}
#Write-Log-Line "LOGGER: fileByIndex = $fileByIndex" $logFile
$fileByIndex
}
function getNumberOfFile($theFile) {
$NumberOfFile = $theFile.Name.split("-")[-1].trim("$fext")
if ($NumberOfFile -match '[a-z]'){
$NumberOfFile = "01"
}
#Write-Log-Line "LOGGER: GetNumberOfFile = $NumberOfFile" $logFile
$NumberOfFile
}
refresh-log-files | %{
[int32]$num = getNumberOfFile $_
Write-Log-Line "LOGGER: checking log file number $num" $logFile
if ([int32]$($num | % tostring 00) -ge $maxCount) {
write-host "Deleting files above log max count $maxCount : $_"
Write-Log-Line "LOGGER: Deleting files above log max count $maxCount : $_" $logFile
Remove-Item $_.fullName
}
}
$files = @(refresh-log-files)
# Now there should be at most $maxCount files, and the highest number is one less than count, unless there are badly named files, eg non-numbers
for ($i = $files.count; $i -gt 0; $i--) {
$newfilename = "$fbase-$($i | % tostring 00)$fext"
#$newfilename = getFileNameByNumber ($i | % tostring 00)
if($i -gt 1) {
$fileToMove = fileByIndex($i-1)
} else {
$fileToMove = $file
}
if (Test-Path $fileToMove.PSPath) { # If there are holes in sequence, file by index might not exist. The 'hole' will shift to next number, as files below hole are moved to fill it
write-host "moving '$fileToMove' => '$newfilename'"
#Write-Log-Line "LOGGER: moving $fileToMove => $newfilename" $logFile
# $fileToMove is a System.IO.FileInfo, but $newfilename is a string. Move-Item takes a string, so we need full path
Move-Item ($fileToMove.FullName) -Destination $fileDir\$newfilename -Force
}
}
} else {
$logRollStatus = $false
}
} else {
$logrollStatus = $false
}
$LogRollStatus
}
Function Write-Log {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]
$Message,
[Parameter(Mandatory=$False)]
[String]
$logFile = "log-$(gc env:computername).log",
[Parameter(Mandatory=$False)]
[String]
$Level = "INFO"
)
#Write-Host $logFile
$levels = ("DEBUG","INFO","WARN","ERROR","FATAL")
$logLevelPos = [array]::IndexOf($levels, $logLevel)
$levelPos = [array]::IndexOf($levels, $Level)
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss:fff")
# First roll the log if needed to null to avoid output
$Null = @(
Roll-logFile -fileName $logFile -filesize $logSize -logcount $logCount
)
if ($logLevelPos -lt 0){
Write-Log-Line "$Stamp ERROR Wrong logLevel configuration [$logLevel]" $logFile
}
if ($levelPos -lt 0){
Write-Log-Line "$Stamp ERROR Wrong log level parameter [$Level]" $logFile
}
# if level parameter is wrong or configuration is wrong I still want to see the
# message in log
if ($levelPos -lt $logLevelPos -and $levelPos -ge 0 -and $logLevelPos -ge 0){
return
}
$Line = "$Stamp $Level $Message"
Write-Log-Line $Line $logFile
}
For those using AngularJS and Angular UI Router with this, here is my solution (using mollwe's toggle). Where ".navbar-main-collapse" is my "data-target".
Create directive:
module.directive('navbarMainCollapse', ['$rootScope', function ($rootScope) {
return {
restrict: 'C',
link: function (scope, element) {
//watch for state/route change (Angular UI Router specific)
$rootScope.$on('$stateChangeSuccess', function () {
if (!element.hasClass('collapse')) {
element.collapse('hide');
}
});
}
};
}]);
Use Directive:
<div class="collapse navbar-collapse navbar-main-collapse">
<your menu>
By doing a rotation of the string you can reverse the order of the words without reversing the order of the letters.
As each word is rotated to the end of the string we reduce the amount of the string to be rotated by the length of the word. We then rotate any spaces to in front of the word we just placed at the end and shorten the rotating part of the string by 1 for each space. If the entire string is rotated with out seeing a space we are done.
Here is am implementation in C+. The l
variable contains the length of the buf
to rotate, and n
counts the number of rotations made.
#include <stdio.h>
#include <string.h>
int main(char *argv[], int argc)
{
char buf[20] = "My name is X Y Z";
int l = strlen(buf);
int n = 1;
while (l >= n) {
unsigned char c = buf[0];
for (int i = 1; i < l; i++) {
buf[i-1] = buf[i];
}
buf[l - 1] = c;
if (buf[0] == ' ' || c == ' ') {
l -= n;
n = 1;
} else {
n++;
}
}
printf("%s\n", buf);
}
The rotation code was purposely left very simple.
Cross fields validations can be done by creating custom constraints.
Example:- Compare password and confirmPassword fields of User instance.
CompareStrings
@Target({TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy=CompareStringsValidator.class)
@Documented
public @interface CompareStrings {
String[] propertyNames();
StringComparisonMode matchMode() default EQUAL;
boolean allowNull() default false;
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
StringComparisonMode
public enum StringComparisonMode {
EQUAL, EQUAL_IGNORE_CASE, NOT_EQUAL, NOT_EQUAL_IGNORE_CASE
}
CompareStringsValidator
public class CompareStringsValidator implements ConstraintValidator<CompareStrings, Object> {
private String[] propertyNames;
private StringComparisonMode comparisonMode;
private boolean allowNull;
@Override
public void initialize(CompareStrings constraintAnnotation) {
this.propertyNames = constraintAnnotation.propertyNames();
this.comparisonMode = constraintAnnotation.matchMode();
this.allowNull = constraintAnnotation.allowNull();
}
@Override
public boolean isValid(Object target, ConstraintValidatorContext context) {
boolean isValid = true;
List<String> propertyValues = new ArrayList<String> (propertyNames.length);
for(int i=0; i<propertyNames.length; i++) {
String propertyValue = ConstraintValidatorHelper.getPropertyValue(String.class, propertyNames[i], target);
if(propertyValue == null) {
if(!allowNull) {
isValid = false;
break;
}
} else {
propertyValues.add(propertyValue);
}
}
if(isValid) {
isValid = ConstraintValidatorHelper.isValid(propertyValues, comparisonMode);
}
if (!isValid) {
/*
* if custom message was provided, don't touch it, otherwise build the
* default message
*/
String message = context.getDefaultConstraintMessageTemplate();
message = (message.isEmpty()) ? ConstraintValidatorHelper.resolveMessage(propertyNames, comparisonMode) : message;
context.disableDefaultConstraintViolation();
ConstraintViolationBuilder violationBuilder = context.buildConstraintViolationWithTemplate(message);
for (String propertyName : propertyNames) {
NodeBuilderDefinedContext nbdc = violationBuilder.addNode(propertyName);
nbdc.addConstraintViolation();
}
}
return isValid;
}
}
ConstraintValidatorHelper
public abstract class ConstraintValidatorHelper {
public static <T> T getPropertyValue(Class<T> requiredType, String propertyName, Object instance) {
if(requiredType == null) {
throw new IllegalArgumentException("Invalid argument. requiredType must NOT be null!");
}
if(propertyName == null) {
throw new IllegalArgumentException("Invalid argument. PropertyName must NOT be null!");
}
if(instance == null) {
throw new IllegalArgumentException("Invalid argument. Object instance must NOT be null!");
}
T returnValue = null;
try {
PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, instance.getClass());
Method readMethod = descriptor.getReadMethod();
if(readMethod == null) {
throw new IllegalStateException("Property '" + propertyName + "' of " + instance.getClass().getName() + " is NOT readable!");
}
if(requiredType.isAssignableFrom(readMethod.getReturnType())) {
try {
Object propertyValue = readMethod.invoke(instance);
returnValue = requiredType.cast(propertyValue);
} catch (Exception e) {
e.printStackTrace(); // unable to invoke readMethod
}
}
} catch (IntrospectionException e) {
throw new IllegalArgumentException("Property '" + propertyName + "' is NOT defined in " + instance.getClass().getName() + "!", e);
}
return returnValue;
}
public static boolean isValid(Collection<String> propertyValues, StringComparisonMode comparisonMode) {
boolean ignoreCase = false;
switch (comparisonMode) {
case EQUAL_IGNORE_CASE:
case NOT_EQUAL_IGNORE_CASE:
ignoreCase = true;
}
List<String> values = new ArrayList<String> (propertyValues.size());
for(String propertyValue : propertyValues) {
if(ignoreCase) {
values.add(propertyValue.toLowerCase());
} else {
values.add(propertyValue);
}
}
switch (comparisonMode) {
case EQUAL:
case EQUAL_IGNORE_CASE:
Set<String> uniqueValues = new HashSet<String> (values);
return uniqueValues.size() == 1 ? true : false;
case NOT_EQUAL:
case NOT_EQUAL_IGNORE_CASE:
Set<String> allValues = new HashSet<String> (values);
return allValues.size() == values.size() ? true : false;
}
return true;
}
public static String resolveMessage(String[] propertyNames, StringComparisonMode comparisonMode) {
StringBuffer buffer = concatPropertyNames(propertyNames);
buffer.append(" must");
switch(comparisonMode) {
case EQUAL:
case EQUAL_IGNORE_CASE:
buffer.append(" be equal");
break;
case NOT_EQUAL:
case NOT_EQUAL_IGNORE_CASE:
buffer.append(" not be equal");
break;
}
buffer.append('.');
return buffer.toString();
}
private static StringBuffer concatPropertyNames(String[] propertyNames) {
//TODO improve concating algorithm
StringBuffer buffer = new StringBuffer();
buffer.append('[');
for(String propertyName : propertyNames) {
char firstChar = Character.toUpperCase(propertyName.charAt(0));
buffer.append(firstChar);
buffer.append(propertyName.substring(1));
buffer.append(", ");
}
buffer.delete(buffer.length()-2, buffer.length());
buffer.append("]");
return buffer;
}
}
User
@CompareStrings(propertyNames={"password", "confirmPassword"})
public class User {
private String password;
private String confirmPassword;
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public String getConfirmPassword() { return confirmPassword; }
public void setConfirmPassword(String confirmPassword) { this.confirmPassword = confirmPassword; }
}
Test
public void test() {
User user = new User();
user.setPassword("password");
user.setConfirmPassword("paSSword");
Set<ConstraintViolation<User>> violations = beanValidator.validate(user);
for(ConstraintViolation<User> violation : violations) {
logger.debug("Message:- " + violation.getMessage());
}
Assert.assertEquals(violations.size(), 1);
}
Output Message:- [Password, ConfirmPassword] must be equal.
By using the CompareStrings validation constraint, we can also compare more than two properties and we can mix any of four string comparison methods.
ColorChoice
@CompareStrings(propertyNames={"color1", "color2", "color3"}, matchMode=StringComparisonMode.NOT_EQUAL, message="Please choose three different colors.")
public class ColorChoice {
private String color1;
private String color2;
private String color3;
......
}
Test
ColorChoice colorChoice = new ColorChoice();
colorChoice.setColor1("black");
colorChoice.setColor2("white");
colorChoice.setColor3("white");
Set<ConstraintViolation<ColorChoice>> colorChoiceviolations = beanValidator.validate(colorChoice);
for(ConstraintViolation<ColorChoice> violation : colorChoiceviolations) {
logger.debug("Message:- " + violation.getMessage());
}
Output Message:- Please choose three different colors.
Similarly, we can have CompareNumbers, CompareDates, etc cross-fields validation constraints.
P.S. I have not tested this code under production environment (though I tested it under dev environment), so consider this code as Milestone Release. If you find a bug, please write a nice comment. :)
There's a property spring.resources.staticLocations
that can be set in the application.properties
. Note that this will override the default locations. See org.springframework.boot.autoconfigure.web.ResourceProperties
.
Adding another solution (Python 3) - Iterating over json files in a directory and on each file iterating over all objects and printing relevant fields.
See comments in the code.
import os,json
data_path = '/path/to/your/json/files'
# 1. Iterate over directory
directory = os.fsencode(data_path)
for file in os.listdir(directory):
filename = os.fsdecode(file)
# 2. Take only json files
if filename.endswith(".json"):
file_full_path=data_path+filename
# 3. Open json file
with open(file_full_path, encoding='utf-8', errors='ignore') as json_data:
data_in_file = json.load(json_data, strict=False)
# 4. Iterate over objects and print relevant fields
for json_object in data_in_file:
print("ttl: %s, desc: %s" % (json_object['title'],json_object['description']) )
(update: 2018)
Note that pd.Timegrouper
is depreciated and will be removed. Use instead:
df.groupby(pd.Grouper(freq='M'))
I found that the simplest way of getting the current time in PHP is something like this.
//Prints out something like 10:00am Just be sure to set your timezone correctly.
date_default_timezone_set("America/Chicago");
$TIME = date('G:ia');
COPY <all> <the> <things> <last-arg-is-destination>
But here is an important excerpt from the docs:
If you have multiple Dockerfile steps that use different files from your context, COPY them individually, rather than all at once. This ensures that each step’s build cache is only invalidated (forcing the step to be re-run) if the specifically required files change.
https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#add-or-copy
Looks like you can construct the link to the NDK that you want and download it from dl.google.com:
Linux example:
http://dl.google.com/android/ndk/android-ndk-r9b-linux-x86.tar.bz2
http://dl.google.com/android/ndk/android-ndk-r9b-linux-x86_64.tar.bz2
OS X example:
http://dl.google.com/android/ndk/android-ndk-r9b-darwin-x86.tar.bz2
http://dl.google.com/android/ndk/android-ndk-r9b-darwin-x86_64.tar.bz2
Windows example:
http://dl.google.com/android/ndk/android-ndk-r9b-windows.zip
Extensions up to r10b:
.tar.bz2
for linux / os x and .zip
for windows.
Since r10c the extensions have changed to:
.bin
for linux / os x and .exe
for windows
Since r11:
.zip
for linux and OS X as well, a new URL base, and no 32 bit versions for OS X and linux.
https://dl.google.com/android/repository/android-ndk-r11-linux-x86_64.zip
In case of Request to a REST Service:
You need to allow the CORS (cross origin sharing of resources) on the endpoint of your REST Service with Spring annotation:
@CrossOrigin(origins = "http://localhost:8080")
Very good tutorial: https://spring.io/guides/gs/rest-service-cors/
The ~/Library/Developer/Xcode/iOS DeviceSupport
folder is basically only needed to symbolicate crash logs.
You could completely purge the entire folder. Of course the next time you connect one of your devices, Xcode would redownload the symbol data from the device.
I clean out that folder once a year or so by deleting folders for versions of iOS I no longer support or expect to ever have to symbolicate a crash log for.
Yes there is a difference.
The Runtime.exec(String)
method takes a single command string that it splits into a command and a sequence of arguments.
The ProcessBuilder
constructor takes a (varargs) array of strings. The first string is the command name and the rest of them are the arguments. (There is an alternative constructor that takes a list of strings, but none that takes a single string consisting of the command and arguments.)
So what you are telling ProcessBuilder to do is to execute a "command" whose name has spaces and other junk in it. Of course, the operating system can't find a command with that name, and the command execution fails.
Using the [key] didn't work for me but using an id property does it. I just add this property in my class.
public int id {get; set;}
Example 2012:
library("xlsx")
FirstTable <- read.xlsx("MyExcelFile.xlsx", 1 , stringsAsFactors=F)
SecondTable <- read.xlsx("MyExcelFile.xlsx", 2 , stringsAsFactors=F)
Example 2015:
library("readxl")
FirstTable <- read_excel("MyExcelFile.xlsx", 1)
SecondTable <- read_excel("MyExcelFile.xlsx", 2)
readxl
and have made good experience with it.Graphviz - from the web page:
The Graphviz layout programs take descriptions of graphs in a simple text language, and make diagrams in several useful formats such as images and SVG for web pages, Postscript for inclusion in PDF or other documents; or display in an interactive graph browser. (Graphviz also supports GXL, an XML dialect.)
It's the simplest and most productive tool I've found to create a variety of boxes-and-lines diagrams. I have and use Visio and OmniGraffle, but there's always the temptation to make "just one more adjustment".
It's also quite easy to write code to produce the "dot file" format that Graphiz consumes, so automated diagram production is also nicely within reach.
I found that Apache2 (you might want to also check Apache 1.5) has a way to restrict this before uploading by dropping this in your .htaccess file:
LimitRequestBody 2097152
This restricts it to 2 megabytes (2 * 1024 * 1024) on file upload (if I did my byte math properly).
Note when you do this, the Apache error log will generate this entry when you exceed this limit on a form post or get request:
Requested content-length of 4000107 is larger than the configured limit of 2097152
And it will also display this message back in the web browser:
<h1>Request Entity Too Large</h1>
So, if you're doing AJAX form posts with something like the Malsup jQuery Form Plugin, you could trap for the H1 response like this and show an error result.
By the way, the error number returned is 413. So, you could use a directive in your .htaccess file like...
Redirect 413 413.html
...and provide a more graceful error result back.
HTML
<div id="dash">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis et dui. Nunc porttitor accumsan orci id luctus. Phasellus ipsum metus, tincidunt non rhoncus id, dictum a lectus. Nam sed ipsum a urna ac
quam.</p>
</div>
jQuery
var p = $('#dash p');
var ks = $('#dash').height();
while ($(p).outerHeight() > ks) {
$(p).text(function(index, text) {
return text.replace(/\W*\s(\S)*$/, '...');
});
}
CSS
#dash {
width: 400px;
height: 60px;
overflow: hidden;
}
#dash p {
padding: 10px;
margin: 0;
}
RESULT
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisi ligula, dapibus a volutpat sit amet, mattis et...
We had exactly the same challenge some time ago. We wanted to go with CEF3 open source library which is WPF-based and supports .NET 3.5.
Firstly, the author of CEF himself listed binding for different languages here.
Secondly, we went ahead with open source .NET CEF3 binding which is called Xilium.CefGlue and had a good success with it. In cases where something is not working as you'd expect, author usually very responsive to the issues opened in build-in bitbucket tracker
So far it has served us well. Author updates his library to support latest CEF3 releases and bug fixes on regular bases.
The quick generic answer:
std::vector<double> vec(carray,carray+carray_size);
or question specific:
std::vector<double> w_(w,w+len);
based on above: Don't forget that you can treat pointers as iterators
I had the same issue. My problem was it was missing “-Dfile.encoding=UTF8” argument under the JAVA_OPTION in statWeblogic.cmd file in WebLogic server.
As per my understanding you want data in dictionary as shown below:
key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3
for this you can use list for each dictionary keys:
case_list = {}
for entry in entries_list:
if key in case_list:
case_list[key1].append(value)
else:
case_list[key1] = [value]
for me, I had to delete the .virtualbox & .docker folder In my user directory... which worked out fine
Just use <pre> </pre>
with some styles like:
pre {
font-family: Arial, Helvetica, sans-serif;
white-space: pre-wrap;
word-wrap: break-word;
font-size: 12px;
line-height: 16px;
}
This function found here, works fine for me
function jsonRemoveUnicodeSequences($struct) {
return preg_replace("/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($struct));
}
// set
$_SESSION['test'] = 1;
// destroy
unset($_SESSION['test']);
you can find your answer in the combination of these two pages in the API:
ref is used to register a reference to an element or a child component. The reference will be registered under the parent component’s $refs object. If used on a plain DOM element, the reference will be that element
An object that holds child components that have ref registered.
For Windows 7:
My Computer
Properties
Advanced System Settings
Advanced
tabEnvironment Variables
Path
under System Variables
Edit
buttonIn Variable value editor paste this at the start of the line
C:\Program Files\Java\jdk1.7.0_72\bin;
Click Ok then Ok again
java -version
in command prompt.Notes on Step 6:
1. This sets the path for the computer, not for the individual user. It may be that you're working on a computer which other developers also use, in which case you'd rather set the user variables, rather than the system variables
The error is triggered because the file you're linking to in your HTML file is the unbundled version of the file.
To get the full bundled version you'll have to install it with npm
:
npm install --save milsymbol
This downloads the full package to your node_modules
folder.
You can then access the standalone minified JavaScript file at node_modules/milsymbol/dist/milsymbol.js
You can do this in any directory, and then just copy the below file to your /src
directory.
Json data
data = {"clo":[{"fin":"auto"},{"fin":"robot"},{"fin":"fail"}]}
When retrieve
$.ajax({
//type
//url
//data
dataType:'json'
}).done(function( data ) {
var i = data.clo.length; while(i--){
$('#el').append('<p>'+data.clo[i].fin+'</>');
}
});
Converting DataTable
to Generic Dictionary
public static Dictionary<object,IList<dynamic>> DataTable2Dictionary(DataTable dt)
{
Dictionary<object, IList<dynamic>> dict = new Dictionary<dynamic, IList<dynamic>>();
foreach(DataColumn column in dt.Columns)
{
IList<dynamic> ts = dt.AsEnumerable()
.Select(r => r.Field<dynamic>(column.ToString()))
.ToList();
dict.Add(column, ts);
}
return dict;
}
I resolved a similar problem by border-color: inherit
, see:
<li style="border-color: <?php echo $hex ?>;">...</li>
li {
border-width: 0;
}
li:before {
content: '';
display: inline-block;
float: none;
margin-right: 10px;
border-width: 4px;
border-style: solid;
border-color: inherit;
}
There is no difference, except that Pragma
is only defined as applicable to the requests by the client, whereas Cache-Control
may be used by both the requests of the clients and the replies of the servers.
So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 defines the scenario as follows:
HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.
Note: because the meaning of "Pragma: no-cache as a response header field is not actually specified, it does not provide a reliable replacement for "Cache-Control: no-cache" in a response
The way I would read the above:
if you're writing a client and need no-cache
:
Pragma: no-cache
in your requests, since you may not know if Cache-Control
is supported by the server;Cache-Control
if you're writing a server:
Cache-Control
; if not found, check for Pragma: no-cache
, and execute the Cache-Control: no-cache
logic;Cache-Control
.Of course, reality might be different from what's written or implied in the RFC!
Primefaces uses cookie polling, too
monitorDownload: function(start, complete, monitorKey) {
if(this.cookiesEnabled()) {
if(start) {
start();
}
var cookieName = monitorKey ? 'primefaces.download_' + monitorKey : 'primefaces.download';
window.downloadMonitor = setInterval(function() {
var downloadComplete = PrimeFaces.getCookie(cookieName);
if(downloadComplete === 'true') {
if(complete) {
complete();
}
clearInterval(window.downloadMonitor);
PrimeFaces.setCookie(cookieName, null);
}
}, 1000);
}
},
instead of using col-md-offset-4 use instead offset-md-4, you no longer have to use col when you're offsetting. In your case use offset-xs-1 and this will work. make sure you've called the bootstrap.css folder into your html as follows .
This seems to do what you want:
numpy.apply_along_axis(lambda args: [complex(*args)], 3, Data)
Here is another solution:
# The ellipsis is equivalent here to ":,:,:"...
numpy.vectorize(complex)(Data[...,0], Data[...,1])
And yet another simpler solution:
Data[...,0] + 1j * Data[...,1]
PS: If you want to save memory (no intermediate array):
result = 1j*Data[...,1]; result += Data[...,0]
devS' solution below is also fast.
Your question is already answered here :
Basically, rt.jar contains all of the compiled class files for the base Java Runtime ("rt") Environment. Normally, javac should know the path to this file
Also, a good link on what happens if we try to include our class file in rt.jar.
On Unix systems, for several projects, I added these lines into the CMakeLists.txt and it was compiling successfully because base (/usr/include) and local includes (/usr/local/include) go into separated directories:
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I/usr/local/include -L/usr/local/lib")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/usr/local/include")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L/usr/local/lib")
It appends the correct directory, including paths for the C and C++ compiler flags and the correct directory path for the linker flags.
Note: C++ compiler (c++) doesn't support -L, so we have to use CMAKE_EXE_LINKER_FLAGS
Well, just do this and your problem is solved :
document.getElementById('buttonLED'+id).setAttribute('onclick','writeLED(1,1)')
Have a nice day XD
public static double addDoubles(double a, double b) {
BigDecimal A = new BigDecimal(a + "");
BigDecimal B = new BigDecimal(b + "");
return A.add(B).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
This works in Ubuntu
Type this to find out the PID
ps aux | grep java
All the running process regarding to java will be shown
In my case is
johnjoe 3315 9.1 4.0 1465240 335728 ? Sl 09:42 3:19 java -jar batch.jar
Now kill it kill -9 3315
The zombie process finally stopped.
You cannot target text nodes with CSS. I'm with you; I wish you could... but you can't :(
If you don't wrap the text node in a <span>
like @Jacob suggests, you could instead give the surrounding element padding
as opposed to margin
:
<p id="theParagraph">The text node!</p>
p#theParagraph
{
border: 1px solid red;
padding-bottom: 10px;
}
You can try onload event as well;
var createIframe = function (src) {
var self = this;
$('<iframe>', {
src: src,
id: 'iframeId',
frameborder: 1,
scrolling: 'no',
onload: function () {
self.isIframeLoaded = true;
console.log('loaded!');
}
}).appendTo('#iframeContainer');
};
You can use
catch(...)
but that is very dangerous. In his book Debugging Windows, John Robbins tells a war story about a really nasty bug that was masked by a catch(...) command. You're much better off catching specific exceptions. Catch whatever you think your try block might reasonably throw, but let the code throw an exception higher up if something really unexpected happens.
Same error
Installing collected packages: six, pyparsing, packaging, appdirs, setuptools
Exception:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main
status = self.run(options, args)
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run
prefix=options.prefix_path,
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install
**kwargs
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install
self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files
isolated=self.isolated,
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files
clobber(source, lib_dir, True)
File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 323, in clobber
shutil.copyfile(srcfile, destfile)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 83, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/six.py'
and here I use --user
without sudo
to solve this issue
$ pip install --user scikit-image h5py keras pygame
Collecting scikit-image
Downloading http://mirrors.aliyun.com/pypi/packages/65/69/27a1d55ce8f77c8ac757938707105b1070ff4f2ae47d2dc99461bfae4491/scikit_image-0.13.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (28.1MB)
100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 28.1MB 380kB/s
Collecting h5py
Downloading http://mirrors.aliyun.com/pypi/packages/b7/cc/1c29b0815b12de2c92b5323cad60f724ac8f0e39d0166d0b9dfacbcb70dd/h5py-2.7.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (4.5MB)
100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 4.5MB 503kB/s
Requirement already satisfied: keras in /Library/Python/2.7/site-packages
Requirement already satisfied: pygame in /Library/Python/2.7/site-packages
Requirement already satisfied: matplotlib>=1.3.1 in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from scikit-image)
Requirement already satisfied: six>=1.7.3 in /Library/Python/2.7/site-packages (from scikit-image)
Requirement already satisfied: pillow>=2.1.0 in /Library/Python/2.7/site-packages (from scikit-image)
Requirement already satisfied: networkx>=1.8 in /Library/Python/2.7/site-packages (from scikit-image)
Requirement already satisfied: PyWavelets>=0.4.0 in /Library/Python/2.7/site-packages (from scikit-image)
Collecting scipy>=0.17.0 (from scikit-image)
Downloading http://mirrors.aliyun.com/pypi/packages/72/eb/d398b9f63ee936575edc62520477d6c2353ed013bacd656bd0c8bc1d0fa7/scipy-0.19.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (16.2MB)
100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 16.2MB 990kB/s
Requirement already satisfied: numpy>=1.7 in /Library/Python/2.7/site-packages (from h5py)
Requirement already satisfied: theano in /Library/Python/2.7/site-packages (from keras)
Requirement already satisfied: pyyaml in /Library/Python/2.7/site-packages (from keras)
Requirement already satisfied: python-dateutil in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: tornado in /Library/Python/2.7/site-packages (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: pyparsing>=1.5.6 in /Users/qiuwei/Library/Python/2.7/lib/python/site-packages (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: nose in /Library/Python/2.7/site-packages (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: olefile in /Library/Python/2.7/site-packages (from pillow>=2.1.0->scikit-image)
Requirement already satisfied: decorator>=3.4.0 in /Library/Python/2.7/site-packages (from networkx>=1.8->scikit-image)
Requirement already satisfied: singledispatch in /Library/Python/2.7/site-packages (from tornado->matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: certifi in /Library/Python/2.7/site-packages (from tornado->matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: backports_abc>=0.4 in /Library/Python/2.7/site-packages (from tornado->matplotlib>=1.3.1->scikit-image)
Installing collected packages: scipy, scikit-image, h5py
Successfully installed h5py-2.7.0 scikit-image-0.13.0 scipy-0.19.0
Hope it will help someone who encounter similar issue!
Starting with v0.20.0
, the dtype
keyword argument in read_excel()
function could be used to specify the data types that needs to be applied to the columns just like it exists for read_csv()
case.
Using converters
and dtype
arguments together on the same column name would lead to the latter getting shadowed and the former gaining preferance.
1) Inorder for it to not interpret the dtypes
but rather pass all the contents of it's columns as they were originally in the file before, we could set this arg to str
or object
so that we don't mess up our data. (one such case would be leading zeros in numbers which would be lost otherwise)
pd.read_excel('file_name.xlsx', dtype=str) # (or) dtype=object
2) It even supports a dict mapping wherein the keys
constitute the column names and values
it's respective data type to be set especially when you want to alter the dtype
for a subset of all the columns.
# Assuming data types for `a` and `b` columns to be altered
pd.read_excel('file_name.xlsx', dtype={'a': np.float64, 'b': np.int32})
function wp_get_post_categories( $post_id = 0, $args = array() )
{
$post_id = (int) $post_id;
$defaults = array('fields' => 'ids');
$args = wp_parse_args( $args, $defaults );
$cats = wp_get_object_terms($post_id, 'category', $args);
return $cats;
}
Here is the second argument of function wp_get_post_categories()
which you can pass the attributes of receiving data.
$category_detail = get_the_category( '4',array( 'fields' => 'names' ) ); //$post->ID
foreach( $category_detail as $cd )
{
echo $cd->name;
}
TL;DR:
No, don't subscribe manually to them, don't use them in services. Use them as is shown in the documentation only to emit events in components. Don't defeat angular's abstraction.
Answer:
EventEmitter is an angular2 abstraction and its only purpose is to emit events in components. Quoting a comment from Rob Wormald
[...] EventEmitter is really an Angular abstraction, and should be used pretty much only for emitting custom Events in components. Otherwise, just use Rx as if it was any other library.
This is stated really clear in EventEmitter's documentation.
Use by directives and components to emit custom Events.
Angular2 will never guarantee us that EventEmitter will continue being an Observable. So that means refactoring our code if it changes. The only API we must access is its emit()
method. We should never subscribe manually to an EventEmitter.
All the stated above is more clear in this Ward Bell's comment (recommended to read the article, and the answer to that comment). Quoting for reference
Do NOT count on EventEmitter continuing to be an Observable!
Do NOT count on those Observable operators being there in the future!
These will be deprecated soon and probably removed before release.
Use EventEmitter only for event binding between a child and parent component. Do not subscribe to it. Do not call any of those methods. Only call
eve.emit()
His comment is in line with Rob's comment long time ago.
Simply use it to emit events from your component. Take a look a the following example.
@Component({
selector : 'child',
template : `
<button (click)="sendNotification()">Notify my parent!</button>
`
})
class Child {
@Output() notifyParent: EventEmitter<any> = new EventEmitter();
sendNotification() {
this.notifyParent.emit('Some value to send to the parent');
}
}
@Component({
selector : 'parent',
template : `
<child (notifyParent)="getNotification($event)"></child>
`
})
class Parent {
getNotification(evt) {
// Do something with the notification (evt) sent by the child!
}
}
class MyService {
@Output() myServiceEvent : EventEmitter<any> = new EventEmitter();
}
Stop right there... you're already wrong...
Hopefully these two simple examples will clarify EventEmitter's proper usage.
You can join the table with itself (on sensor id), and add left.timestamp < right.timestamp
as join condition. Then you pick the rows, where right.id
is null
. Voila, you got the latest entry per sensor.
http://sqlfiddle.com/#!9/45147/37
SELECT L.* FROM sensorTable L
LEFT JOIN sensorTable R ON
L.sensorID = R.sensorID AND
L.timestamp < R.timestamp
WHERE isnull (R.sensorID)
But please note, that this will be very resource intensive if you have a little amount of ids and many values! So, I wouldn't recommend this for some sort of Measuring-Stuff, where each Sensor collects a value every minute. However in a Use-Case, where you need to track "Revisions" of something that changes just "sometimes", it's easy going.
As answered previously, you do not need to set the environment variable on the remote host. Instead, you can simply do the meta-expansion on the local host, and pass the value to the remote host.
ssh [email protected] '~/tools/run_pvt.pl $BUILD_NUMBER'
If you really want to set the environment variable on the remote host and use it, you can use the env
program
ssh [email protected] "env BUILD_NUMBER=$BUILD_NUMBER ~/tools/run_pvt.pl \$BUILD_NUMBER"
In this case this is a bit of an overkill, and note
env BUILD_NUMBER=$BUILD_NUMBER
does the meta expansion on the local
hostBUILD_NUMBER
environment variable will be used bystd::unique_ptr has no copy constructor. You create an instance and then ask the std::vector to copy that instance during initialisation.
error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::uniqu
e_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_D
eleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> =
std::unique_ptr<int>]'
The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.
The following works with the new emplace calls.
std::vector< std::unique_ptr< int > > vec;
vec.emplace_back( new int( 1984 ) );
See using unique_ptr with standard library containers for further reading.
From plt.imshow()
official guide, we know that aspect controls the aspect ratio of the axes. Well in my words, the aspect is exactly the ratio of x unit and y unit. Most of the time we want to keep it as 1 since we do not want to distort out figures unintentionally. However, there is indeed cases that we need to specify aspect a value other than 1. The questioner provided a good example that x and y axis may have different physical units. Let's assume that x is in km and y in m. Hence for a 10x10 data, the extent should be [0,10km,0,10m] = [0, 10000m, 0, 10m]. In such case, if we continue to use the default aspect=1, the quality of the figure is really bad. We can hence specify aspect = 1000 to optimize our figure. The following codes illustrate this method.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.RandomState(0)
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower', extent = [0, 10000, 0, 10], aspect = 1000)
Nevertheless, I think there is an alternative that can meet the questioner's demand. We can just set the extent as [0,10,0,10] and add additional xy axis labels to denote the units. Codes as follows.
plt.imshow(data, origin = 'lower', extent = [0, 10, 0, 10])
plt.xlabel('km')
plt.ylabel('m')
To make a correct figure, we should always bear in mind that x_max-x_min = x_res * data.shape[1]
and y_max - y_min = y_res * data.shape[0]
, where extent = [x_min, x_max, y_min, y_max]
. By default, aspect = 1
, meaning that the unit pixel is square. This default behavior also works fine for x_res and y_res that have different values. Extending the previous example, let's assume that x_res is 1.5 while y_res is 1. Hence extent should equal to [0,15,0,10]. Using the default aspect, we can have rectangular color pixels, whereas the unit pixel is still square!
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10])
# Or we have similar x_max and y_max but different data.shape, leading to different color pixel res.
data=rng.randn(10,5)
plt.imshow(data, origin = 'lower', extent = [0, 5, 0, 5])
The aspect of color pixel is x_res / y_res
. setting its aspect to the aspect of unit pixel (i.e. aspect = x_res / y_res = ((x_max - x_min) / data.shape[1]) / ((y_max - y_min) / data.shape[0])
) would always give square color pixel. We can change aspect = 1.5 so that x-axis unit is 1.5 times y-axis unit, leading to a square color pixel and square whole figure but rectangular pixel unit. Apparently, it is not normally accepted.
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10], aspect = 1.5)
The most undesired case is that set aspect an arbitrary value, like 1.2, which will lead to neither square unit pixels nor square color pixels.
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10], aspect = 1.2)
Long story short, it is always enough to set the correct extent and let the matplotlib do the remaining things for us (even though x_res!=y_res)! Change aspect only when it is a must.
As others have answered, you probably have a DATETIME
(or other variation) column and not a DATE
datatype.
Here's a condition that works for all, including DATE
:
SELECT *
FROM xxx
WHERE dates >= '20121026'
AND dates < '20121028' --- one day after
--- it is converted to '2012-10-28 00:00:00.000'
;
@Aaron Bertrand has blogged about this at: What do BETWEEN
and the devil have in common?
Simple way
Create a new java class
public class ActivityName extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, new Fragment_name_which_you_wantto_open()).commit();}
}
}
in your activity where u want to call fragment
Intent i = new Intent(Currentactivityname.this,ActivityName.class);
startActivity(i);
Another Method
Place frame layout in your activity where u want to open fragment
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</FrameLayout>
Paste this code where u want to open fragment
Fragment mFragment = null;
mFragment = new Name_of_fragment_which_you_want_to_open();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frameLayout, mFragment).commit();
The question has been answered, my contribution consists in clarifying one thing that may confuse beginners:
Some of the suggested and correct answers used firstChild.data
and others used firstChild.nodeValue
instead. In case you are wondering what is the different between them, you should remember they do the same thing because nodeValue
is just an alias for data
.
The reference to my statement can be found as a comment on the source code of minidom:
#
nodeValue
is an alias fordata
Try
byte[] incomingByteArray = receive...; // This is your Base64-encoded bute[]
byte[] decodedByteArray =Convert.FromBase64String (Encoding.ASCII.GetString (incomingByteArray));
// This work because all Base64-encoding is done with pure ASCII characters
Here is a short tutorial:
Model:
namespace ImageUploadApp.Models
{
using System;
using System.Collections.Generic;
public partial class Image
{
public int ID { get; set; }
public string ImagePath { get; set; }
}
}
View:
Create:
@model ImageUploadApp.Models.Image
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("Create", "Image", null, FormMethod.Post,
new { enctype = "multipart/form-data" })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Image</legend>
<div class="editor-label">
@Html.LabelFor(model => model.ImagePath)
</div>
<div class="editor-field">
<input id="ImagePath" title="Upload a product image"
type="file" name="file" />
</div>
<p><input type="submit" value="Create" /></p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Index (for display):
@model IEnumerable<ImageUploadApp.Models.Image>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.ImagePath)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ImagePath)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Ajax.ActionLink("Delete", "Delete", new {id = item.ID} })
</td>
</tr>
}
</table>
Controller (Create)
public ActionResult Create(Image img, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
file.SaveAs(HttpContext.Server.MapPath("~/Images/")
+ file.FileName);
img.ImagePath = file.FileName;
}
db.Image.Add(img);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(img);
}
Hope this will help :)
Sum of total_vm
is 847170 and sum of rss
is 214726, these two values are counted in 4kB pages, which means when oom-killer was running, you had used 214726*4kB=858904kB physical memory and swap space.
Since your physical memory is 1GB and ~200MB was used for memory mapping, it's reasonable for invoking oom-killer when 858904kB was used.
rss
for process 2603 is 181503, which means 181503*4KB=726012 rss, was equal to sum of anon-rss
and file-rss
.
[11686.043647] Killed process 2603 (flasherav) total-vm:1498536kB, anon-rss:721784kB, file-rss:4228kB
Beware that serving images from DB is usually much, much much slower than serving them from disk.
You'll be starting a PHP process, opening a DB connection, having the DB read image data from the same disk and RAM for cache as filesystem would, transferring it over few sockets and buffers and then pushing out via PHP, which by default makes it non-cacheable and adds overhead of chunked HTTP encoding.
OTOH modern web servers can serve images with just few optimized kernel calls (memory-mapped file and that memory area passed to TCP stack), so that they don't even copy memory around and there's almost no overhead.
That's a difference between being able to serve 20 or 2000 images in parallel on one machine.
So don't do it unless you absolutely need transactional integrity (and actually even that can be done with just image metadata in DB and filesystem cleanup routines) and know how to improve PHP's handling of HTTP to be suitable for images.
With regard to Brent.Longborough's answer (appering only on page 2 onward), perhaps you need to set the \thispagestyle{} after \begin{document}. I wonder if the letter class is setting the first page style to empty.
The issue in my case was I included a constructor taking parameters but not an empty constructor with the Inject annotation, like so.
@Inject public VisitorBean() {}
I just tested it without any constructor and this appears to work also.
I would think of one more case when pessimistic locking would be a better choice.
For optimistic locking every participant in data modification must agree in using this kind of locking. But if someone modifies the data without taking care about the version column, this will spoil the whole idea of the optimistic locking.
Elaborating on previous answer by Pir Fahim, he's right but i'm using selectedItem.Text (only way to make it work to me)
Use the SelectedIndexChanged() event to store the data somewhere. In my case, i usually fill a custom class, something like:
class myItem {
string name {get; set;}
string price {get; set;}
string desc {get; set;}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
myItem selected_item = new myItem();
selected_item.name = listBox1.SelectedItem.Text;
Retrieve (selected_item.name);
}
And then you can retrieve the rest of data from a List of "myItems"..
myItem Retrieve (string wanted_item) {
foreach (myItem item in my_items_list) {
if (item.name == wanted_item) {
// This is the selected item
return item;
}
}
return null;
}
I tried just calling -[UITableView cellForRowAtIndexPath:]
, but that didn't work. But, the following works for me for example. I alloc
and release
the NSArray
for tight memory management.
- (void)reloadRow0Section0 {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
[self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
[indexPaths release];
}
Your function worked for me after changing its declaration to this ...
Function processArr(Arr As Variant) As String
You could also consider a ParamArray
like this ...
Function processArr(ParamArray Arr() As Variant) As String
'Dim N As Variant
Dim N As Long
Dim finalStr As String
For N = LBound(Arr) To UBound(Arr)
finalStr = finalStr & Arr(N)
Next N
processArr = finalStr
End Function
And then call the function like this ...
processArr("foo", "bar")
String str_date="13-09-2011";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date);
System.out.println("Today is " +date.getTime());
Try this
CREATE TABLE tbl_PersonalDetail
(ID INT IDENTITY ,[Date] nvarchar(20), Name nvarchar(20), GenderID int);
INSERT INTO Tbl_PersonalDetail VALUES(N'18-4-2015', N'Monay', 2),
(N'31-3-2015', N'Monay', 2),
(N'28-12-2015', N'Monay', 2),
(N'19-4-2015', N'Monay', 2)
DECLARE @Date Nvarchar(200)
SET @Date = (SELECT [Date] FROM Tbl_PersonalDetail WHERE ID = 2)
Update Tbl_PersonalDetail SET [Date] = (REPLACE(@Date , '-','/')) WHERE ID = 2
You can quickly serve static content in JAVA Spring-boot App via thymeleaf
(ref: source)
I assume you have already added Spring Boot plugin apply plugin: 'org.springframework.boot'
and the necessary buildscript
Then go ahead and ADD thymeleaf to your build.gradle
==>
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Lets assume you have added home.html at src/main/resources
To serve this file, you will need to create a controller.
package com.ajinkya.th.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomePageController {
@RequestMapping("/")
public String homePage() {
return "home";
}
}
Thats it ! Now restart your gradle server. ./gradlew bootRun
Is there a certain form which one should choose?
You can choose either. Its matter of choice. All are equivalent. while(1) {}/while(true){}
is frequently used for infinite loop by programmers.
The Response was Empty. Most of the case the codes will stats with 1xx, 2xx, 3xx, 4xx, 5xx.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" />
<div class="View"><?php include 'Small.php'; ?></div>
<script type="text/javascript">
$(document).ready(function() {
$('.View').load('Small.php');
var auto_refresh = setInterval(
function ()
{
$('.View').load('Small.php').fadeIn("slow");
}, 15000); // refresh every 15000 milliseconds
$.ajaxSetup({ cache: true });
});
</script>
Keep in mind that MySQL has a maximum row size limit
The internal representation of a MySQL table has a maximum row size limit of 65,535 bytes, not counting BLOB and TEXT types. BLOB and TEXT columns only contribute 9 to 12 bytes toward the row size limit because their contents are stored separately from the rest of the row. Read more about Limits on Table Column Count and Row Size.
Maximum size a single column can occupy, is different before and after MySQL 5.0.3
Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 255 before MySQL 5.0.3, and 0 to 65,535 in 5.0.3 and later versions. The effective maximum length of a VARCHAR in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used.
However, note that the limit is lower if you use a multi-byte character set like utf8 or utf8mb4.
Use TEXT
types inorder to overcome row size limit.
The four TEXT types are TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT. These correspond to the four BLOB types and have the same maximum lengths and storage requirements.
More details on BLOB and TEXT Types
Even more
Checkout more details on Data Type Storage Requirements which deals with storage requirements for all data types.
From RFC 1945 (HTTP/1.0) and RFC 2617 (HTTP Authentication referenced by HTTP/1.1)
The realm attribute (case-insensitive) is required for all authentication schemes which issue a challenge. The realm value (case-sensitive), in combination with the canonical root URL of the server being accessed, defines the protection space. These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database. The realm value is a string, generally assigned by the origin server, which may have additional semantics specific to the authentication scheme.
In short, pages in the same realm should share credentials. If your credentials work for a page with the realm "My Realm", it should be assumed that the same username and password combination should work for another page with the same realm.
Try to change type of ScoreIfNoMatch, like this:
public class MatrixModel
{
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
public string S7 { get; set; }
public string S8 { get; set; }
public string S9 { get; set; }
public string S10 { get; set; }
// the type should be string
public string ScoreIfNoMatch { get; set; }
}
If you want to keep alias at the global level as is and just want to change for your script.
Just use:
alias cp=cp
and then write your follow up commands.
git push -f origin branchname
Use the above command only if you are sure that you don't need remote branch code otherwise do merge first and then push the code
It works with just this:
.slideContainer {
white-space: nowrap;
}
.slide {
display: inline-block;
width: 600px;
white-space: normal;
}
I did originally have float : left;
and that prevented it from working correctly.
Thanks for posting this solution.
do you use jquery? if then:
$('#xx').val();
or use original javascript(DOM)
document.getElementById('xx').value
or
xxxform.xx.value;
if you want to learn more, w3chool can help you a lot.
You can use:
double example = 12.34567;
double output = ( (double) ( (int) (example * 1000.0) ) ) / 1000.0 ;
What about iterating on the /proc virtual file system ? http://linux.die.net/man/5/proc ?
Since you are not interested in keeping any data, drop the entire database and create a new one.
The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.
Arguably the most common way to select the values is to use Boolean indexing.
With this method, you find out where column 'a' is equal to 1
and then sum the corresponding rows of column 'b'. You can use loc
to handle the indexing of rows and columns:
>>> df.loc[df['a'] == 1, 'b'].sum()
15
The Boolean indexing can be extended to other columns. For example if df
also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:
df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()
Another way to select the data is to use query
to filter the rows you're interested in, select column 'b' and then sum:
>>> df.query("a == 1")['b'].sum()
15
Again, the method can be extended to make more complicated selections of the data:
df.query("a == 1 and c == 2")['b'].sum()
Note this is a little more concise than the Boolean indexing approach.
The alternative approach is to use groupby
to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:
>>> df.groupby('a')['b'].sum()[1]
15
This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a
:
>>> df.groupby('a')['b'].sum()
a
1 15
2 8
Here's how to list local branches that do not have a remote branch in origin with the same name:
git branch | sed 's|* | |' | sort > local
git branch -r | sed 's|origin/||' | sort > remote
comm -23 local remote
Use:
SELECT t.phone,
t.phone2
FROM jewishyellow.users t
WHERE t.phone LIKE '813%'
AND t.phone2 IS NOT NULL
Also, correct me if I'm wrong, but I believe that submit will wait for a new page to load, whereas click will immediately continue executing code
public static int generatRandomPositiveNegitiveValue(int max , int min) {
//Random rand = new Random();
int ii = -min + (int) (Math.random() * ((max - (-min)) + 1));
return ii;
}
It looks like there is an extra curly bracket in the code.
function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("content").innerHTML = xmlhttp.responseText;
}
// extra bracket }
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}
Emil's answer is correct, but it's my understanding that inet_ntoa
is deprecated and that instead you should use inet_ntop
. If you are using IPv4, cast your struct sockaddr
to sockaddr_in
. Your code will look something like this:
struct addrinfo *res; // populated elsewhere in your code
struct sockaddr_in *ipv4 = (struct sockaddr_in *)res->ai_addr;
char ipAddress[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(ipv4->sin_addr), ipAddress, INET_ADDRSTRLEN);
printf("The IP address is: %s\n", ipAddress);
Take a look at this great resource for more explanation, including how to do this for IPv6 addresses.
All cookies expire as per the cookie specification, so this is not a PHP limitation.
Use a far future date. For example, set a cookie that expires in ten years:
setcookie(
"CookieName",
"CookieValue",
time() + (10 * 365 * 24 * 60 * 60)
);
Note that if you set a date past 2038 in 32-bit PHP, the number will wrap around and you'll get a cookie that expires instantly.
Using plain java:
String s = "1234567890";
List<String> list = new Scanner(s).findAll("...").map(MatchResult::group).collect(Collectors.toList());
System.out.printf("%s%n", list);
Produces the output:
[123, 456, 789]
Note that this discards leftover characters (0 in this case).
The answer of @abbotto did not work for me, had to do some things differently: