Basic Steps to Debug a Procedure in Toad
Reference:Toad Debugger
It is because of conflicting SID. For example, in your Oracle12cBase\app\product\12.1.0\dbhome_1\NETWORK\ADMIN\tnsnames.ora file, connection description for ORCL is this:
ORCL =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = orcl)
)
)
And, you are trying to connect using the connection string using same SID but different IP, username/password, like this:
sqlplus username/[email protected]:1521/orcl
To resolve this, make changes in the tnsnames.ora file:
ORCL =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.130.52)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = orcl)
)
)
IF
is a PL/SQL construct. If you are executing a query, you are using SQL not PL/SQL.
In SQL, you can use a CASE
statement in the query itself
SELECT DISTINCT a.item,
(CASE WHEN b.salesman = 'VIKKIE'
THEN 'ICKY'
ELSE b.salesman
END),
NVL(a.manufacturer,'Not Set') Manufacturer
FROM inv_items a,
arv_sales b
WHERE a.co = '100'
AND a.co = b.co
AND A.ITEM_KEY = b.item_key
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
and to_date('011713','mmddrr')
ORDER BY a.item
Since you aren't doing any aggregation, you don't want a GROUP BY
in your query. Are you really sure that you need the DISTINCT
? People often throw that in haphazardly or add it when they are missing a join condition rather than considering whether it is really necessary to do the extra work to identify and remove duplicates.
Not necessary to execute as script
There is another option: with
syntax. To use the OPs example, this would look like:
with data as (
select 'value1' name from dual
union all
select 'value2' name from dual
union all
...
select 'value10000+' name from dual)
select field1, field2, field3
from table1 t1
inner join data on t1.name = data.name;
I ran into this problem. In my case I had a list of data in Java where each item had an item_id and a customer_id. I have two tables in the DB with subscriptions to items respective customers. I want to get a list of all subscriptions to the items or to the customer for that item, together with the item id.
I tried three variants:
Option 1: Multiple Selects from Java
Basically, I first
select item_id, token
from item_subs
where (item_id, 0) in ((:item_id_0, 0)...(:item_id_n, 0))
Then
select cus_id, token
from cus_subs
where (cus_id, 0) in ((:cus_id_0, 0)...(:cus_id_n, 0))
Then I build a Map in Java with the cus_id as the key and a list of items as value, and for each found customer subscription I add (to the list returned from the first select) an entry for all relevant items with that item_id. It's much messier code
Option 2: With-syntax
Get everything at once with an SQL like
with data as (
select :item_id_0 item_id, :cus_id_0 cus_id
union all
...
select :item_id_n item_id, :cus_id_n cus_id )
select I.item_id item_id, I.token token
from item_subs I
inner join data D on I.item_id = D.item_id
union all
select D.item_id item_id, C.token token
from cus_subs C
inner join data D on C.cus_id = D.cus_id
Option 3: Temporary table
Create a global temporary table with three fields: rownr (primary key), item_id and cus_id. Insert all the data there then run a very similar select to option 2, but linking in the temporary table instead of the with data
Performance
This is not a fully-scientific performance analysis.
YMMV.
That said, the temporary table option was much slower. As in double so slow. I was getting 14-15 seconds for option 1, 15-16 for option 2 and 30 for option 3.
I'll try them again from the same network as the DB server and check if that changes things when I get the chance.
If you use UPPER(text)
, the like '%lah%'
will always return zero results. Use '%LAH%'
.
Remove the semicolon ( ; ).
In oracle, you can use semicolon or not when u ran query directly on DB. But when u using java to ran a oracle query, u have to remove semicolon at the end.
I just added the oracle folder to my environmental variables and that fixed my identical error
You may not have permission to dba_sequences. So you can always just do:
select * from user_sequences;
How about this one?
SELECT TO_CHAR(ASOFDATE, 'YYYY') FROM PSASOFDATE
If the date String does not include any value for hours, minutes and etc you cannot directly convert this to a LocalDateTime
. You can only convert it to a LocalDate
, because the string only represent the year,month and date components it would be the correct thing to do.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf); // 2018-03-06
Anyway you can convert this to LocalDateTime
.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf);
LocalDateTime ldt = LocalDateTime.of(ld, LocalTime.of(0,0)); // 2018-03-06T00:00
The only difference i've noted is that things set in a relative layout via drag and drop automatically have their dimensions relative to other elements inferred, so when you run the app what you see is what you get. However in the constraint layout even if you drag and drop an element in the design view, when you run the app things may be shifted around. This can easily be fixed by manually setting the constraints or, a more risky move being to right click the element in the component tree, selecting the constraint layout sub menu, then clicking 'infer constraints'. Hope this helps
Reinstalling android studio worked for me.
Precision is the total number of digits, can be between 1 and 38.
Scale is the number of digits after the decimal point, may also be set as negative for rounding.
Example:
NUMBER(7,5): 12.12345
NUMBER(5,0): 12345
More details on the ORACLE website:
https://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT1832
This is the most simple, and it worked for me:
In the values-21:
<resources>
<style name="AppTheme" parent="AppTheme.Base">
...
<item name="android:windowTranslucentStatus">true</item>
</style>
<dimen name="topMargin">25dp</dimen>
</resources>
In the values:
<resources>
<dimen name="topMargin">0dp</dimen>
</resources>
And set to your toolbar
android:layout_marginTop="@dimen/topMargin"
Storytime!
C, as a language, is an abstraction of a computer. It allows you to do things, in terms of what a computer does, that is manipulate memory, do math, print things, etc.
But C is only an abstraction. And ultimately, what it's extracting from you is Assembly language. Assembly is the language that a CPU reads, and if you use it, you do things in terms of the CPU. What does a CPU do? Basically, it reads from memory, does math, and writes to memory. The CPU doesn't just do math on numbers in memory. First, you have to move a number from memory to memory inside the CPU called a register. Once you're done doing whatever you need to do to this number, you can move it back to normal system memory. Why use system memory at all? Registers are limited in number. You only get about a hundred bytes in modern processors, and older popular processors were even more fantastically limited (The 6502 had 3 8-bit registers for your free use). So, your average math operation looks like:
load first number from memory
load second number from memory
add the two
store answer into memory
A lot of that is... not math. Those load and store operations can take up to half your processing time. C, being an abstraction of computers, freed the programmer the worry of using and juggling registers, and since the number and type vary between computers, C places the responsibility of register allocation solely on the compiler. With one exception.
When you declare a variable register
, you are telling the compiler "Yo, I intend for this variable to be used a lot and/or be short lived. If I were you, I'd try to keep it in a register." When the C standard says compilers don't have to actually do anything, that's because the C standard doesn't know what computer you're compiling for, and it might be like the 6502 above, where all 3 registers are needed just to operate, and there's no spare register to keep your number. However, when it says you can't take the address, that's because registers don't have addresses. They're the processor's hands. Since the compiler doesn't have to give you an address, and since it can't have an address at all ever, several optimizations are now open to the compiler. It could, say, keep the number in a register always. It doesn't have to worry about where it's stored in computer memory (beyond needing to get it back again). It could even pun it into another variable, give it to another processor, give it a changing location, etc.
tl;dr: Short-lived variables that do lots of math. Don't declare too many at once.
In my case it was caused by number of executors (I had 1) and running Jenkins Job (Project) from Pipeline (my pipeline script started other Job in Jenkins). It caused deadlock - my pipeline held executor and was waiting for its job, but the job was waiting for free executor.
The solution may be increasing of # of executors
in Jenkins -> Manage Jenkins -> Manage Nodes -> Configure (icon on required node)
.
Note: you should use the accepted answer if possible. It's better than mine.
It's quite easy with the GD library.
It's built in usually, you probably have it (use phpinfo()
to check)
$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagejpeg($image, "folder/file.jpg");
The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).
$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");
This only works if allow_url_fopen
is true
(it is by default)
Using the std::bitset answers and convenience templates:
#include <iostream>
#include <bitset>
#include <climits>
template<typename T>
struct BinaryForm {
BinaryForm(const T& v) : _bs(v) {}
const std::bitset<sizeof(T)*CHAR_BIT> _bs;
};
template<typename T>
inline std::ostream& operator<<(std::ostream& os, const BinaryForm<T> bf) {
return os << bf._bs;
}
Using it like this:
auto c = 'A';
std::cout << "c: " << c << " binary: " << BinaryForm{c} << std::endl;
unsigned x = 1234;
std::cout << "x: " << x << " binary: " << BinaryForm{x} << std::endl;
int64_t z { -1024 };
std::cout << "z: " << << " binary: " << BinaryForm{z} << std::endl;
Generates output:
c: A binary: 01000001
x: 1234 binary: 00000000000000000000010011010010
z: -1024 binary: 1111111111111111111111111111111111111111111111111111110000000000
>>> a=["a","b","c","d","e"]
>>> a[0],a[3] = a[3],a[0]
>>> a
['d', 'b', 'c', 'a', 'e']
Change the value after the page loads
$('#data').val('').change();
SetOnClickListener (Android.View.view.OnClickListener) in View cannot be applied to (com.helloandroidstudio.MainActivity)
This means in other words (due to your current scenario) that your MainActivity need to implement OnClickListener:
public class Main extends ActionBarActivity implements View.OnClickListener {
// do your stuff
}
This:
buttonname.setOnClickListener(this);
means that you want to assign listener for your Button "on this instance" ->
this instance represents OnClickListener and for this reason your class have to implement that interface.
It's similar with anonymous listener class (that you can also use):
buttonname.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
I had the same problem today. My persistence.xml was in the wrong location. I had to put it in the following path:
project/src/main/resources/META-INF/persistence.xml
to_char(timestamp, 'YYYY-MM')
You say that the order is not "right", but I cannot see why it is wrong (at least until year 10000 comes around).
I just wrote a blog post on saving an object's data to Binary, XML, or Json. You are correct that you must decorate your classes with the [Serializable] attribute, but only if you are using Binary serialization. You may prefer to use XML or Json serialization. Here are the functions to do it in the various formats. See my blog post for more details.
/// <summary>
/// Writes the given object instance to a binary file.
/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the binary file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the binary file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, objectToWrite);
}
}
/// <summary>
/// Reads an object instance from a binary file.
/// </summary>
/// <typeparam name="T">The type of object to read from the binary file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the binary file.</returns>
public static T ReadFromBinaryFile<T>(string filePath)
{
using (Stream stream = File.Open(filePath, FileMode.Open))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
return (T)binaryFormatter.Deserialize(stream);
}
}
Requires the System.Xml assembly to be included in your project.
/// <summary>
/// Writes the given object instance to an XML file.
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var serializer = new XmlSerializer(typeof(T));
writer = new StreamWriter(filePath, append);
serializer.Serialize(writer, objectToWrite);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an XML file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the XML file.</returns>
public static T ReadFromXmlFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
var serializer = new XmlSerializer(typeof(T));
reader = new StreamReader(filePath);
return (T)serializer.Deserialize(reader);
}
finally
{
if (reader != null)
reader.Close();
}
}
You must include a reference to Newtonsoft.Json assembly, which can be obtained from the Json.NET NuGet Package.
/// <summary>
/// Writes the given object instance to a Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
writer = new StreamWriter(filePath, append);
writer.Write(contentsToWriteToFile);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the Json file.</returns>
public static T ReadFromJsonFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
reader = new StreamReader(filePath);
var fileContents = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(fileContents);
}
finally
{
if (reader != null)
reader.Close();
}
}
// Write the contents of the variable someClass to a file.
WriteToBinaryFile<SomeClass>("C:\someClass.txt", object1);
// Read the file contents back into a variable.
SomeClass object1= ReadFromBinaryFile<SomeClass>("C:\someClass.txt");
I got a similar problem. Breakpoints where not working unless I used debugger;
. I fixed my breakpoints problem with "Restore defaults and reload". It's located in the Chrome Developer Tools, Settings, Restore defaults and reload.
First you have to decode your json :
$array = json_decode($the_json_code);
Then after the json decoded you have to do the foreach
foreach ($array as $key => $jsons) { // This will search in the 2 jsons
foreach($jsons as $key => $value) {
echo $value; // This will show jsut the value f each key like "var1" will print 9
// And then goes print 16,16,8 ...
}
}
If you want something specific just ask for a key like this. Put this between the last foreach.
if($key == 'var1'){
echo $value;
}
so do the following edit my.cnf:
[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
language = /usr/share/mysql/English
bind-address = xxx.xxx.xxx.xxx
# skip-networking
after edit hit service mysqld restart
login into mysql and hit this query:
GRANT ALL ON foo.* TO bar@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'PASSWORD';
thats it make sure your iptables allow connection from 3306 if not put the following:
iptables -A INPUT -i lo -p tcp --dport 3306 -j ACCEPT
iptables -A OUTPUT -p tcp --sport 3306 -j ACCEPT
The method is to use another byte along with a bitwise AND to mask out the target bit.
I used convention from my classes here where "0" is the most significant bit and "7" is the least.
public static class ByteExtensions
{
// Assume 0 is the MSB andd 7 is the LSB.
public static bool GetBit(this byte byt, int index)
{
if (index < 0 || index > 7)
throw new ArgumentOutOfRangeException();
int shift = 7 - index;
// Get a single bit in the proper position.
byte bitMask = (byte)(1 << shift);
// Mask out the appropriate bit.
byte masked = (byte)(byt & bitMask);
// If masked != 0, then the masked out bit is 1.
// Otherwise, masked will be 0.
return masked != 0;
}
}
shorter way and easy to understand:
$('#someID').keypress(function(e) {
var k = e.which;
if (k <= 48 || k >= 58) {e.preventDefault()};
});
Instead of using divider in dialog, use the view in the custom layout and set the layout as custom layout in dialog.
custom_popup.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.divago.view.TextViewMedium
android:id="@+id/txtTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:text="AlertDialog"
android:textColor="@android:color/black"
android:textSize="20sp" />
<View
android:id="@+id/border"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="@id/txtTitle"
android:background="@color/txt_dark_grey" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/border"
android:scrollbars="vertical">
<com.divago.view.TextViewRegular
android:id="@+id/txtPopup"
android:layout_margin="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</RelativeLayout>
activity.java:
public void showPopUp(String title, String text) {
LayoutInflater inflater = getLayoutInflater();
View alertLayout = inflater.inflate(R.layout.custom_popup, null);
TextView txtContent = alertLayout.findViewById(R.id.txtPopup);
txtContent.setText(text);
TextView txtTitle = alertLayout.findViewById(R.id.txtTitle);
txtTitle.setText(title);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setView(alertLayout);
alert.setCancelable(true);
alert.setPositiveButton("Done", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = alert.create();
dialog.show();
}
perhaps this may be an alternative for you.
<input name="chkproperty" onchange="($(this).prop('checked') ? $(this).val(true) : $(this).val(false))" type="checkbox" value="true" />`
There is probably a smarter way, but you can add the headers manually like this:
var client = new IdentityProofingService.IdentityProofingWSClient();
using (new OperationContextScope(client.InnerChannel))
{
OperationContext.Current.OutgoingMessageHeaders.Add(
new SecurityHeader("UsernameToken-49", "12345/userID", "password123"));
client.invokeIdentityService(new IdentityProofingRequest());
}
Here, SecurityHeader
is a custom implemented class, which needs a few other classes since I chose to use attributes to configure the XML serialization:
public class SecurityHeader : MessageHeader
{
private readonly UsernameToken _usernameToken;
public SecurityHeader(string id, string username, string password)
{
_usernameToken = new UsernameToken(id, username, password);
}
public override string Name
{
get { return "Security"; }
}
public override string Namespace
{
get { return "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; }
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
XmlSerializer serializer = new XmlSerializer(typeof(UsernameToken));
serializer.Serialize(writer, _usernameToken);
}
}
[XmlRoot(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")]
public class UsernameToken
{
public UsernameToken()
{
}
public UsernameToken(string id, string username, string password)
{
Id = id;
Username = username;
Password = new Password() {Value = password};
}
[XmlAttribute(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")]
public string Id { get; set; }
[XmlElement]
public string Username { get; set; }
[XmlElement]
public Password Password { get; set; }
}
public class Password
{
public Password()
{
Type = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText";
}
[XmlAttribute]
public string Type { get; set; }
[XmlText]
public string Value { get; set; }
}
I have not added the Nonce
bit to the UsernameToken
XML, but it is very similar to the Password
one. The Created
element also needs to be added still, but it's a simple [XmlElement]
.
'ctrl'+'space' will open C/C++ autocomplete.
I am using <style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar>
theme in my android application and in NoActionBar theme, colorControlNormal
property is used to change the color of navigation icon default Back button arrow in my toolbar
styles.xml
<style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorControlNormal">@color/your_color</item>
</style>
You can use the date
function. I'm using strtotime
to get the timestamp to that day ; there are other solutions, like mktime
, for instance.
For instance, with the 'D' modifier, for the textual representation in three letters :
$timestamp = strtotime('2009-10-22');
$day = date('D', $timestamp);
var_dump($day);
You will get :
string 'Thu' (length=3)
And with the 'l' modifier, for the full textual representation :
$day = date('l', $timestamp);
var_dump($day);
You get :
string 'Thursday' (length=8)
Or the 'w' modifier, to get to number of the day (0 to 6, 0 being sunday, and 6 being saturday) :
$day = date('w', $timestamp);
var_dump($day);
You'll obtain :
string '4' (length=1)
/q isn't a valid parameter. /y: Suppresses prompting to confirm overwriting
Also ..\txt means directory txt under the parent directory, not the root directory. The root directory would be: \ And please mention the error you get
Try:
move files\*.txt \
Edit: Try:
move \files\*.txt \
Edit 2:
move C:\files\*.txt C:\txt
var funcs = []
for(var name in myObject) {
if(typeof myObject[name] === 'function') {
funcs.push(name)
}
}
I'm on a phone with no semi colons :) but that is the general idea.
I was trying to to the same, I found lots of information on reading .docx but much less on .doc; Anyway, I managed to read the text using the following:
import win32com.client
word = win32com.client.Dispatch("Word.Application")
word.visible = False
wb = word.Documents.Open("myfile.doc")
doc = word.ActiveDocument
print(doc.Range().Text)
You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.
$("button").click(function() {
var $btn = $(this);
$btn.button('loading');
// simulating a timeout
setTimeout(function () {
$btn.button('reset');
}, 1000);
});
Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.
For checking complete changes:
git diff <commit_Id_1> <commit_Id_2>
For checking only the changed/added/deleted files:
git diff <commit_Id_1> <commit_Id_2> --name-only
NOTE: For checking diff without commit in between, you don't need to put the commit ids.
There are many ways, for example:
Method one:
public string test()
{
string ErrMsg = string.Empty;
try
{
int num = int.Parse("gagw");
}
catch (Exception ex)
{
ErrMsg = ex.Message;
}
return ErrMsg
}
Method two:
public void test(ref string ErrMsg )
{
ErrMsg = string.Empty;
try
{
int num = int.Parse("gagw");
}
catch (Exception ex)
{
ErrMsg = ex.Message;
}
}
Use str_replace function of PHP.
Something like:
$str = str_replace(' ', '_', $str);
If you're interested in generalizing to different architectures, you could also run the command above and substitute uname -m
in with backticks like so:
wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-`uname -m`.sh
As reported by Tim Anderson
Cross-platform development is a big deal, and will continue to be so until a day comes when everyone uses the same platform. Android? HTML? WebKit? iOS? Windows? Xamarin? Titanum? PhoneGap? Corona? ecc.
Sometimes I hear it said that there are essentially two approaches to cross-platform mobile apps. You can either use an embedded browser control and write a web app wrapped as a native app, as in Adobe PhoneGap/Cordova or the similar approach taken by Sencha, or you can use a cross-platform tool that creates native apps, such as Xamarin Studio, Appcelerator Titanium, or Embarcardero FireMonkey.
Within the second category though, there is diversity. In particular, they vary concerning the extent to which they abstract the user interface.
Here is the trade-off. If you design your cross-platform framework you can have your application work almost the same way on every platform. If you are sharing the UI design across all platforms, it is hard to make your design feel equally right in all cases. It might be better to take the approach adopted by most games, using a design that is distinctive to your app and make a virtue of its consistency across platforms, even though it does not have the native look and feel on any platform.
edit Xamarin v3 in 2014 started offering choice of Xamarin.Forms as well as pure native that still follows the philosophy mentioned here (took liberty of inline edit because such a great answer)
Xamarin Studio on the other hand makes no attempt to provide a shared GUI framework:
We don’t try to provide a user interface abstraction layer that works across all the platforms. We think that’s a bad approach that leads to lowest common denominator user interfaces. (Nat Friedman to Tim Anderson)
This is right; but the downside is the effort involved in maintaining two or more user interface designs for your app.
Comparison about PhoneGap and Titanium it's well reported in Kevin Whinnery blog.
The purpose of PhoneGap is to allow HTML-based web applications to be deployed and installed as native applications. PhoneGap web applications are wrapped in a native application shell, and can be installed via the native app stores for multiple platforms. Additionally, PhoneGap strives to provide a common native API set which is typically unavailable to web applications, such as basic camera access, device contacts, and sensors not already exposed in the browser.
To develop PhoneGap applications, developers will create HTML, CSS, and JavaScript files in a local directory, much like developing a static website. Approaching native-quality UI performance in the browser is a non-trivial task - Sencha employs a large team of web programming experts dedicated full-time to solving this problem. Even so, on most platforms, in most browsers today, reaching native-quality UI performance and responsiveness is simply not possible, even with a framework as advanced as Sencha Touch. Is the browser already “good enough” though? It depends on your requirements and sensibilities, but it is unquestionably less good than native UI. Sometimes much worse, depending on the browser.
PhoneGap is not as truly cross-platform as one might believe, not all features are equally supported on all platforms.
Javascript is not an application scale programming language, too many global scope interactions, different libraries don't often co-exist nicely. We spent many hours trying to get knockout.js and jQuery.mobile play well together, and we still have problems.
Fragmented landscape for frameworks and libraries. Too many choices, and too many are not mature enough.
Strangely enough, for the needs of our app, decent performance could be achieved (not with jQuery.Mobile, though). We tried jqMobi (not very mature, but fast).
Very limited capability for interaction with other apps or cdevice capabilities, and this would not be cross-platform anyway, as there aren't any standards in HTML5 except for a few, like geolocation, camera and local databases.
The goal of Titanium Mobile is to provide a high level, cross-platform JavaScript runtime and API for mobile development (today we support iOS, Android and Windows Phone. Titanium actually has more in common with MacRuby/Hot Cocoa, PHP, or node.js than it does with PhoneGap, Adobe AIR, Corona, or Rhomobile. Titanium is built on two assertions about mobile development: - There is a core of mobile development APIs which can be normalized across platforms. These areas should be targeted for code reuse. - There are platform-specific APIs, UI conventions, and features which developers should incorporate when developing for that platform. Platform-specific code should exist for these use cases to provide the best possible experience.
So for those reasons, Titanium is not an attempt at “write once, run everywhere”. Same as Xamarin.
Titanium are going to do a further step in the direction similar to that of Xamarin. In practice, they will do two layers of different depths: the layer Titanium (in JS), which gives you a bee JS-of-Titanium. If you want to go more low-level, have created an additional layer (called Hyperloop), where (always with JS) to call you back directly to native APIs of SO
Xamarin (originally a division of Novell) in the last 18 months has brought to market its own IDE and snap-in for Visual Studio. The underlining premise of Mono is to create disparate mobile applications using C# while maintaining native UI development strategies.
In addition to creating a visual design platform to develop native applications, they have integrated testing suites, incorporated native library support and a Nuget style component store. Recently they provided iOS visual design through their IDE freeing the developer from opening XCode. In Visual Studio all three platforms are now supported and a cloud testing suite is on the horizon.
From the get go, Xamarin has provided a rich Android visual design experience. I have yet to download or open Eclipse or any other IDE besides Xamarin. What is truly amazing is that I am able to use LINQ to work with collections as well as create custom delegates and events that free me from objective-C and Java limitations. Many of the libraries I have been spoiled with, like Newtonsoft JSON.Net, work perfectly in all three environments.
In my opinion there are several HUGE advantages including
Upgrade for me is use Xamarin and MVVMCross combined. It's still quite a new framework, but it's born from experience of several other frameworks (such as MvvmLight and monocross) and it's now been used in at several released cross platform projects.
My choice after knowing all these framwework, was to select development tool based on product needs. In general, however if you start to use a tool with which you feel comfortable (even if it requires a higher initial overhead) after you'll use it forever.
I chose Xamarin + MVVMCross and I must say to be happy with this choice. I'm not afraid of approach Native SDK for software updates or seeing limited functionality of a system or the most trivial thing a feature graphics. Write code fairly structured (DDD + SOA) is very useful to have a core project shared with native C# views implementation.
you are calling a script file not a command so you have to use -file eg :
powershell -executionPolicy bypass -noexit -file "c:\temp\test.ps1" "c:\test with space"
for PS V2
powershell.exe -noexit &'c:\my scripts\test.ps1'
(check bottom of this technet page http://technet.microsoft.com/en-us/library/ee176949.aspx )
If I've understood your question correctly, then you are looking for the mouseup
event, rather than the click
event:
$("#message_link").mouseup(function() {
//Do stuff here
});
The mouseup
event fires when the mouse button is released, and does not take into account whether the mouse button was pressed on that element, whereas click
takes into account both mousedown
and mouseup
.
However, click
should work fine, because it won't actually fire until the mouse button is released.
I used this, and it worked perfectly.
error: function(xhr, status, error){
alertify.error(JSON.parse(xhr.responseText).error);
}
You have an extra closing }
in your function.
var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
nav[i].addEventListener('click',function(){
console.log('haha');
} // <== remove this brace
}, false);
};
You really should be using something like JSHint or JSLint to help find these things. These tools integrate with many editors and IDEs, or you can just paste a code fragment into the above web sites and ask for an analysis.
Just to add another flavor from the Reuben response, I use it like this to add or remove this rule according to a condition:
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams) holder.txtGuestName.getLayoutParams();
if (SOMETHING_THAT_WOULD_LIKE_YOU_TO_CHECK) {
// if true center text:
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
holder.txtGuestName.setLayoutParams(layoutParams);
} else {
// if false remove center:
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 0);
holder.txtGuestName.setLayoutParams(layoutParams);
}
There's no need for Prototype here: JavaScript has for..in
loops. If you're not sure that no one messed with Object.prototype
, check hasOwnProperty()
as well, ie
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
doSomethingWith(obj[prop]);
}
use ng-pattern, so that ng-valid and ng-dirty can act correctly
Email:<input type="email" name="email1" ng-model="emailReg">
Repeat Email:<input type="email" name="email2" ng-model="emailReg2" ng-pattern="emailReg">
<span ng-show="registerForm.email2.$error.pattern">Emails have to match!</span>
For SpringFramework Tests, I would recommend to add the below as well
org.springframework.test.web.servlet.request.MockMvcRequestBuilders
org.springframework.test.web.servlet.request.MockMvcResponseBuilders
org.springframework.test.web.servlet.result.MockMvcResultHandlers
org.springframework.test.web.servlet.result.MockMvcResultMatchers
org.springframework.test.web.servlet.setup.MockMvcBuilders
org.mockito.Mockito
When you add above as new Type it automatically add .* to the package.
You have to use the component's State to update component parameters such as Class Name if you want React to render your DOM correctly and efficiently.
UPDATE: I updated the example to toggle the Sidemenu on a button click. This is not necessary, but you can see how it would work. You might need to use "this.state" vs. "this.props" as I have shown. I'm used to working with Redux components.
constructor(props){
super(props);
}
getInitialState(){
return {"showHideSidenav":"hidden"};
}
render() {
return (
<div className="header">
<i className="border hide-on-small-and-down"></i>
<div className="container">
<a ref="btn" onClick={this.toggleSidenav.bind(this)} href="#" className="btn-menu show-on-small"><i></i></a>
<Menu className="menu hide-on-small-and-down"/>
<Sidenav className={this.props.showHideSidenav}/>
</div>
</div>
)
}
toggleSidenav() {
var css = (this.props.showHideSidenav === "hidden") ? "show" : "hidden";
this.setState({"showHideSidenav":css});
}
Now, when you toggle the state, the component will update and change the class name of the sidenav component. You can use CSS to show/hide the sidenav using the class names.
.hidden {
display:none;
}
.show{
display:block;
}
to use parameters in aliases, i use this method:
alias myalias='function __myalias() { echo "Hello $*"; unset -f __myalias; }; __myalias'
its a self-destructive function wrapped in an alias, so it pretty much is the best of both worlds, and doesnt take up an extra line(s) in your definitions... which i hate, oh yeah and if you need that return value, you'll have to store it before calling unset, and then return the value using the "return" keyword in that self destructive function there:
alias myalias='function __myalias() { echo "Hello $*"; myresult=$?; unset -f __myalias; return $myresult; }; __myalias'
so..
you could, if you need to have that variable in there
alias mongodb='function __mongodb() { ./path/to/mongodb/$1; unset -f __mongodb; }; __mongodb'
of course...
alias mongodb='./path/to/mongodb/'
would actually do the same thing without the need for parameters, but like i said, if you wanted or needed them for some reason (for example, you needed $2 instead of $1), you would need to use a wrapper like that. If it is bigger than one line you might consider just writing a function outright since it would become more of an eyesore as it grew larger. Functions are great since you get all the perks that functions give (see completion, traps, bind, etc for the goodies that functions can provide, in the bash manpage).
I hope that helps you out :)
try this it is worked for me.
$time="10:09";
$time = date('H:i', strtotime($time.'+1 hour'));
echo $time;
This usually has to do with a selector not being used properly. Check and make sure that you are using the jQuery selectors like intended. For example I had this problem when creating a click method:
$("[editButton]").click(function () {
this.css("color", "red");
});
Because I was not using the correct selector method $(this) for jQuery it gave me the same error.
So simply enough, check your selectors!
It's fairly easy using the New-SelfSignedCertificate command in Powershell. Open powershell and run these 3 commands.
1) Create certificate:
$cert = New-SelfSignedCertificate -DnsName www.yourwebsite.com -Type CodeSigning -CertStoreLocation Cert:\CurrentUser\My2) set the password for it:
$CertPassword = ConvertTo-SecureString -String "my_passowrd" -Force –AsPlainText3) Export it:
Export-PfxCertificate -Cert "cert:\CurrentUser\My\$($cert.Thumbprint)" -FilePath "d:\selfsigncert.pfx" -Password $CertPassword
Your certificate selfsigncert.pfx will be located @ D:/
Optional step: You would also require to add certificate password to system environment variables. do so by entering below in cmd: setx CSC_KEY_PASSWORD "my_password"
Thread.State enum class and the new getState() API are provided for querying the execution state of a thread.
A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states [NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED
].
enum Thread.State extends Enum implements Serializable, Comparable
getState()jdk5
- public State getState() {...}
« Returns the state of this
thread. This method is designed for use in monitoring of the system state, not for synchronization control.
isAlive() - public final native boolean isAlive();
« Returns true if the thread upon which it is called is still alive, otherwise it returns false. A thread is alive if it has been started and has not yet died.
Sample Source Code's of classes java.lang.Thread
and sun.misc.VM
.
package java.lang;
public class Thread implements Runnable {
public final native boolean isAlive();
// Java thread status value zero corresponds to state "NEW" - 'not yet started'.
private volatile int threadStatus = 0;
public enum State {
NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED;
}
public State getState() {
return sun.misc.VM.toThreadState(threadStatus);
}
}
package sun.misc;
public class VM {
// ...
public static Thread.State toThreadState(int threadStatus) {
if ((threadStatus & JVMTI_THREAD_STATE_RUNNABLE) != 0) {
return Thread.State.RUNNABLE;
} else if ((threadStatus & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER) != 0) {
return Thread.State.BLOCKED;
} else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_INDEFINITELY) != 0) {
return Thread.State.WAITING;
} else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT) != 0) {
return Thread.State.TIMED_WAITING;
} else if ((threadStatus & JVMTI_THREAD_STATE_TERMINATED) != 0) {
return Thread.State.TERMINATED;
} else if ((threadStatus & JVMTI_THREAD_STATE_ALIVE) == 0) {
return Thread.State.NEW;
} else {
return Thread.State.RUNNABLE;
}
}
}
Example with java.util.concurrent.CountDownLatch
to execute multiple threads parallel, After completing all threads main thread execute. (until parallel threads complete their task main thread will be blocked.)
public class MainThread_Wait_TillWorkerThreadsComplete {
public static void main(String[] args) throws InterruptedException {
System.out.println("Main Thread Started...");
// countDown() should be called 4 time to make count 0. So, that await() will release the blocking threads.
int latchGroupCount = 4;
CountDownLatch latch = new CountDownLatch(latchGroupCount);
new Thread(new Task(2, latch), "T1").start();
new Thread(new Task(7, latch), "T2").start();
new Thread(new Task(5, latch), "T3").start();
new Thread(new Task(4, latch), "T4").start();
//latch.countDown(); // Decrements the count of the latch group.
// await() method block until the current count reaches to zero
latch.await(); // block until latchGroupCount is 0
System.out.println("Main Thread completed.");
}
}
class Task extends Thread {
CountDownLatch latch;
int iterations = 10;
public Task(int iterations, CountDownLatch latch) {
this.iterations = iterations;
this.latch = latch;
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " : Started Task...");
for (int i = 0; i < iterations; i++) {
System.out.println(threadName + " : "+ i);
sleep(1);
}
System.out.println(threadName + " : Completed Task");
latch.countDown(); // Decrements the count of the latch,
}
public void sleep(int sec) {
try {
Thread.sleep(1000 * sec);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@See also
Use this code for API 21 or above. This works and gives better result compared to the other answers, it detects perfectly the foreground process.
if (Build.VERSION.SDK_INT >= 21) {
String currentApp = null;
UsageStatsManager usm = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> applist = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
if (applist != null && applist.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : applist) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
Try this
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
{ echo $password; echo $password; } | passwd $username
Copy-pasted from a recipe written by "Adrián Santalla" on androidcookbook.com: https://www.androidcookbook.com/Recipe.seam?recipeId=3307
1. Create an XML file that represents the button states
Create an xml into drawable called 'button.xml' to name the button states:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_enabled="false"
android:drawable="@drawable/button_disabled" />
<item
android:state_pressed="true"
android:state_enabled="true"
android:drawable="@drawable/button_pressed" />
<item
android:state_focused="true"
android:state_enabled="true"
android:drawable="@drawable/button_focused" />
<item
android:state_enabled="true"
android:drawable="@drawable/button_enabled" />
</selector>
2. Create an XML file that represents each button state
Create one xml file for each of the four button states. All of them should be under drawables folder. Let's follow the names set in the button.xml file.
button_enabled.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
android:startColor="#00CCFF"
android:centerColor="#0000CC"
android:endColor="#00CCFF"
android:angle="90"/>
<padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
<stroke
android:width="2dip"
android:color="#FFFFFF" />
<corners android:radius= "8dp" />
</shape>
button_focused.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
android:startColor="#F7D358"
android:centerColor="#DF7401"
android:endColor="#F7D358"
android:angle="90"/>
<padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
<stroke
android:width="2dip"
android:color="#FFFFFF" />
<corners android:radius= "8dp" />
</shape>
button_pressed.xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
android:startColor="#0000CC"
android:centerColor="#00CCFF"
android:endColor="#0000CC"
android:angle="90"/>
<padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
<stroke
android:width="2dip"
android:color="#FFFFFF" />
<corners android:radius= "8dp" />
</shape>
button_disabled.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
android:startColor="#F2F2F2"
android:centerColor="#A4A4A4"
android:endColor="#F2F2F2"
android:angle="90"/>
<padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
<stroke
android:width="2dip"
android:color="#FFFFFF" />
<corners android:radius= "8dp" />
</shape>
3. Create an XML file that represents the button style
Once you have created the files mentioned above, it's time to create your application button style. Now, you need to create a new XML file, called styles.xml (if you don't have it yet) where you can include more custom styles, into de values directory.
This file will contain the new button style of your application. You need to set your new button style features in it. Note that one of those features, the background of your new style, should be set with a reference to the button (button.xml) drawable that was created in the first step. To refer to the new button style we use the name attribute.
The example below show the content of the styles.xml file:
<resources>
<style name="button" parent="@android:style/Widget.Button">
<item name="android:gravity">center_vertical|center_horizontal</item>
<item name="android:textColor">#FFFFFFFF</item>
<item name="android:shadowColor">#FF000000</item>
<item name="android:shadowDx">0</item>
<item name="android:shadowDy">-1</item>
<item name="android:shadowRadius">0.2</item>
<item name="android:textSize">16dip</item>
<item name="android:textStyle">bold</item>
<item name="android:background">@drawable/button</item>
<item name="android:focusable">true</item>
<item name="android:clickable">true</item>
</style>
</resources>
4. Create an XML with your own custom application theme
Finally, you need to override the default Android button style. For that, you need to create a new XML file, called themes.xml (if you don't have it yet), into the values directory and override the default Android button style.
The example below show the content of the themes.xml:
<resources>
<style name="YourApplicationTheme" parent="android:style/Theme.NoTitleBar">
<item name="android:buttonStyle">@style/button</item>
</style>
</resources>
Hope you guys can have the same luck as I had with this, when I was looking for custom buttons. Enjoy.
There is no updated
dynamic table. There is just inserted
and deleted
. On an UPDATE
command, the old data is stored in the deleted
dynamic table, and the new values are stored in the inserted
dynamic table.
Think of an UPDATE
as a DELETE/INSERT
combination.
For a single boxplot:
import seaborn as sb
sb.boxplot(data=Array).set_title('Title')
For more boxplot in the same plot:
import seaborn as sb
sb.boxplot(data=ArrayofArray).set_title('Title')
e.g.
import seaborn as sb
myarray=[78.195229, 59.104538, 19.884109, 25.941648, 72.234825, 82.313911]
sb.boxplot(data=myarray).set_title('myTitle')
Might be overkill in this particular case but another option involves using StringIO
to create a file-like object
for line in StringIO.StringIO(inputString):
doStuff()
Yes it is possible to continue and to exit of a forEach loop.
To continue, you can use return, the loop will continue but the current function will end.
To exit of the loop, you can set the third parameter to 0 length, set to empty array. The loop will not continue, the current function do, so you can use "return" to finish, like exit in a normal for loop...
This:
[1,2,3,4,5,6,7,8,9,10].forEach((a,b,c) => {
console.log(a);
if(b == 2){return;}
if(b == 4){c.length = 0;return;}
console.log("next...",b);
});
will print this:
1
next... 0
2
next... 1
3
4
next... 3
5
Here's a collection of scripts: http://webtecker.com/2008/03/26/collection-of-password-strength-scripts/
I think both of them rate the password and don't use jQuery... but I don't know if they have native support for disabling the form?
Technically, you will be sending these headers through the connect function before the protocol upgrade phase. This worked for me in a nodejs
project:
var WebSocketClient = require('websocket').client;
var ws = new WebSocketClient();
ws.connect(url, '', headers);
if you want it without try and except then there is the solution
what you are trying to do is print 'hello' if 'harry' in a list then the solution is
'hello' if 'harry' in sam else ''
Before any transaction with git that your machine does git checks for your authentication which can be done using
In simple words, this happened because the credentials stored in your machine are not authentic i.e.there are chances that your password stored in the machine has changed from whats there in git therefore
Head towards, control panel and search for Credential Manager look for your use git url and change the creds.
There you go this works with mostly every that windows keep track off
This is an ES6 version
let date = new Date()
let newDate = new Date(date.setDate(date.getDate()-30))
console.log(newDate.getMonth()+1 + '/' + newDate.getDate() + '/' + newDate.getFullYear() )
Actually I think OZ_ may be somewhat correct.
If you have the route '/users/:userId'
and navigate to '/users/'
(note the trailing /), $routeParams
in your controller should be an object containing userId: ""
in 1.1.5. So no the paramater userId
isn't completely ignored, but I think it's the best you're going to get.
I have used the following steps to resolve this problem
Just throw everything you read into a MemoryStream
and get the byte array in the end. As noted, you should be reading from the underlying stream to get the raw bytes.
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
var buffer = new byte[512];
var bytesRead = default(int);
while ((bytesRead = reader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
memstream.Write(buffer, 0, bytesRead);
bytes = memstream.ToArray();
}
Or if you don't want to manage the buffers:
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
reader.BaseStream.CopyTo(memstream);
bytes = memstream.ToArray();
}
Here is where I found it on a Windows 2008R2 server. Elevated Task Scheduler Click on "Task Scheduler Library" It appears as an option on the right hand "Actions" panel.
a = 2
x = 0
Do Until Cells(a, 1).Value = ""
If Rows(a).Hidden = False Then
x = Cells(a, 1).Value + x
End If
a = a + 1
Loop
End Sub
Just increasing max_connections
is bad idea. You need to increase shared_buffers
and kernel.shmmax
as well.
Considerations
max_connections
determines the maximum number of concurrent connections to the database server. The default is typically 100 connections.
Before increasing your connection count you might need to scale up your deployment. But before that, you should consider whether you really need an increased connection limit.
Each PostgreSQL connection consumes RAM for managing the connection or the client using it. The more connections you have, the more RAM you will be using that could instead be used to run the database.
A well-written app typically doesn't need a large number of connections. If you have an app that does need a large number of connections then consider using a tool such as pg_bouncer which can pool connections for you. As each connection consumes RAM, you should be looking to minimize their use.
How to increase max connections
1. Increase max_connection
and shared_buffers
in /var/lib/pgsql/{version_number}/data/postgresql.conf
change
max_connections = 100
shared_buffers = 24MB
to
max_connections = 300
shared_buffers = 80MB
The shared_buffers
configuration parameter determines how much memory is dedicated to PostgreSQL to use for caching data.
2. Change kernel.shmmax
You would need to increase kernel max segment size to be slightly larger
than the shared_buffers
.
In file /etc/sysctl.conf
set the parameter as shown below. It will take effect when postgresql
reboots (The following line makes the kernel max to 96Mb
)
kernel.shmmax=100663296
References
Disabling 'Show Logical Structure' button/icon of the upper right corner of the variables window in the eclipse debugger resolved it, in my case.
If you are using Express
, the cleanest complete answer is this
const express = require('express')
const app = express()
app.get('*', (req, res) => {
// REDIRECT goes here
res.redirect('https://www.YOUR_URL.com/')
})
app.set('port', (process.env.PORT || 3000))
const server = app.listen(app.get('port'), () => {})
Quite often the issue is a non-breaking space - CHAR(160)
- especially from Web text sources -that CLEAN
can't remove, so I would go a step further than this and try a formula like this which replaces any non-breaking spaces with a standard one
=TRIM(CLEAN(SUBSTITUTE(A1,CHAR(160)," ")))
Ron de Bruin has an excellent post on tips for cleaning data here
You can also remove the CHAR(160)
directly without a workaround formula by
ALT
and type 0160
using the numeric keypadMay I suggest the concept of Duck-typing?
Most likely you would tend to make the Pegasus extend a Bird and a Horse interface but duck typing actually suggests that you should rather inherit behaviour. As already stated in the comments, a pegasus is not a bird but it can fly. So your Pegasus should rather inherit a Flyable
-interface and lets say a Gallopable
-interface.
This kind of concept is utilized in the Strategy Pattern. The given example actually shows you how a duck inherits the FlyBehaviour
and QuackBehaviour
and still there can be ducks, e.g. the RubberDuck
, which can't fly. They could have also made the Duck
extend a Bird
-class but then they would have given up some flexibility, because every Duck
would be able to fly, even the poor RubberDuck
.
In my case this error was specific to the hello-world
docker image. I used the nginx
image instead of the hello-world
image and the error was resolved.
You will need to add a "kernel" for it. Run your enviroment:
>activate tensorflow
Then add a kernel by command (after --name should follow your env. with tensorflow):
>python -m ipykernel install --user --name tensorflow --display-name "TensorFlow-GPU"
After that run jupyter notebook from your tensorflow env.
>jupyter notebook
And then you will see the following enter image description here
Click on it and then in the notebook import packages. It will work out for sure.
genrsa
has been replaced by genpkey
& when run manually in a terminal it will prompt for a password:
openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096
However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell
script:
get_passwd() {
local passwd=
echo -ne "Enter passwd for private key: ? "; read -s passwd
openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}
do this in global.asax.cs:
protected void Application_Start()
{
//string ServerSoftware = Context.Request.ServerVariables["SERVER_SOFTWARE"];
string server = Context.Request.ServerVariables["SERVER_NAME"];
string port = Context.Request.ServerVariables["SERVER_PORT"];
HttpRuntime.Cache.Insert("basePath", "http://" + server + ":" + port + "/");
// ...
}
works like a charm. this.Context.Request is there...
this.Request throws exception intentionally based on a flag
'test' task does not work for Android plugin, for Android plugin use the following:
// Test Logging
tasks.withType(Test) {
testLogging {
events "started", "passed", "skipped", "failed"
}
}
See the following: https://stackoverflow.com/a/31665341/3521637
You may want to look into os dependent line separators, e.g.:
import os
with open('./output.txt', 'a') as f1:
f1.write(content + os.linesep)
Though both the sorts are O(N^2).The hidden constants are much smaller in Insertion sort.Hidden constants refer to the actual number of primitive operations carried out.
When insertion sort has better running time?
Notice that insertion sort is not always better than bubble sort.To get the best of both worlds, you can use insertion sort if array is of small size, and probably merge sort(or quicksort) for larger arrays.
Date
is Comparable
& Equatable
(as of Swift 3)This answer complements @Ankit Thakur's answer.
Since Swift 3 the Date
struct (based on the underlying NSDate
class) adopts the Comparable
and Equatable
protocols.
Comparable
requires that Date
implement the operators: <
, <=
, >
, >=
.Equatable
requires that Date
implement the ==
operator.Equatable
allows Date
to use the default implementation of the !=
operator (which is the inverse of the Equatable
==
operator implementation).The following sample code exercises these comparison operators and confirms which comparisons are true with print
statements.
import Foundation
func describeComparison(date1: Date, date2: Date) -> String {
var descriptionArray: [String] = []
if date1 < date2 {
descriptionArray.append("date1 < date2")
}
if date1 <= date2 {
descriptionArray.append("date1 <= date2")
}
if date1 > date2 {
descriptionArray.append("date1 > date2")
}
if date1 >= date2 {
descriptionArray.append("date1 >= date2")
}
if date1 == date2 {
descriptionArray.append("date1 == date2")
}
if date1 != date2 {
descriptionArray.append("date1 != date2")
}
return descriptionArray.joined(separator: ", ")
}
let now = Date()
describeComparison(date1: now, date2: now.addingTimeInterval(1))
// date1 < date2, date1 <= date2, date1 != date2
describeComparison(date1: now, date2: now.addingTimeInterval(-1))
// date1 > date2, date1 >= date2, date1 != date2
describeComparison(date1: now, date2: now)
// date1 <= date2, date1 >= date2, date1 == date2
I've been looking around for this, but then I realize, damn my website uses php!!! Why not use the trim function on the text input and play with the max length....
Here is a possible solution too for those using php: http://ideone.com/PsTaI
<?php
$s = "In the beginning there was a tree.";
$max_length = 10;
if (strlen($s) > $max_length)
{
$offset = ($max_length - 3) - strlen($s);
$s = substr($s, 0, strrpos($s, ' ', $offset)) . '...';
}
echo $s;
?>
Doesn't that really depends on the complexity of the system, and the in-house conventions?
At the moment I am working on a neural network simulator that is incredibly complex, and the accepted style that I am expected to use is:
Class definitions in classname.h
Class code in classnameCode.h
executable code in classname.cpp
This splits up the user-built simulations from the developer-built base classes, and works best in the situation.
However, I'd be surprised to see people do this in, say, a graphics application, or any other application that's purpose is not to provide users with a code base.
You can create an iterator in Python 3.x or a list in Python 2.x by using:
filter(r.match, list)
To convert the Python 3.x iterator to a list, simply cast it; list(filter(..))
.
the solution: for type entity use option "data" but value is a object. ie:
$em = $this->getDoctrine()->getEntityManager();
->add('sucursal', 'entity', array
(
'class' => 'TestGeneralBundle:Sucursal',
'property'=>'descripcion',
'label' => 'Sucursal',
'required' => false,
'data'=>$em->getReference("TestGeneralBundle:Sucursal",3)
))
while not condition1 or not condition2 or val == -1:
But there was nothing wrong with your original of using an if inside of a while True.
This might be helpful
NSString *sampleUrl = @"http://www.google.com/search.jsp?params=Java Developer";
NSString* encodedUrl = [sampleUrl stringByAddingPercentEscapesUsingEncoding:
NSUTF8StringEncoding];
For iOS 7+, the recommended way is:
NSString* encodedUrl = [sampleUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
You can choose the allowed character set as per the requirement of the URL component.
If you are presenting a ViewController modally, and want to go back to the root ViewController, take care to dismiss this modally presented ViewController before you go back to the root ViewController otherwise this ViewController will not be removed from Memory and cause Memory leaks.
Use readline.get_current_history_length()
to get the length, and readline.get_history_item()
to view each.
Let me share my experience for this issue fix.
Open target -> Build phases -> Copy Bundle Resources and remove info.plist.
Note: If you're using any extensions, remove the info.plist of that extension from the Targets.
Hope it helps.
No need for jQuery unless you target old browsers and don't want to use shims.
var yahooOnly = JSON.parse(jsondata).filter(function (entry) {
return entry.website === 'yahoo';
});
In ES2015:
const yahooOnly = JSON.parse(jsondata).filter(({website}) => website === 'yahoo');
range(x)
returns a list of numbers from 0 to x - 1.
>>> range(1)
[0]
>>> range(2)
[0, 1]
>>> range(3)
[0, 1, 2]
>>> range(4)
[0, 1, 2, 3]
for i in range(x):
executes the body (which is print i
in your first example) once for each element in the list returned by range()
.
i
is used inside the body to refer to the “current” item of the list.
In that case, i
refers to an integer, but it could be of any type, depending on the objet on which you loop.
Working with atom (1.21.1 ia32)... i got the same error, even though i added a reference to my pipe in the app.module.ts and in the declarations within app.module.ts
solution was to restart my node instance... stopping the website and then doing ng serve again... going to localhost:4200 worked like a charm after this restart
You can use StringVar or IntVar, etc, your constant is const_val
val = 'Stackoverflow'
const_val = StringVar(val)
const.trace('w', reverse)
def reverse(*args):
const_val.set(val)
Test castEnum = static_cast<Test>(a-1);
will cast a
to A
. If you don't want to substruct 1, you can redefine the enum
:
enum Test
{
A:1, B
};
In this case Test castEnum = static_cast<Test>(a);
could be used to cast a
to A
.
Just call the action no need for redirect to action
or the new
keyword for model.
[HttpPost]
public ActionResult FillStudent(Student student1)
{
return GetStudent(student1); //this will also work
}
public ActionResult GetStudent(Student student)
{
return View(student);
}
I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, "body goes here" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result=curl_exec ($ch);
Further refinig Sglasses method, the above lines force the use of SQLCMD mode, and either treminates the scirpt if not using SQLCMD mode or uses :on error exit
to exit on any error
CONTEXT_INFO is used to keep track of the state.
SET CONTEXT_INFO 0x1 --Just to make sure everything's ok
GO
--treminate the script on any error. (Requires SQLCMD mode)
:on error exit
--If not in SQLCMD mode the above line will generate an error, so the next line won't hit
SET CONTEXT_INFO 0x2
GO
--make sure to use SQLCMD mode ( :on error needs that)
IF CONTEXT_INFO()<>0x2
BEGIN
SELECT CONTEXT_INFO()
SELECT 'This script must be run in SQLCMD mode! (To enable it go to (Management Studio) Query->SQLCMD mode)\nPlease abort the script!'
RAISERROR('This script must be run in SQLCMD mode! (To enable it go to (Management Studio) Query->SQLCMD mode)\nPlease abort the script!',16,1) WITH NOWAIT
WAITFOR DELAY '02:00'; --wait for the user to read the message, and terminate the script manually
END
GO
----------------------------------------------------------------------------------
----THE ACTUAL SCRIPT BEGINS HERE-------------
Add a border
to the regular item, the same color
as the background
, so that it cannot be seen. That way the item has a border: 1px
whether it is being hovered or not.
is an inline element ..but in css you can change it simply by:- img{display:inline-block;} or img{display:inline-block;} or img{display:inliblock;}
To be entirely sure that it takes effect immediately after the repository is initialized, but before the remote history is fetched or any files checked out, it is safer to use it this way:
git clone -c core.longpaths=true <repo-url>
-c key=value
Set a configuration variable in the newly-created repository; this takes effect immediately after the repository is initialized, but before the remote history is fetched or any files checked out. The key is in the same format as expected by git-config1 (e.g., core.eol=true). If multiple values are given for the same key, each value will be written to the config file. This makes it safe, for example, to add additional fetch refspecs to the origin remote.
If you use dplyr
package you can do:
library(dplyr)
filter(df, aged <= laclen)
Ctrl + A and then Ctrl+D. Doing this will detach you from the screen
session which you can later resume by doing screen -r
.
You can also do: Ctrl+A then type :. This will put you in screen command mode. Type the command detach
to be detached from the running screen session.
Include servlet-api.jar from your server lib folder.
Do this step
30 minutes is 30 * 60 * 1000
miliseconds. Add that to the current date to specify an expiration date 30 minutes in the future.
var date = new Date();
var minutes = 30;
date.setTime(date.getTime() + (minutes * 60 * 1000));
$.cookie("example", "foo", { expires: date });
The AS
keyword is to give an ALIAS name to your database table or to table column. In your example, both statement are correct but there are circumstance where AS clause is needed (though the AS
operator itself is optional), e.g.
SELECT salary * 2 AS "Double salary" FROM employee;
In this case, the Employee
table has a salary
column and we just want the double of the salary with a new name Double Salary
.
Sorry if my explanation is not effective.
Update based on your comment, you're right, my previous statement was invalid. The only reason I can think of is that the AS
clause has been in existence for long in the SQL world that it's been incorporated in nowadays RDMS for backward compatibility..
The issue is most likely you will need to use an auto loader that will take the name of the class (break by '\' in this case) and map it to a directory structure.
You can check out this article on the autoloading functionality of PHP. There are many implementations of this type of functionality in frameworks already.
I've actually implemented one before. Here's a link.
The following code will show the current commit
git show HEAD
An easy way to upgrade all Perl packages (CPAN modules) is the following way:
cpan upgrade /(.*)/
cpan will recognize the regular expression like this and will update/upgrade all packages installed.
Tries with following it will definitely work:_x000D_
_x000D_
@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", Value= "3" })_x000D_
_x000D_
@Html.TextBoxFor(model => model.Destination, new { id = "txtPlace", @Value= "3" })_x000D_
_x000D_
<input id="txtPlace" name="Destination" type="text" value="3" class="ui-input-text ui-body-c ui-corner-all ui-shadow-inset ui-mini" >
_x000D_
https://jsfiddle.net/0vgchj9n/1/
To make sure the event always only fires once, you can use Jquery .one() . JQuery one ensures that your event handler only called once. Additionally, you can subscribe your event handler with one to allow further clicks when you have finished the processing of the current click operation.
<div id="testDiv">
<button class="testClass">Test Button</button>
</div>
…
var subscribeClickEvent = function() {$("#testDiv").one("click", ".testClass", clickHandler);};
function clickHandler() {
//... perform the tasks
alert("you clicked the button");
//... subscribe the click handler again when the processing of current click operation is complete
subscribeClickEvent();
}
subscribeClickEvent();
Another approach to solving this securely is to use the following module.
node_extra_ca_certs_mozilla_bundle
This module can work without any code modification by generating a PEM file that includes all root and intermediate certificates trusted by Mozilla. You can use the following environment variable (Works with Nodejs v7.3+),
To generate the PEM file to use with the above environment variable. You can install the module using:
npm install --save node_extra_ca_certs_mozilla_bundle
and then launch your node script with an environment variable.
NODE_EXTRA_CA_CERTS=node_modules/node_extra_ca_certs_mozilla_bundle/ca_bundle/ca_intermediate_root_bundle.pem node your_script.js
Other ways to use the generated PEM file are available at:
https://github.com/arvind-agarwal/node_extra_ca_certs_mozilla_bundle
NOTE: I am the author of the above module.
What is the young generation?
The Young Generation is where all new objects are allocated and aged. When the young generation fills up, this causes a minor garbage collection. A young generation full of dead objects is collected very quickly. Some survived objects are aged and eventually move to the old generation.
What is the old generation?
The Old Generation is used to store long surviving objects. Typically, a threshold is set for young generation object and when that age is met, the object gets moved to the old generation. Eventually the old generation needs to be collected. This event is called a major garbage collection
What is the permanent generation?
The Permanent generation contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application.
PermGen has been replaced with Metaspace since Java 8 release.
PermSize & MaxPermSize parameters will be ignored now
How does the three generations interact/relate to each other?
Image source & oracle technetwork tutorial article: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html
"The General Garbage Collection Process" in above article explains the interactions between them with many diagrams.
Have a look at summary diagram:
This is what worked for me:
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File("client-p12-keystore.p12"));
try {
keyStore.load(instream, "password".toCharArray());
} finally {
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, "password".toCharArray())
//.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //TODO
CloseableHttpClient httpclient = HttpClients.custom()
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) //TODO
.setSSLSocketFactory(sslsf)
.build();
try {
HttpGet httpget = new HttpGet("https://localhost:8443/secure/index");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
This code is a modified version of http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java
An easy way of doing this:
SELECT ('[' || to_json('Some "text"'::TEXT) || ']')::json ->> 0;
Just convert the json string into a json list
I had this exact same problem which made loss hours so i'm inspired to share my findings and solutions that worked for me.
1. Use an excel file
This is the approach I adopted. Instead of using a csv file, I used an excel file (.xlsx) with content like below.
id username email token website
johndoe [email protected] divostar.com
bobstone [email protected] divosays.com
Notice that the id column has no value.
Next, connect to your DB using Microsoft SQL Server Management Studio and right click on your database and select import data (submenu under task). Select Microsoft Excel as source. When you arrive at the stage called "Select Source Tables and Views", click edit mappings. For id
column under destination, click on it and select ignore . Don't check Enable Identity insert
unless you want to mantain ids incases where you are importing data from another database and would like to maintain the auto increment id of the source db. Proceed to finish and that's it. Your data will be imported smoothly.
2. Using CSV file
In your csv file, make sure your data is like below.
id,username,email,token,website
,johndoe,[email protected],,divostar.com
,bobstone,[email protected],,divosays.com
Run the query below:
BULK INSERT Metrics FROM 'D:\Data Management\Data\CSV2\Production Data 2004 - 2016.csv '
WITH (FIRSTROW = 2, FIELDTERMINATOR = ',', ROWTERMINATOR = '\n');
The problem with this approach is that the CSV should be in the DB server or some shared folder that the DB can have access to otherwise you may get error like "Cannot opened file. The operating system returned error code 21 (The device is not ready)".
If you are connecting to a remote database, then you can upload your CSV to a directory on that server and reference the path in bulk insert.
3. Using CSV file and Microsoft SQL Server Management Studio import option
Launch your import data like in the first approach. For source, select Flat file Source and browse for your CSV file. Make sure the right menu (General, Columns, Advanced, Preview) are ok. Make sure to set the right delimiter under columns menu (Column delimiter). Just like in the excel approach above, click edit mappings. For id column under destination, click on it and select ignore .
Proceed to finish and that's it. Your data will be imported smoothly.
OK, there are lots of solutions here but non actually explain the root cause of the problem so here we go:
when you see an attribute like android:layout_width="match_parent"
the android
part is the prefix, the format for an attribute here is PREFIX:NAME="VALUE"
. in XML, namespaces and prefixes are ways to avoid naming conflicts for example we can have two distinct attributes with same name but different prefixes like: a:a="val"
and b:a="val"
.
to use prefixes like android
or app
or any other your should define a namespace using xmlns
attribute.
so if you have this issue just find prefixes that do not have a namespace defined, if you have tools:...
you should add tools namespace as some answeres suggested, if you have app:...
attribute you should add xmlns:app="http://schemas.android.com/apk/res-auto"
to the root element
Further reading:
There is some issue with some language display time ago for example in Arabic there 3 needed formats to display date. I use this functions in my projects hopefully they can help someone (any suggestion or improvement I'll be apperciate :) )
/**
*
* @param string $date1
* @param string $date2 the date that you want to compare with $date1
* @param int $level
* @param bool $absolute
*/
function app_date_diff( $date1, $date2, $level = 3, $absolute = false ) {
$date1 = date_create($date1);
$date2 = date_create($date2);
$diff = date_diff( $date1, $date2, $absolute );
$d = [
'invert' => $diff->invert
];
$diffs = [
'y' => $diff->y,
'm' => $diff->m,
'd' => $diff->d
];
$level_reached = 0;
foreach($diffs as $k=>$v) {
if($level_reached >= $level) {
break;
}
if($v > 0) {
$d[$k] = $v;
$level_reached++;
}
}
return $d;
}
/**
*
*/
function date_timestring( $periods, $format = 'latin', $separator = ',' ) {
$formats = [
'latin' => [
'y' => ['year','years'],
'm' => ['month','months'],
'd' => ['day','days']
],
'arabic' => [
'y' => ['???','?????','?????'],
'm' => ['???','?????','????'],
'd' => ['???','?????','????']
]
];
$formats = $formats[$format];
$string = [];
foreach($periods as $period=>$value) {
if(!isset($formats[$period])) {
continue;
}
$string[$period] = $value.' ';
if($format == 'arabic') {
if($value == 2) {
$string[$period] = $formats[$period][1];
}elseif($value > 2 && $value <= 10) {
$string[$period] .= $formats[$period][2];
}else{
$string[$period] .= $formats[$period][0];
}
}elseif($format == 'latin') {
$string[$period] .= ($value > 1) ? $formats[$period][1] : $formats[$period][0];
}
}
return implode($separator, $string);
}
function timeago( $date ) {
$today = date('Y-m-d h:i:s');
$diff = app_date_diff($date,$today,2);
if($diff['invert'] == 1) {
return '';
}
unset($diff[0]);
$date_timestring = date_timestring($diff,'latin');
return 'About '.$date_timestring;
}
$date1 = date('Y-m-d');
$date2 = '2018-05-14';
$diff = timeago($date2);
echo $diff;
Removing Python 3 was the worst thing I did since I recently moved to the world of Linux. It removed Firefox, my launcher and, as I read while trying to fix my problem, it may also remove your desktop and terminal! Finally fixed after a long daytime nightmare. Just don't remove Python 3. Keep it there!
If that happens to you, here is the fix:
here is my implementation
public static byte[] intToByteArray(int a) {
return BigInteger.valueOf(a).toByteArray();
}
public static int byteArrayToInt(byte[] b) {
return new BigInteger(b).intValue();
}
How about
session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()
edit: Without the ORM, it would be
session.execute(
select(
[MyUserTable.c.id, MyUserTable.c.name],
MyUserTable.c.id.in_((123, 456))
)
).fetchall()
select()
takes two parameters, the first one is a list of fields to retrieve, the second one is the where
condition. You can access all fields on a table object via the c
(or columns
) property.
import re
p = re.compile("[a-z]")
for m in p.finditer('a1b2c3d4'):
print(m.start(), m.group())
Yes, it prints GARBAGE unless you are lucky.
VERY IMPORTANT.
The type of the printf/sprintf/fprintf argument MUST match the associated format type char.
If the types don't match and it compiles, the results are very undefined.
Many newer compilers know about printf and issue warnings if the types do not match. If you get these warnings, FIX them.
If you want to convert types for arguments for variable functions, you must supply the cast (ie, explicit conversion) because the compiler can't figure out that a conversion needs to be performed (as it can with a function prototype with typed arguments).
printf("%d\n", (int) ch)
In this example, printf is being TOLD that there is an "int" on the stack. The cast makes sure that whatever thing sizeof returns (some sort of long integer, usually), printf will get an int.
printf("%d", (int) sizeof('\n'))
<script>
if($(window).width() >= 1200){
(function($) {
var element = $('.to_move_content'),
originalY = element.offset().top;
// Space between element and top of screen (when scrolling)
var topMargin = 10;
// Should probably be set in CSS; but here just for emphasis
element.css('position', 'relative');
$(window).on('scroll', function(event) {
var scrollTop = $(window).scrollTop();
element.stop(false, false).animate({
top: scrollTop < originalY
? 0
: scrollTop - originalY + topMargin
}, 0);
});
})(jQuery);
}
Try this ! just add class .to_move_content to you div
You should logged in not as "root" user.
Or assign permission to your "current_user" to do this by using following command
sudo chown -R username.www-data /var/www
sudo chmod -R +rwx /var/www
Open the file again using vi. and then press the insert button to begin editing it.
Note that datetime.datetime.fromtimestamp(timestamp) and .utcfromtimestamp(timestamp) fail on windows for dates before Jan. 1, 1970 while negative unix timestamps seem to work on unix-based platforms. The docs say this:
See also Issue1646728
Have you tried this?
Out = subprocess.Popen('/usr/local/bin/script hostname = actual_server_name -p LONGLIST'.split(), shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
Edited per the apt comment from @J.F.Sebastian
First, create your splash screen as a borderless, immovable form with your image on it, set to initially display at the center of the screen, colored the way you want. All of this can be set from within the designer; specifically, you want to:
Then, you need to decide where to show it and where to dismiss it. These two tasks need to occur on opposite sides of the main startup logic of your program. This could be in your application's main() routine, or possibly in your main application form's Load handler; wherever you're creating large expensive objects, reading settings from the hard drive, and generally taking a long time to do stuff behind the scenes before the main application screen displays.
Then, all you have to do is create an instance of your form, Show() it, and keep a reference to it while you do your startup initialization. Once your main form has loaded, Close() it.
If your splash screen will have an animated image on it, the window will need to be "double-buffered" as well, and you will need to be absolutely sure that all initialization logic happens outside the GUI thread (meaning you cannot have your main loading logic in the mainform's Load handler; you'll have to create a BackgroundWorker or some other threaded routine.
You can also use the [Required]
data annotation attribute to solve this:
public class Foo
{
public string FooId { get; set; }
public Boo Boo { get; set; }
}
public class Boo
{
public string BooId { get; set; }
[Required]
public Foo Foo {get; set; }
}
Foo
is required for Boo
.
try this
from StringIO import StringIO
x="1 3\n 4.5 8"
numpy.genfromtxt(StringIO(x))
You should remove the &
(ampersand) symbol, so that line 4 will look like this:
$conn = ADONewConnection($config['db_type']);
This is because ADONewConnection already returns an object by reference. As per documentation, assigning the result of a reference to object by reference results in an E_DEPRECATED message as of PHP 5.3.0
I struggled a lot to resolve it Nothing seemed to work for me.
The steps I followed are mentioned here.
1 - Go to your App settings.
2 - Click on Add domain.
3 - A dialog will open & will ask you to enter the desired domain. (Please add it starting with www
for instance - www.abcd.com
)
4 - One added click on Next to move to the next dialog.
5 - After adding the domain you will get the DNS target, Now you need to navigate to GoDaddy and follow the following steps.
6 - Navigate to https://dcc.godaddy.com/domains & click on your domain.
7 - Once clicked you will navigate to https://dcc.godaddy.com/control/yourdomain/settings
8 - Scroll down to the bottom you will see Manage DNS.
9 - It will navigate you to DNS settings then add the entry similar to mentioned below and delete all other CNAME
records. Here the value of points is your DNS target that you got in the 4th Step.
10 - Then after some time your site should be mapped to the Heroku app URL.
Generally this error arise when we send header after echoing or printing. If this error arise on a specific page then make sure that page is not echoing anything before calling to start_session()
.
Example of Unpredictable Error:
<?php //a white-space before <?php also send for output and arise error
session_start();
session_regenerate_id();
//your page content
One more example:
<?php
includes 'functions.php';
?> <!-- This new line will also arise error -->
<?php
session_start();
session_regenerate_id();
//your page content
Conclusion: Do not output any character before calling session_start()
or header()
functions not even a white-space or new-line
In matplotlib a color map isn't a list, but it contains the list of its colors as colormap.colors
. And the module matplotlib.colors
provides a function ListedColormap()
to generate a color map from a list. So you can reverse any color map by doing
colormap_r = ListedColormap(colormap.colors[::-1])
Another alternative to cut, copy and paste emojis is:
Similar, but again a little bit different.
Make the image 100% opacity so it is clear. And then on img hover reduce it to the opacity you want. In this example, I have also added easing for a nice transition.
img {
-webkit-filter: brightness(100%);
}
img:hover {
-webkit-filter: brightness(70%);
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
-o-transition: all 1s ease;
-ms-transition: all 1s ease;
transition: all 1s ease;
}
That will do it, Hope that helps.
Thank you Robert Byers for your jsfiddle
i fixed my problem by this code on linux file system
if (!file.exists())
Files.createFile(file.toPath());
nvarchar is going to have significant overhead in memory, storage, working set and indexing, so if the specs dictate that it really will never be necessary, don't bother.
I would not have a hard and fast "always nvarchar" rule because it can be a complete waste in many situations - particularly ETL from ASCII/EBCDIC or identifiers and code columns which are often keys and foreign keys.
On the other hand, there are plenty of cases of columns, where I would be sure to ask this question early and if I didn't get a hard and fast answer immediately, I would make the column nvarchar.
use g++
instead of gcc
.
No, you have to use the underscore, but I believe that VB.NET 10 will allow multiple lines w/o the underscore, only requiring if it can't figure out where the end should be.
Use the if __name__ == '__main__'
idiom -- __name__
is a special variable whose value is '__main__'
if the module is being run as a script, and the module name if it's imported. So you'd do something like
# imports
# class/function definitions
if __name__ == '__main__':
# code here will only run when you invoke 'python main.py'
To be clearer, I make an example here,
class ClassA {
class func func1() -> String {
return "func1"
}
static func func2() -> String {
return "func2"
}
/* same as above
final class func func2() -> String {
return "func2"
}
*/
}
static func
is same as final class func
Because it is final
, we can not override it in subclass as below:
class ClassB : ClassA {
override class func func1() -> String {
return "func1 in ClassB"
}
// ERROR: Class method overrides a 'final` class method
override static func func2() -> String {
return "func2 in ClassB"
}
}
Processing speed may not be the only relevant matter, however, as that's the question, here are some numbers in a benchmark: JSON vs. XML: Some hard numbers about verbosity. For the speed, in this simple benchmark, XML presents a 21% overhead over JSON.
An important note about the verbosity, which is as the article says, the most common complain: this is not so much relevant in practice (neither XML nor JSON data are typically handled by humans, but by machines), even if for the matter of speed, it requires some reasonable more time to compress.
Also, in this benchmark, a big amount of data was processed, and a typical web application won't transmit data chunks of such sizes, as big as 90MB, and compression may not be beneficial (for small enough data chunks, a compressed chunk will be bigger than the uncompressed chunk), so not applicable.
Still, if no compression is involved, JSON, as obviously terser, will weight less over the transmission channel, especially if transmitted through a WebSocket connection, where the absence of the classic HTTP overhead may make the difference at the advantage of JSON, even more significant.
After transmission, data is to be consumed, and this count in the overall processing time. If big or complex enough data are to be transmitted, the lack of a schema automatically checked for by a validating XML parser, may require more check on JSON data; these checks would have to be executed in JavaScript, which is not known to be particularly fast, and so it may present an additional overhead over XML in such cases.
Anyway, only testing will provides the answer for your particular use-case (if speed is really the only matter, and not standard nor safety nor integrity…).
Update 1: worth to mention, is EXI, the binary XML format, which offers compression at less cost than using Gzip, and save processing otherwise needed to decompress compressed XML. EXI is to XML, what BSON is to JSON. Have a quick overview here, with some reference to efficiency in both space and time: EXI: The last binary standard?.
Update 2: there also exists a binary XML performance reports, conducted by the W3C, as efficiency and low memory and CPU footprint, is also a matter for the XML area too: Efficient XML Interchange Evaluation.
Worth to be noticed in this context, as HTTP overhead was raised as an issue: the IANA has registered the EXI encoding (the efficient binary XML mentioned above), as a a Content Coding for the HTTP protocol (alongside with compress, deflate and gzip). This means EXI is an option which can be expected to be understood by browsers among possibly other HTTP clients. See Hypertext Transfer Protocol Parameters (iana.org).
public void schedule(TimerTask task,long delay)
Schedules the specified task for execution after the specified delay.
you want:
public void schedule(TimerTask task, long delay, long period)
Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.
How about:
Random generator = new Random();
int i = 10 - generator.nextInt(10);
You can do it with HttpWebRequest
:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
Username = "myusername",
Password = "pass"
});
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
I thought I would add this function for those seeking an answer without importing itertools or any other extra libraries.
def powerSet(items):
"""
Power set generator: get all possible combinations of a list’s elements
Input:
items is a list
Output:
returns 2**n combination lists one at a time using a generator
Reference: edx.org 6.00.2x Lecture 2 - Decision Trees and dynamic programming
"""
N = len(items)
# enumerate the 2**N possible combinations
for i in range(2**N):
combo = []
for j in range(N):
# test bit jth of integer i
if (i >> j) % 2 == 1:
combo.append(items[j])
yield combo
Simple Yield Generator Usage:
for i in powerSet([1,2,3,4]):
print (i, ", ", end="")
Output from Usage example above:
[] , [1] , [2] , [1, 2] , [3] , [1, 3] , [2, 3] , [1, 2, 3] , [4] , [1, 4] , [2, 4] , [1, 2, 4] , [3, 4] , [1, 3, 4] , [2, 3, 4] , [1, 2, 3, 4] ,
The pdfrw
library can do this quite easily, assuming you don't need to preserve bookmarks and annotations, and your PDFs aren't encrypted. cat.py
is an example concatenation script, and subset.py
is an example page subsetting script.
The relevant part of the concatenation script -- assumes inputs
is a list of input filenames, and outfn
is an output file name:
from pdfrw import PdfReader, PdfWriter
writer = PdfWriter()
for inpfn in inputs:
writer.addpages(PdfReader(inpfn).pages)
writer.write(outfn)
As you can see from this, it would be pretty easy to leave out the last page, e.g. something like:
writer.addpages(PdfReader(inpfn).pages[:-1])
Disclaimer: I am the primary pdfrw
author.
From the documentation:
You cannot use ORDER BY or LIMIT in a multiple-table DELETE.
From PHP:
function OutputJs($Content)
{
ob_start();
echo $Content;
$expires = DAY_IN_S; // 60 * 60 * 24 ... defined elsewhere
header("Content-type: x-javascript");
header('Content-Length: ' . ob_get_length());
header('Cache-Control: max-age='.$expires.', must-revalidate');
header('Pragma: public');
header('Expires: '. gmdate('D, d M Y H:i:s', time()+$expires).'GMT');
ob_end_flush();
return;
}
works for me.
As a developer you'll probably quickly run into the situation that you don't want files cached, in which case see Help with aggressive JavaScript caching
You need a split function:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Function [dbo].[udf_Split]
(
@DelimitedList nvarchar(max)
, @Delimiter nvarchar(2) = ','
)
RETURNS TABLE
AS
RETURN
(
With CorrectedList As
(
Select Case When Left(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
+ @DelimitedList
+ Case When Right(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
As List
, Len(@Delimiter) As DelimiterLen
)
, Numbers As
(
Select TOP( Coalesce(DataLength(@DelimitedList)/2,0) ) Row_Number() Over ( Order By c1.object_id ) As Value
From sys.columns As c1
Cross Join sys.columns As c2
)
Select CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
, Substring (
CL.List
, CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen
, CharIndex(@Delimiter, CL.list, N.Value + 1)
- ( CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen )
) As Value
From CorrectedList As CL
Cross Join Numbers As N
Where N.Value <= DataLength(CL.List) / 2
And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter
)
With your split function, you would then use Cross Apply to get the data:
Select T.Col1, T.Col2
, Substring( Z.Value, 1, Charindex(' = ', Z.Value) - 1 ) As AttributeName
, Substring( Z.Value, Charindex(' = ', Z.Value) + 1, Len(Z.Value) ) As Value
From Table01 As T
Cross Apply dbo.udf_Split( T.Col3, '|' ) As Z
Although not exactly answering the question as formulated, but if you need or can take the end result as string you can also use
string s = Char.ConvertFromUtf32(56);
which will give you surrogate UTF-16 pairs if needed, protecting you if you are out side of the BMP.
Even though this thread is old, yet I would like to share my experience (recently started working with facebook), which seems to me straight:
To get the Development key for facebook integration, use the following command from the command line in windows:
keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%.android\debug.keystore | "C:\openssl\bin\openssl.exe" sha1 -binary | "C:\openssl\bin\openssl.exe" base64
NOTE!: please replace the path for openssl.exe (in this example it is "C:\openssl\bin\openssl.exe") with your own installation path.
Enter keystore password: android
Type android as password as shown above.
Thats it! You will be given a 28 character long key. Cheers!
Use the same procedure to get the Release key. Just replace the command with the following and use your release key alias.
keytool -exportcert -alias YOUR_RELEASE_KEY_ALIAS -keystore YOUR_RELEASE_KEY_PATH | "PATH FOR openssl.exe" sha1 -binary | openssl base64
You can use the base64
CLI tool to generate the base64 encoded version of your username + password like this:
$ echo -n "joeuser:secretpass" | base64
am9ldXNlcjpzZWNyZXRwYXNz
-or-
$ base64 <<<"joeuser:secretpass"
am9ldXNlcjpzZWNyZXRwYXNzCg==
Base64 is reversible so you can also decode it to confirm like this:
$ echo -n "joeuser:secretpass" | base64 | base64 -D
joeuser:secretpass
-or-
$ base64 <<<"joeuser:secretpass" | base64 -D
joeuser:secretpass
NOTE: username = joeuser, password = secretpass
You can put this together into curl
like this:
$ curl -H "Authorization: Basic $(base64 <<<"joeuser:secretpass")" http://example.com
Most will likely agree that if you're going to bother doing this, then you might as well just use curl
's -u
option.
$ curl --help |grep -- "--user " -u, --user USER[:PASSWORD] Server user and password
For example:
$ curl -u someuser:secretpass http://example.com
But you can do this in a semi-safer manner if you keep your credentials in a encrypted vault service such as LastPass or Pass.
For example, here I'm using the LastPass' CLI tool, lpass
, to retrieve my credentials:
$ curl -u $(lpass show --username example.com):$(lpass show --password example.com) \
http://example.com
There's an even safer way to hand your credentials off to curl
though. This method makes use of the -K
switch.
$ curl -X GET -K \
<(cat <<<"user = \"$(lpass show --username example.com):$(lpass show --password example.com)\"") \
http://example.com
When used, your details remain hidden, since they're passed to curl
via a temporary file descriptor, for example:
+ curl -skK /dev/fd/63 -XGET -H 'Content-Type: application/json' https://es-data-01a.example.com:9200/_cat/health
++ cat
+++ lpass show --username example.com
+++ lpass show --password example.com
1561075296 00:01:36 rdu-es-01 green 9 6 2171 1085 0 0 0 0 - 100.0%
NOTE: Above I'm communicating with one of our Elasticsearch nodes, inquiring about the cluster's health.
This method is dynamically creating a file with the contents user = "<username>:<password>"
and giving that to curl
.
The methods shown above are facilitating a feature known as Basic Authorization that's part of the HTTP standard.
When the user agent wants to send authentication credentials to the server, it may use the Authorization field.
The Authorization field is constructed as follows:
- The username and password are combined with a single colon (:). This means that the username itself cannot contain a colon.
- The resulting string is encoded into an octet sequence. The character set to use for this encoding is by default unspecified, as long as it is compatible with US-ASCII, but the server may suggest use of UTF-8 by sending the charset parameter.
- The resulting string is encoded using a variant of Base64.
- The authorization method and a space (e.g. "Basic ") is then prepended to the encoded string.
For example, if the browser uses Aladdin as the username and OpenSesame as the password, then the field's value is the base64-encoding of Aladdin:OpenSesame, or QWxhZGRpbjpPcGVuU2VzYW1l. Then the Authorization header will appear as:
Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l
Source: Basic access authentication
Your regex says the following:
/^ - if the line starts with
( - start a capture group
Clinton| - "Clinton"
| - or
[^Bush] - Any single character except "B", "u", "s" or "h"
| - or
Reagan) - "Reagan". End capture group.
/i - Make matches case-insensitive
So, in other words, your middle part of the regex is screwing you up. As it is a "catch-all" kind of group, it will allow any line that does not begin with any of the upper or lower case letters in "Bush". For example, these lines would match your regex:
Our president, George Bush
In the news today, pigs can fly
012-3123 33
You either make a negative look-ahead, as suggested earlier, or you simply make two regexes:
if( ($string =~ m/^(Clinton|Reagan)/i) and
($string !~ m/^Bush/i) ) {
print "$string\n";
}
As mirod has pointed out in the comments, the second check is quite unnecessary when using the caret (^
) to match only beginning of lines, as lines that begin with "Clinton" or "Reagan" could never begin with "Bush".
However, it would be valid without the carets.
np.count_nonzero(~np.isnan(data))
~
inverts the boolean matrix returned from np.isnan
.
np.count_nonzero
counts values that is not 0\false. .sum
should give the same result. But maybe more clearly to use count_nonzero
Testing speed:
In [23]: data = np.random.random((10000,10000))
In [24]: data[[np.random.random_integers(0,10000, 100)],:][:, [np.random.random_integers(0,99, 100)]] = np.nan
In [25]: %timeit data.size - np.count_nonzero(np.isnan(data))
1 loops, best of 3: 309 ms per loop
In [26]: %timeit np.count_nonzero(~np.isnan(data))
1 loops, best of 3: 345 ms per loop
In [27]: %timeit data.size - np.isnan(data).sum()
1 loops, best of 3: 339 ms per loop
data.size - np.count_nonzero(np.isnan(data))
seems to barely be the fastest here. other data might give different relative speed results.
Update: Looks like chartjs has been updated (see comment below). There are some examples up that look very nice:
Original Post
As of Nov 2013, there seem to be very few options for updating charts.
There is a good example here (duplicated below) of adding new points to a line chart. Still kind of jumpy but not too bad. However, I think the effect probably depends on the chart you are using.
It does look like this is somewhere in the development pipeline. I don't see any indication of a release date yet though: https://github.com/nnnick/Chart.js/issues/13 [Closed as of Jul 26, 2014]
JS
$(document).ready(function(){
var count = 10;
var data = {
labels : ["1","2","3","4","5", "6", "7", "8", "9", "10"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [65,59,90,81,56,45,30,20,3,37]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [28,48,40,19,96,87,66,97,92,85]
}
]
}
// this is ugly, don't judge me
var updateData = function(oldData){
var labels = oldData["labels"];
var dataSetA = oldData["datasets"][0]["data"];
var dataSetB = oldData["datasets"][1]["data"];
labels.shift();
count++;
labels.push(count.toString());
var newDataA = dataSetA[9] + (20 - Math.floor(Math.random() * (41)));
var newDataB = dataSetB[9] + (20 - Math.floor(Math.random() * (41)));
dataSetA.push(newDataA);
dataSetB.push(newDataB);
dataSetA.shift();
dataSetB.shift(); };
var optionsAnimation = {
//Boolean - If we want to override with a hard coded scale
scaleOverride : true,
//** Required if scaleOverride is true **
//Number - The number of steps in a hard coded scale
scaleSteps : 10,
//Number - The value jump in the hard coded scale
scaleStepWidth : 10,
//Number - The scale starting value
scaleStartValue : 0
}
// Not sure why the scaleOverride isn't working...
var optionsNoAnimation = {
animation : false,
//Boolean - If we want to override with a hard coded scale
scaleOverride : true,
//** Required if scaleOverride is true **
//Number - The number of steps in a hard coded scale
scaleSteps : 20,
//Number - The value jump in the hard coded scale
scaleStepWidth : 10,
//Number - The scale starting value
scaleStartValue : 0
}
//Get the context of the canvas element we want to select
var ctx = document.getElementById("myChart").getContext("2d");
var optionsNoAnimation = {animation : false}
var myNewChart = new Chart(ctx);
myNewChart.Line(data, optionsAnimation);
setInterval(function(){
updateData(data);
myNewChart.Line(data, optionsNoAnimation)
;}, 2000
);
});
// ChartJS
var Chart=function(s){function v(a,c,b){a=A((a-c.graphMin)/(c.steps*c.stepValue),1,0);return b*c.steps*a}function x(a,c,b,e){function h(){g+=f;var k=a.animation?A(d(g),null,0):1;e.clearRect(0,0,q,u);a.scaleOverlay?(b(k),c()):(c(),b(k));if(1>=g)D(h);else if("function"==typeof a.onAnimationComplete)a.onAnimationComplete()}var f=a.animation?1/A(a.animationSteps,Number.MAX_VALUE,1):1,d=B[a.animationEasing],g=a.animation?0:1;"function"!==typeof c&&(c=function(){});D(h)}function C(a,c,b,e,h,f){var d;a=
Math.floor(Math.log(e-h)/Math.LN10);h=Math.floor(h/(1*Math.pow(10,a)))*Math.pow(10,a);e=Math.ceil(e/(1*Math.pow(10,a)))*Math.pow(10,a)-h;a=Math.pow(10,a);for(d=Math.round(e/a);d<b||d>c;)a=d<b?a/2:2*a,d=Math.round(e/a);c=[];z(f,c,d,h,a);return{steps:d,stepValue:a,graphMin:h,labels:c}}function z(a,c,b,e,h){if(a)for(var f=1;f<b+1;f++)c.push(E(a,{value:(e+h*f).toFixed(0!=h%1?h.toString().split(".")[1].length:0)}))}function A(a,c,b){return!isNaN(parseFloat(c))&&isFinite(c)&&a>c?c:!isNaN(parseFloat(b))&&
isFinite(b)&&a<b?b:a}function y(a,c){var b={},e;for(e in a)b[e]=a[e];for(e in c)b[e]=c[e];return b}function E(a,c){var b=!/\W/.test(a)?F[a]=F[a]||E(document.getElementById(a).innerHTML):new Function("obj","var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('"+a.replace(/[\r\t\n]/g," ").split("<%").join("\t").replace(/((^|%>)[^\t]*)'/g,"$1\r").replace(/\t=(.*?)%>/g,"',$1,'").split("\t").join("');").split("%>").join("p.push('").split("\r").join("\\'")+"');}return p.join('');");return c?
b(c):b}var r=this,B={linear:function(a){return a},easeInQuad:function(a){return a*a},easeOutQuad:function(a){return-1*a*(a-2)},easeInOutQuad:function(a){return 1>(a/=0.5)?0.5*a*a:-0.5*(--a*(a-2)-1)},easeInCubic:function(a){return a*a*a},easeOutCubic:function(a){return 1*((a=a/1-1)*a*a+1)},easeInOutCubic:function(a){return 1>(a/=0.5)?0.5*a*a*a:0.5*((a-=2)*a*a+2)},easeInQuart:function(a){return a*a*a*a},easeOutQuart:function(a){return-1*((a=a/1-1)*a*a*a-1)},easeInOutQuart:function(a){return 1>(a/=0.5)?
0.5*a*a*a*a:-0.5*((a-=2)*a*a*a-2)},easeInQuint:function(a){return 1*(a/=1)*a*a*a*a},easeOutQuint:function(a){return 1*((a=a/1-1)*a*a*a*a+1)},easeInOutQuint:function(a){return 1>(a/=0.5)?0.5*a*a*a*a*a:0.5*((a-=2)*a*a*a*a+2)},easeInSine:function(a){return-1*Math.cos(a/1*(Math.PI/2))+1},easeOutSine:function(a){return 1*Math.sin(a/1*(Math.PI/2))},easeInOutSine:function(a){return-0.5*(Math.cos(Math.PI*a/1)-1)},easeInExpo:function(a){return 0==a?1:1*Math.pow(2,10*(a/1-1))},easeOutExpo:function(a){return 1==
a?1:1*(-Math.pow(2,-10*a/1)+1)},easeInOutExpo:function(a){return 0==a?0:1==a?1:1>(a/=0.5)?0.5*Math.pow(2,10*(a-1)):0.5*(-Math.pow(2,-10*--a)+2)},easeInCirc:function(a){return 1<=a?a:-1*(Math.sqrt(1-(a/=1)*a)-1)},easeOutCirc:function(a){return 1*Math.sqrt(1-(a=a/1-1)*a)},easeInOutCirc:function(a){return 1>(a/=0.5)?-0.5*(Math.sqrt(1-a*a)-1):0.5*(Math.sqrt(1-(a-=2)*a)+1)},easeInElastic:function(a){var c=1.70158,b=0,e=1;if(0==a)return 0;if(1==(a/=1))return 1;b||(b=0.3);e<Math.abs(1)?(e=1,c=b/4):c=b/(2*
Math.PI)*Math.asin(1/e);return-(e*Math.pow(2,10*(a-=1))*Math.sin((1*a-c)*2*Math.PI/b))},easeOutElastic:function(a){var c=1.70158,b=0,e=1;if(0==a)return 0;if(1==(a/=1))return 1;b||(b=0.3);e<Math.abs(1)?(e=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/e);return e*Math.pow(2,-10*a)*Math.sin((1*a-c)*2*Math.PI/b)+1},easeInOutElastic:function(a){var c=1.70158,b=0,e=1;if(0==a)return 0;if(2==(a/=0.5))return 1;b||(b=1*0.3*1.5);e<Math.abs(1)?(e=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/e);return 1>a?-0.5*e*Math.pow(2,10*
(a-=1))*Math.sin((1*a-c)*2*Math.PI/b):0.5*e*Math.pow(2,-10*(a-=1))*Math.sin((1*a-c)*2*Math.PI/b)+1},easeInBack:function(a){return 1*(a/=1)*a*(2.70158*a-1.70158)},easeOutBack:function(a){return 1*((a=a/1-1)*a*(2.70158*a+1.70158)+1)},easeInOutBack:function(a){var c=1.70158;return 1>(a/=0.5)?0.5*a*a*(((c*=1.525)+1)*a-c):0.5*((a-=2)*a*(((c*=1.525)+1)*a+c)+2)},easeInBounce:function(a){return 1-B.easeOutBounce(1-a)},easeOutBounce:function(a){return(a/=1)<1/2.75?1*7.5625*a*a:a<2/2.75?1*(7.5625*(a-=1.5/2.75)*
a+0.75):a<2.5/2.75?1*(7.5625*(a-=2.25/2.75)*a+0.9375):1*(7.5625*(a-=2.625/2.75)*a+0.984375)},easeInOutBounce:function(a){return 0.5>a?0.5*B.easeInBounce(2*a):0.5*B.easeOutBounce(2*a-1)+0.5}},q=s.canvas.width,u=s.canvas.height;window.devicePixelRatio&&(s.canvas.style.width=q+"px",s.canvas.style.height=u+"px",s.canvas.height=u*window.devicePixelRatio,s.canvas.width=q*window.devicePixelRatio,s.scale(window.devicePixelRatio,window.devicePixelRatio));this.PolarArea=function(a,c){r.PolarArea.defaults={scaleOverlay:!0,
scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleShowLine:!0,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!0,scaleLabel:"<%=value%>",scaleFontFamily:"'Arial'",scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",scaleShowLabelBackdrop:!0,scaleBackdropColor:"rgba(255,255,255,0.75)",scaleBackdropPaddingY:2,scaleBackdropPaddingX:2,segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,animation:!0,animationSteps:100,animationEasing:"easeOutBounce",
animateRotate:!0,animateScale:!1,onAnimationComplete:null};var b=c?y(r.PolarArea.defaults,c):r.PolarArea.defaults;return new G(a,b,s)};this.Radar=function(a,c){r.Radar.defaults={scaleOverlay:!1,scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleShowLine:!0,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!1,scaleLabel:"<%=value%>",scaleFontFamily:"'Arial'",scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",scaleShowLabelBackdrop:!0,scaleBackdropColor:"rgba(255,255,255,0.75)",
scaleBackdropPaddingY:2,scaleBackdropPaddingX:2,angleShowLineOut:!0,angleLineColor:"rgba(0,0,0,.1)",angleLineWidth:1,pointLabelFontFamily:"'Arial'",pointLabelFontStyle:"normal",pointLabelFontSize:12,pointLabelFontColor:"#666",pointDot:!0,pointDotRadius:3,pointDotStrokeWidth:1,datasetStroke:!0,datasetStrokeWidth:2,datasetFill:!0,animation:!0,animationSteps:60,animationEasing:"easeOutQuart",onAnimationComplete:null};var b=c?y(r.Radar.defaults,c):r.Radar.defaults;return new H(a,b,s)};this.Pie=function(a,
c){r.Pie.defaults={segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,animation:!0,animationSteps:100,animationEasing:"easeOutBounce",animateRotate:!0,animateScale:!1,onAnimationComplete:null};var b=c?y(r.Pie.defaults,c):r.Pie.defaults;return new I(a,b,s)};this.Doughnut=function(a,c){r.Doughnut.defaults={segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,percentageInnerCutout:50,animation:!0,animationSteps:100,animationEasing:"easeOutBounce",animateRotate:!0,animateScale:!1,
onAnimationComplete:null};var b=c?y(r.Doughnut.defaults,c):r.Doughnut.defaults;return new J(a,b,s)};this.Line=function(a,c){r.Line.defaults={scaleOverlay:!1,scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!0,scaleLabel:"<%=value%>",scaleFontFamily:"'Arial'",scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",scaleShowGridLines:!0,scaleGridLineColor:"rgba(0,0,0,.05)",scaleGridLineWidth:1,bezierCurve:!0,
pointDot:!0,pointDotRadius:4,pointDotStrokeWidth:2,datasetStroke:!0,datasetStrokeWidth:2,datasetFill:!0,animation:!0,animationSteps:60,animationEasing:"easeOutQuart",onAnimationComplete:null};var b=c?y(r.Line.defaults,c):r.Line.defaults;return new K(a,b,s)};this.Bar=function(a,c){r.Bar.defaults={scaleOverlay:!1,scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!0,scaleLabel:"<%=value%>",scaleFontFamily:"'Arial'",
scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",scaleShowGridLines:!0,scaleGridLineColor:"rgba(0,0,0,.05)",scaleGridLineWidth:1,barShowStroke:!0,barStrokeWidth:2,barValueSpacing:5,barDatasetSpacing:1,animation:!0,animationSteps:60,animationEasing:"easeOutQuart",onAnimationComplete:null};var b=c?y(r.Bar.defaults,c):r.Bar.defaults;return new L(a,b,s)};var G=function(a,c,b){var e,h,f,d,g,k,j,l,m;g=Math.min.apply(Math,[q,u])/2;g-=Math.max.apply(Math,[0.5*c.scaleFontSize,0.5*c.scaleLineWidth]);
d=2*c.scaleFontSize;c.scaleShowLabelBackdrop&&(d+=2*c.scaleBackdropPaddingY,g-=1.5*c.scaleBackdropPaddingY);l=g;d=d?d:5;e=Number.MIN_VALUE;h=Number.MAX_VALUE;for(f=0;f<a.length;f++)a[f].value>e&&(e=a[f].value),a[f].value<h&&(h=a[f].value);f=Math.floor(l/(0.66*d));d=Math.floor(0.5*(l/d));m=c.scaleShowLabels?c.scaleLabel:null;c.scaleOverride?(j={steps:c.scaleSteps,stepValue:c.scaleStepWidth,graphMin:c.scaleStartValue,labels:[]},z(m,j.labels,j.steps,c.scaleStartValue,c.scaleStepWidth)):j=C(l,f,d,e,h,
m);k=g/j.steps;x(c,function(){for(var a=0;a<j.steps;a++)if(c.scaleShowLine&&(b.beginPath(),b.arc(q/2,u/2,k*(a+1),0,2*Math.PI,!0),b.strokeStyle=c.scaleLineColor,b.lineWidth=c.scaleLineWidth,b.stroke()),c.scaleShowLabels){b.textAlign="center";b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily;var e=j.labels[a];if(c.scaleShowLabelBackdrop){var d=b.measureText(e).width;b.fillStyle=c.scaleBackdropColor;b.beginPath();b.rect(Math.round(q/2-d/2-c.scaleBackdropPaddingX),Math.round(u/2-k*(a+
1)-0.5*c.scaleFontSize-c.scaleBackdropPaddingY),Math.round(d+2*c.scaleBackdropPaddingX),Math.round(c.scaleFontSize+2*c.scaleBackdropPaddingY));b.fill()}b.textBaseline="middle";b.fillStyle=c.scaleFontColor;b.fillText(e,q/2,u/2-k*(a+1))}},function(e){var d=-Math.PI/2,g=2*Math.PI/a.length,f=1,h=1;c.animation&&(c.animateScale&&(f=e),c.animateRotate&&(h=e));for(e=0;e<a.length;e++)b.beginPath(),b.arc(q/2,u/2,f*v(a[e].value,j,k),d,d+h*g,!1),b.lineTo(q/2,u/2),b.closePath(),b.fillStyle=a[e].color,b.fill(),
c.segmentShowStroke&&(b.strokeStyle=c.segmentStrokeColor,b.lineWidth=c.segmentStrokeWidth,b.stroke()),d+=h*g},b)},H=function(a,c,b){var e,h,f,d,g,k,j,l,m;a.labels||(a.labels=[]);g=Math.min.apply(Math,[q,u])/2;d=2*c.scaleFontSize;for(e=l=0;e<a.labels.length;e++)b.font=c.pointLabelFontStyle+" "+c.pointLabelFontSize+"px "+c.pointLabelFontFamily,h=b.measureText(a.labels[e]).width,h>l&&(l=h);g-=Math.max.apply(Math,[l,1.5*(c.pointLabelFontSize/2)]);g-=c.pointLabelFontSize;l=g=A(g,null,0);d=d?d:5;e=Number.MIN_VALUE;
h=Number.MAX_VALUE;for(f=0;f<a.datasets.length;f++)for(m=0;m<a.datasets[f].data.length;m++)a.datasets[f].data[m]>e&&(e=a.datasets[f].data[m]),a.datasets[f].data[m]<h&&(h=a.datasets[f].data[m]);f=Math.floor(l/(0.66*d));d=Math.floor(0.5*(l/d));m=c.scaleShowLabels?c.scaleLabel:null;c.scaleOverride?(j={steps:c.scaleSteps,stepValue:c.scaleStepWidth,graphMin:c.scaleStartValue,labels:[]},z(m,j.labels,j.steps,c.scaleStartValue,c.scaleStepWidth)):j=C(l,f,d,e,h,m);k=g/j.steps;x(c,function(){var e=2*Math.PI/
a.datasets[0].data.length;b.save();b.translate(q/2,u/2);if(c.angleShowLineOut){b.strokeStyle=c.angleLineColor;b.lineWidth=c.angleLineWidth;for(var d=0;d<a.datasets[0].data.length;d++)b.rotate(e),b.beginPath(),b.moveTo(0,0),b.lineTo(0,-g),b.stroke()}for(d=0;d<j.steps;d++){b.beginPath();if(c.scaleShowLine){b.strokeStyle=c.scaleLineColor;b.lineWidth=c.scaleLineWidth;b.moveTo(0,-k*(d+1));for(var f=0;f<a.datasets[0].data.length;f++)b.rotate(e),b.lineTo(0,-k*(d+1));b.closePath();b.stroke()}c.scaleShowLabels&&
(b.textAlign="center",b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily,b.textBaseline="middle",c.scaleShowLabelBackdrop&&(f=b.measureText(j.labels[d]).width,b.fillStyle=c.scaleBackdropColor,b.beginPath(),b.rect(Math.round(-f/2-c.scaleBackdropPaddingX),Math.round(-k*(d+1)-0.5*c.scaleFontSize-c.scaleBackdropPaddingY),Math.round(f+2*c.scaleBackdropPaddingX),Math.round(c.scaleFontSize+2*c.scaleBackdropPaddingY)),b.fill()),b.fillStyle=c.scaleFontColor,b.fillText(j.labels[d],0,-k*(d+
1)))}for(d=0;d<a.labels.length;d++){b.font=c.pointLabelFontStyle+" "+c.pointLabelFontSize+"px "+c.pointLabelFontFamily;b.fillStyle=c.pointLabelFontColor;var f=Math.sin(e*d)*(g+c.pointLabelFontSize),h=Math.cos(e*d)*(g+c.pointLabelFontSize);b.textAlign=e*d==Math.PI||0==e*d?"center":e*d>Math.PI?"right":"left";b.textBaseline="middle";b.fillText(a.labels[d],f,-h)}b.restore()},function(d){var e=2*Math.PI/a.datasets[0].data.length;b.save();b.translate(q/2,u/2);for(var g=0;g<a.datasets.length;g++){b.beginPath();
b.moveTo(0,d*-1*v(a.datasets[g].data[0],j,k));for(var f=1;f<a.datasets[g].data.length;f++)b.rotate(e),b.lineTo(0,d*-1*v(a.datasets[g].data[f],j,k));b.closePath();b.fillStyle=a.datasets[g].fillColor;b.strokeStyle=a.datasets[g].strokeColor;b.lineWidth=c.datasetStrokeWidth;b.fill();b.stroke();if(c.pointDot){b.fillStyle=a.datasets[g].pointColor;b.strokeStyle=a.datasets[g].pointStrokeColor;b.lineWidth=c.pointDotStrokeWidth;for(f=0;f<a.datasets[g].data.length;f++)b.rotate(e),b.beginPath(),b.arc(0,d*-1*
v(a.datasets[g].data[f],j,k),c.pointDotRadius,2*Math.PI,!1),b.fill(),b.stroke()}b.rotate(e)}b.restore()},b)},I=function(a,c,b){for(var e=0,h=Math.min.apply(Math,[u/2,q/2])-5,f=0;f<a.length;f++)e+=a[f].value;x(c,null,function(d){var g=-Math.PI/2,f=1,j=1;c.animation&&(c.animateScale&&(f=d),c.animateRotate&&(j=d));for(d=0;d<a.length;d++){var l=j*a[d].value/e*2*Math.PI;b.beginPath();b.arc(q/2,u/2,f*h,g,g+l);b.lineTo(q/2,u/2);b.closePath();b.fillStyle=a[d].color;b.fill();c.segmentShowStroke&&(b.lineWidth=
c.segmentStrokeWidth,b.strokeStyle=c.segmentStrokeColor,b.stroke());g+=l}},b)},J=function(a,c,b){for(var e=0,h=Math.min.apply(Math,[u/2,q/2])-5,f=h*(c.percentageInnerCutout/100),d=0;d<a.length;d++)e+=a[d].value;x(c,null,function(d){var k=-Math.PI/2,j=1,l=1;c.animation&&(c.animateScale&&(j=d),c.animateRotate&&(l=d));for(d=0;d<a.length;d++){var m=l*a[d].value/e*2*Math.PI;b.beginPath();b.arc(q/2,u/2,j*h,k,k+m,!1);b.arc(q/2,u/2,j*f,k+m,k,!0);b.closePath();b.fillStyle=a[d].color;b.fill();c.segmentShowStroke&&
(b.lineWidth=c.segmentStrokeWidth,b.strokeStyle=c.segmentStrokeColor,b.stroke());k+=m}},b)},K=function(a,c,b){var e,h,f,d,g,k,j,l,m,t,r,n,p,s=0;g=u;b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily;t=1;for(d=0;d<a.labels.length;d++)e=b.measureText(a.labels[d]).width,t=e>t?e:t;q/a.labels.length<t?(s=45,q/a.labels.length<Math.cos(s)*t?(s=90,g-=t):g-=Math.sin(s)*t):g-=c.scaleFontSize;d=c.scaleFontSize;g=g-5-d;e=Number.MIN_VALUE;h=Number.MAX_VALUE;for(f=0;f<a.datasets.length;f++)for(l=
0;l<a.datasets[f].data.length;l++)a.datasets[f].data[l]>e&&(e=a.datasets[f].data[l]),a.datasets[f].data[l]<h&&(h=a.datasets[f].data[l]);f=Math.floor(g/(0.66*d));d=Math.floor(0.5*(g/d));l=c.scaleShowLabels?c.scaleLabel:"";c.scaleOverride?(j={steps:c.scaleSteps,stepValue:c.scaleStepWidth,graphMin:c.scaleStartValue,labels:[]},z(l,j.labels,j.steps,c.scaleStartValue,c.scaleStepWidth)):j=C(g,f,d,e,h,l);k=Math.floor(g/j.steps);d=1;if(c.scaleShowLabels){b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily;
for(e=0;e<j.labels.length;e++)h=b.measureText(j.labels[e]).width,d=h>d?h:d;d+=10}r=q-d-t;m=Math.floor(r/(a.labels.length-1));n=q-t/2-r;p=g+c.scaleFontSize/2;x(c,function(){b.lineWidth=c.scaleLineWidth;b.strokeStyle=c.scaleLineColor;b.beginPath();b.moveTo(q-t/2+5,p);b.lineTo(q-t/2-r-5,p);b.stroke();0<s?(b.save(),b.textAlign="right"):b.textAlign="center";b.fillStyle=c.scaleFontColor;for(var d=0;d<a.labels.length;d++)b.save(),0<s?(b.translate(n+d*m,p+c.scaleFontSize),b.rotate(-(s*(Math.PI/180))),b.fillText(a.labels[d],
0,0),b.restore()):b.fillText(a.labels[d],n+d*m,p+c.scaleFontSize+3),b.beginPath(),b.moveTo(n+d*m,p+3),c.scaleShowGridLines&&0<d?(b.lineWidth=c.scaleGridLineWidth,b.strokeStyle=c.scaleGridLineColor,b.lineTo(n+d*m,5)):b.lineTo(n+d*m,p+3),b.stroke();b.lineWidth=c.scaleLineWidth;b.strokeStyle=c.scaleLineColor;b.beginPath();b.moveTo(n,p+5);b.lineTo(n,5);b.stroke();b.textAlign="right";b.textBaseline="middle";for(d=0;d<j.steps;d++)b.beginPath(),b.moveTo(n-3,p-(d+1)*k),c.scaleShowGridLines?(b.lineWidth=c.scaleGridLineWidth,
b.strokeStyle=c.scaleGridLineColor,b.lineTo(n+r+5,p-(d+1)*k)):b.lineTo(n-0.5,p-(d+1)*k),b.stroke(),c.scaleShowLabels&&b.fillText(j.labels[d],n-8,p-(d+1)*k)},function(d){function e(b,c){return p-d*v(a.datasets[b].data[c],j,k)}for(var f=0;f<a.datasets.length;f++){b.strokeStyle=a.datasets[f].strokeColor;b.lineWidth=c.datasetStrokeWidth;b.beginPath();b.moveTo(n,p-d*v(a.datasets[f].data[0],j,k));for(var g=1;g<a.datasets[f].data.length;g++)c.bezierCurve?b.bezierCurveTo(n+m*(g-0.5),e(f,g-1),n+m*(g-0.5),
e(f,g),n+m*g,e(f,g)):b.lineTo(n+m*g,e(f,g));b.stroke();c.datasetFill?(b.lineTo(n+m*(a.datasets[f].data.length-1),p),b.lineTo(n,p),b.closePath(),b.fillStyle=a.datasets[f].fillColor,b.fill()):b.closePath();if(c.pointDot){b.fillStyle=a.datasets[f].pointColor;b.strokeStyle=a.datasets[f].pointStrokeColor;b.lineWidth=c.pointDotStrokeWidth;for(g=0;g<a.datasets[f].data.length;g++)b.beginPath(),b.arc(n+m*g,p-d*v(a.datasets[f].data[g],j,k),c.pointDotRadius,0,2*Math.PI,!0),b.fill(),b.stroke()}}},b)},L=function(a,
c,b){var e,h,f,d,g,k,j,l,m,t,r,n,p,s,w=0;g=u;b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily;t=1;for(d=0;d<a.labels.length;d++)e=b.measureText(a.labels[d]).width,t=e>t?e:t;q/a.labels.length<t?(w=45,q/a.labels.length<Math.cos(w)*t?(w=90,g-=t):g-=Math.sin(w)*t):g-=c.scaleFontSize;d=c.scaleFontSize;g=g-5-d;e=Number.MIN_VALUE;h=Number.MAX_VALUE;for(f=0;f<a.datasets.length;f++)for(l=0;l<a.datasets[f].data.length;l++)a.datasets[f].data[l]>e&&(e=a.datasets[f].data[l]),a.datasets[f].data[l]<
h&&(h=a.datasets[f].data[l]);f=Math.floor(g/(0.66*d));d=Math.floor(0.5*(g/d));l=c.scaleShowLabels?c.scaleLabel:"";c.scaleOverride?(j={steps:c.scaleSteps,stepValue:c.scaleStepWidth,graphMin:c.scaleStartValue,labels:[]},z(l,j.labels,j.steps,c.scaleStartValue,c.scaleStepWidth)):j=C(g,f,d,e,h,l);k=Math.floor(g/j.steps);d=1;if(c.scaleShowLabels){b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily;for(e=0;e<j.labels.length;e++)h=b.measureText(j.labels[e]).width,d=h>d?h:d;d+=10}r=q-d-t;m=
Math.floor(r/a.labels.length);s=(m-2*c.scaleGridLineWidth-2*c.barValueSpacing-(c.barDatasetSpacing*a.datasets.length-1)-(c.barStrokeWidth/2*a.datasets.length-1))/a.datasets.length;n=q-t/2-r;p=g+c.scaleFontSize/2;x(c,function(){b.lineWidth=c.scaleLineWidth;b.strokeStyle=c.scaleLineColor;b.beginPath();b.moveTo(q-t/2+5,p);b.lineTo(q-t/2-r-5,p);b.stroke();0<w?(b.save(),b.textAlign="right"):b.textAlign="center";b.fillStyle=c.scaleFontColor;for(var d=0;d<a.labels.length;d++)b.save(),0<w?(b.translate(n+
d*m,p+c.scaleFontSize),b.rotate(-(w*(Math.PI/180))),b.fillText(a.labels[d],0,0),b.restore()):b.fillText(a.labels[d],n+d*m+m/2,p+c.scaleFontSize+3),b.beginPath(),b.moveTo(n+(d+1)*m,p+3),b.lineWidth=c.scaleGridLineWidth,b.strokeStyle=c.scaleGridLineColor,b.lineTo(n+(d+1)*m,5),b.stroke();b.lineWidth=c.scaleLineWidth;b.strokeStyle=c.scaleLineColor;b.beginPath();b.moveTo(n,p+5);b.lineTo(n,5);b.stroke();b.textAlign="right";b.textBaseline="middle";for(d=0;d<j.steps;d++)b.beginPath(),b.moveTo(n-3,p-(d+1)*
k),c.scaleShowGridLines?(b.lineWidth=c.scaleGridLineWidth,b.strokeStyle=c.scaleGridLineColor,b.lineTo(n+r+5,p-(d+1)*k)):b.lineTo(n-0.5,p-(d+1)*k),b.stroke(),c.scaleShowLabels&&b.fillText(j.labels[d],n-8,p-(d+1)*k)},function(d){b.lineWidth=c.barStrokeWidth;for(var e=0;e<a.datasets.length;e++){b.fillStyle=a.datasets[e].fillColor;b.strokeStyle=a.datasets[e].strokeColor;for(var f=0;f<a.datasets[e].data.length;f++){var g=n+c.barValueSpacing+m*f+s*e+c.barDatasetSpacing*e+c.barStrokeWidth*e;b.beginPath();
b.moveTo(g,p);b.lineTo(g,p-d*v(a.datasets[e].data[f],j,k)+c.barStrokeWidth/2);b.lineTo(g+s,p-d*v(a.datasets[e].data[f],j,k)+c.barStrokeWidth/2);b.lineTo(g+s,p);c.barShowStroke&&b.stroke();b.closePath();b.fill()}}},b)},D=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){window.setTimeout(a,1E3/60)},F={}};
HTML
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<h1>Live Updating Chart.js</h1>
<canvas id="myChart" width="400" height="150"></canvas>
</body>
</html>
Think of it as a stack with the disks diameter being represented by integers (4,3,2,1) The first recursion call will be called 3 times and thus filling the run-time stack as follows
After the first recursion ends, the contents of the run-time stack is popped to the middle pole from largest diameter to smallest (first in last out). Next, disk with diameter 4 is moved to the destination.
The second recursion call is the same as the first with the exception of moving the elements from the middle pole to destination.
Or you can use the ItemDataBound
event in the code behind.
Have a look at override_function
to override the functions.
override_function — Overrides built-in functions
Example:
override_function('test', '$a,$b', 'echo "DOING TEST"; return $a * $b;');
in addition to what Kirk said I want to tell you that just "playing around" won't help you to learn asp.net, and there is a lot of free and very good tutorials .
take a look on the asp.net official site tutorials and on 4GuysFromRolla site
DateTime date1 = new DateTime();
date1 = Convert.ToDateTime(TextBox1.Text);
Label1.Text = (date1.ToLongTimeString()); //11:00 AM
Label2.Text = date1.ToLongDateString(); //Friday, November 1, 2019;
Label3.Text = date1.ToString();
Label4.Text = date1.ToShortDateString();
Label5.Text = date1.ToShortTimeString();
I dont think you need to use jQuery at all, just simple JavaScript...
Save the date as a string:
dte = fecha.value;//2014-01-06
Split the string to get the day, month & year values...
dteSplit = dte.split("-");
yr = dteSplit[0][2] + dteSplit[0][3]; //special yr format, take last 2 digits
month = dteSplit[1];
day = dteSplit[2];
Rejoin into final date string:
finalDate = month+"-"+day+"-"+year
Use below command in Debian based container:
apt-get install vim-tiny
Complete instruction for using in Dockerfile:
RUN apt-get update && apt-get install --no-install-recommends -y \
vim-tiny \
&& apt-get clean && rm -rf /var/lib/apt/lists/*
It doesn't install unnecessary packages and removes unnecessary downloaded files, so your docker image size won't increase dramatically.
I use the following format and works well.
robocopy \\SourceServer\Path \\TargetServer\Path filename.txt
to copy everything you can replace filename.txt
with *.*
and there are plenty of other switches to copy subfolders etc... see here: http://ss64.com/nt/robocopy.html
there is a simple trick you can work here but it need preparation before you print, you have to put what ever you wants to print in a variable and then print so you will know the length to remove the string.here is an example.
#include <iostream>
#include <string> //actually this thing is not nessasory in tdm-gcc
using namespace std;
int main(){
//create string variable
string str="Starting count";
//loop for printing numbers
for(int i =0;i<=50000;i++){
//get previous string length and clear it from screen with backspace charactor
cout << string(str.length(),'\b');
//create string line
str="Starting count " +to_string(i);
//print the new line in same spot
cout <<str ;
}
}
If you’re not averse to using double-dollar scope props and you’re writing a directive whose only content is a repeat, there is a pretty simple solution (assuming you only care about the initial render). In the link function:
const dereg = scope.$watch('$$childTail.$last', last => {
if (last) {
dereg();
// do yr stuff -- you may still need a $timeout here
}
});
This is useful for cases where you have a directive that needs to do DOM manip based on the widths or heights of the members of a rendered list (which I think is the most likely reason one would ask this question), but it’s not as generic as the other solutions that have been proposed.
Obviously there is no "better" -- or more worth learning -- language at all. Which language you use is is just a matter of what you like AND what your server supports. You should not learn a language that wouldn't be supported by any server or is said to be dying in the near future. On the other hand it is obvious too that there will be even better languages in the future and that those will be more useful. So learn one that is fast, convenient and that you like and where learning it wouldn't be a too big effort because, as said, you're likely to change in less than 3 years.
I, personally would be considering an "open-source" (not proprietary) one, because the web is open to everyone and open-source is more likely to be supported by every-one. (Which means PHP in this case)
.replace(/\s+/, "")
Will replace the first whitespace only, this includes spaces, tabs and new lines.
To replace all whitespace in the string you need to use global mode
.replace(/\s/g, "")
This is effectively the same as parameterized
as mentioned in a previous answer, but specific to unittest
:
def sub_test(param_list):
"""Decorates a test case to run it as a set of subtests."""
def decorator(f):
@functools.wraps(f)
def wrapped(self):
for param in param_list:
with self.subTest(**param):
f(self, **param)
return wrapped
return decorator
Example usage:
class TestStuff(unittest.TestCase):
@sub_test([
dict(arg1='a', arg2='b'),
dict(arg1='x', arg2='y'),
])
def test_stuff(self, a, b):
...
Database first approach example:
Without writing any code: ASP.NET MVC / MVC3 Database First Approach / Database first
And I think it is better than other approaches because data loss is less with this approach.
This worked fine for me
Hope this work for all Thank you Ramesh Kumar
What matters isn't the attribute but the property, and its value is a boolean.
You can set it using
document.getElementById("edName").required = true;
I sympathise with the question - I too found (find?) the choice bewildering, so I set out scientifically to see which data structure is the fastest (I did the test using VB, but I imagine C# would be the same, since both languages do the same thing at the CLR level). You can see some benchmarking results conducted by me here (there's also some discussion of which data type is best to use in which circumstances).
I'll assume that Time
and Product
are columns in a DataFrame
, df
is an instance of DataFrame
, and that other variables are scalar values:
For now, you'll have to reference the DataFrame
instance:
k1 = df.loc[(df.Product == p_id) & (df.Time >= start_time) & (df.Time < end_time), ['Time', 'Product']]
The parentheses are also necessary, because of the precedence of the &
operator vs. the comparison operators. The &
operator is actually an overloaded bitwise operator which has the same precedence as arithmetic operators which in turn have a higher precedence than comparison operators.
In pandas
0.13 a new experimental DataFrame.query()
method will be available. It's extremely similar to subset modulo the select
argument:
With query()
you'd do it like this:
df[['Time', 'Product']].query('Product == p_id and Month < mn and Year == yr')
Here's a simple example:
In [9]: df = DataFrame({'gender': np.random.choice(['m', 'f'], size=10), 'price': poisson(100, size=10)})
In [10]: df
Out[10]:
gender price
0 m 89
1 f 123
2 f 100
3 m 104
4 m 98
5 m 103
6 f 100
7 f 109
8 f 95
9 m 87
In [11]: df.query('gender == "m" and price < 100')
Out[11]:
gender price
0 m 89
4 m 98
9 m 87
The final query that you're interested will even be able to take advantage of chained comparisons, like this:
k1 = df[['Time', 'Product']].query('Product == p_id and start_time <= Time < end_time')
Just incase anybody is interested in a pure css solution for this. The following code overlays a transparent div over the map, and moves the transparent div behind the map when it is clicked. The overlay prevents zooming, once clicked, and behind the map, zooming is enabled.
See my blog post Google maps toggle zoom with css for an explanation how it works, and pen codepen.io/daveybrown/pen/yVryMr for a working demo.
Disclaimer: this is mainly for learning and probably won't be the best solution for production websites.
HTML:
<div class="map-wrap small-11 medium-8 small-centered columns">
<input id="map-input" type="checkbox" />
<label class="map-overlay" for="map-input" class="label" onclick=""></label>
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d19867.208601651986!2d-0.17101002911118332!3d51.50585742500925!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1sen!2suk!4v1482355389969"></iframe>
</div>
CSS:
.map-wrap {
position: relative;
overflow: hidden;
height: 180px;
margin-bottom: 10px;
}
#map-input {
opacity: 0;
}
.map-overlay {
display: block;
content: '';
position: absolute;
top: 0;
left: 0;
width: 100% !important;
height: 100% !important;
overflow: hidden;
z-index: 2;
}
#map-input[type=checkbox]:checked ~ iframe {
z-index: 3;
}
#map-input[type=checkbox]:checked ~ .map-overlay {
position: fixed;
top: 0;
left: 0;
width: 100% !important;
height: 100% !important;
}
iframe {
position: absolute;
top: 0;
left: 0;
width: 100% !important;
height: 100% !important;
z-index: 1;
border: none;
}
EDIT: This answer was correct until mid-2013, but you may have a more recent version since the big msbuild change. See the answer from Jonny Leeds for more details.
The version under C:\Windows\Microsoft.NET\Framework\v4.0.30319
actually is .NET 4.5. It's a little odd, but certainly mscorlib
there contains AsyncTaskMethodBuilder
etc which are used for async.
.NET 4.5 effectively overwrites .NET 4.
A general purpose set of functions to render any python data structure (dicts and lists nested together) as HTML.
from IPython.display import HTML, display
def _render_list_html(l):
o = []
for e in l:
o.append('<li>%s</li>' % _render_as_html(e))
return '<ol>%s</ol>' % ''.join(o)
def _render_dict_html(d):
o = []
for k, v in d.items():
o.append('<tr><td>%s</td><td>%s</td></tr>' % (str(k), _render_as_html(v)))
return '<table>%s</table>' % ''.join(o)
def _render_as_html(e):
o = []
if isinstance(e, list):
o.append(_render_list_html(e))
elif isinstance(e, dict):
o.append(_render_dict_html(e))
else:
o.append(str(e))
return '<html><body>%s</body></html>' % ''.join(o)
def render_as_html(e):
display(HTML(_render_as_html(e)))
There are only two cases when the circle intersects with the rectangle:
Note that this does not require the rectangle to be axis-parallel.
(One way to see this: if none of the edges has a point in the circle (if all the edges are completely "outside" the circle), then the only way the circle can still intersect the polygon is if it lies completely inside the polygon.)
With that insight, something like the following will work, where the circle has centre P
and radius R
, and the rectangle has vertices A
, B
, C
, D
in that order (not complete code):
def intersect(Circle(P, R), Rectangle(A, B, C, D)):
S = Circle(P, R)
return (pointInRectangle(P, Rectangle(A, B, C, D)) or
intersectCircle(S, (A, B)) or
intersectCircle(S, (B, C)) or
intersectCircle(S, (C, D)) or
intersectCircle(S, (D, A)))
If you're writing any geometry you probably have the above functions in your library already. Otherwise, pointInRectangle()
can be implemented in several ways; any of the general point in polygon methods will work, but for a rectangle you can just check whether this works:
0 = AP·AB = AB·AB and 0 = AP·AD = AD·AD
And intersectCircle()
is easy to implement too: one way would be to check if the foot of the perpendicular from P
to the line is close enough and between the endpoints, and check the endpoints otherwise.
The cool thing is that the same idea works not just for rectangles but for the intersection of a circle with any simple polygon — doesn't even have to be convex!
map()
doesn't return a list, it returns a map
object.
You need to call list(map)
if you want it to be a list again.
Even better,
from itertools import imap
payIntList = list(imap(int, payList))
Won't take up a bunch of memory creating an intermediate object, it will just pass the ints
out as it creates them.
Also, you can do if choice.lower() == 'n':
so you don't have to do it twice.
Python supports +=
: you can do payIntList[i] += 1000
and numElements += 1
if you want.
If you really want to be tricky:
from itertools import count
for numElements in count(1):
payList.append(raw_input("Enter the pay amount: "))
if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
break
and / or
for payInt in payIntList:
payInt += 1000
print payInt
Also, four spaces is the standard indent amount in Python.
Send your file as a base64 string.
var element = angular.element('<a/>');
element.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(atob(response.payload)),
target: '_blank',
download: fname
})[0].click();
If attr method not working in Firefox You can also use javaScript setAttribute method
Symfony is smart and knows how to make the find()
by itself :
public function deleteGuestAction(Guest $guest)
{
if (!$guest) {
throw $this->createNotFoundException('No guest found');
}
$em = $this->getDoctrine()->getEntityManager();
$em->remove($guest);
$em->flush();
return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
}
To send the id in your controller, use {{ path('your_route', {'id': guest.id}) }}
If you are insisting to use the window.location.origin
You can put this in top of your code before reading the origin
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
PS: For the record, it was actually the original question. It was already edited :)
This is a simple way to do it without any triggers or sequences:
insert into WORKQUEUE (ID, facilitycode, workaction, description) values ((select count(1)+1 from WORKQUEUE), 'J', 'II', 'TESTVALUES');
Note : here need to use count(1) in place of max(id) column
It perfectly works for an empty table also.
The answer was posted above but wasn't complete. here is the completed version:
XAML
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MapTest.Window1"
x:Name="Window"
Title="Window1"
Width="1950" Height="1546" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:Controls="clr-namespace:WPFExtensions.Controls;assembly=WPFExtensions" mc:Ignorable="d" Background="#FF000000">
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="52.92"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Border Grid.Row="1" Name="border">
<Image Name="image" Source="map3-2.png" Opacity="1" RenderTransformOrigin="0.5,0.5" />
</Border>
</Grid>
Code Behind
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
namespace MapTest
{
public partial class Window1 : Window
{
private Point origin;
private Point start;
public Window1()
{
InitializeComponent();
TransformGroup group = new TransformGroup();
ScaleTransform xform = new ScaleTransform();
group.Children.Add(xform);
TranslateTransform tt = new TranslateTransform();
group.Children.Add(tt);
image.RenderTransform = group;
image.MouseWheel += image_MouseWheel;
image.MouseLeftButtonDown += image_MouseLeftButtonDown;
image.MouseLeftButtonUp += image_MouseLeftButtonUp;
image.MouseMove += image_MouseMove;
}
private void image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
image.ReleaseMouseCapture();
}
private void image_MouseMove(object sender, MouseEventArgs e)
{
if (!image.IsMouseCaptured) return;
var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
Vector v = start - e.GetPosition(border);
tt.X = origin.X - v.X;
tt.Y = origin.Y - v.Y;
}
private void image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
image.CaptureMouse();
var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
start = e.GetPosition(border);
origin = new Point(tt.X, tt.Y);
}
private void image_MouseWheel(object sender, MouseWheelEventArgs e)
{
TransformGroup transformGroup = (TransformGroup) image.RenderTransform;
ScaleTransform transform = (ScaleTransform) transformGroup.Children[0];
double zoom = e.Delta > 0 ? .2 : -.2;
transform.ScaleX += zoom;
transform.ScaleY += zoom;
}
}
}
I have an example of a full wpf project using this code on my website: Jot the sticky note app.
As NSAttributedString
is primarily used with Core Text on iOS, you have to use CTParagraphStyle
instead of NSParagraphStyle
. There is no mutable variant.
For example:
CTTextAlignment alignment = kCTCenterTextAlignment;
CTParagraphStyleSetting alignmentSetting;
alignmentSetting.spec = kCTParagraphStyleSpecifierAlignment;
alignmentSetting.valueSize = sizeof(CTTextAlignment);
alignmentSetting.value = &alignment;
CTParagraphStyleSetting settings[1] = {alignmentSetting};
size_t settingsCount = 1;
CTParagraphStyleRef paragraphRef = CTParagraphStyleCreate(settings, settingsCount);
NSDictionary *attributes = @{(__bridge id)kCTParagraphStyleAttributeName : (__bridge id)paragraphRef};
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"Hello World" attributes:attributes];
Its a good programming practice to avoid having null
values in a Map.
If you have an entry with null
value, then it is not possible to tell whether an entry is present in the map or has a null
value associated with it.
You can either define a constant for such cases (Example: String NOT_VALID = "#NA"
), or you can have another collection storing keys which have null
values.
Please check this link for more details.
You can find the most up to date answer for the value in your project just execute the
mvn3 help:effective-pom
command and find the <build> ... <directory>
tag's value in the result aka in the effective-pom. It will show the value of the Super POM unless you have overwritten.
This is what I'm doing in my project: I just create another .py file called properties.py which includes all common variables/properties I used in the project, and in any file need to refer to these variables, put
from properties import *(or anything you need)
Used this method to keep svn peace when I was changing dev locations frequently and some common variables were quite relative to local environment. Works fine for me but not sure this method would be suggested for formal dev environment etc.
This ought to work:
^\d+\s?(\([^\)]+\)\s?)?Z$
Haven't tested it though, but let me give you the breakdown, so if there are any bugs left they should be pretty straightforward to find:
First the beginning:
^ = beginning of string
\d+ = one or more decimal characters
\s? = one optional whitespace
Then this part:
(\([^\)]+\)\s?)?
Is actually:
(.............)?
Which makes the following contents optional, only if it exists fully
\([^\)]+\)\s?
\( = an opening bracket
[^\)]+ = a series of at least one character that is not a closing bracket
\) = followed by a closing bracket
\s? = followed by one optional whitespace
And the end is made up of
Z$
Where
Z = your constant string
$ = the end of the string
I changes only two points
Obviously they were according to the version of the versions that it has, otherwise they would have to download them
buil.gradle(Project)
dependencies {
classpath 'com.android.toolsg.build:gradle:2.3.2'
..
}
gradle.wrapper.properties
...
distributionUrl=https://services.gradle.org/distributions/gradle-3.3-all.zip
Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.
@RestController
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {
@Value("${name}")//not necessary
private String name;//not necessary
private static String NAME_STATIC;
@Value("${name}")
public void setNameStatic(String name){
PropertyController.NAME_STATIC = name;
}
}
Ok, first e.preventDefault();
it's not a Jquery element, it's a method of javascript, now what it's true it's if you add this method you avoid the submit the event, now what you could do it's send the form by ajax something like this
$('#subscription_order_form').submit(function(e){
$.ajax({
url: $(this).attr('action'),
data : $(this).serialize(),
success : function (data){
}
});
e.preventDefault();
});
The .btn classes are designed for , or elements (though some browsers may apply a slightly different rendering).
If you’re using .btn classes on elements that are used to trigger functionality ex. collapsing content, these links should be given a role="button" to adequately communicate their meaning to assistive technologies such as screen readers. I hope this help.
This has nothing to do with using PDO, it's just that you are confusing INSERT and UPDATE.
Here's the difference:
INSERT
creates a new row. I'm guessing that you really want to create a new row.UPDATE
changes the values in an existing row, but if this is what you're doing you probably should use a WHERE clause to restrict the change to a specific row, because the default is that it applies to every row.So this will probably do what you want:
$sql = "INSERT INTO `access_users`
(`contact_first_name`,`contact_surname`,`contact_email`,`telephone`)
VALUES (:firstname, :surname, :email, :telephone);
";
Note that I've also changed the order of columns; the order of your columns must match the order of values in your VALUES clause.
MySQL also supports an alternative syntax for INSERT:
$sql = "INSERT INTO `access_users`
SET `contact_first_name` = :firstname,
`contact_surname` = :surname,
`contact_email` = :email,
`telephone` = :telephone
";
This alternative syntax looks a bit more like an UPDATE statement, but it creates a new row like INSERT. The advantage is that it's easier to match up the columns to the correct parameters.
Replying to very old post. But maybe it will help some newbie and if non of the above works out.
Explanation: I know nobody wants explanation crap; rather the solution. But in one liner, you are trying to access a service from your local machine to a remote machine which does not trust your machine. You request need to gain the trust from remote server.
Solution: The following solution assumes that you have the following conditions met
Steps:
You need a .keystore extension file to signup your app. If you don't know how to create .keystore file; then follow along with the following section Create .keystore file or otherwise skip to next section Sign Apk File
Create .keystore file
Open Android Studio. Click top menu Build > Generate Signed APK. In the next window click the Create new... button. In the new window, please input in data in all fields. Remember the two Password field i recommend should have the same password; don't use different password; and also remember the save path at top most field Key store path:. After you input all the field click OK button.
Sign Apk File
Now you need to build a signed app with the .keystore file you just created. Follow these steps
Choose existing...
buttonKey store password
and Key password
fields. Also enter the aliasbuild.gradle
files, you need to select Build Types
and Flavors
.Build Types
choose release
from the dropdownFor Flavors
however it will depends on your settings in build.gradle
file. Choose staging
from this field. I used the following settings in the build.gradle
, you can use the same as mine, but make sure you change the applicationId
to your package name
productFlavors {
staging {
applicationId "com.yourapplication.package"
manifestPlaceholders = [icon: "@drawable/ic_launcher"]
buildConfigField "boolean", "CATALYST_DEBUG", "true"
buildConfigField "boolean", "ALLOW_INVALID_CERTIFICATE", "true"
}
production {
buildConfigField "boolean", "CATALYST_DEBUG", "false"
buildConfigField "boolean", "ALLOW_INVALID_CERTIFICATE", "false"
}
}
Click the bottom two Signature Versions
checkboxes and click Finish
button.
Almost There:
All the hardwork is done, now the movement of truth. Inorder to access the Staging server backed-up by proxy, you need to make some setting in your real testing Android devices.
Proxy Setting in Android Device:
Modify network
Advanced options
if you can't see the Proxy Hostname
fieldProxy Hostname
enter the host IP or name you want to connect. A typical staging server will be named as stg.api.mygoodcompany.com
9502
Save
buttonOne Last Stop:
Remember we generated the signed apk file in Sign APK File section. Now is the time to install that APK file.
adb install
name of the apk file
adb command not found
. Enter the full path as C:\Users\shah\AppData\Local\Android\sdk\platform-tools\adb.exe
install
name of the apk file
I hope the problem might be solved. If not please leave me a comments.
Salam!
As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.
In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field
class HealthConditions extends React.Component {
constructor(props) {
super(props);
this.state = {
inputLinkClicked: false
}
}
handleAddSecondInput() {
this.setState({
inputLinkClicked: true
})
}
render() {
return(
<main id="wrapper" className="" data-reset-cookie-tab>
<div id="content" role="main">
<div className="inner-block">
<H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>
<InputField label="Name of condition"
InputType="text"
InputId="id-condition"
InputName="condition"
/>
{
this.state.inputLinkClicked?
<InputField label=""
InputType="text"
InputId="id-condition2"
InputName="condition2"
/>
:
<div></div>
}
<button
type="button"
className="make-button-link"
data-add-button=""
href="#"
onClick={this.handleAddSecondInput}
>
Add a condition
</button>
<FormButton buttonLabel="Next"
handleSubmit={this.handleSubmit}
linkto={
this.state.illnessOrDisability === 'true' ?
"/404"
:
"/add-your-details"
}
/>
<BackLink backLink="/add-your-details" />
</div>
</div>
</main>
);
}
}