window.location = mypage.href
is a direct command for the browser to dump it's contents and start loading up some more. So for better clarification, here's what's happening in your PHP script:
echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location = "index.php";';
echo '</script>';
1) prepare to accept a modification or addition to the current Javascript cache. 2) show the alert 3) dump everything in browser memory and get ready for some more (albeit an older method of loading a new URL (AND NOTICE that there are no "\n" (new line) indicators between the lines and is therefore causing some havoc in the JS decoder.
Let me suggest that you do this another way..
echo '<script type="text/javascript">\n';
echo 'alert("review your answer");\n';
echo 'document.location.href = "index.php";\n';
echo '</script>\n';
1) prepare to accept a modification or addition to the current Javascript cache. 2) show the alert 3) dump everything in browser memory and get ready for some more (in a better fashion than before) And WOW - it all works because the JS decoder can see that each command is anow a new line.
Best of luck!
I also see that the page loading (performance) takes a long time on using h:commandLink than h:link. h:link is faster compared to h:commandLink
I have spent lots of time doing this
I want to put my django app on my server and when I run python manage.py migrate
I met this questions
And!! I set this
ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock
It worked finally!
For me, an issue where json_encode would return null encoding of an entity was because my jsonSerialize implementation fetched entire objects for related entities; I solved the issue by making sure that I fetched the ID of the related/associated entity and called ->toArray() when there were more than one entity associated with the object to be json serialized. Note, I'm speaking about cases where one implements JsonSerializable
on entities.
The top-scoring answer has the right idea, but the API seems to have evolved so that it no longer works as when it was first written, in 2015.
In place of this:
from OpenSSL import SSL
context = SSL.Context(SSL.PROTOCOL_TLSv1_2)
context.use_privatekey_file('server.key')
context.use_certificate_file('server.crt')
I used this, with Python 3.7.5:
import ssl
context = ssl.SSLContext()
context.load_cert_chain('fullchain.pem', 'privkey.pem')
and then supplied the SSL context in the Flask.run
call as it said:
app.run(…, ssl_context=context)
(My server.crt
file is called fullchain.pem
and my server.key
is called privkey.pem
. These files were supplied to me by my LetsEncrypt Certbot.)
I found a solution for my problem while writing my question !
Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)
I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)
So it seems the problem comes from the use of RDP (windows7 and 8)
Update 2017: Problem occurs on Windows 10 aswell.
You can generate an AWR (automatic workload repository) report from the database.
Run from the SQL*Plus command line:
SQL> @$ORACLE_HOME/rdbms/admin/awrrpt.sql
Read the document related to how to generate & understand an AWR report. It will give a complete view of database performance and resource issues. Once we are familiar with the AWR report it will be helpful to find Top SQL which is consuming resources.
Also, in the 12C EM Express UI we can generate an AWR.
Or try an alternate method using Time datatype:
DECLARE @MyTime TIME = '03:30:00', @MyDay DATETIME = CAST(GETDATE() AS DATE)
SELECT @MyDay+@MyTime
Thank you for the solution. In my case the file %appdata%\pip\pip.ini was not present. I created it manually with this content:
[global]
trusted-host = pypi.python.org files.pythonhosted.org pypi.org pypi.io
The below annotated code would set "value" to "name"
@RequestMapping("/testing")
@Controller
public class TestController {
@RequestMapping(method = RequestMethod.GET)
public String testMestod(HttpServletRequest request){
request.getSession().setAttribute("name", "value");
return "testJsp";
}
}
To access the same in JSP use
${sessionScope.name}
.
For the @ModelAttribute
see this link
#more {
background:none;
border:none;
color:#FFF;
font-family:Verdana, Geneva, sans-serif;
cursor: pointer;
}
Use InvariantCulture. The decimal separator is always "." eventually you can replace "," by "." When you display the result , use your local culture. But internally use always invariant culture
TryParse does not allway work as we would expect There are change request in .net in this area:
You just need to change the table names as per the error in - /etc/phpmyadmin/config.inc.php
$ Cfg ['Servers'] [$ i] ['table_uiprefs'] = ‘pma_table_uiprefs’;
to
$ Cfg ['Servers'] [$ i] ['table_uiprefs'] = ‘pma__table_uiprefs’;
assign the table names accordingly and everything will be fine.
For me,sudo dpkg-reconfigure phpmyadmin
caused more trouble when I chose the option to re-install the database
So many answers, and not a single one explains the WHY? (which Giovanni explicitly asked)...
.NET generics do not act like C++ templates. In C++ templates, overload resolution occurs after the actual template parameters are known.
In .NET generics (including C#), overload resolution occurs without knowing the actual generic parameters. The only information the compiler can use to choose the function to call comes from type constraints on the generic parameters.
First set path of python
https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows
and run python
file
python filename.py
command line argument with python
python filename.py command-line argument
function makeArrayOf(value, length) {
var arr = [], i = length;
while (i--) {
arr[i] = value;
}
return arr;
}
makeArrayOf(0, 5); // [0, 0, 0, 0, 0]
makeArrayOf('x', 3); // ['x', 'x', 'x']
Note that while
is usually more efficient than for-in
, forEach
, etc.
Combining benzado and webmat's answers, updating with git rm
, not failing on files found that aren't in repo, and making it paste-able generically for any user:
# remove any existing files from the repo, skipping over ones not in repo
find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch
# specify a global exclusion list
git config --global core.excludesfile ~/.gitignore
# adding .DS_Store to that list
echo .DS_Store >> ~/.gitignore
You can add your styles in the required page after the external style sheet so they'll cascade and overwrite the first set of rules.
<link rel="stylesheet" href="allpages.css">
<style>
.flex-control-thumbs li {
width: auto;
float: none;
}
</style>
Sometimes "Nothing to be done for all" error can be caused by spaces before command in makefile rule instead of tab. Please ensure that you use tabs instead of spaces inside of your rules.
all:
<\t>$(CC) $(CFLAGS) ...
instead of
all:
$(CC) $(CFLAGS) ...
Please see the GNU make manual for the rule syntax description: https://www.gnu.org/software/make/manual/make.html#Rule-Syntax
I needed to do something like this really fast really simple, from searching for ideas i finally built this template. The idea is receive the weighted values in a form of a json from the api, which here is simulated by the dict.
Then translate it into a list in which each value repeats proportionally to it's weight, and just use random.choice to select a value from the list.
I tried it running with 10, 100 and 1000 iterations. The distribution seems pretty solid.
def weighted_choice(weighted_dict):
"""Input example: dict(apples=60, oranges=30, pineapples=10)"""
weight_list = []
for key in weighted_dict.keys():
weight_list += [key] * weighted_dict[key]
return random.choice(weight_list)
What I have done if all I want to do is see that some string was logged (as opposed to verifying exact log statements which is just too brittle) is to redirect StdOut to a buffer, do a contains, then reset StdOut:
PrintStream original = System.out;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
System.setOut(new PrintStream(buffer));
// Do something that logs
assertTrue(buffer.toString().contains(myMessage));
System.setOut(original);
EclipseLink provided an annotation (e.g. @Index) to define an index on columns. There is an example of its use. Part of the example is included...
The firstName and lastName fields are indexed, together and individually.
@Entity
@Index(name="EMP_NAME_INDEX", columnNames={"F_NAME","L_NAME"}) // Columns indexed together
public class Employee{
@Id
private long id;
@Index // F_NAME column indexed
@Column(name="F_NAME")
private String firstName;
@Index // L_NAME column indexed
@Column(name="L_NAME")
private String lastName;
...
}
Prior to Oracle 12C you cannot select from PL/SQL-defined tables, only from tables based on SQL types like this:
CREATE OR REPLACE TYPE exch_row AS OBJECT(
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);
CREATE OR REPLACE TYPE exch_tbl AS TABLE OF exch_row;
In Oracle 12C it is now possible to select from PL/SQL tables that are defined in a package spec.
Recently ran into this issue with importing CoreNFC on older iphones (e.g. iPhone 6) and Xcode (11.3.1). I was able to get it to work by
This allowed me to compile for older/newer iPhones without making any code changes. I hope this helps other.
If you are using text-overflow:ellipsis
, the browser will show the contents whatever possible within that container. But if you want to specifiy the number of letters before the dots or strip some contents and add dots, you can use the below function.
function add3Dots(string, limit)
{
var dots = "...";
if(string.length > limit)
{
// you can also use substr instead of substring
string = string.substring(0,limit) + dots;
}
return string;
}
call like
add3Dots("Hello World",9);
outputs
Hello Wor...
See it in action here
function add3Dots(string, limit)
{
var dots = "...";
if(string.length > limit)
{
// you can also use substr instead of substring
string = string.substring(0,limit) + dots;
}
return string;
}
console.log(add3Dots("Hello, how are you doing today?", 10));
_x000D_
C# supports some inherited covariance for event delegates, so a method like this:
void LowestCommonHander( object sender, EventArgs e ) { ... }
Can be used to subscribe to your event, no explicit cast required
gcInt.MyEvent += LowestCommonHander;
You can even use lambda syntax and the intellisense will all be done for you:
gcInt.MyEvent += (sender, e) =>
{
e. //you'll get correct intellisense here
};
On the command line:
php -i | grep sourceguardian
If it's there, then you'll get some text. If not, you won't get a thing.
You can change the colour two ways; through XML or through coding. I would recommend XML since it's easier to follow for beginners.
XML:
<Button
android:background="@android:color/white"
android:textColor="@android:color/black"
/>
You can also use hex values ex.
android:background="@android:color/white"
Coding:
//btn represents your button object
btn.setBackgroundColor(Color.WHITE);
btn.setTextColor(Color.BLACK);
Prior to adding the Ajax.BeginForm. Add below scripts to your project in the order mentioned,
Only these two are enough for performing Ajax operation.
I think jQuery cannot find the element.
First of all find the element
var rowTemplate= document.getElementsByName("rowTemplate");
or
var rowTemplate = document.getElementById("rowTemplate");
or
var rowTemplate = $('#rowTemplate');
Then try your code again
rowTemplate.html().replace(....)
You have to read the data too.
Check out : http://www.doughellmann.com/PyMOTW/urllib2/ to understand it.
response = urllib2.urlopen(..)
headers = response.info()
data = response.read()
Of course, what you want is to render it in browser and aaronasterling's answer is what you want.
Loop through the results and place each one in an array
use mysqli_fetch_all()
to get them all at one time
SELECT COUNT(job_id) FROM jobs WHERE posted_date < NOW()-30;
Now()
returns the current Date and Time.
If the column already exists in your table and it is null, you can update the column with this command (replace id, tablename, and tablekey ):
UPDATE x
SET x.<Id> = x.New_Id
FROM (
SELECT <Id>, ROW_NUMBER() OVER (ORDER BY <tablekey>) AS New_Id
FROM <tablename>
) x
I've used a DOS command line to do this. Two lines, actually. The first one to make the "current directory" the folder where the file is - or the root folder of a group of folders where the file can be. The second line does the search.
CD C:\TheFolder
C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG
You can find details about the parameters at this link.
Hope it helps!
NOTE: "Asepsis is no longer under active development and supported under OS X 10.11 (El Capitan) and later."
Here's a comprehensive review of your options. Asepsis (the second solution mentioned) seems to be what you're looking for, it re-routes .DS_Store creation to a unified cache instead of being located on every folder.
I usually add separate safe pipe reusable component as following
# Add Safe Pipe
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({name: 'mySafe'})
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {
}
public transform(url) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
# then create shared pipe module as following
import { NgModule } from '@angular/core';
import { SafePipe } from './safe.pipe';
@NgModule({
declarations: [
SafePipe
],
exports: [
SafePipe
]
})
export class SharedPipesModule {
}
# import shared pipe module in your native module
@NgModule({
declarations: [],
imports: [
SharedPipesModule,
],
})
export class SupportModule {
}
<!-------------------
call your url (`trustedUrl` for me) and add `mySafe` as defined in Safe Pipe
---------------->
<div class="container-fluid" *ngIf="trustedUrl">
<iframe [src]="trustedUrl | mySafe" align="middle" width="100%" height="800" frameborder="0"></iframe>
</div>
You should have to use DateTime.TryParseExact
.
var newDate = DateTime.ParseExact("20111120",
"yyyyMMdd",
CultureInfo.InvariantCulture);
OR
string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;
if (DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
{
//valid
}
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
In 12c you can make use of the fact that columns which are set from invisible to visible are displayed as the last column of the table: Tips and Tricks: Invisible Columns in Oracle Database 12c
Maybe that is the 'trick' @jeffrey-kemp was talking about in his comment, but the link there does not work anymore.
Example:
ALTER TABLE my_tab ADD (col_3 NUMBER(10));
ALTER TABLE my_tab MODIFY (
col_1 invisible,
col_2 invisible
);
ALTER TABLE my_tab MODIFY (
col_1 visible,
col_2 visible
);
Now col_3 would be displayed first in a SELECT * FROM my_tab
statement.
Note: This does not change the physical order of the columns on disk, but in most cases that is not what you want to do anyway. If you really want to change the physical order, you can use the DBMS_REDEFINITION package.
I ran into this problem because one level of tag, <ListView.View>
to be specirfic, was missing in my XAML.
This code produced this error.
<Grid>
<ListView Margin="10" Name="lvDataBinding" >
<GridView>
<GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
<GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
</GridView>
</ListView>
</Grid>
The following fixed it
<Grid>
<ListView Margin="10" Name="lvDataBinding" >
<ListView.View> <!-- This was missing in top! -->
<GridView>
<GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
<GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
</GridView>
</ListView.View>
</ListView>
</Grid>
var string = 'a,b,c,d',
strx = string.split(',');
array = [];
array = array.concat(strx);
// ["a","b","c","d"]
Do it like this:
char s[256];
strcpy(s, "one two three");
char* token = strtok(s, " ");
while (token) {
printf("token: %s\n", token);
token = strtok(NULL, " ");
}
Note: strtok
modifies the string its tokenising, so it cannot be a const char*
.
Even better use implicit remoting to use a module from another Machine!
$s = New-PSSession Server-Name
Invoke-Command -Session $s -ScriptBlock {Import-Module ActiveDirectory}
Import-PSSession -Session $s -Module ActiveDirectory -Prefix REM
This will allow you to use the module off a remote PC for as long as the PSSession is connected.
More Information: https://technet.microsoft.com/en-us/library/ff720181.aspx
I would Recommend to use Global.asax.cs File.
protected void Application_Error(Object sender, EventArgs e)
{
var exception = Server.GetLastError();
if (exception is HttpUnhandledException)
{
Server.Transfer("~/Error.aspx");
}
if (exception != null)
{
Server.Transfer("~/Error.aspx");
}
try
{
// This is to stop a problem where we were seeing "gibberish" in the
// chrome and firefox browsers
HttpApplication app = sender as HttpApplication;
app.Response.Filter = null;
}
catch
{
}
}
To move up a directory, the quickest way would be to add an alias to ~/.bash_profile
alias ..='cd ..'
and then one would need only to type '..[return]'.
MSDocs state this for your scenario:
In order to execute the first time, PackageManagement requires an internet connection to download the Nuget package provider. However, if your computer does not have an internet connection and you need to use the Nuget or PowerShellGet provider, you can download them on another computer and copy them to your target computer. Use the following steps to do this:
Run
Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 -Force
to install the provider from a computer with an internet connection.After the install, you can find the provider installed in
$env:ProgramFiles\PackageManagement\ReferenceAssemblies\\\<ProviderName\>\\\<ProviderVersion\>
or$env:LOCALAPPDATA\PackageManagement\ProviderAssemblies\\\<ProviderName\>\\\<ProviderVersion\>
.Place the folder, which in this case is the Nuget folder, in the corresponding location on your target computer. If your target computer is a Nano server, you need to run Install-PackageProvider from Nano Server to download the correct Nuget binaries.
Restart PowerShell to auto-load the package provider. Alternatively, run
Get-PackageProvider -ListAvailable
to list all the package providers available on the computer. Then useImport-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201
to import the provider to the current Windows PowerShell session.
1. You shouldn't update your dependencies directly on Production, because you don't know how this will affect the stability of your code. There could be bugs introduced with the new dependencies, it might change the way the code behaves affecting your own, it could be incompatible with other dependencies, etc. You should do this in a dev environment, following by proper QA and regression testing, etc.
2. You should version control your composer.lock file, because this stores information about your dependencies and about the dependencies of your dependencies that will allow you to replicate the current state of the code. This is important, because, all your testing and development has been done against specific code. Not caring about the actual version of the code that you have is similar to uploading code changes to your application and not testing them. If you are upgrading your dependencies versions, this should be a willingly act, and you should take the necessary care to make sure everything still works. Losing one or two hours of up time reverting to a previous release version might cost you a lot of money.
One of the arguments that you will see about not needing the composer.lock is that you can set the exact version that you need in your composer.json file, and that in this way, every time someone runs composer install
, it will install them the same code. This is not true, because, your dependencies have their own dependencies, and their configuration might be specified in a format that it allows updates to subversions, or maybe even entire versions.
This means that even when you specify that you want Laravel 4.1.31 in your composer.json, Laravel in its composer.json file might have its own dependencies required as Symfony event-dispatcher: 2.*. With this kind of config, you could end up with Laravel 4.1.31 with Symfony event-dispatcher 2.4.1, and someone else on your team could have Laravel 4.1.31 with event-dispatcher 2.6.5, it would all depend on when was the last time you ran the composer install.
So, having your composer.lock file in the version system will store the exact version of this sub-dependencies, so, when you and your teammate does a composer install (this is the way that you will install your dependencies based on a composer.lock) you both will get the same versions.
What if you wanna update? Then in your dev environment run: composer update
, this will generate a new composer.lock file (if there is something new) and after you test it, and QA test and regression test it and stuff. You can push it for everyone else to download the new composer.lock, since its safe to upgrade.
3. You shouldn't version control your actual dependencies, because it makes no sense. With the composer.lock you can install the exact version of the dependencies and you wouldn't need to commit them. Why would you add to your repo 10000 files of dependencies, when you are not supposed to be updating them. If you require to change one of this, you should fork it and make your changes there. And if you are worried about having to fetch the actual dependencies each time of a build or release, composer has different ways to alleviate this issue, cache, zip files, etc.
You might want to take a look at these questions/answers ; they could give you some informations concerning your problem :
<iframe>
javascript access parent DOM across domains?To make things short : accessing iframe from another domain is not possible, for security reasons -- which explains the error message you are getting.
The Same origin policy page on wikipedia brings some informations about that security measure :
In a nutshell, the policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions — but prevents access to most methods and properties across pages on different sites.
A strict separation between content provided by unrelated sites must be maintained on client side to prevent the loss of data confidentiality or integrity.
Use "
instead of "
to escape it.
web.config is an XML file so you should use XML escaping.
connectionString="Server=dbsrv;User ID=myDbUser;Password=somepass"word"
See this forum thread.
Update:
"
should work, but as it doesn't, have you tried some of the other string escape sequences for .NET? \"
and ""
?
Update 2:
Try single quotes for the connectionString:
connectionString='Server=dbsrv;User ID=myDbUser;Password=somepass"word'
Or:
connectionString='Server=dbsrv;User ID=myDbUser;Password=somepass"word'
Update 3:
From MSDN (SqlConnection.ConnectionString Property):
To include values that contain a semicolon, single-quote character, or double-quote character, the value must be enclosed in double quotation marks. If the value contains both a semicolon and a double-quote character, the value can be enclosed in single quotation marks.
So:
connectionString="Server=dbsrv;User ID=myDbUser;Password='somepass"word'"
The issue is not with web.config, but the format of the connection string. In a connection string, if you have a "
in a value (of the key-value pair), you need to enclose the value in '
. So, while Password=somepass"word
does not work, Password='somepass"word'
does.
Here is my solution after trying other ones available on this post, I'm using it to upload photo on TwitPic:
def upload(photo)
`curl -F media=@#{photo.path} -F username=#{@username} -F password=#{@password} -F message='#{photo.title}' http://twitpic.com/api/uploadAndPost`
end
Simple way is just concatenate ""
with integer:
int i = 100;
String s = "" + i;
now s
will have 100
as string value.
I have found that using cabs(double)
, cabsf(float)
, cabsl(long double)
, __cabsf(float)
, __cabs(double)
, __cabsf(long double)
is the solution
You have to move the css
folder into your web
folder. It seems that your web
folder on the hard drive equals the /ServletApp
folder as seen from the www. Other content than inside your web
folder cannot be accessed from the browsers.
The url of the CSS link is then
<link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>
DELETE FROM story_category
WHERE category_id NOT IN (
SELECT cid FROM (
SELECT DISTINCT category.id AS cid FROM category INNER JOIN story_category ON category_id=category.id
) AS c
)
The answer by @Darius is the most idiomatic (and probably more performant) method. One limitation is that the type you are checking has to be of type interface{}
. If you use a concrete type it will fail.
An alternative way to determine the type of something at run-time, including concrete types, is to use the Go reflect
package. Chaining TypeOf(x).Kind()
together you can get a reflect.Kind
value which is a uint
type: http://golang.org/pkg/reflect/#Kind
You can then do checks for types outside of a switch block, like so:
import (
"fmt"
"reflect"
)
// ....
x := 42
y := float32(43.3)
z := "hello"
xt := reflect.TypeOf(x).Kind()
yt := reflect.TypeOf(y).Kind()
zt := reflect.TypeOf(z).Kind()
fmt.Printf("%T: %s\n", xt, xt)
fmt.Printf("%T: %s\n", yt, yt)
fmt.Printf("%T: %s\n", zt, zt)
if xt == reflect.Int {
println(">> x is int")
}
if yt == reflect.Float32 {
println(">> y is float32")
}
if zt == reflect.String {
println(">> z is string")
}
Which prints outs:
reflect.Kind: int
reflect.Kind: float32
reflect.Kind: string
>> x is int
>> y is float32
>> z is string
Again, this is probably not the preferred way to do it, but it's good to know alternative options.
While this is not a GUI tool, my quick tests indicated that diffxml has some promise. The author appears to have thought about the complexities of representing diffs for nested elements in a standardized way (his DUL - Delta Update Language specification).
Installing and running his tools, I can say that the raw text output is quite clear and concise. It doesn't offer the same degree of immediate apprehension as a GUI tool, but given that the output is standardized as DUL, perhaps you would be able to take that and build a tool to generate a visual representation. I'd certainly love to see one.
The author's "links" section does reference a few other XML differencing tools, but as you mentioned in your post, they're all proprietary.
If anyone is trying to use event.target in React and finding a null value, it is because a SyntheticEvent has replaced the event.target. The SyntheticEvent now holds 'currentTarget', such as in event.currentTarget.getAttribute('data-username').
https://facebook.github.io/react/docs/events.html
It looks like React does this so that it works across more browsers. You can access the old properties through a nativeEvent attribute.
Old but I will try, maybe someone will find this info useful.
This is the minimal amount of code you need to do a GET
request and fetch some JSON
formatted data. This is applicable only to modern browsers like latest versions of Chrome, FF, Safari, Opera and Microsoft Edge.
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/data.json'); // by default async
xhr.responseType = 'json'; // in which format you expect the response to be
xhr.onload = function() {
if(this.status == 200) {// onload called even on 404 etc so check the status
console.log(this.response); // No need for JSON.parse()
}
};
xhr.onerror = function() {
// error
};
xhr.send();
Also check out new Fetch API which is a promise-based replacement for XMLHttpRequest API.
echo "discreet";history -d $(history 1)
lista = list.sort(lista)
This should be
lista.sort()
The .sort()
method is in-place, and returns None. If you want something not in-place, which returns a value, you could use
sorted_list = sorted(lista)
Aside #1: please don't call your lists list
. That clobbers the builtin list type.
Aside #2: I'm not sure what this line is meant to do:
print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")
is it simply
print "value 1a + value 2 = value 3a value 4"
? In other words, I don't know why you're calling str on things which are already str.
Aside #3: sometimes you use print("something")
(Python 3 syntax) and sometimes you use print "something"
(Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..
The exception TypeError: 'NoneType' object is not subscriptable
happens because the value of lista
is actually None
. You can reproduce TypeError
that you get in your code if you try this at the Python command line:
None[0]
The reason that lista
gets set to None is because the return value of list.sort()
is None
... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).
If you do not want to alter the original version you can use
other_list = sorted(lista)
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
date = cal.getTime();
set width or height(what ever u need to match parent ) to 0dp and set margins of left , right, top, bottom to act as match parent
As of 2020, you should use the Clipboard Api.
navigator.clipboard.writeText('text here you want to copy').then(function () {
alert('It worked! Do a CTRL - V to paste')
}, function () {
alert('Failure to copy. Check permissions for clipboard')
});
Here is more info about interacting with the clipboard
Get your object's constructor function and then inspect its name property.
myObj.constructor.name
Returns "myClass".
I used setLogLevel(LogLevel.FULL).setLog(new AndroidLog("YOUR_LOG_TAG"))
, it helped me.
UPDATE.
You can also try for debug purpose use retrofit.client.Response
as response model
Yes, this is an old post. Regardless, someone may find it useful. Here is another way to send parameters to event handlers.
//click handler
function add_event(event, paramA, paramB)
{
//do something with your parameters
alert(paramA ? 'paramA:' + paramA : '' + paramB ? ' paramB:' + paramB : '');
}
//bind handler to click event
$('.leadtoscore').click(add_event);
...
//once you've processed some data and know your parameters, trigger a click event.
//In this case, we will send 'myfirst' and 'mysecond' as parameters
$('.leadtoscore').trigger('click', {'myfirst', 'mysecond'});
//or use variables
var a = 'first',
b = 'second';
$('.leadtoscore').trigger('click', {a, b});
$('.leadtoscore').trigger('click', {a});
You can use NumberUtils.isCreatable() from Apache Commons Lang.
Since NumberUtils.isNumber will be deprecated in 4.0, so use NumberUtils.isCreatable() instead.
What about Boost.Lexical_cast?
Here is their example:
The following example treats command line arguments as a sequence of numeric data:
int main(int argc, char * argv[])
{
using boost::lexical_cast;
using boost::bad_lexical_cast;
std::vector<short> args;
while(*++argv)
{
try
{
args.push_back(lexical_cast<short>(*argv));
}
catch(bad_lexical_cast &)
{
args.push_back(0);
}
}
...
}
As stated in this reddit post, after Angular 7, you can simplify things to these 2 steps:
compilerOptions
in your tsconfig.json
file:"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
import myData from '../assets/data/my-data.json';
And that's it. You can now use myData
in your components/services.
I use the below query
SELECT SPID = er.session_id
,STATUS = ses.STATUS
,[Login] = ses.login_name
,Host = ses.host_name
,BlkBy = er.blocking_session_id
,DBName = DB_Name(er.database_id)
,CommandType = er.command
,ObjectName = OBJECT_NAME(st.objectid)
,CPUTime = er.cpu_time
,StartTime = er.start_time
,TimeElapsed = CAST(GETDATE() - er.start_time AS TIME)
,SQLStatement = st.text
FROM sys.dm_exec_requests er
OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) st
LEFT JOIN sys.dm_exec_sessions ses
ON ses.session_id = er.session_id
LEFT JOIN sys.dm_exec_connections con
ON con.session_id = ses.session_id
WHERE st.text IS NOT NULL
Here's a Boolean thing:
if (not suffix == "flac" ) or (not suffix == "cue" ): # WRONG! FAILS
print filename + ' is not a flac or cue file'
but
if not (suffix == "flac" or suffix == "cue" ): # CORRECT!
print filename + ' is not a flac or cue file'
(not a) or (not b) == not ( a and b )
,
is false only if a and b are both true
not (a or b)
is true only if a and be are both false.
I wrote a javascript function that I call from jQuery $(document).ready(). This will parse all children of the parent div and only update the right most child.
html
...
<div class="stretch">
<div style="padding-left: 5px; padding-right: 5px; display: inline-block;">Some text
</div>
<div class="underline" style="display: inline-block;">Some other text
</div>
</div>
....
javascript
$(document).ready(function(){
stretchDivs();
});
function stretchDivs() {
// loop thru each <div> that has class='stretch'
$("div.stretch").each(function(){
// get the inner width of this <div> that has class='stretch'
var totalW = parseInt($(this).css("width"));
// loop thru each child node
$(this).children().each(function(){
// subtract the margins, borders and padding
totalW -= (parseInt($(this).css("margin-left"))
+ parseInt($(this).css("border-left-width"))
+ parseInt($(this).css("padding-left"))
+ parseInt($(this).css("margin-right"))
+ parseInt($(this).css("border-right-width"))
+ parseInt($(this).css("padding-right")));
// if this is the last child, we can set its width
if ($(this).is(":last-child")) {
$(this).css("width","" + (totalW - 1 /* fudge factor */) + "px");
} else {
// this is not the last child, so subtract its width too
totalW -= parseInt($(this).css("width"));
}
});
});
}
Random generator = new Random();
int i = generator.nextInt(10) + 1;
You can try using this code:
protected ServiceConnection mServerConn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
Log.d(LOG_TAG, "onServiceConnected");
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d(LOG_TAG, "onServiceDisconnected");
}
}
public void start() {
// mContext is defined upper in code, I think it is not necessary to explain what is it
mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
mContext.startService(intent);
}
public void stop() {
mContext.stopService(new Intent(mContext, ServiceRemote.class));
mContext.unbindService(mServerConn);
}
Please note that setting font-sizing with px is not recommended due to accessibility concerns:
"defining font sizes in px is not accessible, because the user cannot change the font size in some browsers. For example, users with limited vision may wish to set the font size much larger than the size chosen by a web designer." (see https://developer.mozilla.org/en-US/docs/Web/CSS/font-size)
A more accessible approach is to set font-size: 100%
in the html, which respects user default size settings, and THEN using either percentages or relative units when resizing (em
or rem
), for example with a @media query.
(see https://betterwebtype.com/articles/2019/06/16/5-keys-to-accessible-web-typography/)
You could use JSON.stringify(array)
to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']);
in your PHP script to retrieve it.
As with many, in my situation I was also getting this because of an error. And sadly I could just read the CSS of the html error page.
The source of my problem was also a rewrite rule on the server. It was rewriting http to https.
String test = DateTime.Now.ToString("dd.MM.yyy");
import java.util.ArrayList;
/**
* @author potter
*
*/
public class storeAny {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Object> anyTy=new ArrayList<Object>();
anyTy.add(new Integer(1));
anyTy.add(new String("Jesus"));
anyTy.add(new Double(12.88));
anyTy.add(new Double(12.89));
anyTy.add(new Double(12.84));
anyTy.add(new Double(12.82));
for (Object o : anyTy) {
if(o instanceof String){
System.out.println(o.toString());
} else if(o instanceof Integer) {
System.out.println(o.toString());
} else if(o instanceof Double) {
System.out.println(o.toString());
}
}
}
}
There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.
There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)
The article is definitely worth a read.
Below are the changes (Marked in BOLD) in your code:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:text="Register"
android:id="@+id/register"
android:layout_width="0dp" //changes made here
android:layout_height="wrap_content"
android:padding="10dip"
android:layout_weight="1" /> //changes made here
<Button
android:text="Not this time"
android:id="@+id/cancel"
android:layout_width="0dp" //changes made here
android:layout_height="wrap_content"
android:padding="10dip"
android:layout_weight="1" /> //changes made here
</LinearLayout>
Since your LinearLayout has orientation as horizontal, therefore you will need to keep your width only as 0dp. for using weights in that direction . (If your orientation was vertical, you would have kept your height only 0dp).
Since there are 2 views and you have placed android:layout_weight="1"
for both the views, it means it will divide the two views equally in horizontal direction (or by width).
Create an Android app using Eclipse.
Create a layout that has a <WebView>
control.
Move your HTML code to /assets
folder.
Load webview with your file:///android_asset/ file.
And you have an android app!
In addition to using KeyListener (as shown by others' answers), sometimes you have to ensure that the JComponent you are using is Focusable. This can be set by adding this to your component(if you are subclassing):
@Override
public void setFocusable(boolean b) {
super.setFocusable(b);
}
And by adding this to your constructor:
setFocusable(true);
Or, if you are calling the function from a parent class/container:
JComponent childComponent = new JComponent();
childComponent.setFocusable(true);
And then doing all the KeyListener stuff mentioned by others.
The str
variable will be available and reserved some space in memory even after while executed below code.
String str;
while(condition){
str = calculateStr();
.....
}
The str
variable will not be available and also the memory will be released which was allocated for str
variable in below code.
while(condition){
String str = calculateStr();
.....
}
If we followed the second one surely this will reduce our system memory and increase performance.
heroku login
git init
heroku git:remote -a app-name123
then check the remote repo :
git remote -v
easy step
brew install postgresql
gem install pg -v 'your version'
Based on rule optimizer:
EXISTS
is much faster than IN
, when the sub-query results is very large.IN
is faster than EXISTS
, when the sub-query results is very small.Based on cost optimizer:
You should first check if Session["emp_num"]
exists in the session.
You can ask the session object if its indexer has the emp_num
value or use string.IsNullOrEmpty(Session["emp_num"])
Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.
set nocount on
create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)
insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)
declare @PersonID int
set @PersonID = 1
IF EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Posted_Flag = 1
AND Staff_Id = @PersonID
)
BEGIN
RAISERROR('Timesheets have already been posted!', 16, 1)
ROLLBACK TRAN
END
ELSE
IF NOT EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Staff_Id = @PersonID
)
BEGIN
RAISERROR('Default list has not been loaded!', 16, 1)
ROLLBACK TRAN
END
ELSE
print 'No problems here'
drop table Timesheet_Hours
Based on Bert F's answer I would like to explain my understanding.
Lets say we have 3 classes as
public class Fruit{}
public class Melon extends Fruit{}
public class WaterMelon extends Melon{}
Here We have
List<? extends Fruit> fruitExtendedList = …
//Says that I can be a list of any object as long as this object extends Fruit.
Ok now lets try to get some value from fruitExtendedList
Fruit fruit = fruitExtendedList.get(position)
//This is valid as it can only return Fruit or its subclass.
Again lets try
Melon melon = fruitExtendedList.get(position)
//This is not valid because fruitExtendedList can be a list of Fruit only, it may not be
//list of Melon or WaterMelon and in java we cannot assign sub class object to
//super class object reference without explicitly casting it.
Same is the case for
WaterMelon waterMelon = fruitExtendedList.get(position)
Now lets try to set some object in fruitExtendedList
Adding fruit object
fruitExtendedList.add(new Fruit())
//This in not valid because as we know fruitExtendedList can be a list of any
//object as long as this object extends Fruit. So what if it was the list of
//WaterMelon or Melon you cannot add Fruit to the list of WaterMelon or Melon.
Adding Melon object
fruitExtendedList.add(new Melon())
//This would be valid if fruitExtendedList was the list of Fruit but it may
//not be, as it can also be the list of WaterMelon object. So, we see an invalid
//condition already.
Finally let try to add WaterMelon object
fruitExtendedList.add(new WaterMelon())
//Ok, we got it now we can finally write to fruitExtendedList as WaterMelon
//can be added to the list of Fruit or Melon as any superclass reference can point
//to its subclass object.
But wait what if someone decides to make a new type of Lemon lets say for arguments sake SaltyLemon as
public class SaltyLemon extends Lemon{}
Now fruitExtendedList can be list of Fruit, Melon, WaterMelon or SaltyLemon.
So, our statement
fruitExtendedList.add(new WaterMelon())
is not valid either.
Basically we can say that we cannot write anything to a fruitExtendedList.
This sums up List<? extends Fruit>
Now lets see
List<? super Melon> melonSuperList= …
//Says that I can be a list of anything as long as its object has super class of Melon.
Now lets try to get some value from melonSuperList
Fruit fruit = melonSuperList.get(position)
//This is not valid as melonSuperList can be a list of Object as in java all
//the object extends from Object class. So, Object can be super class of Melon and
//melonSuperList can be a list of Object type
Similarly Melon, WaterMelon or any other object cannot be read.
But note that we can read Object type instances
Object myObject = melonSuperList.get(position)
//This is valid because Object cannot have any super class and above statement
//can return only Fruit, Melon, WaterMelon or Object they all can be referenced by
//Object type reference.
Now, lets try to set some value from melonSuperList.
Adding Object type object
melonSuperList.add(new Object())
//This is not valid as melonSuperList can be a list of Fruit or Melon.
//Note that Melon itself can be considered as super class of Melon.
Adding Fruit type object
melonSuperList.add(new Fruit())
//This is also not valid as melonSuperList can be list of Melon
Adding Melon type object
melonSuperList.add(new Melon())
//This is valid because melonSuperList can be list of Object, Fruit or Melon and in
//this entire list we can add Melon type object.
Adding WaterMelon type object
melonSuperList.add(new WaterMelon())
//This is also valid because of same reason as adding Melon
To sum it up we can add Melon or its subclass in melonSuperList and read only Object type object.
including over directories can be processed by proxy file
.....|_proxy.php
dbsettings.php:
$host='localhost';
$user='username':
$pass='pass';
proxy.php:
include_once 'db/dbsettings.php
requiredDbSettings.php:
include_once './../proxy.php';
If you are using Ubuntu server, you can use systemctl
systemctl reload apache2
DECLARE @first AS INT = 1
DECLARE @last AS INT = 300
WHILE(@first <= @last)
BEGIN
INSERT INTO tblFoo VALUES(@first)
SET @first += 1
END
In Bootstrap 4 you have to use 'max-width' attribute and then it works perfectly.
<div id="modal_dialog" class="modal fade" tabindex="-1" role="dialog" style="display: none;">
<div class="modal-dialog" style="max-width: 1350px!important;" role="document">
<div class="modal-content">
<div class="modal-body">
Sample text
</div>
</div>
</div>
Change
int wordLength = wordLengthFunction(string word);
to
int wordLength = wordLengthFunction(word);
There are two options available primarily; in case of imputation or filling of missing values NaN / np.nan with only numerical replacements (across column(s):
df['Amount'].fillna(value=None, method= ,axis=1,)
is sufficient:
From the Documentation:
value : scalar, dict, Series, or DataFrame Value to use to fill holes (e.g. 0), alternately a dict/Series/DataFrame of values specifying which value to use for each index (for a Series) or column (for a DataFrame). (values not in the dict/Series/DataFrame will not be filled). This value cannot be a list.
Which means 'strings' or 'constants' are no longer permissable to be imputed.
For more specialized imputations use SimpleImputer():
from sklearn.impute import SimpleImputer
si = SimpleImputer(strategy='constant', missing_values=np.nan, fill_value='Replacement_Value')
df[['Col-1', 'Col-2']] = si.fit_transform(X=df[['C-1', 'C-2']])
I had this issue and tried both, but had to settle for removing crap like "pageEditState", but not removing user info lest I have to look it up again.
public static void RemoveEverythingButUserInfo()
{
foreach (String o in HttpContext.Current.Session.Keys)
{
if (o != "UserInfoIDontWantToAskForAgain")
keys.Add(o);
}
}
I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).
If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::
.
Something along these lines:
create view view1
as
select table1.col1,table2.col1,table3.col3
from table1
inner join
table2
inner join
table3
on
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;
Notice the varchar
typecasting on the table1.col4.
Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.
Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).
I wrote for Visual Basic users :
Protected Function HasColumnAndValue(ByRef reader As IDataReader, ByVal columnName As String) As Boolean
For i As Integer = 0 To reader.FieldCount - 1
If reader.GetName(i).Equals(columnName) Then
Return Not IsDBNull(reader(columnName))
End If
Next
Return False
End Function
I think this is more powerful and the usage is :
If HasColumnAndValue(reader, "ID_USER") Then
Me.UserID = reader.GetDecimal(reader.GetOrdinal("ID_USER")).ToString()
End If
You need to include the protocol scheme:
'http://192.168.1.61:8080/api/call'
Without the http://
part, requests
has no idea how to connect to the remote server.
Note that the protocol scheme must be all lowercase; if your URL starts with HTTP://
for example, it won’t find the http://
connection adapter either.
date must be insert with two apostrophes' As example if the date is 2018/10/20. It can insert from these query
Query -
insert into run(id,name,dob)values(&id,'&name','2018-10-20')
use tar to split into multiple archives
there are plenty of programs that will work with tar files on windows, including cygwin.
IMHO, a very nice solution is to use c++11 emplace_back function:
revenue.emplace_back("string", map[i].second);
It just creates a new element in place.
Ad hoc queries are those that are not already defined that are not needed on a regular basis, so they're not included in the typical set of reports or queries
For completely silencing the output, here what works for me
```{r error=FALSE, warning=FALSE, message=FALSE}
invisible({capture.output({
# Your code here
2 * 2
# etc etc
})})
```
The 5 measures used above are
error = FALSE
warning = FALSE
message = FALSE
invisible()
capture.output()
var eElement; // some E DOM instance
var newFirstElement; //element which should be first in E
eElement.insertBefore(newFirstElement, eElement.firstChild);
Using $emit and $broadcast, (as mentioned by walv in the comments above)
To fire an event upwards (from child to parent)
$scope.$emit('myTestEvent', 'Data to send');
To fire an event downwards (from parent to child)
$scope.$broadcast('myTestEvent', {
someProp: 'Sending you some data'
});
and finally to listen
$scope.$on('myTestEvent', function (event, data) {
console.log(data);
});
For more details :- https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
Enjoy :)
Note: Use CSS counters
to create nested numbering in a modern browser. See the accepted answer. The following is for historical interest only.
If the browser supports content
and counter
,
.foo {_x000D_
counter-reset: foo;_x000D_
}_x000D_
.foo li {_x000D_
list-style-type: none;_x000D_
}_x000D_
.foo li::before {_x000D_
counter-increment: foo;_x000D_
content: "1." counter(foo) " ";_x000D_
}
_x000D_
<ol class="foo">_x000D_
<li>uno</li>_x000D_
<li>dos</li>_x000D_
<li>tres</li>_x000D_
<li>cuatro</li>_x000D_
</ol>
_x000D_
It's usually just easier to skip the mouse altogether--or it would be if Sublime didn't mess up multiselect when word wrapping. Here's the official documentation on using the keyboard and mouse for multiple selection. Since it's a bit spread out, I'll summarize it:
Where shortcuts are different in Sublime Text 3, I've made a note. For v3, I always test using the latest dev build; if you're using the beta build, your experience may be different.
If you lose your selection when switching tabs or windows (particularly on Linux), try using Ctrl + U to restore it.
Building blocks:
Combine as you see fit. For example:
Building blocks:
Combine as you see fit. For example:
On Yosemite and El Capitan, ^?? and ^?? are system keyboard shortcuts by default. If you want them to work in Sublime Text, you will need to change them:
System Preferences
.Shortcuts
tab.Mission Control
in the left listbox.Mission Control
and Application windows
(or disable them). I use ^?? and ^??. They defaults are ^? and ^?; adding ^ to those shortcuts triggers the same actions, but slows the animations.In case you're not familiar with Mac's keyboard symbols:
please try below answer.
+(void)callAFWSPost:(NSDictionary *)dict withURL:(NSString *)strUrl
withBlock:(dictionary)block
{
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
[manager POST:[NSString stringWithFormat:@"%@/%@",WebserviceUrl,strUrl] parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
if (!responseObject)
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:ServerResponceError forKey:@"error"];
block(responseObject);
return ;
}
else if ([responseObject isKindOfClass:[NSDictionary class]]) {
block(responseObject);
return ;
}
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:ServerResponceError forKey:@"error"];
block(dict);
}];
}
I know there is already an answer - and this is an old question - but I was wondering the same thing and after finding this answer I did a little experimentation on my own and had (IMO) a worthwhile addition to the discussion.
The non-visible characters can still be used in a folder name - a placeholder is inserted - but the sort on ASCII value still seems to hold.
I tested on Windows7, holding down the alt-key and typing in the ASCII code using the numeric keypad. I did not test very many, but was successful creating foldernames that started with ASCII 1, ASCII 2, and ASCII 3. Those correspond with SOH, STX and ETX. Respectively it displayed happy face, filled happy face, and filled heart.
I'm not sure if I can duplicate that here - but I will type them in on the next lines and submit.
?foldername
?foldername
?foldername
Did they add a runtime List<> and/or Map<> type class to typepad 1.0
No, providing a runtime is not the focus of the TypeScript team.
is there a solid library out there someone wrote that provides this functionality?
I wrote (really just ported over buckets to typescript): https://github.com/basarat/typescript-collections
JavaScript / TypeScript now support this natively and you can enable them with lib.d.ts
: https://basarat.gitbooks.io/typescript/docs/types/lib.d.ts.html along with a polyfill if you want
Lodash https://lodash.com/docs#isInteger (since 4.0.0) has function to check if variable is an integer:
_.isInteger(3);
// ? true
_.isInteger(Number.MIN_VALUE);
// ? false
_.isInteger(Infinity);
// ? false
_.isInteger('3');
// ? false
It's the "null coalescing operator", added in php 7.0. The definition of how it works is:
It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
So it's actually just isset()
in a handy operator.
Those two are equivalent1:
$foo = $bar ?? 'something';
$foo = isset($bar) ? $bar : 'something';
Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce
In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op
And original RFC https://wiki.php.net/rfc/isset_ternary
EDIT: As this answer gets a lot of views, little clarification:
1There is a difference: In case of ??
, the first expression is evaluated only once, as opposed to ? :
, where the expression is first evaluated in the condition section, then the second time in the "answer" section.
Uncheck this in Windows Explorer.
"Hide file type extensions for known types"
This is because require()
does not exist in the browser/client-side JavaScript.
Now you're going to have to make some choices about your client-side JavaScript script management.
You have three options:
<script>
tag.CommonJS client side-implementations include (most of them require a build step before you deploy):
You can read more about my comparison of Browserify vs (deprecated) Component.
AMD implementations include:
Note, in your search for choosing which one to go with, you'll read about Bower. Bower is only for package dependencies and is unopinionated on module definitions like CommonJS and AMD.
I had the same problem and it was really annoying each time with the terminal. I run the command to the terminal and it was fixed
For those try to remove nvm from brew
it may not be enough to just brew uninstall nvm
if you see npm prefix is still /usr/local, run this command
sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}
You can try this code:
$time = '10:09';
echo date( 'H:i', strtotime( '+1 hour' , strtotime($time) ) );
Chain selectors are not limited just to classes, you can do it for both classes and ids.
Classes
.classA.classB {
/*style here*/
}
Class & Id
.classA#idB {
/*style here*/
}
Id & Id
#idA#idB {
/*style here*/
}
All good current browsers support this except IE 6, it selects based on the last selector in the list. So ".classA.classB" will select based on just ".classB".
For your case
li.left.ui-class-selector {
/*style here*/
}
or
.left.ui-class-selector {
/*style here*/
}
Use Below Code for Navigation Bar Color Customization
struct ContentView: View {
@State var msg = "Hello SwiftUI"
init() {
UINavigationBar.appearance().backgroundColor = .systemPink
UINavigationBar.appearance().largeTitleTextAttributes = [
.foregroundColor: UIColor.white,
.font : UIFont(name:"Helvetica Neue", size: 40)!]
// 3.
UINavigationBar.appearance().titleTextAttributes = [
.font : UIFont(name: "HelveticaNeue-Thin", size: 20)!]
}
var body: some View {
NavigationView {
Text(msg)
.navigationBarTitle(Text("NAVIGATION BAR"))
}
}
}
None of these attributes are reliable because per the servlet spec (2.4, 2.5 and 3.0), these attributes are overridden if you include/forward a second time (or if someone calls getNamedDispatcher). I think the only reliable way to get the original request URI/query string is to stick a filter at the beginning of your filter chain in web.xml that sets your own custom request attributes based on request.getRequestURI()/getQueryString() before any forwards/includes take place.
http://www.caucho.com/resin-3.0/webapp/faq.xtp contains an excellent summary of how this works (minus the technical note that a second forward/include messes up your ability to use these attributes).
I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
/**
* Encode an object as url query string parameters
* - includes the leading "?" prefix
* - example input — {key: "value", alpha: "beta"}
* - example output — output "?key=value&alpha=beta"
* - returns empty string when given an empty object
*/
function encodeQueryString(params) {
const keys = Object.keys(params)
return keys.length
? "?" + keys
.map(key => encodeURIComponent(key)
+ "=" + encodeURIComponent(params[key]))
.join("&")
: ""
}
encodeQueryString({key: "value", alpha: "beta"})
//> "?key=value&alpha=beta"
If you have Pillow
installed with scipy
and it is still giving you error then check your scipy
version because it has been removed from scipy since 1.3.0rc1
.
rather install scipy 1.1.0
by :
pip install scipy==1.1.0
check https://github.com/scipy/scipy/issues/6212
The method imread
in scipy.misc
requires the forked package of PIL
named Pillow
. If you are having problem installing the right version of PIL try using imread
in other packages:
from matplotlib.pyplot import imread
im = imread(image.png)
To read jpg
images without PIL
use:
import cv2 as cv
im = cv.imread(image.jpg)
You can try
from scipy.misc.pilutil import imread
instead of from scipy.misc import imread
Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.
Try Run->Show->Expressions
Enter in the name of the array or whatever you're looking for.
<input type="number" step="any">
This worked for me and i think is the easiest way to make the input field accept any decimal number irrespective of how long the decimal part is. Step attribute actually shows the input field how many decimal points should be accepted. E.g, step="0.01" will accept only two decimal points.
for set empty all input such textarea select and input run this code:
$('#message').val('').change();
I think realpath() may be the best way to validate if a path exist http://www.php.net/realpath
Here is an example function:
<?php
/**
* Checks if a folder exist and return canonicalized absolute pathname (long version)
* @param string $folder the path being checked.
* @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
*/
function folder_exist($folder)
{
// Get canonicalized absolute pathname
$path = realpath($folder);
// If it exist, check if it's a directory
if($path !== false AND is_dir($path))
{
// Return canonicalized absolute pathname
return $path;
}
// Path/folder does not exist
return false;
}
Short version of the same function
<?php
/**
* Checks if a folder exist and return canonicalized absolute pathname (sort version)
* @param string $folder the path being checked.
* @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
*/
function folder_exist($folder)
{
// Get canonicalized absolute pathname
$path = realpath($folder);
// If it exist, check if it's a directory
return ($path !== false AND is_dir($path)) ? $path : false;
}
Output examples
<?php
/** CASE 1 **/
$input = '/some/path/which/does/not/exist';
var_dump($input); // string(31) "/some/path/which/does/not/exist"
$output = folder_exist($input);
var_dump($output); // bool(false)
/** CASE 2 **/
$input = '/home';
var_dump($input);
$output = folder_exist($input); // string(5) "/home"
var_dump($output); // string(5) "/home"
/** CASE 3 **/
$input = '/home/..';
var_dump($input); // string(8) "/home/.."
$output = folder_exist($input);
var_dump($output); // string(1) "/"
Usage
<?php
$folder = '/foo/bar';
if(FALSE !== ($path = folder_exist($folder)))
{
die('Folder ' . $path . ' already exist');
}
mkdir($folder);
// Continue do stuff
This may help someone visiting this question.
I had an issue where it was slow only in very large files. When opening braces such as {
or after completing a type, such as decimal
it would hang.
This was resolved by disabling the "Show a completion list after every character is typed" setting in Options => Text Editor => C# => Intellisense
I had same issue, was due to multiple copies of ssl.conf In /etc/httpd/conf.d - There should only be one.
There are a couple of options I can think of.
array[100]
without having to walk through 1-99
first. And it might not be that handy for you to use either.It is hard to say what option would be best in your situation. Simply creating a large array is ofcourse one of the easiest solutions and shouldn't give you much problems unless it's really large.
using position:fixed
alone is just fine when you don't have a header or logo at the top of your page. This solution will take into account the how far the window has scrolled, and moves the div when you scrolled past your header. It will then lock it back into place when you get to the top again.
if($(window).scrollTop() > Height_of_Header){
//begin to scroll
$("#div").css("position","fixed");
$("#div").css("top",0);
}
else{
//lock it back into place
$("#div").css("position","relative");
}
As far as I know in XP, yes you must use some other app to actually save it.
Vista comes with the Snipping tool, that simplifies the process a bit!
The solution is in your build.gradle change this block:
allprojects {
repositories {
jcenter()
google()
}
}
to google in first position :
allprojects {
repositories {
google()
jcenter()
}
}
Have you copied classes12.jar in lib folder of your web application and set the classpath in eclipse.
Right-click project in Package explorer Build path -> Add external archives...
Select your ojdbc6.jar archive
Press OK
Or
Go through this link and read and do carefully.
The library should be now referenced in the "Referenced Librairies" under the Package explorer. Now try to run your program again.
Solution for me in VS2017 (Under Tools | Options ... )
I changed the path to: C:\Program Files\nodejs
I found Visual Binary Diff was what I was looking for, available on:
Ubuntu:
sudo apt install vbindiff
Arch Linux:
sudo pacman -S vbindiff
Mac OS X via MacPorts:
port install vbindiff
Mac OS X via Homebrew:
brew install vbindiff
simply use this in your imagebutton layout
android:background="@null"
using
android:background="@android:color/transparent
or
btn.setBackgroundColor(Color.TRANSPARENT);
doesn't give perfect transparency
The Starter Trade-offs sheet of my comparison spreadsheet has comprehensive one-on-one comparisons between each generator. So no more need to distortedly cherry-pick great things to say about your favorite.
Here is the one between generator-angular-fullstack and MEAN.js. The percentages are values for each benefit based on my personal weightings, where a perfect generator would be 100%
generator- angular- fullstack offers 8% that MEANJS.org doesn't
MeanJS.org. offers 9% that generator-angular-fullstack doesn't
Here is the one between MEAN.io and MEAN.js in a more readable format
<table border="1" cellpadding="10"><tbody><tr><td valign="top" width="33%"><br><br><h1>MeanJS.org. provides these benefits that MEAN.io. doesn't</h1><br><br><b>Help</b>:<br> * Dedicated/searchable user group for questions, using github issues<br> * There's a book about it<br><b>File Organization</b>:<br> * Basic sourcecode organization, module(->submodule)->side<br> * Module directories hold directives<br><b>Code Modularization</b>:<br> * Approach to AngularJS modules, Only one module definition per file<br> * Approach to AngularJS modules, Don’t alter a module other than where it is defined<br><b>Model</b>:<br> * Object-relational mapping<br> * Server-side validation, server-side example<br> * Client side validation, using Angular 1.3<br><b>View</b>:<br> * Approach to AngularJS views, Directives start with "data-"<br> * Approach to data readiness, Use ng-init<br><b>Control</b>:<br> * Approach to frontend routing or state changing, URLs start with '#!'<br> * Approach to frontend routing or state changing, Use query parameters to store route state<br><b>Support for things</b>:<br> * Languages, LESS<br> * Languages, SASS<br><b>Syntax, language and coding</b>:<br> * JavaScript 5 best practices, Don't use "new"<br><b>Testing</b>:<br> * Testing, using Mocha<br> * End-to-end tests<br> * End-to-end tests, using Protractor<br> * Continuous integration (CI), using Travis<br><b>Development and debugging</b>:<br> * Command line interface (CLI), using Yeoman<br><b>Build</b>:<br> * Build configurations file(s)<br> * Deployment automation, using Azure<br> * Deployment automation, using Digital Ocean, screencast of it<br> * Deployment automation, using Heroku, screencast of it<br><b>Code Generation</b>:<br> * Input application profile<br> * Quick install?<br> * Options for making subcomponents<br> * config generator<br> * controller (client side) generator<br> * directive generator<br> * filter generator<br> * route (client side) generator<br> * service (client side) generator<br> * test - client side<br> * view or view partial generator<br> * controller (server side) generator<br> * model (server side) generator<br> * route (server side) generator<br> * test (server side) generator<br><b>Implemented Functionality</b>:<br> * Account Management, Forgotten Password with Resetting<br> * Chat<br> * CSV processing<br> * E-mail sending system<br> * E-mail sending system, using Nodemailer<br> * E-mail sending system, using its own e-mail implementation<br> * Menus system, state-based<br> * Paypal integration<br> * Responsive design<br> * Social connections management page<br><b>Performance</b>:<br> * Creates a favicon<br><b>Security</b>:<br> * Safe from IP Spoofing<br> * Authorization, Access Contol List (ACL)<br> * Authentication, Cookie<br> * Websocket and RESTful http share security policies<br><br><br></td><td valign="top" width="33%"><br><br><h1>MEAN.io. provides these benefits that MeanJS.org. doesn't</h1><br><br><b>Quality</b>:<br> * Sponsoring company<br><b>Help</b>:<br> * Docs with flatdoc<br><b>Code Modularization</b>:<br> * Share code between projects<br> * Module manager<br><b>View</b>:<br> * Approach to data readiness, Use state.resolve()<br><b>Control</b>:<br> * Approach to frontend code loading, Use AMD with Require.js<br> * Approach to frontend code loading, using wiredep<br> * Approach to error handling, Server-side logging<br><b>Client/Server Communication</b>:<br> * Centralized event handling<br> * Approach to XHR calls, using $http and $q<br><b>Syntax, language and coding</b>:<br> * JavaScript 5 best practices, Wrap code in an IIFE (SEAF, SIAF)<br><b>Development and debugging</b>:<br> * API introspection report and testing interface, using Swagger<br> * Command line interface (CLI), using Independent command line interface<br><b>Build</b>:<br> * Development build, add IIFEs (SEAF, SIAF) to executable copies of code<br> * Deployment automation<br> * Deployment automation, using Heroku<br><b>Code Generation</b>:<br> * Scaffolding undo (mean package -d <name>)<br> * FEATURE (a.k.a. module, entity) generator, Menu items added for new features<br><b>Implemented Functionality</b>:<br> * Admin page for users and roles<br> * Content Management System (Use special data-bound directives in your templates.<br>Switch to edit mode and you can edit the values right where you see them)<br> * File Upload<br> * i18n, localization<br> * Menus system, submenus<br> * Search<br> * Search, actually works with backend API<br> * Search, using Elastic Search<br> * Styles, using Bootstrap, using UI Bootstrap AngularJS directives<br> * Text (WYSIWYG) Editor<br> * Text (WYSIWYG) Editor, using medium-editor<br><b>Performance</b>:<br> * Instrumentation, server-side<br><b>Security</b>:<br> * Serverside authenticated route restriction<br> * Authentication, using Oauth, Link multiple Oauth strategies to one account<br> * Authentication, JSON Web Token (JWT)<br><br><br></td><td valign="top" width="33%"><br><br><h1>MEAN.io. and MeanJS.org. both provide these benefits</h1><br><br><b>Quality</b>:<br> * Version Control, using git<br><b>Platforms</b>:<br> * Client-side JS Framework, using AngularJS<br> * Frontend Server/ Framework, using Node.JS<br> * Frontend Server/ Framework, using Node.JS, using Express<br> * API Server/ Framework, using NodeJS<br> * API Server/ Framework, using NodeJS, using Express<br><b>Help</b>:<br> * Dedicated/searchable user group for questions<br> * Dedicated/searchable user group for questions, using Google Groups<br> * Dedicated/searchable user group for questions, using Facebook<br> * Dedicated/searchable user group for questions, response time mostly under a day<br> * Example application<br> * Tutorial screencast in English<br> * Tutorial screencast in English, using Youtube<br> * Dedicated chatroom<br><b>File Organization</b>:<br> * Basic sourcecode organization, module(->submodule)->side, with type subfolders<br> * Module directories hold controllers<br> * Module directories hold services<br> * Module directories hold templates<br> * Module directories hold unit tests<br> * Separate route configuration files for each module<br><b>Code Modularization</b>:<br> * Modularized Functionality<br> * Approach to AngularJS modules, No global 'app' module variable<br> * Approach to AngularJS modules, No global 'app' module variable without an IIFE<br><b>Model</b>:<br> * Setup of persistent storage<br> * Setup of persistent storage, using NoSQL db<br> * Setup of persistent storage, using NoSQL db, using MongoDB<br><b>View</b>:<br> * No XHR calls in controllers<br> * Templates, using Angular directives<br> * Approach to data readiness, prevents Flash of Unstyled/compiled Content (FOUC)<br><b>Control</b>:<br> * Approach to frontend routing or state changing, example of it<br> * Approach to frontend routing or state changing, State-based routing<br> * Approach to frontend routing or state changing, State-based routing, using ui-router<br> * Approach to frontend routing or state changing, HTML5 Mode<br> * Approach to frontend code loading, using angular.bootstrap()<br><b>Client/Server Communication</b>:<br> * Serve status codes only as responses<br> * Accept nested, JSON parameters<br> * Add timer header to requests<br> * Support for signed and encrypted cookies<br> * Serve URLs based on the route definitions<br> * Can serve headers only<br> * Approach to XHR calls, using JSON<br> * Approach to XHR calls, using $resource (angular-resource)<br><b>Support for things</b>:<br> * Languages, JavaScript (server side)<br> * Languages, Swig<br><b>Syntax, language and coding</b>:<br> * JavaScript 5 best practices, Use 'use strict'<br><b>Tool Configuration/customization</b>:<br> * Separate runtime configuration profiles<br><b>Testing</b>:<br> * Testing, using Jasmine<br> * Testing, using Karma<br> * Client-side unit tests<br> * Continuous integration (CI)<br> * Automated device testing, using Live Reload<br> * Server-side integration & unit tests<br> * Server-side integration & unit tests, using Mocha<br><b>Development and debugging</b>:<br> * Command line interface (CLI)<br><b>Build</b>:<br> * Build-time Dependency Management, using npm<br> * Build-time Dependency Management, using bower<br> * Build tool / Task runner, using Grunt<br> * Build tool / Task runner, using gulp<br> * Development build, script<br> * Development build, reload build script file upon change<br> * Development build, copy assets to build or dist or target folder<br> * Development build, html page processing<br> * Development build, html page processing, inject references by searching directories<br> * Development build, html page processing, inject references by searching directories, injects js references<br> * Development build, html page processing, inject references by searching directories, injects css references<br> * Development build, LESS/SASS/etc files are linted, compiled<br> * Development build, JavaScript style checking<br> * Development build, JavaScript style checking, using jshint or jslint<br> * Development build, run unit tests<br> * Production build, script<br> * Production build, concatenation (aggregation, globbing, bundling) (If you add debug:true to your config/env/development.js the will not be <br>uglified)<br> * Production build, minification<br> * Production build, safe pre-minification, using ng-annotate<br> * Production build, uglification<br> * Production build, make static pages for SEO<br><b>Code Generation</b>:<br> * FEATURE (a.k.a. module, entity) generator (README.md<br>feature css<br>routes<br>controller<br>view<br>additional menu item)<br><b>Implemented Functionality</b>:<br> * 404 Page<br> * 500 Page<br> * Account Management<br> * Account Management, register/login/logout<br> * Account Management, is password manager friendly<br> * Front-end CRUD<br> * Full-stack CRUD<br> * Full-stack CRUD, with Read<br> * Full-stack CRUD, with Create, Update and Delete<br> * Google Analytics<br> * Menus system<br> * Realtime data sync<br> * Realtime data sync, using socket.io<br> * Styles, using Bootstrap<br><b>Performance</b>:<br> * Javascript performance thing<br> * Javascript performance thing, using lodash<br> * One event-loop thread handles all requests<br> * Configurable response caching (Express plugin<br><b>https</b>://www.npmjs.org/package/apicache)<br> * Clustered HTTP sessions<br><b>Security</b>:<br> * JavaScript obfuscation<br> * https<br> * Authentication, using Oauth<br> * Authentication, Basic (With Passport or others)<br> * Authentication, Digest (With Passport or others)<br> * Authentication, Token (With Passport or others)<br></td></tr></tbody></table>
_x000D_
Why I prefer Fragment over Activity in ALL CASES.
Activity is expensive. In Fragment, views and property states are separated - whenever a fragment is in backstack
, its views will be destroyed. So you can stack much more Fragments than Activity.
Backstack
manipulation. With FragmentManager
, it's easy to clear all the Fragments, insert more than on Fragments and etcs. But for Activity, it will be a nightmare to manipulate those stuff.
A much predictable lifecycle. As long as the host Activity is not recycled. the Fragments in the backstack will not be recycled. So it's possible to use FragmentManager::getFragments()
to find specific Fragment (not encouraged).
For a bit more explanation: keep in mind that the "I" in "api" is interface. The slf4j-api jar only holds the needed interfaces (actually LoggerFactory is an abstract class). You also need the actual implementations (an example of which, as noted above, can be found in slf4j-simple). If you look in the jar, you'll find the required classes under the "org.slf4j.impl" package.
Yes, you have to copy all 387 constructors. You can do some reuse by redirecting them:
public Bar(int i): base(i) {}
public Bar(int i, int j) : base(i, j) {}
but that's the best you can do.
If you can provide your image in SVG format and if it is an icon and not a photo so it can be animated with SMIL animations, then it would be definitely the superior alternative to gif images (or even other formats).
SVG images, like other image files, could be used with either standard markup or HTML <img>
element:
![image description](the_path_to/image.svg)
<img src="the_path_to/image.svg" width="128"/>
I've found that for bigger arrays (~100k elements), it actually pays to simply iterate the array with a humble for
loop, performing ~30% better than Math.max.apply()
:
function mymax(a)
{
var m = -Infinity, i = 0, n = a.length;
for (; i != n; ++i) {
if (a[i] > m) {
m = a[i];
}
}
return m;
}
I simple used Eval(string)
and it evaluated as Double.
CSS selector:
Use a CSS selector of img[src='images/toolbar/b_edit.gif']
This says select element(s) with img
tag with attribute src
having value of 'images/toolbar/b_edit.gif'
CSS query:
VBA:
You can apply the selector with the .querySelector
method of document
.
IE.document.querySelector("img[src='images/toolbar/b_edit.gif']").Click
How about writing out some HTML tags and some CSS if you're outputting this to the browser?
echo '<span style="color:#AFA;text-align:center;">Request has been sent. Please wait for my reply!</span>';
Won't work from console though, only through browser.
These are function annotations covered in PEP 3107. Specifically, the ->
marks the return function annotation.
Examples:
>>> def kinetic_energy(m:'in KG', v:'in M/S')->'Joules':
... return 1/2*m*v**2
...
>>> kinetic_energy.__annotations__
{'return': 'Joules', 'v': 'in M/S', 'm': 'in KG'}
Annotations are dictionaries, so you can do this:
>>> '{:,} {}'.format(kinetic_energy(20,3000),
kinetic_energy.__annotations__['return'])
'90,000,000.0 Joules'
You can also have a python data structure rather than just a string:
>>> rd={'type':float,'units':'Joules','docstring':'Given mass and velocity returns kinetic energy in Joules'}
>>> def f()->rd:
... pass
>>> f.__annotations__['return']['type']
<class 'float'>
>>> f.__annotations__['return']['units']
'Joules'
>>> f.__annotations__['return']['docstring']
'Given mass and velocity returns kinetic energy in Joules'
Or, you can use function attributes to validate called values:
def validate(func, locals):
for var, test in func.__annotations__.items():
value = locals[var]
try:
pr=test.__name__+': '+test.__docstring__
except AttributeError:
pr=test.__name__
msg = '{}=={}; Test: {}'.format(var, value, pr)
assert test(value), msg
def between(lo, hi):
def _between(x):
return lo <= x <= hi
_between.__docstring__='must be between {} and {}'.format(lo,hi)
return _between
def f(x: between(3,10), y:lambda _y: isinstance(_y,int)):
validate(f, locals())
print(x,y)
Prints
>>> f(2,2)
AssertionError: x==2; Test: _between: must be between 3 and 10
>>> f(3,2.1)
AssertionError: y==2.1; Test: <lambda>
update July/2017: tested and worked
sudo ln -s /usr/local/mysql-5.5.25-osx10.6-x86_64/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
That worked for me. I installed MySQL from a dmg file.
I think the best and simplest solution is (KISS):
double i = 348842;
double i2 = i/60000;
float k = (float) Math.round(i2 * 100) / 100;
@media queries serve this purpose. Here's an example:
@media only screen and (max-width: 991px) and (min-width: 769px){
/* CSS that should be displayed if width is equal to or less than 991px and larger
than 768px goes here */
}
@media only screen and (max-width: 991px){
/* CSS that should be displayed if width is equal to or less than 991px goes here */
}
{{ $usersType or '' }}
is working fine. The problem here is your foreach loop:
@foreach( $usersType as $type )
<input type="checkbox" class='default-checkbox'> <span>{{ $type->type }}</span>
@endforeach
I suggest you put this in an @if()
:
@if(isset($usersType))
@foreach( $usersType as $type )
<input type="checkbox" class='default-checkbox'> <span>{{ $type->type }}</span>
@endforeach
@endif
You can also use @forelse. Simple and easy.
@forelse ($users as $user)
<li>{{ $user->name }}</li>
@empty
<p>No users</p>
@endforelse
If the number of arguments should be an exact number (less or equal to 9), then this is a simple way to check it:
if "%2" == "" goto args_count_wrong
if "%3" == "" goto args_count_ok
:args_count_wrong
echo I need exactly two command line arguments
exit /b 1
:args_count_ok
You need to use AND statement in your formula
=IF(AND(IF(NOT(ISBLANK(Q2));TRUE;FALSE);Q2<=R2);"1";"0")
And if both conditions are met, return 1.
You could also add more conditions in your AND statement.
Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:
sudo apt-get install bison flex
There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.
If you have date in DateTime
variable then its a DateTime
object and doesn't contain any format. Formatted date are expressed as string
when you call DateTime.ToString
method and provide format in it.
Lets say you have two DateTime
variable, you can use the compare method for comparision,
DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 2, 0, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;
if (result < 0)
relationship = "is earlier than";
else if (result == 0)
relationship = "is the same time as";
else
relationship = "is later than";
Code snippet taken from msdn.
This should technically be achievable using window.location.reload()
:
HTML:
<button (click)="refresh()">Refresh</button>
TS:
refresh(): void {
window.location.reload();
}
Update:
Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload()
is executed.
Microsoft Outlook 2002 and above removes "extra line breaks" from text messages by default (kb308319). That is, Outlook seems to simply ignore line feed and/or carriage return sequences in text messages, running all of the lines together.
This can cause problems if you're trying to write code that will automatically generate an email message to be read by someone using Outlook.
For example, suppose you want to supply separate pieces of information each on separate lines for clarity, like this:
Transaction needs attention!
PostedDate: 1/30/2009
Amount: $12,222.06
TransID: 8gk288g229g2kg89
PostalCode: 91543
Your Outlook recipient will see the information all smashed together, as follows:
Transaction needs attention! PostedDate: 1/30/2009 Amount: $12,222.06 TransID: 8gk288g229g2kg89 ZipCode: 91543
There doesn't seem to be an easy solution. Alternatives are:
You can do more than just fall through in C#, but you must utilize the "dreaded" goto statement. For example:
switch (whatever)
{
case 2:
Result.Write( "Subscribe" );
break;
case 1:
Result.Write( "Un" );
goto case 2;
}
Add another option, maybe not the most lightweight.
dayjs.extend(dayjs_plugin_customParseFormat)
console.log(dayjs('2018-09-06 17:00:00').format( 'YYYY-MM-DDTHH:mm:ss.000ZZ'))
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/plugin/customParseFormat.js"></script>
_x000D_
This is a perfect use-case for DISTINCT ON
- a Postgres specific extension of the standard DISTINCT
:
SELECT DISTINCT ON (category)
id -- , category, date -- any other column (expression) from the same row
FROM tbl
ORDER BY category, date DESC;
Careful with descending sort order. If the column can be NULL, you may want to add NULLS LAST
:
DISTINCT ON
is simple and fast. Detailed explanation in this related answer:
For big tables with many rows per category
consider an alternative approach:
Solution suggested by Prashant worked fine for me.
Tomcat9 Properties > Configure > Startup > Mode = Java Tomcat9 Properties > Configure > Shutdown > Mode = Java
You might want to do this.
input[type=checkbox] {
-ms-transform: scale(2); /* IE */
-moz-transform: scale(2); /* FF */
-webkit-transform: scale(2); /* Safari and Chrome */
-o-transform: scale(2); /* Opera */
padding: 10px;
}
Most answers missing an important point like if you have created csv
file exported from Microsoft Excel on windows and importing the same in linux environment, you will get unexpected result.
the correct syntax would be
load data local infile 'file.csv' into table table fields terminated by ',' enclosed by '"' lines terminated by '\r\n'
here the difference is '\r\n'
as against simply '\n
Your json contains an array, but you're trying to parse it as an object.
This error occurs because objects must start with {
.
You have 2 options:
You can get rid of the ShopContainer
class and use Shop[]
instead
ShopContainer response = restTemplate.getForObject(
url, ShopContainer.class);
replace with
Shop[] response = restTemplate.getForObject(url, Shop[].class);
and then make your desired object from it.
You can change your server to return an object instead of a list
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(list);
replace with
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(
new ShopContainer(list));
Here's one: (check out http://hongouru.blogspot.ie/2011/09/c-ocr-optical-character-recognition.html or http://www.codeproject.com/Articles/41709/How-To-Use-Office-2007-OCR-Using-C for more info)
using MODI;
static void Main(string[] args)
{
DocumentClass myDoc = new DocumentClass();
myDoc.Create(@"theDocumentName.tiff"); //we work with the .tiff extension
myDoc.OCR(MiLANGUAGES.miLANG_ENGLISH, true, true);
foreach (Image anImage in myDoc.Images)
{
Console.WriteLine(anImage.Layout.Text); //here we cout to the console.
}
}
extends
is for extending a class.
implements
is for implementing an interface
The difference between an interface and a regular class is that in an interface you can not implement any of the declared methods. Only the class that "implements" the interface can implement the methods. The C++ equivalent of an interface would be an abstract class (not EXACTLY the same but pretty much).
Also java doesn't support multiple inheritance for classes. This is solved by using multiple interfaces.
public interface ExampleInterface {
public void doAction();
public String doThis(int number);
}
public class sub implements ExampleInterface {
public void doAction() {
//specify what must happen
}
public String doThis(int number) {
//specfiy what must happen
}
}
now extending a class
public class SuperClass {
public int getNb() {
//specify what must happen
return 1;
}
public int getNb2() {
//specify what must happen
return 2;
}
}
public class SubClass extends SuperClass {
//you can override the implementation
@Override
public int getNb2() {
return 3;
}
}
in this case
Subclass s = new SubClass();
s.getNb(); //returns 1
s.getNb2(); //returns 3
SuperClass sup = new SuperClass();
sup.getNb(); //returns 1
sup.getNb2(); //returns 2
Also, note that an @Override
tag is not required for implementing an interface, as there is nothing in the original interface methods to be overridden
I suggest you do some more research on dynamic binding, polymorphism and in general inheritance in Object-oriented programming
This answer is for swift 3.0 -->
first conform to the protocol :
UICollectionViewDelegateFlowLayout
then add these methods :
//this method is for the size of items
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.frame.width/3
let height : CGFloat = 160.0
return CGSize(width: width, height: height)
}
//these methods are to configure the spacing between items
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(0,0,0,0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.
First, create your queue:
Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();
Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):
YourProducer producer = new YourProducer(queue);
and:
YourConsumer consumer = new YourConsumer(queue);
and add stuff to it in your producer:
queue.offer(myObject);
and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):
YourObject myObject = queue.poll();
For more info see the Javadoc
If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.
If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:
Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());
A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.
Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:
BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();
queue.put(myObject); // Blocks until queue isn't full.
YourObject myObject = queue.take(); // Blocks until queue isn't empty.
Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.
Try something like this:
with toupdate as (
select p.*,
(coalesce(max(interfaceid) over (), 0) +
row_number() over (order by (select NULL))
) as newInterfaceId
from prices
)
update p
set interfaceId = newInterfaceId
where interfaceId is NULL
This doesn't quite make them consecutive, but it does assign new higher ids. To make them consecutive, try this:
with toupdate as (
select p.*,
(coalesce(max(interfaceid) over (), 0) +
row_number() over (partition by interfaceId order by (select NULL))
) as newInterfaceId
from prices
)
update p
set interfaceId = newInterfaceId
where interfaceId is NULL
To uninstall Anaconda Fully from your System :
rm -rf ~/miniconda
rm -rf ~/.condarc ~/.conda ~/.continuum
In my case the error was due to incorrect port number (the error is definitely due to incorrect credentials i.e. host/port/dbname/username/password
).
Solution:
.env
file;config/database.php
.Clear cache
php artisan config:cache
Run migration
php artisan migrate
when I add the padding-left property, the width of the DIV changes to 220px
Yes, that is exactly according to the standards. That's how it's supposed to work.
Let's say I create another DIV named anotherdiv exactly the same as newdiv, and put it inside of newdiv but newdiv has no padding and anotherdiv has padding-left: 20px. I get the same thing, newdiv's width will be 220px;
No, newdiv will remain 200px wide.
Here's an update for modern browsers in 2019
let playerSpriteX = 0;_x000D_
_x000D_
document.addEventListener('keyup', (e) => {_x000D_
if (e.code === "ArrowUp") playerSpriteX += 10_x000D_
else if (e.code === "ArrowDown") playerSpriteX -= 10_x000D_
_x000D_
document.getElementById('test').innerHTML = 'playerSpriteX = ' + playerSpriteX;_x000D_
});
_x000D_
Click on this window to focus it, and hit keys up and down_x000D_
<br><br><br>_x000D_
<div id="test">playerSpriteX = 0</div>
_x000D_
Original answer from 2013
window.onkeyup = function(e) {
var key = e.keyCode ? e.keyCode : e.which;
if (key == 38) {
playerSpriteX += 10;
}else if (key == 40) {
playerSpriteX -= 10;
}
}
In the closure you pass to sort
, compare the properties you want to sort by. Like this:
movieArr.sorted { $0.name < $1.name }
or the following in the cases that you want to bypass cases:
movieArr.sorted { $0.name.lowercased() < $1.name.lowercased() }
Sidenote: Typically only types start with an uppercase letter; I'd recommend using name
and date
, not Name
and Date
.
Example, in a playground:
class Movie {
let name: String
var date: Int?
init(_ name: String) {
self.name = name
}
}
var movieA = Movie("A")
var movieB = Movie("B")
var movieC = Movie("C")
let movies = [movieB, movieC, movieA]
let sortedMovies = movies.sorted { $0.name < $1.name }
sortedMovies
sortedMovies
will be in the order [movieA, movieB, movieC]
Swift5 Update
channelsArray = channelsArray.sorted { (channel1, channel2) -> Bool in
let channelName1 = channel1.name
let channelName2 = channel2.name
return (channelName1.localizedCaseInsensitiveCompare(channelName2) == .orderedAscending)
require 'date'
date = DateTime.parse("2011-05-19 10:30:14")
formatted_date = date.strftime('%a %b %d %H:%M:%S %Z %Y')
See strftime() for more information about formatting dates.
Also for openCV in python you can do:
img = cv2.imread('myImage.jpg')
height, width, channels = img.shape
I wrote this pattern:
Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");
And use it in this method:
String escapeSpecialRegexChars(String str) {
return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0");
}
Then you can use it like this, for example:
Pattern toSafePattern(String text)
{
return Pattern.compile(".*" + escapeSpecialRegexChars(text) + ".*");
}
We needed to do that because, after escaping, we add some regex expressions. If not, you can simply use \Q
and \E
:
Pattern toSafePattern(String text)
{
return Pattern.compile(".*\\Q" + text + "\\E.*")
}
if a.Correct
is a bool
flag for the correct answer then you need.
Answer answer = Answers.Single(a => a.Correct);
It looks like you're having a permissions error, based on this message in your output: error: could not create '/lib/python2.7/site-packages/lxml': Permission denied
.
One thing you can try is doing a user install of the package with pip install lxml --user
. For more information on how that works, check out this StackOverflow answer. (Thanks to Ishaan Taylor for the suggestion)
You can also run pip install
as a superuser with sudo pip install lxml
but it is not generally a good idea because it can cause issues with your system-level packages.
Are you trying to submit a form?
Listen to the submit
event instead.
This will handle click
and enter
.
If you must use enter key...
document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
// code for enter
}
});
followings programs will execute,"one number is multiple of another" in
#include<stdio.h>
int main
{
int a,b;
printf("enter any two number\n");
scanf("%d%d",&a,&b);
if (a%b==0)
printf("this is multiple number");
else if (b%a==0);
printf("this is multiple number");
else
printf("this is not multiple number");
return 0;
}
If you place anything in src/main/resources
directory, then by default it will end up in your final *.jar
. If you are referencing it from some other project and it cannot be found on a classpath, then you did one of those two mistakes:
*.jar
is not correctly loaded (maybe typo in the path?)/src/main/resources/conf/settings.properties
is seen on classpath as classpath:conf/settings.properties
MinGW
forked from version 1.3.3 ofCygwin
. Although bothCygwin
andMinGW
can be used to portUNIX
software toWindows
, they have different approaches:Cygwin
aims to provide a completePOSIX layer
that provides emulations of several system calls and libraries that exist onLinux
,UNIX
, and theBSD
variants. ThePOSIX layer
runs on top ofWindows
, sacrificing performance where necessary for compatibility. Accordingly, this approach requiresWindows
programs written withCygwin
to run on top of a copylefted compatibility library that must be distributed with the program, along with the program'ssource code
.MinGW
aims to provide native functionality and performance via directWindows API calls
. UnlikeCygwin
,MinGW
does not require a compatibility layerDLL
and thus programs do not need to be distributed withsource code
.Because
MinGW
is dependent uponWindows API calls
, it cannot provide a fullPOSIX API
; it is unable to compile someUNIX applications
that can be compiled withCygwin
. Specifically, this applies to applications that requirePOSIX
functionality likefork()
,mmap()
orioctl()
and those that expect to be run in aPOSIX environment
. Applications written using across-platform library
that has itself been ported toMinGW
, such asSDL
,wxWidgets
,Qt
, orGTK+
, will usually compile as easily inMinGW
as they would inCygwin
.The combination of
MinGW
andMSYS
provides a small, self-contained environment that can be loaded onto removable media without leaving entries in the registry or files on the computer.Cygwin
Portable provides a similar feature. By providing more functionality,Cygwin
becomes more complicated to install and maintain.It is also possible to
cross-compile Windows applications
withMinGW-GCC under POSIX systems
. This means that developers do not need a Windows installation withMSYS
to compile software that will run onWindows
withoutCygwin
.
(a) wwww.somewebsite.com/a.txt
isn't a 'file URL'. It isn't a URL at all. If you put http://
on the front of it it would be an HTTP URL, which is clearly what you intend here.
(b) FileInputStream
is for files, not URLs.
(c) The way to get an input stream from any URL is via URL.openStream(),
or URL.getConnection().getInputStream(),
which is equivalent but you might have other reasons to get the URLConnection
and play with it first.
I am trying to set a div to a certain percentage height in CSS
Percentage of what?
To set a percentage height, its parent element(*) must have an explicit height. This is fairly self-evident, in that if you leave height as auto
, the block will take the height of its content... but if the content itself has a height expressed in terms of percentage of the parent you've made yourself a little Catch 22. The browser gives up and just uses the content height.
So the parent of the div must have an explicit height
property. Whilst that height can also be a percentage if you want, that just moves the problem up to the next level.
If you want to make the div height a percentage of the viewport height, every ancestor of the div, including <html>
and <body>
, have to have height: 100%
, so there is a chain of explicit percentage heights down to the div.
(*: or, if the div is positioned, the ‘containing block’, which is the nearest ancestor to also be positioned.)
Alternatively, all modern browsers and IE>=9 support new CSS units relative to viewport height (vh
) and viewport width (vw
):
div {
height:100vh;
}
See here for more info.
try this: (you missed the single quotes)
var floorplanSettings = '@Html.Raw(Json.Encode(Model.FloorPlanSettings))';
To get rid of error:
Type '"text"' is not assignable to type '"json"'.
Use
responseType: 'text' as 'json'
import { HttpClient, HttpHeaders } from '@angular/common/http';
.....
return this.http
.post<string>(
this.baseUrl + '/Tickets/getTicket',
JSON.stringify(value),
{ headers, responseType: 'text' as 'json' }
)
.map(res => {
return res;
})
.catch(this.handleError);
Additional data (in case you have more questions):
FOO: {
for my $i ( @listone ){
for my $j ( @listtwo ){
if ( cond( $i,$j ) ){
last FOO; # --->
# |
} # |
} # |
} # |
} # <-------------------------------
It's simpler than I initially thought.. Basically you have a page that does nothing, until the data you want to send is available (say, a new message arrives).
Here is a really basic example, which sends a simple string after 2-10 seconds. 1 in 3 chance of returning an error 404 (to show error handling in the coming Javascript example)
msgsrv.php
<?php
if(rand(1,3) == 1){
/* Fake an error */
header("HTTP/1.0 404 Not Found");
die();
}
/* Send a string after a random number of seconds (2-10) */
sleep(rand(2,10));
echo("Hi! Have a random number: " . rand(1,10));
?>
Note: With a real site, running this on a regular web-server like Apache will quickly tie up all the "worker threads" and leave it unable to respond to other requests.. There are ways around this, but it is recommended to write a "long-poll server" in something like Python's twisted, which does not rely on one thread per request. cometD is an popular one (which is available in several languages), and Tornado is a new framework made specifically for such tasks (it was built for FriendFeed's long-polling code)... but as a simple example, Apache is more than adequate! This script could easily be written in any language (I chose Apache/PHP as they are very common, and I happened to be running them locally)
Then, in Javascript, you request the above file (msg_srv.php
), and wait for a response. When you get one, you act upon the data. Then you request the file and wait again, act upon the data (and repeat)
What follows is an example of such a page.. When the page is loaded, it sends the initial request for the msgsrv.php
file.. If it succeeds, we append the message to the #messages
div, then after 1 second we call the waitForMsg function again, which triggers the wait.
The 1 second setTimeout()
is a really basic rate-limiter, it works fine without this, but if msgsrv.php
always returns instantly (with a syntax error, for example) - you flood the browser and it can quickly freeze up. This would better be done checking if the file contains a valid JSON response, and/or keeping a running total of requests-per-minute/second, and pausing appropriately.
If the page errors, it appends the error to the #messages
div, waits 15 seconds and then tries again (identical to how we wait 1 second after each message)
The nice thing about this approach is it is very resilient. If the clients internet connection dies, it will timeout, then try and reconnect - this is inherent in how long polling works, no complicated error-handling is required
Anyway, the long_poller.htm
code, using the jQuery framework:
<html>
<head>
<title>BargePoller</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css" media="screen">
body{ background:#000;color:#fff;font-size:.9em; }
.msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}
.old{ background-color:#246499;}
.new{ background-color:#3B9957;}
.error{ background-color:#992E36;}
</style>
<script type="text/javascript" charset="utf-8">
function addmsg(type, msg){
/* Simple helper to add a div.
type is the name of a CSS class (old/new/error).
msg is the contents of the div */
$("#messages").append(
"<div class='msg "+ type +"'>"+ msg +"</div>"
);
}
function waitForMsg(){
/* This requests the url "msgsrv.php"
When it complete (or errors)*/
$.ajax({
type: "GET",
url: "msgsrv.php",
async: true, /* If set to non-async, browser shows page as "Loading.."*/
cache: false,
timeout:50000, /* Timeout in ms */
success: function(data){ /* called when request to barge.php completes */
addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
setTimeout(
waitForMsg, /* Request next message */
1000 /* ..after 1 seconds */
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg, /* Try again after.. */
15000); /* milliseconds (15seconds) */
}
});
};
$(document).ready(function(){
waitForMsg(); /* Start the inital request */
});
</script>
</head>
<body>
<div id="messages">
<div class="msg old">
BargePoll message requester!
</div>
</div>
</body>
</html>
Be sure and use 'get' or 'post' consistantly with your $.ajax call for example.
$.ajax({
type: 'get',
must be met with
app.get('/', function(req, res) {
=============== and for post
$.ajax({ type: 'post',
must be met with
app.post('/', function(req, res) {
You can do shortcut via inline function if you want to simply change the state variable without declaring a new function at top:
<input type="text" onChange={e => this.setState({ text: e.target.value })}/>
Let's say that you wanted to cut the line bbb
and paste it under the line ---
Before:
aaa
bbb
---
After:
aaa
---
bbb
bbb
---
Google has this as a top result for For those who need to find a node with certain text. By way of update, a nodelist is now iterable in modern browsers without having to convert it to an array.
The solution can use forEach like so.
var elList = document.querySelectorAll(".some .selector");
elList.forEach(function(el) {
if (el.innerHTML.indexOf("needle") !== -1) {
// Do what you like with el
// The needle is case sensitive
}
});
This worked for me to do a find/replace text inside a nodelist when a normal selector could not choose just one node so I had to filter each node one by one to check it for the needle.
After a change of ip in our oracle virtual machine, the listener never worked again. Finally these command solved the problem (where 192.168.10.200 is the new ip)
[oracle@oracle admin]$ sqlplus / as sysdba
SQL*Plus: Release 11.2.0.1.0 Production on Tue May 10 12:57:37 2016
Copyright (c) 1982, 2009, Oracle. All rights reserved.
Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> alter system set local_listener='(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.10.200)(PORT=1521))' scope=both;
System altered.
SQL> alter system register;
System altered.
SQL> exit
The info at http://nelenkov.blogspot.com/2012/05/storing-application-secrets-in-androids.html is a fairly pragmatic, but "uses-hidden-android-apis" based approach. It's something to consider when you really can't get around storing credentials/passwords locally on the device.
I've also created a cleaned up gist of that idea at https://gist.github.com/kbsriram/5503519 which might be helpful.
Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness:
return Stream.of(id, name).allMatch(Objects::isNull);
This remains quite easy to maintain while avoiding the reflection hammer. This will return true for null attributes.