This is a more general script approach for the stated question.
import pandas as pd
encoding_list = ['ascii', 'big5', 'big5hkscs', 'cp037', 'cp273', 'cp424', 'cp437', 'cp500', 'cp720', 'cp737'
, 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp858', 'cp860', 'cp861', 'cp862'
, 'cp863', 'cp864', 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932', 'cp949', 'cp950'
, 'cp1006', 'cp1026', 'cp1125', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254'
, 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', 'euc_kr'
, 'gb2312', 'gbk', 'gb18030', 'hz', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2'
, 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1', 'iso8859_2'
, 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9'
, 'iso8859_10', 'iso8859_11', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_16', 'johab'
, 'koi8_r', 'koi8_t', 'koi8_u', 'kz1048', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2'
, 'mac_roman', 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004', 'shift_jisx0213', 'utf_32'
, 'utf_32_be', 'utf_32_le', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7', 'utf_8', 'utf_8_sig']
for encoding in encoding_list:
worked = True
try:
df = pd.read_csv(path, encoding=encoding, nrows=5)
except:
worked = False
if worked:
print(encoding, ':\n', df.head())
One starts with all the standard encodings available for the python version (in this case 3.7 python 3.7 standard encodings). A usable python list of the standard encodings for the different python version is provided here: Helpful Stack overflow answer
Trying each encoding on a small chunk of the data; only printing the working encoding. The output is directly obvious. This output also addresses the problem that an encoding like 'latin1' that runs through with ought any error, does not necessarily produce the wanted outcome.
In case of the question, I would try this approach specific for problematic CSV
file and then maybe try to use the found working encoding for all others.
I eventually figured out there was a byte mark exception and removed it using this code:
string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(_byteOrderMarkUtf8))
{
var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length-1;
xml = xml.Remove(0, lastIndexOfUtf8);
}
Doing this yourself is an awful idea. Use Json.NET. It has already solved the problem better than most programmers could if they were given months on end to work on it. As for your specific needs, parsing into arrays and such, check the documentation, particularly on JsonTextReader
. Basically, Json.NET handles JSON arrays natively and will parse them into strings, ints, or whatever the type happens to be without prompting from you. Here is a direct link to the basic code usages for both the reader and the writer, so you can have that open in a spare window while you're learning to work with this.
This is for the best: Be lazy this time and use a library so you solve this common problem forever.
Use Timer and tick event to copy your files.
On start the service, start the time and specify the interval in the time.
So the service is keep running and copy the files ontick.
Hope it help.
Add System.ServiceModel
in references
Using SyndicationFeed
:
string url = "http://fooblog.com/feed";
XmlReader reader = XmlReader.Create(url);
SyndicationFeed feed = SyndicationFeed.Load(reader);
reader.Close();
foreach (SyndicationItem item in feed.Items)
{
String subject = item.Title.Text;
String summary = item.Summary.Text;
...
}
Agreed with the answer from sll, but experienced another hurdle which was having specified a namespace in the attributes, when receiving the return xml that namespace wasn't included and thus failed finding the class.
i had to find a workaround to specifying the namespace in the attribute and it worked.
ie.
[Serializable()]
[XmlRoot("Patient", Namespace = "http://www.xxxx.org/TargetNamespace")]
public class Patient
generated
<Patient xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.xxxx.org/TargetNamespace">
but I had to change it to
[Serializable()]
[XmlRoot("Patient")]
public class Patient
which generated to
<Patient xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
This solved my problem, hope it helps someone else.
From Solution Explorer, right click on myfile.txt and choose "Properties"
From there, set the Build Action
to content
and Copy to Output Directory
to either Copy always
or Copy if newer
This best for XML Deserialize
public static object Deserialize(string xml, Type toType)
{
using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
System.IO.StreamReader str = new System.IO.StreamReader(memoryStream);
System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(toType);
return xSerializer.Deserialize(str);
}
}
I got the same question here. If the document is huge, it is not a good idea to use XmlDocument. The fact is that the first element is the root element, based on which XmlReader can be used to get the root element. Using XmlReader will be much more efficient than using XmlDocument as it doesn't require load the whole document into memory.
using (XmlReader reader = XmlReader.Create(<your_xml_file>)) {
while (reader.Read()) {
// first element is the root element
if (reader.NodeType == XmlNodeType.Element) {
System.Console.WriteLine(reader.Name);
break;
}
}
}
I took the liberty of feeding your classes into the CGbR generator. Because it is in an early stage it doesn't support The generated serialization code looks like this:DateTime
yet, so I simply replaced it with long.
public int Size
{
get
{
var size = 24;
// Add size for collections and strings
size += Cts == null ? 0 : Cts.Count * 4;
size += Tes == null ? 0 : Tes.Count * 4;
size += Code == null ? 0 : Code.Length;
size += Message == null ? 0 : Message.Length;
return size;
}
}
public byte[] ToBytes(byte[] bytes, ref int index)
{
if (index + Size > bytes.Length)
throw new ArgumentOutOfRangeException("index", "Object does not fit in array");
// Convert Cts
// Two bytes length information for each dimension
GeneratorByteConverter.Include((ushort)(Cts == null ? 0 : Cts.Count), bytes, ref index);
if (Cts != null)
{
for(var i = 0; i < Cts.Count; i++)
{
var value = Cts[i];
value.ToBytes(bytes, ref index);
}
}
// Convert Tes
// Two bytes length information for each dimension
GeneratorByteConverter.Include((ushort)(Tes == null ? 0 : Tes.Count), bytes, ref index);
if (Tes != null)
{
for(var i = 0; i < Tes.Count; i++)
{
var value = Tes[i];
value.ToBytes(bytes, ref index);
}
}
// Convert Code
GeneratorByteConverter.Include(Code, bytes, ref index);
// Convert Message
GeneratorByteConverter.Include(Message, bytes, ref index);
// Convert StartDate
GeneratorByteConverter.Include(StartDate.ToBinary(), bytes, ref index);
// Convert EndDate
GeneratorByteConverter.Include(EndDate.ToBinary(), bytes, ref index);
return bytes;
}
public Td FromBytes(byte[] bytes, ref int index)
{
// Read Cts
var ctsLength = GeneratorByteConverter.ToUInt16(bytes, ref index);
var tempCts = new List<Ct>(ctsLength);
for (var i = 0; i < ctsLength; i++)
{
var value = new Ct().FromBytes(bytes, ref index);
tempCts.Add(value);
}
Cts = tempCts;
// Read Tes
var tesLength = GeneratorByteConverter.ToUInt16(bytes, ref index);
var tempTes = new List<Te>(tesLength);
for (var i = 0; i < tesLength; i++)
{
var value = new Te().FromBytes(bytes, ref index);
tempTes.Add(value);
}
Tes = tempTes;
// Read Code
Code = GeneratorByteConverter.GetString(bytes, ref index);
// Read Message
Message = GeneratorByteConverter.GetString(bytes, ref index);
// Read StartDate
StartDate = DateTime.FromBinary(GeneratorByteConverter.ToInt64(bytes, ref index));
// Read EndDate
EndDate = DateTime.FromBinary(GeneratorByteConverter.ToInt64(bytes, ref index));
return this;
}
I created a list of sample objects like this:
var objects = new List<Td>();
for (int i = 0; i < 1000; i++)
{
var obj = new Td
{
Message = "Hello my friend",
Code = "Some code that can be put here",
StartDate = DateTime.Now.AddDays(-7),
EndDate = DateTime.Now.AddDays(2),
Cts = new List<Ct>(),
Tes = new List<Te>()
};
for (int j = 0; j < 10; j++)
{
obj.Cts.Add(new Ct { Foo = i * j });
obj.Tes.Add(new Te { Bar = i + j });
}
objects.Add(obj);
}
Results on my machine in Release
build:
var watch = new Stopwatch();
watch.Start();
var bytes = BinarySerializer.SerializeMany(objects);
watch.Stop();
Size: 149000 bytes
Time: 2.059ms 3.13ms
Edit: Starting with CGbR 0.4.3 the binary serializer supports DateTime. Unfortunately the DateTime.ToBinary
method is insanely slow. I will replace it with somehting faster soon.
Edit2: When using UTC DateTime
by invoking ToUniversalTime()
the performance is restored and clocks in at 1.669ms.
this will open the file with the default windows program (notepad if you haven't changed it);
Process.Start(@"c:\myfile.txt")
Because you didn't specify the Header.
I've added an extended example:
var request = (HttpWebRequest)WebRequest.Create(strServer + strURL.Split('&')[1].ToString());
Header(ref request, p_Method);
And the method Header:
private void Header(ref HttpWebRequest p_request, string p_Method)
{
p_request.ContentType = "application/x-www-form-urlencoded";
p_request.Method = p_Method;
p_request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows CE)";
p_request.Host = strServer.Split('/')[2].ToString();
p_request.Accept = "*/*";
if (String.IsNullOrEmpty(strURLReferer))
{
p_request.Referer = strServer;
}
else
{
p_request.Referer = strURLReferer;
}
p_request.Headers.Add("Accept-Language", "en-us\r\n");
p_request.Headers.Add("UA-CPU", "x86 \r\n");
p_request.Headers.Add("Cache-Control", "no-cache\r\n");
p_request.KeepAlive = true;
}
If you have the XML stored inside a string variable you could use a StringReader:
var xml = @"<car/>";
var serializer = new XmlSerializer(typeof(Car));
using (var reader = new StringReader(xml))
{
var car = (Car)serializer.Deserialize(reader);
}
You can also use this;
string employeeName = chldNode.Attributes().ElementAt(0).Name
I had do this kind of automatic validation in VB and this is how I did it (converted to C#):
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags = settings.ValidationFlags |
Schema.XmlSchemaValidationFlags.ProcessSchemaLocation;
XmlReader XMLvalidator = XmlReader.Create(reader, settings);
Then I subscribed to the settings.ValidationEventHandler
event while reading the file.
I don't know about JSON.NET, but it works fine with JavaScriptSerializer
from System.Web.Extensions.dll
(.NET 3.5 SP1):
using System.Collections.Generic;
using System.Web.Script.Serialization;
public class NameTypePair
{
public string OBJECT_NAME { get; set; }
public string OBJECT_TYPE { get; set; }
}
public enum PositionType { none, point }
public class Ref
{
public int id { get; set; }
}
public class SubObject
{
public NameTypePair attributes { get; set; }
public Position position { get; set; }
}
public class Position
{
public int x { get; set; }
public int y { get; set; }
}
public class Foo
{
public Foo() { objects = new List<SubObject>(); }
public string displayFieldName { get; set; }
public NameTypePair fieldAliases { get; set; }
public PositionType positionType { get; set; }
public Ref reference { get; set; }
public List<SubObject> objects { get; set; }
}
static class Program
{
const string json = @"{
""displayFieldName"" : ""OBJECT_NAME"",
""fieldAliases"" : {
""OBJECT_NAME"" : ""OBJECT_NAME"",
""OBJECT_TYPE"" : ""OBJECT_TYPE""
},
""positionType"" : ""point"",
""reference"" : {
""id"" : 1111
},
""objects"" : [
{
""attributes"" : {
""OBJECT_NAME"" : ""test name"",
""OBJECT_TYPE"" : ""test type""
},
""position"" :
{
""x"" : 5,
""y"" : 7
}
}
]
}";
static void Main()
{
JavaScriptSerializer ser = new JavaScriptSerializer();
Foo foo = ser.Deserialize<Foo>(json);
}
}
Edit:
Json.NET works using the same JSON and classes.
Foo foo = JsonConvert.DeserializeObject<Foo>(json);
INSERT INTO wp_bp_activity
(
user_id,
component,
`type`,
`action`,
content,
primary_link,
item_id,
secondary_item_id,
date_recorded,
hide_sitewide,
mptt_left,
mptt_right
)
VALUES(
1,'activity','activity_update','<a title="admin" href="http://brandnewmusicreleases.com/social-network/members/admin/">admin</a> posted an update','<a title="242925_1" href="http://brandnewmusicreleases.com/social-network/wp-content/uploads/242925_1.jpg" class="buddyboss-pics-picture-link">242925_1</a>','http://brandnewmusicreleases.com/social-network/members/admin/',' ',' ','2012-06-22 12:39:07',0,0,0
)
You can just substract two date objects.
var d1 = new Date(); //"now"
var d2 = new Date("2011/02/01") // some date
var diff = Math.abs(d1-d2); // difference in milliseconds
try {
LdapContext ctx = new InitialLdapContext(env, null);
ctx.setRequestControls(null);
NamingEnumeration<?> namingEnum = ctx.search("ou=people,dc=example,dc=com", "(objectclass=user)", getSimpleSearchControls());
while (namingEnum.hasMore ()) {
SearchResult result = (SearchResult) namingEnum.next ();
Attributes attrs = result.getAttributes ();
System.out.println(attrs.get("cn"));
}
namingEnum.close();
} catch (Exception e) {
e.printStackTrace();
}
private SearchControls getSimpleSearchControls() {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setTimeLimit(30000);
//String[] attrIDs = {"objectGUID"};
//searchControls.setReturningAttributes(attrIDs);
return searchControls;
}
The approach I use is to start the "Visual Studio Command Prompt" which can be found in the Start menu. E.g. my visual studio 2010 Express install has a shortcute Visual Studio Command Prompt (2010)
at Start Menu\Programs\Microsoft Visual Studio 2010\Visual Studio Tools
.
This shortcut prepares an environment by calling a script vcvarsall.bat
where the compiler, linker, etc. are setup from the right Visual Studio installation.
Alternatively, if you already have a prompt open, you can prepare the environment by calling a similar script:
:: For x86 (using the VS100COMNTOOLS env-var)
call "%VS100COMNTOOLS%"\..\..\VC\bin\vcvars32.bat
or
:: For amd64 (using the full path)
call C:\Program Files\Microsoft Visual Studio 10.0\VC\bin\amd64\vcvars64.bat
Your output (with the '$' prompt) suggests that you are attempting to run CMake from a MSys shell. In that case it might be better to run CMake for MSys or MinGW, by explicitly specifying a makefile generator:
cmake -G"MSYS Makefiles"
cmake -G"MinGW Makefiles"
Run cmake --help
to get a list of all possible generators.
Working on your own and just want it to work? Follow these instructions below, they’ve worked reliably for me and many others for years.
Working with others? Git is complicated. Read the comments below this answer before you do something rash.
To revert to a previous commit, ignoring any changes:
git reset --hard HEAD
where HEAD is the last commit in your current branch
To revert to a commit that's older than the most recent commit:
# Resets index to former commit; replace '56e05fced' with your commit code
git reset 56e05fced
# Moves pointer back to previous HEAD
git reset --soft HEAD@{1}
git commit -m "Revert to 56e05fced"
# Updates working copy to reflect the new commit
git reset --hard
Credits go to a similar Stack Overflow question, Revert to a commit by a SHA hash in Git?.
Since Swift 3, many of the NS prefixes have been dropped.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
/* date format string rules
* http://userguide.icu-project.org/formatparse/datetime
*/
let date = dateFormatter.date(from: dateString)
According the the Apple Reference on UIImage the object is immutable and you have no access to the backing bytes. While it is true that you can access the CGImage data if you populated the UIImage
with a CGImage
(explicitly or implicitly), it will return NULL
if the UIImage
is backed by a CIImage
and vice-versa.
Image objects not provide direct access to their underlying image data. However, you can retrieve the image data in other formats for use in your app. Specifically, you can use the cgImage and ciImage properties to retrieve versions of the image that are compatible with Core Graphics and Core Image, respectively. You can also use the UIImagePNGRepresentation(:) and UIImageJPEGRepresentation(:_:) functions to generate an NSData object containing the image data in either the PNG or JPEG format.
As stated your options are
Neither of these are particularly good tricks if you want output that isn't ARGB, PNG, or JPEG data and the data isn't already backed by CIImage.
While developing your project it might make more sense for you to avoid UIImage altogether and pick something else. UIImage, as a Obj-C image wrapper, is often backed by CGImage to the point where we take it for granted. CIImage tends to be a better wrapper format in that you can use a CIContext to get out the format you desire without needing to know how it was created. In your case, getting the bitmap would be a matter of calling
- render:toBitmap:rowBytes:bounds:format:colorSpace:
As an added bonus you can start doing nice manipulations to the image by chaining filters onto the image. This solves a lot of the issues where the image is upside down or needs to be rotated/scaled etc.
I had same problem with 'parallax' plugin.
I changed jQuery librery version to *jquery-1.6.4*
from *jquery-1.10.2*.
And error cleared.
This might not be an ethical and preferred solution but it helps in environments where you can't access the console to kill the job using yarn application command.
Steps are
Go to application master page of spark job. Click on the jobs section. Click on the active job's active stage. You will see "kill" button right next to the active stage.
This works if the succeeding stages are dependent on the currently running stage. Though it marks job as " Killed By User"
Local variables are non existent in the memory after the function termination.
However static
variables remain allocated in the memory throughout the life of the program irrespective of whatever function.
Additionally from your question, static
variables can be declared locally in class
or function scope and globally in namespace
or file scope. They are allocated the memory from beginning to end, it's just the initialization which happens sooner or later.
private void SortGridGenerico< T >(
ref List< T > lista
, SortDirection sort
, string propriedadeAOrdenar)
{
if (!string.IsNullOrEmpty(propriedadeAOrdenar)
&& lista != null
&& lista.Count > 0)
{
Type t = lista[0].GetType();
if (sort == SortDirection.Ascending)
{
lista = lista.OrderBy(
a => t.InvokeMember(
propriedadeAOrdenar
, System.Reflection.BindingFlags.GetProperty
, null
, a
, null
)
).ToList();
}
else
{
lista = lista.OrderByDescending(
a => t.InvokeMember(
propriedadeAOrdenar
, System.Reflection.BindingFlags.GetProperty
, null
, a
, null
)
).ToList();
}
}
}
You can use an interceptor before the method call. That is what aspect-oriented programming focus on.
Suppose M1(Object test) is a method and M2 is a method where we apply an aspect before a method call, M2(Object test2)
. If test2 != null
then call M1, otherwise do another thing. It works for all methods with whom you want to apply an aspect for. If you want to apply an aspect for an instance field and constructor you can use AspectJ. Spring can also be the best choice for a method aspect.
Unexpected end of file
means that something else was expected before the PHP parser reached the end of the script.
Judging from your HUGE file, it's probably that you're missing a closing brace (}
) from an if
statement.
Please at least attempt the following things:
;
in some of your embedded PHP statements, and not in others, ie. <?php echo base_url(); ?>
vs <?php echo $this->layouts->print_includes() ?>
. It's not required, so don't use it (or do, just do one or the other).The question has already been answered, but I thought I'd add an answer with more precise terminology and references to the C++ standard.
Two things are going on here, array parameters being adjusted to pointer parameters, and array arguments being converted to pointer arguments. These are two quite different mechanisms, the first is an adjustment to the actual type of the parameter, whereas the other is a standard conversion which introduces a temporary pointer to the first element.
Adjustments to your function declaration:
After determining the type of each parameter, any parameter of type “array of T” (...) is adjusted to be “pointer to T”.
So int arg[]
is adjusted to be int* arg
.
Conversion of your function argument:
An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The temporary materialization conversion is applied. The result is a pointer to the first element of the array.
So in printarray(firstarray, 3);
, the lvalue firstarray
of type "array of 3 int" is converted to a prvalue (temporary) of type "pointer to int", pointing to the first element.
The toFixed
method will do the appropriate rounding if necessary. It will also add trailing zeroes, which is not always ideal.
(4.55555).toFixed(2);
//-> "4.56"
(4).toFixed(2);
//-> "4.00"
If you cast the return value to a number, those trailing zeroes will be dropped. This is a simpler approach than doing your own rounding or truncation math.
+(4.55555).toFixed(2);
//-> 4.56
+(4).toFixed(2);
//-> 4
All you need to do is reverse your ORDER BY
. Add or remove DESC
to it.
jdk max version is 1.8.0_144
then run monitor
The good news is a transaction in SQL Server can span multiple batches (each exec
is treated as a separate batch.)
You can wrap your EXEC
statements in a BEGIN TRANSACTION
and COMMIT
but you'll need to go a step further and rollback if any errors occur.
Ideally you'd want something like this:
BEGIN TRY
BEGIN TRANSACTION
exec( @sqlHeader)
exec(@sqlTotals)
exec(@sqlLine)
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
The BEGIN TRANSACTION
and COMMIT
I believe you are already familiar with. The BEGIN TRY
and BEGIN CATCH
blocks are basically there to catch and handle any errors that occur. If any of your EXEC
statements raise an error, the code execution will jump to the CATCH
block.
Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.
A TCP connection is specified by the tuple (source IP, source port, destination IP, destination port).
The reason why there is a TIME_WAIT state following session shutdown is because there may still be live packets out in the network on their way to you (or from you which may solicit a response of some sort). If you were to re-create that same tuple and one of those packets showed up, it would be treated as a valid packet for your connection (and probably cause an error due to sequencing).
So the TIME_WAIT time is generally set to double the packets maximum age. This value is the maximum age your packets will be allowed to get to before the network discards them.
That guarantees that, before you're allowed to create a connection with the same tuple, all the packets belonging to previous incarnations of that tuple will be dead.
That generally dictates the minimum value you should use. The maximum packet age is dictated by network properties, an example being that satellite lifetimes are higher than LAN lifetimes since the packets have much further to go.
Basic and general difference is:
Fields
Properties
For those who are using access token and a Windows environment, there is a simple way to do it:
Start menu ? Credential Manager ? Windows Credentials ? find the line (Git: https://whatever/your-repository/url) ? edit, user name is "PersonalAccessToken" and password is your access token.
SBT solution stated above did not work for me. What worked for me is excluding slf4j-log4j12
//dependencies with exclusions_x000D_
libraryDependencies ++= Seq(_x000D_
//depencies_x000D_
).map(_.exclude("org.slf4j","slf4j-log4j12"))
_x000D_
On latest Ubuntu versions (14.04 - 16.04), this command did the trick for me.
hostname -I | awk '{print $1}'
You can also use truncate
> 'Smith'.truncate(1, omission: '')
#=> "S"
or for additional formatting:
> 'Smith'.truncate(4)
#=> "S..."
> 'Smith'.truncate(2, omission: '.')
#=> "S."
I highly recommend using yarn upgrade-interactive to update React, or any Node project for that matter. It lists your packages, current version, the latest version, an indication of a Minor, Major, or Patch update compared to what you have, plus a link to the respective project.
You run it with yarn upgrade-interactive --latest
, check out release notes if you want, go down the list with your arrow keys, choose which packages you want to upgrade by selecting with the space bar, and hit Enter
to complete.
Npm-upgrade is ok but not as slick.
For a more in depth approach read Comparing floating point numbers. Here is the code snippet from that link:
// Usable AlmostEqual function
bool AlmostEqual2sComplement(float A, float B, int maxUlps)
{
// Make sure maxUlps is non-negative and small enough that the
// default NAN won't compare as equal to anything.
assert(maxUlps > 0 && maxUlps < 4 * 1024 * 1024);
int aInt = *(int*)&A;
// Make aInt lexicographically ordered as a twos-complement int
if (aInt < 0)
aInt = 0x80000000 - aInt;
// Make bInt lexicographically ordered as a twos-complement int
int bInt = *(int*)&B;
if (bInt < 0)
bInt = 0x80000000 - bInt;
int intDiff = abs(aInt - bInt);
if (intDiff <= maxUlps)
return true;
return false;
}
Those arrows are part of the Shadow DOM, which are basically DOM elements on your page which are hidden from you. If you're new to the idea, a good introductory read can be found here.
For the most part, the Shadow DOM saves us time and is good. But there are instances, like this question, where you want to modify it.
You can modify these in Webkit now with the right selectors, but this is still in the early stages of development. The Shadow DOM itself has no unified selectors yet, so the webkit selectors are proprietary (and it isn't just a matter of appending -webkit
, like in other cases).
Because of this, it seems likely that Opera just hasn't gotten around to adding this yet. Finding resources about Opera Shadow DOM modifications is tough, though. A few unreliable internet sources I've found all say or suggest that Opera doesn't currently support Shadow DOM manipulation.
I spent a bit of time looking through the Opera website to see if there'd be any mention of it, along with trying to find them in Dragonfly...neither search had any luck. Because of the silence on this issue, and the developing nature of the Shadow DOM + Shadow DOM manipulation, it seems to be a safe conclusion that you just can't do it in Opera, at least for now.
I figure out the answer! You need to use the window.onload function as shown below. Thanks to Tec guy and Karim for the help. Note: You still need to use the document ready function too.
window.onload = function() {$('#logo').hide().fadeIn(3000);};
$(function() {$("#div").load(function() {$('#div').hide().fadeIn(750););
It also worked for me when placed right after the image...Thanks
With Git 2.23 (August 2019), that would be, using git switch -f
:
git switch -f master
That avoids the confusion with git checkout
(which deals with files or branches).
And that will proceeds, even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
If --recurse-submodules
is specified, submodule content is also restored to match the switching target.
This is used to throw away local changes.
Simple solution for cast pointer to object
class myClass
{
public:
void sayHello () {
cout << "Hello";
}
};
int main ()
{
myClass* myPointer;
myClass myObject = myClass(* myPointer); // Cast pointer to object
myObject.sayHello();
return 0;
}
Create unique constraint that two numbers together CANNOT together be repeated:
ALTER TABLE someTable
ADD UNIQUE (col1, col2)
There is no big difference in data.The Major difference is column order In list tables schema column will be after table/view column In list tables show details schema column will be after column type
if(!empty($youtube) && empty($link)) {
}
else if(empty($youtube) && !empty($link)) {
}
else if(empty($youtube) && empty($link)) {
}
Dmytro's answer works fine for my case. I think it's better to declare the function as synchronized. at least for my case, it would invoke null pointer exception otherwise, e.g. getWritableDatabase not yet returned in one thread and openDatabse called in another thread meantime.
public synchronized SQLiteDatabase openDatabase() {
if(mOpenCounter.incrementAndGet() == 1) {
// Opening new database
mDatabase = mDatabaseHelper.getWritableDatabase();
}
return mDatabase;
}
http://api.jqueryui.com/datepicker/#option-maxDate
$( ".selector" ).datepicker( "option", "maxDate", '+0m +0w' );
One caution based on my experience, if your purpose only involves date then be careful to include the timestamp. For example, say today is "2016-11-09"
. Comparison involving timestamp will nullify the logic here. Example,
// input
$var = "2016-11-09 00:00:00.0";
// check if date is today or in the future
if ( time() <= strtotime($var) )
{
// This seems right, but if it's ONLY date you are after
// then the code might treat $var as past depending on
// the time.
}
The code above seems right, but if it's ONLY the date you want to compare, then, the above code is not the right logic. Why? Because, time() and strtotime() will provide include timestamp. That is, even though both dates fall on the same day, but difference in time will matter. Consider the example below:
// plain date string
$input = "2016-11-09";
Because the input is plain date string, using strtotime()
on $input
will assume that it's the midnight of 2016-11-09. So, running time()
anytime after midnight will always treat $input
as past, even though they are on the same day.
To fix this, you can simply code, like this:
if (date("Y-m-d") <= $input)
{
echo "Input date is equal to or greater than today.";
}
I've used:
pg_restore -c -d database_name filename.dump
for the line you wrote
var g = $('<%=Label1.ClientID%>').val(); // Also I tried .text() and .html()
you missed adding #. it should be like this
var g = $('#<%=Label1.ClientID%>').text();
also I do not prefer using this method
that's because if you are calling a control in master or nested master page or if you are calling a control in page from master. Also controls in Repeater. regardless the MVC. this will cause problems.
you should ALWAYS call the ID of the control directly. like this
$('#ControlID')
this is simple and clear. but do not forget to set
ClientIDMode="Static"
in your controls to remain with same ID name after render. that's because ASP.net will modify the ID name in HTML rendered file in some contexts i.e. the page is for Master page the control name will be ConetentPlaceholderName_controlID
I hope it clears the question Good Luck
In Kotlin, use the following codes to get Application Name:
// Get App Name
var appName: String = ""
val applicationInfo = this.getApplicationInfo()
val stringId = applicationInfo.labelRes
if (stringId == 0) {
appName = applicationInfo.nonLocalizedLabel.toString()
}
else {
appName = this.getString(stringId)
}
Try this:
var jIsHasKids = $('#chkIsHasKids').attr('checked');
jIsHasKids = jIsHasKids.toString().toLowerCase();
//OR
jIsHasKids = jIsHasKids.val().toLowerCase();
Possible duplicate with: How do I use jQuery to ignore case when selecting
How to write a compound statement with if?
You can write a compound statement in an if block using parenthesis. The first parenthesis must come on the line with the if and the second on a line by itself.
if %ERRORLEVEL% == 0 (
echo ErrorLevel is zero
echo A second statement
) else if %ERRORLEVEL% == 1 (
echo ErrorLevel is one
echo A second statement
) else (
echo ErrorLevel is > 1
echo A second statement
)
If you're using SQL Server it would be something like this:
DATEDIFF(d,GETDATE(),FUTUREDATE) BETWEEN 0 AND 90
I was facing the same issue. After many tries below solution worked for me.
Before installing VC++ install your windows updates. 1. Go to Start - Control Panel - Windows Update 2. Check for the updates. 3. Install all updates. 4. Restart your system.
After that you can follow the below steps.
@ABHI KUMAR
Download the Visual C++ Redistributable 2015
Visual C++ Redistributable for Visual Studio 2015 (64-bit)
Visual C++ Redistributable for Visual Studio 2015 (32-bit)
(Reinstal if already installed) then restart your computer or use windows updates for download auto.
For link download https://www.microsoft.com/de-de/download/details.aspx?id=48145.
In addition to @Connor Leech's answer.
If you want to create a new custom typography type of your own, define the following in your css file.
.text-foo {
.text-emphasis-variant(#FFFFFF);
}
The mixin text-emphasis-variant
is defined in Bootstrap's mixins.less
file.
I've tried everything suggested here but didn't work for me. So in case I can help anyone with a similar issue, every single tutorial I've checked is not updated to work with version 4.
Here is what I've done to make it work
import React from 'react';
import App from './App';
import ReactDOM from 'react-dom';
import {
HashRouter,
Route
} from 'react-router-dom';
ReactDOM.render((
<HashRouter>
<div>
<Route path="/" render={()=><App items={temasArray}/>}/>
</div>
</HashRouter >
), document.getElementById('root'));
That's the only way I have managed to make it work without any errors or warnings.
In case you want to pass props to your component for me the easiest way is this one:
<Route path="/" render={()=><App items={temasArray}/>}/>
One liner using String.protype.matchAll
(ES2020):
[...sourceStr.matchAll(new RegExp(searchStr, 'gi'))].map(a => a.index)
Using your values:
const sourceStr = 'I learned to play the Ukulele in Lebanon.';
const searchStr = 'le';
const indexes = [...sourceStr.matchAll(new RegExp(searchStr, 'gi'))].map(a => a.index);
console.log(indexes); // [2, 25, 27, 33]
If you're worried about doing a spread and a map()
in one line, I ran it with a for...of
loop for a million iterations (using your strings). The one liner averages 1420ms while the for...of
averages 1150ms on my machine. That's not an insignificant difference, but the one liner will work fine if you're only doing a handful of matches.
According to the documentation of Spring-Cloud-Config
there is one extra scope next to the existing five. It is @RefreshScope
.
This is the short description of RefreshScope
:
When there is a configuration change, a Spring @Bean that is marked as @RefreshScope gets special treatment. This feature addresses the problem of stateful beans that only get their configuration injected when they are initialized. For instance, if a DataSource has open connections when the database URL is changed via the Environment, you probably want the holders of those connections to be able to complete what they are doing. Then, the next time something borrows a connection from the pool, it gets one with the new URL.
Sometimes, it might even be mandatory to apply the @RefreshScope annotation on some beans which can be only initialized once. If a bean is "immutable", you will have to either annotate the bean with @RefreshScope or specify the classname under the property key spring.cloud.refresh.extra-refreshable.
Refresh scope beans are lazy proxies that initialize when they are used (that is, when a method is called), and the scope acts as a cache of initialized values. To force a bean to re-initialize on the next method call, you must invalidate its cache entry.
The RefreshScope is a bean in the context and has a public refreshAll() method to refresh all beans in the scope by clearing the target cache. The /refresh endpoint exposes this functionality (over HTTP or JMX). To refresh an individual bean by name, there is also a refresh(String) method.
The other way is to use BinaryPrimitives like so
byte[] intBytes = BitConverter.GetBytes(123);
int actual = BinaryPrimitives.ReadInt32LittleEndian(intBytes);
If I use exit()
in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing.
See here
But sys.exit()
is better in this case. It closes the program and doesn't create any dialogue box.
There is a minor bug in previous solution.
Here is some updated code:
s.TakeWhile(c => (n -= (c == t ? 1 : 0)) > 0).Count();
private void MainTimesheetForm_Load(object sender, EventArgs e)
{
ListViewItem newList = new ListViewItem("1");
newList.SubItems.Add("2");
newList.SubItems.Add(DateTime.Now.ToLongTimeString());
newList.SubItems.Add("3");
newList.SubItems.Add("4");
newList.SubItems.Add("5");
newList.SubItems.Add("6");
listViewTimeSheet.Items.Add(newList);
}
There are many ways of solving this problem, and the ones listed above are the most commonly used ways of achieving the solution. I want to add two more ways, just in case someone is looking for an alternative.
index_list = [1,3]
df.take(pos)
#or
df.query('index in @index_list')
I make Miquels Version Injectable as service:
import { Injectable } from '@angular/core';
@Injectable()
export class CookiesService {
isConsented = false;
constructor() {}
/**
* delete cookie
* @param name
*/
public deleteCookie(name) {
this.setCookie(name, '', -1);
}
/**
* get cookie
* @param {string} name
* @returns {string}
*/
public getCookie(name: string) {
const ca: Array<string> = decodeURIComponent(document.cookie).split(';');
const caLen: number = ca.length;
const cookieName = `${name}=`;
let c: string;
for (let i = 0; i < caLen; i += 1) {
c = ca[i].replace(/^\s+/g, '');
if (c.indexOf(cookieName) === 0) {
return c.substring(cookieName.length, c.length);
}
}
return '';
}
/**
* set cookie
* @param {string} name
* @param {string} value
* @param {number} expireDays
* @param {string} path
*/
public setCookie(name: string, value: string, expireDays: number, path: string = '') {
const d: Date = new Date();
d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000);
const expires = `expires=${d.toUTCString()}`;
const cpath = path ? `; path=${path}` : '';
document.cookie = `${name}=${value}; ${expires}${cpath}; SameSite=Lax`;
}
/**
* consent
* @param {boolean} isConsent
* @param e
* @param {string} COOKIE
* @param {string} EXPIRE_DAYS
* @returns {boolean}
*/
public consent(isConsent: boolean, e: any, COOKIE: string, EXPIRE_DAYS: number) {
if (!isConsent) {
return this.isConsented;
} else if (isConsent) {
this.setCookie(COOKIE, '1', EXPIRE_DAYS);
this.isConsented = true;
e.preventDefault();
}
}
}
Try to set more reasonable logging level. Setting logging level to info
means that only log event at info
or higher level (warn
, error
and fatal
) are logged, that is debug
logging events are ignored.
log4j.logger.org.hibernate=info
or in XML version of log4j config file:
<logger name="org.hibernate">
<level value="info"/>
</logger>
See also log4j manual.
To update and answer the question without breaking mail servers. Later versions of CentOS 7 have MariaDB included as the base along with PostFix which relies on MariaDB. Removing using yum will also remove postfix and perl-DBD-MySQL. To get around this and keep postfix in place, first make a copy of /usr/lib64/libmysqlclient.so.18 (which is what postfix depends on) and then use:
rpm -qa | grep mariadb
then remove the mariadb packages using (changing to your versions):
rpm -e --nodeps "mariadb-libs-5.5.56-2.el7.x86_64"
rpm -e --nodeps "mariadb-server-5.5.56-2.el7.x86_64"
rpm -e --nodeps "mariadb-5.5.56-2.el7.x86_64"
Delete left over files and folders (which also removes any databases):
rm -f /var/log/mariadb
rm -f /var/log/mariadb/mariadb.log.rpmsave
rm -rf /var/lib/mysql
rm -rf /usr/lib64/mysql
rm -rf /usr/share/mysql
Put back the copy of /usr/lib64/libmysqlclient.so.18 you made at the start and you can restart postfix.
There is more detail at https://code.trev.id.au/centos-7-remove-mariadb-replace-mysql/ which describes how to replace mariaDB with MySQL
This worked for me:
(endDate - beginDate).to_i
Your best bet would be to use a port of the CSS processor you use.
I'm a big fan of SASS so I currently use https://github.com/thomas-mcdonald/bootstrap-sass
It looks like there's a fork for Stylus here: https://github.com/Acquisio/bootstrap-stylus
Otherwise, Search & Replace is your best friend right in the css version...
If you want to insert all the columns then
insert into def select * from abc;
here the number of columns in def should be equal to abc.
if you want to insert the subsets of columns then
insert into def (col1,col2, col3 ) select scol1,scol2,scol3 from abc;
if you want to insert some hardcorded values then
insert into def (col1, col2,col3) select 'hardcoded value',scol2, scol3 from abc;
C programmers use the static attribute to hide variable and function declarations inside modules, much as you would use public and private declarations in Java and C++. C source files play the role of modules. Any global variable or function declared with the static attribute is private to that module. Similarly, any global variable or function declared without the static attribute is public and can be accessed by any other module. It is good programming practice to protect your variables and functions with the static attribute wherever possible.
Use Predefined Character Ranges
echo $words= preg_replace('/[[:digit:]]/','', $words);
You create the relationships the other way around; add foreign keys to the Person
type to create a Many-to-One relationship:
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
anniversary = models.ForeignKey(
Anniversary, on_delete=models.CASCADE)
address = models.ForeignKey(
Address, on_delete=models.CASCADE)
class Address(models.Model):
line1 = models.CharField(max_length=150)
line2 = models.CharField(max_length=150)
postalcode = models.CharField(max_length=10)
city = models.CharField(max_length=150)
country = models.CharField(max_length=150)
class Anniversary(models.Model):
date = models.DateField()
Any one person can only be connected to one address and one anniversary, but addresses and anniversaries can be referenced from multiple Person
entries.
Anniversary
and Address
objects will be given a reverse, backwards relationship too; by default it'll be called person_set
but you can configure a different name if you need to. See Following relationships "backward" in the queries documentation.
JVM is os dependent. for every os JVM different.
".class" is same for all JVMs. so, every JVM understand that ".class" file data.
windows dependent JVM give windows dependent instruction to windows linux dependent JVM give linux dependent instruction to linux.
that's like it for other operating systems. so,java runs on any operating system.
that's why java is os independent.
Using the builtin Date.parse
function which accepts input in ISO8601 format and directly returns the desired integer return value:
var dates_as_int = dates.map(Date.parse);
This problem arise basically when you save your python code in a UTF-8 or UTF-16 encoding because python add some special character at the beginning of the code automatically (which is not shown by the text editors) to identify the encoding format. But, when you try to execute the code it gives you the syntax error in line 1 i.e, start of code because python compiler understands ASCII encoding. when you view the code of file using read() function you can see at the begin of the returned code '\ufeff' is shown. The one simplest solution to this problem is just by changing the encoding back to ASCII encoding(for this you can copy your code to a notepad and save it Remember! choose the ASCII encoding... Hope this will help.
This was what fixed it for me. (I had already tried toggling the capabilities on/off, recreating the provisioning profile, etc).
In the Build Settings tab, in Code Signing Entitlements, my .entitlements file wasn't link for all sections. Once I added it to the Any SDK section, the error was resolved.
You can "style echo" with adding new HTML code.
echo '<span class="city">' . $ip['cityName'] . '</span>';
Assuming that you already downloaded chromeDriver, this error is also occurs when already multiple chrome tabs are open.
If you close all tabs and run again, the error should clear up.
Can't add a comment to the solution but that didn't work for me. The solution that worked for me was to use:
var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass)); return des.data.Count.ToString();
well under linux try reading man page of the find command
man find
something like this should
find . -type f -mtime -7 -print -exec cat {} \; | tar cf - | gzip -9
and you have it
You can use a fantastic library name Videojs. You will find more useful informations here. But with quick start you can do something like this:
<link href="//vjs.zencdn.net/5.11/video-js.min.css" rel="stylesheet">
<script src="//vjs.zencdn.net/5.11/video.min.js"></script>
<video
id="Video"
class="video-js vjs-default-skin vjs-big-play-centered"
controls
preload="none"
width="auto"
height="auto"
poster="poster.jpg"
data-setup='{"techOrder": ["flash", "html5", "other supported tech"], "nativeControlsForTouch": true, "controlBar": { "muteToggle": false, "volumeControl": false, "timeDivider": false, "durationDisplay": false, "progressControl": false } }'
>
<source src="rtmp://{domain_server}/{publisher}" type='rtmp/mp4'/>
</video>
<script>
var player = videojs('Video');
player.play();
</script>
From the fine manual:
ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;
There's no need to specify the type when you're just changing the nullability.
Well to obtain all different values in a Dataframe
you can use distinct. As you can see in the documentation that method returns another DataFrame
. After that you can create a UDF
in order to transform each record.
For example:
val df = sc.parallelize(Array((1, 2), (3, 4), (1, 6))).toDF("age", "salary")
// I obtain all different values. If you show you must see only {1, 3}
val distinctValuesDF = df.select(df("age")).distinct
// Define your udf. In this case I defined a simple function, but they can get complicated.
val myTransformationUDF = udf(value => value / 10)
// Run that transformation "over" your DataFrame
val afterTransformationDF = distinctValuesDF.select(myTransformationUDF(col("age")))
I was puzzled by this also... didn't like the parentheses that windows puts in when you rename in bulk. In my research I decided to write a script with PowerShell instead. Super easy and worked like a charm. Now I can use it whenever I need to batch process file renaming... which is frequent. I take hundreds of photos and the camera names them IMG1234.JPG etc...
Here is the script I wrote:
# filename: bulk_file_rename.ps1
# by: subcan
# PowerShell script to rename multiple files within a folder to a
# name that increments without (#)
# create counter
$int = 1
# ask user for what they want
$regex = Read-Host "Regex for files you are looking for? ex. IMG*.JPG "
$file_name = Read-Host "What is new file name, without extension? ex. New Image "
$extension = Read-Host "What extension do you want? ex. .JPG "
# get a total count of the files that meet regex
$total = Get-ChildItem -Filter $regex | measure
# while loop to rename all files with new name
while ($int -le $total.Count)
{
# diplay where in loop you are
Write-Host "within while loop" $int
# create variable for concatinated new name -
# $int.ToString(000) ensures 3 digit number 001, 010, etc
$new_name = $file_name + $int.ToString(000)+$extension
# get the first occurance and rename
Get-ChildItem -Filter $regex | select -First 1 | Rename-Item -NewName $new_name
# display renamed file name
Write-Host "Renamed to" $new_name
# increment counter
$int++
}
I hope that this is helpful to someone out there.
subcan
Also, starting with .NET Core 3.0 (and .NET Standard 2.1) (C# 8) you can use Index
type to keep array's indexes from end:
var lastElementIndexInAnyArraySize = ^1;
var lastElement = array[lastElementIndexInAnyArraySize];
You can use this index to get last array value in any lenght of array. For example:
var firstArray = new[] {0, 1, 1, 2, 2};
var secondArray = new[] {3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5};
var index = ^1;
var firstArrayLastValue = firstArray[index]; // 2
var secondArrayLastValue = secondArray[index]; // 5
For more information check documentation
Error
and Exception
both extend Throwable
, but mostly Error
is thrown by JVM in a scenario which is fatal and there is no way for the application program to recover from that error. For instance OutOfMemoryError
.
Though even application can raise an Error
but its just not a good a practice, instead applications should use checked exceptions for recoverable conditions and runtime exceptions for programming errors.
Here's how to do it with list comprehension:
a = (1, 2, 3)
b = (4, 5, 6)
[print('f:', i, '; b', j) for i, j in zip(a, b)]
prints:
f: 1 ; b 4
f: 2 ; b 5
f: 3 ; b 6
I also recommend using Joda as mentioned before.
Solving your problem using standard Java Date
objects only can be done as follows:
// **** YOUR CODE **** BEGIN ****
long ts = System.currentTimeMillis();
Date localTime = new Date(ts);
String format = "yyyy/MM/dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format);
// Convert Local Time to UTC (Works Fine)
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date gmtTime = new Date(sdf.format(localTime));
System.out.println("Local:" + localTime.toString() + "," + localTime.getTime() + " --> UTC time:"
+ gmtTime.toString() + "," + gmtTime.getTime());
// **** YOUR CODE **** END ****
// Convert UTC to Local Time
Date fromGmt = new Date(gmtTime.getTime() + TimeZone.getDefault().getOffset(localTime.getTime()));
System.out.println("UTC time:" + gmtTime.toString() + "," + gmtTime.getTime() + " --> Local:"
+ fromGmt.toString() + "-" + fromGmt.getTime());
Output:
Local:Tue Oct 15 12:19:40 CEST 2013,1381832380522 --> UTC time:Tue Oct 15 10:19:40 CEST 2013,1381825180000
UTC time:Tue Oct 15 10:19:40 CEST 2013,1381825180000 --> Local:Tue Oct 15 12:19:40 CEST 2013-1381832380000
try (without format
step)
new Date(moment())
var d = moment.tz("2019-04-15 12:00", "America/New_York");_x000D_
_x000D_
console.log( new Date(d) );_x000D_
console.log( new Date(moment()) );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>
_x000D_
I kept receiving the same message no matter what i did.
To fix this, i removed .gitignore and i am not getting the Github changes not staged for commit message anymore. Before it would allow me to commit once when i ran git add . and then after it would bring up the same message.
Im not sure why the .gitignore file was causing a problem but i added on my local machine and most likely didn't sync it up properly.
I tried to do this in next way
public static DataTable JoinTwoTables(DataTable innerTable, DataTable outerTable)
{
DataTable resultTable = new DataTable();
var innerTableColumns = new List<string>();
foreach (DataColumn column in innerTable.Columns)
{
innerTableColumns.Add(column.ColumnName);
resultTable.Columns.Add(column.ColumnName);
}
var outerTableColumns = new List<string>();
foreach (DataColumn column in outerTable.Columns)
{
if (!innerTableColumns.Contains(column.ColumnName))
{
outerTableColumns.Add(column.ColumnName);
resultTable.Columns.Add(column.ColumnName);
}
}
for (int i = 0; i < innerTable.Rows.Count; i++)
{
var row = resultTable.NewRow();
innerTableColumns.ForEach(x =>
{
row[x] = innerTable.Rows[i][x];
});
outerTableColumns.ForEach(x =>
{
row[x] = outerTable.Rows[i][x];
});
resultTable.Rows.Add(row);
}
return resultTable;
}
a day is 86400 seconds.
$tomorrow = date('y:m:d', time() + 86400);
C# is a strictly/strongly typed language. var was introduced for compile-time type-binding for anonymous types yet you can use var for primitive and custom types that are already known at design time. At runtime there's nothing like var, it is replaced by an actual type that is either a reference type or value type.
When you say,
var x = null;
the compiler cannot resolve this because there's no type bound to null. You can make it like this.
string y = null;
var x = y;
This will work because now x can know its type at compile time that is string in this case.
Before you start, close VirtualBox! After those manipulations start VB as Administrator!
Screen Resolutions
: 1280x720, 1920x1080, 2048x1080, 2560x1440, 3840x2160, 1280x800, 1280x1024, 1440x900, 1600x900
Description:
macOS_Catalina - insert your VB machine name.
1920x1080 - put here your Screen Resolution.
Cheers!
Using Suse Linux (Linux linux 3.16.7-48-default) and PHP 5.6.1 as root, this helped:
zypper in php5-dom
plus restart
systemctl restart apache2
Delete this option from registry helped me in Windows Server 2012 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\KeyExchangAlgorithms
Try this JS solution that toggles webkitOverflowScrolling
style. The trick here is that this style is off, mobile Safari goes to ordinary scrolling and prevents over-bounce — alas, it is not able to cancel ongoing drag. This complex solution also tracks onscroll
as bounce over the top makes scrollTop
negative that may be tracked. This solution was tested on iOS 12.1.1 and has single drawback: while accelerating the scroll single over-bounce still happens as resetting the style may not cancel it immediately.
function preventScrollVerticalBounceEffect(container) {
setTouchScroll(true) //!: enable before the first scroll attempt
container.addEventListener("touchstart", onTouchStart)
container.addEventListener("touchmove", onTouch, { passive: false })
container.addEventListener("touchend", onTouchEnd)
container.addEventListener("scroll", onScroll)
function isTouchScroll() {
return !!container.style.webkitOverflowScrolling
}
let prevScrollTop = 0, prevTouchY, opid = 0
function setTouchScroll(on) {
container.style.webkitOverflowScrolling = on ? "touch" : null
//Hint: auto-enabling after a small pause makes the start
// smoothly accelerated as required. After the pause the
// scroll position is settled, and there is no delta to
// make over-bounce by dragging the finger. But still,
// accelerated content makes short single over-bounce
// as acceleration may not be off instantly.
const xopid = ++opid
!on && setTimeout(() => (xopid === opid) && setTouchScroll(true), 250)
if(!on && container.scrollTop < 16)
container.scrollTop = 0
prevScrollTop = container.scrollTop
}
function isBounceOverTop() {
const dY = container.scrollTop - prevScrollTop
return dY < 0 && container.scrollTop < 16
}
function isBounceOverBottom(touchY) {
const dY = touchY - prevTouchY
//Hint: trying to bounce over the bottom, the finger moves
// up the screen, thus Y becomes smaller. We prevent this.
return dY < 0 && container.scrollHeight - 16 <=
container.scrollTop + container.offsetHeight
}
function onTouchStart(e) {
prevTouchY = e.touches[0].pageY
}
function onTouch(e) {
const touchY = e.touches[0].pageY
if(isBounceOverBottom(touchY)) {
if(isTouchScroll())
setTouchScroll(false)
e.preventDefault()
}
prevTouchY = touchY
}
function onTouchEnd() {
prevTouchY = undefined
}
function onScroll() {
if(isTouchScroll() && isBounceOverTop()) {
setTouchScroll(false)
}
}
}
Either I'm doing it wrongly, or the accepted answer does not work anymore with the current git.
I have actually found the proper solution and posted it under almost the same question here. For more details head there.
Solution:
# Ignore everything inside Resources/ directory
/Resources/**
# Except for subdirectories(won't be committed anyway if there is no committed file inside)
!/Resources/**/
# And except for *.foo files
!*.foo
Try this:
Use back-ticks for NAME
CREATE TABLE `teachers` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`addr` varchar(255) NOT NULL,
`phone` int(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
As Michael said check the "Requires Full Screen" checkbox under General > Targets
and also delete the 'CFBundleIcons-ipad' from the info.plst
This worked for me
I think a 32 bit JVM has a maximum of 2GB memory.This might be out of date though. If I understood correctly, you set the -Xmx on Eclipse launcher. If you want to increase the memory for the program you run from Eclipse, you should define -Xmx in the "Run->Run configurations..."(select your class and open the Arguments tab put it in the VM arguments area) menu, and NOT on Eclipse startup
Edit: details you asked for. in Eclipse 3.4
Run->Run Configurations...
if your class is not listed in the list on the left in the "Java Application" subtree, click on "New Launch configuration" in the upper left corner
on the right, "Main" tab make sure the project and the class are the right ones
select the "Arguments" tab on the right.
this one has two text areas. one is for the program arguments that get in to the args[] array supplied to your main method. the other one is for the VM arguments. put into the one with the VM arguments(lower one iirc) the following:
-Xmx2048m
I think that 1024m should more than enough for what you need though!
Click Apply, then Click Run
Should work :)
Here is your simple and easy answer
Go to your class where you want to give a negative margin then copy and paste this inside the class.
Example for negative margin top
mt-n3
Example for negative margin bottom
mb-n2
The "iterable interface" in python consists of two methods __next__()
and __iter__()
. The __next__
function is the most important, as it defines the iterator behavior - that is, the function determines what value should be returned next. The __iter__()
method is used to reset the starting point of the iteration. Often, you will find that __iter__()
can just return self when __init__()
is used to set the starting point.
See the following code for defining a Class Reverse which implements the "iterable interface" and defines an iterator over any instance from any sequence class. The __next__()
method starts at the end of the sequence and returns values in reverse order of the sequence. Note that instances from a class implementing the "sequence interface" must define a __len__()
and a __getitem__()
method.
class Reverse:
"""Iterator for looping over a sequence backwards."""
def __init__(self, seq):
self.data = seq
self.index = len(seq)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
>>> rev = Reverse('spam')
>>> next(rev) # note no need to call iter()
'm'
>>> nums = Reverse(range(1,10))
>>> next(nums)
9
Simplest Solution:
Tools->Kotlin->Configure Kotin in Project
Upvote if found Usefull.
Use npm run[-script] <script name>
After using npm to install the bin package to your local ./node_modules
directory, modify package.json
to add <script name>
like this:
$ npm install --save learnyounode
$ edit packages.json
>>> in packages.json
...
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"learnyounode": "learnyounode"
},
...
$ npm run learnyounode
It would be nice if npm install had a --add-script option or something or if npm run would work without adding to the scripts block.
Just in case some other poor sod ends up here because they are having the same issue I was: if you have multiple data sources and this is happening with the non-primary data source, then the problem might be with that config. The data source, entity manager factory, and transaction factory all need to be correctly configured, but also -- and this is what tripped me up -- MAKE SURE TO TIE THEM ALL TOGETHER! @EnableJpaRepositories
(configuration class annotation) must include entityManagerFactoryRef
and transactionManagerRef
to pick up all the configuration!
The example in this blog finally helped me see what I was missing, which (for quick reference) were the refs here:
@EnableJpaRepositories(
entityManagerFactoryRef = "barEntityManagerFactory",
transactionManagerRef = "barTransactionManager",
basePackages = "com.foobar.bar")
Hope this helps save someone else from the struggle I've endured!
Facelets is a XML based view technology which uses XHTML+XML to generate HTML output. XML has five special characters which has special treatment by the XML parser:
<
the start of a tag.>
the end of a tag."
the start and end of an attribute value.'
the alternative start and end of an attribute value.&
the start of an entity (which ends with ;
).In case of <
, the XML parser is implicitly looking for the tag name and the end tag >
. However, in your particular case, you were using <
as a JavaScript operator, not as an XML entity. This totally explains the XML parsing error you got:
The content of elements must consist of well-formed character data or markup.
In essence, you're writing JavaScript code in the wrong place, a XML document instead of a JS file, so you should be escaping all XML special characters accordingly. The <
must be escaped as <
.
So, essentially, the
for (var i = 0; i < length; i++) {
must become
for (var i = 0; i < length; i++) {
to make it XML-valid.
However, this makes the JavaScript code harder to read and maintain. As stated in Mozilla Developer Network's excellent document Writing JavaScript for XHTML, you should be placing the JavaScript code in a character data (CDATA) block. Thus, in JSF terms, that would be:
<h:outputScript>
<![CDATA[
// ...
]]>
</h:outputScript>
The XML parser will interpret the block's contents as "plain vanilla" character data and not as XML and hence interpret the XML special characters "as-is".
But, much better is to just put the JS code in its own JS file which you include by <script src>
, or in JSF terms, the <h:outputScript>
.
<h:outputScript name="functions.js" target="head" />
This way you don't need to worry about XML-special characters in your JS code. Additional advantage is that this gives the browser the opportunity to cache the JS file so that average response size is smaller.
No jQuery needed.
Some people say using onclick
is bad practice...
This example uses pure browser javascript. By default, it appears that the click handler will evaluate before the navigation, so you can cancel the navigation and do your own if you wish.
<a id="myButton" href="http://google.com">Click me!</a>
<script>
window.addEventListener("load", () => {
document.querySelector("#myButton").addEventListener("click", e => {
alert("Clicked!");
// Can also cancel the event and manually navigate
// e.preventDefault();
// window.location = e.target.href;
});
});
</script>
It works for me: I have combined the answer of Reading a simple text file
But instead of return a String I am returning a LinkedList of Strings. Then I can select the line that I want.
public static LinkedList<String> readFromAssets(Context context, String filename) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(context.getAssets().open(filename)));
LinkedList<String>linkedList = new LinkedList<>();
// do reading, usually loop until end of file reading
StringBuilder sb = new StringBuilder();
String mLine = reader.readLine();
while (mLine != null) {
linkedList.add(mLine);
sb.append(mLine); // process line
mLine = reader.readLine();
}
reader.close();
return linkedList;
}
import json
json_data = json.dumps({
"result":[
{
"run":[
{
"action":"stop"
},
{
"action":"start"
},
{
"action":"start"
}
],
"find": "true"
}
]
})
item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])
Convert it in dict.
You cannot open Java Applets (nor any other NPAPI plugin) in Microsoft Edge - they aren't supported and won't be added in the future.
Further you should be aware that in the next release of Google Chrome (v45 - due September 2015) NPAPI plugins will also no longer be supported.
There are a couple of things that you can do:
Use Internet Explorer 11
You will find that in Windows 10 you will already have Internet Explorer 11 installed. IE 11 continues to support NPAPI (incl Java Applets).
IE11 is squirrelled away (c:\program files\internet explorer\iexplore.exe
). Just pin this exe to your task bar for easy access.
Use FireFox
You can also install and use a Firefox 32-bit Extended Support Release in Win10. Firefox have disabled NPAPI by default, but this can be overridden. This will only be supported until early 2018.
The getPosts()
function seems to be expecting $con
to be global, but you're not declaring it as such.
A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.
Byte Stream - Stream is sequence of data. Input stream - reads data from source. Output stream - writes data to desitnation. Java Byte Streams are used to perform input/output byte by byte(8bits at a time). A byte stream is suitable for processing raw data like binary files. Java Character Streams are used to perform input/output 2 bytes at a time, because Characters are stored using Unicode conventions in Java with 2 bytes for each character. Character stream is useful when we process(read/write) text files.
RMI(Remote Method Invocation) - an API that provides a mechanism to create distributed application in java. The RMI allows an object to invoke methods on an object running in another JVM.
Both Serialization and Marshalling are loosely used as synonyms. Here are few differences.
Serialization - Data members of an object is written to binary form or Byte Stream(and then can be written in file/memory/database etc). No information about data-types can be retained once object data members are written to binary form.
Marshalling - Object is serialized(to byte stream in binary format) with data-type + Codebase attached and then passed Remote Object(RMI). Marshalling will transform the data-type into a predetermined naming convention so that it can be reconstructed with respect to the initial data-type.
So Serialization is part of Marshalling.
CodeBase is information that tells the receiver of Object where the implementation of this object can be found. Any program that thinks it might ever pass an object to another program that may not have seen it before must set the codebase, so that the receiver can know where to download the code from, if it doesn't have the code available locally. The receiver will, upon deserializing the object, fetch the codebase from it and load the code from that location. (Copied from @Nasir answer)
Serialization is almost like a stupid memory-dump of the memory used by the object(s), while Marshalling stores information about custom data-types.
In a way, Serialization performs marshalling with implematation of pass-by-value because no information of data-type is passed, just the primitive form is passed to byte stream.
Serialization may have some issues related to big-endian, small-endian if the stream is going from one OS to another if the different OS have different means of representing the same data. On the other hand, marshalling is perfectly fine to migrate between OS because the result is a higher-level representation.
use the --expression option
grep searchterm myfile.csv | sed --expression='s/replaceme/withthis/g'
This works both ways and it is simple and clean
JavaScript
var app = angular.module("app");
app.controller("SamePaswordController", function () {
this.password;
this.confirm;
this.save = function () {
alert("Saved!");
};
}
app.directive("match", function () {
return {
restrict:"A",
require:"ngModel",
link: function(scope, element, attrs, ctrl) {
function matchValidator(value) {
scope.$watch(attrs.match, function(newValue, oldValue) {
var isValid = value === scope.$eval(attrs.match);
ctrl.$setValidity('match', isValid);
});
return value;
}
ctrl.$parsers.push(matchValidator);
}
};
});
HTML: note the match directive
<form name="regForm" ng-controller="SamePaswordController as regCtrl"
ng-submit="regForm.$valid && regCtrl.save()" novalidate>
<input name="password" ng-model="regCtrl.password"
type="password" required placeholder="Password"/>
<input name="confirm" ng-model="regCtrl.confirm" match="regCtrl.password"
type="password" required placeholder="Confirm password"/>
<div> regForm is valid:{{regForm.$valid}}</div>
<input type="submit" value="Save"/>
</form>
You can clone the repo with this example https://github.com/rogithub/roangularjs
To search in current directory recursively:
grep -r 'myString' .
Pushed the top answers into a prototype to sort by key.
Array.prototype.alphaSortByKey= function (key) {
this.sort(function (a, b) {
if (a[key] < b[key])
return -1;
if (a[key] > b[key])
return 1;
return 0;
});
return this;
};
var context = new DatabaseEntities();
var t = new test //Make sure you have a table called test in DB
{
ID = Guid.NewGuid(),
name = "blah",
};
context.test.Add(t);
context.SaveChanges();
Should do it
When you give id as a primary key then a pop up is come and those aske you to how many size of this primary key. So you just leave blank because by default int value is set 11. Click then ok on those pop up without any enter a number. in this type of error never will you face in future. Thank you
CREATE OR REPLACE FUNCTION HASTANE.getXXXXX(p_rowid in rowid) return VARCHAR2
as
l_data long;
begin
select XXXXXX into l_data from XXXXX where rowid = p_rowid;
return substr( l_data, 1, 4000);
end getlabrapor1;
How about putting the comments in a non-eval, non-echo R block? i.e.,
```{r echo=FALSE, eval=FALSE}
All the comments!
```
Seems to work well for me.
The Easiest way to implement scrollbar using java swing is as below :
I suspect wpis.entry.lastChangeDate
has been somehow transformed into a string in the view, before arriving to the template.
In order to verify this hypothesis, you may just check in the view if it has some property/method that only strings have - like for instance wpis.entry.lastChangeDate.upper
, and then see if the template crashes.
You could also create your own custom filter, and use it for debugging purposes, letting it inspect the object, and writing the results of the inspection on the page, or simply on the console. It would be able to inspect the object, and check if it is really a DateTimeField.
On an unrelated notice, why don't you use models.DateTimeField(
auto_now_add
=True)
to set the datetime on creation?
Use the built-in timestamps
option for your Schema.
var ItemSchema = new Schema({
name: { type: String, required: true, trim: true }
},
{
timestamps: true
});
This will automatically add createdAt
and updatedAt
fields to your schema.
You can skip the ORM, builders, etc. and simplify your DB/SQL management using sqler
and sqler-mdb
.
-- create this file at: db/mdb/setup/create.database.sql
CREATE DATABASE IF NOT EXISTS sqlermysql
const conf = {
"univ": {
"db": {
"mdb": {
"host": "localhost",
"username":"admin",
"password": "mysqlpassword"
}
}
},
"db": {
"dialects": {
"mdb": "sqler-mdb"
},
"connections": [
{
"id": "mdb",
"name": "mdb",
"dir": "db/mdb",
"service": "MySQL",
"dialect": "mdb",
"pool": {},
"driverOptions": {
"connection": {
"multipleStatements": true
}
}
}
]
}
};
// create/initialize manager
const manager = new Manager(conf);
await manager.init();
// .sql file path is path to db function
const result = await manager.db.mdb.setup.create.database();
console.log('Result:', result);
// after we're done using the manager we should close it
process.on('SIGINT', async function sigintDB() {
await manager.close();
console.log('Manager has been closed');
});
There is no way for the system to tell you if a String
represent a file
or directory
, if it does not exist in the file system. For example:
Path path = Paths.get("/some/path/to/dir");
System.out.println(Files.isDirectory(path)); // return false
System.out.println(Files.isRegularFile(path)); // return false
And for the following example:
Path path = Paths.get("/some/path/to/dir/file.txt");
System.out.println(Files.isDirectory(path)); //return false
System.out.println(Files.isRegularFile(path)); // return false
So we see that in both case system return false. This is true for both java.io.File
and java.nio.file.Path
From the official documentation at http://api.jquery.com/jQuery.browser/:
This property was removed in jQuery 1.9 and is available only through the jQuery.migrate plugin.
You can use for example jquery-migrate-1.4.1.js
to keep your existing code or plugins that use $.browser still working while you find a way to totally get rid of $.browser from your code in the future.
The .success
syntax was correct up to Angular v1.4.3.
For versions up to Angular v.1.6, you have to use then
method. The then()
method takes two arguments: a success
and an error
callback which will be called with a response object.
Using the then()
method, attach a callback
function to the returned promise
.
Something like this:
app.controller('MainCtrl', function ($scope, $http){
$http({
method: 'GET',
url: 'api/url-api'
}).then(function (response){
},function (error){
});
}
See reference here.
Shortcut
methods are also available.
$http.get('api/url-api').then(successCallback, errorCallback);
function successCallback(response){
//success code
}
function errorCallback(error){
//error code
}
The data you get from the response is expected to be in JSON
format.
JSON is a great way of transporting data, and it is easy to use within AngularJS
The major difference between the 2 is that .then()
call returns a promise
(resolved with a value returned from a callback
) while .success()
is more traditional way of registering callbacks
and doesn't return a promise
.
If you are looking for TypeScript working functions then follow
public numericValue = (alphaChar: any) => alphaChar.toUpperCase().charCodeAt(0) - 64;
public alphaValue = (numericDigit: any) =>
String.fromCharCode(64 + numericDigit) : '';
You can make several checks like (numericDigit >= 1 && numericDigit <= 26) ?
inside function body as per the requirements.
I had the same issue today. I solve this problem by removing any PATH
in .bashrc
for older rvm
.
If you use the java keyword abstract
you cannot provide an implementation.
Sometimes this idea comes from having a background in C++ and mistaking the virtual
keyword in C++ as being "almost the same" as the abstract
keyword in Java.
In C++ virtual
indicates that a method can be overridden and polymorphism will follow, but abstract
in Java is not the same thing. In Java abstract
is more like a pure virtual
method, or one where the implementation must be provided by a subclass. Since Java supports polymorphism without the need to declare it, all methods are virtual
from a C++ point of view. So if you want to provide a method that might be overridden, just write it as a "normal" method.
Now to protect a method from being overridden, Java uses the keyword final
in coordination with the method declaration to indicate that subclasses cannot override the method.
#father {
position: relative;
}
#son1 {
position: absolute;
top: 0;
}
#son2 {
position: absolute;
bottom: 0;
}
This works because position: absolute
means something like "use top
, right
, bottom
, left
to position yourself in relation to the nearest ancestor who has position: absolute
or position: relative
."
So we make #father
have position: relative
, and the children have position: absolute
, then use top
and bottom
to position the children.
In Robins's answer ends-with is not supported in xpath 1.0 too.. Only starts-with is supported... So if your condition is not very specific..You can Use like this which worked for me
//*[starts-with(@id,'sometext') and contains(@name,'_text')]`\
<?php
date_default_timezone_set('GMT-5');//Set New York timezone
$today = date("F j, Y")
?>
Yes. You can pass the numerical values to the constructor for the enum, like so:
enum Ids {
OPEN(100),
CLOSE(200);
private int value;
private Ids(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
See the Sun Java Language Guide for more information.
I got the same error because I had accidentally used <div>
instead of <canvas>
as the element on which I attempt to call getContext
.
You seem to be confusing asynchronous IO with asynchronous functions. node.js uses asynchronous non-blocking IO because non blocking IO is better. The best way to understand it is to go watch some videos by ryan dahl.
How do I write asynchronous functions for Node?
Just write normal functions, the only difference is that they are not executed immediately but passed around as callbacks.
How should I implement error event handling correctly
Generally API's give you a callback with an err as the first argument. For example
database.query('something', function(err, result) {
if (err) handle(err);
doSomething(result);
});
Is a common pattern.
Another common pattern is on('error')
. For example
process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
});
Edit:
var async_function = function(val, callback){
process.nextTick(function(){
callback(val);
});
};
The above function when called as
async_function(42, function(val) {
console.log(val)
});
console.log(43);
Will print 42
to the console asynchronously. In particular process.nextTick
fires after the current eventloop callstack is empty. That call stack is empty after async_function
and console.log(43)
have run. So we print 43 followed by 42.
You should probably do some reading on the event loop.
Use the setAttribute property. Note in example that if select 1 apply the readonly attribute on textbox, otherwise remove the attribute readonly.
http://jsfiddle.net/baqxz7ym/2/
document.getElementById("box1").onchange = function(){
if(document.getElementById("box1").value == 1) {
document.getElementById("codigo").setAttribute("readonly", true);
} else {
document.getElementById("codigo").removeAttribute("readonly");
}
};
<input type="text" name="codigo" id="codigo"/>
<select id="box1">
<option value="0" >0</option>
<option value="1" >1</option>
<option value="2" >2</option>
</select>
Simply import the Android library project as a module and in Build.gradle.
Apply plugin: 'com.android.library'
After that, follow these steps:
It's not a cut and paste. The CASE
expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:
SELECT * FROM [Purchasing].[Vendor] WHERE
CASE
WHEN @url IS null OR @url = '' OR @url = 'ALL'
THEN PurchasingWebServiceURL LIKE '%'
WHEN @url = 'blank'
THEN PurchasingWebServiceURL = ''
WHEN @url = 'fail'
THEN PurchasingWebServiceURL NOT LIKE '%treyresearch%'
ELSE PurchasingWebServiceURL = '%' + @url + '%'
END
I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.
However, since @url
is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?
You would do:
char c = str[1];
Or even:
char c = "Hello"[1];
edit: updated to find the "E".
What is the difference between g++
and gcc
?
gcc
has evolved from a single language "GNU C Compiler" to be a multi-language "GNU Compiler Collection". The term "GNU C Compiler" is still used sometimes in the context of C programming.
The g++
is the C++ compiler for the GNU Compiler Collection. Like gnat
is the Ada compiler for gcc
. see Using the GNU Compiler Collection (GCC)
For example, the Ubuntu 16.04 and 18.04 man g++
command returns the GCC(1)
manual page.
The Ubuntu 16.04 and 18.04 man gcc
states that ...
g++
accepts mostly the same options asgcc
and that the default ...
... use of
gcc
does not add the C++ library.g++
is a program that calls GCC and automatically specifies linking against the C++ library. It treats .c, .h and .i files as C++ source files instead of C source files unless -x is used. This program is also useful when precompiling a C header file with a .h extension for use in C++ compilations.
Search the gcc
man pages for more details on the option variances between gcc
and g++
.
Which one should be used for general c++ development?
Technically, either gcc
or g++
can be used for general C++ development with applicable option settings. However, the g++
default behavior is naturally aligned to a C++ development.
The Ubuntu 18.04 'gcc' man page added, and Ubuntu 20.04 continues to have, the following paragraph:
The usual way to run GCC is to run the executable called
gcc
, ormachine-gcc
when cross-compiling, ormachine-gcc-version
to run a specific version of GCC. When you compile C++ programs, you should invoke GCC asg++
instead.
mvn -Dschemaname=public liquibase:update
I had a column(A) in a data frame with 3 values in it (yes, no, unknown). I wanted to filter only those rows which had a value "yes" for which this is the code, hope this will help you guys as well --
df <- df [(!(df$A=="no") & !(df$A=="unknown")),]
Note that you can also use the C99 fixed-width types perfectly well in Objective-C:
#import <stdint.h>
...
int32_t x; // guaranteed to be 32 bits on any platform
The wikipedia page has a decent description of what's available in this header if you don't have a copy of the C standard (you should, though, since Objective-C is just a tiny extension of C). You may also find the headers limits.h
and inttypes.h
to be useful.
I have Nginx and With below Nginx Config:
server {
listen 80;
server_name xxxxxx;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://x.x.x.x:8000;
}
}
@tirtha-r solution worked for me
#!flask/bin/python
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/', methods=['GET'])
def get_tasks():
if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
return jsonify({'ip': request.environ['REMOTE_ADDR']}), 200
else:
return jsonify({'ip': request.environ['HTTP_X_FORWARDED_FOR']}), 200
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0', port=8000)
My Request and Response:
curl -X GET http://test.api
{
"ip": "Client Ip......"
}
I just found the way. Right click on the desired package then Source
-> Organize Imports
.
Shortcut keys:
If you already have the figure object use:
f.set_figheight(15)
f.set_figwidth(15)
But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:
f, axs = plt.subplots(2,2,figsize=(15,15))
I modified Zack's answer since I wanted spaces and interpolation but not newlines and used:
%W[
It's a nice day "#{name}"
for a walk!
].join(' ')
where name = 'fred'
this produces It's a nice day "fred" for a walk!
I previously had the same issue, but I realized that I didn't include the "app.js
" (the main application) inside my main page (index.html
).
So even when you include all the dependencies required by AngularJS, you might end up with that error in the console. So always make sure to include the necessary files inside your main page and you shouldn't have that issue.
Hope this helps.
First, any time you run a script using the interpreter explicitly, as in
$ python ./my_script.py
$ ksh ~/bin/redouble.sh
$ lua5.1 /usr/local/bin/osbf3
the #!
line is always ignored. The #!
line is a Unix feature of executable scripts only, and you can see it documented in full on the man page for execve(2)
. There you will find that the word following #!
must be the pathname of a valid executable. So
#!/usr/bin/env python
executes whatever python
is on the users $PATH
. This form is resilient to the Python interpreter being moved around, which makes it somewhat more portable, but it also means that the user can override the standard Python interpreter by putting something ahead of it in $PATH
. Depending on your goals, this behavior may or may not be OK.
Next,
#!/usr/bin/python
deals with the common case that a Python interpreter is installed in /usr/bin
. If it's installed somewhere else, you lose. But this is a good way to ensure you get exactly the version you want or else nothing at all ("fail-stop" behavior), as in
#!/usr/bin/python2.5
Finally,
#!python
works only if there is a python
executable in the current directory when the script is run. Not recommended.
I usually do like this to remove most of the noise:
void LogException(Exception error) {
Exception realerror = error;
while (realerror.InnerException != null)
realerror = realerror.InnerException;
Console.WriteLine(realerror.ToString())
}
Edit: I forgot about this answer and is surprised no one pointed out that you can just do
void LogException(Exception error) {
Console.WriteLine(error.GetBaseException().ToString())
}
one of the easy way to do that is use landa function without any problem like
userControl_Material1.simpleButton4.Click += (s, ee) =>
{
Save_mat(mat_global);
};
Terminate the Timer once after awake at a specific time in milliseconds.
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
System.out.println(" Run spcific task at given time.");
t.cancel();
}
}, 10000);
I have a slightly different approach that might be useful/more beneficial to some.
Under your main project folder, create a resource folder. Your folder structure should look something like this.
Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.
Under categories on the left side, select Sources.
In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.
You should now be able to pull resources using this line or similar approach:
MyClass.class.getResource("/main.jpg");
If you were to create a package called Images under the resources folder, you can retrieve the resource like this:
MyClass.class.getResource("/Images/main.jpg");
The problem is with Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
this line. The Class qualified name is wrong
It is sqlserver.jdbc
not jdbc.sqlserver
The differences between Model()
and Model.objects.create()
are the following:
INSERT vs UPDATE
Model.save()
does either INSERT or UPDATE of an object in a DB, while Model.objects.create()
does only INSERT.
Model.save()
does
UPDATE If the object’s primary key attribute is set to a value that evaluates to True
INSERT If the object’s primary key attribute is not set or if the UPDATE didn’t update anything (e.g. if primary key is set to a value that doesn’t exist in the database).
Existing primary key
If primary key attribute is set to a value and such primary key already exists, then Model.save()
performs UPDATE, but Model.objects.create()
raises IntegrityError
.
Consider the following models.py:
class Subject(models.Model):
subject_id = models.PositiveIntegerField(primary_key=True, db_column='subject_id')
name = models.CharField(max_length=255)
max_marks = models.PositiveIntegerField()
Insert/Update to db with Model.save()
physics = Subject(subject_id=1, name='Physics', max_marks=100)
physics.save()
math = Subject(subject_id=1, name='Math', max_marks=50) # Case of update
math.save()
Result:
Subject.objects.all().values()
<QuerySet [{'subject_id': 1, 'name': 'Math', 'max_marks': 50}]>
Insert to db with Model.objects.create()
Subject.objects.create(subject_id=1, name='Chemistry', max_marks=100)
IntegrityError: UNIQUE constraint failed: m****t.subject_id
Explanation: In the example, math.save()
does an UPDATE (changes name
from Physics to Math, and max_marks
from 100 to 50), because subject_id
is a primary key and subject_id=1
already exists in the DB. But Subject.objects.create()
raises IntegrityError
, because, again the primary key subject_id
with the value 1
already exists.
Forced insert
Model.save()
can be made to behave as Model.objects.create()
by using force_insert=True
parameter: Model.save(force_insert=True)
.
Return value
Model.save()
return None
where Model.objects.create()
return model instance i.e. package_name.models.Model
Conclusion: Model.objects.create()
does model initialization and performs save()
with force_insert=True
.
Excerpt from the source code of Model.objects.create()
def create(self, **kwargs):
"""
Create a new object with the given kwargs, saving it to the database
and returning the created object.
"""
obj = self.model(**kwargs)
self._for_write = True
obj.save(force_insert=True, using=self.db)
return obj
For more details follow the links:
To hide Navigation bar :
[self.navigationController setNavigationBarHidden:YES animated:YES];
To show Navigation bar :
[self.navigationController setNavigationBarHidden:NO animated:YES];
string nonNormalized = "\r\n\n\r";
string normalized = nonNormalized.Replace("\r", "\n").Replace("\n", "\r\n");
This won't fail on Linq2Objects, but it will fail for Linq2SQL, so I am assuming that you are talking about the SQL provider or something similar.
The reason has to do with the way that the SQL provider handles your lambda expression. It doesn't take it as a function Func<P,T>
, but an expression Expression<Func<P,T>>
. It takes that expression tree and translates it so an actual SQL statement, which it sends off to the server.
The translator knows how to handle basic operators, but it doesn't know how to handle methods on objects. It doesn't know that IsNullOrEmpty(x)
translates to return x == null || x == string.empty
. That has to be done explicitly for the translation to SQL to take place.
Go to the traffic section inside graphs. Here you can find how many unique visitors you have. Other than this there is no other way to know who exactly viewed your account.
Weight sum works exactly as you want (like other answers you don't have to sum all the weights on parent layout). On child view specify the weight you want it to take. Don't forget to specify
android:layout_width="0dp"
Following is an example
<LinearLayout
android:layout_width="500dp"
android:layout_height="20dp" >
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:background="@android:color/holo_green_light"
android:gravity="center"
android:text="30%"
android:textColor="@android:color/white" >
</TextView>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="@android:color/holo_blue_bright"
android:gravity="center"
android:text="20%"
android:textColor="@android:color/white" >
</TextView>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:background="@android:color/holo_orange_dark"
android:gravity="center"
android:text="50%"
android:textColor="@android:color/white" >
</TextView>
</LinearLayout>
This will look like
Assuming you have a test.json
file with the following content:
{"67790": {"1": {"kwh": 319.4}}}
Then, the code below will load
the json file, update the data inside using dict.update()
and dump
into the test.json
file:
import json
a_dict = {'new_key': 'new_value'}
with open('test.json') as f:
data = json.load(f)
data.update(a_dict)
with open('test.json', 'w') as f:
json.dump(data, f)
Then, in test.json
, you'll have:
{"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}
Hope this is what you wanted.
If you changed a namespace make sure to right click and refactor.
The window.navigator.onLine
attribute and its associated events are currently unreliable on certain web browsers (especially Firefox desktop) as @Junto said, so I wrote a little function (using jQuery) that periodically checks the network connectivity status and raise the appropriate offline
and online
events:
// Global variable somewhere in your app to replicate the
// window.navigator.onLine variable (this last is not modifiable). It prevents
// the offline and online events to be triggered if the network
// connectivity is not changed
var IS_ONLINE = true;
function checkNetwork() {
$.ajax({
// Empty file in the root of your public vhost
url: '/networkcheck.txt',
// We don't need to fetch the content (I think this can lower
// the server's resources needed to send the HTTP response a bit)
type: 'HEAD',
cache: false, // Needed for HEAD HTTP requests
timeout: 2000, // 2 seconds
success: function() {
if (!IS_ONLINE) { // If we were offline
IS_ONLINE = true; // We are now online
$(window).trigger('online'); // Raise the online event
}
},
error: function(jqXHR) {
if (jqXHR.status == 0 && IS_ONLINE) {
// We were online and there is no more network connection
IS_ONLINE = false; // We are now offline
$(window).trigger('offline'); // Raise the offline event
} else if (jqXHR.status != 0 && !IS_ONLINE) {
// All other errors (404, 500, etc) means that the server responded,
// which means that there are network connectivity
IS_ONLINE = true; // We are now online
$(window).trigger('online'); // Raise the online event
}
}
});
}
You can use it like this:
// Hack to use the checkNetwork() function only on Firefox
// (http://stackoverflow.com/questions/5698810/detect-firefox-browser-with-jquery/9238538#9238538)
// (But it may be too restrictive regarding other browser
// who does not properly support online / offline events)
if (!(window.mozInnerScreenX == null)) {
window.setInterval(checkNetwork, 30000); // Check the network every 30 seconds
}
To listen to the offline and online events (with the help of jQuery):
$(window).bind('online offline', function(e) {
if (!IS_ONLINE || !window.navigator.onLine) {
alert('We have a situation here');
} else {
alert('Battlestation connected');
}
});
You need to create installer, which will check if user has required .NET Framework 4.0. You can use WiX to create installer. It's very powerfull and customizable. Also you can use ClickOnce to create installer - it's very simple to use. It will allow you with one click add requirement to install .NET Framework 4.0.
The most useful thing you can do here is display/i $pc
, before using stepi
as already suggested in R Samuel Klatchko's answer. This tells gdb to disassemble the current instruction just before printing the prompt each time; then you can just keep hitting Enter to repeat the stepi
command.
(See my answer to another question for more detail - the context of that question was different, but the principle is the same.)
Just create your own action.
namespace WpfUtil
{
using System.Reflection;
using System.Windows;
using System.Windows.Interactivity;
/// <summary>
/// Sets the designated property to the supplied value. TargetObject
/// optionally designates the object on which to set the property. If
/// TargetObject is not supplied then the property is set on the object
/// to which the trigger is attached.
/// </summary>
public class SetPropertyAction : TriggerAction<FrameworkElement>
{
// PropertyName DependencyProperty.
/// <summary>
/// The property to be executed in response to the trigger.
/// </summary>
public string PropertyName
{
get { return (string)GetValue(PropertyNameProperty); }
set { SetValue(PropertyNameProperty, value); }
}
public static readonly DependencyProperty PropertyNameProperty
= DependencyProperty.Register("PropertyName", typeof(string),
typeof(SetPropertyAction));
// PropertyValue DependencyProperty.
/// <summary>
/// The value to set the property to.
/// </summary>
public object PropertyValue
{
get { return GetValue(PropertyValueProperty); }
set { SetValue(PropertyValueProperty, value); }
}
public static readonly DependencyProperty PropertyValueProperty
= DependencyProperty.Register("PropertyValue", typeof(object),
typeof(SetPropertyAction));
// TargetObject DependencyProperty.
/// <summary>
/// Specifies the object upon which to set the property.
/// </summary>
public object TargetObject
{
get { return GetValue(TargetObjectProperty); }
set { SetValue(TargetObjectProperty, value); }
}
public static readonly DependencyProperty TargetObjectProperty
= DependencyProperty.Register("TargetObject", typeof(object),
typeof(SetPropertyAction));
// Private Implementation.
protected override void Invoke(object parameter)
{
object target = TargetObject ?? AssociatedObject;
PropertyInfo propertyInfo = target.GetType().GetProperty(
PropertyName,
BindingFlags.Instance|BindingFlags.Public
|BindingFlags.NonPublic|BindingFlags.InvokeMethod);
propertyInfo.SetValue(target, PropertyValue);
}
}
}
In this case I'm binding to a property called DialogResult on my viewmodel.
<Grid>
<Button>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
Cancel
</Button>
</Grid>
There are a couple of options. You can use the --device
flag that use can use to access USB devices without --privileged
mode:
docker run -t -i --device=/dev/ttyUSB0 ubuntu bash
Alternatively, assuming your USB device is available with drivers working, etc. on the host in /dev/bus/usb
, you can mount this in the container using privileged mode and the volumes option. For example:
docker run -t -i --privileged -v /dev/bus/usb:/dev/bus/usb ubuntu bash
Note that as the name implies, --privileged
is insecure and should be handled with care.
For primitive array types, you would have to write a reverse sort algorithm:
Alternatively, you can convert your int[]
to Integer[]
and write a comparator:
public class IntegerComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
}
or use Collections.reverseOrder()
since it only works on non-primitive array types.
and finally,
Integer[] a2 = convertPrimitiveArrayToBoxableTypeArray(a1);
Arrays.sort(a2, new IntegerComparator()); // OR
// Arrays.sort(a2, Collections.reverseOrder());
//Unbox the array to primitive type
a1 = convertBoxableTypeArrayToPrimitiveTypeArray(a2);
According to the docs, it means the total number throughout history:
Connections
The number of connection attempts (successful or not) to the MySQL server.
You can see the number of active connections either through the Threads_connected
status variable:
Threads_connected
The number of currently open connections.
mysql> show status where `variable_name` = 'Threads_connected';
+-------------------+-------+
| Variable_name | Value |
+-------------------+-------+
| Threads_connected | 4 |
+-------------------+-------+
1 row in set (0.00 sec)
... or through the show processlist
command:
mysql> show processlist;
+----+------+-----------------+--------+---------+------+-------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+------+-----------------+--------+---------+------+-------+------------------+
| 3 | root | localhost | webapp | Query | 0 | NULL | show processlist |
| 5 | root | localhost:61704 | webapp | Sleep | 208 | | NULL |
| 6 | root | localhost:61705 | webapp | Sleep | 208 | | NULL |
| 7 | root | localhost:61706 | webapp | Sleep | 208 | | NULL |
+----+------+-----------------+--------+---------+------+-------+------------------+
4 rows in set (0.00 sec)
You can create an element with an id and then assign that length value to that element.
var name = prompt("What's your name?");_x000D_
var lengthOfName = name.length_x000D_
document.getElementById('message').innerHTML = lengthOfName;
_x000D_
<p id='message'></p>
_x000D_
<script type="text/javascript">
if(jQuery('input[id=input_id]').is(':checked')){
// Your Statment
}else{
// Your Statment
}
OR
if(jQuery('input[name=input_name]').is(':checked')){
// Your Statment
}else{
// Your Statment
}
</script>
Code taken from here : http://chandreshrana.blogspot.in/2015/10/how-to-check-if-checkbox-is-checked-or.html
You can also just search on sites like Tucows and CNET, they have it there too.
After t.thielemans' answer, I worked that just
=VLOOKUP(A1, B:C, 2, FALSE)
works fine and does what I wanted, except that it returns #N/A
for non-matches; so it is suitable for the case where it is known that the value definitely exists in the look-up column.
Edit (based on t.thielemans' comment):
To avoid #N/A
for non-matches, do:
=IFERROR(VLOOKUP(A1, B:C, 2, FALSE), "No Match")
UPDATE
T1
SET
T1.Inci = T2.Inci
FROM
T1
INNER JOIN
T2
ON
T1.Brands = T2.Brands
AND
T1.Category= T2.Category
AND
T1.Date = T2.Date
I had to use the following construct in jQuery UI 1.8.22:
var buttons = $('.ui-dialog-buttonset').children('button');
buttons.removeClass().addClass('button');
This removes all formatting and applies the replacement styling as needed.
Works in most major browsers.
I had a similar requirement in the app I am working on. And, I found a third-party library which does a slide-up, slide-down and slide-right in Android.
Refer to the link for more details: https://github.com/mancj/SlideUp-Android
To set up the library(copied from the ReadMe portion of its Github page on request):
Get SlideUp library
Add the JitPack repository to your build file. Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
maven { url "https://maven.google.com" } // or google() in AS 3.0
}
}
Add the dependency (in the Module gradle)
dependencies {
compile 'com.github.mancj:SlideUp-Android:2.2.1'
compile 'ru.ztrap:RxSlideUp2:2.x.x' //optional, for reactive listeners based on RxJava-2
compile 'ru.ztrap:RxSlideUp:1.x.x' //optional, for reactive listeners based on RxJava
}
To add the SlideUp into your project, follow these three simple steps:
Step 1:
create any type of layout
<LinearLayout
android:id="@+id/slideView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Step 2:
Find that view in your activity/fragment
View slideView = findViewById(R.id.slideView);
Step 3:
Create a SlideUp object and pass in your view
slideUp = new SlideUpBuilder(slideView)
.withStartState(SlideUp.State.HIDDEN)
.withStartGravity(Gravity.BOTTOM)
//.withSlideFromOtherView(anotherView)
//.withGesturesEnabled()
//.withHideSoftInputWhenDisplayed()
//.withInterpolator()
//.withAutoSlideDuration()
//.withLoggingEnabled()
//.withTouchableAreaPx()
//.withTouchableAreaDp()
//.withListeners()
//.withSavedState()
.build();
You may also refer to the sample project on the link. I found it quite useful.
EDIT: Only after posting this, did I realize that @350D's answer does the exact same thing.
Surprisingly, this can be done in just 4 lines of code:
const canvas = document.getElementById("canvas"),
preview = document.getElementById("preview"),
ctx = canvas.getContext("2d");
canvas.width = 1;
canvas.height = 1;
preview.width = 400;
preview.height = 400;
function getDominantColor(imageObject) {
//draw the image to one pixel and let the computer find the dominant color
ctx.drawImage(imageObject, 0, 0, 1, 1);
//get pixel color
const i = ctx.getImageData(0, 0, 1, 1).data;
console.log(`rgba(${i[0]},${i[1]},${i[2]},${i[3]})`);
console.log("#" + ((1 << 24) + (i[0] << 16) + (i[1] << 8) + i[2]).toString(16).slice(1));
}
// vvv all of this is to just get the uploaded image vvv
const input = document.getElementById("input");
input.type = "file";
input.accept = "image/*";
input.onchange = event => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = readerEvent => {
const image = new Image();
image.onload = function() {
//shows preview of uploaded image
preview.getContext("2d").drawImage(
image,
0,
0,
preview.width,
preview.height,
);
getDominantColor(image);
};
image.src = readerEvent.target.result;
};
reader.readAsDataURL(file, "UTF-8");
};
_x000D_
canvas {
width: 200px;
height: 200px;
outline: 1px solid #000000;
}
_x000D_
<canvas id="preview"></canvas>
<canvas id="canvas"></canvas>
<input id="input" type="file" />
_x000D_
How it works:
Create the canvas context
const context = document.createElement("canvas").getContext("2d");
This will draw the image to only one canvas pixel, making the browser find the dominant color for you.
context.drawImage(imageObject, 0, 0, 1, 1);
After that, just get the image data for the pixel:
const i = context.getImageData(0, 0, 1, 1).data;
Finally, convert to rgba
or HEX
:
const rgba = `rgba(${i[0]},${i[1]},${i[2]},${i[3]})`;
const HEX = "#" + ((1 << 24) + (i[0] << 16) + (i[1] << 8) + i[2]).toString(16).slice(1);
There is one problem with this method though, and that is that getImageData
will sometimes throw errors Unable to get image data from canvas because the canvas has been tainted by cross-origin data.
, which is the reason you need to upload images in the demo instead of inputting a URL for example.
This method can also be used for pixelating images by increasing the width and height to draw the image.
This works on chrome but may not on other browsers.
Create a .env file that will hold your credentials at the root of your project and leave it out of versioning:
$ echo ".env" >> .gitignore
In the .env file, add the variables (adapt them according to your installation):
$ echo "DJANGO_SETTINGS_MODULE=myproject.settings.production"> .env
#50 caracter random key
$ echo "SECRET_KEY='####'">> .env
To use them, put this on top of your production.py settings file:
import os
env = os.environ.copy()
SECRET_KEY = env['SECRET_KEY']
Publish it to Heroku using this gem: http://github.com/ddollar/heroku-config.git
$ heroku plugins:install git://github.com/ddollar/heroku-config.git
$ heroku config:push
This way you avoid to change virtualenv files.
*Based on this tutorial
Try this (on the guest machine. i.e. the OS running in the Virtual box):
sudo adduser your-user vboxsf
Now reboot the OS running in the virtual box.
instead of 100% i just add some pixxel got this now and it works for whole page without gap:
html {
height: 1420px; }
body {
height: 1400px;
margin: 0;
background-repeat: no-repeat; }
We had the exact exception (using SpringSource Tools, tomcat, on Win7) and the cause was that we had refactored a filename (renamed a file) from SubDomain.java to Subdomain.java (D vs d) and somehow it collided though SpringSource was showing the new name Subdomain.java. The solution was to delete the file (via SpringSource) and create it again under the name Subdomain.java and copy-pasting its former content. Simple as that.
Making this case insensitive wasn't working in asp.net so I just specified each of the letters.
Here's what I had to do to get it working in an asp.net RegularExpressionValidator:
[Hh][Tt][Tt][Pp][Ss]?://(.*)
Notes:
(?i)
and using /whatever/i
didn't work probably because javascript hasn't brought in all case sensitive functionality^
at beginning but it didn't matter, but the (.*)
did (Expression didn't work without (.*)
but did work without ^
)//
though might be a good idea.Here's the full RegularExpressionValidator if you need it:
<asp:RegularExpressionValidator ID="revURLHeaderEdit" runat="server"
ControlToValidate="txtURLHeaderEdit"
ValidationExpression="[Hh][Tt][Tt][Pp][Ss]?://(.*)"
ErrorMessage="URL should begin with http:// or https://" >
</asp:RegularExpressionValidator>
pytest captures the stdout from individual tests and displays them only on certain conditions, along with the summary of the tests it prints by default.
Extra summary info can be shown using the '-r' option:
pytest -rP
shows the captured output of passed tests.
pytest -rx
shows the captured output of failed tests (default behaviour).
The formatting of the output is prettier with -r than with -s.
Here's a multiple-level sort method. I'm including a snippet from an Angular JS module, but you can accomplish the same thing by scoping the sort keys objects such that your sort function has access to them. You can see the full module at Plunker.
$scope.sortMyData = function (a, b)
{
var retVal = 0, key;
for (var i = 0; i < $scope.sortKeys.length; i++)
{
if (retVal !== 0)
{
break;
}
else
{
key = $scope.sortKeys[i];
if ('asc' === key.direction)
{
retVal = (a[key.field] < b[key.field]) ? -1 : (a[key.field] > b[key.field]) ? 1 : 0;
}
else
{
retVal = (a[key.field] < b[key.field]) ? 1 : (a[key.field] > b[key.field]) ? -1 : 0;
}
}
}
return retVal;
};
If your placeholder is in html enabled mode then "<br />"
will work as a newline
All .idea files that are explicitly ignored are still showing up to commit
you have to remove them from the staging area
git rm --cached .idea
now you have to commit those changes and they will be ignored from this point on.
Once git start to track changes it will not "stop" tracking them even if they were added to the .gitignore
file later on.
You must explicitly remove them and then commit your removal manually in order to fully ignore them.
Using Between condition
SELECT *
FROM TEST
WHERE COLUMN_NAME BETWEEN x AND y ;
Or using Just operators,
SELECT *
FROM TEST
WHERE COLUMN_NAME >= x AND COLUMN_NAME <= y;
"Note that the hard-float and soft-float ABIs are not link-compatible; you must compile your entire program with the same ABI, and link with a compatible set of libraries." https://gcc.gnu.org/onlinedocs/gcc/ARM-Options.html arm-none-eabi-gcc.exe
Silicon Labs "kjostera" "Employee" response to EFR32 Flex Gecko (crossreference Cortex-M4F): "So code compiled with the softfp ABI is not link time compatible with code compiled with hardfp ABI. So since we currently only support RAIL library compiled using the softfp ABI, this means that you will have to build your application as well using the softfp ABI."
"Note that using softfp ABI does not mean that your code cannot use FPU instructions. Any code doing floating point arithmetic will use the FPU when the compiler thinks that it makes sense."
"kjostera" then goes on to demonstrate that the GCC 7 generated Assembly for both the case of -mfloat-abi=softfp
and -mfloat-abi=hard
, the vmul.f32
instruction is invoked and the instruction count is 10 for softfp
and 9 for hard
.
https://www.silabs.com/community/mcu/32-bit/forum.topic.html/enable_fpu_in_rail-p-SEYr https://www.silabs.com/documents/public/data-sheets/efr32fg1-datasheet.pdf https://www.silabs.com/documents/public/reference-manuals/efr32xg12-rm.pdf https://www.silabs.com/documents/public/reference-manuals/efr32xg13-rm.pdf https://www.silabs.com/documents/public/reference-manuals/efr32xg14-rm.pdf
Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.
http://www.rgagnon.com/javadetails/java-0542.html
Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.
package filesendtest;
import java.io.*;
import java.net.*;
class TCPServer {
private final static String fileToSend = "C:\\test1.pdf";
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File( fileToSend );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
package filesendtest;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
private final static String serverIP = "127.0.0.1";
private final static int serverPort = 3248;
private final static String fileOutput = "C:\\testout.pdf";
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket( serverIP , serverPort );
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream( fileOutput );
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
Related
Byte array of unknown length in java
Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):
public static String md5String(File file) {
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0) {
md5er.update(buffer, 0, read);
}
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null) {
return null;
}
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
} catch (Exception e) {
return null;
}
}
You can Try this, After starting Service of elasticsearch Type below line in your browser.
localhost:9200
It will give Output Something like that,
{
"status" : 200,
"name" : "Hypnotia",
"cluster_name" : "elasticsearch",
"version" : {
"number" : "1.7.1",
"build_hash" : "b88f43fc40b0bcd7f173a1f9ee2e97816de80b19",
"build_timestamp" : "2015-07-29T09:54:16Z",
"build_snapshot" : false,
"lucene_version" : "4.10.4"
},
"tagline" : "You Know, for Search"
}
It is very easy to connect remote MySQL Server Using PHP, what you have to do is:
Create a MySQL User in remote server.
Give Full privilege to the User.
Connect to the Server using PHP Code (Sample Given Below)
$link = mysql_connect('your_my_sql_servername or IP Address', 'new_user_which_u_created', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db('sandsbtob',$link) or die ("could not open db".mysql_error());
// we connect to localhost at port 3306
I always use my own mod
function, defined as
int mod(int x, int m) {
return (x%m + m)%m;
}
Of course, if you're bothered about having two calls to the modulus operation, you could write it as
int mod(int x, int m) {
int r = x%m;
return r<0 ? r+m : r;
}
or variants thereof.
The reason it works is that "x%m" is always in the range [-m+1, m-1]. So if at all it is negative, adding m to it will put it in the positive range without changing its value modulo m.
[object Object]
is the default string representation of a JavaScript Object
. It is what you'll get if you run this code:
alert({}); // [object Object]
You can change the default representation by overriding the toString
method like so:
var o = {toString: function(){ return "foo" }};
alert(o); // foo
In some situations you may also want to ignore some files globally. For me, .DS_Store is one of them. Here's how:
git config --global core.excludesfile /Users/mat/.gitignore
(Or any file of your choice)
Then edit the file just like a repo's .gitignore. Note that I think you have to use an absolute path.
Only set the relevant / important CSS properties.
Example (only change the attributes which may cause your div to look completely different):
background: #FFF;
border: none;
color: #000;
display: block;
font: initial;
height: auto;
letter-spacing: normal;
line-height: normal;
margin: 0;
padding: 0;
text-transform: none;
visibility: visible;
width: auto;
word-spacing: normal;
z-index: auto;
Choose a very specific selector, such as div#donttouchme
, <div id="donttouchme"></div>
. Additionally, you can add `!important before every semicolon in the declaration. Your customers are deliberately trying to mess up your lay-out when this option fails.
Of course, as per all other comments here, this simply doesn't work.
I did once construct a simple java applet for a client which forced any capture of of an image to be done via screen capture and you might like to consider a similar technique. It worked, within the limitations, but I still think it was a waste of time.
Another way of solving this problem is by not relying on the correct return value from the display but relying on the Android resources resolving.
Create the file layouts.xml
in the folders res/values-land
and res/values-port
with the following content:
res/values-land/layouts.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="is_landscape">true</bool>
</resources>
res/values-port/layouts.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<bool name="is_landscape">false</bool>
</resources>
In your source code you can now access the current orientation as follows:
context.getResources().getBoolean(R.bool.is_landscape)
You can use the function RESHAPE:
B = reshape(A.',1,[]);
Create an empty file __init__.py
in subdirectory /lib.
And add at the begin of main code
from __future__ import absolute_import
then
import lib.BoxTime as BT
...
BT.bt_function()
or better
from lib.BoxTime import bt_function
...
bt_function()
#x{_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
background-color:orange;_x000D_
position:relative;_x000D_
border-radius:2px;_x000D_
}_x000D_
#x::after,#x::before{_x000D_
position:absolute;_x000D_
top:9px;_x000D_
left:0px;_x000D_
content:'';_x000D_
display:block;_x000D_
width:20px;_x000D_
height:2px;_x000D_
background-color:red;_x000D_
_x000D_
}_x000D_
#x::after{_x000D_
-webkit-transform: rotate(45deg);_x000D_
-moz-transform: rotate(45deg);_x000D_
-ms-transform: rotate(45deg);_x000D_
-o-transform: rotate(45deg);_x000D_
transform: rotate(45deg);_x000D_
}_x000D_
#x::before{_x000D_
-webkit-transform: rotate(-45deg);_x000D_
-moz-transform: rotate(-45deg);_x000D_
-ms-transform: rotate(-45deg);_x000D_
-o-transform: rotate(-45deg);_x000D_
transform: rotate(-45deg);_x000D_
}
_x000D_
<div id=x>_x000D_
</div>
_x000D_
Api Call using Model Class
let urlString = "http://--.154.--.78/------/index.php?route=api/coupon/all"
let url = URL(string: urlString)
var request = URLRequest(url: url!)
request.httpMethod = "GET"
URLSession.shared.dataTask(with:request) { (data, response, error) in
if error != nil {
print(error)
} else {
do {
let parsedDictionaryArray = try JSONSerialization.jsonObject(with: data!) as! [String:AnyObject]
print(parsedDictionaryArray)
if let arry = parsedDictionaryArray["data"] as? [[String:AnyObject]] {
for dic in arry {
let name = dic["name"]
let descriptionData = dic["description"]
self.modelReference.append(model(name: name as! String, descriptionStr: descriptionData as! String))
print(name!)
}
}
} catch let error as NSError {
print(error)
}
}
}.resume()
create a variable and connect with model class
var modelReference = [model]()
create a model class New -> swift class
import Foundation
class model : NSObject{
var name : String
var descriptionStr: String
init(name : String, descriptionStr: String)
{
self.name = name
self.descriptionStr = descriptionStr
}
}
then we can connect with our table view objects
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCellID")as! TableViewCell
cell.listName.text = modelReference[indexPath.row].name
In your XML, you had used Textview, But in Java Code you had used EditText instead of TextView. If you change it into TextView you can set Text to to your TextView Object.
text = (TextView) findViewById(R.id.this_is_the_id_of_textview);
text.setText("TEST");
hope it will work.
I use this to open a workbook and then copy that workbook's data to the template.
Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
With Application.FileDialog(msoFileDialogOpen)
.InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
.Filters.Clear
.Title = "Your Title"
If Not .Show Then
MsgBox "No file selected.": Exit Sub
End If
Workbooks.OpenText .SelectedItems(1)
'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1
Set myfile = ActiveWorkbook
ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
myfile.Close
Template.Activate
ActiveSheet.Cells.Select
Selection.Copy
Sheets("Sheet1").Select
Cells.Select
ActiveSheet.Paste
End With
You use
#main_text .title {
/* Properties */
}
If you just put a space between the selectors, styles will apply to all children (and children of children) of the first. So in this case, any child element of #main_text
with the class name title
. If you use >
instead of a space, it will only select the direct child of the element, and not children of children, e.g.:
#main_text > .title {
/* Properties */
}
Either will work in this case, but the first is more typically used.
You're doing it the correct way but users may be providing urls to sites that have invalid SSL certs installed. You can ignore those cert problems if you put this line in before you make the actual web request:
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
where AcceptAllCertifications
is defined as
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}