You can also mock your property configuration into your test class
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:test-context.xml" })
public class MyTest
{
@Configuration
public static class MockConfig{
@Bean
public Properties myProps(){
Properties properties = new Properties();
properties.setProperty("default.url", "myUrl");
properties.setProperty("property.value2", "value2");
return properties;
}
}
@Value("#{myProps['default.url']}")
private String defaultUrl;
@Test
public void testValue(){
Assert.assertEquals("myUrl", defaultUrl);
}
}
The standard way to find the processing time in ms of a block of code in python 3.x is the following:
import datetime
t_start = datetime.datetime.now()
# Here is the python3 code, you want
# to check the processing time of
t_end = datetime.datetime.now()
print("Time taken : ", (t_end - t_start).total_seconds()*1000, " ms")
for color in ['r', 'b', 'g', 'k', 'm']:
plot(x, y, color=color)
Well, the <head>
tag has nothing to do with the <header>
tag. In the head
comes all the metadata and stuff, while the header
is just a layout component.
And layout comes into body
. So I disagree with you.
Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/
In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.
If you are using PHP Apache server, then you will need to add following in your .htaccess
file:
Header set Access-Control-Allow-Origin "*"
The other answers didn't work for me. I found the answer in their documentation:
http://api.highcharts.com/highcharts#Series
Using this method (see JSFiddle example):
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
});
// the button action
$('#button').click(function() {
chart.series[0].setData([129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4] );
});
Back in the old days of Python, to call a function with arbitrary arguments, you would use apply
:
apply(f,args,kwargs)
apply
still exists in Python2.7 though not in Python3, and is generally not used anymore. Nowadays,
f(*args,**kwargs)
is preferred. The multiprocessing.Pool
modules tries to provide a similar interface.
Pool.apply
is like Python apply
, except that the function call is performed in a separate process. Pool.apply
blocks until the function is completed.
Pool.apply_async
is also like Python's built-in apply
, except that the call returns immediately instead of waiting for the result. An AsyncResult
object is returned. You call its get()
method to retrieve the result of the function call. The get()
method blocks until the function is completed. Thus, pool.apply(func, args, kwargs)
is equivalent to pool.apply_async(func, args, kwargs).get()
.
In contrast to Pool.apply
, the Pool.apply_async
method also has a callback which, if supplied, is called when the function is complete. This can be used instead of calling get()
.
For example:
import multiprocessing as mp
import time
def foo_pool(x):
time.sleep(2)
return x*x
result_list = []
def log_result(result):
# This is called whenever foo_pool(i) returns a result.
# result_list is modified only by the main process, not the pool workers.
result_list.append(result)
def apply_async_with_callback():
pool = mp.Pool()
for i in range(10):
pool.apply_async(foo_pool, args = (i, ), callback = log_result)
pool.close()
pool.join()
print(result_list)
if __name__ == '__main__':
apply_async_with_callback()
may yield a result such as
[1, 0, 4, 9, 25, 16, 49, 36, 81, 64]
Notice, unlike pool.map
, the order of the results may not correspond to the order in which the pool.apply_async
calls were made.
So, if you need to run a function in a separate process, but want the current process to block until that function returns, use Pool.apply
. Like Pool.apply
, Pool.map
blocks until the complete result is returned.
If you want the Pool of worker processes to perform many function calls asynchronously, use Pool.apply_async
. The order of the results is not guaranteed to be the same as the order of the calls to Pool.apply_async
.
Notice also that you could call a number of different functions with Pool.apply_async
(not all calls need to use the same function).
In contrast, Pool.map
applies the same function to many arguments.
However, unlike Pool.apply_async
, the results are returned in an order corresponding to the order of the arguments.
Dictionaries are specifically designed to do super fast key lookups. They are implemented as hashtables and the more entries the faster they are relative to other methods. Using the exception engine is only supposed to be done when your method has failed to do what you designed it to do because it is a large set of object that give you a lot of functionality for handling errors. I built an entire library class once with everything surrounded by try catch blocks once and was appalled to see the debug output which contained a seperate line for every single one of over 600 exceptions!
max-width is the width of the target display area, e.g. the browser; max-device-width is the width of the device's entire rendering area, i.e. the actual device screen.
• If you are using the max-device-width, when you change the size of the browser window on your desktop, the CSS style won't change to different media query setting;
• If you are using the max-width, when you change the size of the browser on your desktop, the CSS will change to different media query setting and you might be shown with the styling for mobiles, such as touch-friendly menus.
By default the android sdk installer path is ~/Library/Android/sdk/
I have found a new version of this that the Typescript compiler is totally okay with, and I think is better because it doesn't require calling a getInstance()
method constantly.
import express, { Application } from 'express';
export class Singleton {
// Define your props here
private _express: Application = express();
private static _instance: Singleton;
constructor() {
if (Singleton._instance) {
return Singleton._instance;
}
// You don't have an instance, so continue
// Remember, to set the _instance property
Singleton._instance = this;
}
}
This does come with a different drawback. If your Singleton
does have any properties, then the Typescript compiler will throw a fit unless you initialize them with a value. That's why I included an _express
property in my example class because unless you initialize it with a value, even if you assign it later in the constructor, Typescript will think it hasn't been defined. This could be fixed by disabling strict mode, but I prefer not to if possible. There is also another downside to this method I should point out, because the constructor is actually getting called, each time it does another instance is technically created, but not accessible. This could, in theory, cause memory leaks.
In your script, this part:
document.getElementById('Noite')
must be returning null
and you are also attempting to set the display
property to an invalid value. There are a couple of possible reasons for this first part to be null
.
You are running the script too early before the document has been loaded and thus the Noite
item can't be found.
There is no Noite
item in your HTML.
I should point out that your use of document.write()
in this case code probably signifies a problem. If the document has already loaded, then a new document.write()
will clear the old content and start a new fresh document so no Noite
item would be found.
If your document has not yet been loaded and thus you're doing document.write()
inline to add HTML inline to the current document, then your document has not yet been fully loaded so that's probably why it can't find the Noite
item.
The solution is probably to put this part of your script at the very end of your document so everything before it has already been loaded. So move this to the end of your body:
document.getElementById('Noite').style.display='block';
And, make sure that there are no document.write()
statements in javascript after the document has been loaded (because they will clear the previous document and start a new one).
In addition, setting the display
property to "display"
doesn't make sense to me. The valid options for that are "block"
, "inline"
, "none"
, "table"
, etc... I'm not aware of any option named "display"
for that style property. See here for valid options for teh display
property.
You can see the fixed code work here in this demo: http://jsfiddle.net/jfriend00/yVJY4/. That jsFiddle is configured to have the javascript placed at the end of the document body so it runs after the document has been loaded.
P.S. I should point out that your lack of braces for your if
statements and your inclusion of multiple statements on the same line makes your code very misleading and unclear.
I'm having a really hard time figuring out what you're asking, but here's a cleaned up version of your code that works which you can also see working here: http://jsfiddle.net/jfriend00/QCxwr/. Here's a list of the changes I made:
var
declarations to your variables (a good habit to always use).if
statement was changed into an if/else which is a lot more efficient and more self-documenting as to what you're doing.if
statement so it absolutely clear which statements are part of the if/else
and which are not.</dd>
tag you were inserting.style.display = '';
to style.display = 'block';
.The code:
<div id="Night" style="display: none;">
<img src="Img/night.png" style="position: fixed; top: 0px; left: 5%; height: auto; width: 100%; z-index: -2147483640;">
<img src="Img/moon.gif" style="position: fixed; top: 0px; left: 5%; height: 100%; width: auto; z-index: -2147483639;">
</div>
<script>
document.write("<dl><dd>");
var day = new Date();
var hr = day.getHours();
if (hr == 0) {
document.write("Meia-noite!<br>Já é amanhã!");
} else if (hr <=5 ) {
document.write(" Você não<br> devia<br> estar<br>dormindo?");
} else if (hr <= 11) {
document.write("Bom dia!");
} else if (hr == 12) {
document.write(" Vamos<br> almoçar?");
} else if (hr <= 17) {
document.write("Boa Tarde");
} else if (hr <= 19) {
document.write(" Bom final<br> de tarde!");
} else if (hr == 20) {
document.write(" Boa Noite");
document.getElementById('Noite').style.display='block';
} else if (hr == 21) {
document.write(" Boa Noite");
document.getElementById('Noite').style.display='none';
} else if (hr == 22) {
document.write(" Boa Noite");
} else if (hr == 23) {
document.write("Ó Meu! Já é quase meia-noite!");
}
document.write("</dl></dd>");
</script>
just mention that - Jan, 2020 Xcode 11.3/iOS13
Swift 5
From the CoreGraphics source code
public struct CGFloat {
/// The native type used to store the CGFloat, which is Float on
/// 32-bit architectures and Double on 64-bit architectures.
public typealias NativeType = Double
In XML do like this
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="vertical"
>
<RelativeLayout
android:id="@+id/REFReLayTellFriend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<EditText
android:id="@+id/etpass1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:bottomLeftRadius="10dp"
android:bottomRightRadius="50dp"
android:fontFamily="@font/frutiger"
android:gravity="start"
android:inputType="textPassword"
android:hint="@string/regpass_pass1"
android:padding="20dp"
android:paddingBottom="10dp"
android:textColor="#000000"
android:textColorHint="#d3d3d3"
android:textSize="14sp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp"/>
<ImageButton
android:id="@+id/imgshowhide1"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="10dp"
android:background="@drawable/showpass"
android:layout_alignRight="@+id/etpass1"/>
</RelativeLayout>
boolean show=true;
//on image click inside password do this
if(show){
imgshowhide2.setBackgroundResource(0);
imgshowhide2.setBackgroundResource(R.drawable.hide);
etpass2.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
etpass2.setSelection(etpass2.getText().length());
show=false;
}else{
imgshowhide2.setBackgroundResource(0);
imgshowhide2.setBackgroundResource(R.drawable.showpass);
//etpass1.setInputType(InputType.TYPE_TEXT);
etpass2.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
etpass2.setSelection(etpass2.getText().length());
show=true;
}
OK, got it working with this (creating the UIImageView programmatically):
var imageViewObject :UIImageView
imageViewObject = UIImageView(frame:CGRectMake(0, 0, 600, 600))
imageViewObject.image = UIImage(named:"afternoon")
self.view.addSubview(imageViewObject)
self.view.sendSubviewToBack(imageViewObject)
$dateTime = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
echo $dateTime->modify("+10 minutes")->format("H:i:s A");
Both of the examples immediately above didn't work for me. Opening a recordset on the table and adding a record does work to add the record, except:
myLong = CLng(rs!AutoNumberField)
returns Null if put between rs.AddNew and rs.Update. If put after rs.Update, it does return something, but it's always wrong, and always the same incorrect value. Looking at the table directly after adding the new record shows an autonumber field value different than the one returned by the above statement.
myLong = DLookup("AutoNumberField","TableName","SomeCriteria")
will work properly, as long as it's done after rs.Update, and there are any other fields which can uniquely identify the record.
To begin with, your problem is that you use the method `compareTo() which is case sensitive. That means that the Capital letters are sorted apart from the lower case. The reason is that it translated in Unicode where the capital letters are presented with numbers which are less than the presented number of lower case. Thus you should use `compareToIgnoreCase()` as many also mentioned in previous posts.
This is my full example approach of how you can do it effecively
After you create an object of the Comparator you can pass it in this version of `sort()` which defined in java.util.Arrays.
static<T>void sort(T[]array,Comparator<?super T>comp)
take a close look at super. This makes sure that the array which is passed into is combatible with the type of comparator.
The magic part of this way is that you can easily sort the array of strings in Reverse order you can easily do by:
return strB.compareToIgnoreCase(strA);
import java.util.Comparator;
public class IgnoreCaseComp implements Comparator<String> {
@Override
public int compare(String strA, String strB) {
return strA.compareToIgnoreCase(strB);
}
}
import java.util.Arrays;
public class IgnoreCaseSort {
public static void main(String[] args) {
String strs[] = {" Hello ", " This ", "is ", "Sorting ", "Example"};
System.out.print("Initial order: ");
for (String s : strs) {
System.out.print(s + " ");
}
System.out.println("\n");
IgnoreCaseComp icc = new IgnoreCaseComp();
Arrays.sort(strs, icc);
System.out.print("Case-insesitive sorted order: ");
for (String s : strs) {
System.out.print(s + " ");
}
System.out.println("\n");
Arrays.sort(strs);
System.out.print("Default, case-sensitive sorted order: ");
for (String s : strs) {
System.out.print(s + " ");
}
System.out.println("\n");
}
}
run:
Initial order: Hello This is Sorting Example
Case-insesitive sorted order: Hello This Example is Sorting
Default, case-sensitive sorted order: Hello This Example Sorting is
BUILD SUCCESSFUL (total time: 0 seconds)
The method compareToIgnoreCase()
, although it works well with many occasions(just like compare string in english),it will wont work well with all languages and locations. This automatically makes it an unfit choice for use. To make sure that it will be suppoorted everywhere you should use compare()
from java.text.Collator.
You can find a collator for your location by calling the method getInstance()
. After that you should set this Collator's strength property. This can be done with the setStrength()
method together with Collator.PRIMARY
as parameter. With this alternative choise the IgnocaseComp can be written just like below. This version of code will generate the same output independently of the location
import java.text.Collator;
import java.util.Comparator;
//this comparator uses one Collator to determine
//the right sort usage with no sensitive type
//of the 2 given strings
public class IgnoreCaseComp implements Comparator<String> {
Collator col;
IgnoreCaseComp() {
//default locale
col = Collator.getInstance();
//this will consider only PRIMARY difference ("a" vs "b")
col.setStrength(Collator.PRIMARY);
}
@Override
public int compare(String strA, String strB) {
return col.compare(strA, strB);
}
}
PHP version > 5.0 has a nice SoapClient integrated. Which doesn't require to parse response xml. Here's a quick example
$client = new SoapClient("http://path.to/wsdl?WSDL");
$res = $client->SoapFunction(array('param1'=>'value','param2'=>'value'));
echo $res->PaymentNotification->payment;
You could use Synonyms part in the database.
Then in view wizard from Synonyms tab find your saved synonyms and add to view and set inner join simply.
if ($('input:text').val().length == 0) {
$(this).parents('p').addClass('warning');
}
In SQL Server 2005 and later use ROW_NUMBER()
:
SELECT * FROM
( SELECT p.*,
ROW_NUMBER() OVER(PARTITION BY Partid ORDER BY PriceDate DESC) AS rn
FROM MyPrice AS p ) AS t
WHERE rn=1
Try this code:--
UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(3,2, 20, 25)];
imv.image=[UIImage imageNamed:@"arrow2.png"];
[cell addSubview:imv];
[imv release];
One .Net build with x86/x64 Dependencies
While all other answers give you a solution to make different Builds according to the platform, I give you an option to only have the "AnyCPU" configuration and make a build that works with your x86 and x64 dlls.
You have to write some plumbing code for this.
Resolution of correct x86/x64-dlls at runtime
Steps:
<ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>None</ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>
Add this postbuild script to your startup project, use and modify the paths of this script sp that it copies all your x86/x64 dlls in corresponding subfolders of your build bin\x86\ bin\x64\
xcopy /E /H /R /Y /I /D $(SolutionDir)\YourPathToX86Dlls $(TargetDir)\x86
xcopy /E /H /R /Y /I /D $(SolutionDir)\YourPathToX64Dlls $(TargetDir)\x64
--> When you would start application now, you get an exception that the assembly could not be found.
Register the AssemblyResolve event right at the beginning of your application entry point
AppDomain.CurrentDomain.AssemblyResolve += TryResolveArchitectureDependency;
withthis method:
/// <summary>
/// Event Handler for AppDomain.CurrentDomain.AssemblyResolve
/// </summary>
/// <param name="sender">The app domain</param>
/// <param name="resolveEventArgs">The resolve event args</param>
/// <returns>The architecture dependent assembly</returns>
public static Assembly TryResolveArchitectureDependency(object sender, ResolveEventArgs resolveEventArgs)
{
var dllName = resolveEventArgs.Name.Substring(0, resolveEventArgs.Name.IndexOf(","));
var anyCpuAssemblyPath = $".\\{dllName}.dll";
var architectureName = System.Environment.Is64BitProcess ? "x64" : "x86";
var assemblyPath = $".\\{architectureName}\\{dllName}.dll";
if (File.Exists(assemblyPath))
{
return Assembly.LoadFrom(assemblyPath);
}
return null;
}
Benefits:
Drawbacks: - No errors at compile time when x86/x64 dlls do not match. - You should still run test in both modes!
Optionally create a second executable that is exclusive for x64 architecture with Corflags.exe in postbuild script
Other Variants to try out: - You don't need the AssemblyResolve event handler if you assure that the right dlls are copied to your binary folder at start (Evaluate Process architecture -> move corresponding dlls from x64/x86 to bin folder and back.) - In Installer evaluate architecture and delete binaries for wrong architecture and move the right ones to the bin folder.
$recipients = "Marcel <[email protected]>, Marcelt <[email protected]>"
is type of string
you need pass to send-mailmessage
a string[]
type (an array):
[string[]]$recipients = "Marcel <[email protected]>", "Marcelt <[email protected]>"
I think that not casting to string[] do the job for the coercing rules of powershell:
$recipients = "Marcel <[email protected]>", "Marcelt <[email protected]>"
is object[]
type but can do the same job.
As shown below, range
only supports integers:
>>> range(15.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: range() integer end argument expected, got float.
>>> range(15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>>
However, c/10
is a float because /
always returns a float.
Before you put it in range
, you need to make c/10
an integer. This can be done by putting it in int
:
range(int(c/10))
or by using //
, which returns an integer:
range(c//10)
It's too late to answer for this question. But if someone is searching for this answer now I've made it to run with no errors.
First of all make sure to download and add maven to path. [ mvn --version
] will give you version specifications of it if you have added to the path correctly.
Now , add following code to the maven project [ pom.xml
] , in the following code replace with your own main file entry point for eg [ com.example.test.Test ].
<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<mainClass>
your_package_to_class_that_contains_main_file .MainFileName</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
Now go to the command line [CMD
] in your project and type mvn package
and it will generate a jar file as something like ProjectName-0.0.1-SNAPSHOT.jar
under target
directory.
Now navigate to the target directory by cd target
.
Finally type java -jar jar-file-name.jar
and yes this should work successfully if you don't have any errors in your program.
You can also use plt.setp
as follows:
import matplotlib.pyplot as plt
import seaborn as sns
plot=sns.barplot(data=df, x=" ", y=" ")
plt.setp(plot.get_xticklabels(), rotation=90)
to rotate the labels 90 degrees.
In general, when you need a character that is "special" in regexes, just prefix it with a \
. So a literal [
would be \[
.
The documentation for css() says that setting the style property to the empty string will remove that property if it does not reside in a stylesheet:
Setting the value of a style property to an empty string — e.g.
$('#mydiv').css('color', '')
— removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's.css()
method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or<style>
element.
Since your styles are inline, you can write:
$(selector).css("-moz-user-select", "");
I found a very easy process to find you MD5, SHA-1 fingerprint using Android Studio.
- Run your project
- Go to Gradle Menu (Menu: View -> Tool Windows -> Gradle)
- Go to 'signingReport' in Gradle window. (Your project -> Tasks -> android -> signingReport)
- Run it. (Using double-click or Ctrl + Shift + F10)
- In Run window you will find all info.
It's work only for debug mode. In realease mode I can not see sha-1.
Here result of gradlew signingReport
Variant: release
Config: none
----------
Variant: releaseUnitTest
Config: none
----------
Variant: debug
Config: debug
Store: path\Android\avd\.android\debug.keystore
Alias: AndroidDebugKey
MD5: xx:xx:xx:62:86:B7:9C:BC:FB:AD:C8:C6:64:69:xx:xx
SHA1: xx:xx:xx:xx:0F:B0:82:86:1D:14:0D:AF:67:99:58:1A:01:xx:xx:xx
Valid until: Friday, July 19, 2047
----------
So I must use keytool to get sha-1. Here official Firebase doc:
After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.
* The arguments which may be supplied in the recovery.command file:
* --send_intent=anystring - write the text out to recovery.intent
* --update_package=path - verify install an OTA package file
* --wipe_data - erase user data (and cache), then reboot
* --wipe_cache - wipe cache (but not user data), then reboot
* --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:
adb shell
recovery --wipe_data
Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.
EDIT:
For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command
For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c
pip3 install mysql-connector-python did solve my problem as well. Ignore using mysql-connector module.
You can also use: file.getCanonicalFile().delete();
You can do this,
User.query.filter_by(id=123).delete()
or
User.query.filter(User.id == 123).delete()
Make sure to commit
for delete()
to take effect.
ASP.NET grants access from the configuration file as a matter of precedence. In case of a potential conflict, the first occurring grant takes precedence. So,
deny user="?"
denies access to the anonymous user. Then
allow users="dan,matthew"
grants access to that user. Finally, it denies access to everyone. This shakes out as everyone except dan,matthew is denied access.
Edited to add: and as @Deviant points out, denying access to unauthenticated is pointless, since the last entry includes unauthenticated as well. A good blog entry discussing this topic can be found at: Guru Sarkar's Blog
I'm a python beginner, so to getter a clear idea of lambda I compared it with a 'for' loop; in terms of efficiency. Here's the code (python 2.7) -
import time
start = time.time() # Measure the time taken for execution
def first():
squares = map(lambda x: x**2, range(10))
# ^ Lambda
end = time.time()
elapsed = end - start
print elapsed + ' seconds'
return elapsed # gives 0.0 seconds
def second():
lst = []
for i in range(10):
lst.append(i**2)
# ^ a 'for' loop
end = time.time()
elapsed = end - start
print elapsed + ' seconds'
return elapsed # gives 0.0019998550415 seconds.
print abs(second() - first()) # Gives 0.0019998550415 seconds!(duh)
<merge/>
is useful because it can get rid of unneeded ViewGroups, i.e. layouts that are simply used to wrap other views and serve no purpose themselves.
For example, if you were to <include/>
a layout from another file without using merge, the two files might look something like this:
layout1.xml:
<FrameLayout>
<include layout="@layout/layout2"/>
</FrameLayout>
layout2.xml:
<FrameLayout>
<TextView />
<TextView />
</FrameLayout>
which is functionally equivalent to this single layout:
<FrameLayout>
<FrameLayout>
<TextView />
<TextView />
</FrameLayout>
</FrameLayout>
That FrameLayout in layout2.xml may not be useful. <merge/>
helps get rid of it. Here's what it looks like using merge (layout1.xml doesn't change):
layout2.xml:
<merge>
<TextView />
<TextView />
</merge>
This is functionally equivalent to this layout:
<FrameLayout>
<TextView />
<TextView />
</FrameLayout>
but since you are using <include/>
you can reuse the layout elsewhere. It doesn't have to be used to replace only FrameLayouts - you can use it to replace any layout that isn't adding something useful to the way your view looks/behaves.
Is very simple. when it says 'Could not locate Gemfile' it means in the folder you are currently in or a directory you are in, there is No a file named GemFile. Therefore in your command prompt give an explicit or full path of the there folder where such file name "Gemfile" is e.g cd C:\Users\Administrator\Desktop\RubyProject\demo.
It will definitely be solved in a minute.
Wrap your OutputStream with a PrintWriter and use the print methods on that class. They take in a String and do the work for you.
The issue of adding tooltips to any HTML-Output (not only FontAwesome) is an entire book on its own. ;-)
The default way would be to use the title-attribute:
<div id="welcomeText" title="So nice to see you!">
<p>Welcome Harriet</p>
</div>
or
<i class="fa fa-cog" title="Do you like my fa-coq icon?"></i>
But since most people (including me) do not like the standard-tooltips, there are MANY tools out there which will "beautify" them and offer all sort of enhancements. My personal favourites are jBox and qtip2.
Google declares that this is not a failure, but some "misleading error reports". This bug will be fixed in version 40 of chrome.
You can read this:
CAUTION: commit any work you wish to retain first.
You may reset your workspace (and recover the deleted files)
git checkout ./*
Consider explicitly setting the header in the $http.post (I put application/json, as I am not sure which of the two versions in your example is the working one, but you can use application/x-www-form-urlencoded if it's the other one):
$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
.then(function (response) {
return response;
});
In case someone is using python and linux and looking for full path to file:
>>> path=os.popen("readlink -f file").read()
>>> print path
abs/path/to/file
So I run a functionally equivalent form of your code in an IPython notebook:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
# Number of samplepoints
N = 600
# sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = scipy.fftpack.fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N/2)
fig, ax = plt.subplots()
ax.plot(xf, 2.0/N * np.abs(yf[:N//2]))
plt.show()
I get what I believe to be very reasonable output.
It's been longer than I care to admit since I was in engineering school thinking about signal processing, but spikes at 50 and 80 are exactly what I would expect. So what's the issue?
The problem here is that you don't have periodic data. You should always inspect the data that you feed into any algorithm to make sure that it's appropriate.
import pandas
import matplotlib.pyplot as plt
#import seaborn
%matplotlib inline
# the OP's data
x = pandas.read_csv('http://pastebin.com/raw.php?i=ksM4FvZS', skiprows=2, header=None).values
y = pandas.read_csv('http://pastebin.com/raw.php?i=0WhjjMkb', skiprows=2, header=None).values
fig, ax = plt.subplots()
ax.plot(x, y)
If you look at the source code for a StringBuilder or StringBuffer the setLength() call just resets an index value for the character array. IMHO using the setLength method will always be faster than a new allocation. They should have named the method 'clear' or 'reset' so it would be clearer.
I'm unclear about your question. From http://effbot.org/tkinterbook/entry.htm#patterns, it seems you just need to do an assignment after you called the delete. To add entry text to the widget, use the insert method. To replace the current text, you can call delete before you insert the new text.
e = Entry(master)
e.pack()
e.delete(0, END)
e.insert(0, "")
Could you post a bit more code?
Try this code
public class WiFiDemo extends Activity implements OnClickListener
{
WifiManager wifi;
ListView lv;
TextView textStatus;
Button buttonScan;
int size = 0;
List<ScanResult> results;
String ITEM_KEY = "key";
ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter;
/* Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textStatus = (TextView) findViewById(R.id.textStatus);
buttonScan = (Button) findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(this);
lv = (ListView)findViewById(R.id.list);
wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled() == false)
{
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
wifi.setWifiEnabled(true);
}
this.adapter = new SimpleAdapter(WiFiDemo.this, arraylist, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value });
lv.setAdapter(this.adapter);
registerReceiver(new BroadcastReceiver()
{
@Override
public void onReceive(Context c, Intent intent)
{
results = wifi.getScanResults();
size = results.size();
}
}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
public void onClick(View view)
{
arraylist.clear();
wifi.startScan();
Toast.makeText(this, "Scanning...." + size, Toast.LENGTH_SHORT).show();
try
{
size = size - 1;
while (size >= 0)
{
HashMap<String, String> item = new HashMap<String, String>();
item.put(ITEM_KEY, results.get(size).SSID + " " + results.get(size).capabilities);
arraylist.add(item);
size--;
adapter.notifyDataSetChanged();
}
}
catch (Exception e)
{ }
}
}
WiFiDemo.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="@+id/textStatus"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Status" />
<Button
android:id="@+id/buttonScan"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:text="Scan" />
</LinearLayout>
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"></ListView>
</LinearLayout>
For ListView- row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/list_value"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14dp" />
</LinearLayout>
Add these permission in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Here is a snippet for not only closing modals without page refresh but when pressing enter it submits modal and closes without refresh
I have it set up on my site where I can have multiple modals and some modals process data on submit and some don't. What I do is create a unique ID for each modal that does processing. For example in my webpage:
HTML (modal footer):
<div class="modal-footer form-footer"><br>
<span class="caption">
<button id="PreLoadOrders" class="btn btn-md green btn-right" type="button" disabled>Add to Cart <i class="fa fa-shopping-cart"></i></button>
<button id="ClrHist" class="btn btn-md red btn-right" data-dismiss="modal" data-original-title="" title="Return to Scan Order Entry" type="cancel">Cancel <i class="fa fa-close"></i></a>
</span>
</div>
jQUERY:
$(document).ready(function(){
// Allow enter key to trigger preloadorders form
$(document).keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
if($(".trigger").is(".ok"))
$("#PreLoadOrders").trigger("click");
else
return;
}
});
});
As you can see this submit performs processing which is why I have this jQuery for this modal. Now let's say I have another modal within this webpage but no processing is performed and since one modal is open at a time I put another $(document).ready()
in a global php/js script that all pages get and I give the modal's close button a class called: ".modal-close"
:
HTML:
<div class="modal-footer caption">
<button type="submit" class="modal-close btn default" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
jQuery (include global.inc):
$(document).ready(function(){
// Allow enter key to trigger a particular button anywhere on page
$(document).keypress(function(e) {
if(e.which == 13) {
if($(".modal").is(":visible")){
$(".modal:visible").find(".modal-close").trigger('click');
}
}
});
});
Pig eats anything! Meaning it can consume unstructured data.
Hive requires a schema.
why dont you add a "source" column to each of the queries with a static value like
select 'source 1' as Source, column1, column2...
from table1
UNION ALL
select 'source 2' as Source, column1, column2...
from table2
TESTED with jquery 1.11.3 & jquery-ui 1.11.4
$(function() {
$("#draggable").draggable({
revert : function(event, ui) {
// on older version of jQuery use "draggable"
// $(this).data("draggable")
// on 2.x versions of jQuery use "ui-draggable"
// $(this).data("ui-draggable")
$(this).data("uiDraggable").originalPosition = {
top : 0,
left : 0
};
// return boolean
return !event;
// that evaluate like this:
// return event !== false ? false : true;
}
});
$("#droppable").droppable();
});
TortoiseGit also provides a command line tool to do see the history of a file. Using PowerShell:
C:\Program` Files\TortoiseGit\bin\TortoiseGitProc.exe /command:log /path:"c:\path\to\your\file.txt"
We can use replace
to change the values in 'mpg' to NA
that corresponds to cyl==4
.
mtcars %>%
mutate(mpg=replace(mpg, cyl==4, NA)) %>%
as.data.frame()
There is a hashchange plug-in which wraps up the functionality and cross browser issues available here.
Runtime describes software/instructions that are executed while your program is running, especially those instructions that you did not write explicitly, but are necessary for the proper execution of your code.
Low-level languages like C have very small (if any) runtime. More complex languages like Objective-C, which allows for dynamic message passing, have a much more extensive runtime.
You are correct that runtime code is library code, but library code is a more general term, describing the code produced by any library. Runtime code is specifically the code required to implement the features of the language itself.
First off, EC2 and Elastic Compute Cloud are the same thing.
Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.
EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n
number of instances.
Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.
For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.
In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.
Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/
Install g++ on openSuSE run
zypper in gcc-c++
--mixed vs --soft vs --hard:
--mixed:
Delete changes from the local repository and staging area.
It won't touch the working directory.
Possible to revert back changes by using the following commands.
- git add
- git commit
Working tree won't be clean.
--soft:
Deleted changes only from the local repository.
It won't touch the staging area and working directory.
Possible to revert back changes by using the following command.
- git commit.
Working tree won't be clean
--hard:
Deleted changes from everywhere.
Not possible to revert changes.
The working tree will be clean.
NOTE: If the commits are confirmed to the local repository and to discard those commits we can use:
`git reset command`.
But if the commits are confirmed to the remote repository then not recommended to use the reset command and we have to use the revert command
to discard the remote commits.
http://docs.jquery.com/Events/jQuery.Event
Try with event.target
Contains the DOM element that issued the event. This can be the element that registered for the event or a child of it.
Try to close all connections to your database first:
use master
ALTER DATABASE BOSEVIKRAM SET SINGLE_USER WITH ROLLBACK IMMEDIATE
ALTER DATABASE BOSEVIKRAM MODIFY NAME = [BOSEVIKRAM_Deleted]
ALTER DATABASE BOSEVIKRAM_Deleted SET MULTI_USER
Taken from here
To answer the second part of your question, to convert to binary you can use a format string and the ord
function:
>>> byte = 'a'
>>> '{0:08b}'.format(ord(byte))
'01100001'
Note that the format pads with the right number of leading zeros, which seems to be your requirement. This method needs Python 2.6 or later.
Only <
and &
are required to be escaped if they are to be treated character data and not markup:
RPC Stubs
There is no need complicating the stuff. After the -m "text...
the next line is gotten by pressing Enter. When Enter is pressed >
appears. When you are done, just put "
and press Enter:
$ git commit -m "Another way of demonstrating multicommit messages:
>
> This is a new line written
> This is another new line written
> This one is really awesome too and we can continue doing so till ..."
$ git log -1
commit 5474e383f2eda610be6211d8697ed1503400ee42 (HEAD -> test2)
Author: ************** <*********@gmail.com>
Date: Mon Oct 9 13:30:26 2017 +0200
Another way of demonstrating multicommit messages:
This is a new line written
This is another new line written
This one is really awesome too and we can continue doing so till ...
Although side_effect
can achieve the goal, it is not so convenient to setup side_effect
function for each test case.
I write a lightweight Mock (which is called NextMock) to enhance the built-in mock to address this problem, here is a simple example:
from nextmock import Mock
m = Mock()
m.with_args(1, 2, 3).returns(123)
assert m(1, 2, 3) == 123
assert m(3, 2, 1) != 123
It also supports argument matcher:
from nextmock import Arg, Mock
m = Mock()
m.with_args(1, 2, Arg.Any).returns(123)
assert m(1, 2, 1) == 123
assert m(1, 2, "123") == 123
Hope this package could make testing more pleasant. Feel free to give any feedback.
Using zip4j you can simply do this
ZipFile zipfile = new ZipFile(new File("D:\\reports\\january\\filename.zip"));
zipfile.addFolder(new File("D:\\reports\\january\\"));
It will archive your folder and everything in it.
Use the .extractAll
method to get it all out:
zipfile.extractAll("D:\\destination_directory");
When I started a new project
react-native init MyPrroject
I got could not connect to development server
on both platforms iOS
and Android
.
My solution is to
sudo lsof -i :8081
//find a PID of node
kill -9 <node_PID>
Also make sure that you use your local IP address
ipconfig getifaddr en0
try this code
using hidden field we can pass php varibale to another page
page1.php
<?php $myVariable = "Some text";?>
<form method="post" action="page2.php">
<input type="hidden" name="text" value="<?php echo $myVariable; ?>">
<button type="submit">Submit</button>
</form>
pass php variable to hidden field value so you can access this variable into another page
page2.php
<?php
$text=$_POST['text'];
echo $text;
?>
My installer copied a log.txt file which had been generated on an XP computer. I was looking at that log file thinking it was generated on Vista. Once I fixed my log4net configuration to be "Vista Compatible". Environment.GetFolderPath was returning the expected results. Therefore, I'm closing this post.
The following SpecialFolder path reference might be useful:
Output On Windows Server 2003:
SpecialFolder.ApplicationData: C:\Documents and Settings\blake\Application Data SpecialFolder.CommonApplicationData: C:\Documents and Settings\All Users\Application Data SpecialFolder.ProgramFiles: C:\Program Files SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files SpecialFolder.DesktopDirectory: C:\Documents and Settings\blake\Desktop SpecialFolder.LocalApplicationData: C:\Documents and Settings\blake\Local Settings\Application Data SpecialFolder.MyDocuments: C:\Documents and Settings\blake\My Documents SpecialFolder.System: C:\WINDOWS\system32`
Output on Vista:
SpecialFolder.ApplicationData: C:\Users\blake\AppData\Roaming SpecialFolder.CommonApplicationData: C:\ProgramData SpecialFolder.ProgramFiles: C:\Program Files SpecialFolder.CommonProgramFiles: C:\Program Files\Common Files SpecialFolder.DesktopDirectory: C:\Users\blake\Desktop SpecialFolder.LocalApplicationData: C:\Users\blake\AppData\Local SpecialFolder.MyDocuments: C:\Users\blake\Documents SpecialFolder.System: C:\Windows\system32
// simple approach
$original_id = 56789;
$shortened_id = base_convert($original_id, 10, 36);
$un_shortened_id = base_convert($shortened_id, 36, 10);
The error log is straightforward. As it suggested,You need to add 198.211.99.20 to your ALLOWED_HOSTS
setting.
In your project settings.py file,set ALLOWED_HOSTS
like this :
ALLOWED_HOSTS = ['198.211.99.20', 'localhost', '127.0.0.1']
For further reading read from here.
ls -R -L
-L
dereferences symbolic links. This will also make it impossible to see any symlinks to files, though - they'll look like the pointed-to file.
Not padding but if your goal is to simply make it larger, you can increase the font-size
. And using it with font-size-adjust
reduces the font-size back to normal on select and not on options, so it ends up making the option
larger.
Not sure if it works on all browsers, or will keep working in current.
Tested on Chrome 85 & Firefox 81.
select {
font-size: 2em;
font-size-adjust: 0.3;
}
_x000D_
<label>
Select: <select>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
</label>
_x000D_
import { HttpClientModule } from '@angular/common/http';
The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it's own package @angular/common/http. One of the most notable changes is that now the response object is a JSON by default, so there's no need to parse it with map method anymore .Straight away we can use like below
http.get('friends.json').subscribe(result => this.result =result);
A simple expansion that doesn't require the datetime
module and isn't handicapped like some other solutions is to use simple string replacement like so:
import logging
import time
class MyFormatter(logging.Formatter):
def formatTime(self, record, datefmt=None):
ct = self.converter(record.created)
if datefmt:
if "%F" in datefmt:
msec = "%03d" % record.msecs
datefmt = datefmt.replace("%F", msec)
s = time.strftime(datefmt, ct)
else:
t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
s = "%s,%03d" % (t, record.msecs)
return s
This way a date format can be written however you want, even allowing for region differences, by using %F
for milliseconds. For example:
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
sh = logging.StreamHandler()
log.addHandler(sh)
fm = MyFormatter(fmt='%(asctime)s-%(levelname)s-%(message)s',datefmt='%H:%M:%S.%F')
sh.setFormatter(fm)
log.info("Foo, Bar, Baz")
# 03:26:33.757-INFO-Foo, Bar, Baz
I think this way helps you...
var name=[];
var age=[];
name.push('sulfikar');
age.push('24');
var ent={};
for(var i=0;i<name.length;i++)
{
ent.name=name[i];
ent.age=age[i];
}
JSON.Stringify(ent);
keycloak version: 4.6.0
I completely disagree with everyone who says OP is correct or there is no harm.
Everyone is talking about a modern and/or legacy OS's.
But what if I'm in an environment where I simply have no OS? Where there isn't anything?
Imagine now you are using thread styled interrupts and allocate memory. In the C standard ISO/IEC:9899 is the lifetime of memory stated as:
7.20.3 Memory management functions
1 The order and contiguity of storage allocated by successive calls to the calloc, malloc, and realloc functions is unspecified. The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated). The lifetime of an allocated object extends from the allocation until the deallocation.[...]
So it has not to be given that the environment is doing the freeing job for you. Otherwise it would be added to the last sentence: "Or until the program terminates."
So in other words: Not freeing memory is not just bad practice. It produces non portable and not C conform code. Which can at least be seen as 'correct, if the following: [...], is supported by environment'.
But in cases where you have no OS at all, no one is doing the job for you (I know generally you don't allocate and reallocate memory on embedded systems, but there are cases where you may want to.)
So speaking in general plain C (as which the OP is tagged), this is simply producing erroneous and non portable code.
Use Console.Write instead, so there's no newline written:
Console.Write("What is your name? ");
var name = Console.ReadLine();
2016 Update: in Chrome Version 51.0.2704.103
There is a Go to member
shortcut (listed in settings > shortcut > Text Editor
). Open the file containing your function (in the sources
panel of the DevTools) and press:
ctrl + shift + O
or in OS X:
? + shift + O
This enables to list and reach members of the current file.
Swift 3 (forget about NSURL).
let fileName = "20-01-2017 22:47"
let folderString = "file:///var/mobile/someLongPath"
To make a URL out of a string:
let folder: URL? = Foundation.URL(string: folderString)
// Optional<URL>
// ? some : file:///var/mobile/someLongPath
If we want to add the filename. Note, that appendingPathComponent() adds the percent encoding automatically:
let folderWithFilename: URL? = folder?.appendingPathComponent(fileName)
// Optional<URL>
// ? some : file:///var/mobile/someLongPath/20-01-2017%2022:47
When we want to have String but without the root part (pay attention that percent encoding is removed automatically):
let folderWithFilename: String? = folderWithFilename.path
// ? Optional<String>
// - some : "/var/mobile/someLongPath/20-01-2017 22:47"
If we want to keep the root part we do this (but mind the percent encoding - it is not removed):
let folderWithFilenameAbsoluteString: String? = folderWithFilenameURL.absoluteString
// ? Optional<String>
// - some : "file:///var/mobile/someLongPath/20-01-2017%2022:47"
To manually add the percent encoding for a string:
let folderWithFilenameAndEncoding: String? = folderWithFilename.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
// ? Optional<String>
// - some : "/var/mobile/someLongPath/20-01-2017%2022:47"
To remove the percent encoding:
let folderWithFilenameAbsoluteStringNoEncodig: String? = folderWithFilenameAbsoluteString.removingPercentEncoding
// ? Optional<String>
// - some : "file:///var/mobile/someLongPath/20-01-2017 22:47"
The percent-encoding is important because URLs for network requests need them, while URLs to file system won't always work - it depends on the actual method that uses them. The caveat here is that they may be removed or added automatically, so better debug these conversions carefully.
Either:
DateTime dt = new DateTime();
or
DateTime dt = default(DateTime);
Another option is to navigate to problems tab, right click on error, click apply quick fix. The should generate the ignore xml code and apply it .pom file for you.
That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if
condition is always true.
The simplest way to make it work, it seems to me, is to account for this case:
var value = $(this).val();
if ( value.length > 0 && value != "Default text" ) ...
Don't forget to either include stylesheets using the link tag
http://www.w3schools.com/TAGS/tag_link.asp
Or enclose CSS within a style tag on your webpage.
<style>
a { text-decoration:none; }
p { text-decoration:underline; }
</style>
I wouldn't recommend using the underline on anything apart from links, underline is generally accepted as something that is clickable. If it isn't clickable don't underline it.
CSS basics can be picked up at w3schools
Answer:
Use a Singleton if:
Do not use a Singleton if:
How to create the best singleton:
Primitives can be converted to objects with @()
expression. So the shortest way is to transform int
to NSNumber
and pick up string representation with stringValue
method:
NSString *strValue = [@(myInt) stringValue];
or
NSString *strValue = @(myInt).stringValue;
I've only tested this in Rails 4 but there's an interesting way to use a range with a where
hash to get this behavior.
User.where(id: 201..Float::INFINITY)
will generate the SQL
SELECT `users`.* FROM `users` WHERE (`users`.`id` >= 201)
The same can be done for less than with -Float::INFINITY
.
I just posted a similar question asking about doing this with dates here on SO.
>=
vs >
To avoid people having to dig through and follow the comments conversation here are the highlights.
The method above only generates a >=
query and not a >
. There are many ways to handle this alternative.
For discrete numbers
You can use a number_you_want + 1
strategy like above where I'm interested in Users with id > 200
but actually look for id >= 201
. This is fine for integers and numbers where you can increment by a single unit of interest.
If you have the number extracted into a well named constant this may be the easiest to read and understand at a glance.
Inverted logic
We can use the fact that x > y == !(x <= y)
and use the where not chain.
User.where.not(id: -Float::INFINITY..200)
which generates the SQL
SELECT `users`.* FROM `users` WHERE (NOT (`users`.`id` <= 200))
This takes an extra second to read and reason about but will work for non discrete values or columns where you can't use the + 1
strategy.
Arel table
If you want to get fancy you can make use of the Arel::Table
.
User.where(User.arel_table[:id].gt(200))
will generate the SQL
"SELECT `users`.* FROM `users` WHERE (`users`.`id` > 200)"
The specifics are as follows:
User.arel_table #=> an Arel::Table instance for the User model / users table
User.arel_table[:id] #=> an Arel::Attributes::Attribute for the id column
User.arel_table[:id].gt(200) #=> an Arel::Nodes::GreaterThan which can be passed to `where`
This approach will get you the exact SQL you're interested in however not many people use the Arel table directly and can find it messy and/or confusing. You and your team will know what's best for you.
Starting in Rails 5 you can also do this with dates!
User.where(created_at: 3.days.ago..DateTime::Infinity.new)
will generate the SQL
SELECT `users`.* FROM `users` WHERE (`users`.`created_at` >= '2018-07-07 17:00:51')
Once Ruby 2.6 is released (December 25, 2018) you'll be able to use the new infinite range syntax! Instead of 201..Float::INFINITY
you'll be able to just write 201..
. More info in this blog post.
A different approach, because in my case I needed to also check whether it contained certain words (like 'test' in this example), not characters alone:
input_string = 'abc test'
input_string_test = input_string
allowed_list = ['a', 'b', 'c', 'test', ' ']
for allowed_list_item in allowed_list:
input_string_test = input_string_test.replace(allowed_list_item, '')
if not input_string_test:
# test passed
So, the allowed strings (char or word) are cut from the input string. If the input string only contained strings that were allowed, it should leave an empty string and therefore should pass if not input_string
.
Start your program as an administrator. The program can't rewrite your files cause your files are in a protected location on your hard drive.
If your vector is not ordered, use the approach MSN suggested:
if(std::find(vector.begin(), vector.end(), item)!=vector.end()){
// Found the item
}
If your vector is ordered, use binary_search method Brian Neal suggested:
if(binary_search(vector.begin(), vector.end(), item)){
// Found the item
}
binary search yields O(log n) worst-case performance, which is way more efficient than the first approach. In order to use binary search, you may use qsort to sort the vector first to guarantee it is ordered.
Try it with Mysqldump
#mysqldump --host=the.remotedatabase.com -u yourusername -p yourdatabasename > /User/backups/adump.sql
In your special case it would be
a=$('[myc="blue"][myid="1"],[myc="blue"][myid="3"]');
here i store the PID in a file called .pid (which is kind of like /run/...) and only execute the script if not already being executed.
#!/bin/bash
if [ -f .pid ]; then
read pid < .pid
echo $pid
ps -p $pid > /dev/null
r=$?
if [ $r -eq 0 ]; then
echo "$pid is currently running, not executing $0 twice, exiting now..."
exit 1
fi
fi
echo $$ > .pid
# do things here
rm .pid
note: there is a race condition as it does not check how that pid is called. if the system is rebooted and .pid exists but is used by a different application this might lead 'unforeseen consequences'.
Quick and dirty - Turn it off:
USE_TZ = False
in your settings.py
COLLATE UTF8_GENERAL_CI
will work as ignore-case.
USE:
SELECT * from games WHERE title COLLATE UTF8_GENERAL_CI LIKE 'age of empires III%';
or
SELECT * from games WHERE LOWER(title) LIKE 'age of empires III%';
Using @mmacaulay , I came up with this for bool:
// MVC Work around for checkboxes.
bool active = (Request.Form["active"] == "on");
If checked active = true
If unchecked active = false
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String args[]) {
// This is how to get today's date in Java
Date today = new Date();
//If you print Date, you will get un formatted output
System.out.println("Today is : " + today);
//formatting date in Java using SimpleDateFormat
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy");
String date = DATE_FORMAT.format(today);
System.out.println("Today in dd-MM-yyyy format : " + date);
//Another Example of formatting Date in Java using SimpleDateFormat
DATE_FORMAT = new SimpleDateFormat("dd/MM/yy");
date = DATE_FORMAT.format(today);
System.out.println("Today in dd/MM/yy pattern : " + date);
//formatting Date with time information
DATE_FORMAT = new SimpleDateFormat("dd-MM-yy:HH:mm:SS");
date = DATE_FORMAT.format(today);
System.out.println("Today in dd-MM-yy:HH:mm:SS : " + date);
//SimpleDateFormat example - Date with timezone information
DATE_FORMAT = new SimpleDateFormat("dd-MM-yy:HH:mm:SS Z");
date = DATE_FORMAT.format(today);
System.out.println("Today in dd-MM-yy:HH:mm:SSZ : " + date);
}
}
Output:
Today is : Fri Nov 02 16:11:27 IST 2012
Today in dd-MM-yyyy format : 02-11-2012
Today in dd/MM/yy pattern : 02/11/12
Today in dd-MM-yy:HH:mm:SS : 02-11-12:16:11:316
Today in dd-MM-yy:HH:mm:SSZ : 02-11-12:16:11:316 +0530
Update 2020
Products are located mainly in the following tables:
wp_posts
table with post_type
like product
(or product_variation
),
wp_postmeta
table with post_id
as relational index (the product ID).
wp_wc_product_meta_lookup
table with product_id
as relational index (the post ID) | Allow fast queries on specific product data (since WooCommerce 3.7)
wp_wc_order_product_lookup
table with product_id
as relational index (the post ID) | Allow fast queries to retrieve products on orders (since WooCommerce 3.7)
Product types, categories, subcategories, tags, attributes and all other custom taxonomies are located in the following tables:
wp_terms
wp_termmeta
wp_term_taxonomy
wp_term_relationships
- column object_id
as relational index (the product ID)
wp_woocommerce_termmeta
wp_woocommerce_attribute_taxonomies
(for product attributes only)
wp_wc_category_lookup
(for product categories hierarchy only since WooCommerce 3.7)
Product types are handled by custom taxonomy product_type
with the following default terms:
simple
grouped
variable
external
Some other product types for Subscriptions and Bookings plugins:
subscription
variable-subscription
booking
Since Woocommerce 3+ a new custom taxonomy named product_visibility
handle:
exclude-from-search
and exclude-from-catalog
featured
outofstock
rated-1
to rated-5
Particular feature: Each product attribute is a custom taxonomy…
References:
Here is a C# implementation of the *nix cksum command line utility for windows https://cksum.codeplex.com/
Try adding JSON.stringify(result)
to convert the JS Object into a JSON string.
From your code I can see you are logging the result in error
which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).
Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.
Another tactic not yet mentioned is using appending to a list, and then converting the list to a tuple at the end:
mylist = []
for x in range(5):
mylist.append(x)
mytuple = tuple(mylist)
print mytuple
returns
(0, 1, 2, 3, 4)
I sometimes use this when I have to pass a tuple as a function argument, which is often necessary for the numpy functions.
In View:
<Button
Height="50" Width="50"
Style="{StaticResource MyButtonStyle}"
Command="{Binding SmallDisp}" CommandParameter="{Binding}"
Cursor="Hand" Visibility="{Binding Path=AdvancedFormat}"/>
In view Model:
public _advancedFormat = Visibility.visible (whatever you start with)
public Visibility AdvancedFormat
{
get{return _advancedFormat;}
set{
_advancedFormat = value;
//raise property changed here
}
You will need to have a property changed event
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChanged.Raise(this, e);
}
protected void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
This is how they use Model-view-viewmodel
But since you want it binded to a boolean, You will need some converter. Another way is to set a boolean outside and when that button is clicked then set the property_advancedFormat to your desired visibility.
you can use DbFunctions.TruncateTime() method for this.
e => DbFunctions.TruncateTime(e.FirstDate.Value) == DbFunctions.TruncateTime(SecondDate);
As stated in the answer, in order to use a non deprecated way to sign your own script, one should use New-SelfSignedCertificate.
New-SelfSignedCertificate -DnsName [email protected] -Type CodeSigning -CertStoreLocation cert:\CurrentUser\My
Export-Certificate -Cert (Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert)[0] -FilePath code_signing.crt
The [0] will make this work for cases when you have more than one certificate... Obviously make the index match the certificate you want to use... or use a way to filtrate (by thumprint or issuer).
Import-Certificate -FilePath .\code_signing.crt -Cert Cert:\CurrentUser\TrustedPublisher
Import-Certificate -FilePath .\code_signing.crt -Cert Cert:\CurrentUser\Root
Set-AuthenticodeSignature .\script.ps1 -Certificate (Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert)
Obviously once you have setup the key, you can simply sign any other scripts with it.
You can get more detailed information and some troubleshooting help in this article.
If you are using Netty and want to use a map with primitive int type keys, you can use its IntObjectHashMap
Some of the reasons to use primitive type collections:
The question of specialized vs generalized collections can make or break programs with high throughput requirements.
Try starting the project using the python_boilerplate template. It largely follows the best practices (e.g. those here), but is better suited in case you find yourself willing to split your project into more than one egg at some point (and believe me, with anything but the simplest projects, you will. One common situation is where you have to use a locally-modified version of someone else's library).
Where do you put the source?
PROJECT_ROOT/src/<egg_name>
.Where do you put application startup scripts?
entry_point
in one of the eggs.Where do you put the IDE project cruft?
PROJECT_ROOT/.<something>
in the root of the project, and this is fine.Where do you put the unit/acceptance tests?
PROJECT_ROOT/src/<egg_name>/tests
directory. I personally prefer to use py.test
to run them.Where do you put non-Python data such as config files?
pkg_resources
package from setuptools
, or since Python 3.7 via the importlib.resources
module from the standard library.PROJECT_ROOT/config
. For deployment there can be various options. On Windows one can use %APP_DATA%/<app-name>/config
, on Linux, /etc/<app-name>
or /opt/<app-name>/config
.PROJECT_ROOT/var
during development, and under /var
during Linux deployment.PROJECT_ROOT/src/<egg_name>/native
Documentation would typically go into PROJECT_ROOT/doc
or PROJECT_ROOT/src/<egg_name>/doc
(this depends on whether you regard some of the eggs to be a separate large projects). Some additional configuration will be in files like PROJECT_ROOT/buildout.cfg
and PROJECT_ROOT/setup.cfg
.
If you're using PowerShell v3, you can use JSON instead of a hashtable, and convert it to an object with Convert-FromJson:
@'
[
{
FileName = "Page";
ObjectName = "vExtractPage";
},
{
ObjectName = "ChecklistItemCategory";
},
{
ObjectName = "ChecklistItem";
},
]
'@ |
Convert-FromJson |
ForEach-Object {
$InputFullTableName = '{0}{1}' -f $TargetDatabase,$_.ObjectName
# In strict mode, you can't reference a property that doesn't exist,
#so check if it has an explicit filename firest.
$outputFileName = $_.ObjectName
if( $_ | Get-Member FileName )
{
$outputFileName = $_.FileName
}
$OutputFullFileName = Join-Path $OutputDirectory $outputFileName
bcp $InputFullTableName out $OutputFullFileName -T -c $ServerOption
}
I think this only happens when you have 'Preserve log' checked and you are trying to view the response data of a previous request after you have navigated away.
For example, I viewed the Response to loading this Stack Overflow question. You can see it.
The second time, I reloaded this page but didn't look at the Headers or Response. I navigated to a different website. Now when I look at the response, it shows 'Failed to load response data'.
This is a known issue, that's been around for a while, and debated a lot. However, there is a workaround, in which you pause on onunload
, so you can view the response before it navigates away, and thereby doesn't lose the data upon navigating away.
window.onunload = function() { debugger; }
For me this problem keeps appearing after I run the APK at first time. Invalidating did not help.
However, I came with a workaround:
Just run the APK, and while it's running you can submit your changes clicking the "Lightning" button (Apply changes) next to to the "Run" button at the top right panel. Works charming for me, when making changes to the layout.
Define a module ( call it "globalbaz" ) and have the variables defined inside it. All the modules using this "pseudoglobal" should import the "globalbaz" module, and refer to it using "globalbaz.var_name"
This works regardless of the place of the change, you can change the variable before or after the import. The imported module will use the latest value. (I tested this in a toy example)
For clarification, globalbaz.py looks just like this:
var_name = "my_useful_string"
I was looking to do exactly the same thing (RESTful web service), and I stumbled upon this firefox addon, which lets you modify the accept headers (actually, any request headers) for requests. It works perfectly.
Run ssh-add
on the client machine, that will add the SSH key to the agent.
Confirm with ssh-add -l
(again on the client) that it was indeed added.
A nice solution that I've found is to do on UI something like:
<div *ngIf="isDataLoaded">
...Your page...
</div
Only when: isDataLoaded is true the page is rendered.
With python 3.6, these two lines return a list (may be empty)
>>[int(x) for x in re.findall('\d+', your_string)]
Similar to
>>list(map(int, re.findall('\d+', your_string))
You can put your servers in the default_step
group and those vars will apply to it:
# inventory file
[default_step]
prod2
web_v2
Then just move your default_step.yml
file to group_vars/default_step.yml
.
All you need is a android:margin_bottom
equal to the android:elevation
value. No AppBarLayout
, clipToPadding
, etc. required.
Example:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_marginBottom="4dp"
android:background="@android:color/white"
android:elevation="4dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--Inner layout goes here-->
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.appcompat.widget.Toolbar>
I went through this issue and I managed to run mysql server using below solution
Install mysql through .dmg
(https://dev.mysql.com/downloads/mysql/5.7.html), you will get mysql service panel in system preferences then start mysql from the panel and try
mysql -u root -p
Images attached for reference
Don't forget to use var/let while declaring any variable.See below examples for JS compiler behaviour.
function func(){
return true;
}
isBool = func();
console.log(typeof (isBool)); // output - string
let isBool = func();
console.log(typeof (isBool)); // output - boolean
\\(?\d{3}\\)?([\-\s\.])?\d{3}\1?\d{4}
This will validate any phone number of variable format:
\\(?\d{3}\\)?
finds 3 digits enclosed by parenthesis or not.
([\-\s\.])?
finds any of these separator characters or not
\d{3}
finds 3 digits
\1
uses the first matched separator - this ensures that the separators are the same. So (000) 999-5555 will not validate here because there is a space and dash separator, so just remove the "\1" and replace with the separator sub-pattern (doing so will also validate non standard formats). You should however be format hinting for user input anyway.
\d{4}
finds 4 digits
Validates:
BTW this is for JavaScript hence to double escapes.
Here is a table of the different events and the levels of browser support. You need to pick an event which is supported across at least all modern browsers.
As you will see from the table, the keypress
and change
event do not have uniform support whereas the keyup
event does.
Also make sure you attach the event handler using a cross-browser-compatible method...
You may need to run the cron job as a user with permissions to execute the PHP script. Try executing the cron job as root, using the command runuser
(man runuser
). Or create a system crontable and run the PHP script as an authorized user, as @Philip described.
I provide a detailed answer how to use cron in this stackoverflow post.
How to write a cron that will run a script every day at midnight?
String y = "hello";
would work (note the double quotes).
char y = 'h'; this will work for chars (note the single quotes)
but the type is the key: '' (single quotes) for one char, "" (double quotes) for string.
Now (2020) NetBeans 11 does it automatically with the "Build" command (right click on the project's name and choose "Build")
In some situations you may also want to ignore some files globally. For me, .DS_Store is one of them. Here's how:
git config --global core.excludesfile /Users/mat/.gitignore
(Or any file of your choice)
Then edit the file just like a repo's .gitignore. Note that I think you have to use an absolute path.
its called scope resolution operator, A hidden global name can be referred to using the scope resolution operator ::
For example;
int x;
void f2()
{
int x = 1; // hide global x
::x = 2; // assign to global x
x = 2; // assign to local x
// ...
}
You have to check if you have the folder with name manager
inside the folder webapps
in your tomcat.
Rubens-MacBook-Pro:tomcat rfanjul$ ls -la webapps/
total 16
drwxr-xr-x 8 rfanjul staff 272 21 May 12:20 .
drwxr-xr-x 14 rfanjul staff 476 21 May 12:22 ..
-rw-r--r--@ 1 rfanjul staff 6148 21 May 12:20 .DS_Store
drwxr-xr-x 19 rfanjul staff 646 17 Feb 15:13 ROOT
drwxr-xr-x 51 rfanjul staff 1734 17 Feb 15:13 docs
drwxr-xr-x 6 rfanjul staff 204 17 Feb 15:13 examples
drwxr-xr-x 7 rfanjul staff 238 17 Feb 15:13 host-manager
drwxr-xr-x 8 rfanjul staff 272 17 Feb 15:13 manager
After that you will be sure that you have this permmint for you user in the file conf/tomcat-users.xml
:
<role rolename="admin-gui"/>
<role rolename="manager-gui"/>
<user username="test" password="test" roles="admin-gui,manager-gui"/>
restart tomcat and stat tomcat again.
sh bin/shutdown.sh
sh bin/startup.sh
I hope that will works fine for you.
I got the same error and when I unknowingly removed all the default pages of the DefaultAppPool itself.
Resolution
I have clicked the DefaultAppPool and opened the Default Document. Then clicked on the Revert to Parent link on the Actions pane. The default documents have came again, and thus it solves the issue. I'm not sure this is the best way, but this one was the error which I have just met and hope to share with you. I hope this may help some one.
click()
to the QMainWindow custom slot you have created).Code example:
MainWindow.h
// ...
include "newwindow.h"
// ...
public slots:
void openNewWindow();
// ...
private:
NewWindow *mMyNewWindow;
// ...
}
MainWindow.cpp
// ...
MainWindow::MainWindow()
{
// ...
connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
// ...
}
// ...
void MainWindow::openNewWindow()
{
mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
mMyNewWindow->show();
// ...
}
This is an example on how display a custom new window. There are a lot of ways to do this.
Based on "MirekE" answer here is a code that i tested now and its working:
var activityIndicator: UIActivityIndicatorView!
var viewActivityIndicator: UIView!
override func viewDidLoad()
{
super.viewDidLoad()
let width: CGFloat = 200.0
let height: CGFloat = 50.0
let x = self.view.frame.width/2.0 - width/2.0
let y = self.view.frame.height/2.0 - height/2.0
self.viewActivityIndicator = UIView(frame: CGRect(x: x, y: y, width: width, height: height))
self.viewActivityIndicator.backgroundColor = UIColor(red: 255.0/255.0, green: 204.0/255.0, blue: 51.0/255.0, alpha: 0.5)
self.viewActivityIndicator.layer.cornerRadius = 10
self.activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
self.activityIndicator.color = UIColor.blackColor()
self.activityIndicator.hidesWhenStopped = false
let titleLabel = UILabel(frame: CGRect(x: 60, y: 0, width: 200, height: 50))
titleLabel.text = "Processing..."
self.viewActivityIndicator.addSubview(self.activityIndicator)
self.viewActivityIndicator.addSubview(titleLabel)
self.view.addSubview(self.viewActivityIndicator)
}
func doSometing()
{
self.activityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
//do something here that will taking time
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
self.viewActivityIndicator.removeFromSuperview()
}
An alternative method to BenAlabaster answer
First of all, you can rewrite the query like this:
var matches = from Users in people
where Users.User_Rights == "Admin" ||
Users.User_Rights == "Users" ||
Users.User_Rights == "Limited"
select Users;
Certainly this is more 'wordy' and a pain to write but it works all the same.
So if we had some utility method that made it easy to create these kind of LINQ expressions we'd be in business.
with a utility method in place you can write something like this:
var matches = ctx.People.Where(
BuildOrExpression<People, string>(
p => p.User_Rights, names
)
);
This builds an expression that has the same effect as:
var matches = from p in ctx.People
where names.Contains(p.User_Rights)
select p;
But which more importantly actually works against .NET 3.5 SP1.
Here is the plumbing function that makes this possible:
public static Expression<Func<TElement, bool>> BuildOrExpression<TElement, TValue>(
Expression<Func<TElement, TValue>> valueSelector,
IEnumerable<TValue> values
)
{
if (null == valueSelector)
throw new ArgumentNullException("valueSelector");
if (null == values)
throw new ArgumentNullException("values");
ParameterExpression p = valueSelector.Parameters.Single();
if (!values.Any())
return e => false;
var equals = values.Select(value =>
(Expression)Expression.Equal(
valueSelector.Body,
Expression.Constant(
value,
typeof(TValue)
)
)
);
var body = equals.Aggregate<Expression>(
(accumulate, equal) => Expression.Or(accumulate, equal)
);
return Expression.Lambda<Func<TElement, bool>>(body, p);
}
I'm not going to try to explain this method, other than to say it essentially builds a predicate expression for all the values using the valueSelector (i.e. p => p.User_Rights) and ORs those predicates together to create an expression for the complete predicate
Your code (vector1 == vector2
) is correct C++ syntax. There is an ==
operator for vectors.
If you want to compare short vector with a portion of a longer vector, you can use theequal()
operator for vectors. (documentation here)
Here's an example:
using namespace std;
if( equal(vector1.begin(), vector1.end(), vector2.begin()) )
DoSomething();
The only real difference here is the size. All of the int types here are signed integer values which have varying sizes
Int16
: 2 bytesInt32
and int
: 4 bytesInt64
: 8 bytesThere is one small difference between Int64
and the rest. On a 32 bit platform assignments to an Int64
storage location are not guaranteed to be atomic. It is guaranteed for all of the other types.
user2689410's code was exactly what I needed. Providing my version (credits to user2689410), which is faster due to calculating mean at once for whole rows in the DataFrame.
Hope my suffix conventions are readable: _s: string, _i: int, _b: bool, _ser: Series and _df: DataFrame. Where you find multiple suffixes, type can be both.
import pandas as pd
from datetime import datetime, timedelta
import numpy as np
def time_offset_rolling_mean_df_ser(data_df_ser, window_i_s, min_periods_i=1, center_b=False):
""" Function that computes a rolling mean
Credit goes to user2689410 at http://stackoverflow.com/questions/15771472/pandas-rolling-mean-by-time-interval
Parameters
----------
data_df_ser : DataFrame or Series
If a DataFrame is passed, the time_offset_rolling_mean_df_ser is computed for all columns.
window_i_s : int or string
If int is passed, window_i_s is the number of observations used for calculating
the statistic, as defined by the function pd.time_offset_rolling_mean_df_ser()
If a string is passed, it must be a frequency string, e.g. '90S'. This is
internally converted into a DateOffset object, representing the window_i_s size.
min_periods_i : int
Minimum number of observations in window_i_s required to have a value.
Returns
-------
Series or DataFrame, if more than one column
>>> idx = [
... datetime(2011, 2, 7, 0, 0),
... datetime(2011, 2, 7, 0, 1),
... datetime(2011, 2, 7, 0, 1, 30),
... datetime(2011, 2, 7, 0, 2),
... datetime(2011, 2, 7, 0, 4),
... datetime(2011, 2, 7, 0, 5),
... datetime(2011, 2, 7, 0, 5, 10),
... datetime(2011, 2, 7, 0, 6),
... datetime(2011, 2, 7, 0, 8),
... datetime(2011, 2, 7, 0, 9)]
>>> idx = pd.Index(idx)
>>> vals = np.arange(len(idx)).astype(float)
>>> ser = pd.Series(vals, index=idx)
>>> df = pd.DataFrame({'s1':ser, 's2':ser+1})
>>> time_offset_rolling_mean_df_ser(df, window_i_s='2min')
s1 s2
2011-02-07 00:00:00 0.0 1.0
2011-02-07 00:01:00 0.5 1.5
2011-02-07 00:01:30 1.0 2.0
2011-02-07 00:02:00 2.0 3.0
2011-02-07 00:04:00 4.0 5.0
2011-02-07 00:05:00 4.5 5.5
2011-02-07 00:05:10 5.0 6.0
2011-02-07 00:06:00 6.0 7.0
2011-02-07 00:08:00 8.0 9.0
2011-02-07 00:09:00 8.5 9.5
"""
def calculate_mean_at_ts(ts):
"""Function (closure) to apply that actually computes the rolling mean"""
if center_b == False:
dslice_df_ser = data_df_ser[
ts-pd.datetools.to_offset(window_i_s).delta+timedelta(0,0,1):
ts
]
# adding a microsecond because when slicing with labels start and endpoint
# are inclusive
else:
dslice_df_ser = data_df_ser[
ts-pd.datetools.to_offset(window_i_s).delta/2+timedelta(0,0,1):
ts+pd.datetools.to_offset(window_i_s).delta/2
]
if (isinstance(dslice_df_ser, pd.DataFrame) and dslice_df_ser.shape[0] < min_periods_i) or \
(isinstance(dslice_df_ser, pd.Series) and dslice_df_ser.size < min_periods_i):
return dslice_df_ser.mean()*np.nan # keeps number format and whether Series or DataFrame
else:
return dslice_df_ser.mean()
if isinstance(window_i_s, int):
mean_df_ser = pd.rolling_mean(data_df_ser, window=window_i_s, min_periods=min_periods_i, center=center_b)
elif isinstance(window_i_s, basestring):
idx_ser = pd.Series(data_df_ser.index.to_pydatetime(), index=data_df_ser.index)
mean_df_ser = idx_ser.apply(calculate_mean_at_ts)
return mean_df_ser
Note: This answer was written in February 2010.
See updates from 2015, 2016 and 2017 at the bottom.
You can't return anything from a function that is asynchronous. What you can return is a promise. I explained how promises work in jQuery in my answers to those questions:
If you could explain why do you want to return the data and what do you want to do with it later, then I might be able to give you a more specific answer how to do it.
Generally, instead of:
function testAjax() {
$.ajax({
url: "getvalue.php",
success: function(data) {
return data;
}
});
}
you can write your testAjax function like this:
function testAjax() {
return $.ajax({
url: "getvalue.php"
});
}
Then you can get your promise like this:
var promise = testAjax();
You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this:
promise.success(function (data) {
alert(data);
});
(See updates below for simplified syntax.)
If your data is available at this point then this function will be invoked immediately. If it isn't then it will be invoked as soon as the data is available.
The whole point of doing all of this is that your data is not available immediately after the call to $.ajax because it is asynchronous. Promises is a nice abstraction for functions to say: I can't return you the data because I don't have it yet and I don't want to block and make you wait so here's a promise instead and you'll be able to use it later, or to just give it to someone else and be done with it.
See this DEMO.
Currently (as of March, 2015) jQuery Promises are not compatible with the Promises/A+ specification which means that they may not cooperate very well with other Promises/A+ conformant implementations.
However jQuery Promises in the upcoming version 3.x will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out). Currently (as of May, 2015) the stable versions of jQuery are 1.x and 2.x.
What I explained above (in March, 2011) is a way to use jQuery Deferred Objects to do something asynchronously that in synchronous code would be achieved by returning a value.
But a synchronous function call can do two things - it can either return a value (if it can) or throw an exception (if it can't return a value). Promises/A+ addresses both of those use cases in a way that is pretty much as powerful as exception handling in synchronous code. The jQuery version handles the equivalent of returning a value just fine but the equivalent of complex exception handling is somewhat problematic.
In particular, the whole point of exception handling in synchronous code is not just giving up with a nice message, but trying to fix the problem and continue the execution, or possibly rethrowing the same or a different exception for some other parts of the program to handle. In synchronous code you have a call stack. In asynchronous call you don't and advanced exception handling inside of your promises as required by the Promises/A+ specification can really help you write code that will handle errors and exceptions in a meaningful way even for complex use cases.
For differences between jQuery and other implementations, and how to convert jQuery promises to Promises/A+ compliant, see Coming from jQuery by Kris Kowal et al. on the Q library wiki and Promises arrive in JavaScript by Jake Archibald on HTML5 Rocks.
The function from my example above:
function testAjax() {
return $.ajax({
url: "getvalue.php"
});
}
returns a jqXHR object, which is a jQuery Deferred Object.
To make it return a real promise, you can change it to - using the method from the Q wiki:
function testAjax() {
return Q($.ajax({
url: "getvalue.php"
}));
}
or, using the method from the HTML5 Rocks article:
function testAjax() {
return Promise.resolve($.ajax({
url: "getvalue.php"
}));
}
This Promise.resolve($.ajax(...))
is also what is explained in the promise
module documentation and it should work with ES6 Promise.resolve()
.
To use the ES6 Promises today you can use es6-promise module's polyfill()
by Jake Archibald.
To see where you can use the ES6 Promises without the polyfill, see: Can I use: Promises.
For more info see:
Future versions of jQuery (starting from 3.x - current stable versions as of May 2015 are 1.x and 2.x) will be compatible with the Promises/A+ specification (thanks to Benjamin Gruenbaum for pointing it out in the comments). "Two changes that we've already decided upon are Promise/A+ compatibility for our Deferred implementation [...]" (jQuery 3.0 and the future of Web development). For more info see: jQuery 3.0: The Next Generations by Dave Methvin and jQuery 3.0: More interoperability, less Internet Explorer by Paul Krill.
There is a new syntax in ECMA-262, 6th Edition, Section 14.2 called arrow functions that may be used to further simplify the examples above.
Using the jQuery API, instead of:
promise.success(function (data) {
alert(data);
});
you can write:
promise.success(data => alert(data));
or using the Promises/A+ API:
promise.then(data => alert(data));
Remember to always use rejection handlers either with:
promise.then(data => alert(data), error => alert(error));
or with:
promise.then(data => alert(data)).catch(error => alert(error));
See this answer to see why you should always use rejection handlers with promises:
Of course in this example you could use just promise.then(alert)
because you're just calling alert
with the same arguments as your callback, but the arrow syntax is more general and lets you write things like:
promise.then(data => alert("x is " + data.x));
Not every browser supports this syntax yet, but there are certain cases when you're sure what browser your code will run on - e.g. when writing a Chrome extension, a Firefox Add-on, or a desktop application using Electron, NW.js or AppJS (see this answer for details).
For the support of arrow functions, see:
There is an even newer syntax right now called async functions with a new await
keyword that instead of this code:
functionReturningPromise()
.then(data => console.log('Data:', data))
.catch(error => console.log('Error:', error));
lets you write:
try {
let data = await functionReturningPromise();
console.log('Data:', data);
} catch (error) {
console.log('Error:', error);
}
You can only use it inside of a function created with the async
keyword. For more info, see:
For support in browsers, see:
For support in Node, see:
In places where you don't have native support for async
and await
you can use Babel:
or with a slightly different syntax a generator based approach like in co
or Bluebird coroutines:
Some other questions about promises for more details:
I'm a bit late it seems to be, but...
a='hello'
print list(a)
# ['h','e','l','l', 'o']
This esc
behavior is IE only by the way. Instead of using jQuery use good old javascript for creating the element and it works.
var element = document.createElement('input');
element.type = 'text';
element.value = 100;
document.getElementsByTagName('body')[0].appendChild(element);
If you want to extend this functionality to other browsers then I would use jQuery's data object to store the default. Then set it when user presses escape.
//store default value for all elements on page. set new default on blur
$('input').each( function() {
$(this).data('default', $(this).val());
$(this).blur( function() { $(this).data('default', $(this).val()); });
});
$('input').keyup( function(e) {
if (e.keyCode == 27) { $(this).val($(this).data('default')); }
});
Make sure you have the Visual C++ Redistributable package installed on your machine.
Yes there is a way to do it.
First declare a class.
//anyfile.ts
export class Custom
{
name: string,
empoloyeeID: number
}
Then in your component import the class
import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
name: string;
empoloyeeID : number;
empList: Array<Custom> = [];
constructor() {
}
ngOnInit() {
}
onEmpCreate(){
//console.log(this.name,this.empoloyeeID);
let customObj = new Custom();
customObj.name = "something";
customObj.employeeId = 12;
this.empList.push(customObj);
this.name ="";
this.empoloyeeID = 0;
}
}
Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html
Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2
you can 'invoke' alternative bindings on Y
this way:
...registered(X, Y), (Y=ct101; Y=ct102; Y=ct103).
Note the parenthesis are required to keep the correct execution control flow. The ;
/2 it's the general or
operator. For your restricted use you could as well choice the more idiomatic
...registered(X, Y), member(Y, [ct101,ct102,ct103]).
that on backtracking binds Y to each member of the list.
edit I understood with a delay your last requirement. If you want that Y match all 3 values the or is inappropriate, use instead
...registered(X, ct101), registered(X, ct102), registered(X, ct103).
or the more compact
...findall(Y, registered(X, Y), L), sort(L, [ct101,ct102,ct103]).
findall/3 build the list in the very same order that registered/2 succeeds. Then I use sort to ensure the matching.
...setof(Y, registered(X, Y), [ct101,ct102,ct103]).
setof/3 also sorts the result list
try this link from github.
https://github.com/mofneko/EmulatorDetector
This module help you to emulator detection to your Android project suported Unity.
Basic checker
Use findElement
instead of findElements
driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).sendKeys("your value");
OR
driver.findElement(By.id("invoice_supplier_id")).sendKeys("value", "your value");
OR using JavascriptExecutor
WebElement element = driver.findElement(By.xpath("enter the xpath here")); // you can use any locator
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].value='enter the value here';", element);
OR
(JavascriptExecutor) driver.executeScript("document.evaluate(xpathExpresion, document, null, 9, null).singleNodeValue.innerHTML="+ DesiredText);
OR (in javascript)
driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).setAttribute("value", "your value")
Hope it will help you :)
You can have an auto-Incrementing column that is not the PRIMARY KEY
, as long as there is an index (key) on it:
CREATE TABLE members (
id int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
memberid VARCHAR( 30 ) NOT NULL ,
`time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
firstname VARCHAR( 50 ) NULL ,
lastname VARCHAR( 50 ) NULL ,
PRIMARY KEY (memberid) ,
KEY (id) --- or: UNIQUE KEY (id)
) ENGINE = MYISAM;
with slice():
var a = [1,2,3,4];
var lastEl = a.slice(-1)[0]; // 4
// a is still [1,2,3,4]
with pop();
var a = [1,2,3,4];
var lastEl = a.pop(); // 4
// a is now [1,2,3]
see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array for more information
I think you will have to loop over the "inserted" table, which contains all rows that were updated. You can use a WHERE loop, or a WITH statement if your primary key is a GUID. This is the simpler (for me) to write, so here is my example. We use this approach, so I know for a fact it works fine.
ALTER TRIGGER [dbo].[RA2Newsletter] ON [dbo].[Reiseagent]
AFTER INSERT
AS
-- This is your primary key. I assume INT, but initialize
-- to minimum value for the type you are using.
DECLARE @rAgent_ID INT = 0
-- Looping variable.
DECLARE @i INT = 0
-- Count of rows affected for looping over
DECLARE @count INT
-- These are your old variables.
DECLARE @rAgent_Name NVARCHAR(50)
DECLARE @rAgent_Email NVARCHAR(50)
DECLARE @rAgent_IP NVARCHAR(50)
DECLARE @hotelID INT
DECLARE @retval INT
BEGIN
SET NOCOUNT ON ;
-- Get count of affected rows
SELECT @Count = Count(rAgent_ID)
FROM inserted
-- Loop over rows affected
WHILE @i < @count
BEGIN
-- Get the next rAgent_ID
SELECT TOP 1
@rAgent_ID = rAgent_ID
FROM inserted
WHERE rAgent_ID > @rAgent_ID
ORDER BY rAgent_ID ASC
-- Populate values for the current row
SELECT @rAgent_Name = rAgent_Name,
@rAgent_Email = rAgent_Email,
@rAgent_IP = rAgent_IP,
@hotelID = hotelID
FROM Inserted
WHERE rAgent_ID = @rAgent_ID
-- Run your stored procedure
EXEC insert2Newsletter '', '', @rAgent_Name, @rAgent_Email,
@rAgent_IP, @hotelID, 'RA', @retval
-- Set up next iteration
SET @i = @i + 1
END
END
GO
I sure hope this helps you out. Cheers!
in menu bar click on Edit->preference->advance at bottom click the check box true that is for Show develop menu in menu bar now a develop menu is display at menu bar where you can see all develop option and inspect.
You can do this too
Before you use this you must declare the DB facade in the controller Simply put this line for that
use Illuminate\Support\Facades\DB;
Now you can get a row using this
$getUserByEmail = DB::table('users')->where('email', $email)->first();
or by this too
$getUserByEmail = DB::select('SELECT * FROM users WHERE email = ?' , ['[email protected]']);
This one returns an array with only one item in it and while the first one returns an object. Keep that in mind.
Hope this helps.
Accessing controller method means accessing a method on parent scope from directive controller/link/scope.
If the directive is sharing/inheriting the parent scope then it is quite straight forward to just invoke a parent scope method.
Little more work is required when you want to access parent scope method from Isolated directive scope.
There are few options (may be more than listed below) to invoke a parent scope method from isolated directives scope or watch parent scope variables (option#6 specially).
Note that I used link function
in these examples but you can use a directive controller
as well based on requirement.
Option#1. Through Object literal and from directive html template
index.html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<p> Directive Content</p>
<sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged(selectedItems)" items="items"> </sd-items-filter>
<P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnedFromDirective}} </p>
</body>
</html>
itemfilterTemplate.html
<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" ng-change="selectedItemsChanged({selectedItems:selectedItems})" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
<option>--</option>
</select>
app.js
var app = angular.module('plunker', []);
app.directive('sdItemsFilter', function() {
return {
restrict: 'E',
scope: {
items: '=',
selectedItems: '=',
selectedItemsChanged: '&'
},
templateUrl: "itemfilterTemplate.html"
}
})
app.controller('MainCtrl', function($scope) {
$scope.name = 'TARS';
$scope.selectedItems = ["allItems"];
$scope.selectedItemsChanged = function(selectedItems1) {
$scope.selectedItemsReturnedFromDirective = selectedItems1;
}
$scope.items = [{
"id": "allItems",
"name": "All Items",
"order": 0
}, {
"id": "CaseItem",
"name": "Case Item",
"model": "PredefinedModel"
}, {
"id": "Application",
"name": "Application",
"model": "Bank"
}]
});
working plnkr: http://plnkr.co/edit/rgKUsYGDo9O3tewL6xgr?p=preview
Option#2. Through Object literal and from directive link/scope
index.html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<p> Directive Content</p>
<sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged(selectedItems)" items="items"> </sd-items-filter>
<P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnedFromDirective}} </p>
</body>
</html>
itemfilterTemplate.html
<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;"
ng-change="selectedItemsChangedDir()" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
<option>--</option>
</select>
app.js
var app = angular.module('plunker', []);
app.directive('sdItemsFilter', function() {
return {
restrict: 'E',
scope: {
items: '=',
selectedItems: '=',
selectedItemsChanged: '&'
},
templateUrl: "itemfilterTemplate.html",
link: function (scope, element, attrs){
scope.selectedItemsChangedDir = function(){
scope.selectedItemsChanged({selectedItems:scope.selectedItems});
}
}
}
})
app.controller('MainCtrl', function($scope) {
$scope.name = 'TARS';
$scope.selectedItems = ["allItems"];
$scope.selectedItemsChanged = function(selectedItems1) {
$scope.selectedItemsReturnedFromDirective = selectedItems1;
}
$scope.items = [{
"id": "allItems",
"name": "All Items",
"order": 0
}, {
"id": "CaseItem",
"name": "Case Item",
"model": "PredefinedModel"
}, {
"id": "Application",
"name": "Application",
"model": "Bank"
}]
});
working plnkr: http://plnkr.co/edit/BRvYm2SpSpBK9uxNIcTa?p=preview
Option#3. Through Function reference and from directive html template
index.html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<p> Directive Content</p>
<sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged" items="items"> </sd-items-filter>
<P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnFromDirective}} </p>
</body>
</html>
itemfilterTemplate.html
<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;"
ng-change="selectedItemsChanged()(selectedItems)" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
<option>--</option>
</select>
app.js
var app = angular.module('plunker', []);
app.directive('sdItemsFilter', function() {
return {
restrict: 'E',
scope: {
items: '=',
selectedItems:'=',
selectedItemsChanged: '&'
},
templateUrl: "itemfilterTemplate.html"
}
})
app.controller('MainCtrl', function($scope) {
$scope.name = 'TARS';
$scope.selectedItems = ["allItems"];
$scope.selectedItemsChanged = function(selectedItems1) {
$scope.selectedItemsReturnFromDirective = selectedItems1;
}
$scope.items = [{
"id": "allItems",
"name": "All Items",
"order": 0
}, {
"id": "CaseItem",
"name": "Case Item",
"model": "PredefinedModel"
}, {
"id": "Application",
"name": "Application",
"model": "Bank"
}]
});
working plnkr: http://plnkr.co/edit/Jo6FcYfVXCCg3vH42BIz?p=preview
Option#4. Through Function reference and from directive link/scope
index.html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<p> Directive Content</p>
<sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged" items="items"> </sd-items-filter>
<P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnedFromDirective}} </p>
</body>
</html>
itemfilterTemplate.html
<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" ng-change="selectedItemsChangedDir()" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
<option>--</option>
</select>
app.js
var app = angular.module('plunker', []);
app.directive('sdItemsFilter', function() {
return {
restrict: 'E',
scope: {
items: '=',
selectedItems: '=',
selectedItemsChanged: '&'
},
templateUrl: "itemfilterTemplate.html",
link: function (scope, element, attrs){
scope.selectedItemsChangedDir = function(){
scope.selectedItemsChanged()(scope.selectedItems);
}
}
}
})
app.controller('MainCtrl', function($scope) {
$scope.name = 'TARS';
$scope.selectedItems = ["allItems"];
$scope.selectedItemsChanged = function(selectedItems1) {
$scope.selectedItemsReturnedFromDirective = selectedItems1;
}
$scope.items = [{
"id": "allItems",
"name": "All Items",
"order": 0
}, {
"id": "CaseItem",
"name": "Case Item",
"model": "PredefinedModel"
}, {
"id": "Application",
"name": "Application",
"model": "Bank"
}]
});
working plnkr: http://plnkr.co/edit/BSqx2J1yCY86IJwAnQF1?p=preview
Option#5: Through ng-model and two way binding, you can update parent scope variables.. So, you may not require to invoke parent scope functions in some cases.
index.html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<p> Directive Content</p>
<sd-items-filter ng-model="selectedItems" selected-items-changed="selectedItemsChanged" items="items"> </sd-items-filter>
<P style="color:red">Selected Items (in parent controller) set to: {{selectedItems}} </p>
</body>
</html>
itemfilterTemplate.html
<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;"
ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
<option>--</option>
</select>
app.js
var app = angular.module('plunker', []);
app.directive('sdItemsFilter', function() {
return {
restrict: 'E',
scope: {
items: '=',
selectedItems: '=ngModel'
},
templateUrl: "itemfilterTemplate.html"
}
})
app.controller('MainCtrl', function($scope) {
$scope.name = 'TARS';
$scope.selectedItems = ["allItems"];
$scope.items = [{
"id": "allItems",
"name": "All Items",
"order": 0
}, {
"id": "CaseItem",
"name": "Case Item",
"model": "PredefinedModel"
}, {
"id": "Application",
"name": "Application",
"model": "Bank"
}]
});
working plnkr: http://plnkr.co/edit/hNui3xgzdTnfcdzljihY?p=preview
Option#6: Through $watch
and $watchCollection
It is two way binding for items
in all above examples, if items are modified in parent scope, items in directive would also reflect the changes.
If you want to watch other attributes or objects from parent scope, you can do that using $watch
and $watchCollection
as given below
html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{user}}!</p>
<p>directive is watching name and current item</p>
<table>
<tr>
<td>Id:</td>
<td>
<input type="text" ng-model="id" />
</td>
</tr>
<tr>
<td>Name:</td>
<td>
<input type="text" ng-model="name" />
</td>
</tr>
<tr>
<td>Model:</td>
<td>
<input type="text" ng-model="model" />
</td>
</tr>
</table>
<button style="margin-left:50px" type="buttun" ng-click="addItem()">Add Item</button>
<p>Directive Contents</p>
<sd-items-filter ng-model="selectedItems" current-item="currentItem" name="{{name}}" selected-items-changed="selectedItemsChanged" items="items"></sd-items-filter>
<P style="color:red">Selected Items (in parent controller) set to: {{selectedItems}}</p>
</body>
</html>
script app.js
var app = angular.module('plunker', []);
app.directive('sdItemsFilter', function() {
return {
restrict: 'E',
scope: {
name: '@',
currentItem: '=',
items: '=',
selectedItems: '=ngModel'
},
template: '<select ng-model="selectedItems" multiple="multiple" style="height: 140px; width: 250px;"' +
'ng-options="item.id as item.name group by item.model for item in items | orderBy:\'name\'">' +
'<option>--</option> </select>',
link: function(scope, element, attrs) {
scope.$watchCollection('currentItem', function() {
console.log(JSON.stringify(scope.currentItem));
});
scope.$watch('name', function() {
console.log(JSON.stringify(scope.name));
});
}
}
})
app.controller('MainCtrl', function($scope) {
$scope.user = 'World';
$scope.addItem = function() {
$scope.items.push({
id: $scope.id,
name: $scope.name,
model: $scope.model
});
$scope.currentItem = {};
$scope.currentItem.id = $scope.id;
$scope.currentItem.name = $scope.name;
$scope.currentItem.model = $scope.model;
}
$scope.selectedItems = ["allItems"];
$scope.items = [{
"id": "allItems",
"name": "All Items",
"order": 0
}, {
"id": "CaseItem",
"name": "Case Item",
"model": "PredefinedModel"
}, {
"id": "Application",
"name": "Application",
"model": "Bank"
}]
});
You can always refer AngularJs documentation for detailed explanations about directives.
Yup...since Java 5: http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html
$("#table tr").click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:first').html();
alert(value);
});
$('.ok').on('click', function(e){
alert($("#table tr.selected td:first").html());
});
Demo:
you can write a stored procedure like this:
CREATE PROCEDURE sanitize_TABLE()
BEGIN
#replace space with underscore
UPDATE Table SET FieldName = REPLACE(FieldName," ","_") WHERE FieldName is not NULL;
#delete dot
UPDATE Table SET FieldName = REPLACE(FieldName,".","") WHERE FieldName is not NULL;
#delete (
UPDATE Table SET FieldName = REPLACE(FieldName,"(","") WHERE FieldName is not NULL;
#delete )
UPDATE Table SET FieldName = REPLACE(FieldName,")","") WHERE FieldName is not NULL;
#raplace or delete any char you want
#..........................
END
In this way you have modularized control over table.
You can also generalize stored procedure making it, parametric with table to sanitoze input parameter
Latecomer to the party here. I'm extremely surprised none of the answers mention the simplest, fastest, most portable solution; the case
statement.
case ${variable#[-+]} in
*[!0-9]* | '') echo Not a number ;;
* ) echo Valid number ;;
esac
The trimming of any sign before the comparison feels like a bit of a hack, but that makes the expression for the case statement so much simpler.
self
is an object reference to the object itself, therefore, they are same.
Python methods are not called in the context of the object itself.
self
in Python may be used to deal with custom object models or something.
CONNECTION_REFUSED is standard when the port is closed, but it could be rejected because SSL is failing authentication (one of a billion reasons). Did you configure SSL with Ratchet? (Apache is bypassed) Did you try without SSL in JavaScript?
I don't think Ratchet has built-in support for SSL. But even if it does you'll want to try the ws:// protocol first; it's a lot simpler, easier to debug, and closer to telnet. Chrome or the socket service may also be generating the REFUSED error if the service doesn't support SSL (because you explicitly requested SSL).
However the refused message is likely a server side problem, (usually port closed).
Samsung Galaxy Ace advertises 158 MB of internal storage in its specifications, but the core applications and services consume about 110 MB of that (I used the task manager on the device to inspect this). My app was 52 MB, because it had a lot of assets. Once I deleted some of those down to 45 MB, the app managed to install without a problem. The device was still alerting me that internal storage was almost full, and I should uninstall some apps, even though I only had one app installed.
After installing a release version of the .apk bundle and then uninstalling it, my device displays 99 MB of free space, so it might be debugging information cluttering up the device after all. See Louis Semprini's answer.
This is the solution (from this post)
video::-internal-media-controls-download-button {
display:none;
}
video::-webkit-media-controls-enclosure {
overflow:hidden;
}
video::-webkit-media-controls-panel {
width: calc(100% + 30px); /* Adjust as needed */
}
Update 2 : New Solution by @Remo
<video width="512" height="380" controls controlsList="nodownload">
<source data-src="mov_bbb.ogg" type="video/mp4">
</video>
Adding a StreamHandler without arguments goes to stderr instead of stdout. If some other process has a dependency on the stdout dump (i.e. when writing an NRPE plugin), then make sure to specify stdout explicitly or you might run into some unexpected troubles.
Here's a quick example reusing the assumed values and LOGFILE from the question:
import logging
from logging.handlers import RotatingFileHandler
from logging import handlers
import sys
log = logging.getLogger('')
log.setLevel(logging.DEBUG)
format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch = logging.StreamHandler(sys.stdout)
ch.setFormatter(format)
log.addHandler(ch)
fh = handlers.RotatingFileHandler(LOGFILE, maxBytes=(1048576*5), backupCount=7)
fh.setFormatter(format)
log.addHandler(fh)
If you are using ipython in linux, then follow the steps:
!cd /directory_name/
You can try all the commands which work in you linux terminal.
!vi file_name.py
Just specify the exclamation(!) symbol before your linux commands.
You could use asprintf
to concatenate both into a new string:
char *new_str;
asprintf(&new_str,"%s%s",str1,str2);
Use the format()
function with a '02x'
format.
>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'
The 02
part tells format()
to use at least 2 digits and to use zeros to pad it to length, x
means lower-case hexadecimal.
The Format Specification Mini Language also gives you X
for uppercase hex output, and you can prefix the field width with #
to include a 0x
or 0X
prefix (depending on wether you used x
or X
as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:
>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'
for using git you have to be
root
if not then use sudo
for removing origin :
git remote remove origin
for adding origin :
git remote add origin http://giturl
If you don't want to make the button a separate image, you can use the <area>
tag. This is done by using html similar to this:
<img src="imgsrc" width="imgwidth" height="imgheight" alt="alttext" usemap="#mapname">
<map name="mapname">
<area shape="rect" coords="see note 1" href="link" alt="alttext">
</map>
Note 1: The coords=" "
attribute must be formatted in this way: coords="x1,y1,x2,y2"
where:
x1=top left X coordinate
y1=top left Y coordinate
x2=bottom right X coordinate
y2=bottom right Y coordinate
Note 2: The usemap="#mapname"
attribute must include the #
.
EDIT:
I looked at your code and added in the <map>
and <area>
tags where they should be. I also commented out some parts that were either overlapping the image or seemed there for no use.
<div class="flexslider">
<ul class="slides" runat="server" id="Ul">
<li class="flex-active-slide" style="background: url("images/slider-bg-1.jpg") no-repeat scroll 50% 0px transparent; width: 100%; float: left; margin-right: -100%; position: relative; display: list-item;">
<div class="container">
<div class="sixteen columns contain"></div>
<img runat="server" id="imgSlide1" style="top: 1px; right: -19px; opacity: 1;" class="item" src="./test.png" data-topimage="7%" height="358" width="728" usemap="#imgmap" />
<map name="imgmap">
<area shape="rect" coords="48,341,294,275" href="http://www.example.com/">
</map>
<!--<a href="#" style="display:block; background:#00F; width:356px; height:66px; position:absolute; left:1px; top:-19px; left: 162px; top: 279px;"></a>-->
</div>
</li>
</ul>
</div>
<!-- <ul class="flex-direction-nav">
<li><a class="flex-prev" href="#"><i class="icon-angle-left"></i></a></li>
<li><a class="flex-next" href="#"><i class="icon-angle-right"></i></a></li>
</ul> -->
Notes:
coord="48,341,294,275"
is in reference to your screenshot you posted.src="./test.png"
is the location and name of the screenshot you posted on my computer.href="http://www.example.com/"
is an example link.This error can be thrown when you import a different library for @Id than Javax.persistance.Id ; You might need to pay attention this case too
In my case I had
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;
import org.springframework.data.annotation.Id;
@Entity
public class Status {
@Id
@GeneratedValue
private int id;
when I change the code like this, it got worked
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Table;
import javax.persistence.Id;
@Entity
public class Status {
@Id
@GeneratedValue
private int id;
More compact version working with spaces and newlines in the file name:
find . -iname '*.txt' -exec sh -c 'echo "{}" ; ls -l "{}"' \;
git reset --hard origin/master
will remove all commits not in origin/master
where origin
is the repo name and master
is the name of the branch.
They key is the backslash escape character will not work with the right square bracket inside of the character class square brackets (it is interpreted as a literal backslash inside the character class square brackets). Add the right square bracket with an OR at the end like this:
select EmpNo, SampleText
from test
where NOT regexp_like(SampleText, '[ A-Za-z0-9.{}[]|]');
In your compare
method, o1
and o2
are already elements in the movieItems
list. So, you should do something like this:
Collections.sort(movieItems, new Comparator<Movie>() {
public int compare(Movie m1, Movie m2) {
return m1.getDate().compareTo(m2.getDate());
}
});
To get default java settings just use :
java -XshowSettings
The only solution that worked for me: http://docs.moodle.org/23/en/Converting_your_MySQL_database_to_UTF8
mysqldump -uusername -ppassword -c -e --default-character-set=utf8 --single-transaction --skip-set-charset --add-drop-database -B dbname > dump.sql
cp dump.sql dump-fixed.sql
vim dump-fixed.sql
:%s/DEFAULT CHARACTER SET latin1/DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci/
:%s/DEFAULT CHARSET=latin1/DEFAULT CHARSET=utf8/
:wq
mysql -uusername -ppassword < dump-fixed.sql
In my case, I need to update selected value at each change because when I submit form, it always gets wrong values and I used multiple chosen drop downs. Rather than updating single entries, change selector to update all drop downs. This might help someone
$(".chosen-select").chosen().change(function () {
var item = $(this).val();
$('.chosen-select').trigger('chosen:updated');
});
Here's a one-liner using Maven:
mvn dependency:get -Dartifact=mysql:mysql-connector-java:5.1.38
Then, with default settings, it's available in:
$HOME/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar
Just replace the version number if you need a different one.
to ckeck the status use the below command, which worked on debian....
/etc/init.d/mysql status
to start my sql server use the below command
/etc/init.d/mysql start
to stop the server use the below command
/etc/init.d/mysql stop
Let's say that your remote is [email protected] and you want its random_branch branch. The process should be as follows:
First check the list of your remotes by
git remote -v
If you don't have the [email protected] remote in the above command's output, you would add it by
git remote add xyz [email protected]
git fetch xyz
git checkout -b my_copy_random_branch xyz/random_branch
git branch -a
The local branch my_copy_random_branch would be tracking the random_branch branch of your remote.
Dim sFileName As String
Dim iFileNum As Integer
Dim sBuf As String
Dim Fields as String
Dim TempStr as String
sFileName = "c:\fields.ini"
''//Does the file exist?
If Len(Dir$(sFileName)) = 0 Then
MsgBox ("Cannot find fields.ini")
End If
iFileNum = FreeFile()
Open sFileName For Input As iFileNum
''//This part skips the first two lines
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr
Do While Not EOF(iFileNum)
Line Input #iFileNum, Fields
MsgBox (Fields)
Loop
Use the Ctrl+Space
shortcut for getting all possible autocomplete options available in a particular context in the editor.
Auto Complete will also allow you to insert custom code templates into the editor, with placeholders for various inputs. For instance, attempting to auto complete the word "test" in a Java editor, in the context of a class body, will allow you to create a unit test that uses JUnit; you'll have to code the body of the method though. Some code templates like the former, come out of the box.
Configuration options of interest
.
character by default. When you have just keyed in typeA.
and you expect to see relevant members that can be accessed, the auto completion list will automatically popup with the appropriate members, on this trigger.The simplest thing would be to check the timestamp of the table files on the disk. For example, You can check under your data directory
cd /var/lib/mysql/<mydatabase>
ls -lhtr *.ibd
This should give you the list of all tables with the table when it was last modified the oldest time, first.
I'd like to find something official like this - 15.6.2.1 Clustered and Secondary Indexes - MySQL.
If the table has no PRIMARY KEY or suitable UNIQUE index, InnoDB internally generates a hidden clustered index named GEN_CLUST_INDEX on a synthetic column containing row ID values. The rows are ordered by the ID that InnoDB assigns to the rows in such a table. The row ID is a 6-byte field that increases monotonically as new rows are inserted. Thus, the rows ordered by the row ID are physically in insertion order.
So, why not create primary key or something like it by yourself? Besides, ORM cannot identify this hidden ID, meaning that you cannot use ID in your code.
If you aren't actually restricted to keeping all of these elements as sibling nodes you can wrap the ones that go together in another default flex box, and have the container of both use space-between.
.space-between {_x000D_
border: 1px solid red;_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.default-flex {_x000D_
border: 1px solid blue;_x000D_
display: flex;_x000D_
}_x000D_
.child {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
border: 1px solid;_x000D_
}
_x000D_
<div class="space-between">_x000D_
<div class="child">1</div>_x000D_
<div class="default-flex">_x000D_
<div class="child">2</div>_x000D_
<div class="child">3</div>_x000D_
<div class="child">4</div>_x000D_
<div class="child">5</div>_x000D_
</div>_x000D_
</div>
_x000D_
Or if you were doing the same thing with flex-start and flex-end reversed you just swap the order of the default-flex container and lone child.
Two possible issues could be
To include Servlet jar in your class path in eclipse, Download the latest Servlet Jar and configure using buildpath option. look at this Link for more info.
If you have included the jar make sure that your import is declared.
import javax.servlet.http.HttpServletResponse
Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644
or 755
(spelled (100644
and 100755
; the 100
part means "regular file"):
diff --git a/path b/path
new file mode 100644
The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask
setting, which would normally be 022
to remove write permission from "group" and "other", or 002
to remove write permission only from "other". It might also be 077
if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".
1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664
in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.
The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.
imo the best approach is using GraphicsMagick Image Processing System with im4java as a comand-line interface for Java.
There are a lot of advantages of GraphicsMagick, but one for all:
The python version could be:
re.compile(r'\A(?:[\da-f]{2}[:-]){5}[\da-f]{2}\Z',re.I)
It just means it expects that as a key in your header data
import requests
endpoint = ".../api/ip"
data = {"ip": "1.1.2.3"}
headers = {"Authorization": "Bearer MYREALLYLONGTOKENIGOT"}
print(requests.post(endpoint, data=data, headers=headers).json())
For xml formatted with attributes...
data.xml:
<building_data>
<building address="some address" lat="28.902914" lng="-71.007235" />
<building address="some address" lat="48.892342" lng="-75.0423423" />
<building address="some address" lat="58.929753" lng="-79.1236987" />
</building_data>
php code:
$reader = new XMLReader();
if (!$reader->open("data.xml")) {
die("Failed to open 'data.xml'");
}
while($reader->read()) {
if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'building') {
$address = $reader->getAttribute('address');
$latitude = $reader->getAttribute('lat');
$longitude = $reader->getAttribute('lng');
}
$reader->close();
it's well documented here:
https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q6
How do I bind to a specific ip address? - "Each Connector element allows an address property. See the HTTP Connector docs or the AJP Connector docs". And HTTP Connectors docs:
http://tomcat.apache.org/tomcat-7.0-doc/config/http.html
Standard Implementation -> address
"For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server."
Dim SaveVar As Object
Sub Main()
Console.WriteLine("Enter Text")
Console.WriteLine("")
SaveVar = Console.ReadLine
My.Computer.FileSystem.WriteAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt", "Text: " & SaveVar & ", ", True)
Console.WriteLine("")
Console.WriteLine("File Saved")
Console.WriteLine("")
Console.WriteLine(My.Computer.FileSystem.ReadAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt"))
Console.ReadLine()
End Sub()
This code work as well, instead eval the html i'm going to append the script to the head
function RunJS(objID) {
//alert(http_request.responseText);
var c="";
var ob = document.getElementById(objID).getElementsByTagName("script");
for (var i=0; i < ob.length - 1; i++) {
if (ob[i + 1].text != null)
c+=ob[i + 1].text;
}
var s = document.createElement("script");
s.type = "text/javascript";
s.text = c;
document.getElementsByTagName("head")[0].appendChild(s);
}
Expanding off of what @twalberg and @iconoclast had, if you're using cmd for whatever reason, you can use:
FOR /F "usebackq" %x IN (`"git branch | grep '*' | cut -f2 -d' '"`) DO FOR /F "usebackq" %y IN (`"git merge-base %x master"`) DO git diff --name-only %x %y
There are (at least) two things you can do here–you can reclone the remote repo, or you can reset --hard
to the common ancestor and then do a pull, which will fast-forward to the latest commit on the remote master.
To be concrete, here's a simple extension of Nevik Rehnel's original answer:
git reset --hard origin/master
git pull origin master
NOTE: using git reset --hard
will discard any uncommitted changes, and it can be easy to confuse yourself with this command if you're new to git, so make sure you have a sense of what it is going to do before proceeding.
...you can (ab)use list comprehension scoping changes and do it in a single expression:
is_python_3_or_above = (lambda x: [x for x in [False]] and None or x)(True)
Much simpler using only SimpleDateFormat, without passing all the parameters individual:
String FORMATER = "yyyy-MM-dd'T'HH:mm:ss'Z'";
DateFormat format = new SimpleDateFormat(FORMATER);
Date date = new Date();
XMLGregorianCalendar gDateFormatted =
DatatypeFactory.newInstance().newXMLGregorianCalendar(format.format(date));
Full example here.
Note: This is working only to remove the last 2 fields: milliseconds and timezone or to remove the entire time component using formatter yyyy-MM-dd
.
I had this problem just now, I had to do git rm -f .idea/workspace.xml
now it seems to be gone (I also had to put it into .gitignore
)
The only way not to capture something is using look-around assertions:
(?<=123-)((apple|banana)(?=-456)|(?=456))
Because even with non-capturing groups (?:…)
the whole regular expression captures their matched contents. But this regular expression matches only apple
or banana
if it’s preceded by 123-
and followed by -456
, or it matches the empty string if it’s preceded by 123-
and followed by 456
.
|Lookaround | Name | What it Does |
-----------------------------------------------------------------------
|(?=foo) | Lookahead | Asserts that what immediately FOLLOWS the |
| | | current position in the string is foo |
-------------------------------------------------------------------------
|(?<=foo) | Lookbehind | Asserts that what immediately PRECEDES the|
| | | current position in the string is foo |
-------------------------------------------------------------------------
|(?!foo) | Negative | Asserts that what immediately FOLLOWS the |
| | Lookahead | current position in the string is NOT foo|
-------------------------------------------------------------------------
|(?<!foo) | Negative | Asserts that what immediately PRECEDES the|
| | Lookbehind | current position in the string is NOT foo|
-------------------------------------------------------------------------
The difference comes in when you use the struct
.
The first way you have to do:
struct myStruct aName;
The second way allows you to remove the keyword struct
.
myStruct aName;
Reason for the error: In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column. Source:MSDN
Actual Code which I faced error:
Before changed the code:
if( ds.Tables[0].Rows[0][0] == null ) // Which is not working
{
seqno = 1;
}
else
{
seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;
}
After changed the code:
if( ds.Tables[0].Rows[0][0] == DBNull.Value ) //which is working properly
{
seqno = 1;
}
else
{
seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;
}
Conclusion: when the database value return the null value, we recommend to use the DBNull class instead of just specifying as a null like in C# language.
You can use the ??
test operator:
This checks if the attribute of the object is not null:
<#if object.attribute??></#if>
This checks if object or attribute is not null:
<#if (object.attribute)??></#if>
Source: FreeMarker Manual
<input type="text" autocomplete="off" />
Putting together comments from a couple different answers here, in the Solr docs and on the other SO question, I found that the following syntax produces the correct result for my use case
(my_field=my_value or my_field is null):
(my_field:"my_value" OR (*:* NOT my_field:*))
This works for solr 4.1.0. This is slightly different than the use case in the OP; but, I thought that others would find it useful.