I had this problem on Laravel Forge.
The issue was that I was using "Website Isolation" and logged in using SSH with the default "forge" user instead of with the isolated username.
This of course caused the issue as permissions were not correct when using the "forge" user for the website in question.
Using the correct isolated username to SSH into the server did the trick.
Perhaps this helps others in the same situation.
Create a new keypair: (go with the defaults)
ssh-keygen
Copy the public key to the server: (password for the last time)
ssh-copy-id [email protected]
From now on the server should recognize your key and not ask you for the password anymore:
ssh [email protected]
You need to make the object first, then use []
to set it.
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
UPDATE 2018:
If you're able to use ES6 and Babel, you can use this new feature:
{
[yourKeyVariable]: someValueArray,
}
There are pieces to this answer that helped me get what I needed (easy multi-line concatenation WITHOUT extra whitespace), but since none of the actual answers had it, I'm compiling them here:
str = 'this is a multi-line string'\
' using implicit concatenation'\
' to prevent spare \n\'s'
=> "this is a multi-line string using implicit concatenation to eliminate spare
\\n's"
As a bonus, here's a version using funny HEREDOC syntax (via this link):
p <<END_SQL.gsub(/\s+/, " ").strip
SELECT * FROM users
ORDER BY users.id DESC
END_SQL
# >> "SELECT * FROM users ORDER BY users.id DESC"
The latter would mostly be for situations that required more flexibility in the processing. I personally don't like it, it puts the processing in a weird place w.r.t. the string (i.e., in front of it, but using instance methods that usually come afterward), but it's there. Note that if you are indenting the last END_SQL
identifier (which is common, since this is probably inside a function or module), you will need to use the hyphenated syntax (that is, p <<-END_SQL
instead of p <<END_SQL
). Otherwise, the indenting whitespace causes the identifier to be interpreted as a continuation of the string.
This doesn't save much typing, but it looks nicer than using + signs, to me.
Also (I say in an edit, several years later), if you're using Ruby 2.3+, the operator <<~ is also available, which removes extra indentation from the final string. You should be able to remove the .gsub
invocation, in that case (although it might depend on both the starting indentation and your final needs).
EDIT: Adding one more:
p %{
SELECT * FROM users
ORDER BY users.id DESC
}.gsub(/\s+/, " ").strip
# >> "SELECT * FROM users ORDER BY users.id DESC"
You have to be careful, server responses in the range of 4xx and 5xx throw a WebException. You need to catch it, and then get status code from a WebException object:
try
{
wResp = (HttpWebResponse)wReq.GetResponse();
wRespStatusCode = wResp.StatusCode;
}
catch (WebException we)
{
wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
}
Here's a kludgy way to get the output from another powershell process:
start-process -wait -nonewwindow powershell 'ps | Export-Clixml out.xml'; import-clixml out.xml
It is today possible to configure Safari to access local files.
- By default Safari doesn't allow access to local files.
- To enable this option: First you need to enable the develop menu.
- Click on the Develop menu Select Disable Local File Restrictions.
Source: http://ccm.net/faq/36342-safari-how-to-enable-local-file-access
Java implicitly assumes a reference to the current object for methods called like this. So
// Test2.java
public class Test2 {
public void testMethod() {
testMethod2();
}
// ...
}
Is exactly the same as
// Test2.java
public class Test2 {
public void testMethod() {
this.testMethod2();
}
// ...
}
I prefer the second version to make more clear what you want to do.
@JustGoscha's answer is spot on, but that's a lot to type when I want access, so I added this to the bottom of my app.js. Then all I have to type is x = getSrv('$http')
to get the http service.
// @if DEBUG
function getSrv(name, element) {
element = element || '*[ng-app]';
return angular.element(element).injector().get(name);
}
// @endif
It adds it to the global scope but only in debug mode. I put it inside the @if DEBUG
so that I don't end up with it in the production code. I use this method to remove debug code from prouduction builds.
I am using EF Core with ASP.NET Core V2.2.6. @Richard Logwood's answer was great and it solved my problem, but I needed a different syntax.
So, For those using EF Core with ASP.NET Core V2.2.6 +...
instead of
Update-Database <Name of last good migration>
I had to use:
dotnet ef database update <Name of last good migration>
And instead of
Remove-Migration
I had to use:
dotnet ef migrations remove
For --help
i had to use :
dotnet ef migrations --help
Usage: dotnet ef migrations [options] [command]
Options:
-h|--help Show help information
-v|--verbose Show verbose output.
--no-color Don't colorize output.
--prefix-output Prefix output with level.
Commands:
add Adds a new migration.
list Lists available migrations.
remove Removes the last migration.
script Generates a SQL script from migrations.
Use "migrations [command] --help" for more information about a command.
This let me role back to the stage where my DB worked as expected, and start from beginning.
var array = [];
//length array now = 0
array[array.length] = 'hello';
//length array now = 1
// 0
//array = ['hello'];//length = 1
The --no-ff
option is useful when you want to have a clear notion of your feature branch. So even if in the meantime no commits were made, FF is possible - you still want sometimes to have each commit in the mainline correspond to one feature. So you treat a feature branch with a bunch of commits as a single unit, and merge them as a single unit. It is clear from your history when you do feature branch merging with --no-ff
.
If you do not care about such thing - you could probably get away with FF whenever it is possible. Thus you will have more svn-like feeling of workflow.
For example, the author of this article thinks that --no-ff
option should be default and his reasoning is close to that I outlined above:
Consider the situation where a series of minor commits on the "feature" branch collectively make up one new feature: If you just do "git merge feature_branch" without --no-ff
, "it is impossible to see from the Git history which of the commit objects together have implemented a feature—you would have to manually read all the log messages. Reverting a whole feature (i.e. a group of commits), is a true headache [if --no-ff
is not used], whereas it is easily done if the --no-ff
flag was used [because it's just one commit]."
Try using an a link element and click it with javascriipt
<a id="SimulateOpenLink" href="#" target="_blank" rel="noopener noreferrer"></a>
and the script
function openURL(url) {
document.getElementById("SimulateOpenLink").href = url
document.getElementById("SimulateOpenLink").click()
}
Use it like this
//do stuff
var id = 123123141;
openURL("/api/user/" + id + "/print") //this open webpage bypassing pop-up blocker
openURL("https://www.google.com") //Another link
If you specify CSS attributes for your body
element it should apply to anything within <body></body>
so long as you don't override them later in the stylesheet.
On Windows, I got this error when running under a non-administrator command prompt. When I ran this as administrator, the error went away.
For those of you that prefer a more concise, easier to read lambda coding style...
This example removes all non-alphanumeric and white space characters from a wide string. You can mix it up with any of the other ctype.h helper functions to remove complex-looking character-based tests.
(I'm not sure how these functions would handle CJK languages, so walk softly there.)
// Boring C loops: 'for(int i=0;i<str.size();i++)'
// Boring C++ eqivalent: 'for(iterator iter=c.begin; iter != c.end; ++iter)'
See if you don't find this easier to understand than noisy C/C++ for/iterator loops:
TSTRING label = _T("1. Replen & Move RPMV");
TSTRING newLabel = label;
set<TCHAR> badChars; // Use ispunct, isalpha, isdigit, et.al. (lambda version, with capture list parameter(s) example; handiest thing since sliced bread)
for_each(label.begin(), label.end(), [&badChars](TCHAR n){
if (!isalpha(n) && !isdigit(n))
badChars.insert(n);
});
for_each(badChars.begin(), badChars.end(), [&newLabel](TCHAR n){
newLabel.erase(std::remove(newLabel.begin(), newLabel.end(), n), newLabel.end());
});
newLabel results after running this code: "1ReplenMoveRPMV"
This is just academic, since it would clearly be more precise, concise and efficient to combine the 'if' logic from lambda0 (first for_each) into the single lambda1 (second for_each), if you have already established which characters are the "badChars".
function getEffectiveVotes($id)
According to the function header, there is only one parameter variable ($id
).
Thus, on line 27, the votes[]
array is undefined and out of scope. You need to add another
parameter value to the function header so that function getEffectiveVotes()
knows to expect two parameters. I'm rusty, but something like this would work.
function getEffectiveVotes($id, $votes)
I'm not saying this is how it should be done, but you might want to research how PHP passes its arrays and decide if you need to explicitly state to pass it by reference
function getEffectiveVotes($id &$votes) <---I forget, no time to look it up right now.
Lastly, call function getEffectiveVotes()
with both arguments wherever it is supposed to be called.
Cheers.
First we need to find a Button
:
Button mButton = (Button) findViewById(R.id.my_button);
After that, you must implement View.OnClickListener
and there you should find the TextView
and execute the method setText
:
mButton.setOnClickListener(new View.OnClickListener {
public void onClick(View v) {
final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
mTextView.setText("Some Text");
}
});
Here is a simple and backward compatible way to deliver ripple effect to raised buttons with the custom background.
Your layout should look like this
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/my_custom_background"
android:foreground="?android:attr/selectableItemBackground"/>
In Windows 10 I had to run the batch file as an administrator.
In Linux command Prompt, I would first stop all postgresql processes that are running by tying this command sudo /etc/init.d/postgresql restart
type the command bg to check if other postgresql processes are still running
then followed by dropdb dbname to drop the database
sudo /etc/init.d/postgresql restart
bg
dropdb dbname
This works for me on linux command prompt
This is how I solved
<a href="#" >
<button type="button" class="btn btn-info">Button Text</button>
</a>
You need to add some arguments. Also, instancing and opening can be put in one line:
fstream file("test.txt", fstream::in | fstream::out | fstream::trunc);
I had a the same error and solved it after moving initialization of formBuilder
from ngOnInit
to constructor.
This works too and you dont have to use join or anything:
DROP VIEW IF EXISTS yourview;
CREATE VIEW yourview AS
SELECT table1.column1,
table2.column2
FROM
table1, table2
WHERE table1.column1 = table2.column1;
String testString = "This is a sentence";
String[] parts = testString.split(" ");
String lastWord = parts[parts.length - 1];
System.out.println(lastWord); // "sentence"
For some projects it's easier to set your target to es6
in your tsconfig.json
.
{
"compilerOptions": {
"target": "es6",
...
You can also use :=
construct to assign and decide on action in one step. Consider following example:
# Example of setting default server and reporting it's status
server=$1
if [[ ${server:=localhost} =~ [a-z] ]] # 'localhost' assigned here to $server
then echo "server is localhost" # echo is triggered since letters were found in $server
else
echo "server was set" # numbers were passed
fi
If $1
is not empty, localhost
will be assigned to server
in the if
condition field, trigger match and report match result. In this way you can assign on the fly and trigger appropriate action.
It means you're trying to call something that isn't a function
const foo = 'string'
foo() // error
Your code should work just as you expect it to if you add @classmethod
decorators.
@classmethod
def setup_class(cls):
"Runs once per class"
@classmethod
def teardown_class(cls):
"Runs at end of class"
See http://pythontesting.net/framework/pytest/pytest-xunit-style-fixtures/
For this, and also for Xcode 6 and above make sure that the breakpoint state button is activated (the blue arrow-like button):
This won't really work at all. There is no date type in JSON. I would recommend to serialize to ISO8601 back and forth (for format agnostics and JS compat). Consider that you have to know which fields contain dates.
If you are just storing it for reference, you can store it as a string, but if you want to do a lookup, for example, to see if the IP address is in some table, you need a "canonical representation." Converting the entire thing to a (large) number is the right thing to do. IPv4 addresses can be stored as a long int (32 bits) but you need a 128 bit number to store an IPv6 address.
For example, all these strings are really the same IP address: 127.0.0.1, 127.000.000.001, ::1, 0:0:0:0:0:0:0:1
UserDict from the Python standard library is designed for this purpose.
Put the modal and javascript into the partial view. Then call the partial view in your page. This will handle form submission too.
Partial View
<div id="confirmDialog" class="modal fade" data-backdrop="false">
<div class="modal-dialog" data-backdrop="false">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Missing Service Order</h4>
</div>
<div class="modal-body">
<p>You have not entered a Service Order. Do you want to continue?</p>
</div>
<div class="modal-footer">
<input id="btnSubmit" type="submit" class="btn btn-primary"
value="Submit" href="javascript:"
onClick="document.getElementById('Coordinate').submit()" />
<button type="button" class="btn btn-default" data-
dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
Javascript
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#Coordinate").on('submit',
function (e) {
if ($("#ServiceOrder").val() == '') {
e.preventDefault();
$('#confirmDialog').modal('show');
}
});
});
</script>
Then just call your partial inside the form of your page.
Create.cshtml
@using (Html.BeginForm("Edit","Home",FormMethod.Post, new {id ="Coordinate"}))
{
//Form Code
@Html.Partial("ConfirmDialog")
}
Try this:
UPDATE business AS b
INNER JOIN business_geocode AS g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
b.mapy = g.longitude
WHERE (b.mapx = '' or b.mapx = 0) and
g.latitude > 0
Since you said the query yielded a syntax error, I created some tables that I could test it against and confirmed that there is no syntax error in my query:
mysql> create table business (business_id int unsigned primary key auto_increment, mapx varchar(255), mapy varchar(255)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)
mysql> create table business_geocode (business_geocode_id int unsigned primary key auto_increment, business_id int unsigned not null, latitude varchar(255) not null, longitude varchar(255) not null, foreign key (business_id) references business(business_id)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)
mysql> UPDATE business AS b
-> INNER JOIN business_geocode AS g ON b.business_id = g.business_id
-> SET b.mapx = g.latitude,
-> b.mapy = g.longitude
-> WHERE (b.mapx = '' or b.mapx = 0) and
-> g.latitude > 0;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0
See? No syntax error. I tested against MySQL 5.5.8.
There is a tool called fabric, this is a crash analytic tool, which will allow you to get crash reports , when application deployed live and during development. Adding this tool to your application was simple as well.. When your application crash that report of the crash can be viewed from your fabric.io dashboard . thw report was catched automatically.it won't ask user for permission. Whether he/she want to send the bug/crash report. And this is completely free... https://get.fabric.io/
You can write queries like this in SQL Server:
--each [0-9] matches a single digit, this would match 5xx
SELECT * FROM YourTable WHERE SomeField LIKE '5[0-9][0-9]'
In terms of speed: #1 and #4, but not by much in most instances.
You could write a benchmark to confirm, but I suspect you'll find #1 and #4 to be slightly faster because the iteration work is done in C instead of Perl, and no needless copying of the array elements occurs. ($_
is aliased to the element in #1, but #2 and #3 actually copy the scalars from the array.)
#5 might be similar.
In terms memory usage: They're all the same except for #5.
for (@a)
is special-cased to avoid flattening the array. The loop iterates over the indexes of the array.
In terms of readability: #1.
In terms of flexibility: #1/#4 and #5.
#2 does not support elements that are false. #2 and #3 are destructive.
#!/bin/bash
cd /opt/
sudo mkdir java
sudo tar -zxvf ~/Downloads/jdk-8u192-linux-x64.tar.gz
sudo ln -s jdk1.8.0_192 current
for file in /opt/java/current/bin/*
do
if [ -x $file ]
then
filename=`basename $file`
sudo update-alternatives --install /usr/bin/$filename $filename $file 20000
sudo update-alternatives --set $filename $file
#echo $file $filename
fi
done
In most cases you should allow the thread pool to handle this. If you post some code or give more details it might be easier to see if there is some reason the default behavior of the thread pool would not be best.
You can find more information on how this should work here: http://en.wikipedia.org/wiki/Thread_pool_pattern
content
doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.
Another problem with your code is "
inside a "
block. You should mix '
and "
(class='headingDetail'
).
If content
did support HTML you could end up in an infinite loop where content
is added inside content
.
Try the reges below
new Regex(@"^\d{4}").IsMatch("6") // false
new Regex(@"^\d{4}").IsMatch("68ab") // false
new Regex(@"^\d{4}").IsMatch("1111abcdefg")
new Regex(@"^\d+").IsMatch("6") // true (any length but at least one digit)
You need to tell it that you are using SSL:
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
In case you miss anything, here is working code:
String d_email = "[email protected]",
d_uname = "Name",
d_password = "urpassword",
d_host = "smtp.gmail.com",
d_port = "465",
m_to = "[email protected]",
m_subject = "Indoors Readable File: " + params[0].getName(),
m_text = "This message is from Indoor Positioning App. Required file(s) are attached.";
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", d_host);
props.put("mail.smtp.port", d_port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SMTPAuthenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
try {
msg.setSubject(m_subject);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
Transport transport = session.getTransport("smtps");
transport.connect(d_host, Integer.valueOf(d_port), d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (AddressException e) {
e.printStackTrace();
return false;
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
using, in the sense of
using (var foo = new Bar())
{
Baz();
}
Is actually shorthand for a try/finally block. It is equivalent to the code:
var foo = new Bar();
try
{
Baz();
}
finally
{
foo.Dispose();
}
You'll note, of course, that the first snippet is much more concise than the second and also that there are many kinds of things that you might want to do as cleanup even if an exception is thrown. Because of this, we've come up with a class that we call Scope that allows you to execute arbitrary code in the Dispose method. So, for example, if you had a property called IsWorking that you always wanted to set to false after trying to perform an operation, you'd do it like this:
using (new Scope(() => IsWorking = false))
{
IsWorking = true;
MundaneYetDangerousWork();
}
You can read more about our solution and how we derived it here.
For making alert just put below javascript code in footer.
<script>
$(document).ready(function(){
alert('Hi');
});
</script>
You need to also load jquery min file. Please insert this script in header.
<script type='text/javascript' src='https://code.jquery.com/jquery-1.12.0.min.js'></script>
Cocoa pods - reduce wait times to 10% ( on Mac OS ) :
1- type pod setup
in your project folder ( first you have to be in the project folder) from terminal in Mac OS.
2- CTRL+z
to stop after it creates master directory ( folder ) [you can see it in your cocoa pods folder location : ~/.cocoapods/repos]
Download .zip from
https://github.com/CocoaPods/Specs
master branch ( its 301 MB) , Extract it . It will take approx 5-10 mins
4.Copy the content to ~/.cocoapods/repos
( now here you only need to copy the contents inside the master folder , so make sure that master folder is created already with pod setup command )
5- once you copy it ( or I should say move , drag and drop as copying will take forever , as its very large ), you can then do pod install --no-repo-update
6- your pods in the pod file now will start installing
Here is a screenshot
In the .NET world AOP isn't too popular, so for DI a framework is your only real option, whether you write one yourself or use another framework.
If you used AOP you can inject when you compile your application, which is more common in Java.
There are many benefits to DI, such as reduced coupling so unit testing is easier, but how will you implement it? Do you want to use reflection to do it yourself?
To answer the original question:
HTMLDocument doc = new HTMLDocument();
IHTMLDocument2 doc2 = (IHTMLDocument2)doc;
doc2.write(fileText);
// now use doc
Then to convert back to a string:
doc.documentElement.outerHTML;
If the goal is to be able to push to a GitHub repo whenever you want to, then in Windows under C:\Users\tiago\.ssh
where the keys are stored (at least in my case), create a file named config and add the following in it
Host github.com
HostName github.com
User your_user_name
IdentityFile ~/.ssh/your_file_name
Then simply open Git Bash and you'll be able to push without having to manually start the ssh-agent and adding the key.
I had a similar problem with flasgger.
The reason for that was that I always use
sudo pip install flask
but for some reason that's not always the way to go. Sometimes, you have to do just
pip install flask
Another gotcha is that sometimes people type pip install Flask
with the cap F
Posting this here in case somebody gets stuck. Let me know if it helped.
Useful Link: What is the difference between pip install and sudo pip install?
Only downside (it seems), is that the table cell widths are identical. Any way to get around this? – Josh Stodola Oct 12 at 15:53
Just define width of the table and width for each table cell
something like
table {border-collapse:collapse; table-layout:fixed; width:900px;}
th {background: yellow; }
td {overflow:hidden;white-space:nowrap; }
.cells1{width:300px;}
.cells2{width:500px;}
.cells3{width:200px;}
It works like a charm :o)
I actually wanted a slightly different behavior than the accepted answer. I was building a moving average feature extractor for an sklearn
pipeline, so I required that the output of the moving average have the same dimension as the input. What I want is for the moving average to assume the series stays constant, ie a moving average of [1,2,3,4,5]
with window 2 would give [1.5,2.5,3.5,4.5,5.0]
.
For column vectors (my use case) we get
def moving_average_col(X, n):
z2 = np.cumsum(np.pad(X, ((n,0),(0,0)), 'constant', constant_values=0), axis=0)
z1 = np.cumsum(np.pad(X, ((0,n),(0,0)), 'constant', constant_values=X[-1]), axis=0)
return (z1-z2)[(n-1):-1]/n
And for arrays
def moving_average_array(X, n):
z2 = np.cumsum(np.pad(X, (n,0), 'constant', constant_values=0))
z1 = np.cumsum(np.pad(X, (0,n), 'constant', constant_values=X[-1]))
return (z1-z2)[(n-1):-1]/n
Of course, one doesn't have to assume constant values for the padding, but doing so should be adequate in most cases.
There's a modern native alternative: File implements Blob, so we can call Blob.text().
async function readText(event) {
const file = event.target.files.item(0)
const text = await file.text();
document.getElementById("output").innerText = text
}
_x000D_
<input type="file" onchange="readText(event)" />
<pre id="output"></pre>
_x000D_
Currently (September 2020) this is supported in Chrome and Firefox, for other Browser you need to load a polyfill, e.g. blob-polyfill.
Demo
$( '.expand' ).click(function() {_x000D_
$( '.img_display_content' ).toggle();_x000D_
});
_x000D_
.wrap {_x000D_
margin-left:auto;_x000D_
margin-right:auto;_x000D_
width:40%;_x000D_
}_x000D_
_x000D_
.img_display_header {_x000D_
height:20px;_x000D_
background-color:#CCC;_x000D_
display:block;_x000D_
border:#333 solid 1px;_x000D_
margin-bottom: 2px;_x000D_
}_x000D_
_x000D_
.expand {_x000D_
float:right;_x000D_
height: 100%;_x000D_
padding-right:5px;_x000D_
cursor:pointer;_x000D_
}_x000D_
_x000D_
.img_display_content {_x000D_
width: 100%;_x000D_
height:100px; _x000D_
background-color:#0F3;_x000D_
margin-top: -2px;_x000D_
display:none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="wrap">_x000D_
<div class="img_display_header">_x000D_
<div class="expand">+</div>_x000D_
</div>_x000D_
<div class="img_display_content"></div>_x000D_
</div>_x000D_
</div>
_x000D_
http://api.jquery.com/toggle/
"Display or hide the matched elements."
This is much shorter in code than using show() and hide() methods.
this method also encounter a deprecate warning:
org.junit.Assert.assertEquals(float expected,float actual) //deprecated
It is because currently junit prefer a third parameter rather than just two float variables input.
The third parameter is delta:
public static void assertEquals(double expected,double actual,double delta) //replacement
this is mostly used to deal with inaccurate Floating point calculations
for more information, please refer this problem: Meaning of epsilon argument of assertEquals for double values
None of the answer for me was working. Actually if you want to watch on nested data with Components being called multiple times. So they are called with different props to identify them.
For example <MyComponent chart="chart1"/> <MyComponent chart="chart2"/>
My workaround is to create an addionnal vuex state variable, that I manually update to point to the property that was last updated.
Here is a Vuex.ts implementation example:
export default new Vuex.Store({
state: {
hovEpacTduList: {}, // a json of arrays to be shared by different components,
// for example hovEpacTduList["chart1"]=[2,6,9]
hovEpacTduListChangeForChart: "chart1" // to watch for latest update,
// here to access "chart1" update
},
mutations: {
setHovEpacTduList: (state, payload) => {
state.hovEpacTduListChangeForChart = payload.chart // we will watch hovEpacTduListChangeForChart
state.hovEpacTduList[payload.chart] = payload.list // instead of hovEpacTduList, which vuex cannot watch
},
}
On any Component function to update the store:
const payload = {chart:"chart1", list: [4,6,3]}
this.$store.commit('setHovEpacTduList', payload);
Now on any Component to get the update:
computed: {
hovEpacTduListChangeForChart() {
return this.$store.state.hovEpacTduListChangeForChart;
}
},
watch: {
hovEpacTduListChangeForChart(chart) {
if (chart === this.chart) // the component was created with chart as a prop <MyComponent chart="chart1"/>
console.log("Update! for", chart, this.$store.state.hovEpacTduList[chart]);
},
},
If you want to delete file first close all the connections and streams. after that delete the file.
I have implemented BasicAuthenticationHandler
for basic authentication so you can use it with standart attributes Authorize
and AllowAnonymous
.
public class BasicAuthenticationHandler : AuthenticationHandler<BasicAuthenticationOptions>
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var authHeader = (string)this.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
{
//Extract credentials
string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
int seperatorIndex = usernamePassword.IndexOf(':', StringComparison.OrdinalIgnoreCase);
var username = usernamePassword.Substring(0, seperatorIndex);
var password = usernamePassword.Substring(seperatorIndex + 1);
//you also can use this.Context.Authentication here
if (username == "test" && password == "test")
{
var user = new GenericPrincipal(new GenericIdentity("User"), null);
var ticket = new AuthenticationTicket(user, new AuthenticationProperties(), Options.AuthenticationScheme);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
else
{
return Task.FromResult(AuthenticateResult.Fail("No valid user."));
}
}
this.Response.Headers["WWW-Authenticate"]= "Basic realm=\"yourawesomesite.net\"";
return Task.FromResult(AuthenticateResult.Fail("No credentials."));
}
}
public class BasicAuthenticationMiddleware : AuthenticationMiddleware<BasicAuthenticationOptions>
{
public BasicAuthenticationMiddleware(
RequestDelegate next,
IOptions<BasicAuthenticationOptions> options,
ILoggerFactory loggerFactory,
UrlEncoder encoder)
: base(next, options, loggerFactory, encoder)
{
}
protected override AuthenticationHandler<BasicAuthenticationOptions> CreateHandler()
{
return new BasicAuthenticationHandler();
}
}
public class BasicAuthenticationOptions : AuthenticationOptions
{
public BasicAuthenticationOptions()
{
AuthenticationScheme = "Basic";
AutomaticAuthenticate = true;
}
}
Registration at Startup.cs - app.UseMiddleware<BasicAuthenticationMiddleware>();
. With this code, you can restrict any controller with standart attribute Autorize:
[Authorize(ActiveAuthenticationSchemes = "Basic")]
[Route("api/[controller]")]
public class ValuesController : Controller
and use attribute AllowAnonymous
if you apply authorize filter on application level.
With Java 8 you can do:
Foo foo = set.stream().filter(item->item.equals(theItemYouAreLookingFor)).findFirst().get();
But be careful, .get() throws a NoSuchElementException, or you can manipulate a Optional item.
If you don't have the tab and you started with an empty activity try this. Below is a sample code example:
<application android:label="@string/app_name">
<activity android:name=".HelloActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
Now go to your AndroidManifest.xml file. Next copy the intent filter from this code. Look at your manifest file really good and paste the intent filter in the exact place it is in the code above. (after the .yourActivityName> part of the manifest.) I hope this helped.
You can use this method to get the digit:
public int digitToValue(char c) {
(c >= '&' && c <= '9') return c - '0';
else if (c >= 'A' && c <= 'F') return 10 + c - 'A';
else if (c >= 'a' && c <= 'f') return 10 + c - 'a';
return -1;
}
Checking if v
contains the element x
:
#include <algorithm>
if(std::find(v.begin(), v.end(), x) != v.end()) {
/* v contains x */
} else {
/* v does not contain x */
}
Checking if v
contains elements (is non-empty):
if(!v.empty()){
/* v is non-empty */
} else {
/* v is empty */
}
You can use:
$answer.replace(' ' , '')
or
$answer -replace " ", ""
if you want to remove all whitespace you can use:
$answer -replace "\s", ""
For Blocks lover you can use ALActionBlocks to add action of gestures in block
__weak ALViewController *wSelf = self;
imageView.userInteractionEnabled = YES;
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithBlock:^(UITapGestureRecognizer *weakGR) {
NSLog(@"pan %@", NSStringFromCGPoint([weakGR locationInView:wSelf.view]));
}];
[self.imageView addGestureRecognizer:gr];
The easiest way to output a single character is to simply use the putchar
function. After all, that's it's sole purpose and it cannot do anything else. It cannot be simpler than that.
The one downside with setInterval
is that it can slow down the main thread. You can do a countdown timer using requestAnimationFrame
instead to prevent this. For example, this is my generic countdown timer component:
class Timer extends Component {
constructor(props) {
super(props)
// here, getTimeRemaining is a helper function that returns an
// object with { total, seconds, minutes, hours, days }
this.state = { timeLeft: getTimeRemaining(props.expiresAt) }
}
// Wait until the component has mounted to start the animation frame
componentDidMount() {
this.start()
}
// Clean up by cancelling any animation frame previously scheduled
componentWillUnmount() {
this.stop()
}
start = () => {
this.frameId = requestAnimationFrame(this.tick)
}
tick = () => {
const timeLeft = getTimeRemaining(this.props.expiresAt)
if (timeLeft.total <= 0) {
this.stop()
// ...any other actions to do on expiration
} else {
this.setState(
{ timeLeft },
() => this.frameId = requestAnimationFrame(this.tick)
)
}
}
stop = () => {
cancelAnimationFrame(this.frameId)
}
render() {...}
}
You have quite a few options for this:
1 - If you can find an SVG file for the map you want, you can use something like RaphaelJS or SnapSVG to add click listeners for your states/regions, this solution is the most customizable...
2 - You can use dedicated tools such as clickablemapbuilder (free) or makeaclickablemap (i think free also).
[disclaimer] Im the author of clickablemapbuilder.com :)
My workaround had been using Perl:
find . -type f -print0 | xargs -0 perl -pi -e 's/was/now/g'
You can indeed match all those characters, but it's safer to escape the -
so that it is clear that it be taken literally.
If you are using a POSIX variant you can opt to use:
([[:alnum:]\-_]+)
But a since you are including the underscore I would simply use:
([\w\-]+)
(works in all variants)
No, any method will require you to resolve every result. You can do
iter_length = len(list(iterable))
but running that on an infinite iterator will of course never return. It also will consume the iterator and it will need to be reset if you want to use the contents.
Telling us what real problem you're trying to solve might help us find you a better way to accomplish your actual goal.
Edit: Using list()
will read the whole iterable into memory at once, which may be undesirable. Another way is to do
sum(1 for _ in iterable)
as another person posted. That will avoid keeping it in memory.
ThreadPoolExecutor
also has beforeExecute
and afterExecute
hook methods that you can override and make use of. Here is the description from ThreadPoolExecutor
's Javadocs.
Hook methods
This class provides protected overridable
beforeExecute(java.lang.Thread, java.lang.Runnable)
andafterExecute(java.lang.Runnable, java.lang.Throwable)
methods that are called before and after execution of each task. These can be used to manipulate the execution environment; for example, reinitializingThreadLocals
, gathering statistics, or adding log entries. Additionally, methodterminated()
can be overridden to perform any special processing that needs to be done once theExecutor
has fully terminated. If hook or callback methods throw exceptions, internal worker threads may in turn fail and abruptly terminate.
Had this error message when I was trying to select from a view.
The problem was the view recently had gained some new null rows (in SubscriberId column), and it had not been updated in EDMX (EF database first).
The column had to be Nullable type for it to work.
var dealer = Context.Dealers.Where(x => x.dealerCode == dealerCode).FirstOrDefault();
Before view refresh:
public int SubscriberId { get; set; }
After view refresh:
public Nullable<int> SubscriberId { get; set; }
Deleting and adding the view back in EDMX worked.
Hope it helps someone.
If you use docker-compose just set UPLOAD_LIMIT
phpmyadmin:
image: phpmyadmin/phpmyadmin
environment:
UPLOAD_LIMIT: 1G
Here is maybe a more elegant and flexible solution with 'resolve' configuration property and 'promises' enabling eventual data loading on routing and routing rules depending on data.
You specify a function in 'resolve' in routing config and in the function load and check data, do all redirects. If you need to load data, you return a promise, if you need to do redirect - reject promise before that. All details can be found on $routerProvider and $q documentation pages.
'use strict';
var app = angular.module('app', [])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "login.html",
controller: LoginController
})
.when('/private', {
templateUrl: "private.html",
controller: PrivateController,
resolve: {
factory: checkRouting
}
})
.when('/private/anotherpage', {
templateUrl:"another-private.html",
controller: AnotherPriveController,
resolve: {
factory: checkRouting
}
})
.otherwise({ redirectTo: '/' });
}]);
var checkRouting= function ($q, $rootScope, $location) {
if ($rootScope.userProfile) {
return true;
} else {
var deferred = $q.defer();
$http.post("/loadUserProfile", { userToken: "blah" })
.success(function (response) {
$rootScope.userProfile = response.userProfile;
deferred.resolve(true);
})
.error(function () {
deferred.reject();
$location.path("/");
});
return deferred.promise;
}
};
For russian-speaking folks there is a post on habr "??????? ????????? ???????? ? AngularJS."
I had this same problem in a large Excel 2000 spreadsheet with hundreds of lines of code. My solution was to make the Worksheet active at the beginning of the Class. I.E. ThisWorkbook.Worksheets("WorkSheetName").Activate This was finally discovered when I noticed that if "WorkSheetName" was active when starting the operation (the code) the error didn't occur. Drove me crazy for quite awhile.
If you want to do it via setAttribute
you would change the style
attribute like so:
element.setAttribute('style','transform:rotate(90deg); -webkit-transform: rotate(90deg)') //etc
This would be helpful if you want to reset all other inline style and only set your needed style properties' values again, BUT in most cases you may not want that. That's why everybody advised to use this:
element.style.transform = 'rotate(90deg)';
element.style.webkitTransform = 'rotate(90deg)';
The above is equivalent to
element.style['transform'] = 'rotate(90deg)';
element.style['-webkit-transform'] = 'rotate(90deg)';
After you write to the MemoryStream
and before you read it back, you need to Seek
back to the beginning of the MemoryStream
so you're not reading from the end.
UPDATE
After seeing your update, I think there's a more reliable way to build the stream:
UnicodeEncoding uniEncoding = new UnicodeEncoding();
String message = "Message";
// You might not want to use the outer using statement that I have
// I wasn't sure how long you would need the MemoryStream object
using(MemoryStream ms = new MemoryStream())
{
var sw = new StreamWriter(ms, uniEncoding);
try
{
sw.Write(message);
sw.Flush();//otherwise you are risking empty stream
ms.Seek(0, SeekOrigin.Begin);
// Test and work with the stream here.
// If you need to start back at the beginning, be sure to Seek again.
}
finally
{
sw.Dispose();
}
}
As you can see, this code uses a StreamWriter to write the entire string (with proper encoding) out to the MemoryStream
. This takes the hassle out of ensuring the entire byte array for the string is written.
Update: I stepped into issue with empty stream several time. It's enough to call Flush right after you've finished writing.
This code employs a simple algorithm with nested lists...
# FUNCTION getCombos: To generate all combos of an input list, consider the following sets of nested lists...
#
# [ [ [] ] ]
# [ [ [] ], [ [A] ] ]
# [ [ [] ], [ [A],[B] ], [ [A,B] ] ]
# [ [ [] ], [ [A],[B],[C] ], [ [A,B],[A,C],[B,C] ], [ [A,B,C] ] ]
# [ [ [] ], [ [A],[B],[C],[D] ], [ [A,B],[A,C],[B,C],[A,D],[B,D],[C,D] ], [ [A,B,C],[A,B,D],[A,C,D],[B,C,D] ], [ [A,B,C,D] ] ]
#
# There is a set of lists for each number of items that will occur in a combo (including an empty set).
# For each additional item, begin at the back of the list by adding an empty list, then taking the set of
# lists in the previous column (e.g., in the last list, for sets of 3 items you take the existing set of
# 3-item lists and append to it additional lists created by appending the item (4) to the lists in the
# next smallest item count set. In this case, for the three sets of 2-items in the previous list. Repeat
# for each set of lists back to the initial list containing just the empty list.
#
def getCombos(listIn = ['A','B','C','D','E','F'] ):
listCombos = [ [ [] ] ] # list of lists of combos, seeded with a list containing only the empty list
listSimple = [] # list to contain the final returned list of items (e.g., characters)
for item in listIn:
listCombos.append([]) # append an emtpy list to the end for each new item added
for index in xrange(len(listCombos)-1, 0, -1): # set the index range to work through the list
for listPrev in listCombos[index-1]: # retrieve the lists from the previous column
listCur = listPrev[:] # create a new temporary list object to update
listCur.append(item) # add the item to the previous list to make it current
listCombos[index].append(listCur) # list length and append it to the current list
itemCombo = '' # Create a str to concatenate list items into a str
for item in listCur: # concatenate the members of the lists to create
itemCombo += item # create a string of items
listSimple.append(itemCombo) # add to the final output list
return [listSimple, listCombos]
# END getCombos()
socket.send
is implemented for compatibility with vanilla WebSocket interface. socket.emit
is feature of Socket.IO only. They both do the same, but socket.emit
is a bit more convenient in handling messages.
Here's a javascript implementation that works with web-kit:
var isHovering = false;
var el = $(".elem").mouseover(function(){
isHovering = true;
spin();
}).mouseout(function(){
isHovering = false;
});
var spin = function(){
if(isHovering){
el.removeClass("spin");
setTimeout(function(){
el.addClass("spin");
setTimeout(spin, 1500);
}, 0);
}
};
spin();
JSFiddle: http://jsfiddle.net/4Vz63/161/
Barf.
There's a Windows Explorer extension made by the dude who makes tools for SVN that will at least open a command prompt window.
I haven't tried it yet, so I don't know if it'll do PowerShell, but I wanted to share the love with my Stack Overflow brethren:
An addendum to this. You can use character entities (such as changing <div>
to <div>
) and it will render in the textarea. But when it is saved, the value of the textarea is the text as rendered. So you don't need to de-encode. I just tested this across browsers (ie back to 11).
Avoid PID-files, crons, or anything else that tries to evaluate processes that aren't their children.
There is a very good reason why in UNIX, you can ONLY wait on your children. Any method (ps parsing, pgrep, storing a PID, ...) that tries to work around that is flawed and has gaping holes in it. Just say no.
Instead you need the process that monitors your process to be the process' parent. What does this mean? It means only the process that starts your process can reliably wait for it to end. In bash, this is absolutely trivial.
until myserver; do
echo "Server 'myserver' crashed with exit code $?. Respawning.." >&2
sleep 1
done
The above piece of bash code runs myserver
in an until
loop. The first line starts myserver
and waits for it to end. When it ends, until
checks its exit status. If the exit status is 0
, it means it ended gracefully (which means you asked it to shut down somehow, and it did so successfully). In that case we don't want to restart it (we just asked it to shut down!). If the exit status is not 0
, until
will run the loop body, which emits an error message on STDERR and restarts the loop (back to line 1) after 1 second.
Why do we wait a second? Because if something's wrong with the startup sequence of myserver
and it crashes immediately, you'll have a very intensive loop of constant restarting and crashing on your hands. The sleep 1
takes away the strain from that.
Now all you need to do is start this bash script (asynchronously, probably), and it will monitor myserver
and restart it as necessary. If you want to start the monitor on boot (making the server "survive" reboots), you can schedule it in your user's cron(1) with an @reboot
rule. Open your cron rules with crontab
:
crontab -e
Then add a rule to start your monitor script:
@reboot /usr/local/bin/myservermonitor
Alternatively; look at inittab(5) and /etc/inittab. You can add a line in there to have myserver
start at a certain init level and be respawned automatically.
Edit.
Let me add some information on why not to use PID files. While they are very popular; they are also very flawed and there's no reason why you wouldn't just do it the correct way.
Consider this:
PID recycling (killing the wrong process):
/etc/init.d/foo start
: start foo
, write foo
's PID to /var/run/foo.pid
foo
dies somehow.bar
) takes a random PID, imagine it taking foo
's old PID.foo
's gone: /etc/init.d/foo/restart
reads /var/run/foo.pid
, checks to see if it's still alive, finds bar
, thinks it's foo
, kills it, starts a new foo
.PID files go stale. You need over-complicated (or should I say, non-trivial) logic to check whether the PID file is stale, and any such logic is again vulnerable to 1.
.
What if you don't even have write access or are in a read-only environment?
It's pointless overcomplication; see how simple my example above is. No need to complicate that, at all.
See also: Are PID-files still flawed when doing it 'right'?
By the way; even worse than PID files is parsing ps
! Don't ever do this.
ps
is very unportable. While you find it on almost every UNIX system; its arguments vary greatly if you want non-standard output. And standard output is ONLY for human consumption, not for scripted parsing!ps
leads to a LOT of false positives. Take the ps aux | grep PID
example, and now imagine someone starting a process with a number somewhere as argument that happens to be the same as the PID you stared your daemon with! Imagine two people starting an X session and you grepping for X to kill yours. It's just all kinds of bad.If you don't want to manage the process yourself; there are some perfectly good systems out there that will act as monitor for your processes. Look into runit, for example.
Short answer:
StandardOutput=file:/var/log1.log
StandardError=file:/var/log2.log
If you don't want the files to be cleared every time the service is run, use append instead:
StandardOutput=append:/var/log1.log
StandardError=append:/var/log2.log
I bumped into this problem using PHP-FPM and Apache after increasing Apache's default LimitRequestFieldSize and LimitRequestLine values.
The only reason I did this (apache says don't mess) is because Yii2 has some pjax problems with POST requests. As a workaround, I decided to increase these limits and use gigantic GET headers.
php-fpm barfed up the 500 error though.
I think this code will resolve your issue. Copy and paste this code on your MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View decorView = getWindow().getDecorView();
decorView.setOnSystemUiVisibilityChangeListener
(new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int visibility) {
if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
hideNavigationBar();
}
}
});
}
private void hideNavigationBar() {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
It will works on Android-10. I hope it will helps.
See svn diff
in the manual:
svn diff -r 8979:11390 http://svn.collab.net/repos/svn/trunk/fSupplierModel.php
If you are using the script approach and have an error concerning the LDF and MDF files, you can first query the the backup file for the logical names (and other details) of files in the backup set, using the following:
-- Queries the backup file for the file list in backup set, where Type denotes
-- type of file. Can be L,D,F or S
-- info: https://docs.microsoft.com/en-us/sql/t-sql/statements/restore-statements-filelistonly-transact-sql
RESTORE FILELISTONLY FROM DISK = 'C:\Temp\DB_backup.bak'
GO
You will get results similar to the following:
And then you can use those logical names in the queries:
-- Script assumes you want MDF and LDF files restored on separate drives. Modify for your scenario
RESTORE DATABASE DB
FROM DISK='C:\Temp\DB_backup.bak'
WITH REPLACE,
MOVE 'DB' TO 'E:\MSSQL\Data\DB.mdf', -- "DB" is the mdf logical name from query above
MOVE 'DB_log' TO 'F:\MSSQL\Logs\DB.ldf'; -- "DB_log" is LDF logical name from query above
More info on RESTORE FILELISTONLY
can be found from the SQL Server docs.
So, I'm not sure why there's so much consternation on this topic. I can name a git stash
with both a push
and the deprecated save
, and I can use a regex to pull it back with an apply
:
$ git stash push -m "john-hancock"
$ git stash apply stash^{/john-hancock}
As it has been mentioned before, the save
command is deprecated, but it still works, so you can used this on older systems where you can't update them with a push
call. Unlike the push
command, the -m
switch isn't required with save
.
// save is deprecated but still functional
$ git stash save john-hancock
This is Git 2.2 and Windows 10.
Here's a beautiful animated GIF demonstrating the process.
The GIF runs quickly, but if you look, the process is this:
ls
command shows 4 files in the directorytouch example.html
adds a 5th filegit stash push -m "john-hancock" -a
(The -a
includes untracked files)ls
command shows 4 files after the stash, meaning the stash and the implicit hard reset workedgit stash apply stash^{/john-hancock}
runsls
command lists 5 files, showing the example.html file was brought back, meaning the git stash apply
command worked.To be frank, I'm not sure what the benefit of this approach is though. There's value in giving the stash a name, but not the retrieval. Maybe to script the shelve and unshelve process it'd be helpful, but it's still way easier to just pop a stash by name.
$ git stash pop 3
$ git stash apply 3
That looks way easier to me than the regex.
Append adds the entire data at once. The whole data will be added to the newly created index. On the other hand, extend
, as it name suggests, extends the current array.
For example
list1 = [123, 456, 678]
list2 = [111, 222]
With append
we get:
result = [123, 456, 678, [111, 222]]
While on extend
we get:
result = [123, 456, 678, 111, 222]
If you are using Spring Boot version >= 2.0 try setting this bean in your configuration:
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http.authorizeExchange().anyExchange().permitAll();
return http.build();
}
Reference: https://stackoverflow.com/a/47292134/1195507
I figured out what it was! When I cleared the fields using the each() method, it also cleared the hidden field which the php needed to run:
if ($_POST['action'] == 'addRunner')
I used the :not() on the selection to stop it from clearing the hidden field.
print("the furnace is now " + str(temperature) + "degrees!")
cast it to str
$_
last argument of last command$#
number of arguments passed to current script$*
/ $@
list of arguments passed to script as string / delimited listoff the top of my head. Google for bash special variables.
If you already have a table pre_loaded_tbl with some data. You can use a trick to load the data into your table with following query
INSERT INTO TABLE tweet_table
SELECT "my_data" AS my_column
FROM pre_loaded_tbl
LIMIT 5;
Also please note that "my_data" is independent of any data in the pre_loaded_tbl. You can select any data and write any column name (here my_data and my_column). Hive does not require it to have same column name. However structure of select statement should be same as that of your tweet_table. You can use limit to determine how many times you can insert into the tweet_table.
However if you haven't' created any table, you will have to load the data using file copy or load data commands in above answers.
Both are the same thing but many of the databases are not providing the varying char mainly postgreSQL is providing. So for the multi database like Oracle Postgre and DB2 it is good to use the Varchar
If you are looking for readability, I believe that this is that code:
print '%(kg).2f kg = %(lb).2f lb = %(gal).2f gal = %(l).2f l' % {
'kg': var1,
'lb': var2,
'gal': var3,
'l': var4,
}
Not very clear what you mean by
"I cant find any examples to help me understand how I can use this to run 2 different statements:"
. Is it using CASE
like a SWITCH
you are after?
select case when totalCount >= 0 and totalCount < 11 then '0-10'
when tatalCount > 10 and totalCount < 101 then '10-100'
else '>100' end as newColumn
from (
SELECT [Some Column], COUNT(*) TotalCount
FROM INCIDENTS
WHERE [Some Column] = 'Target Data'
GROUP BY [Some Column]
) A
Grave digging... I like a different approach:
elem = $('form')
elem.on('keyup','input', checkStatus)
elem.on('change', 'select', checkStatus)
checkStatus = (e) =>
elems = $('form').find('input:enabled').not('input[type=hidden]').map(-> $(this).val())
filled = $.grep(elems, (n) -> n)
bool = elems.size() != $(filled).size()
$('input:submit').attr('disabled', bool)
In general you can say session.gc_maxlifetime specifies the maximum lifetime since the last change of your session data (not the last time session_start
was called!). But PHP’s session handling is a little bit more complicated.
Because the session data is removed by a garbage collector that is only called by session_start
with a probability of session.gc_probability devided by session.gc_divisor. The default values are 1 and 100, so the garbage collector is only started in only 1% of all session_start
calls. That means even if the the session is already timed out in theory (the session data had been changed more than session.gc_maxlifetime seconds ago), the session data can be used longer than that.
Because of that fact I recommend you to implement your own session timeout mechanism. See my answer to How do I expire a PHP session after 30 minutes? for more details.
Quick solution, relies on the -webkit-mask-image
property. -webkit-mask-image
sets a mask image for an element.
There are a few gotchas with this method:
:after
psuedo-element (IMG
tags can't have :before
/:after
pseudo elements, grr)attr(…)
CSS function to get the IMG
tag URL, so it's hard-coded into the CSS separately.If you can look past those issues, this might be a possible solution. SVG filters will be even more flexible, and Canvas solutions will be even more flexible and have a wider range of support (SVG doesn't have Android 2.x support).
A related issue: I came to this page after searching for "how to know what are deleted branches".
While deleting many old branches, felt I mistakenly deleted one of the newer branches, but didn't know the name to recover it.
To know what branches are deleted recently, do the below:
If you go to your Git URL, which will look something like this:
https://your-website-name/orgs/your-org-name/dashboard
Then you can see the feed, of what is deleted, by whom, in the recent past.
Your format specifier is incorrect. From the printf()
man page on my machine:
0
A zero '0
' character indicating that zero-padding should be used rather than blank-padding. A '-
' overrides a '0
' if both are used;Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);
Precision: An optional period, '
.
', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;
For your case, your format would be %09.3f
:
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%09.3f\n", 4917.24);
return 0;
}
Output:
$ make testapp
cc testapp.c -o testapp
$ ./testapp
04917.240
Note that this answer is conditional on your embedded system having a printf()
implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.
The following solution reads from a file if the script is called
with a file name as the first parameter $1
otherwise from standard input.
while read line
do
echo "$line"
done < "${1:-/dev/stdin}"
The substitution ${1:-...}
takes $1
if defined otherwise
the file name of the standard input of the own process is used.
BLOB is for binary data (videos, images, documents, other)
CLOB is for large text data (text)
Maximum size on MySQL 2GB
Maximum size on Oracle 128TB
After misunderstanding, I finally got what you are trying to do. You should check your server configuration files; are you using apache2 or some other server software?
Look for lines that start with LoadModule php
...
There probably are configuration files/directories named mods
or something like that, start from there.
You could also check output from php -r 'phpinfo();' | grep php
and compare lines to phpinfo();
from web server.
php
interactively:(so you can paste/write code in the console)
php -a
php -f file.php
php -f file.php > results.html
To run only small part, one line or like, you can use:
php -r '$x = "Hello World"; echo "$x\n";'
If you are running linux then do man php
at console.
if you need/want to run php through fpm, use cli fcgi
SCRIPT_NAME="file.php" SCRIP_FILENAME="file.php" REQUEST_METHOD="GET" cgi-fcgi -bind -connect "/var/run/php-fpm/php-fpm.sock"
where /var/run/php-fpm/php-fpm.sock is your php-fpm socket file.
For this, I installed an extension called TabOut. Pretty much does what the name suggests.
This is the way I would do it : saying that "list" is a <List<t>>
where t is a class with a Name and a Value field; but of course you can do it with any other class type.
list = list.Where(c=>c.Name == "height")
.Select( new t(){Name = c.Name, Value = 30})
.Union(list.Where(c=> c.Name != "height"))
.ToList();
This works perfectly ! It's a simple linq expression without any loop logic. The only thing you should be aware is that the order of the lines in the result dataset will be different from the order you had in the source dataset. So if sorting is important to you, just reproduce the same order by clauses in the final linq query.
If you're using Bootstrap Sass, here's another way that avoids having to add extra classes to your element markup:
@import "bootstrap/mixins/_border-radius";
@import "bootstrap/_variables";
.your-class {
$r: $border-radius-base; // or $border-radius-large, $border-radius-small, ...
@include border-top-radius($r);
@include border-bottom-radius($r);
}
Try the following:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC]
RewriteRule \.(gif|jpg)$ - [F]
Returns 403, if you access images directly, but allows them to be displayed on site.
Note: It is possible that when you open some page with image and then copy that image's path into the address bar you can see that image, it is only because of the browser's cache, in fact that image has not been loaded from the server (from Davo, full comment below).
Another variation on the already proposed answers without jQuery.
Object.values(document.getElementById('mySelect').options).forEach(option => alert(option))
I just did it like this, including the authentication method:
s3_client = boto3.client(
's3',
aws_access_key_id='access_key',
aws_secret_access_key='access_key_secret',
config=boto3.session.Config(signature_version='s3v4'),
region_name='region'
)
response = s3_client.list_objects(Bucket='bucket_name', Prefix=key)
if ('Contents' in response):
# Object / key exists!
return True
else:
# Object / key DOES NOT exist!
return False
use this tag {!! description text !!}
container can not come front to inner container. but try this below :
Css :
----------------------
.container { position:relative; }
.div1 { width:100px; height:100px; background:#9C3; position:absolute;
z-index:1000; left:50px; top:50px; }
.div2 { width:200px; height:200px; background:#900; }
HTMl :
-----------------------
<div class="container">
<div class="div1">
Div1 content here .........
</div>
<div class="div2">
Div2 contenet here .........
</div>
</div>
Here's how I did it.
Enter the sqlite shell of the db to which the data needs to be added
sqlite> .separator "\t" ---IMPORTANT! should be in double quotes
sqlite> .import afile.csv tablename-to-import-to
Something like...
greetings = 'Hello {name}'.format(name = 'John')
Hello John
All you have to do is use the GetFocusedRowCellValue method of the gridView control and put it into the RowClick event.
For example:
private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
if (this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni") == null)
return;
MessageBox.Show(""+this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni").ToString());
}
Technically, you can't return more than one value. However, there are multiple ways to work around that limitation. The way that acts most like returning multiple values, is with the list
keyword:
function getXYZ()
{
return array(4,5,6);
}
list($x,$y,$z) = getXYZ();
// Afterwards: $x == 4 && $y == 5 && $z == 6
// (This will hold for all samples unless otherwise noted)
Technically, you're returning an array and using list
to store the elements of that array in different values instead of storing the actual array. Using this technique will make it feel most like returning multiple values.
The list
solution is a rather php-specific one. There are a few languages with similar structures, but more languages that don't. There's another way that's commonly used to "return" multiple values and it's available in just about every language (in one way or another). However, this method will look quite different so may need some getting used to.
// note that I named the arguments $a, $b and $c to show that
// they don't need to be named $x, $y and $z
function getXYZ(&$a, &$b, &$c)
{
$a = 4;
$b = 5;
$c = 6;
}
getXYZ($x, $y, $z);
This technique is also used in some functions defined by php itself (e.g. $count
in str_replace, $matches
in preg_match). This might feel quite different from returning multiple values, but it is worth at least knowing about.
A third method is to use an object to hold the different values you need. This is more typing, so it's not used quite as often as the two methods above. It may make sense to use this, though, when using the same set of variables in a number of places (or of course, working in a language that doesn't support the above methods or allows you to do this without extra typing).
class MyXYZ
{
public $x;
public $y;
public $z;
}
function getXYZ()
{
$out = new MyXYZ();
$out->x = 4;
$out->y = 5;
$out->z = 6;
return $out;
}
$xyz = getXYZ();
$x = $xyz->x;
$y = $xyz->y;
$z = $xyz->z;
The above methods sum up the main ways of returning multiple values from a function. However, there are variations on these methods. The most interesting variations to look at, are those in which you are actually returning an array, simply because there's so much you can do with arrays in PHP.
First, we can simply return an array and not treat it as anything but an array:
function getXYZ()
{
return array(1,2,3);
}
$array = getXYZ();
$x = $array[0];
$y = $array[1];
$z = $array[2];
The most interesting part about the code above is that the code inside the function is the same as in the very first example I provided; only the code calling the function changed. This means that it's up to the one calling the function how to treat the result the function returns.
Alternatively, one could use an associative array:
function getXYZ()
{
return array('x' => 4,
'y' => 5,
'z' => 6);
}
$array = getXYZ();
$x = $array['x'];
$y = $array['y'];
$z = $array['z'];
Php does have the compact
function that allows you to do same as above but while writing less code. (Well, the sample won't have less code, but a real world application probably would.) However, I think the amount of typing saving is minimal and it makes the code harder to read, so I wouldn't do it myself. Nevertheless, here's a sample:
function getXYZ()
{
$x = 4;
$y = 5;
$z = 6;
return compact('x', 'y', 'z');
}
$array = getXYZ();
$x = $array['x'];
$y = $array['y'];
$z = $array['z'];
It should be noted that while compact
does have a counterpart in extract
that could be used in the calling code here, but since it's a bad idea to use it (especially for something as simple as this) I won't even give a sample for it. The problem is that it will do "magic" and create variables for you, while you can't see which variables are created without going to other parts of the code.
Finally, I would like to mention that list
doesn't really play well with associative array. The following will do what you expect:
function getXYZ()
{
return array('x' => 4,
'y' => 5,
'z' => 6);
}
$array = getXYZ();
list($x, $y, $z) = getXYZ();
However, the following will do something different:
function getXYZ()
{
return array('x' => 4,
'z' => 6,
'y' => 5);
}
$array = getXYZ();
list($x, $y, $z) = getXYZ();
// Pay attention: $y == 6 && $z == 5
If you used list
with an associative array, and someone else has to change the code in the called function in the future (which may happen just about any situation) it may suddenly break, so I would recommend against combining list
with associative arrays.
We can check error & 404 statusCode, and use try {} catch (err) {}
.
You can try this :
const req = new XMLHttpRequest();_x000D_
req.onreadystatechange = function() {_x000D_
if (req.status == 404) {_x000D_
console.log("404");_x000D_
return false;_x000D_
}_x000D_
_x000D_
if (!(req.readyState == 4 && req.status == 200))_x000D_
return false;_x000D_
_x000D_
const json = (function(raw) {_x000D_
try {_x000D_
return JSON.parse(raw);_x000D_
} catch (err) {_x000D_
return false;_x000D_
}_x000D_
})(req.responseText);_x000D_
_x000D_
if (!json)_x000D_
return false;_x000D_
_x000D_
document.body.innerHTML = "Your city : " + json.city + "<br>Your isp : " + json.org;_x000D_
};_x000D_
req.open("GET", "https://ipapi.co/json/", true);_x000D_
req.send();
_x000D_
Read more :
Okay, first a few terms slightly oversimplified.
In git
, a tag
(like many other things) is what's called a treeish. It's a way of referring to a point in in the history of the project. Treeishes can be a tag, a commit, a date specifier, an ordinal specifier or many other things.
Now a branch
is just like a tag but is movable. When you are "on" a branch and make a commit, the branch is moved to the new commit you made indicating it's current position.
Your HEAD
is pointer to a branch which is considered "current". Usually when you clone a repository, HEAD
will point to master
which in turn will point to a commit. When you then do something like git checkout experimental
, you switch the HEAD
to point to the experimental
branch which might point to a different commit.
Now the explanation.
When you do a git checkout v2.0
, you are switching to a commit that is not pointed to by a branch
. The HEAD
is now "detached" and not pointing to a branch. If you decide to make a commit now (as you may), there's no branch pointer to update to track this commit. Switching back to another commit will make you lose this new commit you've made. That's what the message is telling you.
Usually, what you can do is to say git checkout -b v2.0-fixes v2.0
. This will create a new branch pointer at the commit pointed to by the treeish v2.0
(a tag in this case) and then shift your HEAD
to point to that. Now, if you make commits, it will be possible to track them (using the v2.0-fixes
branch) and you can work like you usually would. There's nothing "wrong" with what you've done especially if you just want to take a look at the v2.0
code. If however, you want to make any alterations there which you want to track, you'll need a branch.
You should spend some time understanding the whole DAG model of git. It's surprisingly simple and makes all the commands quite clear.
We have similar situation right now and as of this answer, I am using laravel 5.6 release.
I will not use your example in the question but mine, because it's related though.
I have route like this:
Route::name('your.name.here')->get('/your/uri', 'YourController@someMethod');
Then in your controller method, make sure you include
use Illuminate\Http\Request;
and this should be above your controller, most likely a default, if generated using php artisan
, now to get variable from the url it should look like this:
public function someMethod(Request $request)
{
$foo = $request->input("start");
$bar = $request->input("limit");
// some codes here
}
Regardless of the HTTP verb, the input() method may be used to retrieve user input.
https://laravel.com/docs/5.6/requests#retrieving-input
Hope this help.
How about the ole goto statement (i know, i know, but it works just fine here ;)
DECLARE
v_attr char(88);
CURSOR SELECT_USERS IS
SELECT id FROM USER_TABLE
WHERE USERTYPE = 'X';
BEGIN
FOR user_rec IN SELECT_USERS LOOP
BEGIN
SELECT attr INTO v_attr
FROM ATTRIBUTE_TABLE
WHERE user_id = user_rec.id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
-- user does not have attribute, continue loop to next record.
goto end_loop;
END;
<<end_loop>>
null;
END LOOP;
END;
Just put end_loop at very end of loop of course. The null can be substituted with a commit maybe or a counter increment maybe, up to you.
There are enough definitions of segmentation fault, i would like to quote few examples which i came across while programming, which might seem silly mistakes, but will waste a lot of time.
you can get segmentation fault in below case while argumet type mismatch in printf
#include<stdio.h>
int main(){
int a = 5;
printf("%s",a);
return 0;
}
output : Segmentation Fault (SIGSEGV)
when you forgot to allocate memory to a pointer, but trying to use it.
#include<stdio.h>
typedef struct{
int a;
}myStruct;
int main(){
myStruct *s;
/* few lines of code */
s->a = 5;
return 0;
}
output : Segmentation Fault (SIGSEGV)
Everyone else has answered the PUT vs PATCH. I was just going to answer what part of the title of the original question asks: "... in REST API real life scenarios". In the real world, this happened to me with internet application that had a RESTful server and a relational database with a Customer table that was "wide" (about 40 columns). I mistakenly used PUT but had assumed it was like a SQL Update command and had not filled out all the columns. Problems: 1) Some columns were optional (so blank was valid answer), 2) many columns rarely changed, 3) some columns the user was not allowed to change such as time stamp of Last Purchase Date, 4) one column was a free-form text "Comments" column that users diligently filled with half-page customer services comments like spouses name to ask about OR usual order, 5) I was working on an internet app at time and there was worry about packet size.
The disadvantage of PUT is that it forces you to send a large packet of info (all columns including the entire Comments column, even though only a few things changed) AND multi-user issue of 2+ users editing the same customer simultaneously (so last one to press Update wins). The disadvantage of PATCH is that you have to keep track on the view/screen side of what changed and have some intelligence to send only the parts that changed. Patch's multi-user issue is limited to editing the same column(s) of same customer.
First of all, I wouldn't use a multi-dimensional array. Only ever seen bad things come of it.
Set up your variable like this:
IEnumerable<IEnumerable<string>> data = new[] {
new[]{"...", "...", "..."},
... etc ...
};
Then you'd simply go:
var firsts = data.Select(x => x.FirstOrDefault()).Where(x => x != null);
The Where makes sure it prunes any nulls if you have an empty list as an item inside.
Alternatively you can implement it as:
string[][] = new[] {
new[]{"...","...","..."},
new[]{"...","...","..."},
... etc ...
};
This could be used similarly to a [x,y]
array but it's used like this: [x][y]
You can zip the two with something like this [like jQuery does]:
function toggleMyDiv() {
if (document.getElementById("myDiv").style.display=="block"){
document.getElementById("myDiv").style.display="none"
}
else{
document.getElementById("myDiv").style.display="block";
}
}
..and use the same function in the two buttons - or generally in the page for both functions.
CREATE TRIGGER sampleTrigger
ON database1.dbo.table1
FOR DELETE
AS
DELETE FROM database2.dbo.table2
WHERE bar = 4 AND ID IN(SELECT deleted.id FROM deleted)
GO
In global scope there is no semantic difference.
But you really should avoid a=0
since your setting a value to an undeclared variable.
Also use closures to avoid editing global scope at all
(function() {
// do stuff locally
// Hoist something to global scope
window.someGlobal = someLocal
}());
Always use closures and always hoist to global scope when its absolutely neccesary. You should be using asynchronous event handling for most of your communication anyway.
As @AvianMoncellor mentioned there is an IE bug with var a = foo
only declaring a global for file scope. This is an issue with IE's notorious broken interpreter. This bug does sound familiar so it's probably true.
So stick to window.globalName = someLocalpointer
As Thomas Owens pointed out, simply concatenating the files will leave multiple ID3 headers scattered throughout the resulting concatenated file - so the time/bitrate info will be wildly wrong.
You're going to need to use a tool which can combine the audio data for you.
mp3wrap would be ideal for this - it's designed to join together MP3 files, without needing to decode + re-encode the data (which would result in a loss of audio quality) and will also deal with the ID3 tags intelligently.
The resulting file can also be split back into its component parts using the mp3splt tool - mp3wrap adds information to the IDv3 comment to allow this.
Any object if it is initailised , its defeault value is null, until unless we explicitly provide a default value.
The threading
module uses threads, the multiprocessing
module uses processes. The difference is that threads run in the same memory space, while processes have separate memory. This makes it a bit harder to share objects between processes with multiprocessing. Since threads use the same memory, precautions have to be taken or two threads will write to the same memory at the same time. This is what the global interpreter lock is for.
Spawning processes is a bit slower than spawning threads.
The problem is, I think, that JPA was never incepted with the idea in mind that we could have a complex preexisting Schema already in place.
I think there are two main shortcomings resulting from this, specific to Enum:
Help my cause and vote on JPA_SPEC-47
Would this not be more elegant than using a @Converter to solve the problem?
// Note: this code won't work!!
// it is just a sample of how I *would* want it to work!
@Enumerated
public enum Language {
ENGLISH_US("en-US"),
ENGLISH_BRITISH("en-BR"),
FRENCH("fr"),
FRENCH_CANADIAN("fr-CA");
@ID
private String code;
@Column(name="DESCRIPTION")
private String description;
Language(String code) {
this.code = code;
}
public String getCode() {
return code;
}
public String getDescription() {
return description;
}
}
Yes:
test2.removeAll(test1)
Although this will mutate test2
, so create a copy if you need to preserve it.
Also, you probably meant <Integer>
instead of <int>
.
I have the same issue today and I concur with Jack Leow. Basically, on Windows XP, I had to go to Control Panel > Java and then:
If you have a variable unsigned int x;
, you can convert it to an int
using (int)x
.
shareing for others:
read stream line by line,should be good for large files piped into stdin, my version:
var n=0;
function on_line(line,cb)
{
////one each line
console.log(n++,"line ",line);
return cb();
////end of one each line
}
var fs = require('fs');
var readStream = fs.createReadStream('all_titles.txt');
//var readStream = process.stdin;
readStream.pause();
readStream.setEncoding('utf8');
var buffer=[];
readStream.on('data', (chunk) => {
const newlines=/[\r\n]+/;
var lines=chunk.split(newlines)
if(lines.length==1)
{
buffer.push(lines[0]);
return;
}
buffer.push(lines[0]);
var str=buffer.join('');
buffer.length=0;
readStream.pause();
on_line(str,()=>{
var i=1,l=lines.length-1;
i--;
function while_next()
{
i++;
if(i<l)
{
return on_line(lines[i],while_next);
}
else
{
buffer.push(lines.pop());
lines.length=0;
return readStream.resume();
}
}
while_next();
});
}).on('end', ()=>{
if(buffer.length)
var str=buffer.join('');
buffer.length=0;
on_line(str,()=>{
////after end
console.error('done')
////end after end
});
});
readStream.resume();
Here is a way to easily escape & char in oracle DB
set escape '\\'
and within query write like
'ERRORS &\\\ PERFORMANCE';
This problem also arise when we don't give the single or double quotes to the database value.
Wrong way:
$query ="INSERT INTO tabel_name VALUE ($value1,$value2)";
As database inserting values must be in quotes ' '/" "
Right way:
$query ="INSERT INTO STUDENT VALUE ('$roll_no','$name','$class')";
If somebody still gets this page in search results:
fig, ax = plt.subplots()
plt.plot(...)
every_nth = 4
for n, label in enumerate(ax.xaxis.get_ticklabels()):
if n % every_nth != 0:
label.set_visible(False)
this piece of code can do its job
UPDATE TOP (100) table_name set column_name = value;
If you want to show the last 100 records, you can use this if you need.
With OrnekWith
as
(
Select Top(100) * from table_name Order By ID desc
)
Update table_name Set column_name = value;
Try this magic spell:
vm.$forceUpdate();
No need to create any hanging vars :)
Update: I found this solution when I only started working with VueJS. However further exploration proved this approach as a crutch. As far as I recall, in a while I got rid of it simply putting all the properties that failed to refresh automatically (mostly nested ones) into computed properties.
More info here: https://vuejs.org/v2/guide/computed.html
you can get the product name like this
foreach ( $cart_object->cart_contents as $value ) {
$_product = apply_filters( 'woocommerce_cart_item_product', $value['data'] );
if ( ! $_product->is_visible() ) {
echo $_product->get_title();
} else {
echo $_product->get_title();
}
}
Here's how to do it in Prototype: $(id).update(data)
And jQuery: $('#id').replaceWith(data)
But document.getElementById(id).innerHTML=data
should work too.
EDIT: Prototype and jQuery automatically evaluate scripts for you.
I noticed that many examples are overcomplicated for localhost where just postgres user without password exist in many cases:
psql -d db_name -f dump.sql
By default, when a flutter app gets installed, the app name on the launcher is your Flutter project name. To change that to your desired application name on Android or iOS both, you need to change AndroidManifest.xml
and Info.plist
respectively. here is a two way to achieve this
1 By plugin
You can use a flutter rename plugin. It helps you to change your flutter project's AppName and BundleId for different platforms, currently only available for iOS, Android and macOS
You can change the bundleId and appName in the following steps
Default Usage if you dont pass -t or --target parameter it will try to rename all available platform project folders inside flutter project.
Run this command inside your flutter project root.
pub global run rename --bundleId com.onatcipli.networkUpp
pub global run rename --appname "Test App Name"
Custom Usage if you want to run commands directly (without using pub global run) ensure you add system catche bin directory to your path
rename --appname yourappname -t ios
or
pub global run rename --appname yourappname --target macOS
To target a specific platform use the "--target" option. e.g.
pub global run rename --bundleId com.example.android.app --target android
2 By manual
For Android
App Name is reflected under Android>src>main>Androidmanifest.xml The label name in the Android manifest is responsible for giving the App Name for Android Application
Go to AndroidManifest.xml
, find <application> tag
. Change its android:label
property with your desired app name.
Navigate to the : android/app/src/main/AndroidManifest.xml
The Androidmanifest.xml can now be modified. Choose the
<application
android:name="io.flutter.app.FlutterApplication"
android:label="YourAppName"
android:icon="@mipmap/ic_launcher">
For Package Name
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.package.name">
This portion represents the actual Android file naming system. Important information like Launcher Icon and App name can be controlled here. Modify the android:label
to change the App Name only.
For iOS
For iOS, open info.plist
. Change CFBundleName (Bundle Name).
Go to the Xcode project folder and open Info.plist
for edit (in Xcode you can choose Open As > Source Code in the file context menu). All we need is to edit the value for key CFBundleName
. It’s a user-visible short name for the bundle.
Navigate to the: project/ios/Runner/Info.plist
Find the CFBundleName <key>
. This denotes the Key that holds the app name. The app name now can be changed by modifying the <String> </String>
below that.
<key>CFBundleName</key>
<string>YouAppName</string>
That’s it. By having these changes, That’s achieved, an updated application name in the launcher when an app gets installed on a device. your new app name will be displayed on your phone now.
If you use UPPER(text)
, the like '%lah%'
will always return zero results. Use '%LAH%'
.
In my case, I used a button to show the modal
<button type="button" class="btn btn-success" style="color:white"
data-toggle="modal" data-target="#my-modal-to-show" >
<i class="fas fa-plus"></i> Call MODAL
</button>
So in my code, to close the modal (that has the id = 'my-modal-to-show') I call that function (in Angular typescript):
closeById(modalId: string) {
$(modalId).modal('toggle');
$(modalId+ ' .close').click();
}
If I call $(modalId).modal('hide') it does't work and I don't know why
PS.: in my modal I coded that button element with .close class too
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
How about this? Again, using indices
> m <- c(1:5)
> m
[1] 1 2 3 4 5
> m[1:length(m)-1]
[1] 1 2 3 4
or
> m[-(length(m))]
[1] 1 2 3 4
Check your terminal it happen only when you have your application running on another terminal..
The port is already listening..
Commands from tips below wrapped as batch script. Save this as unpack.bat. Then place it to dir with jdk/jre extracted files.
@echo off
cd /d "%~dp0"
for /r %%x in (*.pack) do .\bin\unpack200 -r "%%x" "%%~dx%%~px%%~nx.jar"
I found code which converts the json string to NSDictionary or NSArray. Just add the extension.
SWIFT 3.0
HOW TO USE
let jsonData = (convertedJsonString as! String).parseJSONString
EXTENSION
extension String
{
var parseJSONString: AnyObject?
{
let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false)
if let jsonData = data
{
// Will return an object or nil if JSON decoding fails
do
{
let message = try JSONSerialization.jsonObject(with: jsonData, options:.mutableContainers)
if let jsonResult = message as? NSMutableArray {
return jsonResult //Will return the json array output
} else if let jsonResult = message as? NSMutableDictionary {
return jsonResult //Will return the json dictionary output
} else {
return nil
}
}
catch let error as NSError
{
print("An error occurred: \(error)")
return nil
}
}
else
{
// Lossless conversion of the string was not possible
return nil
}
}
}
For safe execution of code, use if-let
block with Data
to prevent app crash & , as function UIImagePNGRepresentation
returns an optional value.
if let img = UIImage(named: "TestImage.png") {
if let data:Data = UIImagePNGRepresentation(img) {
// Handle operations with data here...
}
}
Note: Data is Swift 3+ class. Use Data instead of NSData with Swift 3+
Generic image operations (like png & jpg both):
if let img = UIImage(named: "TestImage.png") { //UIImage(named: "TestImage.jpg")
if let data:Data = UIImagePNGRepresentation(img) {
handleOperationWithData(data: data)
} else if let data:Data = UIImageJPEGRepresentation(img, 1.0) {
handleOperationWithData(data: data)
}
}
*******
func handleOperationWithData(data: Data) {
// Handle operations with data here...
if let image = UIImage(data: data) {
// Use image...
}
}
By using extension:
extension UIImage {
var pngRepresentationData: Data? {
return UIImagePNGRepresentation(self)
}
var jpegRepresentationData: Data? {
return UIImageJPEGRepresentation(self, 1.0)
}
}
*******
if let img = UIImage(named: "TestImage.png") { //UIImage(named: "TestImage.jpg")
if let data = img.pngRepresentationData {
handleOperationWithData(data: data)
} else if let data = img.jpegRepresentationData {
handleOperationWithData(data: data)
}
}
*******
func handleOperationWithData(data: Data) {
// Handle operations with data here...
if let image = UIImage(data: data) {
// Use image...
}
}
If a function does not return anything, e.g.:
def test():
pass
it has an implicit return value of None
.
Thus, as your pick*
methods do not return anything, e.g.:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
the lines that call them, e.g.:
word = pickEasy()
set word
to None
, so wordInput
in getInput
is None
. This means that:
if guess in wordInput:
is the equivalent of:
if guess in None:
and None
is an instance of NoneType
which does not provide iterator/iteration functionality, so you get that type error.
The fix is to add the return type:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
return word
Yes, Java SE is where to start. All the tasks you mention can be handled with it.
Java ME is the Mobile Edition, and EE is Enterprise Edition; these are specialized / extended versions of Standard Edition.
You can check elasticsearch cluster health by using (CURL) and Cluster API provieded by elasticsearch:
$ curl -XGET 'localhost:9200/_cluster/health?pretty'
This will give you the status and other related data you need.
{
"cluster_name" : "xxxxxxxx",
"status" : "green",
"timed_out" : false,
"number_of_nodes" : 2,
"number_of_data_nodes" : 2,
"active_primary_shards" : 15,
"active_shards" : 12,
"relocating_shards" : 0,
"initializing_shards" : 0,
"unassigned_shards" : 0,
"delayed_unassigned_shards" : 0,
"number_of_pending_tasks" : 0,
"number_of_in_flight_fetch" : 0
}
What I did is first check what are the running processes by
SELECT * FROM pg_stat_activity WHERE state = 'active';
Find the process you want to kill, then type:
SELECT pg_cancel_backend(<pid of the process>)
This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.
If the process cannot be killed, try:
SELECT pg_terminate_backend(<pid of the process>)
Updating Warpzit's answer for Android Studio 1.3.2 (differences in bold)
(update: appears to be the same for Android 2.0)
Open settings.gradle (find in root) and add (or verify this is included):
include ':app', ':volley'
Now go to your build.gradle in your project and add the dependency:
compile project(":volley")
var objDiv = document.getElementById("divExample");
objDiv.scrollTop = objDiv.scrollHeight;
You may have to use urlencode on the string 'http://google.com/?var=234&key=234'
It's actually much easier with jQuery's promise API:
$.ajax(
type: "GET",
url: requestURL,
).then((success) =>
console.dir(success)
).failure((failureResponse) =>
console.dir(failureResponse)
)
Alternatively, you can pass in of bind
functions to each result callback; the order of parameters is: (success, failure)
. So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:
$.ajax(
type: "GET",
url: @get("url") + "logout",
beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
).failure((response) -> console.log "Request was unauthorized" if response.status is 401
I had a slightly different flavor of the same problem with the following requirements:
I've combined and tweaked previous answers to come up with the following:
import subprocess
from time import sleep
def run_command(command):
p = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
# Read stdout from subprocess until the buffer is empty !
for line in iter(p.stdout.readline, b''):
if line: # Don't print blank lines
yield line
# This ensures the process has completed, AND sets the 'returncode' attr
while p.poll() is None:
sleep(.1) #Don't waste CPU-cycles
# Empty STDERR buffer
err = p.stderr.read()
if p.returncode != 0:
# The run_command() function is responsible for logging STDERR
print("Error: " + str(err))
This code would be executed the same as previous answers:
for line in run_command(cmd):
print(line)
If you want to revert the file to its state in master
:
git checkout origin/master [filename]
Just right click on a table and select "backup". The popup will show various options, including "Format", select "plain" and you get plain SQL.
pgAdmin is just using pg_dump to create the dump, also when you want plain SQL.
It uses something like this:
pg_dump --user user --password --format=plain --table=tablename --inserts --attribute-inserts etc.
This is the shortest command I could find that does the job:
ps -ax | awk '/[t]he_app_name/{print $1}'
Putting brackets around the first letter stops awk from finding the awk process itself.
This happened to me when I tried to install a newer version of PHP
. After finding that I also would need to reconfigure Apache for that I switched back to the old PHP version. Here the solution which worked for me:
change the httpd.conf to the correct versions:
PHPIniDir ...
LoadModule php5_module ...
Changed the
PATH - Environment Variable
When that does not take any effect
rename or delete the new PHP(-Version)-Folder
For some reason the last step did the trick for me. Even after a restart it did not have an effect before doing this.
You're using the ajax function incorrectly. Since it's synchronous it'll return the data inline like so:
var remote = $.ajax({
type: "GET",
url: remote_url,
async: false
}).responseText;
var tooLong = document.getElementById("longText").value;
if (tooLong.length() > 18){
$('#longText').css('text-overflow', 'ellipsis');
}
The way I understand it is that they are subtly different by design (and I am certainly open for correction): filter(A, B)
will first filter according to A and then subfilter according to B, while filter(A).filter(B)
will return a row that matches A 'and' a potentially different row that matches B.
Look at the example here:
https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships
particularly:
Everything inside a single filter() call is applied simultaneously to filter out items matching all those requirements. Successive filter() calls further restrict the set of objects
...
In this second example (filter(A).filter(B)), the first filter restricted the queryset to (A). The second filter restricted the set of blogs further to those that are also (B). The entries select by the second filter may or may not be the same as the entries in the first filter.`
If you have the flutter SDK installed.
Run:
flutter doctor -v
The first line will show the install path..
(if you don't have it installed go to the documentation)
I guess you'll need absolute position
.vertical_banner {position:relative;}
#bottom_link{position:absolute; bottom:0;}
The answer is amp#13; — change "amp" to the ampersand sign and go.
Let's say you have these lines of code:
test line one
test line two
test line three
test line four
Using Search and Replace Ctrl+H with Regex let's find this: ^
and replace it with "
, we'll have this:
"test line one
"test line two
"test line three
"test line four
Now let's search this: $
and replace it with "
, now we'll have this:
"test line one"
"test line two"
"test line three"
"test line four"
Using document.body.innerHTML = '';
does work! Just saying, if using HTML
(DOM
or on function
) you can usedocument.writeln('');
but only onClick
or onDoubleClick
:)
I'd re-iterate Donny V. answer and Josh's
"The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support."
(and upvote if I had the reputation.)
I can't remember the last time if ever, I was grateful of the fact HttpWebRequest threw exceptions for status codes >= 400. To get around these issues you need to catch the exceptions immediately, and map them to some non-exception response mechanisms in your code...boring, tedious and error prone in itself. Whether it be communicating with a database, or implementing a bespoke web proxy, its 'nearly' always desirable that the Http driver just tell your application code what was returned, and leave it up to you to decide how to behave.
Hence HttpClient is preferable.
The main important difference between the forward() and sendRedirect() method is that in case of forward(), redirect happens at server end and not visible to client, but in case of sendRedirect(), redirection happens at client end and it's visible to client.
DateTime.Now.ToString("HH:mm:ss tt");
this gives it to you as a string.
I would recommend using Properties.Settings to store values like ConnectionStrings and so on inside of the class library. This is where all the connection strings are stores in by suggestion from visual studio when you try to add a table adapter for example. enter image description here
And then they will be accessible by using this code every where in the clas library
var cs= Properties.Settings.Default.[<name of defined setting>];
I got the same error and it turned out I was in the wrong directory. It's a simple mistake to make so double check that you are in the root and then run heroku create
and heroku git push master
again. Of course you must have done git init
, as mentioned in StickMaNX answer above, already before the heroku steps.
Here's a quick little reusable directive that seems to do what you're looking to do. I've simply called it checkList
. It updates the array when the checkboxes change, and updates the checkboxes when the array changes.
app.directive('checkList', function() {
return {
scope: {
list: '=checkList',
value: '@'
},
link: function(scope, elem, attrs) {
var handler = function(setup) {
var checked = elem.prop('checked');
var index = scope.list.indexOf(scope.value);
if (checked && index == -1) {
if (setup) elem.prop('checked', false);
else scope.list.push(scope.value);
} else if (!checked && index != -1) {
if (setup) elem.prop('checked', true);
else scope.list.splice(index, 1);
}
};
var setupHandler = handler.bind(null, true);
var changeHandler = handler.bind(null, false);
elem.bind('change', function() {
scope.$apply(changeHandler);
});
scope.$watch('list', setupHandler, true);
}
};
});
Here's a controller and a view that shows how you might go about using it.
<div ng-app="myApp" ng-controller='MainController'>
<span ng-repeat="fruit in fruits">
<input type='checkbox' value="{{fruit}}" check-list='checked_fruits'> {{fruit}}<br />
</span>
<div>The following fruits are checked: {{checked_fruits | json}}</div>
<div>Add fruit to the array manually:
<button ng-repeat="fruit in fruits" ng-click='addFruit(fruit)'>{{fruit}}</button>
</div>
</div>
app.controller('MainController', function($scope) {
$scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];
$scope.checked_fruits = ['apple', 'pear'];
$scope.addFruit = function(fruit) {
if ($scope.checked_fruits.indexOf(fruit) != -1) return;
$scope.checked_fruits.push(fruit);
};
});
(The buttons demonstrate that changing the array will also update the checkboxes.)
Finally, here is an example of the directive in action on Plunker: http://plnkr.co/edit/3YNLsyoG4PIBW6Kj7dRK?p=preview
BufferedWriter is more efficient. It saves up small writes and writes in one larger chunk if memory serves me correctly. If you are doing lots of small writes then I would use BufferedWriter. Calling write calls to the OS which is slow so having as few writes as possible is usually desirable.
We can also convert data.frame columns generically to a simple vector. as.vector
is not enough as it retains the data.frame class and structure, so we also have to pull out the first (and only) element:
df_column_object <- aframe[,2]
simple_column <- df_column_object[[1]]
All the solutions suggested so far require hardcoding column titles. This makes them non-generic (imagine applying this to function arguments).
Alternatively, you could, of course read the column names from the column first and then insert them in the code in the other solutions.
Use SHA256
. It is not perfect, as SHA512
would be ideal for a fast hash, but out of the options, its the definite choice. As per any hashing technology, be sure to salt the hash for added security.
As an added note, FRKT, please show me where someone can easily crack a salted SHA256 hash? I am truly very interested to see this.
Moving forward please use bcrypt
as a hardened hash. More information can be found here.
Edit on Salting:
Use a random number, or random byte stream etc. You can use the unique field of the record in your database as the salt too, this way the salt is different per user.
You can use DISTINCT
like that
mysql_query("SELECT DISTINCT(ticket_id), column1, column2, column3
FROM temp_tickets
ORDER BY ticket_id");
As of Git for Windows v2.15.0 (October 30th 2017) it is now possible to configure nano
or Notepad++ as Git's default editor instead of vim
.
During the installation you'll see the following screen:
My general lazy CSS rule:
.background{
width:100%;
height:auto;
background: url('yoururl.jpg') no-repeat center;
background-position: 50% 50%;
background-size: 100% cover!important;
overflow:hidden;
}
This may zoom in on your image if it is low-res to begin with (that's to do with your image quality and size in dimensions. To center your image, you may also try (in the CSS)
display:block;
margin: auto 0;
to center your image
in your HTML:
<div class="background"></div>
The solution you will use really depends on how long you need to wait between each execution of your function.
If you are waiting for longer than 10 minutes, I would suggest using AlarmManager
.
// Some time when you want to run
Date when = new Date(System.currentTimeMillis());
try {
Intent someIntent = new Intent(someContext, MyReceiver.class); // intent to be launched
// Note: this could be getActivity if you want to launch an activity
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
0, // id (optional)
someIntent, // intent to launch
PendingIntent.FLAG_CANCEL_CURRENT // PendingIntent flag
);
AlarmManager alarms = (AlarmManager) context.getSystemService(
Context.ALARM_SERVICE
);
alarms.setRepeating(
AlarmManager.RTC_WAKEUP,
when.getTime(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent
);
} catch(Exception e) {
e.printStackTrace();
}
Once you have broadcasted the above Intent
, you can receive your Intent
by implementing a BroadcastReceiver
. Note that this will need to be registered either in your application manifest or via the context.registerReceiver(receiver, intentFilter);
method. For more information on BroadcastReceiver
's please refer to the official documentation..
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent)
{
System.out.println("MyReceiver: here!") // Do your work here
}
}
If you are waiting for shorter than 10 minutes then I would suggest using a Handler
.
final Handler handler = new Handler();
final int delay = 1000; // 1000 milliseconds == 1 second
handler.postDelayed(new Runnable() {
public void run() {
System.out.println("myHandler: here!"); // Do your work here
handler.postDelayed(this, delay);
}
}, delay);
The below actually works very well.
private void networkInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
var _open = false;
FormCollection fc = Application.OpenForms;
foreach (Form frm in fc)
{
if (frm.Name == "FormBrowseNetworkInformation")
{
_open = true;
frm.Select();
break;
}
}
if (_open == false)
{
var formBrowseNetworkInformation = new FormBrowseNetworkInformation();
formBrowseNetworkInformation.Show();
}
}
In short \r has ASCII value 13 (CR) and \n has ASCII value 10 (LF). Mac uses CR as line delimiter (at least, it did before, I am not sure for modern macs), *nix uses LF and Windows uses both (CRLF).
<?php
// Example 1 [Merging associative arrays. When two or more arrays have same key
// then the last array key value overrides the others one]
$array1 = array("a" => "JAVA", "b" => "ASP");
$array2 = array("c" => "C", "b" => "PHP");
echo " <br> Example 1 Output: <br>";
print_r(array_merge($array1,$array2));
// Example 2 [When you want to merge arrays having integer keys and
//want to reset integer keys to start from 0 then use array_merge() function]
$array3 =array(5 => "CSS",6 => "CSS3");
$array4 =array(8 => "JAVASCRIPT",9 => "HTML");
echo " <br> Example 2 Output: <br>";
print_r(array_merge($array3,$array4));
// Example 3 [When you want to merge arrays having integer keys and
// want to retain integer keys as it is then use PLUS (+) operator to merge arrays]
$array5 =array(5 => "CSS",6 => "CSS3");
$array6 =array(8 => "JAVASCRIPT",9 => "HTML");
echo " <br> Example 3 Output: <br>";
print_r($array5+$array6);
// Example 4 [When single array pass to array_merge having integer keys
// then the array return by array_merge have integer keys starting from 0]
$array7 =array(3 => "CSS",4 => "CSS3");
echo " <br> Example 4 Output: <br>";
print_r(array_merge($array7));
?>
Output:
Example 1 Output:
Array
(
[a] => JAVA
[b] => PHP
[c] => C
)
Example 2 Output:
Array
(
[0] => CSS
[1] => CSS3
[2] => JAVASCRIPT
[3] => HTML
)
Example 3 Output:
Array
(
[5] => CSS
[6] => CSS3
[8] => JAVASCRIPT
[9] => HTML
)
Example 4 Output:
Array
(
[0] => CSS
[1] => CSS3
)
Bootstrap 3
Here is a working left sidebar example:
http://bootply.com/90936 (similar to the Bootstrap docs)
The trick is using the affix
component along with some CSS to position it:
#sidebar.affix-top {
position: static;
margin-top:30px;
width:228px;
}
#sidebar.affix {
position: fixed;
top:70px;
width:228px;
}
EDIT- Another example with footer and affix-bottom
Bootstrap 4
The Affix component has been removed in Bootstrap 4, so to create a sticky sidebar, you can use a 3rd party Affix plugin like this Bootstrap 4 sticky sidebar example, or use the sticky-top
class is explained in this answer.
Related: Create a responsive navbar sidebar "drawer" in Bootstrap 4?
OR operator can be alternative of case when in where condition
ALTER PROCEDURE [dbo].[RPT_340bClinicDrugInventorySummary]
-- Add the parameters for the stored procedure here
@ClinicId BIGINT = 0,
@selecttype int,
@selectedValue varchar (50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT
drugstock_drugname.n_cur_bal,drugname.cdrugname,clinic.cclinicname
FROM drugstock_drugname
INNER JOIN drugname ON drugstock_drugname.drugnameid_FK = drugname.drugnameid_PK
INNER JOIN drugstock_drugndc ON drugname.drugnameid_PK = drugstock_drugndc.drugnameid_FK
INNER JOIN drugndc ON drugstock_drugndc.drugndcid_FK = drugndc.drugid_PK
LEFT JOIN clinic ON drugstock_drugname.clinicid_FK = clinic.clinicid_PK
WHERE (@ClinicId = 0 AND 1 = 1)
OR (@ClinicId != 0 AND drugstock_drugname.clinicid_FK = @ClinicId)
-- Alternative Case When You can use OR
AND ((@selecttype = 1 AND 1 = 1)
OR (@selecttype = 2 AND drugname.drugnameid_PK = @selectedValue)
OR (@selecttype = 3 AND drugndc.drugid_PK = @selectedValue)
OR (@selecttype = 4 AND drugname.cdrugclass = 'C2')
OR (@selecttype = 5 AND LEFT(drugname.cdrugclass, 1) = 'C'))
ORDER BY clinic.cclinicname, drugname.cdrugname
END
from http://www.coderanch.com/t/361868/Servlets/java/request-getParameter-request-getAttribute
A "parameter" is a name/value pair sent from the client to the server - typically, from an HTML form. Parameters can only have String values. Sometimes (e.g. using a GET request) you will see these encoded directly into the URL (after the ?, each in the form name=value, and each pair separated by an &). Other times, they are included in the body of the request, when using methods such as POST.
An "attribute" is a server-local storage mechanism - nothing stored in scoped attribues is ever transmitted outside the server unless you explicitly make that happen. Attributes have String names, but store Object values. Note that attributes are specific to Java (they store Java Objects), while parameters are platform-independent (they are only formatted strings composed of generic bytes).
There are four scopes of attributes in total: "page" (for JSPs and tag files only), "request" (limited to the current client's request, destroyed after request is completed), "session" (stored in the client's session, invalidated after the session is terminated), "application" (exist for all components to access during the entire deployed lifetime of your application).
The bottom line is: use parameters when obtaining data from the client, use scoped attributes when storing objects on the server for use internally by your application only.
Like @itsneo said, I personally find ? + [ and ] the most convenient ones on a mac. But I can understand if you come from Linux side of things. Then you can use ? + alt + ? or ?.
Here's a solution:
dates <- c("14.01.2013", "26.03.2014")
# Date format:
dates2 <- strptime(dates, format = "%d.%m.%Y")
dif <- diff(as.numeric(dates2)) # difference in seconds
dif/(60 * 60 * 24 * 7) # weeks
[1] 62.28571
dif/(60 * 60 * 24 * 30) # months
[1] 14.53333
dif/(60 * 60 * 24 * 30 * 3) # quartes
[1] 4.844444
dif/(60 * 60 * 24 * 365) # years
[1] 1.194521
In my opinion, interface has a broader meaning than the one commonly associated with it in Java. I would define "interface" as a set of available operations with some common functionality, that allow controlling/monitoring a module.
In this definition I try to cover both programatic interfaces, where the client is some module, and human interfaces (GUI for example).
As others already said, an interface always has some contract behind it, in terms of inputs and outputs. The interface does not promise anything about the "how" of the operations; it only guarantees some properties of the outcome, given the current state, the selected operation and its parameters.
var data =" Retrieves a substring from this instance. The substring starts at a specified character position.";
var result = data.Split(new[] {'.'}, 1)[0];
Output:
Retrieves a substring from this instance. The substring starts at a specified character position.
That's strange, it definitely works for me:
from matplotlib import pyplot as plt
plt.figure(figsize = (20,2))
plt.imshow(random.rand(8, 90), interpolation='nearest')
I am using the "MacOSX" backend, btw.
In my case
new Date("20151102034013".replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/, "$1-$2-$3T$4:$5:$6"))
Result: Mon Nov 02 2015 04:40:13 GMT+0100 (CET) then I use .getTime() to work with milliseconds
Thanks to @pgregory, I could resolve my problem using this directive for inline editing
.directive("superEdit", function($compile){
return{
link: function(scope, element, attrs){
var colName = attrs["superEdit"];
alert(colName);
scope.getContentUrl = function() {
if (colName == 'Something') {
return 'app/correction/templates/lov-edit.html';
}else {
return 'app/correction/templates/simple-edit.html';
}
}
var template = '<div ng-include="getContentUrl()"></div>';
var linkFn = $compile(template);
var content = linkFn(scope);
element.append(content);
}
}
})