It skips all whitespace (spaces, tabs, new lines, etc.) by default. You can either change its behavior, or use a slightly different mechanism. To change its behavior, use the manipulator noskipws
, as follows:
cin >> noskipws >> a[i];
But, since you seem like you want to look at the individual characters, I'd suggest using get
, like this prior to your loop
cin.get( a, n );
Note: get
will stop retrieving chars from the stream if it either finds a newline char (\n
) or after n-1 chars. It stops early so that it can append the null character (\0
) to the array. You can read more about the istream
interface here.
It is better to use scanf(" %[^\n]",str) in c++ than cin.ignore() after cin>> statement.To do that first you have to include < cstdio > header.
Possibly:
std::cin.ignore(INT_MAX);
This would read in and ignore everything until EOF
. (you can also supply a second argument which is the character to read until (ex: '\n'
to ignore a single line).
Also: You probably want to do a: std::cin.clear();
before this too to reset the stream state.
I faced this issue, and resolved this issue using getchar() to catch the ('\n') new char
There is a function in c called isdigit()
. That will suit you just fine. Example:
int var1 = 'h';
int var2 = '2';
if( isdigit(var1) )
{
printf("var1 = |%c| is a digit\n", var1 );
}
else
{
printf("var1 = |%c| is not a digit\n", var1 );
}
if( isdigit(var2) )
{
printf("var2 = |%c| is a digit\n", var2 );
}
else
{
printf("var2 = |%c| is not a digit\n", var2 );
}
From here
The cin.clear()
clears the error flag on cin
(so that future I/O operations will work correctly), and then cin.ignore(10000, '\n')
skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up to 10000 characters, so the code is assuming the user will not put in a very long, invalid line.
Yes, you can input multiple items from cin
, using exactly the syntax you describe. The result is essentially identical to:
cin >> a;
cin >> b;
cin >> c;
This is due to a technique called "operator chaining".
Each call to operator>>(istream&, T)
(where T
is some arbitrary type) returns a reference to its first argument. So cin >> a
returns cin
, which can be used as (cin>>a)>>b
and so forth.
Note that each call to operator>>(istream&, T)
first consumes all whitespace characters, then as many characters as is required to satisfy the input operation, up to (but not including) the first next whitespace character, invalid character, or EOF.
@Cyntech is right.
Incase your table is empty and you still need to get table column names you can get your column as type Vector,see the following:
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
Vector<Vector<String>>tableVector = new Vector<Vector<String>>();
boolean isTableEmpty = true;
int col = 0;
while(rs.next())
{
isTableEmpty = false; //set to false since rs.next has data: this means the table is not empty
if(col != columnCount)
{
for(int x = 1;x <= columnCount;x++){
Vector<String> tFields = new Vector<String>();
tFields.add(rsmd.getColumnName(x).toString());
tableVector.add(tFields);
}
col = columnCount;
}
}
//if table is empty then get column names only
if(isTableEmpty){
for(int x=1;x<=colCount;x++){
Vector<String> tFields = new Vector<String>();
tFields.add(rsmd.getColumnName(x).toString());
tableVector.add(tFields);
}
}
rs.close();
stmt.close();
return tableVector;
BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:
function getOffsetTop (el) {
if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
return el.offsetTop || 0
}
function getOffsetLeft (el) {
if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
return el.offsetleft || 0
}
function coordinates(el) {
var y1 = getOffsetTop(el) - window.scrollY;
var x1 = getOffsetLeft(el) - window.scrollX;
var y2 = y1 + el.offsetHeight;
var x2 = x1 + el.offsetWidth;
return {
x1: x1, x2: x2, y1: y1, y2: y2
}
}
The following should work as long as you're bound to anything that implements IEnumerable<string>. It will bind the column directly to the string itself, rather than to a Property Path of that string object.
<sdk:DataGridTextColumn Binding="{Binding}" />
It is impossible to change the format
We have to differentiate between the over the wire format and the browser's presentation format.
The HTML5 date input specification refers to the RFC 3339 specification, which specifies a full-date format equal to: yyyy-mm-dd
. See section 5.6 of the RFC 3339 specification for more details.
This format is used by the value
HTML attribute and DOM property and is the one used when doing an ordinary form submission.
Browsers are unrestricted in how they present a date input. At the time of writing Chrome, Edge, Firefox, and Opera have date support (see here). They all display a date picker and format the text in the input field.
Desktop devices
For Chrome, Firefox, and Opera, the formatting of the input field's text is based on the browser's language setting. For Edge, it is based on the Windows language setting. Sadly, all web browsers ignore the date formatting configured in the operating system. To me this is very strange behaviour, and something to consider when using this input type. For example, Dutch users that have their operating system or browser language set to en-us
will be shown 01/30/2019
instead of the format they are accustomed to: 30-01-2019
.
Internet Explorer 9, 10, and 11 display a text input field with the wire format.
Mobile devices
Specifically for Chrome on Android, the formatting is based on the Android display language. I suspect that the same is true for other browsers, though I've not been able to verify this.
Inspired by @Josef's answer:
const fileToBase64 = async (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => resolve(reader.result)
reader.onerror = (e) => reject(e)
})
const file = event.srcElement.files[0];
const imageStr = await fileToBase64(file)
Reason is to have some value other than zero. General practice to have it short globally and long for long working scripts like parsers, crawlers, dumpers, exporting & importing scripts etc.
After hitting ESC (or cmd + C on my computer) you must hit : for the command prompt to appear. Then, you may enter quit
.
You may find that the machine will not allow you to quit because your information hasn't been saved. If you'd like to quit anyway, enter ! directly after the quit (i.e. :quit!
).
USE LIMIT 1 - so It will return only 1 row. Example
customerId- (select id from enumeration where enumerations.name = 'Ready To Invoice' limit 1)
If you look at either of the following keys:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\hivelist
You can find a list of the SIDs there with various values, including where their "home paths" which includes their usernames.
I'm not sure how dependable this is and I wouldn't recommend messing about with this unless you're really sure what you're doing.
Surprisingly no one told about this, which provides some !clarity:
style={{
backgroundColor: 'white',
opacity: 0.7
}}
When you're in a detached head situation and created new files, first make sure that these new files are added to the index, for example with:
git add .
But if you've only changed or deleted existing files, you can add (-a) and commit with a message (-m) at the the same time via:
git commit -a -m "my adjustment message"
Then you can simply create a new branch with your current state with:
git checkout -b new_branch_name
You'll have a new branch and all your adjustments will be there in that new branch. You can then continue to push to the remote and/or checkout/pull/merge as you please.
you can also use Git bash where head and tail are emulated as well
let trimString = function (string, length) {
return string.length > length ?
string.substring(0, length) + '...' :
string;
};
Use Case,
let string = 'How to trim a string to N chars in Javascript';
trimString(string, 20);
//How to trim a string...
On my install, FontProperties only changes the text size, but it's still too large and spaced out. I found a parameter in pyplot.rcParams
: legend.labelspacing
, which I'm guessing is set to a fraction of the font size. I've changed it with
pyplot.rcParams.update({'legend.labelspacing':0.25})
I'm not sure how to specify it to the pyplot.legend function - passing
prop={'labelspacing':0.25}
or
prop={'legend.labelspacing':0.25}
comes back with an error.
The modulus is a mathematical operation, sometimes described as "clock arithmetic." I find that describing it as simply a remainder is misleading and confusing because it masks the real reason it is used so much in computer science. It really is used to wrap around cycles.
Think of a clock: Suppose you look at a clock in "military" time, where the range of times goes from 0:00 - 23.59. Now if you wanted something to happen every day at midnight, you would want the current time mod 24 to be zero:
if (hour % 24 == 0):
You can think of all hours in history wrapping around a circle of 24 hours over and over and the current hour of the day is that infinitely long number mod 24. It is a much more profound concept than just a remainder, it is a mathematical way to deal with cycles and it is very important in computer science. It is also used to wrap around arrays, allowing you to increase the index and use the modulus to wrap back to the beginning after you reach the end of the array.
The method you're looking for is extend()
. From the Python documentation:
list.append(x)
Add an item to the end of the list; equivalent to a[len(a):] = [x].
list.extend(L)
Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
Here are some more console logging "pro tips":
console.table
var animals = [
{ animal: 'Horse', name: 'Henry', age: 43 },
{ animal: 'Dog', name: 'Fred', age: 13 },
{ animal: 'Cat', name: 'Frodo', age: 18 }
];
console.table(animals);
console.trace
Shows you the call stack for leading up to the console.
You can even customise your consoles to make them stand out
console.todo = function(msg) {
console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘–‘);
}
console.important = function(msg) {
console.log(‘ % c % s % s % s’, ‘color: brown; font - weight: bold; text - decoration: underline;’, ‘–‘, msg, ‘–‘);
}
console.todo(“This is something that’ s need to be fixed”);
console.important(‘This is an important message’);
If you really want to level up don't limit your self to the console statement.
Here is a great post on how you can integrate a chrome debugger right into your code editor!
https://hackernoon.com/debugging-react-like-a-champ-with-vscode-66281760037
You should define source code encoding, add this to the top of your script:
# -*- coding: utf-8 -*-
The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:
import sys
print sys.getdefaultencoding()
Also see:
I think you can't achieve what you want in a more efficient manner than you proposed.
The underlying problem is that the timestamps (as you seem aware) are made up of two parts. The data that represents the UTC time, and the timezone, tz_info. The timezone information is used only for display purposes when printing the timezone to the screen. At display time, the data is offset appropriately and +01:00 (or similar) is added to the string. Stripping off the tz_info value (using tz_convert(tz=None)) doesn't doesn't actually change the data that represents the naive part of the timestamp.
So, the only way to do what you want is to modify the underlying data (pandas doesn't allow this... DatetimeIndex are immutable -- see the help on DatetimeIndex), or to create a new set of timestamp objects and wrap them in a new DatetimeIndex. Your solution does the latter:
pd.DatetimeIndex([i.replace(tzinfo=None) for i in t])
For reference, here is the replace
method of Timestamp
(see tslib.pyx):
def replace(self, **kwds):
return Timestamp(datetime.replace(self, **kwds),
offset=self.offset)
You can refer to the docs on datetime.datetime
to see that datetime.datetime.replace
also creates a new object.
If you can, your best bet for efficiency is to modify the source of the data so that it (incorrectly) reports the timestamps without their timezone. You mentioned:
I want to work with timezone naive timeseries (to avoid the extra hassle with timezones, and I do not need them for the case I am working on)
I'd be curious what extra hassle you are referring to. I recommend as a general rule for all software development, keep your timestamp 'naive values' in UTC. There is little worse than looking at two different int64 values wondering which timezone they belong to. If you always, always, always use UTC for the internal storage, then you will avoid countless headaches. My mantra is Timezones are for human I/O only.
Two alternative strategies to get consistent about line-endings in mixed environments (Microsoft + Linux + Mac):
1) Convert all to one format
find . -type f -not -path "./.git/*" -exec dos2unix {} \;
git commit -a -m 'dos2unix conversion'
2) Set core.autocrlf
to input
on Linux/UNIX or true
on MS Windows (repository or global)
git config --global core.autocrlf input
3) [ Optional ] set core.safecrlf
to true
(to stop) or warn
(to sing:) to add extra guard comparing if the reversed newline transformation would result in the same file
git config --global core.safecrlf true
1) Convert all to one format
find . -type f -not -path "./.git/*" -exec dos2unix {} \;
git commit -a -m 'dos2unix conversion'
2) add .gitattributes
file to your repository
echo "* text=auto" > .gitattributes
git add .gitattributes
git commit -m 'adding .gitattributes for unified line-ending'
Don't worry about your binary files - Git should be smart enough about them.
your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?
Solution for me was to just do it server side
I used the C# WebClient
library to get the data (in my case it was image data) and send it back to the client. There's probably something very similar in your chosen server-side language.
//Server side, api controller
[Route("api/ItemImage/GetItemImageFromURL")]
public IActionResult GetItemImageFromURL([FromQuery] string url)
{
ItemImage image = new ItemImage();
using(WebClient client = new WebClient()){
image.Bytes = client.DownloadData(url);
return Ok(image);
}
}
You can tweak it to whatever your own use case is. The main point is client.DownloadData()
worked without any CORS errors. Typically CORS issues are only between websites, hence it being okay to make 'cross-site' requests from your server.
Then the React fetch call is as simple as:
//React component
fetch(`api/ItemImage/GetItemImageFromURL?url=${imageURL}`, {
method: 'GET',
})
.then(resp => resp.json() as Promise<ItemImage>)
.then(imgResponse => {
// Do more stuff....
)}
First add #include <cmath>
then
you can use pow
methode in your code for example :
pow(3.5, 3);
Which 3.5 is base and 3 is exp
var fav = [];
$.each($("input[name='name']:checked"), function(){
fav.push($(this).val());
});
It will give you the value separeted by commas
Unfortunately, even with maven 3 the only way to do that is to patch source code.
Here is short instruction how to do that.
Clone or fork Maven 3 repo: "git clone https://github.com/apache/maven-3.git"
Edit org.apache.maven.cli.MavenCli#logging, and change
cliRequest.request.setLoggingLevel( MavenExecutionRequest.LOGGING_LEVEL_INFO );
to
cliRequest.request.setLoggingLevel( MavenExecutionRequest.LOGGING_LEVEL_WARN );
In current snapshot version it's at line 270
Then just run "mvn install", your new maven distro will be located in "apache-maven\target\" folder
See this diff for the reference: https://github.com/ushkinaz/maven-3/commit/cc079aa75ca8c82658c7ff53f18c6caaa32d2131
Apart from string interpolation, you can also call a function using back-tick.
var sayHello = function () {
console.log('Hello', arguments);
}
// To call this function using ``
sayHello`some args`; // Check console for the output
// Or
sayHello`
some args
`;
Check styled component. They use it heavily.
If I understand you correctly, Adding this after any media queries overrides the width restrictions on the default grids. Works for me on bootstrap 3 where I needed a 100% width layout
.container {
max-width: 100%;
/* This will remove the outer padding, and push content edge to edge */
padding-right: 0;
padding-left: 0;
}
Then you can put your row and grid elements inside the container.
Below code absolutely worked for me to update File extension.
Ex: abc.pdf to abc.txt
Filepath = "Pls mention your Filepath"
Set objFso = CreateObject("Scripting.FileSystemObject")
'' Below line of code is to get the object for Folder where list of files are located
Set objFolder = objFso.GetFolder(Filepath)
'' Below line of code used to get the collection object to hold list of files located in the Filepath.
Set FileCollection = objFolder.Files
For Each file In FileCollection
WScript.Echo "File name ->" + file.Name
''Instr used to Return the position of the first occurrence of "." within the File name
s = InStr(1, file.Name, ".",1)
WScript.Echo s
WScript.Echo "Extn --> " + Mid(file.Name, s, Len(file.Name))
'Left(file.Name,s-1) = Used to fetch the file name without extension
' Move method is used to move the file in the Desitnation folder you mentioned
file.Move(Filepath & Left(file.Name,s-1)&".txt")
Next
a much more practical way for those who do not want to use regex:
$data = filter_var($data, FILTER_SANITIZE_NUMBER_INT);
note: it works with phone numbers too.
I don't think you can call
$.attr('checked',true);
because there is no element selector in the first place. $ must be followed by $('selector_name'). GOod luck!
DefaultThreadCurrentCulture
and DefaultThreadCurrentUICulture
are present in Framework 4.0 too, but they are Private. Using Reflection you can easily set them. This will affect all threads where CurrentCulture
is not explicitly set (running threads too).
Public Sub SetDefaultThreadCurrentCulture(paCulture As CultureInfo)
Thread.CurrentThread.CurrentCulture.GetType().GetProperty("DefaultThreadCurrentCulture").SetValue(Thread.CurrentThread.CurrentCulture, paCulture, Nothing)
Thread.CurrentThread.CurrentCulture.GetType().GetProperty("DefaultThreadCurrentUICulture").SetValue(Thread.CurrentThread.CurrentCulture, paCulture, Nothing)
End Sub
This error happens very rarely on my Windows machine. I ended up rebooting the machine, and the error went away.
As it is already explained in other answers, const
in C merely means that a variable is read-only. It is still a run-time value. However, you can use an enum
as a real constant in C:
enum { NUM_TYPES = 4 };
static int types[NUM_TYPES] = {
1, 2, 3, 4
};
this would hep you
DECLARE @DATE1 datetime = '2014-01-22 9:07:58.923'
DECLARE @DATE2 datetime = '2014-01-22 10:20:58.923'
SELECT DATEDIFF(HOUR, @DATE1,@DATE2) ,
DATEDIFF(MINUTE, @DATE1,@DATE2) - (DATEDIFF(HOUR,@DATE1,@DATE2)*60)
SELECT CAST(DATEDIFF(HOUR, @DATE1,@DATE2) AS nvarchar(200)) +
':'+ CAST(DATEDIFF(MINUTE, @DATE1,@DATE2) -
(DATEDIFF(HOUR,@DATE1,@DATE2)*60) AS nvarchar(200))
As TotalHours
Or you can do this without using Delay.
set /a "counter=0"
-> your for loop here
do (
statement1
statement2
call :increaseby1
)
:increaseby1
set /a "counter+=1"
Not sure if any of these help, but this might get you started: http://studiostyles.info
I know that the site owner has been gradually adding functionality to allow support for new color assignments, so perhaps there's something there.
One approach is to detect peaks based on the following observation:
It avoids false positives by waiting until the uptrend is over. It is not exactly "real-time" in the sense that it will miss the peak by one dt. sensitivity can be controlled by requiring a margin for comparison. There is a trade off between noisy detection and time delay of detection. You can enrich the model by adding more parameters:
where dt and m are parameters to control sensitivity vs time-delay
This is what you get with the mentioned algorithm:
here is the code to reproduce the plot in python:
import numpy as np
import matplotlib.pyplot as plt
input = np.array([ 1. , 1. , 1. , 1. , 1. , 1. , 1. , 1.1, 1. , 0.8, 0.9,
1. , 1.2, 0.9, 1. , 1. , 1.1, 1.2, 1. , 1.5, 1. , 3. ,
2. , 5. , 3. , 2. , 1. , 1. , 1. , 0.9, 1. , 1. , 3. ,
2.6, 4. , 3. , 3.2, 2. , 1. , 1. , 1. , 1. , 1. ])
signal = (input > np.roll(input,1)) & (input > np.roll(input,-1))
plt.plot(input)
plt.plot(signal.nonzero()[0], input[signal], 'ro')
plt.show()
By setting m = 0.5
, you can get a cleaner signal with only one false positive:
It looks that some files are still left and some registry keys are left. So you can run revocleaner tool to remove those entries as well. Do a reboot and install again it should be doing it now. I also faced issue and by complete cleaning I got Rid of it.
display PDF file into WinForms
Displaying a pdf file from Winform.
displaying a pdf on a windows form?
How to display PDF or Word's DOC/DOCX inside WinForms window?
Technically, the Integrity attribute helps with just that - it enables the proper verification of the data source. That is, it merely allows the browser to verify the numbers in the right source file with the amounts requested by the source file located on the CDN server.
Going a bit deeper, in case of the established encrypted hash value of this source and its checked compliance with a predefined value in the browser - the code executes, and the user request is successfully processed.
Crossorigin attribute helps developers optimize the rates of CDN performance, at the same time, protecting the website code from malicious scripts.
In particular, Crossorigin downloads the program code of the site in anonymous mode, without downloading cookies or performing the authentication procedure. This way, it prevents the leak of user data when you first load the site on a specific CDN server, which network fraudsters can easily replace addresses.
Source: https://yon.fun/what-is-link-integrity-and-crossorigin/
After upgrading to Mountain Lion
using the NDK
, I had the following error:
Cannot find 'make' program. Please install Cygwin make package or define the GNUMAKE variable to point to it
Error was fixed by downloading and using the latest NDK
With the most simple programming language: DOS batch
echo %LOGONSERVER%
try this:
var result = from r in myDataTable.AsEnumerable()
where r.Field<string>("Name") != "n/a" &&
r.Field<string>("Name") != "" select r;
DataTable dtResult = result.CopyToDataTable();
If by array of String you mean array of char:
public class Test
{
public static void main(String[] args)
{
String test = "aabbab ";
char[] t = test.toCharArray();
for(char c : t)
System.out.println(c);
System.out.println("The end!");
}
}
If not, the String.split()
function could transform a String into an array of String
See those String.split
examples
/* String to split. */
String str = "one-two-three";
String[] temp;
/* delimiter */
String delimiter = "-";
/* given string will be split by the argument delimiter provided. */
temp = str.split(delimiter);
/* print substrings */
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);
The input.split("(?!^)")
proposed by Joachim in his answer is based on:
?!
' zero-width negative lookahead (see Lookaround)^
' as an Anchor to match the start of the string the regex pattern is applied toAny character which is not the first will be split. An empty string will not be split but return an empty array.
Yeah, I missed ++ and -- functionality as well. A few million lines of c code engrained that kind of thinking in my old head, and rather than fight it... Here's a class I cobbled up that implements:
pre- and post-increment, pre- and post-decrement, addition,
subtraction, multiplication, division, results assignable
as integer, printable, settable.
Here 'tis:
class counter(object):
def __init__(self,v=0):
self.set(v)
def preinc(self):
self.v += 1
return self.v
def predec(self):
self.v -= 1
return self.v
def postinc(self):
self.v += 1
return self.v - 1
def postdec(self):
self.v -= 1
return self.v + 1
def __add__(self,addend):
return self.v + addend
def __sub__(self,subtrahend):
return self.v - subtrahend
def __mul__(self,multiplier):
return self.v * multiplier
def __div__(self,divisor):
return self.v / divisor
def __getitem__(self):
return self.v
def __str__(self):
return str(self.v)
def set(self,v):
if type(v) != int:
v = 0
self.v = v
You might use it like this:
c = counter() # defaults to zero
for listItem in myList: # imaginary task
doSomething(c.postinc(),listItem) # passes c, but becomes c+1
...already having c, you could do this...
c.set(11)
while c.predec() > 0:
print c
....or just...
d = counter(11)
while d.predec() > 0:
print d
...and for (re-)assignment into integer...
c = counter(100)
d = c + 223 # assignment as integer
c = c + 223 # re-assignment as integer
print type(c),c # <type 'int'> 323
...while this will maintain c as type counter:
c = counter(100)
c.set(c + 223)
print type(c),c # <class '__main__.counter'> 323
EDIT:
And then there's this bit of unexpected (and thoroughly unwanted) behavior,
c = counter(42)
s = '%s: %d' % ('Expecting 42',c) # but getting non-numeric exception
print s
...because inside that tuple, getitem() isn't what used, instead a reference to the object is passed to the formatting function. Sigh. So:
c = counter(42)
s = '%s: %d' % ('Expecting 42',c.v) # and getting 42.
print s
...or, more verbosely, and explicitly what we actually wanted to happen, although counter-indicated in actual form by the verbosity (use c.v
instead)...
c = counter(42)
s = '%s: %d' % ('Expecting 42',c.__getitem__()) # and getting 42.
print s
There is actually a nice Gem called local_time
by basecamp to do all of that on client side only, I believe:
After a bit of time (and more searching), I found this blog entry by Jomo Fisher.
One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:
Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.
[Snip]
The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:
<startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0"/> </startup>
So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy
attribute reverts back to CLR 2.0 loading.
They way I did it was by selecting all of the data
select * from myTable
and then right-clicking on the result set and chose "Save results as..." a csv file.
Opening the csv file in Notepad++ I saw the LF characters not visible in SQL Server result set.
Perhaps an example will help:
git rm --cached asd
git commit -m "the file asd is gone from the repository"
versus
git reset HEAD -- asd
git commit -m "the file asd remains in the repository"
Note that if you haven't changed anything else, the second commit won't actually do anything.
Not sure why this works but dynamic (or wildcard if you prefer) routes are possible in angular 1.2.0-rc.2...
http://code.angularjs.org/1.2.0-rc.2/angular.min.js
http://code.angularjs.org/1.2.0-rc.2/angular-route.min.js
angular.module('yadda', [
'ngRoute'
]).
config(function ($routeProvider, $locationProvider) {
$routeProvider.
when('/:a', {
template: '<div ng-include="templateUrl">Loading...</div>',
controller: 'DynamicController'
}).
controller('DynamicController', function ($scope, $routeParams) {
console.log($routeParams);
$scope.templateUrl = 'partials/' + $routeParams.a;
}).
example.com/foo -> loads "foo" partial
example.com/bar-> loads "bar" partial
No need for any adjustments in the ng-view. The '/:a' case is the only variable I have found that will acheive this.. '/:foo' does not work unless your partials are all foo1, foo2, etc... '/:a' works with any partial name.
All values fire the dynamic controller - so there is no "otherwise" but, I think it is what you're looking for in a dynamic or wildcard routing scenario..
You can also create a request instance with default options:
require('request').defaults({ rejectUnauthorized: false })
This is the code i used:
Date date = new Date(); // to get the date
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); // getting date in this format
String formattedDate = df.format(date.getTime());
text.setText(formattedDate);
try
{
//Handle the alert pop-up using seithTO alert statement
Alert alert = driver.switchTo().alert();
//Print alert is present
System.out.println("Alert is present");
//get the message which is present on pop-up
String message = alert.getText();
//print the pop-up message
System.out.println(message);
alert.sendKeys("");
//Click on OK button on pop-up
alert.accept();
}
catch (NoAlertPresentException e)
{
//if alert is not present print message
System.out.println("alert is not present");
}
A simple method of creating the service, adding headers and reading the JSON response,
private static void WebRequest()
{
const string WEBSERVICE_URL = "<<Web Service URL>>";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "GET";
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
webRequest.Headers.Add("Authorization", "Basic dcmGV25hZFzc3VudDM6cGzdCdvQ=");
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
Console.WriteLine(String.Format("Response: {0}", jsonResponse));
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
CSS "classes" are not OOP "classes". The inheritance works the other way around.
A DOM element can have many classes, either directly or inherited or otherwise associated, which will all be applied in order, overriding earlier defined properties:
<div class="foo bar">
.foo {
color: blue;
width: 200px;
}
.bar {
color: red;
}
The div will be 200px wide and have the color red.
You override properties of DOM elements with different classes, not properties of CSS classes. CSS "classes" are rulesets, the same way ids or tags can be used as rulesets.
Note that the order in which the classes are applied depends on the precedence and specificity of the selector, which is a complex enough topic in itself.
Your error
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
appears because you must call setRequestHeader
after calling open
. Simply move your setRequestHeader
line below your open
line (but before send
):
xmlhttp.open("POST", url);
xmlhttp.setRequestHeader("x-filename", photoId);
xmlhttp.send(formData);
For sorting narrow range of integers try Counting sort, which has a complexity of O(range + n)
, where n
is number of items to be sorted. If you'd like to sort something not discrete use optimal n*log(n) algorithms (quicksort, heapsort, mergesort). Merge sort is also used in a method already mentioned by other responses Arrays.sort
. There is no simple way how to recommend some algorithm or function call, because there are dozens of special cases, where you would use some sort, but not the other.
So please specify the exact purpose of your application (to learn something (well - start with the insertion sort or bubble sort), effectivity for integers (use counting sort), effectivity and reusability for structures (use n*log(n) algorithms), or zou just want it to be somehow sorted - use Arrays.sort :-)). If you'd like to sort string representations of integers, than u might be interrested in radix sort....
I installed System.Configuration.ConfigurationManager
from Nuget into my .net core 2.2 application.
I then reference using System.Configuration;
Next, I changed
WebConfigurationManager.AppSettings
to ..
ConfigurationManager.AppSettings
So far I believe this is correct. 4.5.0 is typical with .net core 2.2
I have not had any issues with this.
string url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
string path = url.split('?')[0];
revised: okay to have some kind of find you would need something other than dictionary, since if you think about it dictionary are one way keys. that is, the values might not be unique
that said it looks like you're using c#3.0 so you might not have to resort to looping and could use something like:
var key = (from k in yourDictionary where string.Compare(k.Value, "yourValue", true) == 0 select k.Key).FirstOrDefault();
atm they are working on that issue https://github.com/firebase/quickstart-android/issues/4
when you send a notification from the Firebase console is uses your app icon by default, and the Android system will turn that icon solid white when in the notification bar.
If you are unhappy with that result you should implement FirebaseMessagingService and create the notifications manually when you receive a message. We are working on a way to improve this but for now that's the only way.
edit: with SDK 9.8.0 add to AndroidManifest.xml
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/my_favorite_pic"/>
Simply
<select id = 'color2'
name = 'color'
onchange = "if ($('#color2').val() == 'others') {
$('#color').show();
} else {
$('#color').hide();
}">
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<input type = 'text'
name = 'color'
id = 'color' />
edit: requires JQuery plugin
Using itertools.count
:
import itertools
for i in itertools.count(start=1):
if there_is_a_reason_to_break(i):
break
In Python 2, range()
and xrange()
were limited to sys.maxsize
. In Python 3 range()
can go much higher, though not to infinity:
import sys
for i in range(sys.maxsize**10): # you could go even higher if you really want
if there_is_a_reason_to_break(i):
break
So it's probably best to use count()
.
You need to read the file in chunks of suitable size:
def md5_for_file(f, block_size=2**20):
md5 = hashlib.md5()
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
return md5.digest()
NOTE: Make sure you open your file with the 'rb' to the open - otherwise you will get the wrong result.
So to do the whole lot in one method - use something like:
def generate_file_md5(rootdir, filename, blocksize=2**20):
m = hashlib.md5()
with open( os.path.join(rootdir, filename) , "rb" ) as f:
while True:
buf = f.read(blocksize)
if not buf:
break
m.update( buf )
return m.hexdigest()
The update above was based on the comments provided by Frerich Raabe - and I tested this and found it to be correct on my Python 2.7.2 windows installation
I cross-checked the results using the 'jacksum' tool.
jacksum -a md5 <filename>
You could create a dict comprehension of just the elements whose values are None, and then update back into the original:
tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)
Update - did some performance tests
Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.
For System.Timers.Timer
, according to MSDN documentation, http://msdn.microsoft.com/en-us/library/system.timers.timer.enabled.aspx:
If the interval is set after the Timer has started, the count is reset. For example, if you set the interval to 5 seconds and then set the Enabled property to true, the count starts at the time Enabled is set. If you reset the interval to 10 seconds when count is 3 seconds, the Elapsed event is raised for the first time 13 seconds after Enabled was set to true.
So,
const double TIMEOUT = 5000; // milliseconds
aTimer = new System.Timers.Timer(TIMEOUT);
aTimer.Start(); // timer start running
:
:
aTimer.Interval = TIMEOUT; // restart the timer
Create this subclass
public class MyApp extends Application {
String foo;
}
In the AndroidManifest.xml add android:name
Example
<application android:name=".MyApp"
android:icon="@drawable/icon"
android:label="@string/app_name">
Try to do this way
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
or if you use .net core try it
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Usuario>().ToTable("Usuario");
}
Replace Usuario for your Entity Name, like a DbSet<<EntityName>> Entities without Plural
If you VS solution contains several projects, select all of them in the right pane, and press "properties". Then go to C++ -> Code Generation and chose one Run Time library option for all of them
You can use this class I wrote. It offers only the basic functions. If you want a fully functional ProgressDialog, then use this lightweight library.
Add the following dependency to module/build.gradle:
compile 'com.lmntrx.android.library.livin.missme:missme:0.1.5'
Usage is similar to original ProgressDialog
ProgressDialog progressDialog = new
progressDialog(YourActivity.this);
progressDialog.setMessage("Please wait");
progressDialog.setCancelable(false);
progressDialog.show();
progressDialog.dismiss();
NB: You must override activity's onBackPressed()
Java8 Implementation:
@Override
public void onBackPressed() {
progressDialog.onBackPressed(
() -> {
super.onBackPressed();
return null;
}
);
}
Kotlin Implementation:
override fun onBackPressed() {
progressDialog.onBackPressed { super.onBackPressed() }
}
If you're comfortable with numba it allows to create a fast short-circuit (stops as soon as a NaN is found) function:
import numba as nb
import math
@nb.njit
def anynan(array):
array = array.ravel()
for i in range(array.size):
if math.isnan(array[i]):
return True
return False
If there is no NaN
the function might actually be slower than np.min
, I think that's because np.min
uses multiprocessing for large arrays:
import numpy as np
array = np.random.random(2000000)
%timeit anynan(array) # 100 loops, best of 3: 2.21 ms per loop
%timeit np.isnan(array.sum()) # 100 loops, best of 3: 4.45 ms per loop
%timeit np.isnan(array.min()) # 1000 loops, best of 3: 1.64 ms per loop
But in case there is a NaN in the array, especially if it's position is at low indices, then it's much faster:
array = np.random.random(2000000)
array[100] = np.nan
%timeit anynan(array) # 1000000 loops, best of 3: 1.93 µs per loop
%timeit np.isnan(array.sum()) # 100 loops, best of 3: 4.57 ms per loop
%timeit np.isnan(array.min()) # 1000 loops, best of 3: 1.65 ms per loop
Similar results may be achieved with Cython or a C extension, these are a bit more complicated (or easily avaiable as bottleneck.anynan
) but ultimatly do the same as my anynan
function.
mongod --wiredTigerCacheSizeGB 2 xx
this could be your answer, use params method of activated route to get paramter from URL/route that you want to read, below is demo snippet
import {ActivatedRoute} from '@angular/router';
@Component({
})
export class Test{
constructor(private route: ActivatedRoute){
this.route.params.subscribe(params => {
this.yourVariable = params['required_param_name'];
});
}
}
Have you tried the GNU make documentation? It has a whole section about conditionals with examples.
All of the DISPATCH_QUEUE_PRIORITY_X queues are concurrent queues (meaning they can execute multiple tasks at once), and are FIFO in the sense that tasks within a given queue will begin executing using "first in, first out" order. This is in comparison to the main queue (from dispatch_get_main_queue()), which is a serial queue (tasks will begin executing and finish executing in the order in which they are received).
So, if you send 1000 dispatch_async() blocks to DISPATCH_QUEUE_PRIORITY_DEFAULT, those tasks will start executing in the order you sent them into the queue. Likewise for the HIGH, LOW, and BACKGROUND queues. Anything you send into any of these queues is executed in the background on alternate threads, away from your main application thread. Therefore, these queues are suitable for executing tasks such as background downloading, compression, computation, etc.
Note that the order of execution is FIFO on a per-queue basis. So if you send 1000 dispatch_async() tasks to the four different concurrent queues, evenly splitting them and sending them to BACKGROUND, LOW, DEFAULT and HIGH in order (ie you schedule the last 250 tasks on the HIGH queue), it's very likely that the first tasks you see starting will be on that HIGH queue as the system has taken your implication that those tasks need to get to the CPU as quickly as possible.
Note also that I say "will begin executing in order", but keep in mind that as concurrent queues things won't necessarily FINISH executing in order depending on length of time for each task.
As per Apple:
A concurrent dispatch queue is useful when you have multiple tasks that can run in parallel. A concurrent queue is still a queue in that it dequeues tasks in a first-in, first-out order; however, a concurrent queue may dequeue additional tasks before any previous tasks finish. The actual number of tasks executed by a concurrent queue at any given moment is variable and can change dynamically as conditions in your application change. Many factors affect the number of tasks executed by the concurrent queues, including the number of available cores, the amount of work being done by other processes, and the number and priority of tasks in other serial dispatch queues.
Basically, if you send those 1000 dispatch_async() blocks to a DEFAULT, HIGH, LOW, or BACKGROUND queue they will all start executing in the order you send them. However, shorter tasks may finish before longer ones. Reasons behind this are if there are available CPU cores or if the current queue tasks are performing computationally non-intensive work (thus making the system think it can dispatch additional tasks in parallel regardless of core count).
The level of concurrency is handled entirely by the system and is based on system load and other internally determined factors. This is the beauty of Grand Central Dispatch (the dispatch_async() system) - you just make your work units as code blocks, set a priority for them (based on the queue you choose) and let the system handle the rest.
So to answer your above question: you are partially correct. You are "asking that code" to perform concurrent tasks on a global concurrent queue at the specified priority level. The code in the block will execute in the background and any additional (similar) code will execute potentially in parallel depending on the system's assessment of available resources.
The "main" queue on the other hand (from dispatch_get_main_queue()) is a serial queue (not concurrent). Tasks sent to the main queue will always execute in order and will always finish in order. These tasks will also be executed on the UI Thread so it's suitable for updating your UI with progress messages, completion notifications, etc.
you can read file by
var readMyFile = function(path, cb) {
fs.readFile(path, 'utf8', function(err, content) {
if (err) return cb(err, null);
cb(null, content);
});
};
Adding on you can write to file,
var createMyFile = (path, data, cb) => {
fs.writeFile(path, data, function(err) {
if (err) return console.error(err);
cb();
});
};
and even chain it together
var readFileAndConvertToSentence = function(path, callback) {
readMyFile(path, function(err, content) {
if (err) {
callback(err, null);
} else {
var sentence = content.split('\n').join(' ');
callback(null, sentence);
}
});
};
MySQL has a short description of their more or less strict rules:
https://dev.mysql.com/doc/internals/en/coding-style.html
Most common codingstyle for MySQL by Simon Holywell:
See also this question: Are there any published coding style guidelines for SQL?
You do not need to create an element like the < br > tag, or any other spacer tag. What you should do is apply a style to the element that needs spacing around it.
Let's say the element you want to have space around is a DIV tag called "myelement".
<div class="myelement">
I am content that needs spacing around it!
</div>
This is the style you would need to use.
.myelement {
clear:left;
height:25px;
margin: 20px; // See below for explanation of this
}
This is the style you can use to better understand CSS for beginners
.myelement {
clear:left;
height:25px;
margin-top:20px;
margin-right:20px;
margin-bottom:20px;
margin-left:20px;
}
Also, avoid using the height: CSS property until you know what you are doing. You will run into some issues when using height that are harder to troubleshoot as a beginner.
for me adding /
worked at the end of location of folder.
Hence, if you are copying into folder, don't forget to put /
In your index.php
file add the line:
define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
I was having the same problem and the post of Paolo helped me out, but I needed to adjust one thing. My form with id advancedindexsearch only contained input fields and gets the values from a session. For some reason the following did not work for me:
$("#advancedindexsearch").find("input:text").val("");
If I put an alert after this, I saw the values where removed correctly but afterwards they where replaced again. I still don't know how or why but the following line did do the trick for me:
$("#advancedindexsearch").find("input:text").attr("value","");
What I know is one reason when “GC overhead limit exceeded” error is thrown when 2% of the memory is freed after several GC cycles
By this error your JVM is signalling that your application is spending too much time in garbage collection. so the little amount GC was able to clean will be quickly filled again thus forcing GC to restart the cleaning process again.
You should try changing the value of -Xmx
and -Xms
.
It also posible string replacement with stringByReplacingCharactersInRange:withString:
for (int i = 0; i < card.length - 4; i++) {
if (![[card substringWithRange:NSMakeRange(i, 1)] isEqual:@" "]) {
NSRange range = NSMakeRange(i, 1);
card = [card stringByReplacingCharactersInRange:range withString:@"*"];
}
} //out: **** **** **** 1234
It's about how much type-safety you want to impose.
When you write (bar) foo
(which is equivalent to reinterpret_cast<bar> foo
if you haven't provided a type conversion operator) you are telling the compiler to ignore type safety, and just do as it's told.
When you write static_cast<bar> foo
you are asking the compiler to at least check that the type conversion makes sense and, for integral types, to insert some conversion code.
EDIT 2014-02-26
I wrote this answer more than 5 years ago, and I got it wrong. (See comments.) But it still gets upvotes!
TLS/SSL (The S in HTTPS) guarantees that there are no eavesdroppers between you and the server you are contacting, i.e. no proxies. Normally, you use CONNECT
to open up a TCP connection through the proxy. In this case, the proxy will not be able to cache, read, or modify any requests/responses, and therefore be rather useless.
If you want the proxy to be able to read information, you can take the following approach:
An example is Squid's SSL bump. Similarly, burp can be configured to do this. This has also been used in a less-benign context by an Egyptian ISP.
Note that modern websites and browsers can employ HPKP or built-in certificate pins which defeat this approach.
In addition of the modification of the file C:\wamp64\bin\apache\apache2.4.27\conf\httpd.conf
.
To get the url shortcuts working, edit the file C:\wamp64\wampmanager.conf
and change the port:
[apache]
apachePortUsed = "8080"
Then exit and relaunch wamp.
If you add the favicon into the root/images folder with the name favicon.ico browser will automatically understand and get it as favicon.I tested and worked. your link must be www.website.com/images/favicon.ico
For more information look this answer:
Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?
set rowcount 1000000
Update table set int_field = -1 where int_field<>-1
see how fast that takes, adjust and repeat as necessary
Add a system variable named "node", with value of your node path. It solves my problem, hope it helps.
code {_x000D_
background: black;_x000D_
color: white;_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<p>Some text <code>A<br />B<br />C<br />D</code> continues afterward.</p>
_x000D_
Tested and works in Safari 5 and IE6+.
Simply
<label class="btn btn-primary">
<i class="fa fa-image"></i> Your text here<input type="file" style="display: none;" name="image">
</label>
[Edit with snippet]
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<label class="btn btn-primary">_x000D_
<i class="fa fa-image"></i> Your text here<input type="file" style="display: none;" name="image">_x000D_
</label>
_x000D_
$$
is defined to return the process ID of the parent in a subshell; from the man page under "Special Parameters":
$ Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the current shell, not the subshell.
In bash
4, you can get the process ID of the child with BASHPID
.
~ $ echo $$
17601
~ $ ( echo $$; echo $BASHPID )
17601
17634
Set SSH up for Public Key Authentication, with no pasphrase on the Key. Loads of guides on the net. You won't need a password to login then. You can then limit connections for a key based on client hostname. Provides reasonable security and is great for automated logins.
Let's say you have Python 2.7.16:
C:\Windows\system32>python --version
python2 2.7.16
...and you want to upgrade to the (now current) 3.x.y version. There is a simple way to install a parallel installation of Python 3.x.y using a Windows package management tool.
Now that modern Windows has package management, just like Debian Linux distributions have apt-get, and RedHat has dnf: we can put it to work for us! It's called Chocolatey.
Chocolatey is a scriptable, command line tool that is based on .NET 4.0 and the nuget package manager baked into Visual Studio.
If you want to learn about Chocolatey and why to use it, which some here reading this might find particularly useful, go to https://chocolatey.org/docs/why
To get the Chocolatey Package Manager, you follow a process that is described at https://chocolatey.org/docs/installation#installing-chocolatey,
I'll summarize it for you here. There are basically two options: using the cmd prompt, or using the PowerShell prompt.
Launch an administrative command prompt. On Windows 10, to do this:
If you don't have administrator rights on the system, go to the Chocolatey website. You may not be completely out of luck and can perform a limited local install, but I won't cover that here.
@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
Chocolatey will be downloaded and installed for you as below:
Getting latest version of the Chocolatey package for download.
Getting Chocolatey from https://chocolatey.org/api/v2/package/chocolatey/0.10.11.
Downloading 7-Zip commandline tool prior to extraction.
Extracting C:\Users\blahblahblah\AppData\Local\Temp\chocolatey\chocInstall\chocolatey.zip to C:\Users\blahblahblah\AppData\Local\Temp\chocolatey\chocInstall...
Installing chocolatey on this machine
Creating ChocolateyInstall as an environment variable (targeting 'Machine')
Setting ChocolateyInstall to 'C:\ProgramData\chocolatey'
WARNING: It's very likely you will need to close and reopen your shell
before you can use choco.
Restricting write permissions to Administrators
We are setting up the Chocolatey package repository.
The packages themselves go to 'C:\ProgramData\chocolatey\lib'
(i.e. C:\ProgramData\chocolatey\lib\yourPackageName).
A shim file for the command line goes to 'C:\ProgramData\chocolatey\bin'
and points to an executable in 'C:\ProgramData\chocolatey\lib\yourPackageName'.
Creating Chocolatey folders if they do not already exist.
WARNING: You can safely ignore errors related to missing log files when
upgrading from a version of Chocolatey less than 0.9.9.
'Batch file could not be found' is also safe to ignore.
'The system cannot find the file specified' - also safe.
chocolatey.nupkg file not installed in lib.
Attempting to locate it from bootstrapper.
PATH environment variable does not have C:\ProgramData\chocolatey\bin in it. Adding...
WARNING: Not setting tab completion: Profile file does not exist at 'C:\Users\blahblahblah\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1'.
Chocolatey (choco.exe) is now ready.
You can call choco from anywhere, command line or powershell by typing choco.
Run choco /? for a list of functions.
You may need to shut down and restart powershell and/or consoles
first prior to using choco.
Ensuring chocolatey commands are on the path
Ensuring chocolatey.nupkg is in the lib folder
Either Exit the CMD prompt or type the following command to reload the environment variables:
refreshenv
If you prefer PowerShell to the cmd prompt, you can do this directly from there, however you will have to tell PowerShell to run with a proper script execution policy to get it to work. On Windows 10, the simplest way I have found to do this is to type the following into the Cortana search bar next to the Windows button:
PowerShell.exe
Next, right click on the 'Best Match' choice in the menu that pops up and select 'Run as Administrator'
Now that you're in PowerShell, hopefully running with Administrator privileges, execute the following to install Chocolatey:
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
PowerShell will download Chocolatey for you and launch the installation. It only takes a few moments. It looks exactly like the CMD installation, save perhaps some fancy colored text.
Either Exit PowerShell or type the following command to reload the environment variables:
refreshenv
The choco command is the same whether you use PowerShell or the cmd prompt. Launch your favorite using the instructions as above. I'll use the administrator cmd prompt:
C:\WINDOWS\system32>choco upgrade python -y
Essentially, chocolatey will tell you "Hey, Python isn't installed" since you're coming from 2.7.x and it treats the 2.7 version as completely separate. It is only going to give you the most current version, 3.x.y (as of this writing, 3.7.2, but that will change in a few months):
Chocolatey v0.10.11
Upgrading the following packages:
python
By upgrading you accept licenses for the packages.
python is not installed. Installing...
python3 v3.x.y [Approved]
python3 package files upgrade completed. Performing other installation steps.
Installing 64-bit python3...
python3 has been installed.
Installed to: 'C:\Python37'
python3 can be automatically uninstalled.
Environment Vars (like PATH) have changed. Close/reopen your shell to
see the changes (or in powershell/cmd.exe just type `refreshenv`).
The upgrade of python3 was successful.
Software installed as 'exe', install location is likely default.
python v3.x.y [Approved]
python package files upgrade completed. Performing other installation steps.
The upgrade of python was successful.
Software install location not explicitly set, could be in package or
default install location if installer.
Chocolatey upgraded 2/2 packages.
See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log).
Either exit out of the cmd/Powershell prompt and re-enter it, or use refreshenv then type py --version
C:\Windows\System32>refreshenv
Refreshing environment variables from registry for cmd.exe. Please wait...Finished..
C:\Windows\system32>py --version
Python 3.7.2
Note that the most recent Python install will now take over when you type Python at the command line. You can run either version by using the following commands:
py -2
Python 2.7.16 (v2.7.16:413a49145e, Mar 4 2019, 01:37:19) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()
C:\>py -3
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>exit()
C:\>
From here I suggest you use the Python pip utility to install whatever packages you need. For example, let's say you wanted to install Flask. The commands below first upgrade pip, then install Flask
C:\>py -3 -m pip install --upgrade pip
Collecting pip
Downloading https://files.pythonhosted.org/packages/d8/f3/413bab4ff08e1fc4828dfc59996d721917df8e8583ea85385d51125dceff/pip-19.0.3-py2.py3-none-any.whl (1.4MB)
100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 1.4MB 1.6MB/s
Installing collected packages: pip
Found existing installation: pip 18.1
Uninstalling pip-18.1:
Successfully uninstalled pip-18.1
Successfully installed pip-19.0.3
c:\>py -3 -m pip install Flask
...will do the trick. Happy Pythoning!
I was successful via settings > Terminal > Integrated > Shell: Linux
from there I edited the path of the shell to be /bin/zsh from the default /bin/bash
@charlieParker - here's what i'm seeing for available commands in the command pallette
The following code I use mostly for achieving the asked effect:
body {
background-image: url('../images/bg.jpg');
background-repeat: no-repeat;
background-size: 100%;
}
According to the Apache documentation, found here, the DirectoryIndex
directive needs to be specified in the site .conf
file (typically found in /etc/apache2/sites-available
on linux).
Quoting from the docs, it reads:
If no file from the
DirectoryIndex
directive can be located in the directory, then mod_autoindex can generate a listing of the directory contents. This is turned on and off using theOptions
directive. For example, to turn on directory listings for a particular directory, you can use:<Directory /usr/local/apache2/htdocs/listme> Options +Indexes </Directory>
To prevent directory listings (for security purposes, for example), you should remove the Indexes keyword from every Options directive in your configuration file. Or to prevent them only for a single directory, you can use:
<Directory /usr/local/apache2/htdocs/dontlistme> Options -Indexes </Directory>
Use this instead:
string objTextBox = t.Text;
The object t
is the TextBox
. The object you call objTextBox
is assigned the ID
property of the TextBox
.
So better code would be:
TextBox objTextBox = (TextBox)sender;
string theText = objTextBox.Text;
More Suggestive answer supporting rmaddy's answer as our primary purpose is to delete unnecessary file and folder:
Delete this folder after every few days interval. Most of the time, it occupy huge space!
~/Library/Developer/Xcode/DerivedData
All your targets are kept in the archived form in Archives folder. Before you decide to delete contents of this folder, here is a warning - if you want to be able to debug deployed versions of your App, you shouldn’t delete the archives. Xcode will manage of archives and creates new file when new build is archived.
~/Library/Developer/Xcode/Archives
iOS Device Support folder creates a subfolder with the device version as an identifier when you attach the device. Most of the time it’s just old stuff. Keep the latest version and rest of them can be deleted (if you don’t have an app that runs on 5.1.1, there’s no reason to keep the 5.1.1 directory/directories). If you really don't need these, delete. But we should keep a few although we test app from device mostly.
~/Library/Developer/Xcode/iOS DeviceSupport
Core Simulator folder is familiar for many Xcode users. It’s simulator’s territory; that's where it stores app data. It’s obvious that you can toss the older version simulator folder/folders if you no longer support your apps for those versions. As it is user data, no big issue if you delete it completely but it’s safer to use ‘Reset Content and Settings’ option from the menu to delete all of your app data in a Simulator.
~/Library/Developer/CoreSimulator
(Here's a handy shell command for step 5: xcrun simctl delete unavailable
)
Caches are always safe to delete since they will be recreated as necessary. This isn’t a directory; it’s a file of kind Xcode Project. Delete away!
~/Library/Caches/com.apple.dt.Xcode
Additionally, Apple iOS device automatically syncs specific files and settings to your Mac every time they are connected to your Mac machine. To be on safe side, it’s wise to use Devices pane of iTunes preferences to delete older backups; you should be retaining your most recent back-ups off course.
~/Library/Application Support/MobileSync/Backup
Source: https://ajithrnayak.com/post/95441624221/xcode-users-can-free-up-space-on-your-mac
I got back about 40GB!
I think below explanation will help to you..
differentiation between those:
Correlated subquery
is an inner query referenced by main query (outer query) such that inner query considered as being excuted repeatedly.
non-correlated subquery
is a sub query that is an independent of the outer query and it can executed on it's own without relying on main outer query.
plain subquery
is not dependent on the outer query,
Which version of JUnit is this? I've only ever seen delta, not epsilon - but that's a side issue!
From the JUnit javadoc:
delta - the maximum delta between expected and actual for which both numbers are still considered equal.
It's probably overkill, but I typically use a really small number, e.g.
private static final double DELTA = 1e-15;
@Test
public void testDelta(){
assertEquals(123.456, 123.456, DELTA);
}
If you're using hamcrest assertions, you can just use the standard equalTo()
with two doubles (it doesn't use a delta). However if you want a delta, you can just use closeTo()
(see javadoc), e.g.
private static final double DELTA = 1e-15;
@Test
public void testDelta(){
assertThat(123.456, equalTo(123.456));
assertThat(123.456, closeTo(123.456, DELTA));
}
FYI the upcoming JUnit 5 will also make delta optional when calling assertEquals()
with two doubles. The implementation (if you're interested) is:
private static boolean doublesAreEqual(double value1, double value2) {
return Double.doubleToLongBits(value1) == Double.doubleToLongBits(value2);
}
You need to clear the old array out before you push the new data in. There are many ways to accomplish this but I used this one:
options.series[0].data.length = 0;
So your code should look like this:
options.series[0].data.length = 0;
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var data = {};
$.each(items, function(itemNo, item) {
if (itemNo === 0) {
data.name = item;
} else {
data.y = parseFloat(item);
}
});
options.series[0].data.push(data);
});
Now when the button is clicked the old data is purged and only the new data should show up. Hope that helps.
When I started to use Latex, I used Eclipse with the texlipse plugin. That allowed me to use the same environment in Linux and Windows, has some auto completion features and runs all tools (latex, bibtex, makeindex, ...) automatically to fully build the project.
But now I switched. Eclipse is large and slow on my PCs, crashes often and shows some weird behaviour here and there. Now I use vim for editing and make in collaboration with a self written perl script to build my projects. Using cygwin I am still able to use the same work flows under Linux and Windows.
What is a JavaScript or jQuery solution that will select all of the contents of a textbox when the textbox receives focus?
You only need to add the following attribute:
onfocus="this.select()"
For example:
<input type="text" value="sometext" onfocus="this.select()">
(Honestly I have no clue why you would need anything else.)
If you don't want to do it manually use Apache Commons - Codec library. The class you are looking at is: org.apache.commons.codec.net.URLCodec
String final url = "http://www.google.com?...."
String final urlSafe = org.apache.commons.codec.net.URLCodec.encode(url);
you can make use of localhost.org
or rather .localhost.org
it will always resolve to 127.0.0.1
If you have GNU find you can also say
find . -newermt '1 minute ago'
The t
options makes the reference "file" for newer
become a reference date string of the sort that you could pass to GNU date -d
, which understands complex date specifications like the one given above.
I think you can simply do:
class OuterClass:
outer_var = 1
class InnerClass:
pass
InnerClass.inner_var = outer_var
The problem you encountered is due to this:
A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition.
(...)
A scope defines the visibility of a name within a block.
(...)
The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes generator expressions since they are implemented using a function scope. This means that the following will fail:class A: a = 42 b = list(a + i for i in range(10))
http://docs.python.org/reference/executionmodel.html#naming-and-binding
The above means:
a function body is a code block and a method is a function, then names defined out of the function body present in a class definition do not extend to the function body.
Paraphrasing this for your case:
a class definition is a code block, then names defined out of the inner class definition present in an outer class definition do not extend to the inner class definition.
Try This,It's working perfect for me,
Follow below steps:
1. Define values in .h file.
#define kNoOfColumsForCollection 3
#define kNoOfRowsForCollection 4
#define kcellSpace 5
#define kCollectionViewCellWidth (self.view.frame.size.width - kcellSpace*kNoOfColumsForCollection)/kNoOfColumsForCollection
#define kCollectionViewCellHieght (self.view.frame.size.height-40- kcellSpace*kNoOfRowsForCollection)/kNoOfRowsForCollection
OR
#define kNoOfColumsForCollection 3
#define kCollectionViewCellWidthHieght (self.view.frame.size.width - 6*kNoOfColumsForCollection)/kNoOfColumsForCollection
2.Add Code in collection View Layout data source methods as below,
#pragma mark Collection View Layout data source methods
// collection view with autolayout
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return 4;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
return 1;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(4, 4, 4, 4);
}
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return
CGSizeMake(kCollectionViewCellWidth,kCollectionViewCellHieght);
// CGSizeMake (kCollectionViewCellWidthHieght,kCollectionViewCellWidthHieght);
}
Hope this will be help for some one.
My way to code that would be as follows:
// enum A { a, b, c }
static final Set<Short> enumA = new LinkedHashSet<>(Arrays.asList(new Short[]{'a','b','c'}));
// enum B extends A { d }
static final Set<Short> enumB = new LinkedHashSet<>(enumA);
static {
enumB.add((short) 'd');
// If you have to add more elements:
// enumB.addAll(Arrays.asList(new Short[]{ 'e', 'f', 'g', '?', '?' }));
}
LinkedHashSet
provides both that each entry only exists once, and that their order is preserved. If order doesn’t matter, you can use HashSet
instead. The following code is not possible in Java:
for (A a : B.values()) { // enum B extends A { d }
switch (a) {
case a:
case b:
case c:
System.out.println("Value is: " + a.toString());
break;
default:
throw new IllegalStateException("This should never happen.");
}
}
The code can be written as follows:
for (Short a : enumB) {
switch (a) {
case 'a':
case 'b':
case 'c':
System.out.println("Value is: " + new String(Character.toChars(a)));
break;
default:
throw new IllegalStateException("This should never happen.");
}
}
From Java 7 onwards you can even do the same with String
:
// enum A { BACKWARDS, FOREWARDS, STANDING }
static final Set<String> enumA = new LinkedHashSet<>(Arrays.asList(new String[] {
"BACKWARDS", "FOREWARDS", "STANDING" }));
// enum B extends A { JUMP }
static final Set<String> enumB = new LinkedHashSet<>(enumA);
static {
enumB.add("JUMP");
}
Using the enum replacement:
for (String a : enumB) {
switch (a) {
case "BACKWARDS":
case "FOREWARDS":
case "STANDING":
System.out.println("Value is: " + a);
break;
default:
throw new IllegalStateException("This should never happen.");
}
}
A static library must be linked into the final executable; it becomes part of the executable and follows it wherever it goes. A dynamic library is loaded every time the executable is executed and remains separate from the executable as a DLL file.
You would use a DLL when you want to be able to change the functionality provided by the library without having to re-link the executable (just replace the DLL file, without having to replace the executable file).
You would use a static library whenever you don't have a reason to use a dynamic library.
If anyone is trying to connect Nexus 5 to a formatted Windows XP then follow these steps:
Add both a maximum and a minimum value. You can specify the range of allowed values:
<input type="number" min="1" max="999" />
It's not that your file is partially downloaded. It fails authentication and hence downloads e.g "index.html" but it names it myfile.zip (since this is what you want to download).
I followed the link suggested by @thomasbabuj and figured it out eventually.
You should try adding --auth-no-challenge
and as @thomasbabuj suggested replace your password entry
I.e
wget --auth-no-challenge --user=myusername --ask-password https://test.mydomain.com/files/myfile.zip
You can make ArrayList of ViewHolder :
ArrayList<MyViewHolder> myViewHolders = new ArrayList<>();
ArrayList<MyViewHolder> myViewHolders2 = new ArrayList<>();
and, all store ViewHolder(s) in the list like :
@Override
public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
final String str = arrayList.get(position);
myViewHolders.add(position,holder);
}
and add/remove other ViewHolder in the ArrayList as per your requirement.
git add
adds your modified files to the queue to be committed later. Files are not committed
git commit
commits the files that have been added and creates a new revision with a log... If you do not add any files, git will not commit anything. You can combine both actions with git commit -a
git push
pushes your changes to the remote repository.
This figure from this git cheat sheet gives a good idea of the work flow
git add
isn't on the figure because the suggested way to commit is the combined git commit -a
, but you can mentally add a git add
to the change block to understand the flow.
Lastly, the reason why push
is a separate command is because of git
's philosophy. git
is a distributed versioning system, and your local working directory is your repository! All changes you commit are instantly reflected and recorded. push
is only used to update the remote repo (which you might share with others) when you're done with whatever it is that you're working on. This is a neat way to work and save changes locally (without network overhead) and update it only when you want to, instead of at every commit. This indirectly results in easier commits/branching etc (why not, right? what does it cost you?) which leads to more save points, without messing with the repository.
This is what you are trying to do but it poses some security and encoding problems so don't do it.
$url = "http://localhost/main.php?email=" . $email_address . "&eventid=" . $event_id;
All variables in querystrings need to be urlencoded to ensure proper transmission. You should never pass a user's personal information in a url because urls are very leaky. Urls end up in log files, browsing histories, referal headers, etc. The list goes on and on.
As for proper url encoding, it can be achieved using either urlencode()
or http_build_query()
. Either one of these should work:
$url = "http://localhost/main.php?email=" . urlencode($email_address) . "&eventid=" . urlencode($event_id);
or
$vars = array('email' => $email_address, 'event_id' => $event_id);
$querystring = http_build_query($vars);
$url = "http://localhost/main.php?" . $querystring;
Additionally, if $event_id
is in your session, you don't actually need to pass it around in order to access it from different pages. Just call session_start()
and it should be available.
Do you mean something like this? JSFiddle
Attribute used:
margin-left: 50px;
import os
path = chap_name
if not os.path.exists(path):
os.makedirs(path)
filename = img_alt + '.jpg'
with open(os.path.join(path, filename), 'wb') as temp_file:
temp_file.write(buff)
Key point is to use os.makedirs
in place of os.mkdir
. It is recursive, i.e. it generates all intermediate directories. See http://docs.python.org/library/os.html
Open the file in binary mode as you are storing binary (jpeg) data.
In response to Edit 2, if img_alt sometimes has '/' in it:
img_alt = os.path.basename(img_alt)
public abstract class Metadata
{
}
// extend abstract Metadata class
public class Metadata<DataType> : Metadata where DataType : struct
{
private DataType mDataType;
}
Try this way header('Content-Type: text/plain; charset=utf-8');
For simple input, like two prompts and two corresponding fixed responses, you could also use a "here document", the syntax of which looks like this:
test.sh <<!
y
pasword
!
The << prefixes a pattern, in this case '!'. Everything up to a line beginning with that pattern is interpreted as standard input. This approach is similar to the suggestion to pipe a multi-line echo into ssh, except that it saves the fork/exec of the echo command and I find it a bit more readable. The other advantage is that it uses built-in shell functionality so it doesn't depend on expect.
In Ecmascript 6,
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};
var res = Object.entries(obj);
console.log(res);
One can also use the java.util.EnumSet like this
@Test
void test(){
Enum aEnum =DayOfWeek.MONDAY;
printAll(aEnum);
}
void printAll(Enum value){
Set allValues = EnumSet.allOf(value.getClass());
System.out.println(allValues);
}
You are looking at sqljdbc4.2 version like :
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
but, for sqljdbc4 version statement should be:
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
I think if you change your first version to write the correct Class.forName , your application will run.
The XML declaration in the document map consists of the following:
The version number, ?xml version="1.0"?.
This is mandatory. Although the number might change for future versions of XML, 1.0 is the current version.
The encoding declaration,
encoding="UTF-8"?
This is optional. If used, the encoding declaration must appear immediately after the version information in the XML declaration, and must contain a value representing an existing character encoding.
uese following code.
NSString *searchText = @"Bhupi"
NSString *formatedSearchText = [NSString stringWithFormat:@"%%%@%%",searchText];
will output: %Bhupi%
Here is a fully worked example based on the top voted answer, which is:
int timeout = 1000;
var task = SomeOperationAsync();
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
// task completed within timeout
} else {
// timeout logic
}
The main advantage of the implementation in this answer is that generics have been added, so the function (or task) can return a value. This means that any existing function can be wrapped in a timeout function, e.g.:
Before:
int x = MyFunc();
After:
// Throws a TimeoutException if MyFunc takes more than 1 second
int x = TimeoutAfter(MyFunc, TimeSpan.FromSeconds(1));
This code requires .NET 4.5.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace TaskTimeout
{
public static class Program
{
/// <summary>
/// Demo of how to wrap any function in a timeout.
/// </summary>
private static void Main(string[] args)
{
// Version without timeout.
int a = MyFunc();
Console.Write("Result: {0}\n", a);
// Version with timeout.
int b = TimeoutAfter(() => { return MyFunc(); },TimeSpan.FromSeconds(1));
Console.Write("Result: {0}\n", b);
// Version with timeout (short version that uses method groups).
int c = TimeoutAfter(MyFunc, TimeSpan.FromSeconds(1));
Console.Write("Result: {0}\n", c);
// Version that lets you see what happens when a timeout occurs.
try
{
int d = TimeoutAfter(
() =>
{
Thread.Sleep(TimeSpan.FromSeconds(123));
return 42;
},
TimeSpan.FromSeconds(1));
Console.Write("Result: {0}\n", d);
}
catch (TimeoutException e)
{
Console.Write("Exception: {0}\n", e.Message);
}
// Version that works on tasks.
var task = Task.Run(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(1));
return 42;
});
// To use async/await, add "await" and remove "GetAwaiter().GetResult()".
var result = task.TimeoutAfterAsync(TimeSpan.FromSeconds(2)).
GetAwaiter().GetResult();
Console.Write("Result: {0}\n", result);
Console.Write("[any key to exit]");
Console.ReadKey();
}
public static int MyFunc()
{
return 42;
}
public static TResult TimeoutAfter<TResult>(
this Func<TResult> func, TimeSpan timeout)
{
var task = Task.Run(func);
return TimeoutAfterAsync(task, timeout).GetAwaiter().GetResult();
}
private static async Task<TResult> TimeoutAfterAsync<TResult>(
this Task<TResult> task, TimeSpan timeout)
{
var result = await Task.WhenAny(task, Task.Delay(timeout));
if (result == task)
{
// Task completed within timeout.
return task.GetAwaiter().GetResult();
}
else
{
// Task timed out.
throw new TimeoutException();
}
}
}
}
Caveats
Having given this answer, its generally not a good practice to have exceptions thrown in your code during normal operation, unless you absolutely have to:
Only use this code if you absolutely cannot alter the function you are calling so it times out after a specific TimeSpan
.
This answer is really only applicable when dealing with 3rd party library libraries that you simply cannot refactor to include a timeout parameter.
How to write robust code
If you want to write robust code, the general rule is this:
Every single operation that could potentially block indefinitely, must have a timeout.
If you do not observe this rule, your code will eventually hit an operation that fails for some reason, then it will block indefinitely, and your app has just permanently hung.
If there was a reasonable timeout after some time, then your app would hang for some extreme amount of time (e.g. 30 seconds) then it would either display an error and continue on its merry way, or retry.
When you have too complex objects with saveral collection could not be good idea to have all of them with EAGER fetchType, better use LAZY and when you really need to load the collections use: Hibernate.initialize(parent.child)
to fetch the data.
You can use backslash to quote "funny" characters in your jQuery selectors:
$('#input\\[23\\]')
For attribute values, you can use quotes:
$('input[name="weirdName[23]"]')
Now, I'm a little confused by your example; what exactly does your HTML look like? Where does the string "inputName" show up, in particular?
edit fixed bogosity; thanks @Dancrumb
Convert your dates to GMT timezone as you're stuffing them into Mongo. That way there's never a timezone issue. Then just do the math on the twitter/timezone field when you pull the data back out for presentation.
That should work:
function get_content(){
var p = document.getElementById("txt");
var spans = p.getElementsByTagName("span");
var text = '';
for (var i = 0; i < spans.length; i++){
text += spans[i].innerHTML;
}
p.innerHTML = text;
}
Try this fiddle: http://jsfiddle.net/7gnyc/2/
The only option I have found to do this is find some exact wording and put that under the "Has the words" option. Its not the best option, but it works.
There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX function gettimeofday().
I use a similar technique to what @Sarfraz posted, except instead of hiding elements, I just manipulate the class of the image that I'm loading.
<style type="text/css">
.loading { background-image: url(loading.gif); }
.loaderror { background-image: url(loaderror.gif); }
</style>
...
<img id="image" class="loading" />
...
<script type="text/javascript">
var img = new Image();
img.onload = function() {
i = document.getElementById('image');
i.removeAttribute('class');
i.src = img.src;
};
img.onerror = function() {
document.getElementById('image').setAttribute('class', 'loaderror');
};
img.src = 'http://path/to/image.png';
</script>
In my case, sometimes images don't load, so I handle the onerror event to change the image class so it displays an error background image (rather than the browser's broken image icon).
"abcdefgh..".IndexOf("d")
returns 3
In general returns first occurrence index, if not present returns -1
It's an old trick, but I still find the easiest way to do this is to use outline-offset with a negative value (example below uses -6px). Here's a fiddle of it—I've made the outer border red and the outline white to differentiate the two:
.outline-offset {
width:300px;
height:200px;
background:#333c4b;
border:2px solid red;
outline:2px #fff solid;
outline-offset:-6px;
}
<div class="outline-offset"></div>
The __import__
function can be a bit hard to understand.
If you change
i = __import__('matplotlib.text')
to
i = __import__('matplotlib.text', fromlist=[''])
then i
will refer to matplotlib.text
.
In Python 2.7 and Python 3.1 or later, you can use importlib
:
import importlib
i = importlib.import_module("matplotlib.text")
Some notes
If you're trying to import something from a sub-folder e.g. ./feature/email.py
, the code will look like importlib.import_module("feature.email")
You can't import anything if there is no __init__.py
in the folder with file you are trying to import
Three libraries for accessing and manipulating dates and times, namely datetime, arrow and pendulum, all make these items available in namedtuples whose elements are accessible either by name or index. Moreover, the items are accessible in precisely the same way. (I suppose if I were more intelligent I wouldn't be surprised.)
>>> YEARS, MONTHS, DAYS, HOURS, MINUTES = range(5)
>>> import datetime
>>> import arrow
>>> import pendulum
>>> [datetime.datetime.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [arrow.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [pendulum.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 16]
ByteArrayInputStream also does the trick:
InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );
Then convert to reader:
InputStreamReader reader = new InputStreamReader(is);
Old thread, but learned something new, hope this might help someone.
If you want to change the background color but retain other styles, then below might help.
button.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.colorAccent), PorterDuff.Mode.MULTIPLY);
Couldn't get the accepted answer to work. Then found out that actually the solution is much simpler anyway as Ghostscript not just natively supports PNG but even multiple different "encodings":
png256
png16
pnggray
pngmono
The shell command that works for me is:
gs -dNOPAUSE -q -sDEVICE=pnggray -r500 -dBATCH -dFirstPage=2 -dLastPage=2 -sOutputFile=test.png test.pdf
It will save page 2 of test.pdf to test.png using the pnggray
encoding and 500 DPI.
Sure! Setup:
>>> import pandas as pd
>>> from random import randint
>>> df = pd.DataFrame({'A': [randint(1, 9) for x in range(10)],
'B': [randint(1, 9)*10 for x in range(10)],
'C': [randint(1, 9)*100 for x in range(10)]})
>>> df
A B C
0 9 40 300
1 9 70 700
2 5 70 900
3 8 80 900
4 7 50 200
5 9 30 900
6 2 80 700
7 2 80 400
8 5 80 300
9 7 70 800
We can apply column operations and get boolean Series objects:
>>> df["B"] > 50
0 False
1 True
2 True
3 True
4 False
5 False
6 True
7 True
8 True
9 True
Name: B
>>> (df["B"] > 50) & (df["C"] == 900)
0 False
1 False
2 True
3 True
4 False
5 False
6 False
7 False
8 False
9 False
[Update, to switch to new-style .loc
]:
And then we can use these to index into the object. For read access, you can chain indices:
>>> df["A"][(df["B"] > 50) & (df["C"] == 900)]
2 5
3 8
Name: A, dtype: int64
but you can get yourself into trouble because of the difference between a view and a copy doing this for write access. You can use .loc
instead:
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"]
2 5
3 8
Name: A, dtype: int64
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"].values
array([5, 8], dtype=int64)
>>> df.loc[(df["B"] > 50) & (df["C"] == 900), "A"] *= 1000
>>> df
A B C
0 9 40 300
1 9 70 700
2 5000 70 900
3 8000 80 900
4 7 50 200
5 9 30 900
6 2 80 700
7 2 80 400
8 5 80 300
9 7 70 800
Note that I accidentally typed == 900
and not != 900
, or ~(df["C"] == 900)
, but I'm too lazy to fix it. Exercise for the reader. :^)
Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.
Try this Using moment.js (Its quite easy to compute date operations in javascript)
firstDate.diff(secondDate, 'days', false);// true|false for fraction value
Result will give you number of days in integer.
I am also new to this.
I have followed this process to start the application in Mac:
apache-jmeter-3.3_src.zip
from
http://jmeter.apache.org/download_jmeter.cgi website.jmeter
, this is an executable file. Right click
on this and open with terminal and wait for 5 minutes, that's it.Thank you, I hope this might help.
Try this: tar -cf file.tar file-to-compress ; xz -z file.tar
Note:
|
because this runs commands simultaneously. Using ;
or &
executes commands one after another.This has been mentioned in other questions, but ctrl + [ is an equivalent to ESC on all keyboards.
See, why this way that you are doing is not working. First, you are trying to get integer from a Row Type, the output of your collect is like this:
>>> mvv_list = mvv_count_df.select('mvv').collect()
>>> mvv_list[0]
Out: Row(mvv=1)
If you take something like this:
>>> firstvalue = mvv_list[0].mvv
Out: 1
You will get the mvv
value. If you want all the information of the array you can take something like this:
>>> mvv_array = [int(row.mvv) for row in mvv_list.collect()]
>>> mvv_array
Out: [1,2,3,4]
But if you try the same for the other column, you get:
>>> mvv_count = [int(row.count) for row in mvv_list.collect()]
Out: TypeError: int() argument must be a string or a number, not 'builtin_function_or_method'
This happens because count
is a built-in method. And the column has the same name as count
. A workaround to do this is change the column name of count
to _count
:
>>> mvv_list = mvv_list.selectExpr("mvv as mvv", "count as _count")
>>> mvv_count = [int(row._count) for row in mvv_list.collect()]
But this workaround is not needed, as you can access the column using the dictionary syntax:
>>> mvv_array = [int(row['mvv']) for row in mvv_list.collect()]
>>> mvv_count = [int(row['count']) for row in mvv_list.collect()]
And it will finally work!
how do you get
"\u6f22\u5b57"
from??
in JavaScript?
These are JavaScript Unicode escape sequences e.g. \u12AB
. To convert them, you could iterate over every code unit in the string, call .toString(16)
on it, and go from there.
However, it is more efficient to also use hexadecimal escape sequences e.g. \xAA
in the output wherever possible.
Also note that ASCII symbols such as A
, b
, and -
probably don’t need to be escaped.
I’ve written a small JavaScript library that does all this for you, called jsesc
. It has lots of options to control the output.
Here’s an online demo of the tool in action: http://mothereff.in/js-escapes#1%E6%BC%A2%E5%AD%97
Your question was tagged as utf-8
. Reading the rest of your question, UTF-8 encoding/decoding didn’t seem to be what you wanted here, but in case you ever need it: use utf8.js
(online demo).
If you are using JetPack Navigation.
Here is the layout for MainActivity
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolBar"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.appcompat.widget.Toolbar>
<fragment
android:id="@+id/my_nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintTop_toBottomOf="@id/toolBar"
app:layout_constraintBottom_toTopOf="parent"
app:navGraph="@navigation/nav_graph"/>
SetUp your toolbar in your activity like below in onCreate() of your Activity class.
val navHostFragment = supportFragmentManager
.findFragmentById(R.id.my_nav_host_fragment) as NavHostFragment? ?: return
val navController = navHostFragment.findNavController()
val toolBar = findViewById<Toolbar>(R.id.toolBar)
setSupportActionBar(toolBar) // To set toolBar as ActionBar
setupActionBarWithNavController(navController)
setupActionBarWithNavController(navController) Will create a back button on the toolBar if needed and handles the backButton functionality. If you need to write a CustomBack functionality, create a callBack as below on your fragment onCreate() method
val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
// Handle the back button event
}
From Documentation:https://developer.android.com/guide/navigation/navigation-custom-back
You could do $stmt->queryString
to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.
First Level Cache
Session object holds the first level cache data. It is enabled by default. The first level cache data will not be available to entire application. An application can use many session object.
Second Level Cache
SessionFactory object holds the second level cache data. The data stored in the second level cache will be available to entire application. But we need to enable it explicitly.
FXCop typically prefers OrdinalIgnoreCase
. But your requirements may vary.
For English there is very little difference. It is when you wander into languages that have different written language constructs that this becomes an issue. I am not experienced enough to give you more than that.
OrdinalIgnoreCase
The StringComparer returned by the OrdinalIgnoreCase property treats the characters in the strings to compare as if they were converted to uppercase using the conventions of the invariant culture, and then performs a simple byte comparison that is independent of language. This is most appropriate when comparing strings that are generated programmatically or when comparing case-insensitive resources such as paths and filenames. http://msdn.microsoft.com/en-us/library/system.stringcomparer.ordinalignorecase.aspx
InvariantCultureIgnoreCase
The StringComparer returned by the InvariantCultureIgnoreCase property compares strings in a linguistically relevant manner that ignores case, but it is not suitable for display in any particular culture. Its major application is to order strings in a way that will be identical across cultures. http://msdn.microsoft.com/en-us/library/system.stringcomparer.invariantcultureignorecase.aspx
The invariant culture is the CultureInfo object returned by the InvariantCulture property.
The InvariantCultureIgnoreCase property actually returns an instance of an anonymous class derived from the StringComparer class.
It is also possible to include bitmaps. I think you also can use transformations on that.
A complete beginner like myself to the topic may find it harder to implement one of these answers than, if within your control, to resize the image yourself with an online editor or a photo editor like Photoshop.
A 500x500 image will appear larger on the map than a 50x50 image.
No programming required.
There are three states for a thread.
Now, when a notify() is called, JVM picks one thread and move them to the BLOCKED state and hence to the RUNNING state as there is no competition for the monitor object.
When a notifyAll() is called, JVM picks all the threads and move all of them to BLOCKED state. All these threads will get the lock of the object on a priority basis. Thread which is able to acquire the monitor first will be able to go to the RUNNING state first and so on.
(Not cross-browser tested), but this is my answer:
.btn-circle {
width: 40px;
height: 40px;
line-height: 40px; /* adjust line height to align vertically*/
padding:0;
border-radius: 50%;
}
I found this solution in this article
.parent-element {
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
transform-style: preserve-3d;
}
.element {
position: relative;
top: 50%;
transform: translateY(-50%);
}
It work like a charm if the height of element is not fixed.
I still prefer the method in one line
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime())
First, convert the base 64 string to an Image
, then use the Image.Save
method.
To convert from base 64 string to Image
:
public Image Base64ToImage(string base64String)
{
// Convert base 64 string to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
// Convert byte[] to Image
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
Image image = Image.FromStream(ms, true);
return image;
}
}
To convert from Image
to base 64 string:
public string ImageToBase64(Image image,System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to base 64 string
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
Finally, you can easily to call Image.Save(filePath);
to save the image.
Take a look at the vkbeautify module.
It is a python version of my very popular javascript/nodejs plugin with the same name. It can pretty-print/minify XML, JSON and CSS text. Input and output can be string/file in any combinations. It is very compact and doesn't have any dependency.
Examples:
import vkbeautify as vkb
vkb.xml(text)
vkb.xml(text, 'path/to/dest/file')
vkb.xml('path/to/src/file')
vkb.xml('path/to/src/file', 'path/to/dest/file')
I think in this case concat
is what you want:
In [12]:
pd.concat([df,df1], axis=0, ignore_index=True)
Out[12]:
attr_1 attr_2 attr_3 id quantity
0 0 1 NaN 1 20
1 1 1 NaN 2 23
2 1 1 NaN 3 19
3 0 0 NaN 4 19
4 1 NaN 0 5 8
5 0 NaN 1 6 13
6 1 NaN 1 7 20
7 1 NaN 1 8 25
by passing axis=0
here you are stacking the df's on top of each other which I believe is what you want then producing NaN
value where they are absent from their respective dfs.
Depending on your application, you may want to consider using System.nanoTime()
instead.
Web.Config file:
<configuration>
<system.net>
<mailSettings>
<smtp from="[email protected]">
<network host="smtp.gmail.com"
port="587"
userName="[email protected]"
password="yourpassword"
enableSsl="true"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
The spring configuration precedence is as follows.
So your configuration will be overridden at the command-line if you wish to do that. But the recommendation is to avoid overriding, though you can use multiple profiles.
Based on Rubens' solution, you need to enable Delayed Expansion of env variables (type "help setlocal" or "help cmd") so that the var is correctly evaluated in the loop:
@echo off
setlocal enabledelayedexpansion
set myvar=the list:
for /r %%i In (*.sql) DO set myvar=!myvar! %%i,
echo %myvar%
Also consider the following restriction (MSDN):
The maximum individual environment variable size is 8192bytes.
Through program :
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(YourApplicationMain.class)
.web(WebApplicationType.NONE)
.run(args);
Through application.properties file :
spring.main.web-environment=false
Through application.yml file :
spring:
main:
web-environment:false
Just open it in 'a'
mode:
a
Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file.
with open(filename, 'a') as f:
f.write(...)
To see whether you're writing to a new file, check the stream position. If it's zero, either the file was empty or it is a new file.
with open('somefile.txt', 'a') as f:
if f.tell() == 0:
print('a new file or the file was empty')
f.write('The header\n')
else:
print('file existed, appending')
f.write('Some data\n')
If you're still using Python 2, to work around the bug, either add f.seek(0, os.SEEK_END)
right after open
or use io.open
instead.
Then there's the way of expressing your 'if' construct more tersely:
FOO='default'
[ -n "${VARIABLE}" ] && FOO=${VARIABLE}
Check box-sizing
css property of your td
elements. I had problem with css template which sets it to border-box
value. You need set box-sizing: content-box
.
Found a strange behaviour about this hidden value () and we can't make it to work.
After playing around we found the best way is just defined the value in controller itself after the form scope.
.controller('AddController', [$scope, $http, $state, $stateParams, function($scope, $http, $state, $stateParams) {
$scope.routineForm = {};
$scope.routineForm.hiddenfield1 = "whatever_value_you_pass_on";
$scope.sendData = function {
// JSON http post action to API
}
}])
ZoneId usersTimeZone = ZoneId.of("Asia/Tashkent");
Locale usersLocale = Locale.forLanguageTag("ga-IE");
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
.withLocale(usersLocale);
long microsSince1970 = 1_512_345_678_901_234L;
long secondsSince1970 = TimeUnit.MICROSECONDS.toSeconds(microsSince1970);
long remainingMicros = microsSince1970 - TimeUnit.SECONDS.toMicros(secondsSince1970);
ZonedDateTime dateTime = Instant.ofEpochSecond(secondsSince1970,
TimeUnit.MICROSECONDS.toNanos(remainingMicros))
.atZone(usersTimeZone);
String dateTimeInUsersFormat = dateTime.format(formatter);
System.out.println(dateTimeInUsersFormat);
The above snippet prints:
4 Noll 2017 05:01:18
“Noll” is Gaelic for December, so this should make your user happy. Except there may be very few Gaelic speaking people living in Tashkent, so please specify the user’s correct time zone and locale yourself.
I am taking seriously that you got microseconds from your database. If second precision is fine, you can do without remainingMicros
and just use the one-arg Instant.ofEpochSecond()
, which will make the code a couple of lines shorter. Since Instant
and ZonedDateTime
do support nanosecond precision, I found it most correct to keep the full precision of your timestamp. If your timestamp was in milliseconds rather than microseconds (which they often are), you may just use Instant.ofEpochMilli()
.
The answers using Date
, Calendar
and/or SimpleDateFormat
were fine when this question was asked 7 years ago. Today those classes are all long outdated, and we have so much better in java.time
, the modern Java date and time API.
For most uses I recommend you use the built-in localized formats as I do in the code. You may experiment with passing SHORT
, LONG
or FULL
for format style. Yo may even specify format style for the date and for the time of day separately using an overloaded ofLocalizedDateTime
method. If a specific format is required (this was asked in a duplicate question), you can have that:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss, dd/MM/uuuu");
Using this formatter instead we get
05:01:18, 04/12/2017
Link: Oracle tutorial: Date Time explaining how to use java.time
.
If you set numberOfLines
to 0 (and the label to word wrap), the label will automatically wrap and use as many of lines as needed.
If you're editing a UILabel
in IB, you can enter multiple lines of text by pressing option+return to get a line break - return alone will finish editing.
You haven't at time of writing described what you are going to do with the response or what its content type is. An answer already contains a very basic usage of MSXML2.XMLHTTP
(I recommend the more explicit MSXML2.XMLHTTP.3.0
progID) however you may need to do different things with the response, it may not be text.
The XMLHTTP also has a responseBody
property which is a byte array version of the reponse and there is a responseStream
which is an IStream
wrapper for the response.
Note that in a server-side requirement (e.g., VBScript hosted in ASP) you would use MSXML.ServerXMLHTTP.3.0
or WinHttp.WinHttpRequest.5.1
(which has a near identical interface).
Here is an example of using XmlHttp to fetch a PDF file and store it:-
Dim oXMLHTTP
Dim oStream
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0")
oXMLHTTP.Open "GET", "http://someserver/folder/file.pdf", False
oXMLHTTP.Send
If oXMLHTTP.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write oXMLHTTP.responseBody
oStream.SaveToFile "c:\somefolder\file.pdf"
oStream.Close
End If
You can use:
List<String> list = Files.readAllLines(new File("input.txt").toPath(), Charset.defaultCharset() );
Source: Java API 7.0
Hmmm, perhaps another option would be to use something like sshfs (there an sshfs for Mac too). Once your router is mounted you can just copy the files outright. I'm not sure if that works for your particular application but it's a nice solution to keep handy.
Try this:
string text = "My text that I want to display";
MessageBox.Show(text);
I had the same problem. In my case I had by mistake I had set all the projects apart from the project with the main method as console application.
To resolve I went to every project other than the one with main function and right click> properites > output type > class library
If using XML configuration you can use
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security">
<security:http>
<security:headers>
<security:frame-options disabled="true"></security:frame-options>
</security:headers>
</security:http>
</beans>
I encountered the same problem even I set "UseDefaultCredentials" to false. Later I found that the root cause is that I turned on "2-step Verification" in my account. After I turned it off, the problem is gone.
In this two queries, you are using JOIN to query all employees that have at least one department associated.
But, the difference is: in the first query you are returning only the Employes for the Hibernate. In the second query, you are returning the Employes and all Departments associated.
So, if you use the second query, you will not need to do a new query to hit the database again to see the Departments of each Employee.
You can use the second query when you are sure that you will need the Department of each Employee. If you not need the Department, use the first query.
I recomend read this link if you need to apply some WHERE condition (what you probably will need): How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?
Update
If you don't use fetch
and the Departments continue to be returned, is because your mapping between Employee and Department (a @OneToMany
) are setted with FetchType.EAGER
. In this case, any HQL (with fetch
or not) query with FROM Employee
will bring all Departments. Remember that all mapping *ToOne (@ManyToOne
and @OneToOne
) are EAGER by default.
I had the same problem with my Windows 8. The Android/SDK USB driver was installed correctly, but I forgot to install the USB driver from my phone. After installing the phone USB driver ADB works fine.
I hope this will help.
Use the object tag:
<object data="http://iamawesome.com" type="text/html" width="200" height="200">
<a href="http://iamawesome.com">access the page directly</a>
</object>
Ref: http://debug.ga/embedding-external-pages-without-iframes/
Here is an idea you can try. Original table - no identity column table1 create a new table - call table2 along with identity column. copy the data from table1 to table2 - the identity column is populated automatically with auto incremented numbers.
rename the original table - table1 to table3 rename the new table - table2 to table1 (original table) Now you have the table1 with identity column included and populated for the existing data. after making sure there is no issue and working properly, drop the table3 when no longer needed.
I was getting the same the error inside a shared function, but it was only happening for some calls to this shared function. I eventually realized that one of classes calling the shared function wasn't wrapping it inside of a Unit of Work. Once I updated this classes functions with a Unit of Work everything worked as expected.
So just posting this for any future visitors who run into this same error, but for whom the accepted answer doesn't apply.
pure javascript no jQuery
function sah() {_x000D_
$("#div2").attr("disabled", "disabled").off('click');_x000D_
var x1=$("#div2").hasClass("disabledDiv");_x000D_
_x000D_
(x1==true)?$("#div2").removeClass("disabledDiv"):$("#div2").addClass("disabledDiv");_x000D_
sah1(document.getElementById("div1"));_x000D_
_x000D_
}_x000D_
_x000D_
function sah1(el) {_x000D_
try {_x000D_
el.disabled = el.disabled ? false : true;_x000D_
} catch (E) {}_x000D_
if (el.childNodes && el.childNodes.length > 0) {_x000D_
for (var x = 0; x < el.childNodes.length; x++) {_x000D_
sah1(el.childNodes[x]);_x000D_
}_x000D_
}_x000D_
}
_x000D_
#div2{_x000D_
padding:5px 10px;_x000D_
background-color:#777;_x000D_
width:150px;_x000D_
margin-bottom:20px;_x000D_
}_x000D_
.disabledDiv {_x000D_
pointer-events: none;_x000D_
opacity: 0.4;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<div id="div1">_x000D_
<div id="div2" onclick="alert('Hello')">Click me</div>_x000D_
<input type="text" value="SAH Computer" />_x000D_
<br />_x000D_
<input type="button" value="SAH Computer" />_x000D_
<br />_x000D_
<input type="radio" name="sex" value="Male" />Male_x000D_
<Br />_x000D_
<input type="radio" name="sex" value="Female" />Female_x000D_
<Br />_x000D_
</div>_x000D_
<Br />_x000D_
<Br />_x000D_
<input type="button" value="Click" onclick="sah()" />
_x000D_
I think Dan and Nicola have suitable corrected code, however you may not be clear on why the original code didn't work.
What has been called here a "ternary operator" is called a conditional operator in ECMA-262 section 11.12. It has the form:
LogicalORExpression ? AssignmentExpression : AssignmentExpression
The LogicalORExpression is evaluated and the returned value converted to Boolean (just like an expression in an if condition). If it evaluates to true, then the first AssignmentExpression is evaluated and the returned value returned, otherwise the second is evaluated and returned.
The error in the original code is the extra semi-colons that change the attempted conditional operator into a series of statements with syntax errors.
What is the value you're passing to the primary key (presumably "pk_OrderID")? You can set it up to auto increment, and then there should never be a problem with duplicating the value - the DB will take care of that. If you need to specify a value yourself, you'll need to write code to determine what the max value for that field is, and then increment that.
If you have a column named "ID" or such that is not shown in the query, that's fine as long as it is set up to autoincrement - but it's probably not, or you shouldn't get that err msg. Also, you would be better off writing an easier-on-the-eye query and using params. As the lad of nine years hence inferred, you're leaving your database open to SQL injection attacks if you simply plop in user-entered values. For example, you could have a method like this:
internal static int GetItemIDForUnitAndItemCode(string qry, string unit, string itemCode)
{
int itemId;
using (SqlConnection sqlConn = new SqlConnection(ReportRunnerConstsAndUtils.CPSConnStr))
{
using (SqlCommand cmd = new SqlCommand(qry, sqlConn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@Unit", SqlDbType.VarChar, 25).Value = unit;
cmd.Parameters.Add("@ItemCode", SqlDbType.VarChar, 25).Value = itemCode;
sqlConn.Open();
itemId = Convert.ToInt32(cmd.ExecuteScalar());
}
}
return itemId;
}
...that is called like so:
int itemId = SQLDBHelper.GetItemIDForUnitAndItemCode(GetItemIDForUnitAndItemCodeQuery, _unit, itemCode);
You don't have to, but I store the query separately:
public static readonly String GetItemIDForUnitAndItemCodeQuery = "SELECT PoisonToe FROM Platypi WHERE Unit = @Unit AND ItemCode = @ItemCode";
You can verify that you're not about to insert an already-existing value by (pseudocode):
bool alreadyExists = IDAlreadyExists(query, value) > 0;
The query is something like "SELECT COUNT FROM TABLE WHERE BLA = @CANDIDATEIDVAL" and the value is the ID you're potentially about to insert:
if (alreadyExists) // keep inc'ing and checking until false, then use that id value
Justin wants to know if this will work:
string exists = "SELECT 1 from AC_Shipping_Addresses where pk_OrderID = " _Order.OrderNumber; if (exists > 0)...
What seems would work to me is:
string existsQuery = string.format("SELECT 1 from AC_Shipping_Addresses where pk_OrderID = {0}", _Order.OrderNumber);
// Or, better yet:
string existsQuery = "SELECT COUNT(*) from AC_Shipping_Addresses where pk_OrderID = @OrderNumber";
// Now run that query after applying a value to the OrderNumber query param (use code similar to that above); then, if the result is > 0, there is such a record.
You can use this easiest method.
<form action="validator.php" method="post" id="form1">_x000D_
<input type="text" name="user">_x000D_
<input type="password" name="password">_x000D_
<input type="submit" value="submit" form="form1">_x000D_
</form>_x000D_
_x000D_
<br />_x000D_
_x000D_
<form action="validator.php" method="post" id="form2">_x000D_
<input type="text" name="user">_x000D_
<input type="password" name="password">_x000D_
<input type="submit" value="submit" form="form2">_x000D_
</form>
_x000D_
You can use moment()
and format()
functions in AngularJS.
Controller:
var app = angular.module('demoApp', []);
app.controller( 'demoCtrl', ['$scope', '$moment' function($scope , $moment) {
$scope.date = $moment().format('MM/DD/YYYY');
}]);
View:
<div ng-app="demoApp">
<div ng-controller="demoCtrl">
{{date}}
</div>
</div>
You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:
Dim MyVar as string = "some text ""hello"" "
This will give the MyVar
variable a value of some text "hello"
.
Updating gradle/wrapper/gradle-wrapper.properties
with the following version fixed it for me:
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
It seems strange that you would write arrays without commas (is that a MATLAB syntax?)
Have you tried going through NumPy's documentation on multi-dimensional arrays?
It seems NumPy has a "Python-like" append method to add items to a NumPy n-dimensional array:
>>> p = np.array([[1,2],[3,4]])
>>> p = np.append(p, [[5,6]], 0)
>>> p = np.append(p, [[7],[8],[9]],1)
>>> p
array([[1, 2, 7], [3, 4, 8], [5, 6, 9]])
It has also been answered already...
From the documentation for MATLAB users:
You could use a matrix constructor which takes a string in the form of a matrix MATLAB literal:
mat("1 2 3; 4 5 6")
or
matrix("[1 2 3; 4 5 6]")
Please give it a try and tell me how it goes.
Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "]
with array("title" => "Welcome ")
Yes, it can be done.
It is based on the new html5 "download" attribute of anchor tags.
The flow should be something like this :
href
attribute for an anchor tag in the dom download="desired-file-name"
) to that a
element
That's it. all the user has to do is click your "download link" and the image will be downloaded to his pc. I'll come back with a demo when I get the chance.
Update
Here's the live demo as I promised. It takes the jsfiddle logo and crops 5px of each margin.
The code looks like this :
var img = new Image();
img.onload = function(){
var cropMarginWidth = 5,
canvas = $('<canvas/>')
.attr({
width: img.width - 2 * cropMarginWidth,
height: img.height - 2 * cropMarginWidth
})
.hide()
.appendTo('body'),
ctx = canvas.get(0).getContext('2d'),
a = $('<a download="cropped-image" title="click to download the image" />'),
cropCoords = {
topLeft : {
x : cropMarginWidth,
y : cropMarginWidth
},
bottomRight :{
x : img.width - cropMarginWidth,
y : img.height - cropMarginWidth
}
};
ctx.drawImage(img, cropCoords.topLeft.x, cropCoords.topLeft.y, cropCoords.bottomRight.x, cropCoords.bottomRight.y, 0, 0, img.width, img.height);
var base64ImageData = canvas.get(0).toDataURL();
a
.attr('href', base64ImageData)
.text('cropped image')
.appendTo('body');
a
.clone()
.attr('href', img.src)
.text('original image')
.attr('download','original-image')
.appendTo('body');
canvas.remove();
}
img.src = 'some-image-src';
Update II
Forgot to mention : of course there is a downside :(.
Because of the same-origin policy that is applied to images too, if you want to access an image's data (through the canvas method toDataUrl
).
So you would still need a server-side proxy that would serve your image as if it were hosted on your domain.
Update III Although I can't provide a live demo for this (for security reasons), here is a php sample code that solves the same-origin policy :
file proxy.php
:
$imgData = getimagesize($_GET['img']);
header("Content-type: " . $imgData['mime']);
echo file_get_contents($_GET['img']);
This way, instead of loading the external image direct from it's origin :
img.src = 'http://some-domain.com/imagefile.png';
You can load it through your proxy :
img.src = 'proxy.php?img=' + encodeURIComponent('http://some-domain.com/imagefile.png');
And here's a sample php code for saving the image data (base64) into an actual image :
file save-image.php
:
$data = preg_replace('/data:image\/(png|jpg|jpeg|gif|bmp);base64/','',$_POST['data']);
$data = base64_decode($data);
$img = imagecreatefromstring($data);
$path = 'path-to-saved-images/';
// generate random name
$name = substr(md5(time()),10);
$ext = 'png';
$imageName = $path.$name.'.'.$ext;
// write the image to disk
imagepng($img, $imageName);
imagedestroy($img);
// return the image path
echo $imageName;
All you have to do then is post the image data to this file and it will save the image to disc and return you the existing image filename.
Of course all this might feel a bit complicated, but I wanted to show you that what you're trying to achieve is possible.
I had this same issue - I had just added the font-awesome cdn links - commenting out the bootstrap one below solved my issue.. didnt really troubleshoot it as the font awesome still worked -
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
OR you can use pandas
:
>>> import pandas as pd
>>> L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
>>> df=pd.DataFrame(L)
>>> df[1]
0 2
1 3
2 5
3 4
4 7
5 7
6 8
Name: 1, dtype: int64
>>> df[1].tolist()
[2, 3, 5, 4, 7, 7, 8]
>>>
Or numpy
:
>>> import numpy as np
>>> L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
>>> arr=np.array(L)
>>> arr.T[1]
array([2, 3, 5, 4, 7, 7, 8])
>>> arr.T[1].tolist()
[2, 3, 5, 4, 7, 7, 8]
>>>
The only safe way to protect your code is not giving it away. With client deployment, there is no avoiding the client having access to the code.
So the short answer is: You can't do it
The longer answer is considering flash or Silverlight. Although I believe silverlight will gladly give away it's secrets with reflector running on the client.
I'm not sure if something simular exists with the flash platform.