Here is how to create the desired outcome:
library(reshape2); library(tidyverse)
melt(outer(1:4, 1:4), varnames = c("X1", "X2")) %>%
ggplot() +
geom_tile(aes(X1, X2, fill = value)) +
scale_fill_continuous(guide = guide_legend()) +
theme(legend.position="bottom",
legend.spacing.x = unit(0, 'cm'))+
guides(fill = guide_legend(label.position = "bottom"))
Created on 2019-12-07 by the reprex package (v0.3.0)
Edit: no need for these imperfect options anymore, but I'm leaving them here for reference.
Two imperfect options that don't give you exactly what you were asking for, but pretty close (will at least put the colours together).
library(reshape2); library(tidyverse)
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
theme(legend.position="bottom", legend.direction="vertical")
p1 + scale_fill_continuous(guide = "colorbar") + theme(legend.position="bottom")
Created on 2019-02-28 by the reprex package (v0.2.1)
You can also try using flex-box
<head><style>
body {
color:white;
font-family:arial;
font-size:1.2em;
}
form {
margin:0 auto;
padding:20px;
background:#444;
}
.input-group {
margin-top:10px;
width:60%;
display:flex;
justify-content:space-between;
flex-wrap:wrap;
}
label, input {
flex-basis:100px;
}
</style></head>
<body>
<form>
<div class="wrapper">
<div class="input-group">
<label for="user_name">name:</label>
<input type="text" id="user_name">
</div>
<div class="input-group">
<label for="user_pass">Password:</label>
<input type="password" id="user_pass">
</div>
</div>
</form>
</body>
</html>
The best way to do this is to surround your tree in the triple backticks to denote a code block. For more info, see the markdown docs: http://daringfireball.net/projects/markdown/syntax#code
This is completely possible. Use Javascript.
I use jQuery to select the input element. I have it set up with an on change event.
$("#aFile_upload").on("change", function (e) {
var count=1;
var files = e.currentTarget.files; // puts all files into an array
// call them as such; files[0].size will get you the file size of the 0th file
for (var x in files) {
var filesize = ((files[x].size/1024)/1024).toFixed(4); // MB
if (files[x].name != "item" && typeof files[x].name != "undefined" && filesize <= 10) {
if (count > 1) {
approvedHTML += ", "+files[x].name;
}
else {
approvedHTML += files[x].name;
}
count++;
}
}
$("#approvedFiles").val(approvedHTML);
});
The code above saves all the file names that I deem worthy of persisting to the submission page, before the submit actually happens. I add the "approved" files to an input element's val using jQuery so a form submit will send the names of the files I want to save. All the files will be submitted, however, now on the server side we do have to filter these out. I haven't written any code for that yet, but use your imagination. I assume one can accomplish this by a for loop and matching the names sent over from the input field and match them to the $_FILES(PHP Superglobal, sorry I dont know ruby file variable) variable.
My point is you can do checks for files before submission. I do this and then output it to the user before he/she submits the form, to let them know what they are uploading to my site. Anything that doesn't meet the criteria does not get displayed back to the user and therefore they should know, that the files that are too large wont be saved. This should work on all browsers because I'm not using FormData object.
Yes, Mid
.
Dim sub_str
sub_str = Mid(source_str, 10, 5)
The first parameter is the source string, the second is the start index, and the third is the length.
@bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid
results in "invalid procedure call or argument Mid".
git gc --prune=now
is not what you want.
git remote prune public
or git remote prune origin
# if thats the the remote source
is what you want
As of September 2016 this addon is the best to disable CORS: https://github.com/fredericlb/Force-CORS/releases
In the options panel you can configure which header to inject and specific website to have it enabled automatically.
Add them to a static map inside (this.getClass().getName()) the parent classes constructor (or create a default one) but this will get updated in runtime. If lazy initialization is an option you can try this approach.
You can't declare an extern
local method inside of a method, or any other method with an attribute. Move your DLL import into the class:
using System.Runtime.InteropServices;
public class WindowHandling
{
[DllImport("User32.dll")]
public static extern int SetForegroundWindow(IntPtr point);
public void ActivateTargetApplication(string processName, List<string> barcodesList)
{
Process p = Process.Start("notepad++.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
IntPtr processFoundWindow = p.MainWindowHandle;
}
}
re: Windows users
No. Don't remove the Javapath environment reference from your PATH variable.
The reason why the registry didn't work is that the Oracle Javapath script needs to run in the PATH sequence ahead of the JRE & JDK directories - it will sort out the current version:
put this directory at the HEAD of your %PATH%
variable:
C:\ProgramData\Oracle\Java\javapath
[or wherever it is on your desktop]
so your PATH will look something like this - mine for example
PATH=C:\ProgramData\Oracle\Java\javapath;<other path directories>;E:\Program Files\Java\jdk1.8.0_77\bin;E:\Program Files\Java\jre1.8.0_77\bin
You will then see the correct, current version:
C:\>java -version
java version "1.8.0_77"
Java(TM) SE Runtime Environment (build 1.8.0_77-b03)
Java HotSpot(TM) 64-Bit Server VM (build 25.77-b03, mixed mode)
Using jQuery you can use contents()
. For example:
var inside = $('#one').contents();
the OOP way to do this in ES5 is to make that variable into a property using the this keyword.
function first(){
this.nameContent=document.getElementById('full_name').value;
}
function second() {
y=new first();
alert(y.nameContent);
}
if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:
If x and/or y is 2-dimensional, then the corresponding columns will be plotted.
In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:
np.squeez doc: Remove single-dimensional entries from the shape of an array.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()
But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:
We encountered this issue and discovered that the error was being thrown when using (IE in our case) the browser logged in as the process account, then changing the session log in through the application (SharePoint). I believe this scenario passes two authentication schemes:
The application hosted an *.asmx web service, that was being called on a load balanced server, initiating a web service call to itself using a WCF-like .NET3.5 binding.
Code that was used to call the web service:
public class WebServiceClient<T> : IDisposable
{
private readonly T _channel;
private readonly IClientChannel _clientChannel;
public WebServiceClient(string url)
: this(url, null)
{
}
/// <summary>
/// Use action to change some of the connection properties before creating the channel
/// </summary>
public WebServiceClient(string url,
Action<CustomBinding, HttpTransportBindingElement, EndpointAddress, ChannelFactory> init)
{
var binding = new CustomBinding();
binding.Elements.Add(
new TextMessageEncodingBindingElement(MessageVersion.Soap12, Encoding.UTF8));
var transport = url.StartsWith("https", StringComparison.InvariantCultureIgnoreCase)
? new HttpsTransportBindingElement()
: new HttpTransportBindingElement();
transport.AuthenticationScheme = System.Net.AuthenticationSchemes.Ntlm;
binding.Elements.Add(transport);
var address = new EndpointAddress(url);
var factory = new ChannelFactory<T>(binding, address);
factory.Credentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
if (init != null)
{
init(binding, transport, address, factory);
}
this._clientChannel = (IClientChannel)factory.CreateChannel();
this._channel = (T)this._clientChannel;
}
/// <summary>
/// Use this property to call service methods
/// </summary>
public T Channel
{
get { return this._channel; }
}
/// <summary>
/// Use this porperty when working with
/// Session or Cookies
/// </summary>
public IClientChannel ClientChannel
{
get { return this._clientChannel; }
}
public void Dispose()
{
this._clientChannel.Dispose();
}
}
We discovered that if the session credential was the same as the browser's process account, then just NTLM was used and the call was successful. Otherwise it would result in this captured exception:
The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate,NTLM'.
In the end, I am fairly certain that one of the authentication schemes would pass authentication while the other wouldn't, because it was not granted appropriate access.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<ConfigurationRepository>(options =>
options.UseSqlServer(Configuration.GetConnectionString("SqlConnectionString")));
services.AddScoped<IConfigurationBL, ConfigurationBL>();
services.AddScoped<IConfigurationRepository, ConfigurationRepository>();
}
Check my answer here
The use of Layout Inspector tool can be very convenient when you have a complex view or you are using a third party library where you can't add an id to a view
And do not forget the "new" service type (from the k8s docu):
ExternalName: Maps the Service to the contents of the externalName field (e.g. foo.bar.example.com), by returning a CNAME record with its value. No proxying of any kind is set up.
Note: You need either kube-dns version 1.7 or CoreDNS version 0.0.8 or higher to use the ExternalName type.
Here is a modified version of @ntoskrnl's code featuring isRestrictedCryptography
check by actual Cipher.getMaxAllowedKeyLength
, slf4j logging and support of singleton initialization from application bootstrap like this:
static {
UnlimitedKeyStrengthJurisdictionPolicy.ensure();
}
This code would correctly stop mangling with reflection when unlimited policy becomes available by default in Java 8u162 as @cranphin's answer predicts.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Cipher;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.security.NoSuchAlgorithmException;
import java.security.Permission;
import java.security.PermissionCollection;
import java.util.Map;
// https://stackoverflow.com/questions/1179672/how-to-avoid-installing-unlimited-strength-jce-policy-files-when-deploying-an
public class UnlimitedKeyStrengthJurisdictionPolicy {
private static final Logger log = LoggerFactory.getLogger(UnlimitedKeyStrengthJurisdictionPolicy.class);
private static boolean isRestrictedCryptography() throws NoSuchAlgorithmException {
return Cipher.getMaxAllowedKeyLength("AES/ECB/NoPadding") <= 128;
}
private static void removeCryptographyRestrictions() {
try {
if (!isRestrictedCryptography()) {
log.debug("Cryptography restrictions removal not needed");
return;
}
/*
* Do the following, but with reflection to bypass access checks:
*
* JceSecurity.isRestricted = false;
* JceSecurity.defaultPolicy.perms.clear();
* JceSecurity.defaultPolicy.add(CryptoAllPermission.INSTANCE);
*/
Class<?> jceSecurity = Class.forName("javax.crypto.JceSecurity");
Class<?> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions");
Class<?> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission");
Field isRestrictedField = jceSecurity.getDeclaredField("isRestricted");
isRestrictedField.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(isRestrictedField, isRestrictedField.getModifiers() & ~Modifier.FINAL);
isRestrictedField.set(null, false);
Field defaultPolicyField = jceSecurity.getDeclaredField("defaultPolicy");
defaultPolicyField.setAccessible(true);
PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null);
Field perms = cryptoPermissions.getDeclaredField("perms");
perms.setAccessible(true);
((Map<?, ?>) perms.get(defaultPolicy)).clear();
Field instance = cryptoAllPermission.getDeclaredField("INSTANCE");
instance.setAccessible(true);
defaultPolicy.add((Permission) instance.get(null));
log.info("Successfully removed cryptography restrictions");
} catch (Exception e) {
log.warn("Failed to remove cryptography restrictions", e);
}
}
static {
removeCryptographyRestrictions();
}
public static void ensure() {
// just force loading of this class
}
}
Try this:
Go to virtual box > right click the OS > settings > under one of the many tab that I don't remember(sorry for this, i dont have vbox installed)> locate the VDI (virtual box disk image) file..
and save the settings.. then try to start the OS..
Here is example code what I did for an asynchronous method
@RequestMapping(value = "/import", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void importDataFromFile(@RequestParam("file") MultipartFile file)
{
accountingSystemHandler.importData(file, assignChargeCodes);
}
You do not need to return any thing from your method all you need to use this annotation so that your method should return OK in every case
@ResponseStatus(value = HttpStatus.OK)
This method holds instructions to paint this component. Actually, in Swing, you should change paintComponent() instead of paint(), as paint calls paintBorder(), paintComponent() and paintChildren(). You shouldn't call this method directly, you should call repaint() instead.
This method can't be overridden. It controls the update() -> paint() cycle. You should call this method to get a component to repaint itself. If you have done anything to change the look of the component, but not its size ( like changing color, animating, etc. ) then call this method.
http://code.google.com/p/monad-tutorial/ is a work in progress to address exactly this question.
# Bloqueio facebook
for ip in `whois -h whois.radb.net '!gAS32934' | grep /`
do
iptables -A FORWARD -p all -d $ip -j REJECT
done
I guess you want
last_index = len(list1) - 1
which would store 3 in last_index
.
I think the problem is the way you call your javascript function. Your code is like so:
<input type="button" onclick="javascript: myFunc(myID)" value="button"/>
myID should be wrapped in quotes.
The proper way to do this is like so:
@ECHO off
SET MY_PATH=M:\Dir\^
With Spaces\Sub Folder^
\Dir\Folder
:: calls M:\Dir\With Spaces\Sub Folder\Dir\Folder\hello.bat
CALL "%MY_PATH%\hello.bat"
pause
It is a unary operator (taking a single argument) that is borrowed from C, where all data types are just different ways of interpreting bytes. It is the "invert" or "complement" operation, in which all the bits of the input data are reversed.
In Python, for integers, the bits of the twos-complement representation of the integer are reversed (as in b <- b XOR 1
for each individual bit), and the result interpreted again as a twos-complement integer. So for integers, ~x
is equivalent to (-x) - 1
.
The reified form of the ~
operator is provided as operator.invert
. To support this operator in your own class, give it an __invert__(self)
method.
>>> import operator
>>> class Foo:
... def __invert__(self):
... print 'invert'
...
>>> x = Foo()
>>> operator.invert(x)
invert
>>> ~x
invert
Any class in which it is meaningful to have a "complement" or "inverse" of an instance that is also an instance of the same class is a possible candidate for the invert operator. However, operator overloading can lead to confusion if misused, so be sure that it really makes sense to do so before supplying an __invert__
method to your class. (Note that byte-strings [ex: '\xff'
] do not support this operator, even though it is meaningful to invert all the bits of a byte-string.)
Here's an example that actually filters for BIN files. Also Windows now want you to save files to user locations, not system locations, so here's an example (you can use intellisense to browse the other options):
var saveFileDialog = new Microsoft.Win32.SaveFileDialog()
{
DefaultExt = "*.xml",
Filter = "BIN Files (*.bin)|*.bin",
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
};
var result = saveFileDialog.ShowDialog();
if (result != null && result == true)
{
// Save the file here
}
[UPDATED privacy keys list to iOS 13 - see below]
There is a list of all Cocoa Keys
that you can specify in your Info.plist
file:
(Xcode: Target -> Info -> Custom iOS Target Properties)
iOS already required permissions to access microphone, camera, and media library earlier (iOS 6, iOS 7), but since iOS 10 app will crash if you don't provide the description why you are asking for the permission (it can't be empty).
Privacy keys with example description:
Alternatively, you can open Info.plist
as source code:
And add privacy keys like this:
<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} always location use</string>
List of all privacy keys: [UPDATED to iOS 13]
NFCReaderUsageDescription
NSAppleMusicUsageDescription
NSBluetoothAlwaysUsageDescription
NSBluetoothPeripheralUsageDescription
NSCalendarsUsageDescription
NSCameraUsageDescription
NSContactsUsageDescription
NSFaceIDUsageDescription
NSHealthShareUsageDescription
NSHealthUpdateUsageDescription
NSHomeKitUsageDescription
NSLocationAlwaysUsageDescription
NSLocationUsageDescription
NSLocationWhenInUseUsageDescription
NSMicrophoneUsageDescription
NSMotionUsageDescription
NSPhotoLibraryAddUsageDescription
NSPhotoLibraryUsageDescription
NSRemindersUsageDescription
NSSiriUsageDescription
NSSpeechRecognitionUsageDescription
NSVideoSubscriberAccountUsageDescription
In the last months, two of my apps were rejected during the review because the camera usage description wasn't specifying what I do with taken photos.
I had to change the description from ${PRODUCT_NAME} need access to the camera to take a photo
to ${PRODUCT_NAME} need access to the camera to update your avatar
even though the app context was obvious (user tapped on the avatar).
It seems that Apple is now paying even more attention to the privacy usage descriptions, and we should explain in details why we are asking for permission.
This helped to me (in ionic, but idea is the same) https://mhartington.io/post/setting-input-focus/
in template:
<ion-item>
<ion-label>Home</ion-label>
<ion-input #input type="text"></ion-input>
</ion-item>
<button (click)="focusInput(input)">Focus</button>
in controller:
focusInput(input) {
input.setFocus();
}
From the documentation,
bool array_walk ( array &$array , callback $funcname [, mixed $userdata ] ) <-return bool
array_walk takes an array and a function F
and modifies it by replacing every element x with F(x)
.
array array_map ( callback $callback , array $arr1 [, array $... ] )<-return array
array_map does the exact same thing except that instead of modifying in-place it will return a new array with the transformed elements.
array array_filter ( array $input [, callback $callback ] )<-return array
array_filter with function F
, instead of transforming the elements, will remove any elements for which F(x)
is not true
Here are two methods, one sweet and simple(and conceptual), the other more formal and can be extended in a variety of situations, after having read a dataset.
Method 1: Conceptual
X2=[]
X1=[1,2,3]
X2.append(X1)
X3=[4,5,6]
X2.append(X3)
X2 thus has [[1,2,3],[4,5,6]] ie a list of lists.
Method 2 : Formal and extensible
Another elegant way to store a list as a list of lists of different numbers - which it reads from a file. (The file here has the dataset train) Train is a data-set with say 50 rows and 20 columns. ie. Train[0] gives me the 1st row of a csv file, train[1] gives me the 2nd row and so on. I am interested in separating the dataset with 50 rows as one list, except the column 0 , which is my explained variable here, so must be removed from the orignal train dataset, and then scaling up list after list- ie a list of a list. Here's the code that does that.
Note that I am reading from "1" in the inner loop since I am interested in explanatory variables only. And I re-initialize X1=[] in the other loop, else the X2.append([0:(len(train[0])-1)]) will rewrite X1 over and over again - besides it more memory efficient.
X2=[]
for j in range(0,len(train)):
X1=[]
for k in range(1,len(train[0])):
txt2=train[j][k]
X1.append(txt2)
X2.append(X1[0:(len(train[0])-1)])
Unfortunately, Date
object in javascript returns information about months only in numeric format. The faster thing you can do is to create an array of months (they are not supposed to change frequently!) and create a function which returns the name based on the number.
Something like this:
function getMonthNameByMonthNumber(mm) {
var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
return months[mm];
}
Your code therefore becomes:
var prnDt = "Printed on Thursday, " + now.getDate() + " " + getMonthNameByMonthNumber(now.getMonth) + " "+ now.getFullYear() + " at " + h + ":" + m + ":" s;
You can use IOUtils.write(byte[] data, OutputStream output) from Apache Commons IO.
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
byte[] encoded = key.getEncoded();
FileOutputStream output = new FileOutputStream(new File("target-file"));
IOUtils.write(encoded, output);
Oracle specific, and doesn't rely on pre-existing large tables or complicated system views over data dictionary objects.
SELECT c1 from dual
MODEL DIMENSION BY (1 as rn) MEASURES (sysdate as c1)
RULES ITERATE (365)
(c1[ITERATION_NUMBER]=SYSDATE-ITERATION_NUMBER)
order by 1
I think it's worth pointing out that there can be some unexpected behaviour here if you don't thoroughly understand how PRIMARY KEY and UNIQUE interact.
As an example, if you want to insert a record only if the NAME field isn't currently taken, and if it is, you want a constraint exception to fire to tell you, then INSERT OR REPLACE will not throw and exception and instead will resolve the UNIQUE constraint itself by replacing the conflicting record (the existing record with the same NAME). Gaspard's demonstrates this really well in his answer above.
If you want a constraint exception to fire, you have to use an INSERT statement, and rely on a separate UPDATE command to update the record once you know the name isn't taken.
With tidyr_1.0.0
, another option is pivot_longer
library(tidyr)
pivot_longer(df1, -c(Code, Country), values_to = "Value", names_to = "Year")
# A tibble: 10 x 4
# Code Country Year Value
# <fct> <fct> <chr> <fct>
# 1 AFG Afghanistan 1950 20,249
# 2 AFG Afghanistan 1951 21,352
# 3 AFG Afghanistan 1952 22,532
# 4 AFG Afghanistan 1953 23,557
# 5 AFG Afghanistan 1954 24,555
# 6 ALB Albania 1950 8,097
# 7 ALB Albania 1951 8,986
# 8 ALB Albania 1952 10,058
# 9 ALB Albania 1953 11,123
#10 ALB Albania 1954 12,246
df1 <- structure(list(Code = structure(1:2, .Label = c("AFG", "ALB"), class = "factor"),
Country = structure(1:2, .Label = c("Afghanistan", "Albania"
), class = "factor"), `1950` = structure(1:2, .Label = c("20,249",
"8,097"), class = "factor"), `1951` = structure(1:2, .Label = c("21,352",
"8,986"), class = "factor"), `1952` = structure(2:1, .Label = c("10,058",
"22,532"), class = "factor"), `1953` = structure(2:1, .Label = c("11,123",
"23,557"), class = "factor"), `1954` = structure(2:1, .Label = c("12,246",
"24,555"), class = "factor")), class = "data.frame", row.names = c(NA,
-2L))
ALT+SHIFT+G will create the auto generated comments for your method (place the cursor at starting position of your method).
I'm the author of the article in question.
No doubt there are multiple ways to do it, but the way I typically do it is to implement a custom UserDetails
that knows about roles and permissions. Role
and Permission
are just custom classes that you write. (Nothing fancy--Role
has a name and a set of Permission
instances, and Permission
has a name.) Then the getAuthorities()
returns GrantedAuthority
objects that look like this:
PERM_CREATE_POST
, PERM_UPDATE_POST
, PERM_READ_POST
instead of returning things like
ROLE_USER
, ROLE_MODERATOR
The roles are still available if your UserDetails
implementation has a getRoles()
method. (I recommend having one.)
Ideally you assign roles to the user and the associated permissions are filled in automatically. This would involve having a custom UserDetailsService
that knows how to perform that mapping, and all it has to do is source the mapping from the database. (See the article for the schema.)
Then you can define your authorization rules in terms of permissions instead of roles.
Hope that helps.
The answer is: for no good reason whatsoever.
Contrary to its name, the XmlSerializer
class is used not only for serialization, but also for deserialization. It performs certain checks on your class to make sure that it will work, and some of those checks are only pertinent to deserialization, but it performs them all anyway, because it does not know what you intend to do later on.
The check that your class fails to pass is one of the checks that are only pertinent to deserialization. Here is what happens:
During deserialization, the XmlSerializer
class will need to create
instances of your type.
In order to create an instance of a type, a constructor of that type needs to be invoked.
If you did not declare a constructor, the compiler has already supplied a default parameterless constructor, but if you did declare a constructor, then that's the only constructor available.
So, if the constructor that you declared accepts parameters, then the only way to instantiate your class is by invoking that constructor which accepts parameters.
However, XmlSerializer
is not capable of invoking any constructor
except a parameterless constructor, because it does not know what
parameters to pass to constructors that accept parameters. So, it checks to see if your class has a parameterless constructor, and since it does not, it fails.
So, if the XmlSerializer
class had been written in such a way as to only perform the checks pertinent to serialization, then your class would pass, because there is absolutely nothing about serialization that makes it necessary to have a parameterless constructor.
As others have already pointed out, the quick solution to your problem is to simply add a parameterless constructor. Unfortunately, it is also a dirty solution, because it means that you cannot have any readonly
members initialized from constructor parameters.
In addition to all this, the XmlSerializer
class could have been written in such a way as to allow even deserialization of classes without parameterless constructors. All it would take would be to make use of "The Factory Method Design Pattern" (Wikipedia). From the looks of it, Microsoft decided that this design pattern is far too advanced for DotNet programmers, who apparently should not be unnecessarily confused with such things. So, DotNet programmers should better stick to parameterless constructors, according to Microsoft.
A very simple example of __slot__
attribute.
__slots__
If I don't have __slot__
attribute in my class, I can add new attributes to my objects.
class Test:
pass
obj1=Test()
obj2=Test()
print(obj1.__dict__) #--> {}
obj1.x=12
print(obj1.__dict__) # --> {'x': 12}
obj1.y=20
print(obj1.__dict__) # --> {'x': 12, 'y': 20}
obj2.x=99
print(obj2.__dict__) # --> {'x': 99}
If you look at example above, you can see that obj1 and obj2 have their own x and y attributes and python has also created a dict
attribute for each object (obj1 and obj2).
Suppose if my class Test has thousands of such objects? Creating an additional attribute dict
for each object will cause lot of overhead (memory, computing power etc.) in my code.
__slots__
Now in the following example my class Test contains __slots__
attribute. Now I can't add new attributes to my objects (except attribute x
) and python doesn't create a dict
attribute anymore. This eliminates overhead for each object, which can become significant if you have many objects.
class Test:
__slots__=("x")
obj1=Test()
obj2=Test()
obj1.x=12
print(obj1.x) # --> 12
obj2.x=99
print(obj2.x) # --> 99
obj1.y=28
print(obj1.y) # --> AttributeError: 'Test' object has no attribute 'y'
There is no option to downgrade XAMPP. XAMPP is hardcoded with specific PHP version to make sure all the modules are compatible and working properly. However if your project needs PHP 5.6, you can just install a older version of XAMPP with PHP 5.6 packaged into it.
For me this worked:
<TextBlock Text="{Binding Date , StringFormat=g}" Width="130"/>
If want to show seconds also using G instead of g :
<TextBlock Text="{Binding Date , StringFormat=G}" Width="130"/>
Also if want for changing date type to another like Persian , using Language :
<TextBlock Text="{Binding Date , StringFormat=G}" Width="130" Language="fa-IR"/>
In your entity for that table, add the DatabaseGenerated
attribute above the column for which identity insert is set:
Example:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TaskId { get; set; }
The best solution that works for me without any problems looks this way:
1. Add temporary rule with some comment:
comment=$(cat /proc/sys/kernel/random/uuid | sed 's/\-//g')
iptables -A ..... -m comment --comment "${comment}" -j REQUIRED_ACTION
2. When the rule added and you wish to remove it (or everything with this comment), do:
iptables-save | grep -v "${comment}" | iptables-restore
So, you'll 100% delete all rules that match the $comment and leave other lines untouched. This solution works for last 2 months with about 100 changes of rules per day - no issues.Hope, it helps
Changing Bundle Identifier worked for me.
If it still doesn't work, try again with these steps before:
cd /Users/my_username/Library/MobileDevice/Provisioning Profiles && rm *
(in my case)If this is your detail.html
I don't see where do you load detail.js
?
Maybe this
<script src="js/index.js"></script>
should be this
<script src="js/detail.js"></script>
?
In my case, i got wifi problem. make sure you have valid internet connection
After that you have to parse the results. Suppose results are in integers, then
int testint1 = Integer.parse(test1);
Similarly others should be parsed. Now the results should be checked for two higher marks in them, by using if statement After that take out the average.
If you want to get this library into your library and use it, follow these steps:
You can create a new folder within Eclipse by right-clicking on your project, and selecting New Folder. The library folder is traditionally called lib
.
Drag and drop your jar folder into the new lib
folder, and when prompted select Copy Files.
Selecting the Project tab at the top of the screen, and click Properties.
Select Java Build Path followed by the Libraries tab.
Click the Add JARs… button and select your JAR file from within the lib
folder.
Your JAR file will now appear in both the lib
and Referenced Libraries folders. You can explore the JAR's resources by clicking Referenced Libraries.
Rather than giving an error or some sentinel value (e.g. '?') for inputs outside of 0-25, I sometimes find it useful to have a well-defined string for all integers. I like to use the following:
0 -> A
1 -> B
2 -> C
...
25 -> Z
26 -> AA
27 -> AB
28 -> AC
...
701 -> ZZ
702 -> AAA
...
This can be extended to negatives as well:
-1 -> -A
-2 -> -B
-3 -> -C
...
-26 -> -Z
-27 -> -AA
...
Java Code:
public static String toAlphabetic(int i) {
if( i<0 ) {
return "-"+toAlphabetic(-i-1);
}
int quot = i/26;
int rem = i%26;
char letter = (char)((int)'A' + rem);
if( quot == 0 ) {
return ""+letter;
} else {
return toAlphabetic(quot-1) + letter;
}
}
Python code, including the ability to use alphanumeric (base 36) or case-sensitive (base 62) alphabets:
def to_alphabetic(i,base=26):
if base < 0 or 62 < base:
raise ValueError("Invalid base")
if i < 0:
return '-'+to_alphabetic(-i-1)
quot = int(i)/base
rem = i%base
if rem < 26:
letter = chr( ord("A") + rem)
elif rem < 36:
letter = str( rem-26)
else:
letter = chr( ord("a") + rem - 36)
if quot == 0:
return letter
else:
return to_alphabetic(quot-1,base) + letter
The steps for schedule jobs in Jenkins:
@midnight
Note: under the schedule field, can see the last and the next date-time run.
Jenkins also supports predefined aliases to schedule build:
@hourly
, @daily
, @weekly
, @monthly
, @midnight
@hourly
--> Build every hour at the beginning of the hour --> 0 * * * *
@daily, @midnight
--> Build every day at midnight --> 0 0 * * *
@weekly
--> Build every week at midnight on Sunday morning --> 0 0 * * 0
@monthly
--> Build every month at midnight of the first day of the month --> 0 0 1 * *
Visual Code restart is needed if any update or install or clear cache
You could use the Chr(int) function
In Sql when any word contain @ sign it means it is variable and we use this variable to set value in it and use it on number area on the same sql script because it is only restricted on the single script while you can declare lot of variables of same type and name on many script. We use this variable in stored procedure lot because stored procedure are pre-compiled queries and we can pass values in these variable from script, desktop and websites for further information read Declare Local Variable, Sql Stored Procedure and sql injections.
Also read Protect from sql injection it will guide how you can protect your database.
Hope it help you to understand also any question comment me.
To list all of the packages in the active environment, use:
conda list
To list all of the packages in a deactivated environment, use:
conda list -n myenv
use net stop mysql57 instead, it should be the version that is not specified
Most of the answers suggest the Array.prototype.indexOf
method, the only problem is that it will not work on any IE version before IE9.
As an alternative I leave you two more options that will work on all browsers:
if (/Foo|Bar|Baz/.test(str)) {
// ...
}
if (str.match("Foo|Bar|Baz")) {
// ...
}
Class({
Namespace:ABC,
Name:"ClassL2",
Bases:[ABC.ClassTop],
Private:{
m_var:2
},
Protected:{
proval:2,
fight:Property(function(){
this.m_var--;
console.log("ClassL2::fight (m_var)" +this.m_var);
},[Property.Type.Virtual])
},
Public:{
Fight:function(){
console.log("ClassL2::Fight (m_var)"+this.m_var);
this.fight();
}
}
});
You could use regular expressions to replace the '\n' or '\n\r' characters with '<br />'.
you have this:
var h1 = document.createElement("h1");
h1.textContent = "This is a very long string and I would like to insert a carriage return HERE...
moreover, I would like to insert another carriage return HERE...
so this text will display in a new line";
you can replace your characters like this:
h1.innerHTML = h1.innerHTML.replace(/\n\r?/g, '<br />');
check the javascript reference for the String and Regex objects:
Note that the TIMEDIFF()
solution only works when the datetimes
are less than 35 days apart!
TIMEDIFF()
returns a TIME
datatype, and the max value for TIME is 838:59:59 hours (=34,96 days)
By design it is to be done this way:
OutputStream out = ...;
try (Writer w = new OutputStreamWriter(out, "UTF-8")) {
w.write("Hello, World!");
} // or w.close(); //close will auto-flush
user:Array[]=[1,2,3];
if(this.user.length)
{
console.log("user has contents");
}
else{
console.log("user is empty");
}
Nested classes relate to other classes a little differently than outer classes. Taking Java as an example:
Non-static nested classes have access to other members of the enclosing class, even if they are declared private. Also, non-static nested classes require an instance of the parent class to be instantiated.
OuterClass outerObj = new OuterClass(arguments);
outerObj.InnerClass innerObj = outerObj.new InnerClass(arguments);
There are several compelling reasons for using them:
If a class is useful to only one other class, then it is logical to relate and embed it in that class and keep the two together.
Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
A nested class usually relates to it's parent class and together form a "package"
You can have similar behavior in PHP without nested classes.
If all you want to achieve is structure/organization, as Package.OuterClass.InnerClass, PHP namespaces might sufice. You can even declare more than one namespace in the same file (although, due to standard autoloading features, that might not be advisable).
namespace;
class OuterClass {}
namespace OuterClass;
class InnerClass {}
If you desire to emulate other characteristics, such as member visibility, it takes a little more effort.
namespace {
class Package {
/* protect constructor so that objects can't be instantiated from outside
* Since all classes inherit from Package class, they can instantiate eachother
* simulating protected InnerClasses
*/
protected function __construct() {}
/* This magic method is called everytime an inaccessible method is called
* (either by visibility contrains or it doesn't exist)
* Here we are simulating shared protected methods across "package" classes
* This method is inherited by all child classes of Package
*/
public function __call($method, $args) {
//class name
$class = get_class($this);
/* we check if a method exists, if not we throw an exception
* similar to the default error
*/
if (method_exists($this, $method)) {
/* The method exists so now we want to know if the
* caller is a child of our Package class. If not we throw an exception
* Note: This is a kind of a dirty way of finding out who's
* calling the method by using debug_backtrace and reflection
*/
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
if (isset($trace[2])) {
$ref = new ReflectionClass($trace[2]['class']);
if ($ref->isSubclassOf(__CLASS__)) {
return $this->$method($args);
}
}
throw new \Exception("Call to private method $class::$method()");
} else {
throw new \Exception("Call to undefined method $class::$method()");
}
}
}
}
namespace Package {
class MyParent extends \Package {
public $publicChild;
protected $protectedChild;
public function __construct() {
//instantiate public child inside parent
$this->publicChild = new \Package\MyParent\PublicChild();
//instantiate protected child inside parent
$this->protectedChild = new \Package\MyParent\ProtectedChild();
}
public function test() {
echo "Call from parent -> ";
$this->publicChild->protectedMethod();
$this->protectedChild->protectedMethod();
echo "<br>Siblings<br>";
$this->publicChild->callSibling($this->protectedChild);
}
}
}
namespace Package\MyParent
{
class PublicChild extends \Package {
//Makes the constructor public, hence callable from outside
public function __construct() {}
protected function protectedMethod() {
echo "I'm ".get_class($this)." protected method<br>";
}
protected function callSibling($sibling) {
echo "Call from " . get_class($this) . " -> ";
$sibling->protectedMethod();
}
}
class ProtectedChild extends \Package {
protected function protectedMethod() {
echo "I'm ".get_class($this)." protected method<br>";
}
protected function callSibling($sibling) {
echo "Call from " . get_class($this) . " -> ";
$sibling->protectedMethod();
}
}
}
$parent = new Package\MyParent();
$parent->test();
$pubChild = new Package\MyParent\PublicChild();//create new public child (possible)
$protChild = new Package\MyParent\ProtectedChild(); //create new protected child (ERROR)
Output:
Call from parent -> I'm Package protected method
I'm Package protected method
Siblings
Call from Package -> I'm Package protected method
Fatal error: Call to protected Package::__construct() from invalid context
I really don't think trying to emulate innerClasses in PHP is such a good idea. I think the code is less clean and readable. Also, there are probably other ways to achieve similar results using a well established pattern such as the Observer, Decorator ou COmposition Pattern. Sometimes, even simple inheritance is sufficient.
if your using php for the backend maybe you can use this code.
// Validate image file size
if (($_FILES["file-input"]["size"] > 2000000)) {
$msg = "Image File Size is Greater than 2MB.";
header("Location: ../product.php?error=$msg");
exit();
}
If someone want to run it in PowerShell it works like below,
Run Powershell as Administrator
Then
setx /M PATH "$Env:PATH;<path to add>"
To verify, open another Powershell and view PATH as below,
$Env:PATH
TryParse is faster...
The first of these functions, Parse, is one that should be familiar to any .Net developer. This function will take a string and attempt to extract an integer out of it and then return the integer. If it runs into something that it can’t parse then it throws a FormatException or if the number is too large an OverflowException. Also, it can throw an ArgumentException if you pass it a null value.
TryParse is a new addition to the new .Net 2.0 framework that addresses some issues with the original Parse function. The main difference is that exception handling is very slow, so if TryParse is unable to parse the string it does not throw an exception like Parse does. Instead, it returns a Boolean indicating if it was able to successfully parse a number. So you have to pass into TryParse both the string to be parsed and an Int32 out parameter to fill in. We will use the profiler to examine the speed difference between TryParse and Parse in both cases where the string can be correctly parsed and in cases where the string cannot be correctly parsed.
The Convert class contains a series of functions to convert one base class into another. I believe that Convert.ToInt32(string) just checks for a null string (if the string is null it returns zero unlike the Parse) then just calls Int32.Parse(string). I’ll use the profiler to confirm this and to see if using Convert as opposed to Parse has any real effect on performance.
Hope this helps.
Tensorflow requires a 64-bit version of Python.
Additionally, it only supports Python 3.5.x through Python 3.8.x.
If you're using a 32-bit version of Python or a version that's too old or new, then you'll get that error message.
To fix it, you can install the 64-bit version of Python 3.8.6 via Python's website.
sqlite> create table t(id integer, col2 varchar(32), col3 varchar(8));
sqlite> insert into t values(1, 'he', 'ha');
sqlite>
sqlite> create table t2(id integer primary key, col2 varchar(32), col3 varchar(8));
sqlite> insert into t2 select * from t;
sqlite> .schema
CREATE TABLE t(id integer, col2 varchar(32), col3 varchar(8));
CREATE TABLE t2(id integer primary key, col2 varchar(32), col3 varchar(8));
sqlite> drop table t;
sqlite> alter table t2 rename to t;
sqlite> .schema
CREATE TABLE IF NOT EXISTS "t"(id integer primary key, col2 varchar(32), col3 varchar(8));
Is it possible to add onclick to a div and have it occur if any area of the div is clicked.
Yes … although it should be done with caution. Make sure there is some mechanism that allows keyboard access. Build on things that work
If yes then why is the onclick method not going through to my div.
You are assigning a string where a function is expected.
divTag.onclick = printWorking;
There are nicer ways to assign event handlers though, although older versions of Internet Explorer are sufficiently different that you should use a library to abstract it. There are plenty of very small event libraries and every major library jQuery) has event handling functionality.
That said, now it is 2019, older versions of Internet Explorer no longer exist in practice so you can go direct to addEventListener
On reason for an Error of: "Editor does not contain a main type"
Error encountered in: Eclipse Neon
Operating System: Windows 10 Pro
When you copy your source folders over from a thumb-drive and leave out the Eclipse_Projects.metadata folder.
Other than a fresh install, you will have to make sure you merge the files from (Thrumb-drive)F:Eclipse_Projects.metadata.plugins .
These plug-ins are the bits and pieces of library code taken from the SDK when a class is created. I really all depends on what you-----import javax.swing.*;----- into your file. Because your transferring it over make sure to merge the ------Eclipse_Projects.metadata.plugins------ manually with a simple copy and paste, while accepting the skip feature for already present plugins in your Folder.
For windows 10: you can find your working folders following a similar pattern of file hierarchy.
C:Users>Mikes Laptop> workspace > .metadata > .plugins <---merge plugins here
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/jsp-api-6.0.16.jar
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/servlet-api-6.0.16.jar
You should not have any server-specific libraries in the /WEB-INF/lib
. Leave them in the appserver's own library. It would only lead to collisions in the classpath. Get rid of all appserver-specific libraries in /WEB-INF/lib
(and also in JRE/lib
and JRE/lib/ext
if you have placed any of them there).
A common cause that the appserver-specific libraries are included in the webapp's library is that starters think that it is the right way to fix compilation errors of among others the javax.servlet
classes not being resolveable. Putting them in webapp's library is the wrong solution. You should reference them in the classpath during compilation, i.e. javac -cp /path/to/server/lib/servlet.jar
and so on, or if you're using an IDE, you should integrate the server in the IDE and associate the web project with the server. The IDE will then automatically take server-specific libraries in the classpath (buildpath) of the webapp project.
I would choose this simple solution.
Summarizing it:
#S
and sends it to the Clienth(pw)
(which is what is stored in the DB)#C
h(pw) + #S + #C
and calculates its hash, call it h(all)
username
, #C
and h(all)
h(pw)'
for the specified username
, from the DBh(all')
, like Client didh(all)
= h(all')
then h(pw)
= h(pw)'
, almost certainlyNo one can repeat the request to log in as the specified user. #S
adds a variable component to the hash, each time (it's fundamental). #C
adds additional noise in it.
Here is a jsfiddle so you can see an example of this working.
HTML code:
<div class="circle"></div>
CSS code:
.circle {_x000D_
/*This creates a 1px solid red border around your element(div) */_x000D_
border:1px solid red;_x000D_
background-color: #FFFFFF;_x000D_
height: 100px;_x000D_
/* border-radius 50% will make it fully rounded. */_x000D_
border-radius: 50%;_x000D_
-moz-border-radius:50%;_x000D_
-webkit-border-radius: 50%;_x000D_
width: 100px;_x000D_
}
_x000D_
<div class='circle'></div>
_x000D_
Although using '@' is more appropriate than using '=' for your particular scenario, sometimes I use '=' so that I don't have to remember to use attrs.$observe():
<su-label tooltip="field.su_documentation">{{field.su_name}}</su-label>
Directive:
myApp.directive('suLabel', function() {
return {
restrict: 'E',
replace: true,
transclude: true,
scope: {
title: '=tooltip'
},
template: '<label><a href="#" rel="tooltip" title="{{title}}" data-placement="right" ng-transclude></a></label>',
link: function(scope, element, attrs) {
if (scope.title) {
element.addClass('tooltip-title');
}
},
}
});
With '=' we get two-way databinding, so care must be taken to ensure scope.title is not accidentally modified in the directive. The advantage is that during the linking phase, the local scope property (scope.title) is defined.
Technically you can apply styles programmatically, with custom views anyway:
private MyRelativeLayout extends RelativeLayout {
public MyRelativeLayout(Context context) {
super(context, null, R.style.LightStyle);
}
}
The one argument constructor is the one used when you instantiate views programmatically.
So chain this constructor to the super that takes a style parameter.
RelativeLayout someLayout = new MyRelativeLayout(new ContextThemeWrapper(this,R.style.RadioButton));
Or as @Dori pointed out simply:
RelativeLayout someLayout = new RelativeLayout(new ContextThemeWrapper(activity,R.style.LightStyle));
Now in Kotlin:
class MyRelativeLayout @JvmOverloads constructor(
context: Context,
attributeSet: AttributeSet? = null,
defStyleAttr: Int = R.style.LightStyle,
) : RelativeLayout(context, attributeSet, defStyleAttr)
or
val rl = RelativeLayout(ContextThemeWrapper(activity, R.style.LightStyle))
Use this annotation
@RequestMapping(value = "/url", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON})
For react-native users who don't use Xcode often, you can just use find
. Open a terminal and search by with the database name.
$ find ~/Library/Developer -name 'myname.db'
If you don't know the exact name you can use wildcards:
$ find ~/Library/Developer -name 'myname.*'
A simple way to find unique common elements of lists a and b:
a = [1,2,3]
b = [3,6,2]
for both in set(a) & set(b):
print(both)
I would use .*
. .
matches any character, *
signifies 0 or more occurrences. You might need a DOTALL switch to the regex to capture new lines with .
.
What you are seeing here is not an overloaded +
oparator, but autoboxing behaviour. The Integer
class is immutable and your code:
Integer i = 0;
i = i + 1;
is seen by the compiler (after the autoboxing) as:
Integer i = Integer.valueOf(0);
i = Integer.valueOf(i.intValue() + 1);
so you are correct in your conclusion that the Integer
instance is changed, but not sneakily - it is consistent with the Java language definition :-)
Try this I am also not 100 % sure
for( int i = 0 ;i< dt.Rows.Count; i++)
{
If(dt.Rows[i].Product_id == 2)
{
dt.Rows[i].Columns["Product_name"].ColumnName = "cde";
}
}
The move_uploaded_file
will return false if the file was not successfully moved you can put something into your code to alert you in a log if that happens, that should help you figure out why your having trouble renaming the file
If you just do eval $cmd
when we do cmd="ls -l"
(interactively and in a script) we get the desired result. In your case, you have a pipe with a grep without a pattern, so the grep part will fail with an error message. Just $cmd
will generate a "command not found" (or some such) message.
So try use eval and use a finished command, not one that generates an error message.
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
In the package explorer, in the upper right corner of the view, there is a little down arrow. Tool tip will say view menu. From that menu, select filters
From there, uncheck .* resources.
So Package Explorer -> View Menu -> Filters -> uncheck .* resources
.
With Eclipse Kepler and OS X this is a bit different:
Package Explorer -> Customize View -> Filters -> uncheck .* resources
from PIL import Image
image = Image.open('File.jpg')
image.show()
You can simply implement your own compare function
[compareWith]="compareItems"
See as well the docu. So the complete code would look like:
<div>
<mat-select
[(value)]="selected2" [compareWith]="compareItems">
<mat-option
*ngFor="let option of options2"
value="{{ option.id }}">
{{ option.name }}
</mat-option>
</mat-select>
</div>
and in the Typescript file:
compareItems(i1, i2) {
return i1 && i2 && i1.id===i2.id;
}
Yes you can use setValue to set value for edit/update purpose.
this.personalform.setValue({
name: items.name,
address: {
city: items.address.city,
country: items.address.country
}
});
You can refer http://musttoknow.com/use-angular-reactive-form-addinsert-update-data-using-setvalue-setpatch/ to understand how to use Reactive forms for add/edit feature by using setValue. It saved my time
In C++ (but not plain C), it's perfectly legal to typedef a type twice, so long as both definitions are completely identical:
// foo.h
struct A{};
typedef A *PA;
// bar.h
struct A; // forward declare A
typedef A *PA;
void func(PA x);
// baz.cc
#include "bar.h"
#include "foo.h"
// We've now included the definition for PA twice, but it's ok since they're the same
...
A x;
func(&x);
Just had the same error message, but when I was running a package.json with:
"scripts": {
"build": "tsc -p ./src",
}
tsc
is the command to run the TypeScript compiler.
I never had any issues with this project because I had TypeScript installed as a global module. As this project didn't include TypeScript as a dev dependency (and expected it to be installed as global), I had the error when testing in another machine (without TypeScript) and running npm install
didn't fix the problem. So I had to include TypeScript as a dev dependency (npm install typescript --save-dev
) to solve the problem.
You should always include the table name in the SQL query when dealing with associations.
Indeed if another table has the user_id
column and you join both tables, you will have an ambiguous column name in the SQL query (i.e. troubles).
So, in your example:
GroupUser.where("groups_users.user_id != ?", me)
Or a bit more verbose:
GroupUser.where("#{table_name}.user_id IS NOT ?", me)
Note that if you are using a hash, you don't need to worry about that because Rails takes care of it for you:
GroupUser.where(user: me)
In Rails 4, as said by @dr4k3, the query method not
has been added:
GroupUser.where.not(user: me)
Don't use doubles. You can lose some precision. Here's a general purpose function.
public static double round(double unrounded, int precision, int roundingMode)
{
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
You can call it with
round(yourNumber, 3, BigDecimal.ROUND_HALF_UP);
"precision" being the number of decimal points you desire.
From the XML specification:
To allow attribute values to contain both single and double quotes, the apostrophe or single-quote character (') may be represented as "'", and the double-quote character (") as """.
There are a few things wrong here:
First, terminology. "Epoch" refers to the starting point of something. The "Unix Epoch" is Midnight, January 1st 1970 UTC. You can't convert an arbitrary "date string to epoch". You probably meant "Unix Time", which is often erroneously called "Epoch Time".
.unix()
returns Unix Time in whole seconds, but the default moment
constructor accepts a timestamp in milliseconds. You should instead use .valueOf()
to return milliseconds. Note that calling .unix()*1000
would also work, but it would result in a loss of precision.
You're parsing a string without providing a format specifier. That isn't a good idea, as values like 1/2/2014 could be interpreted as either February 1st or as January 2nd, depending on the locale of where the code is running. (This is also why you get the deprecation warning in the console.) Instead, provide a format string that matches the expected input, such as:
moment("10/15/2014 9:00", "M/D/YYYY H:mm")
.calendar()
has a very specific use. If you are near to the date, it will return a value like "Today 9:00 AM". If that's not what you expected, you should use the .format()
function instead. Again, you may want to pass a format specifier.
To answer your questions in comments, No - you don't need to call .local()
or .utc()
.
Putting it all together:
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").valueOf();
var m = moment(ts);
var s = m.format("M/D/YYYY H:mm");
alert("Values are: ts = " + ts + ", s = " + s);
On my machine, in the US Pacific time zone, it results in:
Values are: ts = 1413388800000, s = 10/15/2014 9:00
Since the input value is interpreted in terms of local time, you will get a different value for ts
if you are in a different time zone.
Also note that if you really do want to work with whole seconds (possibly losing precision), moment has methods for that as well. You would use .unix()
to return the timestamp in whole seconds, and moment.unix(ts)
to parse it back to a moment.
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").unix();
var m = moment.unix(ts);
Well, the selected answer doesn't work if you forked your branch out of unspecific branch (i.e., not master
or develop
).
Here I offer a another way I am using in my pre-push
git hooks.
# Run production build before push
echo "[INFO] run .git/hooks/pre-push"
echo "[INFO] Check if only one commit"
# file .git/hooks/pre-push
currentBranch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')
gitLog=$(git log --graph --abbrev-commit --decorate --first-parent HEAD)
commitCountOfCurrentBranch=0
startCountCommit=""
baseBranch=""
while read -r line; do
# if git log line started with something like "* commit aaface7 (origin/BRANCH_NAME)" or "commit ae4f131 (HEAD -> BRANCH_NAME)"
# that means it's on our branch BRANCH_NAME
matchedCommitSubstring="$( [[ $line =~ \*[[:space:]]commit[[:space:]].*\((.*)\) ]] && echo ${BASH_REMATCH[1]} )"
if [[ ! -z ${matchedCommitSubstring} ]];then
if [[ $line =~ $currentBranch ]];then
startCountCommit="true"
else
startCountCommit=""
if [[ -z ${baseBranch} ]];then
baseBranch=$( [[ ${matchedCommitSubstring} =~ (.*)\, ]] && echo ${BASH_REMATCH[1]} || echo ${matchedCommitSubstring} )
fi
fi
fi
if [[ ! -z ${startCountCommit} && $line =~ ^\*[[:space:]]commit[[:space:]] ]];then
((commitCountOfCurrentBranch++))
fi
done <<< "$gitLog"
if [[ -z ${baseBranch} ]];then
baseBranch="origin/master"
else
baseBranch=$( [[ ${baseBranch} =~ ^(.*)\, ]] && echo ${BASH_REMATCH[1]} || echo ${baseBranch} )
fi
echo "[INFO] Current commit count of the branch ${currentBranch}: ${commitCountOfCurrentBranch}"
if [[ ${commitCountOfCurrentBranch} -gt 1 ]];then
echo "[ERROR] Only a commit per branch is allowed. Try run 'git rebase -i ${baseBranch}'"
exit 1
fi
For more analysis, please visit my blog
If you say that it works with accessing directly manageproducts.do?option=1
in the browser then it should work with:
$.get('manageproducts.do', { option: '1' }, function(data) {
...
});
as it would send the same GET request.
Just create a new branch with git checkout -b ABC_1
; your uncommitted changes will be kept, and you then commit them to that branch.
JSON is JavaScript Object Notation. It is a much-more compact way of transmitting sets of data across network connections as compared to XML. I suggest JSON be used in any AJAX-like applications where XML would otherwise be the "recommended" option. The verbosity of XML will add to download time and increased bandwidth consumption ($$$). You can accomplish the same effect with JSON and its mark-up is almost exclusively dedicated to the data itself and not the underlying structure.
The general idea of abstract classes and interfaces is to be extended/implemented by other classes (cannot be constructed alone) that use these general "settings" (some kind of a template), making it simple to set a specific-general behaviour for all the objects that later extend it.
An abstract class has regular methods set AND abstract methods. Extended classes can include unset methods after being extended by an abstract class. When setting abstract methods - they are defined by the classes that are extending it later.
Interfaces have the same properties as an abstract class, but includes only abstract methods, which could be implemented in an other class/es (and can be more than one interface to implement), this creates a more permanent-solid definishion of methods/static variables. Unlike the abstract class, you cannot add custom "regular" methods.
MYISAM:
INNODB:
Solution in Kotlin (will work in Java too, of course), which includes both cases of when you know the size or not:
fun InputStream.readBytesWithSize(size: Long): ByteArray? {
return when {
size < 0L -> this.readBytes()
size == 0L -> ByteArray(0)
size > Int.MAX_VALUE -> null
else -> {
val sizeInt = size.toInt()
val result = ByteArray(sizeInt)
readBytesIntoByteArray(result, sizeInt)
result
}
}
}
fun InputStream.readBytesIntoByteArray(byteArray: ByteArray,bytesToRead:Int=byteArray.size) {
var offset = 0
while (true) {
val read = this.read(byteArray, offset, bytesToRead - offset)
if (read == -1)
break
offset += read
if (offset >= bytesToRead)
break
}
}
If you know the size, it saves you on having double the memory used compared to the other solutions (in a brief moment, but still could be useful). That's because you have to read the entire stream to the end, and then convert it to a byte array (similar to ArrayList which you convert to just an array).
So, if you are on Android, for example, and you got some Uri to handle, you can try to get the size using this:
fun getStreamLengthFromUri(context: Context, uri: Uri): Long {
context.contentResolver.query(uri, arrayOf(MediaStore.MediaColumns.SIZE), null, null, null)?.use {
if (!it.moveToNext())
return@use
val fileSize = it.getLong(it.getColumnIndex(MediaStore.MediaColumns.SIZE))
if (fileSize > 0)
return fileSize
}
//if you wish, you can also get the file-path from the uri here, and then try to get its size, using this: https://stackoverflow.com/a/61835665/878126
FileUtilEx.getFilePathFromUri(context, uri, false)?.use {
val file = it.file
val fileSize = file.length()
if (fileSize > 0)
return fileSize
}
context.contentResolver.openInputStream(uri)?.use { inputStream ->
if (inputStream is FileInputStream)
return inputStream.channel.size()
else {
var bytesCount = 0L
while (true) {
val available = inputStream.available()
if (available == 0)
break
val skip = inputStream.skip(available.toLong())
if (skip < 0)
break
bytesCount += skip
}
if (bytesCount > 0L)
return bytesCount
}
}
return -1L
}
You could try with this for mime type
$image = getimagesize($_FILES['image']['tmp_name']);
$image['mime']
will return the mime type.
This function doesn't require GD library. You can find the documentation here.
This returns the mime type of the image.
Some people use the $_FILES["file"]["type"]
but it's not reliable as been given by the browser and not by PHP.
You can use pathinfo()
as ThiefMaster suggested to retrieve the image extension.
First make sure that the image is being uploaded successfully while in development before performing any operations with the image.
NOTE! "The static factory method is NOT the same as the Factory Method pattern" (c) Effective Java, Joshua Bloch.
Factory Method: "Define an interface for creating an object, but let the classes which implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses" (c) GoF.
"Static factory method is simply a static method that returns an instance of a class." (c) Effective Java, Joshua Bloch. Usually this method is inside a particular class.
The difference:
The key idea of static factory method is to gain control over object creation and delegate it from constructor to static method. The decision of object to be created is like in Abstract Factory made outside the method (in common case, but not always). While the key (!) idea of Factory Method is to delegate decision of what instance of class to create inside Factory Method. E.g. classic Singleton implementation is a special case of static factory method. Example of commonly used static factory methods:
It should also be mentioned that <span>
tags allow inside them -- block-level items negate MD natively inside them unless you configure them not to do so, but in-line styles natively allow MD within them. As such, I often do something akin to...
This is a superfluous paragraph thing.
<span class="class-red">And thus I delve into my topic, Lorem ipsum lollipop bubblegum.</span>
And thus with that I conclude.
I am not 100% sure if this is universal but seems to be the case in all MD editors I've used.
The following API can be used in c++ as shown in my article.
You need to define several constants:
//
#define GroupAdmin <YOUR GROUP ADMIN MOBILE PHONE>
#define GroupName <YOUR GROUP NAME>
#define CLIENT_ID <YOUR CLIENT ID>
#define CLIENT_SECRET <YOUR CLIENT SECRET>
#define GROUP_API_SERVER L"api.whatsmate.net"
#define GROUP_API_PATH L"/v3/whatsapp/group/text/message/12"
#define IMAGE_SINGLE_API_URL L"http://api.whatsmate.net/v3/whatsapp/group/image/message/12"
//
Then you connect to the API’s endpoint.
hOpenHandle = InternetOpen(_T("HTTP"), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (hOpenHandle == NULL)
{
return false;
}
hConnectHandle = InternetConnect(hOpenHandle,
GROUP_API_SERVER,
INTERNET_DEFAULT_HTTP_PORT,
NULL, NULL, INTERNET_SERVICE_HTTP,
0, 1);
if (hConnectHandle == NULL)
{
InternetCloseHandle(hOpenHandle);
return false;
}
Then send both header and body and wait for the result that needs to be “OK”.
Step 1 - open an HTTP request:
const wchar_t *AcceptTypes[] = { _T("application/json"),NULL };
HINTERNET hRequest = HttpOpenRequest(hConnectHandle, _T("POST"), GROUP_API_PATH, NULL, NULL, AcceptTypes, 0, 0);
if (hRequest == NULL)
{
InternetCloseHandle(hConnectHandle);
InternetCloseHandle(hOpenHandle);
return false;
}
Step 2 - send the header:
std::wstring HeaderData;
HeaderData += _T("X-WM-CLIENT-ID: ");
HeaderData += _T(CLIENT_ID);
HeaderData += _T("\r\nX-WM-CLIENT-SECRET: ");
HeaderData += _T(CLIENT_SECRET);
HeaderData += _T("\r\n");
HttpAddRequestHeaders(hRequest, HeaderData.c_str(), HeaderData.size(), NULL);
Step 3 - send the message:
std::wstring WJsonData;
WJsonData += _T("{");
WJsonData += _T("\"group_admin\":\"");
WJsonData += groupAdmin;
WJsonData += _T("\",");
WJsonData += _T("\"group_name\":\"");
WJsonData += groupName;
WJsonData += _T("\",");
WJsonData += _T("\"message\":\"");
WJsonData += message;
WJsonData += _T("\"");
WJsonData += _T("}");
const std::string JsonData(WJsonData.begin(), WJsonData.end());
bResults = HttpSendRequest(hRequest, NULL, 0, (LPVOID)(JsonData.c_str()), JsonData.size());
Now just check the result:
TCHAR StatusText[BUFFER_LENGTH] = { 0 };
DWORD StatusTextLen = BUFFER_LENGTH;
HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_TEXT, &StatusText, &StatusTextLen, NULL);
bResults = (StatusTextLen && wcscmp(StatusText, L"OK")==FALSE);
Quoting directly from the help page for factor
:
To transform a factor f to its original numeric values, as.numeric(levels(f))[f]
is recommended and slightly more efficient than as.numeric(as.character(f))
.
I modify it in the .env APP_TIMEZONE.
For Colombia: APP_TIMEZONE = America / Bogota also for paris like this: APP_TIMEZONE = Europe / Paris
cat >> filename
This is text, perhaps pasted in from some other source.
Or else entered at the keyboard, doesn't matter.
^D
Essentially, you can dump any text you want into the file. CTRL-D sends an end-of-file signal, which terminates input and returns you to the shell.
Once you are in terminal/command line, access the database/collection you want to use as follows:
show dbs
use <db name>
show collections
choose your collection and type the following to see all contents of that collection:
db.collectionName.find()
More info here on the MongoDB Quick Reference Guide.
It's a linker error. ld
is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.
The error message tells you that none of the object files you're linking against contains a definition for avergecolumns
. The reason for that is that the function you've defined is called averagecolumns
(in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).
You can do it using AVD Manager, choose Tools -> Options. Set HTTP Proxy Server to 8.8.8.8,8.8.4.4
The emulator will be connected.
Use Gradle to build your project, then the jar is within the build file. Here is a Stack Overflow link on how to build .jar files with Gradle.
Java project with Gradle and building jar file in Intellij IDEA - how to?
This work for me now and today at Angular version 9
You need to use these parameters in your list view:
Scroll
lv.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
Set the head of the list to it bottom
lv.setStackFromBottom(true);
You can also set these parameters in XML, eg. like this:
<ListView
...
android:transcriptMode="alwaysScroll"
android:stackFromBottom="true" />
Ok, at that time got it done with the help of a friend and the code looks like this.
Sub Saving()
Dim part1 As String
Dim part2 As String
part1 = Range("C5").Value
part2 = Range("C8").Value
ActiveWorkbook.SaveAs Filename:= _
"C:\-docs\cmat\Desktop\pieteikumi\" & part1 & " " & part2 & ".xlsm", FileFormat:= _
xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End Sub
How do I edit this part (FileFormat:= _ xlOpenXMLWorkbookMacroEnabled) for it to save as Excel 97-2013 Workbook, have tried several variations with no success. Thankyou
Seems, that I found the solution, but my idea is flawed. By doing this FileFormat:= _ xlOpenXMLWorkbook, it drops out a popup saying, the you cannot save this workbook as a file without Macro enabled. So, is this impossible?
The issue is two-fold:
As a prerequisite (as of August, 2016), you need to link an AdSense account and then turn on monetization in your YouTube channel. It's a painful change that broke a lot of live streams.
You will need to use the following URL format for the embed:
<iframe width="560" height="315" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID&autoplay=1" frameborder="0" allowfullscreen></iframe>
The &autoplay=1
is not necessary, but I like to include it. Change CHANNEL
to your channel's ID. One thing to note is that WordPress may reformat the URL once you commit your change. Therefore, you'll need a plugin that allows you to use raw code and not have it override. Using a custom PHP code plugin can help and you would just echo the code like so:
<?php echo '<iframe width="560" height="315" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID&autoplay=1" frameborder="0" allowfullscreen></iframe>'; ?>
Let me know if that worked for you!
(In reply to the "has the situation improved?" part of the question):
Unfortunately, not really. Illustrator's support for SVG has always been a little shaky, and, having mucked around in Illustrator's internals, I doubt we'll see much improvement as far as Illustrator is concerned.
If you're looking for DOM-style access to an Illustrator document, you might want to check out Hanpuku (Disclosure #1: I'm the author. Disclosure #2: It's research code, meaning there are bugs aplenty, and future support is unlikely).
With Hanpuku, you could do something like:
In the script editor, type:
selection.attr('d', 'M 0 0 L 20 134 L 233 24 Z');
Click run
Granted, this approach doesn't expose the original path string. If you follow the instructions toward the end of the plugin's welcome page, it's possible to edit the Illustrator document with Chrome's developer tools, but there will be lots of ugly engineering exposed everywhere (the SVG DOM that mirrors the Illustrator document is buried inside an iframe deep in the extension—changing the DOM with Chrome's tools and clicking "To Illustrator" should still work, but you will likely encounter lots of problems).
TL;DR: Illustrator uses an internal model that's pretty different from SVG in a lot of ways, meaning that when you iterate between the two, currently, your only choice is to use the subset of features that both support in the same way.
Flexbox works.
.box{_x000D_
display: flex;_x000D_
flex-flow: row nowrap;_x000D_
justify-content: center;_x000D_
align-content: center;_x000D_
align-items:center;_x000D_
border:1px solid #e3f2fd;_x000D_
}_x000D_
.item{_x000D_
flex: 1 1 auto;_x000D_
border:1px solid #ffebee;_x000D_
}
_x000D_
<div class="box">_x000D_
<p class="item">A</p>_x000D_
<p class="item">B</p>_x000D_
<p class="item">C</p>_x000D_
</div>
_x000D_
I solved this problem by programmatically creating the Labels and Textfields, and then Command-Dragged from the little empty circles on the left of the code to the components on the Storyboard. To illustrate my point: I wrote @IBOutlet weak var HelloLabel: UILabel!
, and then pressed Command and dragged the code into the component on the storyboard.
That DateTime format is actually ISO 8601 DateTime. JSON does not specify any particular format for dates/times. If you Google a bit, you will find plenty of implementations to parse it in Java.
If you are open to using something other than Java's built-in Date/Time/Calendar classes, I would also suggest Joda Time. They offer (among many things) a ISODateTimeFormat
to parse these kinds of strings.
$(':checkbox').change(function(){
$('#delete').removeAttr('hidden');
});
Note, thanks to tip by A.Wolff
, you should use removeAttr
instead of setting to false. When set to false, the element will still be hidden. Therefore, removing is more effective.
I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.
ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
-- Perform more appropriate alters
ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl)
REFERENCES User_tbl(appId);
-- Perform all appropriate alters to bring the key constraints back
However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
@Override
public void handle(WindowEvent event) {
Platform.exit();
System.exit(0);
}
});
None of these worked for me in SSIS v18.0, so I would up doing something like this:
WHERE CHARINDEX('_', thingyoursearching) < 1
..where I am trying to ignore strings with an underscore in them. If you want to find things that have an underscore, just flip it around:
WHERE CHARINDEX('_', thingyoursearching) > 0
It looks like you may be confused as to when commands are run. In your example, you are calling the get
method before the GUI has a chance to be displayed on the screen (which happens after you call mainloop
.
Try adding a button that calls the get
method. This is much easier if you write your application as a class. For example:
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.entry = tk.Entry(self)
self.button = tk.Button(self, text="Get", command=self.on_button)
self.button.pack()
self.entry.pack()
def on_button(self):
print(self.entry.get())
app = SampleApp()
app.mainloop()
Run the program, type into the entry widget, then click on the button.
$id = $access_data['Privilege']['id'];
if(!in_array($id,$user_access_arr));
$user_access_arr[] = $id;
$this->Session->setFlash(__('Access Denied! You are not eligible to access this.'), 'flash_custom_success');
return $this->redirect(array('controller'=>'Dashboard','action'=>'index'));
There are two ways to mount files into your container. It looks like you want a bind mount.
This mounts local files directly into the container's filesystem. The containerside path and the hostside path both point to the same file. Edits made from either side will show up on both sides.
? echo foo > ./foo
? docker run --mount type=bind,source=$(pwd)/foo,target=/foo -it debian:latest
# cat /foo
foo # local file shows up in container
? echo 'bar' > ./foo # make a hostside change
# cat /foo
bar # the hostside change shows up
# echo baz > /foo # make a containerside change
# exit
? cat foo
baz # the containerside change shows up
? docker run --mount type=volume,source=foovolume,target=/foo -it debian:latest
root@containerB# echo 'this is in a volume' > /foo/data
? docker volume ls
DRIVER VOLUME NAME
local foovolume
? docker run --mount type=volume,source=foovolume,target=/foo -it debian:latest
root@containerC:/# cat /foo/data
this is in a volume # data is still available
-v
vs --mount
These do the same thing. -v
is more concise, --mount
is more explicit.
bind mounts
-v /hostside/path:/containerside/path
--mount type=bind,source=/hostside/path,target=/containerside/path
volume mounts
-v /containerside/path
-v volumename:/containerside/path
--mount type=volume,source=volumename,target=/containerside/path
(If a volume name is not specified, a random one is chosen.)
The documentaion tries to convince you to use one thing in favor of another instead of just telling you how it works, which is confusing.
This works for me, using Microsoft SQL Server 2005:
DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,'2009-05-01')+1,0))
Get-Content
has bad performance; it tries to read the file into memory all at once.
C# (.NET) file reader reads each line one by one
Best Performace
foreach($line in [System.IO.File]::ReadLines("C:\path\to\file.txt"))
{
$line
}
Or slightly less performant
[System.IO.File]::ReadLines("C:\path\to\file.txt") | ForEach-Object {
$_
}
The foreach
statement will likely be slightly faster than ForEach-Object
(see comments below for more information).
As Yaron mentioned, there isn't any difference between where
and filter
.
filter
is an overloaded method that takes a column or string argument. The performance is the same, regardless of the syntax you use.
We can use explain()
to see that all the different filtering syntaxes generate the same Physical Plan. Suppose you have a dataset with person_name
and person_country
columns. All of the following code snippets will return the same Physical Plan below:
df.where("person_country = 'Cuba'").explain()
df.where($"person_country" === "Cuba").explain()
df.where('person_country === "Cuba").explain()
df.filter("person_country = 'Cuba'").explain()
These all return this Physical Plan:
== Physical Plan ==
*(1) Project [person_name#152, person_country#153]
+- *(1) Filter (isnotnull(person_country#153) && (person_country#153 = Cuba))
+- *(1) FileScan csv [person_name#152,person_country#153] Batched: false, Format: CSV, Location: InMemoryFileIndex[file:/Users/matthewpowers/Documents/code/my_apps/mungingdata/spark2/src/test/re..., PartitionFilters: [], PushedFilters: [IsNotNull(person_country), EqualTo(person_country,Cuba)], ReadSchema: struct<person_name:string,person_country:string>
The syntax doesn't change how filters are executed under the hood, but the file format / database that a query is executed on does. Spark will execute the same query differently on Postgres (predicate pushdown filtering is supported), Parquet (column pruning), and CSV files. See here for more details.
$string = "Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don't know how long maybe around 1000 characters. Anyway this should be over 50 characters know...";
if(strlen($string) >= 50)
{
echo substr($string, 50); //prints everything after 50th character
echo substr($string, 0, 50); //prints everything before 50th character
}
The following code will allow you to have two headings on the same line, the first left-aligned and the second right-aligned, and has the added advantage of keeping both headings on the same baseline.
The HTML Part:
<h1 class="text-left-right">
<span class="left-text">Heading Goes Here</span>
<span class="byline">Byline here</span>
</h1>
And the CSS:
.text-left-right {
text-align: right;
position: relative;
}
.left-text {
left: 0;
position: absolute;
}
.byline {
font-size: 16px;
color: rgba(140, 140, 140, 1);
}
I faced to this problem when my membership was expired and I renewed it. I use xCode6 and I solve this problem by revoking expired developer certificate from Member Center and cleaning build folder ( alt+[Product>Clean] ). xCode handle others issue itself.
See "Replacing Expired Certificates" section on this link: https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/MaintainingCertificates/MaintainingCertificates.html
For Searchview
use these code
For XML
<android.support.v7.widget.SearchView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/searchView">
</android.support.v7.widget.SearchView>
In your Fragment or Activity
package com.example.user.salaryin;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.user.salaryin.Adapter.BusinessModuleAdapter;
import com.example.user.salaryin.Network.ApiClient;
import com.example.user.salaryin.POJO.ProductDetailPojo;
import com.example.user.salaryin.Service.ServiceAPI;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class OneFragment extends Fragment implements SearchView.OnQueryTextListener {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
ArrayList<ProductDetailPojo> arrayList;
BusinessModuleAdapter adapter;
private ProgressDialog pDialog;
GridLayoutManager gridLayoutManager;
SearchView searchView;
public OneFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.one_fragment,container,false);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
searchView=(SearchView)rootView.findViewById(R.id.searchView);
searchView.setQueryHint("Search BY Brand");
searchView.setOnQueryTextListener(this);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setLayoutManager(layoutManager);
gridLayoutManager = new GridLayoutManager(this.getActivity().getApplicationContext(), 2);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setHasFixedSize(true);
getImageData();
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.one_fragment, container, false);
return rootView;
}
private void getImageData() {
pDialog.show();
ServiceAPI service = ApiClient.getRetrofit().create(ServiceAPI.class);
Call<List<ProductDetailPojo>> call = service.getBusinessImage();
call.enqueue(new Callback<List<ProductDetailPojo>>() {
@Override
public void onResponse(Call<List<ProductDetailPojo>> call, Response<List<ProductDetailPojo>> response) {
if (response.isSuccessful()) {
arrayList = (ArrayList<ProductDetailPojo>) response.body();
adapter = new BusinessModuleAdapter(arrayList, getActivity());
recyclerView.setAdapter(adapter);
pDialog.dismiss();
} else if (response.code() == 401) {
pDialog.dismiss();
Toast.makeText(getActivity(), "Data is not found", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<List<ProductDetailPojo>> call, Throwable t) {
Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
});
}
/* @Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
getActivity().getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
searchView.setQueryHint("Search Product");
searchView.setOnQueryTextListener(this);
}*/
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
newText = newText.toLowerCase();
ArrayList<ProductDetailPojo> newList = new ArrayList<>();
for (ProductDetailPojo productDetailPojo : arrayList) {
String name = productDetailPojo.getDetails().toLowerCase();
if (name.contains(newText) )
newList.add(productDetailPojo);
}
adapter.setFilter(newList);
return true;
}
}
In adapter class
public void setFilter(List<ProductDetailPojo> newList){
arrayList=new ArrayList<>();
arrayList.addAll(newList);
notifyDataSetChanged();
}
First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.
Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.
Instead, I would move all of the "application" content to a separate component, like a JPanel
for example and simply move this between the applet or frame as required...
ps- You can use f.setLocationRelativeTo(null)
to center the window on the screen ;)
Updated
You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...
Within the constructor of GalzyTable2
you are doing...
JApplet app = new JApplet(); add(app); app.init(); app.start();
...Why are you adding another applet to an applet??
Case in point...
Within the main
method, you are trying to add the instance of JFrame
to itself...
f.getContentPane().add(f, button2);
Instead, create yourself a class that extends from something like JPanel
, add your UI logical to this, using compound components if required.
Then, add this panel to whatever top level container you need.
Take the time to read through Creating a GUI with Swing
Updated with example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GalaxyTable2 extends JPanel { private static final int PREF_W = 700; private static final int PREF_H = 600; String[] columnNames = {"Phone Name", "Brief Description", "Picture", "price", "Buy"}; // Create image icons ImageIcon Image1 = new ImageIcon( getClass().getResource("s1.png")); ImageIcon Image2 = new ImageIcon( getClass().getResource("s2.png")); ImageIcon Image3 = new ImageIcon( getClass().getResource("s3.png")); ImageIcon Image4 = new ImageIcon( getClass().getResource("s4.png")); ImageIcon Image5 = new ImageIcon( getClass().getResource("note.png")); ImageIcon Image6 = new ImageIcon( getClass().getResource("note2.png")); ImageIcon Image7 = new ImageIcon( getClass().getResource("note3.png")); Object[][] rowData = { {"Galaxy S", "3G Support,CPU 1GHz", Image1, 120, false}, {"Galaxy S II", "3G Support,CPU 1.2GHz", Image2, 170, false}, {"Galaxy S III", "3G Support,CPU 1.4GHz", Image3, 205, false}, {"Galaxy S4", "4G Support,CPU 1.6GHz", Image4, 230, false}, {"Galaxy Note", "4G Support,CPU 1.4GHz", Image5, 190, false}, {"Galaxy Note2 II", "4G Support,CPU 1.6GHz", Image6, 190, false}, {"Galaxy Note 3", "4G Support,CPU 2.3GHz", Image7, 260, false},}; MyTable ss = new MyTable( rowData, columnNames); // Create a table JTable jTable1 = new JTable(ss); public GalaxyTable2() { jTable1.setRowHeight(70); add(new JScrollPane(jTable1), BorderLayout.CENTER); JPanel buttons = new JPanel(); JButton button = new JButton("Home"); buttons.add(button); JButton button2 = new JButton("Confirm"); buttons.add(button2); add(buttons, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public void actionPerformed(ActionEvent e) { new AMainFrame7().setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new GalaxyTable2()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
You also seem to have a lack of understanding about how to use layout managers.
Take the time to read through Creating a GUI with Swing and Laying components out in a container
Please note that soultions written above removes only space. If you want also to remove tab or new line use stri_replace_all_charclass
from stringi
package.
library(stringi)
stri_replace_all_charclass(" ala \t ma \n kota ", "\\p{WHITE_SPACE}", "")
## [1] "alamakota"
I had to remove my project from eclipse entirely. To do so I copied the folder of my project in workspace and pasted it onto my desktop. Then navigated back into eclipse right clicked selected delete and then check the box to delete the project from my workspace.
After this I closed eclipse. Opened Android studio and tried to open my imported project. At this point it told me the project didn't exist and provided me with an option to remove it from the list. After clicking this i closed Android Studio, and when i reopened it the project was gone.
Finally, I reopened eclipse and imported my project from existing sources to get it back inside eclipse.
NOTE
I would advise against using Android Studio on projects that you have that already work fine with eclipse. Android studio is cool when you are creating new projects but from my experience there are a lot of problems with build paths when I import a build.gradle from eclipse to Android Studio. Android Studio is great but remember it is still in the I/O pre-release!!!
--Just my 2 cents!
Performance test:
http://jsperf.com/array-clear-methods/3
a = []; // 37% slower
a.length = 0; // 89% slower
a.splice(0, a.length) // 97% slower
while (a.length > 0) {
a.pop();
} // Fastest
CSS only solution for modern browsers
@keyframes slidein {
0% {margin-left:1500px;}
100% {margin-left:0px;}
}
.note {
animation-name: slidein;
animation-duration: .9s;
display: block;
}
According to the PHP.net manual:
If
$_SESSION
(or$HTTP_SESSION_VARS
for PHP 4.0.6 or less) is used, useisset()
to check a variable is registered in$_SESSION
.
Use WSDL.EXE utility to generate a Web Service proxy from WSDL.
You'll get a long C# source file that contains a class that looks like this:
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="MyService", Namespace="http://myservice.com/myservice")]
public partial class MyService : System.Web.Services.Protocols.SoapHttpClientProtocol {
...
}
In your client-side, Web-service-consuming code:
To add into every ajax request, I have answered it here: https://stackoverflow.com/a/58964440/1909708
To add into particular ajax requests, this' how I implemented:
var token_value = $("meta[name='_csrf']").attr("content");
var token_header = $("meta[name='_csrf_header']").attr("content");
$.ajax("some-endpoint.do", {
method: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader(token_header, token_value);
},
data: {form_field: $("#form_field").val()},
success: doSomethingFunction,
dataType: "json"
});
You must add the meta
elements in the JSP, e.g.
<html>
<head>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<meta name="_csrf" content="${_csrf.token}"/>
To add to a form submission (synchronous) request, I have answered it here: https://stackoverflow.com/a/58965526/1909708
Python calls them lists. You can write a list literal with square brackets and commas:
>>> [6,28,496,8128]
[6, 28, 496, 8128]
Swift 3.0
If you don't want to show user location in map, but just want to store it in firebase or some where else then follow this steps,
import MapKit
import CoreLocation
Now use CLLocationManagerDelegate on your VC and you must override the last three methods shown below. You can see how the requestLocation() method will get you the current user location using these methods.
class MyVc: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
isAuthorizedtoGetUserLocation()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
}
}
//if we have no permission to access user location, then ask user for permission.
func isAuthorizedtoGetUserLocation() {
if CLLocationManager.authorizationStatus() != .authorizedWhenInUse {
locationManager.requestWhenInUseAuthorization()
}
}
//this method will be called each time when a user change his location access preference.
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
print("User allowed us to access location")
//do whatever init activities here.
}
}
//this method is called by the framework on locationManager.requestLocation();
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Did location updates is called")
//store the user location here to firebase or somewhere
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Did location updates is called but failed getting location \(error)")
}
}
Now you can code the below call once user sign in to your app. When requestLocation() is invoked it will further invoke didUpdateLocations above and you can store the location to Firebase or anywhere else.
if CLLocationManager.locationServicesEnabled() {
locationManager.requestLocation();
}
if you are using GeoFire then in the didUpdateLocations method above you can store the location as below
geoFire?.setLocation(locations.first, forKey: uid) where uid is the user id who logged in to the app. I think you will know how to get UID based on your app sign in implementation.
Last but not least, go to your Info.plist and enable "Privacy -Location when in Use Usage Description."
When you use simulator to test it always give you one custom location that you configured in Simulator -> Debug -> Location.
just wanted to put my 2cents in about this issue...
I had a similar need where i was pulling data from another table via INDEX/MATCH, and it was difficult to distinguish between a real 0 value vs. a 0 value because of no match (for example for a column chart that shows the progress of values over the 12 months and where we are only in february but the rest of the months data is not available yet and the column chart still showed 0's everywhere for Mar to Dec)
What i ended up doing is create a new series and plot this new series on the graph as a line chart and then i hid the line chart by choosing not to display the line in the options and i put the data labels on top, the formula for the values for this new series was something like :
=IF(LEN([@[column1]])=0,NA(),[@[column1]])
I used LEN as a validation because ISEMPTY/ISBLANK didn't work because the result of the INDEX/MATCH always returned something other than a blank even though i had put a "" after the IFERROR...
On the line chart the error value NA() makes it so that the value isn't displayed ...so this worked out for me...
I guess it's a bit difficult to follow this procedure without pictures, but i hope it paints some kind of picture to allow you to use a workaround if you have a similar case like mine
Numeric defines the TOTAL number of digits, and then the number after the decimal.
A numeric(3,2) can only hold up to 9.99.
Here is what I did
private void myEvent_Handler(object sender, SomeEvent e)
{
// I dont know how many times this event will fire
Task t = new Task(() =>
{
if (something == true)
{
DoSomething(e);
}
});
t.RunSynchronously();
}
working great and not blocking UI thread
regex for ip v4:
^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
otherwise you take not valid ip address like 999.999.999.999, 256.0.0.0 etc
Well, it depends on what language you are using, but in general they are 2 separate configurations, each with its own settings. By default, Debug includes debug information in the compiled files (allowing easy debugging) while Release usually has optimizations enabled.
As far as conditional compilation goes, they each define different symbols that can be checked in your program, but they are language-specific macros.
dir /s /b /a:d>output.txt
will port it to a text file
I'll be the first to admit Java can be very verbose, but I don't think this is unreasonable:
JOptionPane.showMessageDialog(null, "My Goodness, this is so concise");
If you statically import javax.swing.JOptionPane.showMessageDialog
using:
import static javax.swing.JOptionPane.showMessageDialog;
This further reduces to
showMessageDialog(null, "This is even shorter");
If you're generating your javascript with a php file, add this as the beginning of your file:
<?php Header("Content-Type: application/x-javascript; charset=UTF-8"); ?>
FatJar can help you in this case.
In addition to the"Export as Jar" function which is included to Eclipse the Plug-In bundles all dependent JARs together into one executable jar.
The Plug-In adds the Entry "Build Fat Jar" to the Context-Menu of Java-projects
This is useful if your final exported jar includes other external jars.
If you have Ganymede, the Export Jar dialog is enough to export your resources from your project.
After Ganymede, you have:
Git as a system manages and manipulates three trees in its normal operation:
HEAD is the pointer to the current branch reference, which is in turn a pointer to the last commit made on that branch. That means HEAD will be the parent of the next commit that is created. It’s generally simplest to think of HEAD as the snapshot of your last commit on that branch.
What does it contain?
To see what that snapshot looks like run the following in root directory of your repository:
git ls-tree -r HEAD
it would result in something like this:
$ git ls-tree -r HEAD
100644 blob a906cb2a4a904a152... README
100644 blob 8f94139338f9404f2... Rakefile
040000 tree 99f1a6d12cb4b6f19... lib
Git populates this index with a list of all the file contents that were last checked out into your working directory and what they looked like when they were originally checked out. You then replace some of those files with new versions of them, and git commit converts that into the tree for a new commit.
What does it contain?
Use git ls-files -s
to see what it looks like. You should see something like this:
100644 a906cb2a4a904a152e80877d4088654daad0c859 0 README
100644 8f94139338f9404f26296befa88755fc2598c289 0 Rakefile
100644 47c6340d6459e05787f644c2447d2595f5d3a54b 0 lib/simplegit.rb
This is where your files reside and where you can try changes out before committing them to your staging area (index) and then into history.
Let's see how do these three trees (As the ProGit book refers to them) work together?
Git’s typical workflow is to record snapshots of your project in successively better states, by manipulating these three trees. Take a look at this picture:
To get a good visualized understanding consider this scenario. Say you go into a new directory with a single file in it. Call this v1 of the file. It is indicated in blue. Running git init
will create a Git repository with a HEAD reference which points to the unborn master branch
At this point, only the working directory tree has any content.
Now we want to commit this file, so we use git add
to take content in the working directory and copy it to the index.
Then we run git commit
, which takes the contents of the index and saves it as a permanent snapshot, creates a commit object which points to that snapshot, and updates master to point to that commit.
If we run git status
, we’ll see no changes, because all three trees are the same.
The beautiful point
git status shows the difference between these trees in the following manner:
git status
will show there are some changes not staged for commitgit status
will show some files under changes to be committed section in its resultgit status
will show some files under changes not staged for commit section and some other files under changes to be committed section in its result.Note about git reset
command
Hopefully, knowing how reset
command works will further brighten the reason behind the existence of these three trees.
reset
command is your Time Machine in git which can easily take you back in time and bring some old snapshots for you to work on. In this manner, HEAD is the wormhole through which you can travel in time. Let's see how it works with an example from the book:
Consider the following repository which has a single file and 3 commits which are shown in different colours and different version numbers:
The state of trees is like the next picture:
The first thing reset will do is move what HEAD points to. This isn’t the same as changing HEAD itself (which is what checkout does). reset moves the branch that HEAD is pointing to. This means if HEAD is set to the master branch, running git reset 9e5e6a4 will start by making master point to 9e5e6a4. If you call reset
with --soft
option it will stop here, without changing index
and working directory
. Our repo will look like this now:
Notice: HEAD~ is the parent of HEAD
Looking a second time at the image, we can see that the command essentially undid the last commit. As the working tree and the index are the same but different from HEAD, git status
will now show changes in green ready to be committed.
This is the default option of the command
Running reset
with --mixed
option updates the index with the contents of whatever snapshot HEAD points to currently, leaving Working Directory intact. Doing so, your repository will look like when you had done some work that is not staged and git status
will show that as changes not staged for commit in red. This option will also undo the last commit and also unstage all the changes. It's like you made changes but have not called git add
command yet. Our repo would look like this now:
If you call reset
with --hard
option it will copy contents of the snapshot HEAD is pointing to into HEAD, index and Working Directory. After executing reset --hard command, it would mean like you got back to a previous point in time and haven't done anything after that at all. see the picture below:
I hope now you have a better understanding of these trees and have a great idea of the power they bring to you by enabling you to change your files in your repository to undo or redo things you have done mistakenly.
When uncertain or in doubt, run in circles, scream and shout.
class Ourself
{
public static string OurFileName() {
System.Reflection.Assembly _objParentAssembly;
if (System.Reflection.Assembly.GetEntryAssembly() == null)
_objParentAssembly = System.Reflection.Assembly.GetCallingAssembly();
else
_objParentAssembly = System.Reflection.Assembly.GetEntryAssembly();
if (_objParentAssembly.CodeBase.StartsWith("http://"))
throw new System.IO.IOException("Deployed from URL");
if (System.IO.File.Exists(_objParentAssembly.Location))
return _objParentAssembly.Location;
if (System.IO.File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + System.AppDomain.CurrentDomain.FriendlyName))
return System.AppDomain.CurrentDomain.BaseDirectory + System.AppDomain.CurrentDomain.FriendlyName;
if (System.IO.File.Exists(System.Reflection.Assembly.GetExecutingAssembly().Location))
return System.Reflection.Assembly.GetExecutingAssembly().Location;
throw new System.IO.IOException("Assembly not found");
}
}
I can't claim to have tested each option, but it doesn't do anything stupid like returning the vhost during debugging sessions.
Now there are a lot of cloud providers , providing solutions like MBaaS (Mobile Backend as a Service). Some only give access to cloud database, some will do the user management for you, some let you place code around cloud database and there are facilities of access control, push notifications, analytics, integrated image and file hosting etc.
Here are some providers which have a "free-tier" (may change in future):
Open source solutions:
The accepted answer did not work for me
note : using rollup js dont know if this answer belongs here
after
npm i --save jquery
in custom.js
import {$, jQuery} from 'jquery';
or
import {jQuery as $} from 'jquery';
i was getting error :
Module ...node_modules/jquery/dist/jquery.js does not export jQuery
or
Module ...node_modules/jquery/dist/jquery.js does not export $
rollup.config.js
export default {
entry: 'source/custom',
dest: 'dist/custom.min.js',
plugins: [
inject({
include: '**/*.js',
exclude: 'node_modules/**',
jQuery: 'jquery',
// $: 'jquery'
}),
nodeResolve({
jsnext: true,
}),
babel(),
// uglify({}, minify),
],
external: [],
format: 'iife', //'cjs'
moduleName: 'mycustom',
};
instead of rollup inject, tried
commonjs({
namedExports: {
// left-hand side can be an absolute path, a path
// relative to the current directory, or the name
// of a module in node_modules
// 'node_modules/jquery/dist/jquery.js': [ '$' ]
// 'node_modules/jquery/dist/jquery.js': [ 'jQuery' ]
'jQuery': [ '$' ]
},
format: 'cjs' //'iife'
};
package.json
"devDependencies": {
"babel-cli": "^6.10.1",
"babel-core": "^6.10.4",
"babel-eslint": "6.1.0",
"babel-loader": "^6.2.4",
"babel-plugin-external-helpers": "6.18.0",
"babel-preset-es2015": "^6.9.0",
"babel-register": "6.9.0",
"eslint": "2.12.0",
"eslint-config-airbnb-base": "3.0.1",
"eslint-plugin-import": "1.8.1",
"rollup": "0.33.0",
"rollup-plugin-babel": "2.6.1",
"rollup-plugin-commonjs": "3.1.0",
"rollup-plugin-inject": "^2.0.0",
"rollup-plugin-node-resolve": "2.0.0",
"rollup-plugin-uglify": "1.0.1",
"uglify-js": "2.7.0"
},
"scripts": {
"build": "rollup -c",
},
This worked :
removed the rollup inject and commonjs plugins
import * as jQuery from 'jquery';
then in custom.js
$(function () {
console.log('Hello jQuery');
});
In my case I was using s3.getSignedUrl('getObject')
when I needed to be using s3.getSignedUrl('putObject')
(because I'm using a PUT to upload my file), which is why the signatures didn't match.
There is no difference between moving and renaming; you should simply call Directory.Move
.
In general, if you're only doing a single operation, you should use the static
methods in the File
and Directory
classes instead of creating FileInfo
and DirectoryInfo
objects.
For more advice when working with files and directories, see here.
use this xml change the color with your choice.
<item>
<layer-list>
<item>
<shape>
<solid android:color="@color/gray_500" />
</shape>
</item>
<!-- CONTENT LAYER -->
<item android:bottom="2dp" >
<shape>
<solid android:color="#ffffff" />
</shape>
</item>
</layer-list>
</item>
In Case if you want programmatically
public static Drawable getStorkLineDrawable(@ColorInt int colorStrok, int iSize, int left, int top, int right, int bottom)
{
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setShape(GradientDrawable.RECTANGLE);
gradientDrawable.setStroke(iSize, colorStrok);
LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{gradientDrawable});
layerDrawable.setLayerInset(0, left, top, right, bottom);
return layerDrawable;
}
call this method like
Drawable yourLineDrawable= getStorkLineDrawable(yourColor, iSize, -iSize, -iSize, -iSize, 0);
You could use this for all devices,
$(document).on('scroll', function() {
if( $(this).scrollTop() >= $('#target_element').position().top ){
do_something();
}
});
Arrow looks promising for this:
>>> import arrow
>>> arrow.get('2014-11-13T14:53:18.694072+00:00').datetime
datetime.datetime(2014, 11, 13, 14, 53, 18, 694072, tzinfo=tzoffset(None, 0))
Arrow is a Python library that provides a sensible, intelligent way of creating, manipulating, formatting and converting dates and times. Arrow is simple, lightweight and heavily inspired by moment.js and requests.
You want to do the check for undefined
first. If you do it the other way round, it will generate an error if the array is undefined.
if (array === undefined || array.length == 0) {
// array empty or does not exist
}
This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null
values, other types of objects with a length
property, etc. It is also not very idiomatic JavaScript.
The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length
property.
if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ? do not attempt to process array
}
To break it down:
Array.isArray()
, unsurprisingly, checks whether its argument is an array. This weeds out values like null
, undefined
and anything else that is not an array.
Note that this will also eliminate array-like objects, such as the arguments
object and DOM NodeList
objects. Depending on your situation, this might not be the behavior you're after.
The array.length
condition checks whether the variable's length
property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0
or array.length !== 0
are not required here.
The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.
In those cases, I tend to go for the following, more idiomatic JavaScript:
if (!array || !array.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or, more frequently, its inverse:
if (array && array.length) {
// array and array.length are truthy
// ? probably OK to process array
}
With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:
if (!array?.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or the opposite:
if (array?.length) {
// array and array.length are truthy
// ? probably OK to process array
}
Swift version to get Bool?
NSUserDefaults.standardUserDefaults().objectForKey(DefaultsIsGiver) as? Bool
The difference between link
and controller
comes into play when you want to nest directives in your DOM and expose API functions from the parent directive to the nested ones.
From the docs:
Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.
Say you want to have two directives my-form
and my-text-input
and you want my-text-input
directive to appear only inside my-form
and nowhere else.
In that case, you will say while defining the directive my-text-input
that it requires a controller from the parent
DOM element using the require argument, like this: require: '^myForm'
. Now the controller from the parent element will be injected
into the link
function as the fourth argument, following $scope, element, attributes
. You can call functions on that controller and communicate with the parent directive.
Moreover, if such a controller is not found, an error will be raised.
There is no real need to use the link
function if one is defining the controller
since the $scope
is available on the controller
. Moreover, while defining both link
and controller
, one does need to be careful about the order of invocation of the two (controller
is executed before).
However, in keeping with the Angular way, most DOM manipulation and 2-way binding using $watchers
is usually done in the link
function while the API for children and $scope
manipulation is done in the controller
. This is not a hard and fast rule, but doing so will make the code more modular and help in separation of concerns (controller will maintain the directive
state and link
function will maintain the DOM
+ outside bindings).
It's simple. I did it the following way to get a string with unique values (from two columns of an output sheet):
Dim startpoint, endpoint, ArrCount As Integer
Dim SentToArr() As String
'created by running the first part (check for new entries)
startpoint = ThisWorkbook.Sheets("temp").Range("A1").Value
'set counter on 0
Arrcount = 0
'last filled row in BG
endpoint = ThisWorkbook.Sheets("BG").Range("G1047854").End(xlUp).Row
'create arr with all data - this could be any data you want!
With ThisWorkbook.Sheets("BG")
For i = startpoint To endpoint
ArrCount = ArrCount + 1
ReDim Preserve SentToArr(1 To ArrCount)
SentToArr(ArrCount) = .Range("A" & i).Value
'get prep
ArrCount = ArrCount + 1
ReDim Preserve SentToArr(1 To ArrCount)
SentToArr(ArrCount) = .Range("B" & i).Value
Next i
End With
'iterate the arr and get a key (l) in each iteration
For l = LBound(SentToArr) To UBound(SentToArr)
Key = SentToArr(l)
'iterate one more time and compare the first key (l) with key (k)
For k = LBound(SentToArr) To UBound(SentToArr)
'if key = the new key from the second iteration and the position is different fill it as empty
If Key = SentToArr(k) And Not k = l Then
SentToArr(k) = ""
End If
Next k
Next l
'iterate through all 'unique-made' values, if the value of the pos is
'empty, skip - you could also create a new array by using the following after the IF below - !! dont forget to reset [ArrCount] as well:
'ArrCount = ArrCount + 1
'ReDim Preserve SentToArr(1 To ArrCount)
'SentToArr(ArrCount) = SentToArr(h)
For h = LBound(SentToArr) To UBound(SentToArr)
If SentToArr(h) = "" Then GoTo skipArrayPart
GetEmailArray = GetEmailArray & "; " & SentToArr(h)
skipArrayPart:
Next h
'some clean up
If Left(GetEmailArray, 2) = "; " Then
GetEmailArray = Right(GetEmailArray, Len(GetEmailArray) - 2)
End If
'show us the money
MsgBox GetEmailArray
In phpMyAdmin v.4.6.5.2 there's a checkbox option "The first line of the file contains the table column names...." :
Here is another answer:
With DinnerComboBox
.AddItem "Italian"
.AddItem "Chinese"
.AddItem "Frites and Meat"
End With
Source: Show the
If the steps provided by @MainMa didn't work follow following steps
Step 1 Try killing the process from windows task manager or using taskkill /F /PID . You can find pid of the process by command 'sc queryex '. Try next step if you still can't uninstall.
Step 2 If above
Run Autoruns for Windows Search for service by name and delete results.
Related or maybe not related, using superscript as a HTML element or as a span+css in text might cause problem with localization - in localization programs.
For example let's say "3rd party software":
3<sup>rd</sup> party software
3<span class="superscript">rd</span> party software
How can translators translate "rd"? They can leave it empty for several cyrrilic languages, but what about of other exotic or RTL languages?
In this case it is better to avoid using superscripts and use a full wording like "third-party software". Or, as mentioned here in other comments, adding plus signs in superscript via jQuery.
"... that are independent of their timezone"
var timezone = d.getTimezoneOffset() // difference in minutes from GMT
A fine example found here. Powerlord got it right, below, for POST you need HttpURLConnection
, instead.
Below is the code to do that,
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty ("Authorization", encodedCredentials);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(data);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
Change URLConnection
to HttpURLConnection
, to make it POST request.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
Suggestion (...in comments):
You might need to set these properties too,
conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "Accept", "*/*" );
Depending on the libc release it could be needed to set both SO_REUSEADDR and SO_REUSEPORT socket options as explained in socket(7) documentation :
SO_REUSEPORT (since Linux 3.9) Permits multiple AF_INET or AF_INET6 sockets to be bound to an identical socket address. This option must be set on each socket (including the first socket) prior to calling bind(2) on the socket. To prevent port hijacking, all of the processes binding to the same address must have the same effective UID. This option can be employed with both TCP and UDP sockets.
As this socket option appears with kernel 3.9 and raspberry use 3.12.x, it will be needed to set SO_REUSEPORT.
You can set theses two options before calling bind like this :
int reuse = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEADDR) failed");
#ifdef SO_REUSEPORT
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEPORT) failed");
#endif
Creating a single combined plot with your current data set up would look something like this
p <- ggplot() +
# blue plot
geom_point(data=visual1, aes(x=ISSUE_DATE, y=COUNTED)) +
geom_smooth(data=visual1, aes(x=ISSUE_DATE, y=COUNTED), fill="blue",
colour="darkblue", size=1) +
# red plot
geom_point(data=visual2, aes(x=ISSUE_DATE, y=COUNTED)) +
geom_smooth(data=visual2, aes(x=ISSUE_DATE, y=COUNTED), fill="red",
colour="red", size=1)
however if you could combine the data sets before plotting then ggplot will automatically give you a legend, and in general the code looks a bit cleaner
visual1$group <- 1
visual2$group <- 2
visual12 <- rbind(visual1, visual2)
p <- ggplot(visual12, aes(x=ISSUE_DATE, y=COUNTED, group=group, col=group, fill=group)) +
geom_point() +
geom_smooth(size=1)
try this:
DBMS_SNAPSHOT.REFRESH( 'v_materialized_foo_tbl','f');
first parameter is name of mat_view
and second defines type of refresh
. f denotes fast refresh.
but keep this thing in mind it will override any any other refresh timing options.
I solve this by SQL command:
ALTER USER 'mysqlUsername'@'localhost' IDENTIFIED WITH mysql_native_password BY 'mysqlUsernamePassword';
which is referenced by https://dev.mysql.com/doc/refman/8.0/en/alter-user.html
if you are creating new user
CREATE USER 'jeffrey'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
which is referenced by https://dev.mysql.com/doc/refman/8.0/en/create-user.html
this works for me
The form
tag needs some attributes set:
action
: The URL that the form data is sent to on submit. Generate it with url_for
. It can be omitted if the same URL handles showing the form and processing the data.method="post"
: Submits the data as form data with the POST method. If not given, or explicitly set to get
, the data is submitted in the query string (request.args
) with the GET method instead.enctype="multipart/form-data"
: When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.The input
tag needs a name
parameter.
Add a view to handle the submitted data, which is in request.form
under the same key as the input's name
. Any file inputs will be in request.files
.
@app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
Set the form's action
to that view's URL using url_for
:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>
One gotcha arises when you want to instantiate a public type defined in an external package and that type embeds other types that are private.
Example:
package animals
type otherProps{
Name string
Width int
}
type Duck{
Weight int
otherProps
}
How do you instantiate a Duck
in your own program? Here's the best I could come up with:
package main
import "github.com/someone/animals"
func main(){
var duck animals.Duck
// Can't instantiate a duck with something.Duck{Weight: 2, Name: "Henry"} because `Name` is part of the private type `otherProps`
duck.Weight = 2
duck.Width = 30
duck.Name = "Henry"
}
Yes that is valid syntax but it may well not do what you want.
Execution will continue after your RAISERROR
except if you add a RETURN
. So you will need to add a block with BEGIN ... END
to hold the two statements.
Also I'm not sure why you plumped for severity 15. That usually indicates a syntax error.
Finally I'd simplify the conditions using IN
CREATE PROCEDURE [dbo].[AddApplicationUser] (@TenantId BIGINT,
@UserType TINYINT,
@UserName NVARCHAR(100),
@Password NVARCHAR(100))
AS
BEGIN
IF ( @TenantId IS NULL
AND @UserType IN ( 0, 1 ) )
BEGIN
RAISERROR('The value for @TenantID should not be null',15,1);
RETURN;
END
END
You can use the WooCommerce Layered Nav widget, which allows you to use different sets of attributes as filters for products. Here's the "official" description:
Shows a custom attribute in a widget which lets you narrow down the list of products when viewing product categories.
If you look into plugins/woocommerce/widgets/widget-layered_nav.php, you can see the way it operates with the attributes in order to set filters. The URL then looks like this:
... and the digits are actually the id-s of the different attribute values, that you want to set.
With the Material Components library you can customize the TextInputLayout
the hint text color using:
In the layout:
app:hintTextColor
attribute : the color of the label when it is collapsed and the text field is activeandroid:textColorHint
attribute: the color of the label in all other text field states (such as resting and disabled)Something like:
<com.google.android.material.textfield.TextInputLayout
app:hintTextColor="@color/mycolor"
android:textColorHint="@color/text_input_hint_selector"
.../>
Using the rowid()
function in data.table
:
> set.seed(100)
> df <- data.frame(cat = c(rep("aaa", 5), rep("bbb", 5), rep("ccc", 5)), val = runif(15))
> df <- df[order(df$cat, df$val), ]
> df$num <- data.table::rowid(df$cat)
> df
cat val num
4 aaa 0.05638315 1
2 aaa 0.25767250 2
1 aaa 0.30776611 3
5 aaa 0.46854928 4
3 aaa 0.55232243 5
10 bbb 0.17026205 1
8 bbb 0.37032054 2
6 bbb 0.48377074 3
9 bbb 0.54655860 4
7 bbb 0.81240262 5
13 ccc 0.28035384 1
14 ccc 0.39848790 2
11 ccc 0.62499648 3
15 ccc 0.76255108 4
12 ccc 0.88216552 5
Add spring-tx jar file and it should settle it.
Both System.Timers.Timer
and System.Threading.Timer
will work for services.
The timers you want to avoid are System.Web.UI.Timer
and System.Windows.Forms.Timer
, which are respectively for ASP applications and WinForms. Using those will cause the service to load an additional assembly which is not really needed for the type of application you are building.
Use System.Timers.Timer
like the following example (also, make sure that you use a class level variable to prevent garbage collection, as stated in Tim Robinson's answer):
using System;
using System.Timers;
public class Timer1
{
private static System.Timers.Timer aTimer;
public static void Main()
{
// Normally, the timer is declared at the class level,
// so that it stays in scope as long as it is needed.
// If the timer is declared in a long-running method,
// KeepAlive must be used to prevent the JIT compiler
// from allowing aggressive garbage collection to occur
// before the method ends. (See end of method.)
//System.Timers.Timer aTimer;
// Create a timer with a ten second interval.
aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
// If the timer is declared in a long-running method, use
// KeepAlive to prevent garbage collection from occurring
// before the method ends.
//GC.KeepAlive(aTimer);
}
// Specify what you want to happen when the Elapsed event is
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}
}
/* This code example produces output similar to the following:
Press the Enter key to exit the program.
The Elapsed event was raised at 5/20/2007 8:42:27 PM
The Elapsed event was raised at 5/20/2007 8:42:29 PM
The Elapsed event was raised at 5/20/2007 8:42:31 PM
...
*/
If you choose System.Threading.Timer
, you can use as follows:
using System;
using System.Threading;
class TimerExample
{
static void Main()
{
AutoResetEvent autoEvent = new AutoResetEvent(false);
StatusChecker statusChecker = new StatusChecker(10);
// Create the delegate that invokes methods for the timer.
TimerCallback timerDelegate =
new TimerCallback(statusChecker.CheckStatus);
// Create a timer that signals the delegate to invoke
// CheckStatus after one second, and every 1/4 second
// thereafter.
Console.WriteLine("{0} Creating timer.\n",
DateTime.Now.ToString("h:mm:ss.fff"));
Timer stateTimer =
new Timer(timerDelegate, autoEvent, 1000, 250);
// When autoEvent signals, change the period to every
// 1/2 second.
autoEvent.WaitOne(5000, false);
stateTimer.Change(0, 500);
Console.WriteLine("\nChanging period.\n");
// When autoEvent signals the second time, dispose of
// the timer.
autoEvent.WaitOne(5000, false);
stateTimer.Dispose();
Console.WriteLine("\nDestroying timer.");
}
}
class StatusChecker
{
int invokeCount, maxCount;
public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
}
// This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Checking status {1,2}.",
DateTime.Now.ToString("h:mm:ss.fff"),
(++invokeCount).ToString());
if(invokeCount == maxCount)
{
// Reset the counter and signal Main.
invokeCount = 0;
autoEvent.Set();
}
}
}
Both examples comes from the MSDN pages.
This isn't as easy to do as one might expect -- you can really only do vertical alignment if you know the height of your container. IF this is the case, you can do it with absolute positioning.
The concept is to set the top / left positions at 50%, and then use negative margins (set to half the height / width) to pull the container back to being centered.
Example: http://jsbin.com/ipawe/edit
Basic CSS:
#mydiv {
position: absolute;
top: 50%;
left: 50%;
height: 400px;
width: 700px;
margin-top: -200px; /* -(1/2 height) */
margin-left: -350px; /* -(1/2 width) */
}
Here is what I came up with ( and like all Date Time conundrums it is probably going to be disproved based on some weird timezone-leapyear-daylight adjustment :D )
Date
<<->> LocalDateTime
Given: Date date = [some date]
(1) LocalDateTime
<< Instant
<< Date
Instant instant = Instant.ofEpochMilli(date.getTime());
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
(2) Date
<< Instant
<< LocalDateTime
Instant instant = ldt.toInstant(ZoneOffset.UTC);
Date date = Date.from(instant);
Example:
Date date = new Date();
System.out.println(date + " long: " + date.getTime());
LocalDateTime
<< Instant
<< Date
:Create Instant
from Date
:
Instant instant = Instant.ofEpochMilli(date.getTime());
System.out.println("Instant from Date:\n" + instant);
Create Date
from Instant
(not necessary,but for illustration):
date = Date.from(instant);
System.out.println("Date from Instant:\n" + date + " long: " + date.getTime());
Create LocalDateTime
from Instant
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
System.out.println("LocalDateTime from Instant:\n" + ldt);
Date
<< Instant
<< LocalDateTime
Create Instant
from LocalDateTime
:
instant = ldt.toInstant(ZoneOffset.UTC);
System.out.println("Instant from LocalDateTime:\n" + instant);
Create Date
from Instant
:
date = Date.from(instant);
System.out.println("Date from Instant:\n" + date + " long: " + date.getTime());
Fri Nov 01 07:13:04 PDT 2013 long: 1383315184574
Instant from Date:
2013-11-01T14:13:04.574Z
Date from Instant:
Fri Nov 01 07:13:04 PDT 2013 long: 1383315184574
LocalDateTime from Instant:
2013-11-01T14:13:04.574
Instant from LocalDateTime:
2013-11-01T14:13:04.574Z
Date from Instant:
Fri Nov 01 07:13:04 PDT 2013 long: 1383315184574
Alex provided the correct reason for not being able to do what you're trying to do, so +1. But you are encountering this issue because you're not quite using resolves how they're designed.
resolve
takes either the string of a service or a function returning a value to be injected. Since you're doing the latter, you need to pass in an actual function:
resolve: {
data: function (dbService) {
return dbService.getData();
}
}
When the framework goes to resolve data
, it will inject the dbService
into the function so you can freely use it. You don't need to inject into the config
block at all to accomplish this.
Bon appetit!
Use sprintf()
:
int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);
All numbers that are representable by int
will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int
. When using numbers with greater bitsize, e.g. long
with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.
public static void setListViewHeightBasedOnChildren(ListView listView) {
// ??ListView???Adapter
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()????????
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0); // ????View ???
totalHeight += listItem.getMeasuredHeight(); // ??????????
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
// listView.getDividerHeight()?????????????
// params.height??????ListView?????????
listView.setLayoutParams(params);
}
you can use this code for listview in scrollview
This code will always fail.
As written, it says: "Look for a property named "Employee" on my DataContext property, and set it to the DataContext property". Clearly that isn't right.
To get your code to work, as is, change your window declaration to:
<Window x:Class="SampleApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SampleApplication"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:Employee/>
</Window.DataContext>
This declares a new XAML namespace (local) and sets the DataContext to an instance of the Employee class. This will cause your bindings to display the default data (from your constructor).
However, it is highly unlikely this is actually what you want. Instead, you should have a new class (call it MainViewModel) with an Employee
property that you then bind to, like this:
public class MainViewModel
{
public Employee MyEmployee { get; set; } //In reality this should utilize INotifyPropertyChanged!
}
Now your XAML becomes:
<Window x:Class="SampleApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SampleApplication"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
...
<TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding MyEmployee.EmpID}" />
<TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding MyEmployee.EmpName}" />
Now you can add other properties (of other types, names), etc. For more information, see Implementing the Model-View-ViewModel Pattern
moment.js
is great but sometimes you don't want to pull a large number of dependencies for simple things.
The following works as well:
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1);
// => '2015-01-26T06:40:36.181'
The slice(0, -1)
gets rid of the trailing Z
which represents Zulu timezone and can be replaced by your own.
In my case, I had this in my code which did not work:
@Override
protected void onCreate(Bundle savedInstanceState) {
context = getApplicationContext();
requestWindowFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Then I played with the order of the code:
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
}
And it worked!
Conclusion: requestWindowFeature should be the first thing you call in the onCreate method.
This shows the licence type and number of licences:
SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')