import re
ul = '\u00a1-\uffff' # unicode letters range (must not be a raw string)
# IP patterns
ipv4_re = r'(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}'
ipv6_re = r'\[[0-9a-f:\.]+\]'
# Host patterns
hostname_re = r'[a-z' + ul + r'0-9](?:[a-z' + ul + r'0-9-]{0,61}[a-z' + ul + r'0-9])?'
domain_re = r'(?:\.(?!-)[a-z' + ul + r'0-9-]{1,63}(?<!-))*' # domain names have max length of 63 characters
tld_re = (
r'\.' # dot
r'(?!-)' # can't start with a dash
r'(?:[a-z' + ul + '-]{2,63}' # domain label
r'|xn--[a-z0-9]{1,59})' # or punycode label
r'(?<!-)' # can't end with a dash
r'\.?' # may have a trailing dot
)
host_re = '(' + hostname_re + domain_re + tld_re + '|localhost)'
regex = re.compile(
r'^(?:http|ftp)s?://' # http(s):// or ftp(s)://
r'(?:\S+(?::\S*)?@)?' # user:pass authentication
r'(?:' + ipv4_re + '|' + ipv6_re + '|' + host_re + ')' # localhost or ip
r'(?::\d{2,5})?' # optional port
r'(?:[/?#][^\s]*)?' # resource path
r'\Z', re.IGNORECASE)
source: https://github.com/django/django/blob/master/django/core/validators.py#L74
For future reference - the Line2D
artist returned by plot()
also has a set_markevery()
method which allows you to only set markers on certain points - see https://matplotlib.org/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D.set_markevery
It's easier with the enumitem package:
\documentclass{article}
\usepackage{enumitem}
\begin{document}
Less space:
\begin{itemize}[noitemsep]
\item foo
\item bar
\item baz
\end{itemize}
Even more compact:
\begin{itemize}[noitemsep,nolistsep]
\item foo
\item bar
\item baz
\end{itemize}
\end{document}
The enumitem package provides a lot of features to customize bullets, numbering and lengths.
The paralist package provides very compact lists: compactitem, compactenum and even lists within paragraphs like inparaenum and inparaitem.
cmd.Parameters.Add(new OracleParameter("GUSERID ", OracleType.VarChar)).Value = userId;
I was having eight parameters and one was with space at the end as shown in the above code for "GUSERID ".Removed the space and everything started working .
You can simply add these lines of codes here to hide a row,
Either you can write border:0
or border-style:hidden;
border: none
or it will happen the same thing
<style type="text/css">_x000D_
table, th, td {_x000D_
border: 1px solid;_x000D_
}_x000D_
_x000D_
tr.hide_all > td, td.hide_all{_x000D_
border: 0;_x000D_
_x000D_
}_x000D_
}_x000D_
</style>_x000D_
<table>_x000D_
<tr>_x000D_
<th>Firstname</th>_x000D_
<th>Lastname</th>_x000D_
<th>Savings</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Peter</td>_x000D_
<td>Griffin</td>_x000D_
<td>$100</td>_x000D_
</tr>_x000D_
<tr class= hide_all>_x000D_
<td>Lois</td>_x000D_
<td>Griffin</td>_x000D_
<td>$150</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Joe</td>_x000D_
<td>Swanson</td>_x000D_
<td>$300</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Cleveland</td>_x000D_
<td>Brown</td>_x000D_
<td>$250</td>_x000D_
</tr>_x000D_
</table>
_x000D_
running these lines of codes can solve the problem easily
Basically you have two options
scale_x_continuous(limits = c(-5000, 5000))
or
coord_cartesian(xlim = c(-5000, 5000))
Where the first removes all data points outside the given range and the second only adjusts the visible area. In most cases you would not see the difference, but if you fit anything to the data it would probably change the fitted values.
You can also use the shorthand function xlim
(or ylim
), which like the first option removes data points outside of the given range:
+ xlim(-5000, 5000)
For more information check the description of coord_cartesian
.
The RStudio cheatsheet for ggplot2
makes this quite clear visually. Here is a small section of that cheatsheet:
Distributed under CC BY.
private void Form1_Load(object sender, System.EventArgs e)
{
ToolTip toolTip1 = new ToolTip();
toolTip1.AutoPopDelay = 5000;
toolTip1.InitialDelay = 1000;
toolTip1.ReshowDelay = 500;
toolTip1.ShowAlways = true;
toolTip1.SetToolTip(this.button1, "My button1");
toolTip1.SetToolTip(this.checkBox1, "My checkBox1");
}
try it, maybe useful...
box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 3px #cbc9c9;
-webkit-box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 5px #cbc9c9;
-o-box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 5px #cbc9c9;
-moz-box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 5px #cbc9c9;
above CSS
cause you have a box shadow in bottom.
you can red more Here
You'll need to keep the current value of the input in state (or pass changes in its value up to a parent via a callback function, or sideways, or <your app's state management solution here> such that it eventually gets passed back into your component as a prop) so you can derive the disabled prop for the button.
Example using state:
<meta charset="UTF-8">_x000D_
<script src="https://fb.me/react-0.13.3.js"></script>_x000D_
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>_x000D_
<div id="app"></div>_x000D_
<script type="text/jsx;harmony=true">void function() { "use strict";_x000D_
_x000D_
var App = React.createClass({_x000D_
getInitialState() {_x000D_
return {email: ''}_x000D_
},_x000D_
handleChange(e) {_x000D_
this.setState({email: e.target.value})_x000D_
},_x000D_
render() {_x000D_
return <div>_x000D_
<input name="email" value={this.state.email} onChange={this.handleChange}/>_x000D_
<button type="button" disabled={!this.state.email}>Button</button>_x000D_
</div>_x000D_
}_x000D_
})_x000D_
_x000D_
React.render(<App/>, document.getElementById('app'))_x000D_
_x000D_
}()</script>
_x000D_
If someone is in search for a quick minimal solution,
import signal
# The code which crashes program on interruption
signal.signal(signal.SIGINT, call_this_function_if_interrupted)
# The code skipped if interrupted
I got the same error when the script file I was including container some special characters and when I was running in local moode (directly from local disk). I my case the solution was to explicitly tell the encoding:
<script src="my.js" charset="UTF-8"></script>
http://en.wikipedia.org/wiki/Database_transaction
http://en.wikipedia.org/wiki/ACID
ACID = Atomicity, Consistency, Isolation, Durability
When you wish for multiple transactional resources to be involved in a single transaction, you will need to use something like a two-phase commit solution. XA is quite widely supported.
Use this one :
onSelect: function(dateText) {
$("input#DateTo").datepicker('option', 'minDate', dateText);
}
This may be useful : http://jsfiddle.net/injulkarnilesh/xNeTe/
Try this :
Create anim folder inside your res folder and copy this four files :
slide_in_bottom.xml :
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="100%p"
android:duration="@android:integer/config_longAnimTime"/>
slide_out_bottom.xml :
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="0"
android:duration="@android:integer/config_longAnimTime" />
slide_in_top.xml :
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:toYDelta="0%p"
android:duration="@android:integer/config_longAnimTime" />
slide_out_top.xml :
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:toYDelta="100%p"
android:duration="@android:integer/config_longAnimTime" />
When you click on image view call:
overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom);
When you click on original place call:
overridePendingTransition(R.anim.slide_in_top, R.anim.slide_out_top);
Main Activity :
package com.example.animationtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, test.class));
}
});
}
}
activity_main.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
</LinearLayout>
test.java :
package com.example.animationtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class test extends Activity {
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
btn1 = (Button) findViewById(R.id.btn1);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_out_right);
startActivity(new Intent(test.this, MainActivity.class));
}
});
}
}
test.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
</LinearLayout>
Hope this helps.
Try out cat
and sprintf
in your for loop.
eg.
cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))
See here
You can simply import the data from the source file, read it, and save what you want to append to a variable. Then open the destination file, assign the list data inside to a new variable (presumably this will all be valid JSON), then use the 'append' function on this list variable and append the first variable to it. Viola, you have appended to the JSON list. Now just overwrite your destination file with the newly appended list (as JSON).
The 'a' mode in your 'open' function will not work here because it will just tack everything on to the end of the file, which will make it non-valid JSON format.
Starting simple, with no HTML:
foreach($database as $file) {
echo $file['filename'] . ' at ' . $file['filepath'];
}
And you can otherwise manipulate the fields in the foreach.
com.google.common.base.Strings.isNullOrEmpty(String string)
from Google Guava
if you just need to load script dont do as bellow
$(document.body).html('<script type="text/javascript" src="/json.js" async="async"><\/script>');
Try this
var scriptEl = document.createElement('SCRIPT');
scriptEl.src = "/module/script/form?_t="+(new Date()).getTime();
//$('#holder').append(scriptEl) // <--- create warning
document.body.appendChild(scriptEl);
I think your problems are due to your test structure. I've found it difficult to mix mocking with the traditional method of implementing interfaces in the test class (as you've done here).
If you implement the listener as a Mock you can then verify the interaction.
Listener listener = mock(Listener.class);
w.addListener(listener);
world.doAction(..);
verify(listener).doAction();
This should satisfy you that the 'World' is doing the right thing.
You have so many choices, how could you be confused :-)? The main controls are:
# \pset format
# \H
# \x
# \pset pager off
Each has options and interactions with the others. The most automatic options are:
# \x off;\pset format wrapped
# \x auto
The newer "\x auto" option switches to line-by-line display only "if needed".
-[ RECORD 1 ]---------------
id | 6
description | This is a gallery of oilve oil brands.
authority | I love olive oil, and wanted to create a place for
reviews and comments on various types.
-[ RECORD 2 ]---------------
id | 19
description | XXX Test A
authority | Testing
The older "\pset format wrapped" is similar in that it tries to fit the data neatly on screen, but falls back to unaligned if the headers won't fit. Here's an example of wrapped:
id | description | authority
----+--------------------------------+---------------------------------
6 | This is a gallery of oilve | I love olive oil, and wanted to
; oil brands. ; create a place for reviews and
; ; comments on various types.
19 | Test Test A | Testing
If you look into the source of java.lang.Runtime, you'll see exec finally call protected method: execVM, which means it uses Virtual memory. So for Unix-like system, VM depends on amount of swap space + some ratio of physical memory.
Michael's answer did solve your problem but it might (or to say, would eventually) cause the O.S. deadlock in memory allocation issue since 1 tell O.S. less careful of memory allocation & 0 is just guessing & obviously that you are lucky that O.S. guess you can have memory THIS TIME. Next time? Hmm.....
Better approach is that you experiment your case & give a good swap space & give a better ratio of physical memory used & set value to 2 rather than 1 or 0.
Consolidating the caveats mentioned in comments/answers for several use cases.
Mostly, see http://docs.telerik.com/fiddler/Configure-Fiddler/Tasks/ConfigureDotNETApp
In a console app, you might not need to specify the proxyaddress
:
<proxy bypassonlocal="False" usesystemdefault="True" />
In a web application / something hosted in IIS, you need to add the proxyaddress
:
<proxy bypassonlocal="False" usesystemdefault="True" proxyaddress="http://127.0.0.1:8888" />
HttpWebRequest
, etc) it will always bypass the Fiddler proxy for URLs containing localhost
, so you must use an alias like the machine name or make up something in your 'hosts' file (which is why something like localhost.fiddler
or http://HOSTNAME
works)If you specify the proxyaddress
, you must remove it from your config if Fiddler isn't on, or any requests your app makes will throw an exception like:
No connection could be made because the target machine actively refused it 127.0.0.1:8888
Just a little addition:
I believe it's a common and known thing to add exit;
after the header function in case we don't want the rest of the code to load or execute...
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
For XAMMP versions >=7.5.9-0 also change the DocumentRoot in file "/opt/lampp/etc/extra/httpd-ssl.conf" accordingly.
install TypeScript :
npm install typescript
add tsc script to package.json:
"scripts": {
"tsc": "tsc"
},
run this:
npx tsc --init
$user->data
is an array of objects. Each element in the array has a name
and value
property (as well as others).
Try putting the 2nd foreach
inside the 1st.
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}
Generate the HTML, CSS and JavaScript. It is easier to write generators than parsers, so you could generate each served page differently. You can no longer use a cache or static content then.
When it says users are connected, what does the query "select * from pg_stat_activity;" say? Are the other users besides yourself now connected? If so, you might have to edit your pg_hba.conf file to reject connections from other users, or shut down whatever app is accessing the pg database to be able to drop it. I have this problem on occasion in production. Set pg_hba.conf to have a two lines like this:
local all all ident
host all all 127.0.0.1/32 reject
and tell pgsql to reload or restart (i.e. either sudo /etc/init.d/postgresql reload or pg_ctl reload) and now the only way to connect to your machine is via local sockets. I'm assuming you're on linux. If not this may need to be tweaked to something other than local / ident on that first line, to something like host ... yourusername.
Now you should be able to do:
psql postgres
drop database mydatabase;
The string ctor is suitable for this conversion:
System.out.println("string " + new String(new byte[] {0x63}));
Sometimes the field is not recognized by crystal reports as DATE, so you can add a formula with function: Date({YourField}), And add it to the report, now when you open the format object dialog you will find the date formatting options.
$ git fetch --unshallow origin
$ git push you remote name
Here is a simple 3 step ES6 implementation using function binding in the parent constructor. This is the first way the official react tutorial recommends (there is also public class fields syntax not covered here). You can find all of this information here https://reactjs.org/docs/handling-events.html
Binding Parent Functions so Children Can Call Them (And pass data up to the parent! :D )
Parent Function
handleFilterApply(filterVals){}
Parent Constructor
this.handleFilterApply = this.handleFilterApply.bind(this);
Prop Passed to Child
onApplyClick = {this.handleFilterApply}
Child Event Call
onClick = {() => {props.onApplyClick(filterVals)}
Open the Settings / Preferences dialog (Ctrl + Alt + S), then click Editor and File Encodings.
Then, on the bottom, you will fing default encodings for properties files. Choose your encoding type.
Alternatively you can use unicode symbols instead of text in your resource bundle (for example "??"
equals \u0456\u0432
)
If you want every cell in the grid to have the same background color, you can just do this:
dataGridView1.DefaultCellStyle.BackColor = Color.Green;
Here is an example of how to send email through GMail which also uses SSL/465. Minor tweaking of the code below should work!
using System.Web.Mail;
using System;
public class MailSender
{
public static bool SendEmail(
string pGmailEmail,
string pGmailPassword,
string pTo,
string pSubject,
string pBody,
System.Web.Mail.MailFormat pFormat,
string pAttachmentPath)
{
try
{
System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserver",
"smtp.gmail.com");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
"465");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusing",
"2");
//sendusing: cdoSendUsingPort, value 2, for sending the message using
//the network.
//smtpauthenticate: Specifies the mechanism used when authenticating
//to an SMTP
//service over the network. Possible values are:
//- cdoAnonymous, value 0. Do not authenticate.
//- cdoBasic, value 1. Use basic clear-text authentication.
//When using this option you have to provide the user name and password
//through the sendusername and sendpassword fields.
//- cdoNTLM, value 2. The current process security context is used to
// authenticate with the service.
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate","1");
//Use 0 for anonymous
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusername",
pGmailEmail);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendpassword",
pGmailPassword);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
"true");
myMail.From = pGmailEmail;
myMail.To = pTo;
myMail.Subject = pSubject;
myMail.BodyFormat = pFormat;
myMail.Body = pBody;
if (pAttachmentPath.Trim() != "")
{
MailAttachment MyAttachment =
new MailAttachment(pAttachmentPath);
myMail.Attachments.Add(MyAttachment);
myMail.Priority = System.Web.Mail.MailPriority.High;
}
System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
System.Web.Mail.SmtpMail.Send(myMail);
return true;
}
catch (Exception ex)
{
throw;
}
}
}
Use example with from the post of Szilágyi Donát.
I use two querys, one to know what roles I have, excluding connect grant:
SELECT * FROM USER_ROLE_PRIVS WHERE GRANTED_ROLE != 'CONNECT'; -- Roles of the actual Oracle Schema
Know I like to find what privileges/roles my schema/user have; examples of my roles ROLE_VIEW_PAYMENTS & ROLE_OPS_CUSTOMERS. But to find the tables/objecst of an specific role I used:
SELECT * FROM ALL_TAB_PRIVS WHERE GRANTEE='ROLE_OPS_CUSTOMERS'; -- Objects granted at role.
The owner schema for this example could be PRD_CUSTOMERS_OWNER (or the role/schema inself).
Regards.
Image.paste
does not work as expected when the background image also contains transparency. You need to use real Alpha Compositing.
Pillow 2.0 contains an alpha_composite
function that does this.
background = Image.open("test1.png")
foreground = Image.open("test2.png")
Image.alpha_composite(background, foreground).save("test3.png")
EDIT: Both images need to be of the type RGBA. So you need to call convert('RGBA')
if they are paletted, etc.. If the background does not have an alpha channel, then you can use the regular paste method (which should be faster).
"Plain Old C# Object"
Just a normal class, no attributes describing infrastructure concerns or other responsibilities that your domain objects shouldn't have.
EDIT - as other answers have stated, it is technically "Plain Old CLR Object" but I, like David Arno comments, prefer "Plain Old Class Object" to avoid ties to specific languages or technologies.
TO CLARIFY: In other words, they don’t derive from some special base class, nor do they return any special types for their properties.
See below for an example of each.
Example of a POCO:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Example of something that isn’t a POCO:
public class PersonComponent : System.ComponentModel.Component
{
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Name { get; set; }
public int Age { get; set; }
}
The example above both inherits from a special class to give it additional behavior as well as uses a custom attribute to change behavior… the same properties exist on both classes, but one is not just a plain old object anymore.
As others have suggested that you should look into MERGE statement but nobody provided a solution using it I'm adding my own answer with this particular TSQL construct. I bet you'll like it.
Your code has a typo in your if
statement in not exists(select...)
part. Inner select
statement has only one where
condition while UserName condition is excluded from the not exists
due to invalid brace completion. In any case you cave too many closing braces.
I assume this based on the fact that you're using two where
conditions in update
statement later on in your code.
Let's continue to my answer...
MERGE statement is a beautiful TSQL gem very well suited for "insert or update" situations. In your case it would look similar to the following code. Take into consideration that I'm declaring variables what are likely stored procedure parameters (I suspect).
declare @clockDate date = '08/10/2012';
declare @userName = 'test';
merge Clock as target
using (select @clockDate, @userName) as source (ClockDate, UserName)
on (target.ClockDate = source.ClockDate and target.UserName = source.UserName)
when matched then
update
set BreakOut = getdate()
when not matched then
insert (ClockDate, UserName, BreakOut)
values (getdate(), source.UserName, getdate());
Use urllib2. For more specifics, check out this example from doc.python.org:
Here's a snippet from the tutorial that may help
import urllib2
req = urllib2.Request('ftp://example.com')
response = urllib2.urlopen(req)
the_page = response.read()
I solved this by right clicking in my textEdit program file and selecting [substitutions] and un-checking smart quotes.
Swift 4.2 / 5
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground),
name: Notification.Name.UIApplicationWillEnterForeground,
object: nil)
}
@objc func willEnterForeground() {
// do what's needed
}
Actually your checkAll(..)
is hanging without any attachment.
1) Add onchange
event handler
<th><INPUT type="checkbox" onchange="checkAll(this)" name="chk[]" /> </th>
2) Modified the code to handle check/uncheck
function checkAll(ele) {
var checkboxes = document.getElementsByTagName('input');
if (ele.checked) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = true;
}
}
} else {
for (var i = 0; i < checkboxes.length; i++) {
console.log(i)
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
}
<html>
<head >
<title>Welcome</title>
<style type="text/css">
#maincontainer
{
top:0px;
padding-top:0;
margin:auto; position:relative;
width:950px;
height:100%;
}
</style>
</head>
<body>
<div id="maincontainer ">
</div>
</body>
</html>
Adding to the other answers, please keep in mind that StringBuilder can be told an initial amount of memory to allocate.
The capacity parameter defines the maximum number of characters that can be stored in the memory allocated by the current instance. Its value is assigned to the Capacity property. If the number of characters to be stored in the current instance exceeds this capacity value, the StringBuilder object allocates additional memory to store them.
If capacity is zero, the implementation-specific default capacity is used.
Repeatedly appending to a StringBuilder that hasn't been pre-allocated can result in a lot of unnecessary allocations just like repeatedly concatenating regular strings.
If you know how long the final string will be, can trivially calculate it, or can make an educated guess about the common case (allocating too much isn't necessarily a bad thing), you should be providing this information to the constructor or the Capacity property. Especially when running performance tests to compare StringBuilder with other methods like String.Concat, which do the same thing internally. Any test you see online which doesn't include StringBuilder pre-allocation in its comparisons is wrong.
If you can't make any kind of guess about the size, you're probably writing a utility function which should have its own optional argument for controlling pre-allocation.
Perhaps your question is in this sense:
If you want to use: $python myscript.py
You don't need that line at all. The system will call python and then python interpreter will run your script.
But if you intend to use: $./myscript.py
Calling it directly like a normal program or bash script, you need write that line to specify to the system which program use to run it, (and also make it executable with chmod 755
)
This is bug in Android Studio. Usually you get error: Unsupported major.minor version 52.0
WORKAROUND: If you have installed Android N, change Android rendering version with older one and the problem will disappear.
SOLUTION: Install Android SDK Tools 25.1.3 (tools) or higher
You cannot.
According to the XML Schema specification, a boolean is true
or false
. True
is not valid:
3.2.2.1 Lexical representation An instance of a datatype that is defined as ·boolean· can have the following legal literals {true, false, 1, 0}. 3.2.2.2 Canonical representation The canonical representation for boolean is the set of literals {true, false}.
If the tool you are using truly validates against the XML Schema standard, then you cannot convince it to accept True for a boolean.
You can actually try this yourself, that should help you get a feel for how this works.
Open a two windows (tabs) in management studio, each of them will have it's own connection to sql.
Now you can begin a transaction in one window, do some stuff like insert/update/delete, but not yet commit. then in the other window you can see how the database looks from outside the transaction. Depending on the isolation level, the table may be locked until the first window is committed, or you might (not) see what the other transaction has done so far, etc.
Play around with the different isolation levels and no lock hint to see how they affect the results.
Also see what happens when you throw an error in the transaction.
It's very important to understand how all this stuff works or you will be stumped by what sql does, many a time.
Have fun! GJ.
My problem was, that Visual Studio somehow automatically lowercased *ngFor
to *ngfor
on copy&paste.
I was getting the same error in Visual Studio 2017 and to fix it just added #define _CRT_SECURE_NO_WARNINGS
after #include "pch.h"
#include "pch.h"
#define _CRT_SECURE_NO_WARNINGS
....
We can use the following regex explained with the help of sed system command. The similar regex can be used in other languages and platforms.
Add the text into some file say test
manjeet-laptop:Desktop manjeet$ cat test
"The dog has a long tail, and it is RED!"
We can use the following regex to replace all white spaces with single space
manjeet-laptop:Desktop manjeet$ sed 's/ \{1,\}/ /g' test
"The dog has a long tail, and it is RED!"
Hope this serves the purpose
It sounds like something like the below will suit your needs:
With Sheets("Sheet1")
.Rows( X & ":" & .Rows.Count).Delete
End With
Where X is a variable that = the row number ( 415 )
To flatten w/o recursion (as you have asked for), you can use a stack. Naturally you can put this into a function of it's own like array_flatten
. The following is a version that works w/o keys:.
function array_flatten(array $array)
{
$flat = array(); // initialize return array
$stack = array_values($array); // initialize stack
while($stack) // process stack until done
{
$value = array_shift($stack);
if (is_array($value)) // a value to further process
{
array_unshift($stack, ...$value);
}
else // a value to take
{
$flat[] = $value;
}
}
return $flat;
}
Elements are processed in their order. Because subelements will be moved on top of the stack, they will be processed next.
It's possible to take keys into account as well, however, you'll need a different strategy to handle the stack. That's needed because you need to deal with possible duplicate keys in the sub-arrays. A similar answer in a related question: PHP Walk through multidimensional array while preserving keys
I'm not specifically sure, but I I had tested this in the past: The RecurisiveIterator
does use recursion, so it depends on what you really need. Should be possible to create a recursive iterator based on stacks as well:
foreach(new FlatRecursiveArrayIterator($array) as $key => $value)
{
echo "** ($key) $value\n";
}
I didn't make it so far, to implement the stack based on RecursiveIterator
which I think is a nice idea.
I believe the original question said:
a character belongs to a list/array of invalid characters
and not:
belongs to a null-terminated string
which, if it did, then strchr
would indeed be the most suitable answer. If, however, there is no null termination to an array of chars or if the chars are in a list structure, then you will need to either create a null-terminated string and use strchr
or manually iterate over the elements in the collection, checking each in turn. If the collection is small, then a linear search will be fine. A large collection may need a more suitable structure to improve the search times - a sorted array or a balanced binary tree for example.
Pick whatever works best for you situation.
panel.setStyle("-fx-background-color: #FFFFFF;");
I had this issue after upgrading to .NET Framework 4.7.2. I found out that Nuget package for System.Net.Http is no longer recommended. Here are workarounds:
In your apache conf folder, open the httpd file and look for 8080 port. Change 8080 to any port you like. I believe you will find 8080 on two places. Restart your server to see changes.
myFunction(
contextParamers : {
param1: any,
param2: string
param3: string
}){
contextParamers.param1 = contextParamers.param1+ 'canChange';
//contextParamers.param4 = "CannotChange";
var contextParamers2 : any = contextParamers;// lost the typescript on the new object of type any
contextParamers2.param4 = 'canChange';
return contextParamers2;
}
Initially go to your home and press Ctrl + H it will show you hidden files now look for .bashrc
file, open it with any text editor then place below lines at the end of file.
export ANDROID_HOME=/home/varun/Android/Sdk
export PATH=$PATH:/home/varun/Android/Sdk/tools
export PATH=$PATH:/home/varun/Android/Sdk/platform-tools
Please change /home/varun/Android/Sdk
path to your SDK path.
Do the same for tools and platform-tools.
After this save .bashrc
file and close it.
Now you are ready to use ADB commands on terminal.
@Manuel was part way there. You can add the compiler option as well, like this:
If you have CMake 3.1.0+, this becomes even easier:
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app PRIVATE Threads::Threads)
If you are using CMake 2.8.12+, you can simplify this to:
find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
target_compile_options(my_app PUBLIC "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()
Older CMake versions may require:
find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
set_property(TARGET my_app PROPERTY COMPILE_OPTIONS "-pthread")
set_property(TARGET my_app PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()
If you want to use one of the first two methods with CMake 3.1+, you will need set(THREADS_PREFER_PTHREAD_FLAG ON)
there too.
im not really that good at C , but i believe this code should get you complete single line till the end...
#include<stdio.h>
int main()
{
char line[1024];
FILE *f=fopen("filename.txt","r");
fscanf(*f,"%[^\n]",line);
printf("%s",line);
}
There is the semicolon missing (;) after the "50%"
but you should also notice that the percentage of your div is connected to the div that contains it.
for instance:
<div id="wrapper">
<div class="container">
adsf
</div>
</div>
#wrapper {
height:100px;
}
.container
{
width:80%;
height:50%;
background-color:#eee;
}
here the height of your .container will be 50px. it will be 50% of the 100px from the wrapper div.
if you have:
adsf
#wrapper {
height:400px;
}
.container
{
width:80%;
height:50%;
background-color:#eee;
}
then you .container will be 200px. 50% of the wrapper.
So you may want to look at the divs "wrapping" your ".container"...
Same issue i was getting , but When we open our eclipse software then automatically we can see eclipse version and workspace location like these pic below
var startDate = moment(startDateVal, "DD.MM.YYYY");//Date format
var endDate = moment(endDateVal, "DD.MM.YYYY");
var isAfter = moment(startDate).isAfter(endDate);
if (isAfter) {
window.showErrorMessage("Error Message");
$(elements.endDate).focus();
return false;
}
I have the same problem. I changed the mac. And when I downloaded the Xcode certificate, I received an error message: "The error is that the security profile does not include the certificate signature."
1) Go to https://developer.apple.com/account/ios/profile/limited/edit Select the project => edit => Certificates => Select All => Create => Download
2) In Xcode: Project file => Signing (Debug) => Provisioning profile => Import profile => Select file with 1
First thing first, button()
is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:
$("#filter").click(function(){
alert('clicked!');
});
Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func)
which execute the callback once the DOM is ready.
Usage:
$(function(){
$("#filter").click(function(){
alert('clicked!');
});
});
So even if the order is this it will work:
$(function(){
$("#filter").click(function(){
alert('clicked!');
});
});
<input type="button" id="filter" name="filter" value="Filter" />
The main article in the Angular2 documentation on this subject is :
https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child
It covers the following:
Pass data from parent to child with input binding
Intercept input property changes with a setter
Intercept input property changes with ngOnChanges
Parent listens for child event
Parent interacts with child via a local variable
Parent calls a ViewChild
Parent and children communicate via a service
Step-1: Your Model class
public class RechargeMobileViewModel
{
public string CustomerFullName { get; set; }
public string TelecomSubscriber { get; set; }
public int TotalAmount { get; set; }
public string MobileNumber { get; set; }
public int Month { get; set; }
public List<SelectListItem> getAllDaysList { get; set; }
// Define the list which you have to show in Drop down List
public List<SelectListItem> getAllWeekDaysList()
{
List<SelectListItem> myList = new List<SelectListItem>();
var data = new[]{
new SelectListItem{ Value="1",Text="Monday"},
new SelectListItem{ Value="2",Text="Tuesday"},
new SelectListItem{ Value="3",Text="Wednesday"},
new SelectListItem{ Value="4",Text="Thrusday"},
new SelectListItem{ Value="5",Text="Friday"},
new SelectListItem{ Value="6",Text="Saturday"},
new SelectListItem{ Value="7",Text="Sunday"},
};
myList = data.ToList();
return myList;
}
}
Step-2: Call this method to fill Drop down in your controller Action
namespace MvcVariousApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
RechargeMobileViewModel objModel = new RechargeMobileViewModel();
objModel.getAllDaysList = objModel.getAllWeekDaysList();
return View(objModel);
}
}
}
Step-3: Fill your Drop-Down List of View as follows
@model MvcVariousApplication.Models.RechargeMobileViewModel
@{
ViewBag.Title = "Contact";
}
@Html.LabelFor(model=> model.CustomerFullName)
@Html.TextBoxFor(model => model.CustomerFullName)
@Html.LabelFor(model => model.MobileNumber)
@Html.TextBoxFor(model => model.MobileNumber)
@Html.LabelFor(model => model.TelecomSubscriber)
@Html.TextBoxFor(model => model.TelecomSubscriber)
@Html.LabelFor(model => model.TotalAmount)
@Html.TextBoxFor(model => model.TotalAmount)
@Html.LabelFor(model => model.Month)
@Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")
I have used this option always:
ArrayList<Dog> clonedList = new ArrayList<Dog>(name_of_arraylist_that_you_need_to_Clone);
I have been trying to achieve this by using 1 row single entry but I ended that Invoke command did not worked successfully because it is killing the process immediately after starting despite it can work if you are entering the session and waiting enough before exiting.
The only working way I could find, for example, to run a command with arguments and space on the remote machine HFVMACHINE1 (running Windows 7) is the following:
([WMICLASS]"\\HFVMACHINE1\ROOT\CIMV2:win32_process").Create('c:\Program Files (x86)\Thinware\vBackup\vBackup.exe -v HFSVR12-WWW')
Try this, replace ? with your schema name
select TABLE_NAME from INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA =?
AND TABLE_TYPE = 'BASE TABLE'
Perhaps a little off topic, just be informed that these kind of messages can also be seen when you are debugging your code with a breakpoint inside an async function like setTimeout
like below:
[Violation] 'setTimeout' handler took 43129ms
That number (43129ms) depends on how long you stop in your async function
To install a specific python package version whether it is the first time, an upgrade or a downgrade use:
pip install --force-reinstall MySQL_python==1.2.4
MySQL_python version 1.2.2 is not available so I used a different version. To view all available package versions from an index exclude the version:
pip install MySQL_python==
The main issue is that you haven't supplied the first grep with any input. You will need to reorder your command something like
grep "word1" logs | grep "word2"
If you want to count the occurences, then put a '-c' on the second grep.
Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.
As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:
var clone = _.clone(data, true);
data[1].values.d = 'x';
_.isEqual(data, clone) === false
_.isEqual(data, clone) === true
I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.
Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).
You may have milestones set up and your job won't run until the previous job is complete.
Sample Html code
<div id="temp">
F1 <input type="text" value="111"/><br/>
F2 <input type="text" value="222"/><br/>
F3 <input type="text" value="333"/><br/>
Type <select>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<input type="button" value="Go" onclick="getVal()">
</div>
Javascript
function getVal()
{
var test = document.getElementById("temp").getElementsByTagName("input");
alert("Number of Input Elements "+test.length);
for(var i=0;i<test.length;i++)
{
if(test[i].type=="text")
{
alert(test[i].value);
}
}
test = document.getElementById("temp").getElementsByTagName("select");
alert("Select box "+test[0].options[test[0].selectedIndex].text);
}
By providing different tag names we can get all the values from the div.
Starting with 1.6.4, Arduino IDE can be used to program and upload the NodeMCU board by installing the ESP8266 third-party platform package (refer https://github.com/esp8266/Arduino):
To install additional ESP8266WiFi library:
After above steps, you should compile the sketch normally.
You could override your object's ToString() method:
public override string ToString ()
{
return string.Format ("{0},{1},{2}", this.number, this.id, this.whatever);
}
It allows servlets to have multiple servlet mappings:
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/bill</url-pattern>
</servlet-mapping>
It allows filters to be mapped on the particular servlet:
<filter-mapping>
<filter-name>Filter1</filter-name>
<servlet-name>Servlet1</servlet-name>
</filter-mapping>
Your proposal would support neither of them. Note that the web.xml
is read and parsed only once during application's startup, not on every HTTP request as you seem to think.
Since Servlet 3.0, there's the @WebServlet
annotation which minimizes this boilerplate:
@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {
don't have to use grep either
an example:
sed -n '/searchwords/{s/^\(.\{12\}\).*/\1/g;p}' file
Try xcorr
, it's a built-in function in MATLAB for cross-correlation:
c = xcorr(A_1, A_2);
However, note that it requires the Signal Processing Toolbox installed. If not, you can look into the corrcoef
command instead.
int i = 25;
NSString *myString = [NSString stringWithFormat:@"%d",i];
This is one of many ways.
To make it easier for yourself you could also create an actionfilterattribute
public class AllowJsonGetAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
var jsonResult = filterContext.Result as JsonResult;
if (jsonResult == null)
throw new ArgumentException("Action does not return a JsonResult,
attribute AllowJsonGet is not allowed");
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
base.OnResultExecuting(filterContext);
}
}
and use it on your action
[AllowJsonGet]
public JsonResult MyAjaxAction()
{
return Json("this is my test");
}
Use word boundaries:
/\b($word)\b/i
Or if you're searching for "S.P.E.C.T.R.E." like in Sinan Ünür's example:
/(?:\W|^)(\Q$word\E)(?:\W|$)/i
Broadcast receivers receive events of a certain type. I don't think you can invoke them by class name.
First, your IntentFilter must contain an event.
static final String SOME_ACTION = "com.yourcompany.yourapp.SOME_ACTION";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);
Second, when you send a broadcast, use this same action:
Intent i = new Intent(SOME_ACTION);
sendBroadcast(i);
Third, do you really need MyIntentService to be inline? Static? [EDIT] I discovered that MyIntentSerivce MUST be static if it is inline.
Fourth, is your service declared in the AndroidManifest.xml?
This is good and efficient approach as per time complexity prospect. Once it will get a true condition , it will not check any other after this. In multiple If , it will check each and condition.
<c:choose>
<c:when test="${condtion1}">
do something condtion1
</c:when>
<c:when test="${condtion2}">
do something condtion2
</c:when>
......
......
......
.......
<c:when test="${condtionN}">
do something condtionn N
</c:when>
<c:otherwise>
do this w
</c:otherwise>
</c:choose>
If you're using Bash, you can also do the following if, let's say, you want to remove the directory /home/wrong/dir/
from your PATH
variable:
PATH=`echo $PATH | sed -e 's/:\/home\/wrong\/dir\/$//'`
There is no API to post photo to instagram using API , But there is a simple way is that install google extension " User Agent " it will covert your browser to android mobile chrome version . Here is the extension link https://chrome.google.com/webstore/detail/user-agent-switcher/clddifkhlkcojbojppdojfeeikdkgiae?utm_source=chrome-ntp-icon
just click on extension icon and choose chrome for android and open Instagram.com
At any stage of maven build life cycle, all the previous goals are performed.
Ex: mvn install will invoke mvn validate, mvn compile, mvn test, mvn package etc.
I believe you want to use CHARINDEX
. You can read about it here.
It's not a direct answer to the question but you could just use the OR-operator
( grep "#SystemMaxUse=" journald.conf > /dev/null && sed -i 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf ) || echo "This file has been edited. You'll need to do it manually."
SQL - Structured Query Language. It is declarative computer language aimed at querying relational databases.
MySQL is a relational database - a piece of software optimized for data storage and retrieval. There are many such databases - Oracle, Microsoft SQL Server, SQLite and many others are examples of such.
This is one of the few places that I disagree with the convention enough to go against it. TBH, I HATE that the definition of an enum and the instance of it can have the same name. I postfix all of my Enums with "Enum" specifically because it makes it clear what the context of it is in any given usage. IMO it makes the code much more readable.
public enum PersonTypesEnum {
smart,
sad,
funny,
angry
}
public class Person {
public PersonTypesEnum PersonType {get; set;}
}
Nobody will ever confuse what is the enum and what is the instance of it.
First you need to use Dispatcher.Invoke
to change the UI from another thread and to do that from another class, you can use events.
Then you can register to that event(s) in the main class and Dispatch the changes to the UI and in the calculation class you throw the event when you want to notify the UI:
class MainWindow : Window
{
private void startCalc()
{
//your code
CalcClass calc = new CalcClass();
calc.ProgressUpdate += (s, e) => {
Dispatcher.Invoke((Action)delegate() { /* update UI */ });
};
Thread calcthread = new Thread(new ParameterizedThreadStart(calc.testMethod));
calcthread.Start(input);
}
}
class CalcClass
{
public event EventHandler ProgressUpdate;
public void testMethod(object input)
{
//part 1
if(ProgressUpdate != null)
ProgressUpdate(this, new YourEventArgs(status));
//part 2
}
}
UPDATE:
As it seems this is still an often visited question and answer I want to update this answer with how I would do it now (with .NET 4.5) - this is a little longer as I will show some different possibilities:
class MainWindow : Window
{
Task calcTask = null;
void buttonStartCalc_Clicked(object sender, EventArgs e) { StartCalc(); } // #1
async void buttonDoCalc_Clicked(object sender, EventArgs e) // #2
{
await CalcAsync(); // #2
}
void StartCalc()
{
var calc = PrepareCalc();
calcTask = Task.Run(() => calc.TestMethod(input)); // #3
}
Task CalcAsync()
{
var calc = PrepareCalc();
return Task.Run(() => calc.TestMethod(input)); // #4
}
CalcClass PrepareCalc()
{
//your code
var calc = new CalcClass();
calc.ProgressUpdate += (s, e) => Dispatcher.Invoke((Action)delegate()
{
// update UI
});
return calc;
}
}
class CalcClass
{
public event EventHandler<EventArgs<YourStatus>> ProgressUpdate; // #5
public TestMethod(InputValues input)
{
//part 1
ProgressUpdate.Raise(this, status); // #6 - status is of type YourStatus
//part 2
}
}
static class EventExtensions
{
public static void Raise<T>(this EventHandler<EventArgs<T>> theEvent,
object sender, T args)
{
if (theEvent != null)
theEvent(sender, new EventArgs<T>(args));
}
}
@1) How to start the "synchronous" calculations and run them in the background
@2) How to start it "asynchronous" and "await it": Here the calculation is executed and completed before the method returns, but because of the async
/await
the UI is not blocked (BTW: such event handlers are the only valid usages of async void
as the event handler must return void
- use async Task
in all other cases)
@3) Instead of a new Thread
we now use a Task
. To later be able to check its (successfull) completion we save it in the global calcTask
member. In the background this also starts a new thread and runs the action there, but it is much easier to handle and has some other benefits.
@4) Here we also start the action, but this time we return the task, so the "async event handler" can "await it". We could also create async Task CalcAsync()
and then await Task.Run(() => calc.TestMethod(input)).ConfigureAwait(false);
(FYI: the ConfigureAwait(false)
is to avoid deadlocks, you should read up on this if you use async
/await
as it would be to much to explain here) which would result in the same workflow, but as the Task.Run
is the only "awaitable operation" and is the last one we can simply return the task and save one context switch, which saves some execution time.
@5) Here I now use a "strongly typed generic event" so we can pass and receive our "status object" easily
@6) Here I use the extension defined below, which (aside from ease of use) solve the possible race condition in the old example. There it could have happened that the event got null
after the if
-check, but before the call if the event handler was removed in another thread at just that moment. This can't happen here, as the extensions gets a "copy" of the event delegate and in the same situation the handler is still registered inside the Raise
method.
You don't need to ALTER
any table. Just use the following queries, prior to the actual SELECT
query that you want to use the wildcard:
set names `utf8`;
SET COLLATION_CONNECTION=utf8_general_ci;
SET CHARACTER_SET_CLIENT=utf8;
SET CHARACTER_SET_RESULTS=utf8;
You can simply call filter
multiple times:
query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \
filter(User.lastname.like(searchVar2))
If the stashed files need to merge with the current version so use the previous ways using diff. Otherwise you might use git pop
for unstashing them, git add fileWantToKeep
for staging your file, and do a git stash save --keep-index
, for stashing everything except what is on stage.
Remember that the difference of this way with the previous ones is that it "pops" the file from stash. The previous answers keep it git checkout stash@{0} -- <filename>
so it goes according to your needs.
Try this to convert string to uri
String mystring="Hello"
Uri myUri = Uri.parse(mystring);
Uri to String
Uri uri;
String uri_to_string;
uri_to_string= uri.toString();
Don't forget to also install the iOS cert for your Apple Developer Account.
Using the Safari browser (not Chrome, Firefox or Opera) on Mac OS X 10.9 (Mavericks) visit https://registry.npmjs.org
Click the Show certificate button and then check the checkbox labelled Always trust. Then click Continue and enter your password if required.
Curl should now work with that URL correctly.
CURSORS are an option here, but generally frowned upon as they often do not make best use of the query engine. Consider investigating 'SET Based Queries' to see if you can achieve what it is you want to do without using a CURSOR.
var dictionary = {
"data":[{"id":"0","name":"ABC"}, {"id":"1","name":"DEF"}],
"images": [ {"id":"0","name":"PQR"},"id":"1","name":"xyz"}]
};
for (var key in dictionary) {
var getKey = dictionary[key];
getKey.forEach(function(item) {
console.log(item.name + ' ' + item.id);
});
}
Export all the needed variables and then use a perl onliner
TEXT=$(echo "$TEXT"|perl -wpne 's#\${?(\w+)}?# $ENV{$1} // $& #ge;')
This will replace all the ENV variables present in TEXT with actual values. Quotes are also preserved :)
No.
The content-type should be whatever it is known to be, if you know it. application/octet-stream
is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.
You can combine the use of Content-Disposition
with other content-types, such as image/png
or even text/html
to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html
but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).
RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline
to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename
part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.
Hence:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"
Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"
Means "This is a PNG image. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: inline; filename="picture.png"
Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".
Of those browsers that recognise inline
some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).
What are iml files in Android Studio project?
A Google search on iml file
turns up:
IML is a module file created by IntelliJ IDEA, an IDE used to develop Java applications. It stores information about a development module, which may be a Java, Plugin, Android, or Maven component; saves the module paths, dependencies, and other settings.
(from this page)
why not to use gradle scripts to integrate with external modules that you add to your project.
You do "use gradle scripts to integrate with external modules", or your own modules.
However, Gradle is not IntelliJ IDEA's native project model — that is separate, held in .iml
files and the metadata in .idea/
directories. In Android Studio, that stuff is largely generated out of the Gradle build scripts, which is why you are sometimes prompted to "sync project with Gradle files" when you change files like build.gradle
. This is also why you don't bother putting .iml
files or .idea/
in version control, as their contents will be regenerated.
If I have a team that work in different IDE's like Eclipse and AS how to make project IDE agnostic?
To a large extent, you can't.
You are welcome to have an Android project that uses the Eclipse-style directory structure (e.g., resources and manifest in the project root directory). You can teach Gradle, via build.gradle
, how to find files in that structure. However, other metadata (compileSdkVersion
, dependencies, etc.) will not be nearly as easily replicated.
Other alternatives include:
Move everybody over to another build system, like Maven, that is equally integrated (or not, depending upon your perspective) to both Eclipse and Android Studio
Hope that Andmore takes off soon, so that perhaps you can have an Eclipse IDE that can build Android projects from Gradle build scripts
Have everyone use one IDE
Note: This assumes that you will declare constants for row and column indexes named COLUMN_HEADING_ROW
, FIRST_COL
, and LAST_COL
, and that _xlSheet
is the name of the ExcelSheet
(using Microsoft.Interop.Excel
)
First, define the range:
var columnHeadingsRange = _xlSheet.Range[
_xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
_xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];
Then, set the background color of that range:
columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;
Finally, set the font color:
columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;
And here's the code combined:
var columnHeadingsRange = _xlSheet.Range[
_xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
_xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];
columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;
columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;
To get a prompt with the color depending on the last command’s exit status, you could use this:
PS1='%(?.%F{green}.%F{red})%n@%m:%~%# %f'
Just add this line to your ~/.zshrc
.
The documentation lists possible placeholders.
A more simple way I came across while searching for this answer as well;
string date = DateTime.Now.ToString("yyyyMMdd", System.Globalization.CultureInfo.GetCultureInfo("en-US"));
Generally when I want to create a JSON or YAML string, I start out by building the Perl data structure, and then running a simple conversion on it. You could put a UI in front of the Perl data structure generation, e.g. a web form.
Converting a structure to JSON is very straightforward:
use strict;
use warnings;
use JSON::Any;
my $data = { arbitrary structure in here };
my $json_handler = JSON::Any->new(utf8=>1);
my $json_string = $json_handler->objToJson($data);
I know, I am tooooo late to post an answer, but hoping that it might help someone. Plus, I just solved this issue I had with my tests. This is what I had in my test:
My test class
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "path-to-context" })
@Transactional
public class MyIntegrationTest
Context xml
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
I still had the problem that, the database was not being cleaned up automatically.
Issue was resolved when I added following property to BasicDataSource
<property name="defaultAutoCommit" value="false" />
Hope it helps.
Jenkins determines the success/failure of a step by the return value of the step. For the case of a shell, it should be the return of the last value. For both Windows CMD and (POSIX) Bash shells, you should be able to set the return value manually by using exit 0
as the last command.
Buttons can be added to frozen rows as images. Assigning a function within the attached script to the button makes it possible to run the function. The comment which says you can not is of course a very old comment, possibly things have changed now.
@@
should do it.
This is an elaboration on @Jeff M's and my comments.
When you do this:
a, b = c, d
It works with tuple packing and unpacking. You can separate the packing and unpacking steps:
_ = c, d
a, b = _
The first line creates a tuple called _
which has two elements, the first with the value of c
and the second with the value of d
. The second line unpacks the _
tuple into the variables a
and b
. This breaks down your one huge line:
a, b, c, d, e, f, g, h, i, j = True, True, True, True, True, False, True, True, True, True
Into two smaller lines:
_ = True, True, True, True, True, False, True, True, True, True
a, b, c, d, e, f, g, h, i, j = _
It will give you the exact same result as the first line (including the same exception if you add values or variables to one part but forget to update the other). However, in this specific case, yan's answer is perhaps the best.
If you have a list of values, you can still unpack them. You just have to convert it to a tuple first. For example, the following will assign a value between 0 and 9 to each of a
through j
, respectively:
a, b, c, d, e, f, g, h, i, j = tuple(range(10))
EDIT: Neat trick to assign all of them as true except element 5 (variable f
):
a, b, c, d, e, f, g, h, i, j = tuple(x != 5 for x in range(10))
Set the form property to open in maximized state.
this.WindowState = FormWindowState.Maximized;
Chr(10)
is the Line Feed character and Chr(13)
is the Carriage Return character.
You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.
Historically, Line Feed would move down a line but not return to column 1:
This
is
a
test.
Similarly Carriage Return would return to column 1 but not move down a line:
This
is
a
test.
Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.
This is a good example where you want to get count of Pincode which stored in the last of address field
SELECT DISTINCT
RIGHT (address, 6),
count(*) AS count
FROM
datafile
WHERE
address IS NOT NULL
GROUP BY
RIGHT (address, 6)
You could just use a for loop and there is no need to add an extra if
inside the for
body:
for (int i = 0; i < Model.Results.Count - 1; i++) {
var item = Model.Results[i];
}
The -1
in the for
condition takes care of skipping the last item.
From what I know, the correct syntax is:
function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
document.getElementById(tabName).style.backgroundImage = "url('buttons/" + imagePrefix + ".png')";
}
So basically, getElementById(tabName).backgroundImage
and split the string like:
"cssInHere('and" + javascriptOutHere + "/cssAgain')";
Another answer is to force xargs
to process the commands in batches. For instance to delete
the files 100
at a time, cd
into the directory and run this:
echo *.pdf | xargs -n 100 rm
str.replace(new RegExp(".","gm")," ")
This can also happen when you're trying to load a DLL and that in turn needs another DLL which cannot be not found.
Take a look at SimpleDateFormat
:
java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
System.out.println(sdf.format(sq));
Starting with .NET 4.0 you can use ExpressionVisitor
to find properties:
class ExprVisitor : ExpressionVisitor {
public bool IsFound { get; private set; }
public string MemberName { get; private set; }
public Type MemberType { get; private set; }
protected override Expression VisitMember(MemberExpression node) {
if (!IsFound && node.Member.MemberType == MemberTypes.Property) {
IsFound = true;
MemberName = node.Member.Name;
MemberType = node.Type;
}
return base.VisitMember(node);
}
}
Here is how you use this visitor:
var visitor = new ExprVisitor();
visitor.Visit(expr);
if (visitor.IsFound) {
Console.WriteLine("First property in the expression tree: Name={0}, Type={1}", visitor.MemberName, visitor.MemberType.FullName);
} else {
Console.WriteLine("No properties found.");
}
based on this
I modified the original to this:
^(?:(?:(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec))(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:(?:0?2|(?:Feb))(\/|-|\.)(?:29)\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
Using fs-extra package is quite simple:
Sync:
const fs = require('fs-extra')
const packageObj = fs.readJsonSync('./package.json')
console.log(packageObj.version)
Async:
const fs = require('fs-extra')
const packageObj = await fs.readJson('./package.json')
console.log(packageObj.version)
I don't know how good that solution is but it is definitely THE EASY ONE i just used in my app and it is working fine
you load the image like that
public void loadImage (){
Picasso picasso = Picasso.get();
picasso.setIndicatorsEnabled(true);
picasso.load(quiz.getImageUrl()).into(quizImage);
}
You can get the bimap
like that
Bitmap bitmap = Picasso.get().load(quiz.getImageUrl()).get();
Now covert that Bitmap
into a JPG
file and store in the in the cache, below is complete code for getting the bimap and caching it
Thread thread = new Thread() {
public void run() {
File file = new File(getCacheDir() + "/" +member.getMemberId() + ".jpg");
try {
Bitmap bitmap = Picasso.get().load(uri).get();
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100,new FileOutputStream(file));
fOut.flush();
fOut.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
})
the get()
method of Piccasso
need to be called on separate thread , i am saving that image also on that same thread.
Once the image is saved you can get all the files like that
List<File> files = new LinkedList<>(Arrays.asList(context.getExternalCacheDir().listFiles()));
now you can find the file you are looking for like below
for(File file : files){
if(file.getName().equals("fileyouarelookingfor" + ".jpg")){ // you need the name of the file, for example you are storing user image and the his image name is same as his id , you can call getId() on user to get the file name
Picasso.get() // if file found then load it
.load(file)
.into(mThumbnailImage);
return; // return
}
// fetch it over the internet here because the file is not found
}
Those who installed node.js via the package manager can just run:
sudo apt-get purge nodejs
Optionally if you have installed it by adding the official NodeSource repository as stated in Installing Node.js via package manager, do:
sudo rm /etc/apt/sources.list.d/nodesource.list
If you want to clean up npm cache as well:
rm -rf ~/.npm
It is bad practice to try to remove things manually, as it can mess up the package manager, and the operating system itself. This answer is completely safe to follow
Other examples here are difficult to remember. At its simplest:
date -r 1305712800
xml:space="preserve"
has to work for all compliant XML parsers.
However, note that in HTML the line break is just whitespace and NOT a line break (this is represented with the <br />
(X)HTML tag, maybe this is the problem which you are facing.
You can also add
and/or
to insert CR/LF characters.
Something like this if you're into regex, not sure of the exact syntax for the replace tho!
MyNumberAsString.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
Open below file C:\xampp\htdocs\project\common\config\params-local.php
Before your code:
<?php
return [
];
after your code:
<?php
yii::setAlias('@path1', 'localhost/foodbam/backend/web');
return [
];
If you're using Express, you can use this:
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({key:"value"}));
or just this
res.json({key:"value"});
NOTE: This answer was given before iOS 5 was released.
Get the json-framework and do this:
#import "SBJsonWriter.h"
...
SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
NSString *jsonString = [jsonWriter stringWithObject:myDictionary];
[jsonWriter release];
myDictionary
will be your dictionary.
Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo
.
A new version of OSX or XCode was installed and Apple wants you to agree to their Terms and Conditions. So just launch Xcode and "Agree" to them.
Instead of flex: 1 0 auto
just use flex: 1
main, aside, article {_x000D_
margin: 10px;_x000D_
border: solid 1px #000;_x000D_
border-bottom: 0;_x000D_
height: 50px;_x000D_
}_x000D_
main {_x000D_
display: flex;_x000D_
}_x000D_
aside {_x000D_
flex: 0 0 200px;_x000D_
}_x000D_
article {_x000D_
flex: 1;_x000D_
}
_x000D_
<main>_x000D_
<aside>x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x </aside>_x000D_
<article>don't let flex item overflow container.... y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y </article>_x000D_
</main>
_x000D_
The JDK path might change when you update JAVA. For Mac you should go to the following path to check the JAVA version installed.
/Library/Java/JavaVirtualMachines/
Next, say JDK version that you find is jdk1.8.0_151.jdk
, the path to home directory within it is the JDK home path.
In my case it was :
/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home
You can configure it by going to File -> Project Structure -> SDKs
.
Using Javascript's es6 or node, you can do the following:
var [a,b,c,d] = [0,1,2,3]
And if you want to easily print multiple variables in a single line, just do this:
console.log(a, b, c, d)
0 1 2 3
This is similar to @alex gray 's answer here, but this example is in Javascript instead of CoffeeScript.
Note that this uses Javascript's array destructuring assignment
pip install -U pip
pip install -U cython
Suppose there are multiple static synchronized methods (m1, m2, m3, m4) in a class, and suppose one thread is accessing m1, then no other thread at the same time can access any other static synchronized methods.
or even more better, you can put this code in a class file
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Forms;
internal class OpenFolderDialog : IDisposable {
/// <summary>
/// Gets/sets folder in which dialog will be open.
/// </summary>
public string InitialFolder { get; set; }
/// <summary>
/// Gets/sets directory in which dialog will be open if there is no recent directory available.
/// </summary>
public string DefaultFolder { get; set; }
/// <summary>
/// Gets selected folder.
/// </summary>
public string Folder { get; private set; }
internal DialogResult ShowDialog(IWin32Window owner) {
if (Environment.OSVersion.Version.Major >= 6) {
return ShowVistaDialog(owner);
} else {
return ShowLegacyDialog(owner);
}
}
private DialogResult ShowVistaDialog(IWin32Window owner) {
var frm = (NativeMethods.IFileDialog)(new NativeMethods.FileOpenDialogRCW());
uint options;
frm.GetOptions(out options);
options |= NativeMethods.FOS_PICKFOLDERS | NativeMethods.FOS_FORCEFILESYSTEM | NativeMethods.FOS_NOVALIDATE | NativeMethods.FOS_NOTESTFILECREATE | NativeMethods.FOS_DONTADDTORECENT;
frm.SetOptions(options);
if (this.InitialFolder != null) {
NativeMethods.IShellItem directoryShellItem;
var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem
if (NativeMethods.SHCreateItemFromParsingName(this.InitialFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {
frm.SetFolder(directoryShellItem);
}
}
if (this.DefaultFolder != null) {
NativeMethods.IShellItem directoryShellItem;
var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem
if (NativeMethods.SHCreateItemFromParsingName(this.DefaultFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {
frm.SetDefaultFolder(directoryShellItem);
}
}
if (frm.Show(owner.Handle) == NativeMethods.S_OK) {
NativeMethods.IShellItem shellItem;
if (frm.GetResult(out shellItem) == NativeMethods.S_OK) {
IntPtr pszString;
if (shellItem.GetDisplayName(NativeMethods.SIGDN_FILESYSPATH, out pszString) == NativeMethods.S_OK) {
if (pszString != IntPtr.Zero) {
try {
this.Folder = Marshal.PtrToStringAuto(pszString);
return DialogResult.OK;
} finally {
Marshal.FreeCoTaskMem(pszString);
}
}
}
}
}
return DialogResult.Cancel;
}
private DialogResult ShowLegacyDialog(IWin32Window owner) {
using (var frm = new SaveFileDialog()) {
frm.CheckFileExists = false;
frm.CheckPathExists = true;
frm.CreatePrompt = false;
frm.Filter = "|" + Guid.Empty.ToString();
frm.FileName = "any";
if (this.InitialFolder != null) { frm.InitialDirectory = this.InitialFolder; }
frm.OverwritePrompt = false;
frm.Title = "Select Folder";
frm.ValidateNames = false;
if (frm.ShowDialog(owner) == DialogResult.OK) {
this.Folder = Path.GetDirectoryName(frm.FileName);
return DialogResult.OK;
} else {
return DialogResult.Cancel;
}
}
}
public void Dispose() { } //just to have possibility of Using statement.
}
internal static class NativeMethods {
#region Constants
public const uint FOS_PICKFOLDERS = 0x00000020;
public const uint FOS_FORCEFILESYSTEM = 0x00000040;
public const uint FOS_NOVALIDATE = 0x00000100;
public const uint FOS_NOTESTFILECREATE = 0x00010000;
public const uint FOS_DONTADDTORECENT = 0x02000000;
public const uint S_OK = 0x0000;
public const uint SIGDN_FILESYSPATH = 0x80058000;
#endregion
#region COM
[ComImport, ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FCanCreate), Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
internal class FileOpenDialogRCW { }
[ComImport(), Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IFileDialog {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
[PreserveSig()]
uint Show([In, Optional] IntPtr hwndOwner); //IModalWindow
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileTypes([In] uint cFileTypes, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr rgFilterSpec);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileTypeIndex([In] uint iFileType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetFileTypeIndex(out uint piFileType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Advise([In, MarshalAs(UnmanagedType.Interface)] IntPtr pfde, out uint pdwCookie);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Unadvise([In] uint dwCookie);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetOptions([In] uint fos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetOptions(out uint fos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, uint fdap);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Close([MarshalAs(UnmanagedType.Error)] uint hr);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetClientGuid([In] ref Guid guid);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint ClearClientData();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter);
}
[ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IShellItem {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint BindToHandler([In] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IntPtr ppvOut);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetDisplayName([In] uint sigdnName, out IntPtr ppszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetAttributes([In] uint sfgaoMask, out uint psfgaoAttribs);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Compare([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder);
}
#endregion
[DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);
}
And use it like this
using (var frm = new OpenFolderDialog()) {
if (frm.ShowDialog(this)== DialogResult.OK) {
MessageBox.Show(this, frm.Folder);
}
}
Workaround simple and quick. Upload file/photo on cloud (from outside the emulator) and download with browser on the emulator.
You probably just need to see the ASCII
and EXTENDED ASCII
character sets. As far as I know any of these are allowed in a char
/varchar
field.
If you use nchar
/nvarchar
then it's pretty much any character in any unicode set in the world.
Another option is
if (myString?.trim()) {
...
}
Thanks for commenting, I understand what you mean but I didn't want to check old values. I just wanted to get a pointer to that view.
Looking at someone else's code I have just found a workaround, you can access the root of a layout using LayoutInflater
.
The code is the following, where this
is an Activity:
final LayoutInflater factory = getLayoutInflater();
final View textEntryView = factory.inflate(R.layout.landmark_new_dialog, null);
landmarkEditNameView = (EditText) textEntryView.findViewById(R.id.landmark_name_dialog_edit);
You need to get the inflater for this
context, access the root view through the inflate method and finally call findViewById
on the root view of the layout.
Hope this is useful for someone! Bye
SUBSTR (documentation):
SELECT SUBSTR(OrderNo, 1, 2) As NewColumnName from shipment
When selected, it's like any other column. You should give it a name (with As
keyword), and you can selected other columns in the same statement:
SELECT SUBSTR(OrderNo, 1, 2) As NewColumnName, column2, ... from shipment
As @DSM points out, you can do this more directly using the vectorised string methods:
df['Date'].str[-4:].astype(int)
Or using extract (assuming there is only one set of digits of length 4 somewhere in each string):
df['Date'].str.extract('(?P<year>\d{4})').astype(int)
An alternative slightly more flexible way, might be to use apply
(or equivalently map
) to do this:
df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
# converts the last 4 characters of the string to an integer
The lambda function, is taking the input from the Date
and converting it to a year.
You could (and perhaps should) write this more verbosely as:
def convert_to_year(date_in_some_format):
date_as_string = str(date_in_some_format) # cast to string
year_as_string = date_in_some_format[-4:] # last four characters
return int(year_as_string)
df['Date'] = df['Date'].apply(convert_to_year)
Perhaps 'Year' is a better name for this column...
There may be a simpler option, but you can use VLOOKUP to check if a value appears in a list (and VLOOKUP is a powerful formula to get to grips with anyway).
So for A1, you can set a conditional format using the following formula:
=NOT(ISNA(VLOOKUP(A1,$B:$B,1,FALSE)))
Copy and Paste Special > Formats to copy that conditional format to the other cells in column A.
What the above formula is doing:
Check this Spring 3 WebMVC - Optional Path Variables. It shows an article of making an extension to AntPathMatcher to enable optional path variables and might be of help. All credits to Sebastian Herold for posting the article.
Just wanted to add that if you want to debug stuff, you should compile with debug information before you debug, otherwise the debugger won't work. So, in g++ you need to do g++ -g source.cpp
. The -g
flag means that the compiler will insert debugging information into your executable, so that you can run gdb on it.
TextView t2 = (TextView) findViewById(R.id.textviewidname);
t2.setMovementMethod(LinkMovementMethod.getInstance());
and
<string name="google_stackoverflow"><a href="https://stackoverflow.com/questions/9852184/android-textview-hyperlink?rq=1">google stack overflow</a></string>
The link is, "Android: textview hyperlink"
and the tag is, "google stack overflow"
Define the first code block in your java and the second code block in your strings.xml file. Also, be sure to reference the id of the textView from your page layout in your java.
Sub Check_DT_ForNull()
Debug.Print WS_FE.ListObjects.Item(1).DataBodyRange.Item(1).Value
If Not WS_FE.ListObjects.Item(1).DataBodyRange.Item(1).Value = "" Then
Debug.Print WS_FE.ListObjects.Item(1).DataBodyRange.Rows.Count
End If
End Sub
This checks the first row value in the DataBodyRange for Null and Count the total rows This worked for me as I downloaded my datatable from server It had not data's but table was created with blanks and Rows.Count was not 0 but blank rows.
2016 Update
Use the Sharing Debugger to figure out what your problems are.
Make sure you're following the Facebook Sharing Best Practices.
Make sure you're using the Open Graph Markup correctly.
Original Answer
I agree with what has already been said here, but per documentation on the Facebook developer site, you might want to use the following meta tags.
<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />
If you are not able to accomplish your goal with meta tags and you need a URL embedded version, see @Lelis718's answer below.
You can use it by easy way, through store
method in your controller
like the below
{{Form::open(['route' => 'user.store', 'files' => true])}}
{{Form::label('user_photo', 'User Photo',['class' => 'control-label'])}}
{{Form::file('user_photo')}}
{{Form::submit('Save', ['class' => 'btn btn-success'])}}
{{Form::close()}}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function store(Request $request)
{
// get current time and append the upload file extension to it,
// then put that name to $photoName variable.
$photoName = time().'.'.$request->user_photo->getClientOriginalExtension();
/*
talk the select file and move it public directory and make avatars
folder if doesn't exsit then give it that unique name.
*/
$request->user_photo->move(public_path('avatars'), $photoName);
}
}
That’s it. Now you can save the $photoName
to the database as a user_photo
field value. You can use asset(‘avatars’)
function in your view and access the photos.
I had a similar problem, but I was getting an error message
cannot execute binary file
I discovered that the filename contained non-ASCII characters. When those were fixed, the script ran fine with ./script.sh
.
if you want enable any extension then you have to install an extension first, extension maybe enabled but not installed so, taking example of bcmath
1.yum search php-bcmath
2.then ensure php version in which u want to install this extension
3.u will get output like after yum search command>>
yum search php-bcmath** Loaded plugins: fastestmirror, universal-hooks Loading mirror speeds from cached hostfile
EA4: 66.71.244.18
cpanel-addons-production-feed: 66.71.244.18
base: mirror.nodesdirect.com
epel: mirror.coastal.edu
extras: www.gtlib.gatech.edu
nux-dextop: mirror.li.nux.ro
updates: mirror.jaleco.com
**============================================================== N/S matched: php-bcmath ===============================================================
ea-php54-php-bcmath.x86_64 : A module for PHP applications for using the bcmath library
ea-php55-php-bcmath.x86_64 : A module for PHP applications for using the bcmath library
ea-php56-php-bcmath.x86_64 : A module for PHP applications for using the bcmath library
ea-php70-php-bcmath.x86_64 : A module for PHP applications for using the bcmath library
ea-php71-php-bcmath.x86_64 : A module for PHP applications for using the bcmath library
ea-php72-php-bcmath.x86_64 : A module for PHP applications for using the bcmath library
then use >yum install ea-php72-php-bcmath.x86_64
5.this bcmath extension for php7.2
6.I wanna install for php71 then the command will be like **yum install ea-php71-php-bcmath.x86_64** or yum install php71-bcmath.
7.u can install any extension from above steps.
For PHP (I know the question is Java, but Google brought me here), you can use stream wrappers and file_exists
$bucket = "MyBucket";
$key = "MyKey";
$s3 = Aws\S3\S3Client->factory([...]);
$s3->registerStreamWrapper();
$keyExists = file_exists("s3://$bucket/$key");
{{-- dynamic select/dropdown --}}
<select class="form-control m-bot15" name="district_id"
onchange ="location = this.options[this.selectedIndex].value;"
>
<option value="">--Select--</option>
<option value="?">All</option>
@foreach($location as $district)
<option value="?district_id={{ $district->district_id }}" >
{{ $district->district }}
</option>
@endforeach
</select>
Seeing that it appears you are running using the SQL syntax, try with the correct wild card.
SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4;
Assuming the field in timestamp firestore is called timestamp, in dart you could call the toDate() method on the returned map.
// Map from firestore
// Using flutterfire package hence the returned data()
Map<String, dynamic> data = documentSnapshot.data();
DateTime _timestamp = data['timestamp'].toDate();
Or if you want a ripple pulse effect, you could use this:
http://jsfiddle.net/Fy8vD/3041/
.gps_ring {
border: 2px solid #fff;
-webkit-border-radius: 50%;
height: 18px;
width: 18px;
position: absolute;
left:20px;
top:214px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.0;
}
.gps_ring:before {
content:"";
display:block;
border: 2px solid #fff;
-webkit-border-radius: 50%;
height: 30px;
width: 30px;
position: absolute;
left:-8px;
top:-8px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
-webkit-animation-delay: 0.1s;
opacity: 0.0;
}
.gps_ring:after {
content:"";
display:block;
border:2px solid #fff;
-webkit-border-radius: 50%;
height: 50px;
width: 50px;
position: absolute;
left:-18px;
top:-18px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
-webkit-animation-delay: 0.2s;
opacity: 0.0;
}
@-webkit-keyframes pulsate {
0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
50% {opacity: 1.0;}
100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}
Reflection.
using System.Reflection;
Vendor vendor = new Vendor();
object tag = vendor.Tag;
Type tagt = tag.GetType();
FieldInfo field = tagt.GetField("test");
string value = field.GetValue(tag);
Use the power wisely. Don't forget error checking. :)
typeof
is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetType
is called on an object at runtime. In both cases the result is an object of the type System.Type
containing meta-information on a type.
Example where compile-time and run-time types are equal
string s = "hello";
Type t1 = typeof(string);
Type t2 = s.GetType();
t1 == t2 ==> true
Example where compile-time and run-time types are different
object obj = "hello";
Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType(); // ==> string!
t1 == t2 ==> false
i.e., the compile time type (static type) of the variable obj
is not the same as the runtime type of the object referenced by obj
.
Testing types
If, however, you only want to know whether mycontrol
is a TextBox
then you can simply test
if (mycontrol is TextBox)
Note that this is not completely equivalent to
if (mycontrol.GetType() == typeof(TextBox))
because mycontrol
could have a type that is derived from TextBox
. In that case the first comparison yields true
and the second false
! The first and easier variant is OK in most cases, since a control derived from TextBox
inherits everything that TextBox
has, probably adds more to it and is therefore assignment compatible to TextBox
.
public class MySpecializedTextBox : TextBox
{
}
MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox) ==> true
if (specialized.GetType() == typeof(TextBox)) ==> false
Casting
If you have the following test followed by a cast and T is nullable ...
if (obj is T) {
T x = (T)obj; // The casting tests, whether obj is T again!
...
}
... you can change it to ...
T x = obj as T;
if (x != null) {
...
}
Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as
operator followed by a test for null
is more performing.
Starting with C# 7.0 you can simplify the code by using pattern matching:
if (obj is T t) {
// t is a variable of type T having a non-null value.
...
}
Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:
if (o is int? ni) ===> does NOT compile!
This is because either the value is null
or it is an int
. This works for int? o
as well as for object o = new Nullable<int>(x);
:
if (o is int i) ===> OK!
I like it, because it eliminates the need to access the Nullable<T>.Value
property.
In my case, I removed "image" from the little dropdown on the right. It showed up just fine after that. That's because it will be searching the log for the keyword in that searchbox, so if it doesn't find any matches, it returns blank
Complementing the @NoahD's answer
To have a greater precision you can cast to decimal:
(decimal)100/863
//0.1158748551564310544611819235
Or:
Decimal.Divide(100, 863)
//0.1158748551564310544611819235
Double are represented allocating 64 bits while decimal uses 128
(double)100/863
//0.11587485515643106
For more details about the floating point representation in binary and its precision take a look at this article from Jon Skeet where he talks about floats
and doubles
and this one where he talks about decimals
.
There are 3 ways of doing this:
404.php
code..htaccess
file.Complete tutorial given at http://bornvirtual.com/wordpress/redirect-404-error-in-wordpress/906/
To run the python file on mac.
Click on the install in the preferences to install packages.
Search for package "script" and click on install
Now open the python file(with .py extension ) you want to run and press 'control + r ' (^ + r)
css href link is incorrect. Use relative path instead:
<link href="../css/loginstyle.css" rel="stylesheet" type="text/css">
To add to some of the other answers, note that:
keyup
and keydown
differ from keypress
String.fromCharCode()
to get the actual digit from keyup
, you'll need to first normalize the keyCode
.Below is a self-documenting example that determines if the key is numeric, along with which number it is (example uses the range
function from lodash
).
const isKeypad = range(96, 106).includes(keyCode);
const normalizedKeyCode = isKeypad ? keyCode - 48 : keyCode;
const isDigit = range(48, 58).includes(normalizedKeyCode);
const digit = String.fromCharCode(normalizedKeyCode);
You're asking it to parse the JSON text something
(not "something"
). That's invalid JSON, strings must be in double quotes.
If you want an equivalent to your first example:
var s = '"something"';
var result = JSON.parse(s);
Numbers calculated by a computer through a deterministic process, cannot, by definition, be random.
If you want a genuine random numbers, the randomness comes from atmospheric noise or radioactive decay.
You can try for example RANDOM.ORG (it reduces performance)
Note that you can also determine in pure js in what browser you script is beeing executed through : window.navigator.userAgent
However, that's not a recommended way as it's configurable in the browser settings. More info available there: https://developer.mozilla.org/fr/docs/DOM/window.navigator.userAgent
this solution also considered the case that url is empty and disabled(gray) the empty link.
$(function() {_x000D_
changeAnchor();_x000D_
});_x000D_
_x000D_
function changeAnchor() {_x000D_
$("a[name$='aWebsiteUrl']").each(function() { // you can write your selector here_x000D_
$(this).css("background", "none");_x000D_
$(this).css("font-weight", "normal");_x000D_
_x000D_
var url = $(this).attr('href').trim();_x000D_
if (url == " " || url == "") { //disable empty link_x000D_
$(this).attr("class", "disabled");_x000D_
$(this).attr("href", "javascript:void(0)");_x000D_
} else {_x000D_
$(this).attr("target", "_blank");// HERE set the non-empty links, open in new window_x000D_
}_x000D_
});_x000D_
}
_x000D_
a.disabled {_x000D_
text-decoration: none;_x000D_
pointer-events: none;_x000D_
cursor: default;_x000D_
color: grey;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
<a name="aWebsiteUrl" href="http://www.baidu.com" class='#'>[website]</a>_x000D_
<a name="aWebsiteUrl" href=" " class='#'>[website]</a>_x000D_
<a name="aWebsiteUrl" href="http://www.alibaba.com" class='#'>[website]</a>_x000D_
<a name="aWebsiteUrl" href="http://www.qq.com" class='#'>[website]</a>
_x000D_
DELIMITER $$
DROP FUNCTION IF EXISTS `split_name`$$
CREATE FUNCTION split_name (p_fullname TEXT, p_part INTEGER)
RETURNS TEXT
READS SQL DATA
BEGIN
DECLARE v_words INT UNSIGNED;
DECLARE v_name TEXT;
SET p_fullname=RTRIM(LTRIM(p_fullname));
SET v_words=(SELECT SUM(LENGTH(p_fullname) - LENGTH(REPLACE(p_fullname, ' ', ''))+1));
IF v_words=1 THEN
IF p_part=1 THEN
SET v_name=p_fullname;
ELSEIF p_part=2 THEN
SET v_name=NULL;
ELSEIF p_part=3 THEN
SET v_name=NULL;
ELSE
SET v_name=NULL;
END IF;
ELSEIF v_words=2 THEN
IF p_part=1 THEN
SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
ELSEIF p_part=2 THEN
SET v_name=SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1);
ELSEIF p_part=3 THEN
SET v_name=NULL;
ELSE
SET v_name=NULL;
END IF;
ELSEIF v_words=3 THEN
IF p_part=1 THEN
SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
ELSEIF p_part=2 THEN
SET p_fullname=SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1);
SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
ELSEIF p_part=3 THEN
SET p_fullname=REVERSE (SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
SET p_fullname=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
SET v_name=REVERSE(p_fullname);
ELSE
SET v_name=NULL;
END IF;
ELSEIF v_words>3 THEN
IF p_part=1 THEN
SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
ELSEIF p_part=2 THEN
SET p_fullname=REVERSE(SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
SET p_fullname=SUBSTRING(p_fullname, LOCATE(' ', p_fullname,SUBSTRING_INDEX(p_fullname,' ',1)+1) + 1);
SET v_name=REVERSE(p_fullname);
ELSEIF p_part=3 THEN
SET p_fullname=REVERSE (SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
SET p_fullname=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
SET v_name=REVERSE(p_fullname);
ELSE
SET v_name=NULL;
END IF;
ELSE
SET v_name=NULL;
END IF;
RETURN v_name;
END;
SELECT split_name('Md. Obaidul Haque Sarker',1) AS first_name,
split_name('Md. Obaidul Haque Sarker',2) AS middle_name,
split_name('Md. Obaidul Haque Sarker',3) AS last_name
You can just use a Hook
add_filter( 'nav_menu_submenu_css_class', 'some_function', 10, 3 );
function some_function( $classes, $args, $depth ){
foreach ( $classes as $key => $class ) {
if ( $class == 'sub-menu' ) {
$classes[ $key ] = 'my-sub-menu';
}
}
return $classes;
}
where
$classes(array) - The CSS classes that are applied to the menu <ul> element.
$args(stdClass) - An object of wp_nav_menu() arguments.
$depth(int) - Depth of menu item. Used for padding.
Solution for me.
Step: 1
<a onclick="exportAsExcel()">Export to excel</a>
Step: 2
I'm using file-saver lib.
Read more: https://www.npmjs.com/package/file-saver
npm i file-saver
Step: 3
let FileSaver = require('file-saver'); // path to file-saver
function exportAsExcel() {
let dataBlob = '...kAAAAFAAIcmtzaGVldHMvc2hlZXQxLnhtbFBLBQYAAAAACQAJAD8CAADdGAAAAAA='; // If have ; You should be split get blob data only
this.downloadFile(dataBlob);
}
function downloadFile(blobContent){
let blob = new Blob([base64toBlob(blobContent, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')], {});
FileSaver.saveAs(blob, 'report.xlsx');
}
function base64toBlob(base64Data, contentType) {
contentType = contentType || '';
let sliceSize = 1024;
let byteCharacters = atob(base64Data);
let bytesLength = byteCharacters.length;
let slicesCount = Math.ceil(bytesLength / sliceSize);
let byteArrays = new Array(slicesCount);
for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
let begin = sliceIndex * sliceSize;
let end = Math.min(begin + sliceSize, bytesLength);
let bytes = new Array(end - begin);
for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
Work for me. ^^
Well, here is my "answer". It uses the fact that String.Split can be told hold many items it should split to (which I found lacking in the other answers):
string theString = "Some Very Large String Here";
var array = theString.Split(new [] { ' ' }, 2); // return at most 2 parts
// note: be sure to check it's not an empty array
string firstElem = array[0];
// note: be sure to check length first
string restOfArray = array[1];
This is very similar to the Substring
method, just by a different means.
Try this with SQL join statements
CREATE PROCEDURE [dbo].[deleteItem]
@ItemId int = 0
AS
Begin
DECLARE @cnt int;
SET NOCOUNT ON
SELECT @cnt =COUNT(ttm.Id)
from ItemTransaction itr INNER JOIN ItemUnitMeasurement ium
ON itr.Id = ium.ItemTransactionId INNER JOIN ItemMaster im
ON itr.ItemId = im.Id INNER JOIN TransactionTypeMaster ttm
ON itr.TransactionTypeMasterId = ttm.Id
where im.Id = @ItemId
if(@cnt = 1)
Begin
DECLARE @transactionType varchar(255);
DECLARE @mesurementAmount float;
DECLARE @itemTransactionId int;
DECLARE @itemUnitMeasurementId int;
SELECT @transactionType = ttm.TransactionType, @mesurementAmount = ium.Amount, @itemTransactionId = itr.Id, @itemUnitMeasurementId = ium.Id
from ItemTransaction itr INNER JOIN ItemUnitMeasurement ium
ON itr.Id = ium.ItemTransactionId INNER JOIN TransactionTypeMaster ttm
ON itr.TransactionTypeMasterId = ttm.Id
where itr.ItemId = @ItemId
if(@transactionType = 'Close' and @mesurementAmount = 0)
Begin
delete from ItemUnitMeasurement where Id = @itemUnitMeasurementId;
End
else
Begin
delete from ItemTransaction where Id = @itemTransactionId;
End
End
else
Begin
delete from ItemMaster where Id = @ItemId;
End
END
you must changes in $watch ....
function MyController($scope) {_x000D_
$scope.form = {_x000D_
name: 'my name',_x000D_
}_x000D_
_x000D_
$scope.$watch('form.name', function(newVal, oldVal){_x000D_
console.log('changed');_x000D_
_x000D_
});_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>_x000D_
<div ng-app>_x000D_
<div ng-controller="MyController">_x000D_
<label>Name:</label> <input type="text" ng-model="form.name"/>_x000D_
_x000D_
<pre>_x000D_
{{ form }}_x000D_
</pre>_x000D_
</div>_x000D_
</div>
_x000D_
Simple answer
If you are behind a proxy server, please set the proxy for curl. The curl is not able to connect to server so it shows wrong version number. Set proxy by opening subl ~/.curlrc or use any other text editor. Then add the following line to file: proxy= proxyserver:proxyport For e.g. proxy = 10.8.0.1:8080
If you are not behind a proxy, make sure that the curlrc file does not contain the proxy settings.
Both
SuperClass.__init__(self, x)
or
super(SubClass,self).__init__( x )
will work (I prefer the 2nd one, as it adheres more to the DRY principle).
See here: http://docs.python.org/reference/datamodel.html#basic-customization
if it is a RSA key
openssl rsa -pubout -in my_rsa_key.pem
if you need it in a format for openssh , please see Use RSA private key to generate public key?
Note that public key is generated from the private key and ssh uses the identity file (private key file) to generate and send public key to server and un-encrypt the encrypted token from the server via the private key in identity file.
This is a very old question, but it still happens a lot and there is no truly comprehensive answer here.
I have had this problem more times than I want to admit. It can be caused by a wide variety of issues that mostly all have to do with your project structure not matching what's expected. Here's a list of all the problems I've had:
Importing from Eclipse to Android Studio does not always work smoothly, especially with older versions of Android Studio. Make sure you're using the correct directory tree. It should look like this for a moderately mature app:
AppName/ // AppName is your app's name, obviously
.gradle/ // This is a compiler created directory. You should normally leave it alone
.idea/ // Ditto
build/ // This too
gradle/ // And this
app/
build/
libs/
src/
androidTest/ // Tests based on the Android instrumentation runner should go here
main/
java/
fully/ // Typically com
qualified/ // the domain name. Longer package
// names may have deeper folder trees
AppName/ // All your java files go here
res/
drawable-*/ // One of these for each resolution you support
layout/ // All of your general layouts
menu/ // All of your menu layouts
values/ // All of your resource xml files
xml/ // PreferenceScreen layouts go here
AndroidManifest.xml
debug/
test/ // Pure jUnit tests should go here
.gitignore
app.iml
build.gradle // This is the gradle file you should be making most changes to
proguard-rules.pro
.gitignore
build.gradle // This gradle file should mostly be left alone
gradle.properties
gradlew
local.properties
AppName.iml
settings.gradle
It may not look like this in your IDE. There is a drop-down above the file tree that displays your files in different ways, and it defaults on my system to one called Android that breaks your files out into their different types. It's easier to fix this kind of problem from the one called Project, and even easier directly from your OS's file system, because Android Studio collapses folders that only contain another folder onto a single line.
Especially if you ever change the name of your app, you need to make sure that the source tree main/java/com/domain/AppName is updated. Also make sure that the package tag in your AndroidManifest.xml is correct.
If there are errors in either your Gradle files or your AndroidManifest.xml, this will prevent Android Studio from properly building your resource files. Gradle files can be broken by upgrading Android Studio sometimes, especially from the pre-1.0 versions. Sometimes this is because it stops supporting older versions of the Gradle plugin, so you need to update your version numbers. It can sometimes be hard to find what the current versions are. As of today, 7/17/15, my apps are compiling fine with com.android.tools.build:gradle:1.2.3
. This is in the dependencies block in the outermost gradle file,
If your AndroidManifest references a non-existent drawable or string resource or activity, it will break and cause this error. Sometimes if anything references a nonexistent drawable or string resource you will get this error.
If you have a file in your resources that is corrupted, or an invalid xml file, you will get this error.
In my experience, sometimes Android Studio just hiccups for no reason, and you need to restart it and/or your PC. I don't know why, but sometimes it works.
If you have two xml resources with the same name, in directories that do not override each other, you can have this problem. For instance, you can have the same name in drawable-mhdpi and drawable-xhdpi because they override each other depending on the target device, but if you have the same name in layout and in menu, it will cause a problem. Rename or delete one of the files.
If only some resources are having this problem, those resources are most likely in the wrong directory.
In one case I had to completely reinstall Android Studio. I don't know what was wrong, but it worked.
In one case I moved my entire project to a different directory and re-imported it as a new project. I don't know what was wrong, but it worked.
Xml files with reserved words for names can cause this problem. Rename or delete them.
There are a few ways your Gradle file can end up referencing a version of the build-tools that you do not have installed. Correct this by changing Gradle or downloading the appropriate build-tools.
Finally, after you've fixed whatever is wrong, you need to clean your Gradle project. You do this by going to the Build menu at the top and selecting Clean Project.
No, plain old batch files use REM
as a comment. ECHO
is the command that prints something on the screen.
To "comment out" sections of the file you could use GOTO
. An example of all these commands/techniques:
REM it starts here the section below can be safely erased once the file is customised
ECHO Hey you need to edit this file before running it! Check the instructions inside
ECHO Now press ctrl-c to interrupt execution or enter to continue
PAUSE
REM erase the section above once you have customised the file
python executed1.py
ECHO Skipping some stuff now
GOTO End
python skipped1.py
python skipped2.py
:END
python executed2.py
What can I say? batch files are a relic of times long gone, they're clunky and ugly.
You can read more on this website.
EDIT: modified the example a bit to have it contain the elements you are apparently looking for.
Your code should like this:
<span id="replies">8</span>
var currentValue = $("#replies").text();
var newValue = parseInt(parseFloat(currentValue)) + 1;
$("replies").text(newValue);
Can you change the if condition to this:
if (!is.na(comments[l])) print(comments[l]);
You can only check for NA values with is.na().
Looking into this, it seems like the LibMan approach works best for my needs with adding Bootstrap. I like it because it is now built into Visual Studio 2017(15.8 or later) and has its own dialog boxes.
Update 6/11/2020: bootstrap 4.1.3 is now added by default with VS-2019.5 (Thanks to Harald S. Hanssen for noticing.)
The default method VS adds to projects uses Bower but it looks like it is on the way out. In the header of Microsofts bower page they write:
Following a couple links lead to Use LibMan with ASP.NET Core in Visual Studio where it shows how libs can be added using a built-in Dialog:
In Solution Explorer, right-click the project folder in which the files should be added. Choose Add > Client-Side Library. The Add Client-Side Library dialog appears: [source: Scott Addie 2018]
Then for bootstrap just (1) select the unpkg, (2) type in "bootstrap@.." (3) Install. After this, you would just want to verify all the includes in the _Layout.cshtml or other places are correct. They should be something like href="~/lib/bootstrap/dist/js/bootstrap...")
I tried solving this problem for hours after I haven't used Android Studio some time and wasn't aware of the updates.
It is important that google()
is the first item that stands in repositories
like this:
allprojects {
repositories {
google()
jcenter()
mavenCentral()
}
}
Somehow google()
was the second item after jcenter()
, so everything was messed up and didn't work. Maybe this helps someone.
HttpClient is a new API that came with 4.3, it has updated API's with support for progress events, json deserialization by default, Interceptors and many other great features. See more here https://angular.io/guide/http
Http is the older API and will eventually be deprecated.
Since their usage is very similar for basic tasks I would advise using HttpClient since it is the more modern and easy to use alternative.
You can pass different type of message using with
return redirect()->back()->with('error', 'Your current account is inactive ')->with('error2','please check');
To show message
@if(session('error'))
<div class="alert alert-danger" role="alert">
<p> {{session('error')}} </p>
<p> {{session('error2')}}</p>
</div>
@endif
I believe John's answer is correct. For instance, I'm using my laptop through a wifi service run by a conference centre -- I'm pretty sure that there is no way for javascript running within my browser to discover the IP address being used by the service provider. On the other hand, it may be possible to address a suitable external resource from javascript. You can write your own if your own by making an ajax call to a server which can take the IP address from the HTTP headers and return it, or try googling "find my ip". The cleanest solution is probably to capture the information before the page is served and insert it in the html returned to the user. See How to get a viewer's IP address with python? for info on how to capture the information if you are serving the page with python.
I find Jack Aidley's suggested answer a useful one.
I wanted to throw out another option. Suppose you have a series with many small numbers, and you want to ensure the axis labels write out the full decimal point (e.g. 5e-05 -> 0.0005), then:
NotFancy <- function(l) {
l <- format(l, scientific = FALSE)
parse(text=l)
}
ggplot(data = data.frame(x = 1:100,
y = seq(from=0.00005,to = 0.0000000000001,length.out=100) + runif(n=100,-0.0000005,0.0000005)),
aes(x=x, y=y)) +
geom_point() +
scale_y_continuous(labels=NotFancy)
Use SequenceEqual
to check for sequence equality because Equals
method checks for reference equality.
var a = ints1.SequenceEqual(ints2);
Or if you don't care about elements order use Enumerable.All
method:
var a = ints1.All(ints2.Contains);
The second version also requires another check for Count
because it would return true even if ints2
contains more elements than ints1
. So the more correct version would be something like this:
var a = ints1.All(ints2.Contains) && ints1.Count == ints2.Count;
In order to check inequality just reverse the result of All
method:
var a = !ints1.All(ints2.Contains)
How to Troubleshoot ORA-30926 Errors? (Doc ID 471956.1)
1) Identify the failing statement
alter session set events ‘30926 trace name errorstack level 3’;
or
alter system set events ‘30926 trace name errorstack off’;
and watch for .trc files in UDUMP when it occurs.
2) Having found the SQL statement, check if it is correct (perhaps using explain plan or tkprof to check the query execution plan) and analyze or compute statistics on the tables concerned if this has not recently been done. Rebuilding (or dropping/recreating) indexes may help too.
3.1) Is the SQL statement a MERGE? evaluate the data returned by the USING clause to ensure that there are no duplicate values in the join. Modify the merge statement to include a deterministic where clause
3.2) Is this an UPDATE statement via a view? If so, try populating the view result into a table and try updating the table directly.
3.3) Is there a trigger on the table? Try disabling it to see if it still fails.
3.4) Does the statement contain a non-mergeable view in an 'IN-Subquery'? This can result in duplicate rows being returned if the query has a "FOR UPDATE" clause. See Bug 2681037
3.5) Does the table have unused columns? Dropping these may prevent the error.
4) If modifying the SQL does not cure the error, the issue may be with the table, especially if there are chained rows. 4.1) Run the ‘ANALYZE TABLE VALIDATE STRUCTURE CASCADE’ statement on all tables used in the SQL to see if there are any corruptions in the table or its indexes. 4.2) Check for, and eliminate, any CHAINED or migrated ROWS on the table. There are ways to minimize this, such as the correct setting of PCTFREE. Use Note 122020.1 - Row Chaining and Migration 4.3) If the table is additionally Index Organized, see: Note 102932.1 - Monitoring Chained Rows on IOTs
Every function inside a class, and every class variable must take the self argument as pointed.
class mystuff:
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
def sum(self,a,b):
return a+b
print mystuff.average(9,18,27) # should raise error
print mystuff.sum(18,27) # should be ok
If class variables are involved:
class mystuff:
def setVariables(self,a,b):
self.x = a
self.y = b
return a+b
def mult(self):
return x * y # This line will raise an error
def sum(self):
return self.x + self.y
print mystuff.setVariables(9,18) # Setting mystuff.x and mystuff.y
print mystuff.mult() # should raise error
print mystuff.sum() # should be ok