Simple try to remove name attribute from input element.
So it has to look like
<input type="checkbox" checked="" id="class_box_2" value="2">
I believe what are you asking about is a variable interpolation in PHP.
Let's do a simple fixture:
$obj = (object) array('foo' => array('bar'), 'property' => 'value');
$var = 'foo';
Now we have an object, where:
print_r($obj);
Will give output:
stdClass Object
(
[foo] => Array
(
[0] => bar
)
[property] => value
)
And we have variable $var
containing string "foo".
If you'll try to use:
$give_me_foo = $obj->$var[0];
Instead of:
$give_me_foo = $obj->foo[0];
You get "Cannot use string offset as an array [...]" error message as a result, because what you are trying to do, is in fact sending message $var[0]
to object $obj
. And - as you can see from fixture - there is no content of $var[0]
defined. Variable $var
is a string and not an array.
What you can do in this case is to use curly braces, which will assure that at first is called content of $var
, and subsequently the rest of message-sent:
$give_me_foo = $obj->{$var}[0];
The result is "bar"
, as you would expect.
Installing bzip2
and zip
PHP extensions solved my issue in Ubuntu:
sudo apt-get install php7.0-bz2
sudo apt-get install php7.0-zip
Use php(you version)-(extension)
to install and enable any missing modules that is required in the phpmyadmin readme.
The '\r' stands for "Carriage Return" - it's a holdover from the days of typewriters and really old printers. The best example is in Windows and other DOSsy OSes, where a newline is given as "\r\n". These are the instructions sent to an old printer to start a new line: first move the print head back to the beginning, then go down one.
Different OSes will use other newline sequences. Linux and OSX just use '\n'. Older Mac OSes just use '\r'. Wikipedia has a more complete list, but those are the important ones.
Hope this helps!
PS: As for why you get that weird output... Perhaps the console is moving the "cursor" back to the beginning of the line, and then overwriting the first bit with spaces or summat.
If you want to get the value of an integer for 2 raised to the power of something it is always better to use the shift option:
pow(2,5)
can be replaced by 1<<5
This is much more efficient.
select CASE
when exists (SELECT U.USERID,U.USERNAME,U.PASSWORDHASH
FROM TBLUSERS U WHERE U.USERID =U.USERID
AND U.PASSWORDHASH=U.PASSWORDHASH)
then 'OLD PASSWORD EXISTS'
else 'OLD PASSWORD NOT EXISTS'
end as OUTPUT
from DUAL;
After some searching and trawling through some old stackoverflow questions I've found a solution in a previously asked SO question:
Here's the code that I ended up using.
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
public X509Certificate[] getAcceptedIssuers(){return null;}
public void checkClientTrusted(X509Certificate[] certs, String authType){}
public void checkServerTrusted(X509Certificate[] certs, String authType){}
}};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
;
}
Google Apps Script is javascript, you can use all the string methods...
var grade = itemResponse.getResponse();
if(grade.indexOf("9th")>-1){do something }
You can find doc on many sites, this one for example.
Neither of the suggestions here were helpful for me. So I had to debug primefaces and found the reason of the problem was:
java.lang.IllegalStateException: No multipart config for servlet fileUpload
Then I have added section into my faces servlet in the web.xml. So that has fixed the problem:
<servlet>
<servlet-name>main</servlet-name>
<servlet-class>org.apache.myfaces.webapp.MyFacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<multipart-config>
<location>/tmp</location>
<max-file-size>20848820</max-file-size>
<max-request-size>418018841</max-request-size>
<file-size-threshold>1048576</file-size-threshold>
</multipart-config>
</servlet>
You can use UNION ALL instead.
SELECT mt.ID, mt.ParentID, ot.MasterID
FROM dbo.MainTable AS mt
Union ALL
SELECT mt.ID, mt.ParentID, ot.MasterID
FROM dbo.OtherTable AS ot
I was having the same issue and i resolved with below steps:-
Go to emulator setting and then go to
setting->Proxy->Either configure it Manually or use Tick use Android Studio HTTP proxy simulator.
Use listboxControl.Column(intColumn,intRow)
. Both Column and Row are zero-based.
Using HttpClient (Http's replacement) in Angular 4.3+, the entire mapping/casting process is made simpler/eliminated.
Using your CountryData class, you would define a service method like this:
getCountries() {
return this.httpClient.get<CountryData[]>('http://theUrl.com/all');
}
Then when you need it, define an array like this:
countries:CountryData[] = [];
and subscribe to it like this:
this.countryService.getCountries().subscribe(countries => this.countries = countries);
A complete setup answer is posted here also.
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("myDynamicElement")));
This waits up to 10 seconds before throwing a TimeoutException or if it finds the element will return it in 0 - 10 seconds. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully. A successful return is for ExpectedCondition type is Boolean return true or not null return value for all other ExpectedCondition types.
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
Element is Clickable - it is Displayed and Enabled.
You can use Pandas library to read the first few lines from the huge dataset.
import pandas as pd
data = pd.read_csv("names.csv", nrows=1)
You can mention the number of lines to be read in the nrows parameter.
IN your view insert
@Html.ValidationMessage("Error")
then in the controller after you use new in your model
var model = new yourmodel();
try{
[...]
}catch(Exception ex){
ModelState.AddModelError("Error", ex.Message);
return View(model);
}
The following answer was written by Eric Leschinki in 2014/15 at https://stackoverflow.com/a/26743484/1709587 (now deleted):
Mini walkthrough on how to detect locked tables:
This may prevent the database from enforcing atomicity in the affected tables and rows. The locks were designed to make sure things stay consistent and this procedure will prevent that process from taking place as designed.
Create your table, insert some rows
create table penguins(spam int, ham int); insert into penguins(spam, ham) values (3, 4);
show open tables:
show open tables like "penguins"
prints:
your_database penguins 0 0
Penguins isn't locked, lets lock it:
LOCK TABLES penguins READ;
Check if it's locked:
show open tables like "penguins"
Prints:
your_database, penguins 1, 0
Aha! It is locked! Lets unlock it:
unlock tables
Now it is unlocked:
show open tables like "penguins"
Prints:
your_database penguins 0 0
show all current locks
show open tables where in_use <> 0
It would be much more helpful if the MySQL developers put this information in a regular table (so I can do a
select my_items from my_table where my_clauses
), rather than this stripped down 'show table' syntax from system variables.
One simple option is to just type form.instance.fieldName
in the template instead of form.fieldName
.
The functionality is already present in atom via the Symbols View package you don't need to install anything.
The command you are searching for is symbols-view:go-to-declaration (Jump to the symbol under the cursor) which is bound by default to cmd-alt-down on macOS and ctrl-alt-down on Linux.
just note that it will work only if you will have generated tags for your project, either via this package or via ctags (exuberant or not)
Update: check for existence using TryGetValue
to do only one lookup in the case where you have the list:
List<int> list;
if (!dictionary.TryGetValue("foo", out list))
{
list = new List<int>();
dictionary.Add("foo", list);
}
list.Add(2);
var dictionary = new Dictionary<string, List<int>>();
if (!dictionary.ContainsKey("foo"))
dictionary.Add("foo", new List<int>());
dictionary["foo"].Add(42);
dictionary["foo"].AddRange(oneHundredInts);
Or List<string>
as in your case.
As an aside, if you know how many items you are going to add to a dynamic collection such as List<T>
, favour the constructor that takes the initial list capacity: new List<int>(100);
.
This will grab the memory required to satisfy the specified capacity upfront, instead of grabbing small chunks every time it starts to fill up. You can do the same with dictionaries if you know you have 100 keys.
You could also use zip
import matplotlib.pyplot as plt
l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
(2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
(4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
x, y = zip(*l)
plt.plot(x, y)
What worked for me is:
java
path is available:$ which java
/usr/bin/java
netbeans_jdkhome
is commented outYou would expect ./netbeans --jdkhome=/usr/bin/java
to work, but it doesn't for some reason.
?you should do these steps :
??simply here is the summery of those 5 steps:
.mother_Element {
position : relative;
height : 20%;
width : 5%;
text-align : center
}
.child_Element {
height : 1.2 em;
width : 5%;
margin : auto;
position : absolute;
top:0;
bottom:0;
left:0;
right:0;
}
In your case, you can use root
directive, because $uri
part of the location
directive is the same with last root
directive part.
Nginx documentation advices it as well:
When location matches the last part of the directive’s value:location /images/ { alias /data/w3/images/; }
it is better to use the root directive instead:
location /images/ { root /data/w3; }
and root
directive will append $uri
to the path.
Current for 2016 link is https://msdn.microsoft.com/en-us/library/mt204009.aspx
SQL Server Data Tools in Visual Studio 2015 is a modern development tool that you can download for free to build SQL Server relational databases, Azure SQL databases, Integration Services packages, Analysis Services data models, and Reporting Services reports. With SSDT, you can design and deploy any SQL Server content type with the same ease as you would develop an application in Visual Studio. This release supports SQL Server 2016 through SQL Server 2005, and provides the design environment for adding features that are new in SQL Server 2016.
Note that you don't need to have Visual Studio pre-installed. SSDT will install required components of VS, if it is not installed on your machine.
This release supports SQL Server 2016 through SQL Server 2005, and provides the design environment for adding features that are new in SQL Server 2016
Previously included in SQL Server standalone Business Intelligence Studio is not available any more and in last years replaced by SQL Server Data Tools (SSDT) for Visual Studio. See answer http://sqlmag.com/sql-server-2014/q-where-business-intelligence-development-studio-bids-sql-server-2014
To remove it from all inputs
input {
outline:none;
}
The regex validation for india should make sure that +91 is used, then make sure that 7, 8,9 is used after +91 and finally followed by 9 digits.
/^+91(7\d|8\d|9\d)\d{9}$/
Get the more information from below link
w3schools.com/jsref/jsref_obj_regexp.asp
Install GCC in Ubuntu Debian Base
sudo apt-get install build-essential
Yes you can which is Peer-To-Peer Mode
Peer-To-Peer Mode
Bidirectional P2P connection to exchange data between devices
–Proximity triggered interactions
–Nexus S: Devices have to be placed back-to-back
Example of Applications
–Exchange of vCards
–Hand-over of Tickets & P2P Payment
–Web-page sharing, Youtube-video-sharing
–Application sharing
pthread_exit()
will terminate the calling thread and exit from that(but resources used by calling thread is not released to operating system if it is not detached from main thread.)
pthrade_join()
will wait or block the calling thread until target thread is not terminated.
In simple word it will wait for to exit the target thread.
In your code, if you put sleep(or delay) in PrintHello
function before pthread_exit()
, then main thread may be exit and terminate full process, Although your PrintHello
function is not completed it will terminate. If you use pthrade_join()
function in main before calling pthread_exit()
from main it will block main thread and wait to complete your calling thread (PrintHello
).
dataGridView1.DataSource=null;
This is the simplest method you can do and reduce your efforts. just paste this function in your class and call it anywhere:
you can do this by creating a substring.
simple exampe is here:
public static String removeTillWord(String input, String word) {
return input.substring(input.indexOf(word));
}
removeTillWord("Your String", "\");
_x000D_
The lock screen works without keyguard i have tested it. The home button stops working and you can't get to task manager by holding the home key. I wish they didn't develop a new process when it used to be built into system ui or whatever. I don't see the need for the change and extra process
You're trying to pass file objects as filenames. Try using
infile = '110331_HS1A_1_rtTA.result'
outfile = '2.txt'
at the top of your code.
(Not only does the doubled usage of open()
cause that problem with trying to open the file again, it also means that infile
and outfile
are never closed during the course of execution, though they'll probably get closed once the program ends.)
if you just want any letters:
'a'*10 # gives 'aaaaaaaaaa'
if you want consecutive letters (up to 26):
''.join(['%c' % x for x in range(97, 97+10)]) # gives 'abcdefghij'
Have you tried the Arrays.fill function?
If you need old XLS format. Below code for ansii 'cp1251'.
import xlrd
file=u'C:/Landau/task/6200.xlsx'
try:
book = xlrd.open_workbook(file,encoding_override="cp1251")
except:
book = xlrd.open_workbook(file)
print("The number of worksheets is {0}".format(book.nsheets))
print("Worksheet name(s): {0}".format(book.sheet_names()))
sh = book.sheet_by_index(0)
print("{0} {1} {2}".format(sh.name, sh.nrows, sh.ncols))
print("Cell D30 is {0}".format(sh.cell_value(rowx=29, colx=3)))
for rx in range(sh.nrows):
print(sh.row(rx))
Expanding on patszim's answer for those in a rush.
add the following code:
Function RegxFunc(strInput As String, regexPattern As String) As String
Dim regEx As New RegExp
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.pattern = regexPattern
End With
If regEx.Test(strInput) Then
Set matches = regEx.Execute(strInput)
RegxFunc = matches(0).Value
Else
RegxFunc = "not matched"
End If
End Function
The regex pattern is placed in one of the cells and absolute referencing is used on it.
Function will be tied to workbook that its created in.
If there's a need for it to be used in different workbooks, store the function in Personal.XLSB
In C
#include <stdlib.h>
system("./foo 1 2 3");
In C++
#include <cstdlib>
std::system("./foo 1 2 3");
Then open and read the file as usual.
I used brute force and removed the remote and then added it
git remote rm <remote>
git remote add <url or ssh>
i think this can be as simple
let as assume that you are going to pass multiple parameters to you action as you read up there actions accept only two parameters context
and payload
which is your data you want to pass in action so let take an example
Setting up Action
instead of
actions: {
authenticate: ({ commit }, token, expiration) => commit('authenticate', token, expiration)
}
do
actions: {
authenticate: ({ commit }, {token, expiration}) => commit('authenticate', token, expiration)
}
Calling (dispatching) Action
instead of
this.$store.dispatch({
type: 'authenticate',
token: response.body.access_token,
expiration: response.body.expires_in + Date.now()
})
do
this.$store.dispatch('authenticate',{
token: response.body.access_token,
expiration: response.body.expires_in + Date.now()
})
hope this gonna help
From this documentation
pandas provides a single function, merge, as the entry point for all standard database join operations between DataFrame objects:
merge(left, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=True, suffixes=('_x', '_y'), copy=True, indicator=False)
And :
DataFrame.join
is a convenient method for combining the columns of two potentially differently-indexed DataFrames into a single result DataFrame. Here is a very basic example: The data alignment here is on the indexes (row labels). This same behavior can be achieved using merge plus additional arguments instructing it to use the indexes:result = pd.merge(left, right, left_index=True, right_index=True, how='outer')
I had to modify Lars' answer a bit, as an orphaned \
ended up in the regex, to only compare the actual host (not paying attention to the protocol or port) and I wanted to support localhost
domain besides my production domain. Thus I changed the $allowed
parameter to be an array.
function getCORSHeaderOrigin($allowed, $input)
{
if ($allowed == '*') {
return '*';
}
if (!is_array($allowed)) {
$allowed = array($allowed);
}
foreach ($allowed as &$value) {
$value = preg_quote($value, '/');
if (($wildcardPos = strpos($value, '\*')) !== false) {
$value = str_replace('\*', '(.*)', $value);
}
}
$regexp = '/^(' . implode('|', $allowed) . ')$/';
$inputHost = parse_url($input, PHP_URL_HOST);
if ($inputHost === null || !preg_match($regexp, $inputHost, $matches)) {
return 'none';
}
return $input;
}
Usage as follows:
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: " . getCORSHeaderOrigin(array("*.myproduction.com", "localhost"), $_SERVER['HTTP_ORIGIN']));
}
My solution is:
sudo -E env "PATH=$PATH" n stable
Works fine for me.
Found it here: https://stackoverflow.com/a/29400598/861615
This happens because you have change default global packages directory
Below command worked on 16.4 Ubuntu
This issue comes when your .sh file is corrupt or not formatted as per unix protocols.
dos2unix converts the .sh file to Unix format!
sudo apt-get install dos2unix -y
dos2unix test.sh
sudo chmod u+x test.sh
sudo ./test.sh
Wanted to comment on the last answer, but without login it’s only possible to make an answer:
To get rid of the "read only error" just stop the device immediately after it’s ready. My script looks as follows:
#!/bin/bash
~/bin/AndroidSdk/tools/emulator @Nexus_6P_API_23 -no-boot-anim &
adb wait-for-device
adb shell stop
adb remount
adb push GmsCore.apk /system/priv-app
adb push GoogleServicesFramework.apk /system/priv-app
adb push GoogleLoginService.apk /system/priv-app
adb push Phonesky.apk /system/priv-app
adb shell start
You can use this function to query for any element on the page, regardless of if it is nested inside of an iframe (or many iframes):
function querySelectorAllInIframes(selector) {
let elements = [];
const recurse = (contentWindow = window) => {
const iframes = contentWindow.document.body.querySelectorAll('iframe');
iframes.forEach(iframe => recurse(iframe.contentWindow));
elements = elements.concat(contentWindow.document.body.querySelectorAll(selector));
}
recurse();
return elements;
};
querySelectorAllInIframes('#elementToBeFound');
Note: Keep in mind that each of the iframes on the page will need to be of the same-origin, or this function will throw an error.
SIGTERM is used to restart Apache (provided that it's setup in init to auto-restart): http://httpd.apache.org/docs/2.2/stopping.html
The entries you see in the logs are almost certainly there because your provider used SIGTERM for that purpose. If it's truly crashing, not even serving static content, then that sounds like some sort of a thread/connection exhaustion issue. Perhaps a DoS that holds connections open?
Should definitely be something for your provider to investigate.
You can also customize the card theme globally with ThemeData.cardTheme
:
MaterialApp(
title: 'savvy',
theme: ThemeData(
cardTheme: CardTheme(
shape: RoundedRectangleBorder(
borderRadius: const BorderRadius.all(
Radius.circular(8.0),
),
),
),
// ...
FOR /r %%X IN (*) DO (ECHO %%X & DEL %%X)
a=1
for i in *.jpg; do
mv -- "$i" "$a.jpg"
a=`expr $a + 1`
done
You can replace "quote" characters with an empty string, like this:
>>> a = '"sajdkasjdsak" "asdasdasds"'
>>> a
'"sajdkasjdsak" "asdasdasds"'
>>> a = a.replace('"', '')
>>> a
'sajdkasjdsak asdasdasds'
In your case, you can do the same for out
variable.
Make sure that Access less secure app is allowed.
MailMessage mail = new MailMessage();
mail.From = new MailAddress("[email protected]");
mail.Sender = new MailAddress("[email protected]");
mail.To.Add("external@emailaddress");
mail.IsBodyHtml = true;
mail.Subject = "Email Sent";
mail.Body = "Body content from";
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "xx");
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.EnableSsl = true;
smtp.Timeout = 30000;
try
{
smtp.Send(mail);
}
catch (SmtpException e)
{
textBox1.Text= e.Message;
}
not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
The native lib is expected in one of the following locations
/usr/java/packages/lib/amd64
/usr/lib64
/lib64
/lib
/usr/lib
and not in
tomcat/lib
The files in tomcat/lib
are all jar
file and are added by tomcat to the classpath
so that they are available to your application.
The native lib is needed by tomcat to perform better on the platform it is installed on and thus cannot be a jar
, for linux it could be a .so
file, for windows it could be a .dll
file.
Just download the native library for your platform and place it in the one of the locations tomcat is expecting it to be.
Note that you are not required to have this lib for development/test purposes. Tomcat runs just fine without it.
org.apache.catalina.startup.Catalina start INFO: Server startup in 2882 ms
EDIT
The output you are getting is very normal, it's just some logging outputs from tomcat, the line right above indicates that the server correctly started and is ready for operating.
If you are troubling with running your servlet then after the run on sever
command eclipse opens a browser window (embeded (default) or external, depends on your config). If nothing shows on the browser, then check the url bar of the browser to see whether your servlet was requested or not.
It should be something like that
http://localhost:8080/<your-context-name>/<your-servlet-name>
EDIT 2
Try to call your servlet using the following url
http://localhost:8080/com.filecounter/FileCounter
Also each web project has a web.xml, you can find it in your project under WebContent\WEB-INF
.
It is better to configure your servlets there using servlet-name
servlet-class
and url-mapping
. It could look like that:
<servlet>
<description></description>
<display-name>File counter - My first servlet</display-name>
<servlet-name>file_counter</servlet-name>
<servlet-class>com.filecounter.FileCounter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>file_counter</servlet-name>
<url-pattern>/FileFounter</url-pattern>
</servlet-mapping>
In eclipse dynamic web project the default context name is the same as your project name.
http://localhost:8080/<your-context-name>/FileCounter
will work too.
Actutally std::vector are meant to be used as C tab when needed. (C++ standard requests that for vector implementation , as far as I know - replacement for array in Wikipedia) For instance it is perfectly legal to do this folowing, according to me:
int main()
{
void foo(const char *);
sdt::vector<char> vec;
vec.push_back('h');
vec.push_back('e');
vec.push_back('l');
vec.push_back('l');
vec.push_back('o');
vec.push_back('/0');
foo(&vec[0]);
}
Of course, either foo must not copy the address passed as a parameter and store it somewhere, or you should ensure in your program to never push any new item in vec, or requesting to change its capacity. Or risk segmentation fault...
Therefore in your exemple it leads to
vector.insert(pos, &vec[first_index], &vec[last_index]);
I'm sure that the above answers work perfectly. However, I had the difficulty of adding the double quotes as my bash lines where closer to 100. So, the following way helped me. (In a nutshell, no double quotes around each line of the shell)
Also, when I had "bash '''#!/bin/bash" within steps, I got the following error java.lang.NoSuchMethodError: No such DSL method '**bash**' found among steps
pipeline {
agent none
stages {
stage ('Hello') {
agent any
steps {
echo 'Hello, '
sh '''#!/bin/bash
echo "Hello from bash"
echo "Who I'm $SHELL"
'''
}
}
}
}
The result of the above execution is
I once had the same problem, and then I searched and found this and it worked for me:
I had got some of the boxes unchecked, so I checked them again, then it worked. Just go to
Windows > Preferences > Java > Editor > Content Assist > Advanced
and check the boxes which you want .
> and <
is a character entity reference for the >
and <
character in HTML.
It is not possible to use the less than (<) or greater than (>) signs in your file, because the browser will mix them with tags.
for these difficulties you can use entity names(>
) and entity numbers(<
).
As far as I can think bout it, there's only two ways you can do it. How can you know the user has finished writing a word? Either on focus lost, or clicking on an "ok" button. There's no way on my mind you can know the user pressed the last character...
So call onFocusChange(View v, boolean hasFocus)
or add a button and a click listener to it.
DES AES
Developed 1977 2000
Key Length 56 bits 128, 192, or 256 bits
Cipher Type Symmetric Symmetric
Block Size 64 bits 128 bits
Security inadequate secure
Performance Fast Slow
When you use unnormalized input features, the loss function is likely to have very elongated valleys. When optimizing with gradient descent, this becomes an issue because the gradient will be steep with respect some of the parameters. That leads to large oscillations in the search space, as you are bouncing between steep slopes. To compensate, you have to stabilize optimization with small learning rates.
Consider features x1 and x2, where range from 0 to 1 and 0 to 1 million, respectively. It turns out the ratios for the corresponding parameters (say, w1 and w2) will also be large.
Normalizing tends to make the loss function more symmetrical/spherical. These are easier to optimize because the gradients tend to point towards the global minimum and you can take larger steps.
Using morelinq you can use DistinctBy
:
myList.DistinctBy(x => x.id);
Otherwise, you can use a group:
myList.GroupBy(x => x.id)
.Select(g => g.First());
The following document linked from the draft RFC mentioned by Jim in his answer further addresses the question and definitely worth a direct note here:
Test Cases for HTTP Content-Disposition header and RFC 2231/2047 Encoding
It depends on where you're displaying the text. On the console or a textbox for example, \n will suffice. On a RichTextBox I think you need both.
Surely it's a little extreme to say
...never use a for in loop to enumerate over an array. Never. Use good old for(var i = 0; i<arr.length; i++)
?
It is worth highlighting the section in the Douglas Crockford extract
...The second form should be used with objects...
If you require an associative array ( aka hashtable / dictionary ) where keys are named instead of numerically indexed, you will have to implement this as an object, e.g. var myAssocArray = {key1: "value1", key2: "value2"...};
.
In this case myAssocArray.length
will come up null (because this object doesn't have a 'length' property), and your i < myAssocArray.length
won't get you very far. In addition to providing greater convenience, I would expect associative arrays to offer performance advantages in many situations, as the array keys can be useful properties (i.e. an array member's ID property or name), meaning you don't have to iterate through a lengthy array repeatedly evaluating if statements to find the array entry you're after.
Anyway, thanks also for the explanation of the JSLint error messages, I will use the 'isOwnProperty' check now when interating through my myriad associative arrays!
If you are using a Ubuntu system, use the following to Store Password Permanently:
git config --global credential.helper store
number=input("number")
numls20={"1":"one","2":"two","3":"three","4":"four","5":"five","6":"six","7":"seven","8":"eight","9":"nine","10":"ten","11":"elevn","12":"twelve","13":"thirteen","14":"fourteen","15":"fifteen","16":"sixteen","17":"seventeen","18":"eighteen","19":"ninteen"}
numls100={"1":"ten","2":"twenty","3":"thrity","4":"fourty","5":"fifty","6":"sixty","7":"seventy","8":"eighty","9":"ninty"}
numls1000={"1":"hundred","2":"twohundred","3":"threehundred","4":"fourhundred","5":"fivehundred","6":"sixhundred","7":"sevenhundred","8":"eighthundred","9":"ninehundred"}
def num2str(number):
if (int(number)<20):
print(numls20[number])
elif(int(number)<100):
print(numls100[number[0]]+" "+numls20[number[1]])
elif(int(number)<1000):
if ((int(number))%100 == 0):
print(numls1000[number[0]])
else:
print(numls1000[number[0]]+" and "+numls100[number[1]]+" "+numls20[number[2]])
elif(int(number)<10000):
if ((int(number))%1000 == 0):
print(numls20[number[0]]+" thousand")
elif(int(number)%100 == 0):
print(numls20[number[0]]+" thousand "+numls1000[number[1]])
elif(int(number)%10 == 0):
print(numls20[number[0]]+" thousand "+numls1000[number[1]]+" and "+numls100[number[2]])
else:
print(numls20[number[0]]+" thousand "+numls1000[number[1]]+" and "+numls100[number[2]]+" "+numls20[number[3]])
num2str(number)
You can also use the tag, this works in divs and everything else:
<center><form></form></center>
This link will help you with the tag:
In a bootstrap environment none of the top answers helped, but applying the following removed all borders:
.noBorder {
border:none !important;
}
Applied as:
<td class="noBorder">
You could also disable user select on all elements:
* {
-webkit-touch-callout:none;
-webkit-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
}
And than enable it on the elements you do want the user to be able to select:
input, textarea /*.contenteditable?*/ {
-webkit-touch-callout:default;
-webkit-user-select:text;
-moz-user-select:text;
-ms-user-select:text;
user-select:text;
}
You can set the line size as per the width of the window and set wrap off using the following command.
set linesize 160;
set wrap off;
I have used 160 as per my preference you can set it to somewhere between 100 - 200
and setting wrap will not your data and it will display the data properly.
I was looking for a inline editing solution and I found a plunker that seemed promising, but it didn't work for me out of the box. After some tinkering with the code I got it working. Kudos to the person who made the initial effort to code this piece.
The example is available here http://plnkr.co/edit/EsW7mV?p=preview
Here goes the code:
app.controller('MainCtrl', function($scope) {
$scope.updateTodo = function(indx) {
console.log(indx);
};
$scope.cancelEdit = function(value) {
console.log('Canceled editing', value);
};
$scope.todos = [
{id:123, title: 'Lord of the things'},
{id:321, title: 'Hoovering heights'},
{id:231, title: 'Watership brown'}
];
});
// On esc event
app.directive('onEsc', function() {
return function(scope, elm, attr) {
elm.bind('keydown', function(e) {
if (e.keyCode === 27) {
scope.$apply(attr.onEsc);
}
});
};
});
// On enter event
app.directive('onEnter', function() {
return function(scope, elm, attr) {
elm.bind('keypress', function(e) {
if (e.keyCode === 13) {
scope.$apply(attr.onEnter);
}
});
};
});
// Inline edit directive
app.directive('inlineEdit', function($timeout) {
return {
scope: {
model: '=inlineEdit',
handleSave: '&onSave',
handleCancel: '&onCancel'
},
link: function(scope, elm, attr) {
var previousValue;
scope.edit = function() {
scope.editMode = true;
previousValue = scope.model;
$timeout(function() {
elm.find('input')[0].focus();
}, 0, false);
};
scope.save = function() {
scope.editMode = false;
scope.handleSave({value: scope.model});
};
scope.cancel = function() {
scope.editMode = false;
scope.model = previousValue;
scope.handleCancel({value: scope.model});
};
},
templateUrl: 'inline-edit.html'
};
});
Directive template:
<div>
<input type="text" on-enter="save()" on-esc="cancel()" ng-model="model" ng-show="editMode">
<button ng-click="cancel()" ng-show="editMode">cancel</button>
<button ng-click="save()" ng-show="editMode">save</button>
<span ng-mouseenter="showEdit = true" ng-mouseleave="showEdit = false">
<span ng-hide="editMode" ng-click="edit()">{{model}}</span>
<a ng-show="showEdit" ng-click="edit()">edit</a>
</span>
</div>
To use it just add water:
<div ng-repeat="todo in todos"
inline-edit="todo.title"
on-save="updateTodo($index)"
on-cancel="cancelEdit(todo.title)"></div>
UPDATE:
Another option is to use the readymade Xeditable for AngularJS:
Make sure you follow the language definition for JSON. In your second example, the section:
"labs":[{
""
}]
Is invalid since an object must be composed of zero or more key-value pairs "a" : "b"
, where "b"
may be any valid value. Some parsers may automatically interpret { "" }
to be { "" : null }
, but this is not a clearly defined case.
Also, you are using a nested array of objects [{}]
quite a bit. I would only do this if:
For Windows user, please note to use "
instead of '
Also added -f
to force the command if another backup is already there.
git filter-branch -f --tree-filter "rm -rf FOLDERNAME" --prune-empty HEAD
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
echo FOLDERNAME/ >> .gitignore
git add .gitignore
git commit -m "Removing FOLDERNAME from git history"
git gc
git push origin master --force
if you want the color to change when you have simply add the :hover
pseudo
div.e:hover {
background-color:red;
}
If you find any security issue then follow steps as well
Thats DONE!
DECLARE @q nvarchar(4000)
SET @q = 'DECLARE @tmp TABLE (code VARCHAR(50), mount MONEY)
INSERT INTO @tmp
(
code,
mount
)
SELECT coa_code,
amount
FROM T_Ledger_detail
SELECT *
FROM @tmp'
EXEC sp_executesql @q
If you want in dynamic query
The function returns too early. I've added a comment to the code below:
$(document).ready(function(){
$(document).bind("contextmenu",function(e){
return false;
$('.alert').fadeToggle(); // this line never gets called
});
});
Try swapping the return false;
with the next line.
Assuming your page is available under "http://example.com"
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://example.com")
Select element by id:
inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')
Now you can simulate hitting ENTER:
inputElement.send_keys(Keys.ENTER)
or if it is a form you can submit:
inputElement.submit()
For users of IntelliJ IDEA or Android Studio make these steps:
* From the menu Build/Generate signed APK
* You need to create a keystore path. From the dialog click Create new
. You will create a jks file that includes your keys. Select folder, define a password. So your keystore ok.
* Create new key by for your application by using alias, key password, your name etc.
* Click next.
* From the dialog either select Proguard or not.
Your signed APK file is ready.
Help file: https://www.jetbrains.com/idea/webhelp/generate-signed-apk-wizard.html
You can use customValidity
$(function(){ var elements = document.getElementsByTagName("input"); for (var i = 0; i < elements.length; i++) { elements[i].oninvalid = function(e) { e.target.setCustomValidity("This can't be left blank!"); }; } });
I think that will work on at least Chrome and FF, I'm not sure about other browsers
> S = matrix(c(1,2,3,4,5,2,1,2,3,4,3,2,1,2,3,4,3,2,1,2,5,4,3,2,1),ncol = 5,byrow = TRUE);S
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 2 1 2 3 4
[3,] 3 2 1 2 3
[4,] 4 3 2 1 2
[5,] 5 4 3 2 1
> S<-S[,-2]
> S
[,1] [,2] [,3] [,4]
[1,] 1 3 4 5
[2,] 2 2 3 4
[3,] 3 1 2 3
[4,] 4 2 1 2
[5,] 5 3 2 1
Just use the command S <- S[,-2]
to remove the second column. Similarly to delete a row, for example, to delete the second row use S <- S[-2,]
.
Indeed, it would be nice if
git-add
had a--mode
flag
git 2.9.x/2.10 (Q3 2016) actually will allow that (thanks to Edward Thomson):
git add --chmod=+x -- afile
git commit -m"Executable!"
That makes the all process quicker, and works even if core.filemode
is set to false.
See commit 4e55ed3 (31 May 2016) by Edward Thomson (ethomson
).
Helped-by: Johannes Schindelin (dscho
).
(Merged by Junio C Hamano -- gitster
-- in commit c8b080a, 06 Jul 2016)
add
: add--chmod=+x
/--chmod=-x
optionsThe executable bit will not be detected (and therefore will not be set) for paths in a repository with
core.filemode
set to false, though the users may still wish to add files as executable for compatibility with other users who do havecore.filemode
functionality.
For example, Windows users adding shell scripts may wish to add them as executable for compatibility with users on non-Windows.Although this can be done with a plumbing command (
git update-index --add --chmod=+x foo
), teaching thegit-add
command allows users to set a file executable with a command that they're already familiar with.
You can easily simulate a click on an element, but a click on a <select>
won’t open up the dropdown.
Using multiple selects can be problematic. Perhaps you should consider radio buttons inside a container element which you can expand and contract as needed.
Not valid HTML, anyway pretty much every browser seems to consider just the second instance.
Tested under the last versions of FF and Google Chrome under Fedora, and FF, Opera, IE, and Chrome under XP.
The LINQy way
String.Concat( "223232-1.jpg".TakeWhile(c => c != '-') )
(But, you do need to test for null ;)
First, you want a running list of subsequences:
subseqs = (seq[:i] for i in range(1, len(seq)+1))
Then you just call sum
on each subsequence:
sums = [sum(subseq) for subseq in subseqs]
(This isn't the most efficient way to do it, because you're adding all of the prefixes repeatedly. But that probably won't matter for most use cases, and it's easier to understand if you don't have to think of the running totals.)
If you're using Python 3.2 or newer, you can use itertools.accumulate
to do it for you:
sums = itertools.accumulate(seq)
And if you're using 3.1 or earlier, you can just copy the "equivalent to" source straight out of the docs (except for changing next(it)
to it.next()
for 2.5 and earlier).
You don't say which version of Excel you are using. This is written for 2007/2010 (a different apprach is required for Excel 2003 )
You also don't say how you are calling addDataToTable
and what you are passing into arrData
.
I'm guessing you are passing a 0
based array. If this is the case (and the Table starts in Column A
) then iCount
will count from 0
and .Cells(lLastRow + 1, iCount)
will try to reference column 0
which is invalid.
You are also not taking advantage of the ListObject
. Your code assumes the ListObject
1 is located starting at row 1
. If this is not the case your code will place the data in the wrong row.
Here's an alternative that utilised the ListObject
Sub MyAdd(ByVal strTableName As String, ByRef arrData As Variant)
Dim Tbl As ListObject
Dim NewRow As ListRow
' Based on OP
' Set Tbl = Worksheets(4).ListObjects(strTableName)
' Or better, get list on any sheet in workbook
Set Tbl = Range(strTableName).ListObject
Set NewRow = Tbl.ListRows.Add(AlwaysInsert:=True)
' Handle Arrays and Ranges
If TypeName(arrData) = "Range" Then
NewRow.Range = arrData.Value
Else
NewRow.Range = arrData
End If
End Sub
Can be called in a variety of ways:
Sub zx()
' Pass a variant array copied from a range
MyAdd "MyTable", [G1:J1].Value
' Pass a range
MyAdd "MyTable", [G1:J1]
' Pass an array
MyAdd "MyTable", Array(1, 2, 3, 4)
End Sub
With pure Javascript, you'd have to cycle through each option, and check the value of it individually.
// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
(op[i].value.toLowerCase() == "stackoverflow")
? op[i].disabled = true
: op[i].disabled = false ;
}
Without enabling non-targeted elements:
// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
if (op[i].value.toLowerCase() == "stackoverflow") {
op[i].disabled = true;
}
}
With jQuery you can do this with a single line:
$("option[value='stackoverflow']")
.attr("disabled", "disabled")
.siblings().removeAttr("disabled");
Without enabling non-targeted elements:
$("option[value='stackoverflow']").attr("disabled", "disabled");
? Note that this is not case insensitive. "StackOverflow" will not equal "stackoverflow". To get a case-insensitive match, you'd have to cycle through each, converting the value to a lower case, and then check against that:
$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled").siblings().removeAttr("disabled");
}
});
Without enabling non-targeted elements:
$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled");
}
});
The one that worked for me is:
grep -e '->'
The -e means that the next argument is the pattern, and won't be interpreted as an argument.
From: http://www.linuxquestions.org/questions/programming-9/how-to-grep-for-string-769460/
Try the Magnific Popup, it's responsive and weights just around 3KB.
You can try like below
public List<Object> dataList;
public bool AddData(ref Object data)
bool success = false;
try
{
if (data != null)
{
dataList.Add(data);
success = doOtherStuff(data);
}
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
return success;
}
Creating a property with only a getter makes your property read-only for any code that is outside the class.
You can however change the value using methods provided by your class :
public class FuelConsumption {
private double fuel;
public double Fuel
{
get { return this.fuel; }
}
public void FillFuelTank(double amount)
{
this.fuel += amount;
}
}
public static void Main()
{
FuelConsumption f = new FuelConsumption();
double a;
a = f.Fuel; // Will work
f.Fuel = a; // Does not compile
f.FillFuelTank(10); // Value is changed from the method's code
}
Setting the private field of your class as readonly
allows you to set the field value only once (using an inline assignment or in the class constructor).
You will not be able to change it later.
public class ReadOnlyFields {
private readonly double a = 2.0;
private readonly double b;
public ReadOnlyFields()
{
this.b = 4.0;
}
}
readonly
class fields are often used for variables that are initialized during class construction, and will never be changed later on.
In short, if you need to ensure your property value will never be changed from the outside, but you need to be able to change it from inside your class code, use a "Get-only" property.
If you need to store a value which will never change once its initial value has been set, use a readonly
field.
The canvas
element provides a toDataURL
method which returns a data:
URL that includes the base64-encoded image data in a given format. For example:
var jpegUrl = canvas.toDataURL("image/jpeg");
var pngUrl = canvas.toDataURL(); // PNG is the default
Although the return value is not just the base64 encoded binary data, it's a simple matter to trim off the scheme and the file type to get just the data you want.
The toDataURL
method will fail if the browser thinks you've drawn to the canvas any data that was loaded from a different origin, so this approach will only work if your image files are loaded from the same server as the HTML page whose script is performing this operation.
For more information see the MDN docs on the canvas
API, which includes details on toDataURL
, and the Wikipedia article on the data:
URI scheme, which includes details on the format of the URI you'll receive from this call.
You could also use find_by_sql
# A simple SQL query spanning multiple tables
Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
> [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
To answer your question this is all you need see full responsive demo with prefixed css:
/* Using col-xs media query breakpoint but you can change 481 to 768 to only apply to col-sm and above if you'd like*/
@media only screen and (min-width : 481px) {
.flex-row {
display: flex;
flex-wrap: wrap;
}
.flex-row > [class*='col-'] {
display: flex;
flex-direction: column;
}
.flex-row.row:after,
.flex-row.row:before {
display: flex;
}
}
To add support for thumbnail content flex within flex columns like the screenshot above also add this... Note you could do this with panels as well:
.flex-row .thumbnail,
.flex-row .caption {
display: flex;
flex: 1 0 auto;
flex-direction: column;
}
.flex-text {
flex-grow: 1;
}
.flex-row img {
width: 100%;
}
While flexbox doesn't work in IE9 and below you can use the demo with a fallback using conditional tags with something like javascript grids as a polyfill:
<!--[if lte IE 9]>
<![endif]-->
As for the other two examples in the accepted answer... The table demo is a decent idea but is being implemented wrong. Applying that CSS on bootstrap column classes specifically will without a doubt break the grid framework entirely. You should be using a custom selector for one and two the tables styles should not be applied to [class*='col-']
that have defined widths. This method should ONLY be used if you want equal height AND equal width columns. It is not meant for any other layouts and is NOT responsive. We can make it fallback however on mobile displays...
<div class="table-row-equal">
<div class="thumbnail">
Content...
</div>
<div class="thumbnail">
Content...
</div>
</div>
@media only screen and (min-width : 480px){
.table-row-equal {
display: table;
width: 100%;
table-layout: fixed;
border-spacing: 30px 0px;
word-wrap: break-word;
}
.table-row-equal .thumbnail {
float: none;
display: table-cell;
vertical-align: top;
width: 1%;
}
}
Lastly, the first demo in the accepted answer which implements a version of the one true layout is a good choice for some situations, but not suitable for bootstrap columns. The reason for this is that all the columns expand to the container height. So this will also break responsiveness since the columns are not expanding to the elements next to them, but the entire container. This method will also not allow you to apply bottom margins to rows any longer and will also cause other issues along the way like scrolling to anchor tags.
For the complete code see the Codepen which automatically prefixes the flexbox code.
Instead of Googling for %02d
you should have been searching for sprintf()
function.
%02d
means "format the integer with 2 digits, left padding it with zeroes", so:
Format Data Result %02d 1 01 %02d 11 11
private String[] getStringArray(JSONArray jsonArray) throws JSONException {_x000D_
if (jsonArray != null) {_x000D_
String[] stringsArray = new String[jsonArray.length()];_x000D_
for (int i = 0; i < jsonArray.length(); i++) {_x000D_
stringsArray[i] = jsonArray.getString(i);_x000D_
}_x000D_
return stringsArray;_x000D_
} else_x000D_
return null;_x000D_
}
_x000D_
If matching a sequence of characters is not sufficient and you need to match whole words, here is a simple function that gets the job done. It basically appends spaces where necessary and searches for that in the string:
def smart_find(haystack, needle):
if haystack.startswith(needle+" "):
return True
if haystack.endswith(" "+needle):
return True
if haystack.find(" "+needle+" ") != -1:
return True
return False
This assumes that commas and other punctuations have already been stripped out.
I would consider writing a CLR replace function with RegEx support for this kind of string manipulation.
With Kotlin, works with Gmail :
val i = Intent(Intent.ACTION_SENDTO).apply {
type = "text/html"
data = Uri.parse("mailto:")
putExtra(Intent.EXTRA_EMAIL, arrayOf(email))
putExtra(Intent.EXTRA_SUBJECT, subject)
putExtra(Intent.EXTRA_TITLE, subject)
}
if (packageManager != null && i.resolveActivity(packageManager) != null) {
startActivity(i)
}
If anyone find a solution to display the message too...
There is the concatenate function. For example
=CONCATENATE(E2,"-",F2)But the & operator always concatenates strings. + often will work, but if there is a number in one of the cells, it won't work as expected.
If you are using any user control and want to get any text box values then you can use the below code:
var result = document.getElementById('LE_OtherCostsDetails_txtHomeOwnerInsurance').value;
Here, LE_OtherCostsDetails
, is the name of the user control and txtHomeOwnerInsurance
is the id of the text box.
The (un)safe way to do this - if you are ok with not using option explicit - is...
Not TypeName(myObj) = "Empty"
This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...
Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ true, the object exists - TypeName is Object
'Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ false, the object has not been declared
This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.
Having hit this one a few times and followed a bunch of suggestions, if you don't find it available after installing the NuGet Microsoft.AspNet.WebApi.Client manually add a reference from the packages folder in the solution to:
\Microsoft.AspNet.WebApi.Client.5.2.6\lib\net45\System.Net.Http.Formatting.dll
And don't get into the trap of adding older references to the System.Net.Http.Formatting.dll NuGet
grep was born to extract things:
grep -Po 'name="\K[^"]*'
test with your data:
kent$ echo '<parameter name="PortMappingEnabled" access="readWrite" type="xsd:boolean"></parameter>
<parameter name="PortMappingLeaseDuration" access="readWrite" activeNotify="canDeny" type="xsd:unsignedInt"></parameter>
<parameter name="RemoteHost" access="readWrite"></parameter>
<parameter name="ExternalPort" access="readWrite" type="xsd:unsignedInt"></parameter>
<parameter name="ExternalPortEndRange" access="readWrite" type="xsd:unsignedInt"></parameter>
<parameter name="InternalPort" access="readWrite" type="xsd:unsignedInt"></parameter>
<parameter name="PortMappingProtocol" access="readWrite"></parameter>
<parameter name="InternalClient" access="readWrite"></parameter>
<parameter name="PortMappingDescription" access="readWrite"></parameter>
'|grep -Po 'name="\K[^"]*'
PortMappingEnabled
PortMappingLeaseDuration
RemoteHost
ExternalPort
ExternalPortEndRange
InternalPort
PortMappingProtocol
InternalClient
PortMappingDescription
Go to google-services.json file and in client part check the package name and compare it with App package name if they are different then change the client package name according to your app package name it worked for me best of luck..
google-services.json file-> "package_name": "com.example.application.tracker"
App package name->package "com.example.application.tracker";
Here are a couple dplyr
options:
library(dplyr)
# all columns:
df %>%
mutate_all(~na_if(., ''))
# specific column types:
df %>%
mutate_if(is.factor, ~na_if(., ''))
# specific columns:
df %>%
mutate_at(vars(A, B), ~na_if(., ''))
# or:
df %>%
mutate(A = replace(A, A == '', NA))
# replace can be used if you want something other than NA:
df %>%
mutate(A = as.character(A)) %>%
mutate(A = replace(A, A == '', 'used to be empty'))
I tested Github Flavored Markdown for a while and can summarize with four rules:
-
For example, if your section is named this:
## 1.1 Hello World
Create a link to it this way:
[Link](#11-hello-world)
"N/A" is not a string it is an error, try this:
=if(ISNA(A1),C1)
you have to place this fomula in cell B1 so it will get the value of your formula
Alternatively, you may also use the composite operator F then indicating how many decimal spots you wish to appear after the decimal.
string.Format("{0:F2}", 123.456789); //123.46
string.Format("{0:F3}", 123.456789); //123.457
string.Format("{0:F4}", 123.456789); //123.4568
It will round up so be aware of that.
I sourced the general documentation. There are a ton of other formatting operators there as well that you may check out.
Source: https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx
Beware. I did this on a development server and wanted to change it later.
I had to clear my caches to change it. In order to avoid this head-scratching in the future, I was able to make it temporary like so:
from django.views.generic import RedirectView
url(r'^source$', RedirectView.as_view(permanent=False,
url='/dest/')),
open a terminal and run this command xhost +
. This commands needs to be run every time you restart your machine. If everything works fine may be you can add this to startup commands
Also make sure in your /etc/environment file there is a line
export DISPLAY=:0.0
And then, run your tests to see if your issue is resolved.
All please note the comment from sardathrion below before using this.
I played with this two weeks ago, it's very simple. The only problem is that all the tutorials just talk about saving the image locally. This is how I did it:
1) I set up a form so I can use a POST method.
2) When the user is done drawing, he can click the "Save" button.
3) When the button is clicked I take the image data and put it into a hidden field. After that I submit the form.
document.getElementById('my_hidden').value = canvas.toDataURL('image/png');
document.forms["form1"].submit();
4) When the form is submited I have this small php script:
<?php
$upload_dir = somehow_get_upload_dir(); //implement this function yourself
$img = $_POST['my_hidden'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir."image_name.png";
$success = file_put_contents($file, $data);
header('Location: '.$_POST['return_url']);
?>
You need to set the thumbnail class to position relative then the post-content to absolute.
Check this fiddle
.post-content {
top:0;
left:0;
position: absolute;
}
.thumbnail{
position:relative;
}
Giving it top and left 0 will make it appear in the top left corner.
CTRL+SHIFT+ENTER, ARRAY FORMULA EXCEL 2016 MAC. So I arrive late into the game, but maybe someone else will. This almost drove me nuts. No matter what I searched for in Google I came up empty. Whatever I tried, no solution seemed to be in sight. Switched to Excel 2016 quite some time ago and today I needed to do some array formulas. Also sitting on a MacBook Pro 15 Touch Bar 2016. Not that it really matters, but still, since the solution was published on Youtube in 2013. The reason why, for me anyway, nothing worked, is in the Mac OS, the control key by default, for me anyway, is set to manage Mission control, which, at least for me, disabled the control button in Excel. In order to enable the key to actually control functions in Excel, you need to go to System preferences > Mission Control, and disable shortcuts for Mission control. So, let's see how long this solution will last. Probably be back to square one after the coffee break. Have a good one!
Updated for iOS 8.0
Since iOS 8.0, you will need to use UIAlertController as the following:
-(void)alertMessage:(NSString*)message
{
UIAlertController* alert = [UIAlertController
alertControllerWithTitle:@"Alert"
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction
actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
}
Where self in my example is a UIViewController, which implements "presentViewController" method for a popup.
David
Add padding and elevation:
android:elevation="10dp"
android:padding="10dp"
The proper way to do this is like so:
@ECHO off
SET MY_PATH=M:\Dir\^
With Spaces\Sub Folder^
\Dir\Folder
:: calls M:\Dir\With Spaces\Sub Folder\Dir\Folder\hello.bat
CALL "%MY_PATH%\hello.bat"
pause
You can also load the body of the script and execute it within the same process:
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile("script2.vbs")
body = ts.ReadAll
ts.Close
Execute body
If you can live with a fixed aspect ratio and you would like a responsive iframe, this code will be useful to you. It's just CSS rules.
.iframe-container {
overflow: hidden;
/* Calculated from the aspect ration of the content (in case of 16:9 it is 9/16=
0.5625) */
padding-top: 56.25%;
position: relative;
}
.iframe-container iframe {
border: 0;
height: 100%;
left: 0;
position: absolute;
top: 0;
width: 100%;
}
The iframe must have a div as container.
<div class="iframe-container">
<iframe src="http://example.org"></iframe>
</div>
The source code is based on this site and Ben Marshall has a good explanation.
All of this can easily be acheived in the xaml by adding the following code in the grid
<Grid>
<Grid.Background>
<ImageBrush ImageSource="/MyProject;component/Images/bg.png"/>
</Grid.Background>
</Grid>
Left for you to do, is adding a folder to the solution called 'Images' and adding an existing file to your new 'Images' folder, in this case called 'bg.png'
Maybe you should have a look at Mapquests Traffic API: http://www.mapquestapi.com/traffic/
The webservice is unfortunately only available for some citys in the US, I think. But probably it solves your problem.
The same as in Eli's answer - just using a shorter form, because you can skip a lambda
part here.
Creating new list:
>>> xs = ['dddd','a','bb','ccc']
>>> sorted(xs, key=len)
['a', 'bb', 'ccc', 'dddd']
In-place sorting:
>>> xs.sort(key=len)
>>> xs
['a', 'bb', 'ccc', 'dddd']
Sure you can with reflection. Here is the code to grab the properties off of a given type.
var info = typeof(SomeType).GetProperties();
If you can give more info on what you're comparing about the properties we can get together a basic diffing algorithmn. This code for intstance will diff on names
public bool AreDifferent(Type t1, Type t2) {
var list1 = t1.GetProperties().OrderBy(x => x.Name).Select(x => x.Name);
var list2 = t2.GetProperties().OrderBy(x => x.Name).Select(x => x.Name);
return list1.SequenceEqual(list2);
}
from learnyounode:
var http = require('http')
var bl = require('bl')
http.get(process.argv[2], function (response) {
response.pipe(bl(function (err, data) {
if (err)
return console.error(err)
data = data.toString()
console.log(data)
}))
})
You can use *args and **kwargs syntax for variable length arguments.
What do *args and **kwargs mean?
And from the official python tutorial
http://docs.python.org/dev/tutorial/controlflow.html#more-on-defining-functions
I checked quite some links for the solution, finally did the below mentioned steps to get it working. I am using Gradle 2.9.
Make the following changes in your build,gradle file :
Mention plugin:
apply plugin: 'eu.appsatori.fatjar'
Provide the Buildscript:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "eu.appsatori:gradle-fatjar-plugin:0.3"
}
}
Provide the Main Class:
fatJar {
classifier 'fat'
manifest {
attributes 'Main-Class': 'my.project.core.MyMainClass'
}
exclude 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.SF'
}
Create the fatjar:
./gradlew clean fatjar
Run the fatjar from /build/libs/ :
java -jar MyFatJar.jar
In Nexus 5, Go to Settings -> Google -> Security and uncheck "Scan device for Security threats" and "Improve harmful app detection".
It is just a matter of changing the port user by mysql:3308 to 3306
Just right click on wamp-> select tools
under Port Used By mysql:3308 clcik on "use a port other than 3308
In the text port text box appear : type 3306 and save. Wait until the wampserver restarts and get green.
Now run your PHP code, It will work. That's it - Good Luck
If getting this error trying to build .Net Core 2.0 app on VSTS then ensure your build definition is using the Hosted VS2017
Agent queue.
In version v2.3.0
this work for me :
socket.handshake.headers['x-forwarded-for'].split(',')[0]
from the current directory provide the full path to the script directory to execute the command
/root/server/user/home/bin/script.sh
You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.
I had this problem and did not find any solution which I liked, so I created a python wrapper for mpg321: mpyg321.
You would need to have mpg321 installed on your computer, and then do pip install mpyg321
.
The usage is pretty simple:
from mpyg321.mpyg321 import MPyg321Player
from time import sleep
player = MPyg321Player() # instanciate the player
player.play_song("sample.mp3") # play a song
sleep(5)
player.pause() # pause playing
sleep(3)
player.resume() # resume playing
sleep(5)
player.stop() # stop playing
player.quit() # quit the player
You can also define callbacks for several events (music paused by user, end of song...).
replace "150x150" with 720x720 and remove /vp/ from the link.it should work.
I tried below code its worked for fine
var modWidth = 250;
var modHeight = 150;
example below :-
$( "#ContainerId .sDashboard li" ).width( modWidth ).height(modHeight);
For reference, a non-CSS solution:
Below is some JS that re-sizes a font depending on the text length within a container.
Codepen with slightly modified code, but same idea as below:
function scaleFontSize(element) {
var container = document.getElementById(element);
// Reset font-size to 100% to begin
container.style.fontSize = "100%";
// Check if the text is wider than its container,
// if so then reduce font-size
if (container.scrollWidth > container.clientWidth) {
container.style.fontSize = "70%";
}
}
For me, I call this function when a user makes a selection in a drop-down, and then a div in my menu gets populated (this is where I have dynamic text occurring).
scaleFontSize("my_container_div");
In addition, I also use CSS ellipses ("...") to truncate yet even longer text too, like so:
#my_container_div {
width: 200px; /* width required for text-overflow to work */
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
So, ultimately:
Short text: e.g. "APPLES"
Fully rendered, nice big letters.
Long text: e.g. "APPLES & ORANGES"
Gets scaled down 70%, via the above JS scaling function.
Super long text: e.g. "APPLES & ORANGES & BANAN..."
Gets scaled down 70% AND gets truncated with a "..." ellipses, via the above JS scaling function together with the CSS rule.
You could also explore playing with CSS letter-spacing to make text narrower while keeping the same font size.
First edit the Nginx configuration file (nginx.conf
)
Location: sudo nano /etc/nginx/nginx.conf
Add following codes:
http {
client_max_body_size 100M;
}
Then Add the following lines in PHP configuration file(php.ini
)
Location: sudo gedit /etc/php5/fpm/php.ini
Add following codes:
memory_limit = 128M
post_max_size = 20M
upload_max_filesize = 10M
You should use Ctrl+shift+enter when using the =SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE)) that results in {=SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE))} en also works.
You can use a for-loop to address a field with $i:
ls -l | awk '{for(i=3 ; i<8 ; i++) {printf("%s\t", $i)} print ""}'
If you are caching information that you will ultimately want to "include" at a later point in time, you may want to try using var_export. That way you only take the hit in the "serialize" and not in the "unserialize".
You could do:
sub("*\\.[0-9]", "", a)
or
library(stringr)
str_sub(a, start=1, end=-3)
Example:
.parent-class .flex-control-thumbs li {
width: auto;
float: none;
}
Demo:
.sample-class {
height: 50px;
width: 50px;
background: red;
}
.inner-page .sample-class {
background: green;
}
_x000D_
<div>
<div class="sample-class"></div>
</div>
<div class="inner-page">
<div class="sample-class"></div>
</div>
_x000D_
The explanation that none of the other answers supplies is that the original arguments are still available, but not in the original position in the arguments
object.
The arguments
object contains one element for each actual parameter provided to the function. When you call a
you supply three arguments: the numbers 1
, 2
, and, 3
. So, arguments
contains [1, 2, 3]
.
function a(args){
console.log(arguments) // [1, 2, 3]
b(arguments);
}
When you call b
, however, you pass exactly one argument: a
's arguments
object. So arguments
contains [[1, 2, 3]]
(i.e. one element, which is a
's arguments
object, which has properties containing the original arguments to a
).
function b(args){
// arguments are lost?
console.log(arguments) // [[1, 2, 3]]
}
a(1,2,3);
As @Nick demonstrated, you can use apply
to provide a set arguments
object in the call.
The following achieves the same result:
function a(args){
b(arguments[0], arguments[1], arguments[2]); // three arguments
}
But apply
is the correct solution in the general case.
You should do like this:
@Html.DropDownListFor(m => m.ContribType,
new SelectList(Model.ContribTypeOptions,
"ContribId", "Value"))
Where:
m => m.ContribType
is a property where the result value will be.
The problem you face is that you try to assign the return of imshow
(which is an matplotlib.image.AxesImage
to an existing axes object.
The correct way of plotting image data to the different axes in axarr
would be
f, axarr = plt.subplots(2,2)
axarr[0,0].imshow(image_datas[0])
axarr[0,1].imshow(image_datas[1])
axarr[1,0].imshow(image_datas[2])
axarr[1,1].imshow(image_datas[3])
The concept is the same for all subplots, and in most cases the axes instance provide the same methods than the pyplot (plt) interface.
E.g. if ax
is one of your subplot axes, for plotting a normal line plot you'd use ax.plot(..)
instead of plt.plot()
. This can actually be found exactly in the source from the page you link to.
In my experience, to use wmic
in a script, you need to get the nested quoting right:
wmic product where "name = 'Windows Azure Authoring Tools - v2.3'" call uninstall /nointeractive
quoting both the query and the name. But wmic will only uninstall things installed via windows installer.
You must use the same Tokenizer you used to build your model!
Else this will give different vector to each word.
Then, I am using:
phrase = "not good"
tokens = myTokenizer.texts_to_matrix([phrase])
model.predict(np.array(tokens))
You have what you have used in stored procedures like this for reference, but they are not intended to be used as you have now. You can use IF
as shown by duskwuff
. But a Case
statement is better for eyes. Like this:
select id,
(
CASE
WHEN qty_1 <= '23' THEN price
WHEN '23' > qty_1 && qty_2 <= '23' THEN price_2
WHEN '23' > qty_2 && qty_3 <= '23' THEN price_3
WHEN '23' > qty_3 THEN price_4
ELSE 1
END) AS total
from product;
This looks cleaner. I suppose you do not require the inner SELECT
anyway..
try using the cloning technique.
{
DataGridViewRow row = (DataGridViewRow)yourdatagrid.Rows[0].Clone();
// then for each of the values use a loop like below.
int cc = yourdatagrid.Columns.Count;
for (int i2 = 0; i < cc; i2++)
{
row.Cells[i].Value = yourdatagrid.Rows[0].Cells[i].Value;
}
yourdatagrid.Rows.Add(row);
i++;
}
}
This should work. I'm not sure about how the binding works though. Hopefully it won't prevent this from working.
You can optimize/check and repair all the tables of database, using mysql client.
First, you should get all the tables list, separated with ',':
mysql -u[USERNAME] -p[PASSWORD] -Bse 'show tables' [DB_NAME]|xargs|perl -pe 's/ /,/g'
Now, when you have all the tables list for optimization:
mysql -u[USERNAME] -p[PASSWORD] -Bse 'optimize tables [tables list]' [DB_NAME]
It normally represents a parameter to be supplied by client.
Its because of the new DbContext T4 template that is used for generating the EntityFramework entities. In order to be able to perform the change tracking, this templates uses the Proxy pattern, by wrapping your nice POCOs with them. This then causes the issues when serializing with the JavaScriptSerializer.
So then the 2 solutions are:
You may switch off the automatic generation of proxies by setting it on the context's configuration
context.Configuration.ProxyCreationEnabled = false;
Very well explained in the below article.
http://juristr.com/blog/2011/08/javascriptserializer-circular-reference/
open the console as a administrator. Right Click on the command prompt or bash -> more and select "run as administrator"
SELECT *
FROM ecs_table
WHERE (start_date, end_date) OVERLAPS ('2012-01-01'::DATE, '2012-04-12'::DATE + interval '1');
You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of
function email() {
// Opens SS by its ID
var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");
// Get the name of this SS
var name = ss.getName(); // Not necessary
// Read cell 1,1 * Line below does't work *
// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet
var range = sheet.getRange(1,1);
var data = range.getValue();
}
The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.
You have to use (without @)
npm uninstall -g angular/cli
because
If you're using Angular CLI beta.28 or less, you need to uninstall angular-cli package. It should be done due to changing of package's name and scope from angular-cli to @angular/cli https://github.com/angular/angular-cli
If you want to retrieve POST data:
first_name = request.form.get("firstname")
If you want to retrieve GET (query string) data:
first_name = request.args.get("firstname")
Or if you don't care/know whether the value is in the query string or in the post data:
first_name = request.values.get("firstname")
request.values is a CombinedMultiDict that combines Dicts from request.form and request.args.
What's the difference between Perl's backticks (`
), system
, and exec
?
exec -> exec "command"; ,
system -> system("command"); and
backticks -> print `command`;
exec
exec
executes a command and never resumes the Perl script. It's to a script like a return
statement is to a function.
If the command is not found, exec
returns false. It never returns true, because if the command is found, it never returns at all. There is also no point in returning STDOUT
, STDERR
or exit status of the command. You can find documentation about it in perlfunc, because it is a function.
E.g.:
#!/usr/bin/perl
print "Need to start exec command";
my $data2 = exec('ls');
print "Now END exec command";
print "Hello $data2\n\n";
In above code, there are three print
statements, but due to exec
leaving the script, only the first print statement is executed. Also, the exec
command output is not being assigned to any variable.
Here, only you're only getting the output of the first print
statement and of executing the ls
command on standard out.
system
system
executes a command and your Perl script is resumed after the command has finished. The return value is the exit status of the command. You can find documentation about it in perlfunc.
E.g.:
#!/usr/bin/perl
print "Need to start system command";
my $data2 = system('ls');
print "Now END system command";
print "Hello $data2\n\n";
In above code, there are three print
statements. As the script is resumed after the system
command, all three print statements are executed.
Also, the result of running system
is assigned to data2
, but the assigned value is 0
(the exit code from ls
).
Here, you're getting the output of the first print
statement, then that of the ls
command, followed by the outputs of the final two print
statements on standard out.
`
)Like system
, enclosing a command in backticks executes that command and your Perl script is resumed after the command has finished. In contrast to system
, the return value is STDOUT
of the command. qx//
is equivalent to backticks. You can find documentation about it in perlop, because unlike system and exec
, it is an operator.
E.g.:
#!/usr/bin/perl
print "Need to start backticks command";
my $data2 = `ls`;
print "Now END system command";
print "Hello $data2\n\n";
In above code, there are three print
statements and all three are being executed. The output of ls
is not going to standard out directly, but assigned to the variable data2
and then printed by the final print statement.
Invalid JSON from the server should always be an expected use case. A million things can go wrong during transmission. Gson is a bit tricky, because its error output will give you one problem, and the actual exception you catch will be of a different type.
With all that in mind, the proper fix on the client side is
try
{
gson.fromJSON(ad, Ad.class);
//...
}
catch (IllegalStateException | JsonSyntaxException exception)
{
//...
If you want to know why the JSON you received from the server is wrong, you can look inside your catch block at the exception. But even if it is your problem, it's not the client's responsibility to fix JSON it is receiving from the internet.
Either way, it is the client's responsibility to decide what to do when it gets bad JSON. Two possibilities are rejecting the JSON and doing nothing, and trying again.
If you are going to try again, I highly recommend setting a flag inside the try / catch block and then responding to that flag outside the try / catch block. Nested try / catch is likely how Gson got us into this mess with our stack trace and exceptions not matching up.
In other words, even though I'll admit it doesn't look very elegant, I would recommend
boolean failed = false;
try
{
gson.fromJSON(ad, Ad.class);
//...
}
catch (IllegalStateException | JsonSyntaxException exception)
{
failed = true;
//...
}
if (failed)
{
//...
This is a huge topic, with answers from 3 lines of code to entire research magazines.
I will outline the most common such techniques and their results.
One of the simplest & fastest methods. Proposed decades ago as a means to find picture simmilarities. The idea is that a forest will have a lot of green, and a human face a lot of pink, or whatever. So, if you compare two pictures with forests, you'll get some simmilarity between histograms, because you have a lot of green in both.
Downside: it is too simplistic. A banana and a beach will look the same, as both are yellow.
OpenCV method: compareHist()
A good example here matchTemplate finding good match. It convolves the search image with the one being search into. It is usually used to find smaller image parts in a bigger one.
Downsides: It only returns good results with identical images, same size & orientation.
OpenCV method: matchTemplate()
Considered one of the most efficient ways to do image search. A number of features are extracted from an image, in a way that guarantees the same features will be recognized again even when rotated, scaled or skewed. The features extracted this way can be matched against other image feature sets. Another image that has a high proportion of the features matching the first one is considered to be depicting the same scene.
Finding the homography between the two sets of points will allow you to also find the relative difference in shooting angle between the original pictures or the amount of overlapping.
There are a number of OpenCV tutorials/samples on this, and a nice video here. A whole OpenCV module (features2d) is dedicated to it.
Downsides: It may be slow. It is not perfect.
Over on the OpenCV Q&A site I am talking about the difference between feature descriptors, which are great when comparing whole images and texture descriptors, which are used to identify objects like human faces or cars in an image.
See svn diff
in the manual:
svn diff -r 8979:11390 http://svn.collab.net/repos/svn/trunk/fSupplierModel.php
This should work, try;
Add a System Reference.
using System.Diagnostics;
Then use this code to run your command in a hiden CMD Window.
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.Arguments = "Enter your command here";
cmd.Start();
Was getting the error while I was using jupyter.
ModuleNotFoundError: No module named 'xlrd'
...
ImportError: Install xlrd >= 0.9.0 for Excel support
it was resolved for me after using.
!pip install xlrd
Use DateTime::createFromFormat
$date = date_create_from_format('d/m/Y:H:i:s', $s);
$date->getTimestamp();
In Bootstrap 3, .form-control
(the class you give your inputs) has a width of 100%, which allows you to wrap them into col-lg-X divs for arrangement. Example from the docs:
<div class="row">
<div class="col-lg-2">
<input type="text" class="form-control" placeholder=".col-lg-2">
</div>
<div class="col-lg-3">
<input type="text" class="form-control" placeholder=".col-lg-3">
</div>
<div class="col-lg-4">
<input type="text" class="form-control" placeholder=".col-lg-4">
</div>
</div>
See under Column sizing.
It's a bit different than in Bootstrap 2.3.2, but you get used to it quickly.
Adding to Gaby's post, my jdbc getTables() for Oracle 10g requires all caps to work:
"employee" -> "EMPLOYEE"
Otherwise I would get an exception:
java.sql.SqlExcepcion exhausted resultset
(even though "employee" is in the schema)
getimagesize() returns an array containing the image properties.
list($width, $height) = getimagesize("path/to/image.jpg");
to just get the width and height or
list($width, $height, $type, $attr)
to get some more information.
The tabularx
package gives you
X
, all X
columns will grow to fill up the total width.For your example:
\usepackage{tabularx}
% ...
\begin{document}
% ...
\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF & simulation & jsp\\
\hline
\end{tabularx}
The answers already explain how attributes and properties are handled differently, but I really would like to point out how totally insane this is. Even if it is to some extent the spec.
It is crazy, to have some of the attributes (e.g. id, class, foo, bar) to retain only one kind of value in the DOM, while some attributes (e.g. checked, selected) to retain two values; that is, the value "when it was loaded" and the value of the "dynamic state". (Isn't the DOM supposed to be to represent the state of the document to its full extent?)
It is absolutely essential, that two input fields, e.g. a text and a checkbox behave the very same way. If the text input field does not retain a separate "when it was loaded" value and the "current, dynamic" value, why does the checkbox? If the checkbox does have two values for the checked attribute, why does it not have two for its class and id attributes? If you expect to change the value of a text *input* field, and you expect the DOM (i.e. the "serialized representation") to change, and reflect this change, why on earth would you not expect the same from an input field of type checkbox on the checked attribute?
The differentiation, of "it is a boolean attribute" just does not make any sense to me, or is, at least not a sufficient reason for this.
The following should work for any struct type. It is based off code by Matt Manela from MSDN forums. As Murph points out the exception handling could be expensive compared to using the Types dedicated TryParse method.
public static bool TryParseStruct<T>(this string value, out Nullable<T> result)
where T: struct
{
if (string.IsNullOrEmpty(value))
{
result = new Nullable<T>();
return true;
}
result = default(T);
try
{
IConvertible convertibleString = (IConvertible)value;
result = new Nullable<T>((T)convertibleString.ToType(typeof(T), System.Globalization.CultureInfo.CurrentCulture));
}
catch(InvalidCastException)
{
return false;
}
catch (FormatException)
{
return false;
}
return true;
}
These were the basic test cases I used.
string parseOne = "1";
int? resultOne;
bool successOne = parseOne.TryParseStruct<int>(out resultOne);
Assert.IsTrue(successOne);
Assert.AreEqual(1, resultOne);
string parseEmpty = string.Empty;
int? resultEmpty;
bool successEmpty = parseEmpty.TryParseStruct<int>(out resultEmpty);
Assert.IsTrue(successEmpty);
Assert.IsFalse(resultEmpty.HasValue);
string parseNull = null;
int? resultNull;
bool successNull = parseNull.TryParseStruct<int>(out resultNull);
Assert.IsTrue(successNull);
Assert.IsFalse(resultNull.HasValue);
string parseInvalid = "FooBar";
int? resultInvalid;
bool successInvalid = parseInvalid.TryParseStruct<int>(out resultInvalid);
Assert.IsFalse(successInvalid);
You need to push a bytes-like
object (bytes
, bytearray
, etc) to the base64.b64encode()
method. Here are two ways:
>>> import base64
>>> data = base64.b64encode(b'data to be encoded')
>>> print(data)
b'ZGF0YSB0byBiZSBlbmNvZGVk'
Or with a variable:
>>> import base64
>>> string = 'data to be encoded'
>>> data = base64.b64encode(string.encode())
>>> print(data)
b'ZGF0YSB0byBiZSBlbmNvZGVk'
In Python 3, str
objects are not C-style character arrays (so they are not byte arrays), but rather, they are data structures that do not have any inherent encoding. You can encode that string (or interpret it) in a variety of ways. The most common (and default in Python 3) is utf-8, especially since it is backwards compatible with ASCII (although, as are most widely-used encodings). That is what is happening when you take a string
and call the .encode()
method on it: Python is interpreting the string in utf-8 (the default encoding) and providing you the array of bytes that it corresponds to.
Originally the question title asked about Base-64 encoding. Read on for Base-64 stuff.
base64
encoding takes 6-bit binary chunks and encodes them using the characters A-Z, a-z, 0-9, '+', '/', and '=' (some encodings use different characters in place of '+' and '/'). This is a character encoding that is based off of the mathematical construct of radix-64 or base-64 number system, but they are very different. Base-64 in math is a number system like binary or decimal, and you do this change of radix on the entire number, or (if the radix you're converting from is a power of 2 less than 64) in chunks from right to left.
In base64
encoding, the translation is done from left to right; those first 64 characters are why it is called base64
encoding. The 65th '=' symbol is used for padding, since the encoding pulls 6-bit chunks but the data it is usually meant to encode are 8-bit bytes, so sometimes there are only two or 4 bits in the last chunk.
Example:
>>> data = b'test'
>>> for byte in data:
... print(format(byte, '08b'), end=" ")
...
01110100 01100101 01110011 01110100
>>>
If you interpret that binary data as a single integer, then this is how you would convert it to base-10 and base-64 (table for base-64):
base-2: 01 110100 011001 010111 001101 110100 (base-64 grouping shown)
base-10: 1952805748
base-64: B 0 Z X N 0
base64
encoding, however, will re-group this data thusly:
base-2: 011101 000110 010101 110011 011101 00(0000) <- pad w/zeros to make a clean 6-bit chunk
base-10: 29 6 21 51 29 0
base-64: d G V z d A
So, 'B0ZXN0' is the base-64 version of our binary, mathematically speaking. However, base64
encoding has to do the encoding in the opposite direction (so the raw data is converted to 'dGVzdA') and also has a rule to tell other applications how much space is left off at the end. This is done by padding the end with '=' symbols. So, the base64
encoding of this data is 'dGVzdA==', with two '=' symbols to signify two pairs of bits will need to be removed from the end when this data gets decoded to make it match the original data.
Let's test this to see if I am being dishonest:
>>> encoded = base64.b64encode(data)
>>> print(encoded)
b'dGVzdA=='
base64
encoding?Let's say I have to send some data to someone via email, like this data:
>>> data = b'\x04\x6d\x73\x67\x08\x08\x08\x20\x20\x20'
>>> print(data.decode())
>>> print(data)
b'\x04msg\x08\x08\x08 '
>>>
There are two problems I planted:
\x04
character was read, because that is ASCII for END-OF-TRANSMISSION
(Ctrl-D), so the remaining data would be left out of the transmission.BACKSPACE
characters and three SPACE
characters to erase the 'msg'. Thus, even if I didn't have the EOF
character there the end user wouldn't be able to translate from the text on screen to the real, raw data.This is just a demo to show you how hard it can be to simply send raw data. Encoding the data into base64 format gives you the exact same data but in a format that ensures it is safe for sending over electronic media such as email.
Look in JavaScript split() Method
Usage:
"something -- something_else".split(" -- ")
You don't actually declare things, but this is how you create an array in Python:
from array import array
intarray = array('i')
For more info see the array module: http://docs.python.org/library/array.html
Now possible you don't want an array, but a list, but others have answered that already. :)
The Facebook "Graph API Rate Limiting" docs says that an error with code #4
is an app level rate limit, which is different than user level rate limits. Although it doesn't give any exact numbers, it describes their app level rate-limit as:
This rate limiting is applied globally at the app level. Ads api calls are excluded.
- Rate limiting happens real time on sliding window for past one hour.
- Stats is collected for number of calls and queries made, cpu time spent, memory used for each app.
- There is a limit for each resource multiplied by monthly active users of a given app.
- When the app uses more than its allowed resources the error is thrown.
- Error, Code: 4, Message: Application request limit reached
The docs also give recommendations for avoiding the rate limits. For app level limits, they are:
Recommendations:
- Verify the error code (4) to confirm the throttling type.
- Do not make burst of calls, spread out the calls throughout the day.
- Do smart fetching of data (important data, non duplicated data, etc).
- Real-time insights, make sure API calls are structured in a way that you can read insights for as many as Page posts as possible, with minimum number of requests.
- Don't fetch users feed twice (in the case that two App users have a specific friend in common)
- Don't fetch all user's friends feed in a row if the number of friends is more than 250. Separate the fetches over different days. As an option, fetch first the app user's news feed (me/home) in order to detect which friends are more important to the App user. Then, fetch those friends feeds first.
- Consider to limit/filter the requests by using the following parameters: "since", "until", "limit"
- For page related calls use realtime updates to subscribe to changes in data.
- Field expansion allows ton "join" multiple graph queries into a single call.
- Etags to check if the data querying has changed since the last check.
- For page management developers who does not have massive user base, have the admins of the page to accept the app to increase the number of users.
Finally, the docs give the following informational tips:
- Batching calls will not reduce the number of api calls.
- Making parallel calls will not reduce the number of api calls.
If you have access to you httpd.conf file (in ubuntu it is in the /etc/apache2 directory), you should add the same lines that you would to the .htaccess
file in the specific directory. That is (for example):
ServerName YOURSERVERNAMEHERE
<Directory /var/www/>
AllowOverride None
order deny,allow
Options -Indexes FollowSymLinks
</Directory>
Do this for every directory that you want to control the information, and you will have one file in one spot to manage all access. It the example above, I did it for the root directory, /var/www.
This option may not be available with outsourced hosting, especially shared hosting. But it is a better option than adding many .htaccess
files.
All the other posts here had major holes in them, so here's a solution that will:
In the XML:
<EditText
...
android:inputType="numberDecimal"
... />
Class variable:
private boolean isDecimalSeparatorComma = false;
In onCreate, find the separator used in the current locale:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
NumberFormat nf = NumberFormat.getInstance();
if (nf instanceof DecimalFormat) {
DecimalFormatSymbols sym = ((DecimalFormat) nf).getDecimalFormatSymbols();
char decSeparator = sym.getDecimalSeparator();
isDecimalSeparatorComma = Character.toString(decSeparator).equals(",");
}
}
Also onCreate, Use this to update it if you're loading in a current value:
// Replace editText with commas or periods as needed for viewing
String editTextValue = getEditTextValue(); // load your current value
if (editTextValue.contains(".") && isDecimalSeparatorComma) {
editTextValue = editTextValue.replaceAll("\\.",",");
} else if (editTextValue.contains(",") && !isDecimalSeparatorComma) {
editTextValue = editTextValue.replaceAll(",",".");
}
setEditTextValue(editTextValue); // override your current value
Also onCreate, Add the Listeners
editText.addTextChangedListener(editTextWatcher);
if (isDecimalSeparatorComma) {
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789,"));
} else {
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
}
editTextWatcher
TextWatcher editTextWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
@Override
public void afterTextChanged(Editable s) {
String editTextValue = s.toString();
// Count up the number of commas and periods
Pattern pattern = Pattern.compile("[,.]");
Matcher matcher = pattern.matcher(editTextValue);
int count = 0;
while (matcher.find()) {
count++;
}
// Don't let it put more than one comma or period
if (count > 1) {
s.delete(s.length()-1, s.length());
} else {
// If there is a comma or period at the end the value hasn't changed so don't update
if (!editTextValue.endsWith(",") && !editTextValue.endsWith(".")) {
doSomething()
}
}
}
};
doSomething() example, convert to standard period for data manipulation
private void doSomething() {
try {
String editTextStr = editText.getText().toString();
if (isDecimalSeparatorComma) {
editTextStr = editTextStr.replaceAll(",",".");
}
float editTextFloatValue = editTextStr.isEmpty() ?
0.0f :
Float.valueOf(editTextStr);
... use editTextFloatValue
} catch (NumberFormatException e) {
Log.e(TAG, "Error converting String to Double");
}
}
I have not used pyserial but based on the API documentation at https://pyserial.readthedocs.io/en/latest/shortintro.html it seems like a very nice interface. It might be worth double-checking the specification for AT commands of the device/radio/whatever you are dealing with.
Specifically, some require some period of silence before and/or after the AT command for it to enter into command mode. I have encountered some which do not like reads of the response without some delay first.
To remove the "keep-alive" header in requests, I just created it from the Request object and then send it with Session
headers = {
'Host' : '1.2.3.4',
'User-Agent' : 'Test client (x86_64-pc-linux-gnu 7.16.3)',
'Accept' : '*/*',
'Accept-Encoding' : 'deflate, gzip',
'Accept-Language' : 'it_IT'
}
url = "https://stream.twitter.com/1/statuses/filter.json"
#r = requests.get(url, headers = headers) #this triggers keep-alive: True
s = requests.Session()
r = requests.Request('GET', url, headers)
Choose Database | Set Datasource Location... Select the database node (yellow-ish cylinder) of the current connection, then select the database node of the desired connection (you may need to authenticate), then click Update.
You will need to do this for the 'Subreports' nodes as well.
FYI, you can also do individual tables by selecting each individually, then choosing Update.
Here is a complete example of how to create a smaller image (thumbnail). This snippet resizes the Image, rotates it when needed (if a phone was held vertically) and pads the image if you want to create square thumbs. This snippet creates a JPEG, but it can easily be modified for other file types. Even if the image would be smaller than the max allowed size the image will still be compressed and it's resolution altered to create images of the same dpi and compression level.
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
//set the resolution, 72 is usually good enough for displaying images on monitors
float imageResolution = 72;
//set the compression level. higher compression = better quality = bigger images
long compressionLevel = 80L;
public Image resizeImage(Image image, int maxWidth, int maxHeight, bool padImage)
{
int newWidth;
int newHeight;
//first we check if the image needs rotating (eg phone held vertical when taking a picture for example)
foreach (var prop in image.PropertyItems)
{
if (prop.Id == 0x0112)
{
int orientationValue = image.GetPropertyItem(prop.Id).Value[0];
RotateFlipType rotateFlipType = getRotateFlipType(orientationValue);
image.RotateFlip(rotateFlipType);
break;
}
}
//apply the padding to make a square image
if (padImage == true)
{
image = applyPaddingToImage(image, Color.Red);
}
//check if the with or height of the image exceeds the maximum specified, if so calculate the new dimensions
if (image.Width > maxWidth || image.Height > maxHeight)
{
double ratioX = (double)maxWidth / image.Width;
double ratioY = (double)maxHeight / image.Height;
double ratio = Math.Min(ratioX, ratioY);
newWidth = (int)(image.Width * ratio);
newHeight = (int)(image.Height * ratio);
}
else
{
newWidth = image.Width;
newHeight = image.Height;
}
//start the resize with a new image
Bitmap newImage = new Bitmap(newWidth, newHeight);
//set the new resolution
newImage.SetResolution(imageResolution, imageResolution);
//start the resizing
using (var graphics = Graphics.FromImage(newImage))
{
//set some encoding specs
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
}
//save the image to a memorystream to apply the compression level
using (MemoryStream ms = new MemoryStream())
{
EncoderParameters encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, compressionLevel);
newImage.Save(ms, getEncoderInfo("image/jpeg"), encoderParameters);
//save the image as byte array here if you want the return type to be a Byte Array instead of Image
//byte[] imageAsByteArray = ms.ToArray();
}
//return the image
return newImage;
}
//=== image padding
public Image applyPaddingToImage(Image image, Color backColor)
{
//get the maximum size of the image dimensions
int maxSize = Math.Max(image.Height, image.Width);
Size squareSize = new Size(maxSize, maxSize);
//create a new square image
Bitmap squareImage = new Bitmap(squareSize.Width, squareSize.Height);
using (Graphics graphics = Graphics.FromImage(squareImage))
{
//fill the new square with a color
graphics.FillRectangle(new SolidBrush(backColor), 0, 0, squareSize.Width, squareSize.Height);
//put the original image on top of the new square
graphics.DrawImage(image, (squareSize.Width / 2) - (image.Width / 2), (squareSize.Height / 2) - (image.Height / 2), image.Width, image.Height);
}
//return the image
return squareImage;
}
//=== get encoder info
private ImageCodecInfo getEncoderInfo(string mimeType)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType.ToLower() == mimeType.ToLower())
{
return encoders[j];
}
}
return null;
}
//=== determine image rotation
private RotateFlipType getRotateFlipType(int rotateValue)
{
RotateFlipType flipType = RotateFlipType.RotateNoneFlipNone;
switch (rotateValue)
{
case 1:
flipType = RotateFlipType.RotateNoneFlipNone;
break;
case 2:
flipType = RotateFlipType.RotateNoneFlipX;
break;
case 3:
flipType = RotateFlipType.Rotate180FlipNone;
break;
case 4:
flipType = RotateFlipType.Rotate180FlipX;
break;
case 5:
flipType = RotateFlipType.Rotate90FlipX;
break;
case 6:
flipType = RotateFlipType.Rotate90FlipNone;
break;
case 7:
flipType = RotateFlipType.Rotate270FlipX;
break;
case 8:
flipType = RotateFlipType.Rotate270FlipNone;
break;
default:
flipType = RotateFlipType.RotateNoneFlipNone;
break;
}
return flipType;
}
//== convert image to base64
public string convertImageToBase64(Image image)
{
using (MemoryStream ms = new MemoryStream())
{
//convert the image to byte array
image.Save(ms, ImageFormat.Jpeg);
byte[] bin = ms.ToArray();
//convert byte array to base64 string
return Convert.ToBase64String(bin);
}
}
For the asp.net users a little example of how to upload a file, resize it and display the result on the page.
//== the button click method
protected void Button1_Click(object sender, EventArgs e)
{
//check if there is an actual file being uploaded
if (FileUpload1.HasFile == false)
{
return;
}
using (Bitmap bitmap = new Bitmap(FileUpload1.PostedFile.InputStream))
{
try
{
//start the resize
Image image = resizeImage(bitmap, 256, 256, true);
//to visualize the result, display as base64 image
Label1.Text = "<img src=\"data:image/jpg;base64," + convertImageToBase64(image) + "\">";
//save your image to file sytem, database etc here
}
catch (Exception ex)
{
Label1.Text = "Oops! There was an error when resizing the Image.<br>Error: " + ex.Message;
}
}
}
The map function
does not exist on the Object.prototype
however you can emulate it like so
var myMap = function ( obj, callback ) {
var result = {};
for ( var key in obj ) {
if ( Object.prototype.hasOwnProperty.call( obj, key ) ) {
if ( typeof callback === 'function' ) {
result[ key ] = callback.call( obj, obj[ key ], key, obj );
}
}
}
return result;
};
var myObject = { 'a': 1, 'b': 2, 'c': 3 };
var newObject = myMap( myObject, function ( value, key ) {
return value * value;
});
Improved version of Paulius Zaliaduonis' answer:
In order to make the validation work properly I had to change the Model to:
public class ViewModel
{
public HttpPostedFileBase File { get; set; }
[Required(ErrorMessage="A header image is required"), FileExtensions(ErrorMessage = "Please upload an image file.")]
public string FileName
{
get
{
if (File != null)
return File.FileName;
else
return String.Empty;
}
}
}
and the view to:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.File, new { type = "file" })
@Html.ValidationMessageFor(m => m.FileName)
}
This is required because what @Serj Sagan wrote about FileExtension attribute working only with strings.
Yet another option is argh. It builds on argparse, and lets you write things like:
import argh
# declaring:
def echo(text):
"Returns given word as is."
return text
def greet(name, greeting='Hello'):
"Greets the user with given name. The greeting is customizable."
return greeting + ', ' + name
# assembling:
parser = argh.ArghParser()
parser.add_commands([echo, greet])
# dispatching:
if __name__ == '__main__':
parser.dispatch()
It will automatically generate help and so on, and you can use decorators to provide extra guidance on how the arg-parsing should work.
you can get the size of InputStream using getBytes(inputStream) of Utils.java check this following link
I have created tool similar to Ned Batchelder:
Searching .dll and .exe files in PATH
While my tool is primarly for searching of various dll versions it shows more info (date, size, version) but it do not use PATHEXT (I hope to update my tool soon).
[UIView setAnimationsEnabled:NO];
// your code here
[UIView setAnimationsEnabled:YES];
it's a pointer to the pointer's address value. (that's terrible I know)
basically, it lets you pass a pointer to the value of the address of another pointer, so you can modify where another pointer is pointing from a sub function, like:
void changeptr(int** pp)
{
*pp=&someval;
}
Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.
But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)
I dont know if this is still useful. I achieved something like this with a java library at http://www.pushlets.com/
Althoug doing it in a service won't prevent android from shutting it down an killing the listener thread.
That what manual says about setOnClickListener
method is:
public void setOnClickListener (View.OnClickListener l)
Added in API level 1 Register a callback to be invoked when this view is clicked. If this view is not clickable, it becomes clickable.
Parameters
l View.OnClickListener: The callback that will run
And normally you have to use it like this
public class ExampleActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedValues) {
...
Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(this);
}
// Implement the OnClickListener callback
public void onClick(View v) {
// do something when the button is clicked
}
...
}
Take a look at this lesson as well Building a Simple Calculator using Android Studio.
The Network pending state on time, means your request is in progressing state. As soon as it responds the time will be updated with total elapsed time.
This picture shows the network call is in processing state(Pending)
This picture shows the time taken in processing by network call.
Alongside nmaier's answer, as he said you'll always receive code 1006. However, if you were to somehow theoretically receive other codes, here is code to display the results (via RFC6455).
var websocket;
if ("WebSocket" in window)
{
websocket = new WebSocket("ws://yourDomainNameHere.org/");
websocket.onopen = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was opened");
};
websocket.onclose = function (event) {
var reason;
alert(event.code);
// See http://tools.ietf.org/html/rfc6455#section-7.4.1
if (event.code == 1000)
reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
else if(event.code == 1001)
reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
else if(event.code == 1002)
reason = "An endpoint is terminating the connection due to a protocol error";
else if(event.code == 1003)
reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
else if(event.code == 1004)
reason = "Reserved. The specific meaning might be defined in the future.";
else if(event.code == 1005)
reason = "No status code was actually present.";
else if(event.code == 1006)
reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
else if(event.code == 1007)
reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
else if(event.code == 1008)
reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
else if(event.code == 1009)
reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
else if(event.code == 1011)
reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
else if(event.code == 1015)
reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
else
reason = "Unknown reason";
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
};
websocket.onmessage = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "New message arrived: " + event.data);
};
websocket.onerror = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "There was an error with your websocket.");
};
}
else
{
alert("Websocket is not supported by your browser");
return;
}
websocket.send("Yo wazzup");
websocket.close();