You can also use order_by method with fluent and eloquent like as:
Posts::where_status(1)->order_by(DB::raw(''),DB::raw('RAND()'));
This is a little bit weird usage, but works.
Edit: As @Alex said, this usage is cleaner and also works:
Posts::where_status(1)->order_by(DB::raw('RAND()'));
You can use an array in the select() to define more columns and you can use the DB::raw() there with aliasing it to followers. Should look like this:
$query = DB::table('category_issue')
->select(array('issues.*', DB::raw('COUNT(issue_subscriptions.issue_id) as followers')))
->where('category_id', '=', 1)
->join('issues', 'category_issue.issue_id', '=', 'issues.id')
->left_join('issue_subscriptions', 'issues.id', '=', 'issue_subscriptions.issue_id')
->group_by('issues.id')
->order_by('followers', 'desc')
->get();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date(); System.out.println(dateFormat.format(date)); //2014/08/06 15:59:4
If you just want to get your HDFS back to normal state and don't worry much about the data, then
This will list the corrupt HDFS blocks:
hdfs fsck -list-corruptfileblocks
This will delete the corrupted HDFS blocks:
hdfs fsck / -delete
Note that, you might have to use sudo -u hdfs
if you are not the sudo user (assuming "hdfs" is name of the sudo user)
If you also want the values you can use the inspect
module
import inspect
def func(a, b, c):
frame = inspect.currentframe()
args, _, _, values = inspect.getargvalues(frame)
print 'function name "%s"' % inspect.getframeinfo(frame)[2]
for i in args:
print " %s = %s" % (i, values[i])
return [(i, values[i]) for i in args]
>>> func(1, 2, 3)
function name "func"
a = 1
b = 2
c = 3
[('a', 1), ('b', 2), ('c', 3)]
If you want to kill the Sticky Service,the following command NOT WORKING:
adb shell am force-stop <PACKAGE>
adb shell kill <PID>
The following command is WORKING:
adb shell pm disable <PACKAGE>
If you want to restart the app,you must run command below first:
adb shell pm enable <PACKAGE>
def expiration_time():
import datetime,calendar
timestamp = calendar.timegm(datetime.datetime.now().timetuple())
returnValue = datetime.timedelta(minutes=5).total_seconds() + timestamp
return returnValue
To update the local list of remote branches:
git remote update origin --prune
To show all local and remote branches that (local) Git knows about
git branch -a
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> items, int maxItems)
{
return items.Select((item, index) => new { item, index })
.GroupBy(x => x.index / maxItems)
.Select(g => g.Select(x => x.item));
}
Your code sample didn't expand on part of your topic, namely symbols, and so that part of the question went unanswered.
If you have two strings, foo and bar, and both can be either a string or a symbol, you can test equality with
foo.to_s == bar.to_s
It's a little more efficient to skip the string conversions on operands with known type. So if foo is always a string
foo == bar.to_s
But the efficiency gain is almost certainly not worth demanding any extra work on behalf of the caller.
Prior to Ruby 2.2, avoid interning uncontrolled input strings for the purpose of comparison (with strings or symbols), because symbols are not garbage collected, and so you can open yourself to denial of service through resource exhaustion. Limit your use of symbols to values you control, i.e. literals in your code, and trusted configuration properties.
Ruby 2.2 introduced garbage collection of symbols.
className
is just a string so you can use the regular indexOf function to see if the list of classes contains another string.
You need to know at least basics of Objective-C to develop for iPhone. However, it is possible to use C++ classes.
As far as I know Adobe is working on building Flex/Flash applications for iPhone. Read more here: http://theflashblog.com/?p=1513
If you want to stay with underscore so your predicate function can be more flexible, here are 2 ideas.
Since the predicate for _.find
receives both the value and index of an element, you can use side effect to retrieve the index, like this:
var idx;
_.find(tv, function(voteItem, voteIdx){
if(voteItem.id == voteID){ idx = voteIdx; return true;};
});
Looking at underscore source, this is how _.find
is implemented:
_.find = _.detect = function(obj, predicate, context) {
var result;
any(obj, function(value, index, list) {
if (predicate.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
To make this a findIndex
function, simply replace the line result = value;
with result = index;
This is the same idea as the first method. I included it to point out that underscore uses side effect to implement _.find
as well.
I've taken elindeblom's solution and modified it - the use of strings (even if cast to dates) makes me nervous for the different formats of dates used around the world. This avoids that issue.
While not requested, I've also included time so the week ends 1 second before midnight:
DECLARE @WeekNum INT = 12,
@YearNum INT = 2014 ;
SELECT DATEADD(wk,
DATEDIFF(wk, 6,
CAST(RTRIM(@YearNum * 10000 + 1 * 100 + 1) AS DATETIME))
+ ( @WeekNum - 1 ), 6) AS [start_of_week],
DATEADD(second, -1,
DATEADD(day,
DATEDIFF(day, 0,
DATEADD(wk,
DATEDIFF(wk, 5,
CAST(RTRIM(@YearNum * 10000
+ 1 * 100 + 1) AS DATETIME))
+ ( @WeekNum + -1 ), 5)) + 1, 0)) AS [end_of_week] ;
Yes, I know I'm still casting but from a number. It "feels" safer to me.
This results in:
start_of_week end_of_week
----------------------- -----------------------
2014-03-16 00:00:00.000 2014-03-22 23:59:59.000
This is the simplest method you can do and reduce your efforts. just paste this function in your class and call it anywhere:
you can do this by creating a substring.
simple exampe is here:
public static String removeTillWord(String input, String word) {
return input.substring(input.indexOf(word));
}
removeTillWord("Your String", "\");
_x000D_
Use \overleftarrow
to create a long arrow to the left.
\overleftarrow{blahblahblah}
The recommended way to create random integers with NumPy these days is to use numpy.random.Generator.integers
. (documentation)
import numpy as np
import pandas as pd
rng = np.random.default_rng()
df = pd.DataFrame(rng.integers(0, 100, size=(100, 4)), columns=list('ABCD'))
df
----------------------
A B C D
0 58 96 82 24
1 21 3 35 36
2 67 79 22 78
3 81 65 77 94
4 73 6 70 96
... ... ... ... ...
95 76 32 28 51
96 33 68 54 77
97 76 43 57 43
98 34 64 12 57
99 81 77 32 50
100 rows × 4 columns
In general I added the private Object _ temporarily to the object. You have to open the privacy exlipcitly in the "Power-constructor" for the method. If you call the method from the prototype, you will be able to overwrite the prototype-method
Make a public method accessible in the "Power-constructor": (ctx is the object context)
ctx.test = GD.Fabric.open('test', GD.Test.prototype, ctx, _); // is a private object
Now I have this openPrivacy:
GD.Fabric.openPrivacy = function(func, clss, ctx, _) {
return function() {
ctx._ = _;
var res = clss[func].apply(ctx, arguments);
ctx._ = null;
return res;
};
};
If you are in ES6 just use the "static" keyword on your method from your example would be the following: static alertMessage: function() {
...
},
Hope can help anyone out there :)
Let us call the sample code posted here the redirector and the other program the redirected. If it were me then I would probably write a test redirected program that can be used to duplicate the problem.
So I did. For test data I used the ECMA-334 C# Language Specificationv PDF; it is about 5MB. The following is the important part of that.
StreamReader stream = null;
try { stream = new StreamReader(Path); }
catch (Exception ex)
{
Console.Error.WriteLine("Input open error: " + ex.Message);
return;
}
Console.SetIn(stream);
int datasize = 0;
try
{
string record = Console.ReadLine();
while (record != null)
{
datasize += record.Length + 2;
record = Console.ReadLine();
Console.WriteLine(record);
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error: {ex.Message}");
return;
}
The datasize value does not match the actual file size but that does not matter. It is not clear if a PDF file always uses both CR and LF at the end of lines but that does not matter for this. You can use any other large text file to test with.
Using that the sample redirector code hangs when I write the large amount of data but not when I write a small amount.
I tried very much to somehow trace the execution of that code and I could not. I commented out the lines of the redirected program that disabled creation of a console for the redirected program to try to get a separate console window but I could not.
Then I found How to start a console app in a new window, the parent’s window, or no window. So apparently we cannot (easily) have a separate console when one console program starts another console program without ShellExecute and since ShellExecute does not support redirection we must share a console, even if we specify no window for the other process.
I assume that if the redirected program fills up a buffer somewhere then it must wait for the data to be read and if at that point no data is read by the redirector then it is a deadlock.
The solution is to not use ReadToEnd and to read the data while the data is being written but it is not necessary to use asynchronous reads. The solution can be quite simple. The following works for me with the 5 MB PDF.
ProcessStartInfo info = new ProcessStartInfo(TheProgram);
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
Process p = Process.Start(info);
string record = p.StandardOutput.ReadLine();
while (record != null)
{
Console.WriteLine(record);
record = p.StandardOutput.ReadLine();
}
p.WaitForExit();
Another possibility is to use a GUI program to do the redirection. The preceding code works in a WPF application except with obvious modifications.
I know this is an old question but I want to share an example that I think explains bounded wildcards pretty well. java.util.Collections
offers this method:
public static <T> void sort(List<T> list, Comparator<? super T> c) {
list.sort(c);
}
If we have a List of T
, the List can, of course, contain instances of types that extend T
. If the List contains Animals, the List can contain both Dogs and Cats (both Animals). Dogs have a property "woofVolume" and Cats have a property "meowVolume." While we might like to sort based upon these properties particular to subclasses of T
, how can we expect this method to do that? A limitation of Comparator is that it can compare only two things of only one type (T
). So, requiring simply a Comparator<T>
would make this method usable. But, the creator of this method recognized that if something is a T
, then it is also an instance of the superclasses of T
. Therefore, he allows us to use a Comparator of T
or any superclass of T
, i.e. ? super T
.
Use localhost
instead of your IP address.
e.g,
$myServer = "localhost";
And also double check your mysql username and password.
for mysql 'text':
@Column(columnDefinition = "TEXT")
private String description;
for mysql 'longtext':
@Lob
private String description;
There is one property in mysql configuration file under section [mysqld]
with name - tmpdir
for example:
tmpdir = c:/temp (Windows) or tmpdir = /tmp (Linux)
and LOAD DATA INFILE
command can perform read and write on this location only.
so if you put your file at that specified location then LOAD DATA INFILE
can read/write any file easily.
One more solution
we can import data by following command too
load data local infile
In this case there is no need to move file to tmpdir, you can give the absolute path of file, but to execute this command, you need to change one flag value. The flag is
--local-infile
you can change its value by command prompt while getting access of mysql
mysql -u username -p --local-infile=1
Cheers
You can also use below mentioned code
Response.Write("<script type='text/javascript'>"); Response.Write("window.location = '" + redirect url + "'</script>");Response.Flush();
Now the plugin is Multi Line tricks. The end and start buttons broke the selection.
We can use summary
on factor column:
summary(myDF$factorColumn)
You need to use the __getitem__
method.
class MyClass:
def __getitem__(self, key):
return key * 2
myobj = MyClass()
myobj[3] #Output: 6
And if you're going to be setting values you'll need to implement the __setitem__
method too, otherwise this will happen:
>>> myobj[5] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'
You should validate your JSON string here.
A valid JSON string must have double quotes around the keys:
JSON.parse({"u1":1000,"u2":1100}) // will be ok
If there are no quotes, it will cause an error:
JSON.parse({u1:1000,u2:1100})
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2
Using single quotes will also cause an error:
JSON.parse({'u1':1000,'u2':1100})
// error Uncaught SyntaxError: Unexpected token ' in JSON at position 1
Try using the BackgroundWorker class. You give it delegates for what to run, and to be notified when work has finished. There is an example on the MSDN page that I linked to.
I have a page it loads an HTML body from MYSQL I want to present that code in a frame so it renders it self independent of the rest of the page and in the confines of that specific bordering.
An object
with a unencoded dataUri might have also fit your need if it was only to load a portion of data text:
The HTML
<object>
element represents an external resource, which can be treated as an image, a nested browsing context, or a resource to be handled by a plugin.
body {display:flex;min-height:25em;}
p {margin:auto;}
object {margin:0 auto;background:lightgray;}
_x000D_
<p>here My uploaded content: </p>
<object data='data:text/html,
<style>
.table {
display: table;
text-align:center;
width:100%;
height:100%;
}
.table > * {
display: table-row;
}
.table > main {
display: table-cell;
height: 100%;
vertical-align: middle;
}
</style>
<div class="table">
<header>
<h1>Title</h1>
<p>subTitle</p>
</header>
<main>
<p>Collection</p>
<p>Version</p>
<p>Id</p>
</main>
<footer>
<p>Edition</p>
</footer>'>
</object>
_x000D_
But keeping your Iframe idea, You could also load your HTML inside your iframe tag and set it as the srcdoc value.You should not have to mind about quotes nor turning it into a dataUri but only mind to fire onload once.
The HTML Inline Frame element (
<iframe>
) represents a nested browsing context, embedding another HTML page into the current one.
Both iframe below will render the same, one require extra javascript.
example loading a full document :
body {
display: flex;
min-height: 25em;
}
p {
margin: auto;
}
iframe {
margin: 0 auto;
min-height: 100%;
background:lightgray;
}
_x000D_
<p>here my uploaded contents =>:</p>
<iframe srcdoc='<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
html, body {
height: 100%;
margin:0;
}
body.table {
display: table;
text-align:center;
width:100%;
}
.table > * {
display: table-row;
}
.table > main {
display: table-cell;
height: 100%;
vertical-align: middle;
}
</style>
</head>
<body class="table">
<header>
<h1>title</h1>
<p>injected via <code>srcdoc</code></p>
</header>
<main>
<p>Collection</p>
<p>Version</p>
<p>Id</p>
</main>
<footer>
<p>Edition</p>
</footer>
</body>
</html>'>
</iframe>
<iframe onload="this.setAttribute('srcdoc', this.innerHTML);this.setAttribute('onload','')">
<!-- below html loaded -->
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<style>
html,
body {
height: 100%;
margin: 0;
overflow:auto;
}
body.table {
display: table;
text-align: center;
width: 100%;
}
.table>* {
display: table-row;
}
.table>main {
display: table-cell;
height: 100%;
vertical-align: middle;
}
</style>
</head>
<body class="table">
<header>
<h1>Title</h1>
<p>Injected from <code>innerHTML</code></p>
</header>
<main>
<p>Collection</p>
<p>Version</p>
<p>Id</p>
</main>
<footer>
<p>Edition</p>
</footer>
</body>
</html>
</iframe>
_x000D_
As others said the convenient jQuery prepend functionality can be emulated:
var html = '<div>Hello prepended</div>';
document.body.innerHTML = html + document.body.innerHTML;
While some say it is better not to "mess" with innerHTML, it is reliable in many use cases, if you know this:
If a
<div>
,<span>
, or<noembed>
node has a child text node that includes the characters (&
), (<
), or (>
), innerHTML returns these characters as&
,<
and>
respectively. UseNode.textContent
to get a correct copy of these text nodes' contents.
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
Or:
var html = '<div>Hello prepended</div>';
document.body.insertAdjacentHTML('afterbegin', html)
insertAdjacentHTML
is probably a good alternative: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
PK - Primary Key
NN - Not Null
BIN - Binary (stores data as binary strings. There is no character set so sorting and comparison is based on the numeric values of the bytes in the values.)
UN - Unsigned (non-negative numbers only. so if the range is -500 to 500, instead its 0 - 1000, the range is the same but it starts at 0)
UQ - Create/remove Unique Key
ZF - Zero-Filled (if the length is 5 like INT(5) then every field is filled with 0’s to the 5th digit. 12 = 00012, 400 = 00400, etc. )
AI - Auto Increment
G - Generated column. i.e. value generated by a formula based on the other columns
Try below code
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
android:bottomLeftRadius="30dp"
android:bottomRightRadius="30dp"
android:topLeftRadius="30dp"
android:topRightRadius="30dp" />
<solid android:color="#1271BB" />
<stroke
android:width="5dp"
android:color="#1271BB" />
<padding
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" /></shape>
Vertical alignment doesn't work with floated elements, indeed. That's because float lifts the element from the normal flow of the document. You might want to use other vertical aligning techniques, like the ones based on transform, display: table, absolute positioning, line-height, js (last resort maybe) or even the plain old html table (maybe the first choice if the content is actually tabular). You'll find that there's a heated debate on this issue.
However, this is how you can vertically align YOUR 3 divs:
.wrap{
width: 500px;
overflow:hidden;
background: pink;
}
.left {
width: 150px;
margin-right: 10px;
background: yellow;
display:inline-block;
vertical-align: middle;
}
.left2 {
width: 150px;
margin-right: 10px;
background: aqua;
display:inline-block;
vertical-align: middle;
}
.right{
width: 150px;
background: orange;
display:inline-block;
vertical-align: middle;
}
Not sure why you needed both fixed width, display: inline-block and floating.
To download a directory recursively, which rejects index.html* files and downloads without the hostname, parent directory and the whole directory structure :
wget -r -nH --cut-dirs=2 --no-parent --reject="index.html*" http://mysite.com/dir1/dir2/data
Java 7 support was added at build tools 19. You can now use features like the diamond operator, multi-catch, try-with-resources, strings in switches, etc. Add the following to your build.gradle
.
android {
compileSdkVersion 19
buildToolsVersion "19.0.0"
defaultConfig {
minSdkVersion 7
targetSdkVersion 19
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
Gradle 1.7+, Android gradle plugin 0.6.+ are required.
Note, that only try with resources require minSdkVersion
19. Other features works on previous platforms.
Here are two methods to get more than 1 column in a scalar subquery (or inline subquery) and querying the lookup table only once. This is a bit convoluted but can be the very efficient in some special cases.
You can use concatenation to get several columns at once:
SELECT x,
regexp_substr(yz, '[^^]+', 1, 1) y,
regexp_substr(yz, '[^^]+', 1, 2) z
FROM (SELECT a.x,
(SELECT b.y || '^' || b.z yz
FROM b
WHERE b.v = a.v)
yz
FROM a)
You would need to make sure that no column in the list contain the separator character.
You could also use SQL objects:
CREATE OR REPLACE TYPE b_obj AS OBJECT (y number, z number);
SELECT x,
v.yz.y y,
v.yz.z z
FROM (SELECT a.x,
(SELECT b_obj(y, z) yz
FROM b
WHERE b.v = a.v)
yz
FROM a) v
For Python 2.7, one can easily install using this
apt-get install python2.7-mysqldb
Console.Write((int)response.StatusCode);
HttpStatusCode (the type of response.StatusCode
) is an enumeration where the values of the members match the HTTP status codes, e.g.
public enum HttpStatusCode
{
...
Moved = 301,
OK = 200,
Redirect = 302,
...
}
This way should cover a situation of concurrency when the function is called again while is still executing (and items need used only once):
while (list.Count > 0)
{
string Item = list[0];
list.RemoveAt(0);
// do here what you need to do with item
}
If the function get called while is still executing items will not reiterate from the first again as they get deleted as soon as they get used. Should not affect performance much for small lists.
Something like the following would get you closer
class Clazz
{
public static <U extends Clazz> void doIt(U thing)
{
}
}
EDIT: Updated example with more detail
public abstract class Thingo
{
public static <U extends Thingo> void doIt(U p_thingo)
{
p_thingo.thing();
}
protected abstract void thing();
}
class SubThingoOne extends Thingo
{
@Override
protected void thing()
{
System.out.println("SubThingoOne");
}
}
class SubThingoTwo extends Thingo
{
@Override
protected void thing()
{
System.out.println("SuThingoTwo");
}
}
public class ThingoTest
{
@Test
public void test()
{
Thingo t1 = new SubThingoOne();
Thingo t2 = new SubThingoTwo();
Thingo.doIt(t1);
Thingo.doIt(t2);
// compile error --> Thingo.doIt(new Object());
}
}
I use a small function to verify a variable has been declared, which really cuts down on the amount of clutter in my javascript files. I add a check for the value to make sure that the variable not only exists, but has also been assigned a value. The second condition checks whether the variable has also been instantiated, because if the variable has been defined but not instantiated (see example below), it will still throw an error if you try to reference it's value in your code.
Not instantiated - var my_variable;
Instantiated - var my_variable = "";
function varExists(el) {
if ( typeof el !== "undefined" && typeof el.val() !== "undefined" ) {
return true;
} else {
return false;
}
}
You can then use a conditional statement to test that the variable has been both defined AND instantiated like this...
if ( varExists(variable_name) ) { // checks that it DOES exist }
or to test that it hasn't been defined and instantiated use...
if( !varExists(variable_name) ) { // checks that it DOESN'T exist }
I had exactly the same problem. Just one more working modification of the solution given by Denis (the type must be specified):
SELECT ARRAY(
SELECT column_name::text
FROM information_schema.columns
WHERE table_name='aean'
)
This link contains relevant information on detecting versions of Internet Explorer:
http://tanalin.com/en/articles/ie-version-js/
Example:
if (document.all && !document.addEventListener) {
alert('IE8 or older.');
}
If its in a landscape then you will be needing more width and less height! That's just what all websites have.
Lets go with a basic first then the rest!
The basic CSS:
By CSS you can do this,
#body {
width: 100%;
height: 100%;
}
Here you are using a div with id
body, as:
<body>
<div id="body>
all the text would go here!
</div>
</body>
Then you can have a web page with 100%
height and width.
What if he tries to resize the window?
The issues pops up, what if he tries to resize the window? Then all the elements inside #body
would try to mess up the UI. For that you can write this:
#body {
height: 100%;
width: 100%;
}
And just add min-height
max-height
min-width
and max-width
.
This way, the page element would stay at the place they were at the page load.
Using JavaScript:
Using JavaScript, you can control the UI, use jQuery as:
$('#body').css('min-height', '100%');
And all other remaining CSS properties, and JS will take care of the User Interface when the user is trying to resize the window.
How to not add scroll to the web page:
If you are not trying to add a scroll, then you can use this JS
$('#body').css('min-height', screen.height); // or anyother like window.height
This way, the document will get a new height whenever the user would load the page.
Second option is better, because when users would have different screen resolutions they would want a CSS or Style sheet created for their own screen. Not for others!
Tip: So try using JS to find current Screen size and edit the page! :)
Despite answer from CaioToOn above, I still had problems getting this to work initially.
After multiple attempts, finally got it working. Am pasting my final version here - hoping it will benefit somebody else.
<build>
<plugins>
<!--
Copy all Maven Dependencies (-MD) into libMD/ folder to use in classpath via shellscript
-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<executions>
<execution>
<id>copy</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libMD</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<!--
Above maven-dependepcy-plugin gives a validation error in m2e.
To fix that, add the plugin management step below. Per: http://stackoverflow.com/a/12109018
-->
<pluginManagement>
<plugins>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<versionRange>[2.0,)</versionRange>
<goals>
<goal>copy-dependencies</goal>
</goals>
</pluginExecutionFilter>
<action>
<execute />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
In my case, this error was caused by improper use of "fixture.detectChanges()" It seems this method is an event listener (async) which will only respond a callback when changes are detected. If no changes are detected it will not invoke the callback, resulting in a timeout error. Hope this helps :)
http://www.boutell.com/newfaq/creating/include.html
this would explain how to write your own clientsideinlcude but jQuery is a lot, A LOT easier option ... plus you will gain a lot more by using jQuery anyways
function truncateString(str, length) {
return str.length > length ? str.substring(0, length - 3) + '...' : str
}
TS gets compiled to JS which then executed. Therefore you have access to all of the objects in the JS runtime. One of those objects is the JSON
object. This contains the following methods:
JSON.parse()
method parses a JSON string, constructing the JavaScript value or object described by the string.JSON.stringify()
method converts a JavaScript object or value to a JSON string.Example:
const jsonString = '{"employee":{ "name":"John", "age":30, "city":"New York" }}';_x000D_
_x000D_
_x000D_
const JSobj = JSON.parse(jsonString);_x000D_
_x000D_
console.log(JSobj);_x000D_
console.log(typeof JSobj);_x000D_
_x000D_
const JSON_string = JSON.stringify(JSobj);_x000D_
_x000D_
console.log(JSON_string);_x000D_
console.log(typeof JSON_string);
_x000D_
Try IcoMoon: http://icomoon.io
Say, you picked the play icon, assigned the letter 'P' to it, and downloaded the file icomoon.ttf
to your asset folder. This is how you show the icon:
xml:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="48sp"
android:text="P" />
java:
Typeface typeface = Typeface.createFromAsset(getAssets(), "icomoon.ttf");
textView.setTypeface(typeface);
I've given a talk on making beautiful Android apps, which includes explanation on using icon fonts, plus adding gradients to make the icons even prettier: http://www.sqisland.com/talks/beautiful-android
The icon font explanation starts at slide 34: http://www.sqisland.com/talks/beautiful-android/#34
It's a language abstraction - some languages have both, some one, some neither.
In the case of C++, the code is not run in either the stack or the heap. You can test what happens if you run out of heap memory by repeatingly calling new
to allocate memory in a loop without calling delete
to free it it. But make a system backup before doing this.
Very first will declare outer Arraylist which will contain another inner Arraylist inside it
ArrayList> CompletesystemStatusArrayList; ArrayList systemStatusArrayList
CompletesystemStatusArrayList=new ArrayList
systemStatusArrayList=new ArrayList();
systemStatusArrayList.add("1");
systemStatusArrayList.add("2");
systemStatusArrayList.add("3");
systemStatusArrayList.add("4");
systemStatusArrayList.add("5");
systemStatusArrayList.add("6");
systemStatusArrayList.add("7");
systemStatusArrayList.add("8");
CompletesystemStatusArrayList.add(systemStatusArrayList);
Try the following commands to search the string inside all previous tracked files:
git log --patch | less +/searching_string
or
git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'
which needs to be run from the parent directory where you'd like to do the searching.
Modern async/await way ( Node 12.8.x )
const fileExists = async path => !!(await fs.promises.stat(path).catch(e => false));
const main = async () => {
console.log(await fileExists('/path/myfile.txt'));
}
main();
We need to use fs.stat() or fs.access()
because fs.exists(path, callback)
now is deprecated
Another good way is fs-extra
Does it have to be gray? You could just set the opacity of the image lower (to dull it). Alternatively, you could create a <div>
overlay and set that to be gray (change the alpha to get the effect).
html:
<div id="wrapper">
<img id="myImage" src="something.jpg" />
</div>
css:
#myImage {
opacity: 0.4;
filter: alpha(opacity=40); /* msie */
}
/* or */
#wrapper {
opacity: 0.4;
filter: alpha(opacity=40); /* msie */
background-color: #000;
}
As stated in prior answers - it depends on the answer to "cpu or i/o bound?",
but also to the answer to "threaded or multi-processing?":
Examples run on Raspberry Pi 3B 1.2GHz 4-core with Python3.7.3
--( With other processes running including htop )
Typical Result:
. Starting 4000 cycles of io-bound threading
. Sequential run time: 39.15 seconds
. 4 threads Parallel run time: 18.19 seconds
. 2 threads Parallel - twice run time: 20.61 seconds
Typical Result:
. Starting 1000000 cycles of cpu-only threading
. Sequential run time: 9.39 seconds
. 4 threads Parallel run time: 10.19 seconds
. 2 threads Parallel twice - run time: 9.58 seconds
Typical Result:
. Starting 4000 cycles of io-bound processing
. Sequential - run time: 39.74 seconds
. 4 procs Parallel - run time: 17.68 seconds
. 2 procs Parallel twice - run time: 20.68 seconds
Typical Result:
. Starting 1000000 cycles of cpu-only processing
. Sequential run time: 9.24 seconds
. 4 procs Parallel - run time: 2.59 seconds
. 2 procs Parallel twice - run time: 4.76 seconds
compare_io_multiproc.py:
#!/usr/bin/env python3
# Compare single proc vs multiple procs execution for io bound operation
"""
Typical Result:
Starting 4000 cycles of io-bound processing
Sequential - run time: 39.74 seconds
4 procs Parallel - run time: 17.68 seconds
2 procs Parallel twice - run time: 20.68 seconds
"""
import time
import multiprocessing as mp
# one thousand
cycles = 1 * 1000
def t():
with open('/dev/urandom', 'rb') as f:
for x in range(cycles):
f.read(4 * 65535)
if __name__ == '__main__':
print(" Starting {} cycles of io-bound processing".format(cycles*4))
start_time = time.time()
t()
t()
t()
t()
print(" Sequential - run time: %.2f seconds" % (time.time() - start_time))
# four procs
start_time = time.time()
p1 = mp.Process(target=t)
p2 = mp.Process(target=t)
p3 = mp.Process(target=t)
p4 = mp.Process(target=t)
p1.start()
p2.start()
p3.start()
p4.start()
p1.join()
p2.join()
p3.join()
p4.join()
print(" 4 procs Parallel - run time: %.2f seconds" % (time.time() - start_time))
# two procs
start_time = time.time()
p1 = mp.Process(target=t)
p2 = mp.Process(target=t)
p1.start()
p2.start()
p1.join()
p2.join()
p3 = mp.Process(target=t)
p4 = mp.Process(target=t)
p3.start()
p4.start()
p3.join()
p4.join()
print(" 2 procs Parallel twice - run time: %.2f seconds" % (time.time() - start_time))
compare_cpu_multiproc.py
#!/usr/bin/env python3
# Compare single proc vs multiple procs execution for cpu bound operation
"""
Typical Result:
Starting 1000000 cycles of cpu-only processing
Sequential run time: 9.24 seconds
4 procs Parallel - run time: 2.59 seconds
2 procs Parallel twice - run time: 4.76 seconds
"""
import time
import multiprocessing as mp
# one million
cycles = 1000 * 1000
def t():
for x in range(cycles):
fdivision = cycles / 2.0
fcomparison = (x > fdivision)
faddition = fdivision + 1.0
fsubtract = fdivision - 2.0
fmultiply = fdivision * 2.0
if __name__ == '__main__':
print(" Starting {} cycles of cpu-only processing".format(cycles))
start_time = time.time()
t()
t()
t()
t()
print(" Sequential run time: %.2f seconds" % (time.time() - start_time))
# four procs
start_time = time.time()
p1 = mp.Process(target=t)
p2 = mp.Process(target=t)
p3 = mp.Process(target=t)
p4 = mp.Process(target=t)
p1.start()
p2.start()
p3.start()
p4.start()
p1.join()
p2.join()
p3.join()
p4.join()
print(" 4 procs Parallel - run time: %.2f seconds" % (time.time() - start_time))
# two procs
start_time = time.time()
p1 = mp.Process(target=t)
p2 = mp.Process(target=t)
p1.start()
p2.start()
p1.join()
p2.join()
p3 = mp.Process(target=t)
p4 = mp.Process(target=t)
p3.start()
p4.start()
p3.join()
p4.join()
print(" 2 procs Parallel twice - run time: %.2f seconds" % (time.time() - start_time))
I'm using webstorm on the deployed files
One can simply define two functions to write ($4 is the assigned value) and read a matrix with arbitrary name ($1) and indexes ($2 and $3) exploiting eval and indirect referencing.
#!/bin/bash
matrix_write () {
eval $1"_"$2"_"$3=$4
# aux=$1"_"$2"_"$3 # Alternative way
# let $aux=$4 # ---
}
matrix_read () {
aux=$1"_"$2"_"$3
echo ${!aux}
}
for ((i=1;i<10;i=i+1)); do
for ((j=1;j<10;j=j+1)); do
matrix_write a $i $j $[$i*10+$j]
done
done
for ((i=1;i<10;i=i+1)); do
for ((j=1;j<10;j=j+1)); do
echo "a_"$i"_"$j"="$(matrix_read a $i $j)
done
done
import os
os.path.abspath(os.path.expanduser(os.path.expandvars(PathNameString)))
Note that expanduser
is necessary (on Unix) in case the given expression for the file (or directory) name and location may contain a leading ~/
(the tilde refers to the user's home directory), and expandvars
takes care of any other environment variables (like $HOME
).
I would add another two arguments:
An img tag is good if you need to resize the image. E.g. if the original image is 100px by 100 px, and you want it to be 80px by 80px, you can set the CSS width and height of the img tag. I don't know of any good way to do this using background-image. EDIT: This can now also be done with a background-image, using the background-size
CSS3 attribute.
Using background-image is good when you need to dynamically switch between sprites. E.g. if you have a button image, and you want a separate image displayed when the cursor is hovering over the element, you can use a background image containing both the normal and hover sprites, and dynamically change the background-position.
Well, Izhar solution was OK but, personally, I am trying to avoid from code that looks as this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//Do what you need for this SDK
};
As well, I don't like to duplicate code either. In your answer I have to add such line of code in all Activities:
setStatusBarColor(findViewById(R.id.statusBarBackground),getResources().getColor(android.R.color.white));
So, I took Izhar solution and used XML to get the same result: Create a layout for the StatusBar status_bar.xml
<View xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/statusBarHeight"
android:background="@color/primaryColorDark"
android:elevation="@dimen/statusBarElevation">
Notice the height and elevation attributes, these will be set in values, values-v19, values-v21 further down.
Add this layout to your activities layout using include, main_activity.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/Black" >
<include layout="@layout/status_bar"/>
<include android:id="@+id/app_bar" layout="@layout/app_bar"/>
//The rest of your layout
</RelativeLayout>
For the Toolbar, add top margin attribute:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="@color/primaryColor"
app:theme="@style/MyCustomToolBarTheme"
app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"
android:elevation="@dimen/toolbarElevation"
android:layout_marginTop="@dimen/appBarTopMargin"
android:textDirection="ltr"
android:layoutDirection="ltr">
In your appTheme style-v19.xml and styles-v21.xml, add the windowTranslucent attr:
styles-v19.xml, v21:
<resources>
<item name="android:windowTranslucentStatus">true</item>
</resources>
And finally, on your dimens, dimens-v19, dimens-v21, add the values for the Toolbar topMargin, and the height of the statusBarHeight: dimens.xml for less than KitKat:
<resources>
<dimen name="toolbarElevation">4dp</dimen>
<dimen name="appBarTopMargin">0dp</dimen>
<dimen name="statusBarHeight">0dp</dimen>
</resources>
The status bar height is always 24dp dimens-v19.xml for KitKat and above:
<resources>
<dimen name="statusBarHeight">24dp</dimen>
<dimen name="appBarTopMargin">24dp</dimen>
</resources>
dimens-v21.xml for Lolipop, just add the elevation if needed:
<resources>
<dimen name="statusBarElevation">4dp</dimen>
</resources>
This is the result for Jellybean KitKat and Lollipop:
If you need stricter replacement matching, PostgreSQL's regexp_replace
function can match using POSIX regular expression patterns. It has the syntax regexp_replace(source, pattern, replacement [, flags ]).
I will use flags i
and g
for case-insensitive and global matching, respectively. I will also use \m
and \M
to match the beginning and the end of a word, respectively.
There are usually quite a few gotchas when performing regex replacment. Let's see how easy it is to replace a cat with a dog.
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog');
--> Cat bobdog cat cats catfish
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'i');
--> dog bobcat cat cats catfish
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'g');
--> Cat bobdog dog dogs dogfish
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat', 'dog', 'gi');
--> dog bobdog dog dogs dogfish
SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat', 'dog', 'gi');
--> dog bobcat dog dogs dogfish
SELECT regexp_replace('Cat bobcat cat cats catfish', 'cat\M', 'dog', 'gi');
--> dog bobdog dog cats catfish
SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat\M', 'dog', 'gi');
--> dog bobcat dog cats catfish
SELECT regexp_replace('Cat bobcat cat cats catfish', '\mcat(s?)\M', 'dog\1', 'gi');
--> dog bobcat dog dogs catfish
Even after all of that, there is at least one unresolved condition. For example, sentences that begin with "Cat" will be replaced with lower-case "dog" which break sentence capitalization.
Check out the current PostgreSQL pattern matching docs for all the details.
Given my examples, maybe the safest option would be:
UPDATE table SET field = regexp_replace(field, '\mcat\M', 'dog', 'gi');
In docs.python.org Topic = 5.6.2. String Formatting Operations http://docs.python.org/library/stdtypes.html#string-formatting then further down to the chart (text above chart is "The conversion types are:")
My comment: help does not include attitude which is a bonus. The attitude post enabled me to search further and find the info.
In simple terms you need to build your payload into a key array
payload = {'key1': 'value1', 'key2': 'value2'}
Then send the payload directly to the action
this.$store.dispatch('yourAction', payload)
No change in your action
yourAction: ({commit}, payload) => {
commit('YOUR_MUTATION', payload )
},
In your mutation call the values with the key
'YOUR_MUTATION' (state, payload ){
state.state1 = payload.key1
state.state2 = payload.key2
},
After posting this I did come up with a way that works. However, I don't feel it is the best way to handle this. Any suggestions on a better one?
//Check to see if we get rows back, if we do just bind.
if (dtFunding.Rows.Count != 0)
{
grdFunding.DataSource = dtFunding;
grdFunding.DataBind();
}
else
{
//Other wise add a emtpy "New Row" to the datatable and then hide it after binding.
dtFunding.Rows.Add(dtFunding.NewRow());
grdFunding.DataSource = dtFunding;
grdFunding.DataBind();
grdFunding.Rows[0].Visible = false;
}
You can get a subset of the np.set_printoptions
functionality from the np.array_str
command, which applies only to a single print statement.
http://docs.scipy.org/doc/numpy/reference/generated/numpy.array_str.html
For example:
In [27]: x = np.array([[1.1, 0.9, 1e-6]]*3)
In [28]: print x
[[ 1.10000000e+00 9.00000000e-01 1.00000000e-06]
[ 1.10000000e+00 9.00000000e-01 1.00000000e-06]
[ 1.10000000e+00 9.00000000e-01 1.00000000e-06]]
In [29]: print np.array_str(x, precision=2)
[[ 1.10e+00 9.00e-01 1.00e-06]
[ 1.10e+00 9.00e-01 1.00e-06]
[ 1.10e+00 9.00e-01 1.00e-06]]
In [30]: print np.array_str(x, precision=2, suppress_small=True)
[[ 1.1 0.9 0. ]
[ 1.1 0.9 0. ]
[ 1.1 0.9 0. ]]
The method you are trying to use checks if the button is active:
btnAdd.isEnabled()
When enabled, any component associated with this object is active and able to fire this object's actionPerformed method.
This method does not check if the button is pressed.
If i understand your question correctly, you want to disable your "Add" button after the user clicks "Check out".
Try disabling your button at start: btnAdd.setEnabled(false)
or after the user presses "Check out"
So to add a user icon, just add 
to the placeholder
attribute, or wherever you want it.
You may want to check this cheat sheet.
Example:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<input type="text" class="form-control" placeholder=" placeholder..." style="font-family: 'Glyphicons Halflings', Arial">_x000D_
<input type="text" class="form-control" value=" value..." style="font-family: 'Glyphicons Halflings', Arial">_x000D_
<input type="submit" class="btn btn-primary" value=" submit-button" style="font-family: 'Glyphicons Halflings', Arial">
_x000D_
Don't forget to set the input's font to the Glyphicon one, using the following code:
font-family: 'Glyphicons Halflings', Arial
, where Arial is the font of the regular text in the input.
On Debian the best way to do it would be
sudo apt-get install python-pip
Instead of doing this:
compile "com.android.support:support-v4:18.0.+"
Do this:
compile 'com.android.support:support-v4:18.0.+'
Worked for me
Couple of ways. Firstly, if you're adding a row each time a [de]activation occurs, you can set the column default to GETDATE() and not set the value in the insert. Otherwise,
UPDATE TableName SET [ColumnName] = GETDATE() WHERE UserId = @userId
In my case it was because of the url pattern I used
my url was like /ui/project/:parameter1/:parameter2.
I didn't need paramerter2 in all cases of state change. In cases where I didn't need the second parameter my url would be like /ui/project/:parameter1/. And so whenever I had a state change I will have my controller refreshed twice.
The solution was to set parameter2 as empty string and do the state change.
You can use arguments with default values.
def someMethod(def mandatory,def optional=null){}
if argument "optional" not exist, it turns to "null".
IF exists
IF exists (select * from table_1 where col1 = 'value')
BEGIN
-- one or more
insert into table_1 (col1) values ('valueB')
END
ELSE
-- zero
insert into table_1 (col1) values ('value')
The simpliest way is to drop database phpmyadmin and run sql/create_tables.sql script. Just login to mysql console and:
DROP DATABASE phpmyadmin;
\. {your path to pma}/sql/reate_tables.sql
You can update progress bar only from ProgressChanged
or RunWorkerCompleted
event handlers as these are synchronized with the UI thread.
The basic idea is. Thread.Sleep
just simulates some work here. Replace it with your real routing call.
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.WorkerReportsProgress = true;
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
I use ssh to connect to remote server and have python code execute cv2.VideoCapture(0) to capture remote webcam, then encounter this error message:
error: (-215)size.width>0 && size.height>0 in function imshow
Finally, I have to grant access to /dev/video0 (which is my webcam device) with my user account and the error message was gone. Use usermod to add user into group video
usermod -a -G video user
head
is defined inside the main as follows.
struct Node *head = new Node;
But you are changing the head in addNode()
and initNode()
functions only. The changes are not reflected back on the main.
Make the declaration of the head as global and do not pass it to functions.
The functions should be as follows.
void initNode(int n){
head->x = n;
head->next = NULL;
}
void addNode(int n){
struct Node *NewNode = new Node;
NewNode-> x = n;
NewNode->next = head;
head = NewNode;
}
You can also use:
git reset HEAD file/path
1) Server.MapPath(".")
-- Returns the "Current Physical Directory" of the file (e.g. aspx
) being executed.
Ex. Suppose D:\WebApplications\Collage\Departments
2) Server.MapPath("..")
-- Returns the "Parent Directory"
Ex. D:\WebApplications\Collage
3) Server.MapPath("~")
-- Returns the "Physical Path to the Root of the Application"
Ex. D:\WebApplications\Collage
4) Server.MapPath("/")
-- Returns the physical path to the root of the Domain Name
Ex. C:\Inetpub\wwwroot
SELECT DATEDIFF(day, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
Turns out the Samsung file explorer uses a custom action. This is why I could see the Samsung file explorer when looking for a file from the samsung apps, but not from mine.
The action is "com.sec.android.app.myfiles.PICK_DATA"
I created a custom Activity Picker which displays activities filtering both intents.
You can do something like this to check if any mysql
process is running or not:
ps aux | grep mysqld
ps aux | grep mysql
Then if it is running you can killall
by using(depending on what all processes are running currently):
killall -9 mysql
killall -9 mysqld
killall -9 mysqld_safe
List has Contains method that return bool. We can use that method in query.
List<int> listA = new List<int>();
List<int> listB = new List<int>();
listA.AddRange(new int[] { 1,2,3,4,5 });
listB.AddRange(new int[] { 3,5,6,7,8 });
var v = from x in listA
where !listB.Contains(x)
select x;
foreach (int i in v)
Console.WriteLine(i);
If you change your property to use a backing field (instead of an automatic property), you can do the following:
public event EventHandler ImageFullPath1Changed;
private string _imageFullPath1 = string.Empty;
public string ImageFullPath1
{
get
{
return imageFullPath1 ;
}
set
{
if (_imageFullPath1 != value)
{
_imageFullPath1 = value;
EventHandler handler = ImageFullPathChanged;
if (handler != null)
handler(this, e);
}
}
}
You can have a look at this link for a comparison of the two (and others) approaches in a real example.
Basically, when requirements change, you end up modifying more code if you use factories instead of DI.
This is also valid with manual DI (i.e. when there isn't an external framework that provides the dependencies to your objects, but you pass them in each constructor).
You need to use a regular expression, so that you can specify the global (g) flag:
var s = 'some+multi+word+string'.replace(/\+/g, ' ');
(I removed the $()
around the string, as replace
is not a jQuery method, so that won't work at all.)
Update 2019
The :has()
pseudo-selector is propsed in the CSS Selectors 4 spec, and will address this use case once implemented.
To use it, we will write something like:
.foo > .bar:has(> .baz) { /* style here */ }
In a structure like:
<div class="foo">
<div class="bar">
<div class="baz">Baz!</div>
</div>
</div>
This CSS will target the .bar
div - because it both has a parent .foo
and from its position in the DOM, > .baz
resolves to a valid element target.
Original Answer (left for historical purposes) - this portion is no longer accurate
For completeness, I wanted to point out that in the Selectors 4 specification (currently in proposal), this will become possible. Specifically, we will gain Subject Selectors, which will be used in the following format:
!div > span { /* style here */
The !
before the div
selector indicates that it is the element to be styled, rather than the span
. Unfortunately, no modern browsers (as of the time of this posting) have implemented this as part of their CSS support. There is, however, support via a JavaScript library called Sel, if you want to go down the path of exploration further.
$this->db->select('id, name, price, author, category, language, ISBN, publish_date');
$this->db->from('tbl_books');
I was looking for a resolution to this issue in Windows, and it seems to be that if you don't have the environments vars ok, you need to put the complete directory. For eg. with a file in the same directory than PHP:
F:\myfolder\php\php.exe -f F:\myfolder\php\script.php
You can also reference a local gem with git if you happen to be working on it.
gem 'foo',
:git => '/Path/to/local/git/repo',
:branch => 'my-feature-branch'
Then, if it changes I run
bundle exec gem uninstall foo
bundle update foo
But I am not sure everyone needs to run these two steps.
I had this problem and i searched for it then i made my own method using some java keywords just need to pass String variable as parameter and get output as proper titled String.
public class Main
{
public static void main (String[]args)
{
String st = "pARVeEN sISHOsIYA";
String mainn = getTitleCase (st);
System.out.println (mainn);
}
public static String getTitleCase(String input)
{
StringBuilder titleCase = new StringBuilder (input.length());
boolean hadSpace = false;
for (char c:input.toCharArray ()){
if(Character.isSpaceChar(c)){
hadSpace = true;
titleCase.append (c);
continue;
}
if(hadSpace){
hadSpace = false;
c = Character.toUpperCase(c);
titleCase.append (c);
}else{
c = Character.toLowerCase(c);
titleCase.append (c);
}
}
String temp=titleCase.toString ();
StringBuilder titleCase1 = new StringBuilder (temp.length ());
int num=1;
for (char c:temp.toCharArray ())
{ if(num==1)
c = Character.toUpperCase(c);
titleCase1.append (c);
num=0;
}
return titleCase1.toString ();
}
}
Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.
What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n
children, that state should be "owned" by whatever contains your component. eg:
class AppComponent extends React.Component {
state = {
numChildren: 0
}
render () {
const children = [];
for (var i = 0; i < this.state.numChildren; i += 1) {
children.push(<ChildComponent key={i} number={i} />);
};
return (
<ParentComponent addChild={this.onAddChild}>
{children}
</ParentComponent>
);
}
onAddChild = () => {
this.setState({
numChildren: this.state.numChildren + 1
});
}
}
const ParentComponent = props => (
<div className="card calculator">
<p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
<div id="children-pane">
{props.children}
</div>
</div>
);
const ChildComponent = props => <div>{"I am child " + props.number}</div>;
You can write directly to the response but then it isn't testable. It is preferred to return an ActionResult that has deferred execution. Here is my resusable StreamResult:
public class StreamResult : ViewResult
{
public Stream Stream { get; set; }
public string ContentType { get; set; }
public string ETag { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.ContentType = ContentType;
if (ETag != null) context.HttpContext.Response.AddHeader("ETag", ETag);
const int size = 4096;
byte[] bytes = new byte[size];
int numBytes;
while ((numBytes = Stream.Read(bytes, 0, size)) > 0)
context.HttpContext.Response.OutputStream.Write(bytes, 0, numBytes);
}
}
Trailing whitespace:
It is extra spaces (and tabs) at the end of line
^^^^^ here
Strip them:
#!/usr/bin/env python2
"""\
strip trailing whitespace from file
usage: stripspace.py <file>
"""
import sys
if len(sys.argv[1:]) != 1:
sys.exit(__doc__)
content = ''
outsize = 0
inp = outp = sys.argv[1]
with open(inp, 'rb') as infile:
content = infile.read()
with open(outp, 'wb') as output:
for line in content.splitlines():
newline = line.rstrip(" \t")
outsize += len(newline) + 1
output.write(newline + '\n')
print("Done. Stripped %s bytes." % (len(content)-outsize))
Possible solution without using substr()
#include<iostream>
#include<string>
using namespace std;
int main() {
string c="12345";
int p=0;
for(int i=0;i<c.length();i++) {
cout<<c[i];
p++;
if (p % 2 == 0 && i != c.length()-1) {
cout<<" "<<c[i];
p++;
}
}
}
How about
user r = {"",{}};
or
user r = {"",{'\0'}};
or
user r = {"",std::vector<unsigned char>()};
or
user r;
For enable PHP Extension intl , follow the Steps..
You don't appear to understand what still reachable
means.
Anything still reachable
is not a leak. You don't need to do anything about it.
I have the same problem, I overcame it with an ugly -- but useful -- set of GOTOs.
The reason I call the "script runner" before everything is that I want to hide the complexity and ugly approach from any developer that just wants to work with the actual script. At the same time, I can make sure that the script is run in the two (extensible to three and more) databases in the exact same way.
GOTO ScriptRunner
ScriptExecutes:
--------------------ACTUAL SCRIPT--------------------
-------- Will be executed in DB1 and in DB2 ---------
--TODO: Your script right here
------------------ACTUAL SCRIPT ENDS-----------------
GOTO ScriptReturns
ScriptRunner:
USE DB1
GOTO ScriptExecutes
ScriptReturns:
IF (db_name() = 'DB1')
BEGIN
USE DB2
GOTO ScriptExecutes
END
With this approach you get to keep your variables and SQL Server does not freak out if you happen to go over a DECLARE statement twice.
They tell what size can be stored in a integer variable. To remember the size you can think in terms of :-) 2 beer( 2 bytes) , 4 beer(4 bytes) or 8 beer( 8 bytes).
Int16 :-2 beers/bytes = 16 bit = 2^16 = 65536 = 65536/2 = -32768 to 32767
Int32 :- 4 beers/bytes = 32 bit = 2^32 = 4294967296 = 4294967296/2 = -2147483648 to 2147483647
Int64 :- 8 beer/ bytes = 64 bit = 2^64 = 18446744073709551616 = 18446744073709551616 /2 = -9223372036854775808 to 9223372036854775807
In short you can store more than 32767 value in int16 , more than 2147483647 value in int32 and more than 9223372036854775807 value in int64.
To understand above calculation you can check out this video int16 vs int32 vs int64
Here you go:
https://support.google.com/docs/answer/3093281
This is all the documentation that Google provides.
Editing VM Configuration worked for me.
-Djava.util.Arrays.useLegacyMergeSort=true
Destroy the datepicker's instance when you don't want it and create new instance whenever necessary.
I know this is ugly but only this seems to be working...
$("#ddlSearchType").change(function () {
if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date") {
$("#txtSearch").datepicker();
}
else {
$("#txtSearch").datepicker("destroy");
}
});
To process a file line-by-line, you simply need to decouple the reading of the file and the code that acts upon that input. You can accomplish this by buffering your input until you hit a newline. Assuming we have one JSON object per line (basically, format B):
var stream = fs.createReadStream(filePath, {flags: 'r', encoding: 'utf-8'});
var buf = '';
stream.on('data', function(d) {
buf += d.toString(); // when data is read, stash it in a string buffer
pump(); // then process the buffer
});
function pump() {
var pos;
while ((pos = buf.indexOf('\n')) >= 0) { // keep going while there's a newline somewhere in the buffer
if (pos == 0) { // if there's more than one newline in a row, the buffer will now start with a newline
buf = buf.slice(1); // discard it
continue; // so that the next iteration will start with data
}
processLine(buf.slice(0,pos)); // hand off the line
buf = buf.slice(pos+1); // and slice the processed data off the buffer
}
}
function processLine(line) { // here's where we do something with a line
if (line[line.length-1] == '\r') line=line.substr(0,line.length-1); // discard CR (0x0D)
if (line.length > 0) { // ignore empty lines
var obj = JSON.parse(line); // parse the JSON
console.log(obj); // do something with the data here!
}
}
Each time the file stream receives data from the file system, it's stashed in a buffer, and then pump
is called.
If there's no newline in the buffer, pump
simply returns without doing anything. More data (and potentially a newline) will be added to the buffer the next time the stream gets data, and then we'll have a complete object.
If there is a newline, pump
slices off the buffer from the beginning to the newline and hands it off to process
. It then checks again if there's another newline in the buffer (the while
loop). In this way, we can process all of the lines that were read in the current chunk.
Finally, process
is called once per input line. If present, it strips off the carriage return character (to avoid issues with line endings – LF vs CRLF), and then calls JSON.parse
one the line. At this point, you can do whatever you need to with your object.
Note that JSON.parse
is strict about what it accepts as input; you must quote your identifiers and string values with double quotes. In other words, {name:'thing1'}
will throw an error; you must use {"name":"thing1"}
.
Because no more than a chunk of data will ever be in memory at a time, this will be extremely memory efficient. It will also be extremely fast. A quick test showed I processed 10,000 rows in under 15ms.
This is going to be something to do with character encodings.
Are you sure the mirrored site has the same properties with regards to character encodings as your main server?
Depending on what sort of server you have, this may be a property of the server process itself, or it could be an environment variable.
For example, if this is a UNIX environment, perhaps try comparing LANG or LC_ALL?
See also here
__stdcall
is the calling convention used for the function. This tells the compiler the rules that apply for setting up the stack, pushing arguments and getting a return value.
There are a number of other calling conventions, __cdecl
, __thiscall
, __fastcall
and the wonderfully named __declspec(naked)
. __stdcall
is the standard calling convention for Win32 system calls.
Wikipedia covers the details.
It primarily matters when you are calling a function outside of your code (e.g. an OS API) or the OS is calling you (as is the case here with WinMain). If the compiler doesn't know the correct calling convention then you will likely get very strange crashes as the stack will not be managed correctly.
It really depends on your use-case.
Comparing 0MQ with ActiveMQ or RabbitMQ is not fair. ActiveMQ and RabbitMQ are Messaging Systems wich require installation and administration. They offer featurewise a lot more than ZeroMQ. They have real persistent Queues, Support for transactions etc.
ZeroMQ is a lightweight message orientated socket implementation. It is also suitable for in-process asynchronous programming. It is possible to run a "Enterprise Messaging System" over ZeroMQ, but you would have to implement a lot on your own.
So:
ActiveMQ, RabbitMQ, Websphere MQ & MSMQ are "Enterprise Message Queues"
ZeroMQ is a message orientated IPC Library.
Use the in
keyword.
if 'apples' in d:
if d['apples'] == 20:
print('20 apples')
else:
print('Not 20 apples')
If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get
function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None
instead):
if d.get('apples', 0) == 20:
print('20 apples.')
else:
print('Not 20 apples.')
I put together a little test here:
\documentclass[10pt,twocolumn]{article}
\title{Article Title}
\author{
First Author\\
Department\\
school\\
email@edu
\and
Second Author\\
Department\\
school\\
email@edu
\and
Third Author\\
Department\\
school\\
email@edu
\and
Fourth Author\\
Department\\
school\\
email@edu
}
\date{\today}
\begin{document}
\maketitle
\begin{abstract}
\ldots
\end{abstract}
\section{Introduction}
\ldots
\end{document}
Things to note, the title, author and date fields are declared before \begin{document}
. Also, the multicol package is likely unnecessary in this case since you have declared twocolumn
in the document class.
This example puts all four authors on the same line, but if your authors have longer names, departments or emails, this might cause it to flow over onto another line. You might be able to change the font sizes around a little bit to make things fit. This could be done by doing something like {\small First Author}
. Here's a more detailed article on \LaTeX
font sizes:
https://engineering.purdue.edu/ECN/Support/KB/Docs/LaTeXChangingTheFont
To italicize you can use {\it First Name}
or \textit{First Name}
.
Be careful though, if the document is meant for publication often times journals or conference proceedings have their own formatting guidelines so font size trickery might not be allowed.
Use this code between two words:
& vbCrLf &
Using this, the next word displays on the next line.
Restarting the Management Studio worked for me.
The []
makes no sense in the moment of making an ArrayList of Integers because I imagine you just want to add Integer values.
Just use
List<Integer> list = new ArrayList<>();
to create the ArrayList and it will work.
Here is a mapping for reference, assuming UTC for spreadsheet systems like Microsoft Excel:
Unix Excel Mac Excel Human Date Human Time
Excel Epoch -2209075200 -1462 0 1900/01/00* 00:00:00 (local)
Excel = 2011 Mac† -2082758400 0 1462 1904/12/31 00:00:00 (local)
Unix Epoch 0 24107 25569 1970/01/01 00:00:00 UTC
Example Below 1234567890 38395.6 39857.6 2009/02/13 23:31:30 UTC
Signed Int Max 2147483648 51886 50424 2038/01/19 03:14:08 UTC
One Second 1 0.0000115740… — 00:00:01
One Hour 3600 0.0416666666… - 01:00:00
One Day 86400 1 1 - 24:00:00
* “Jan Zero, 1900” is 1899/12/31; see the Bug section below. † Excel 2011 for Mac (and older) use the 1904 date system.
As I often use awk
to process CSV and space-delimited content, I developed a way to convert UNIX epoch to timezone/DST-appropriate Excel date format:
echo 1234567890 |awk '{
# tries GNU date, tries BSD date on failure
cmd = sprintf("date -d@%d +%%z 2>/dev/null || date -jf %%s %d +%%z", $1, $1)
cmd |getline tz # read in time-specific offset
hours = substr(tz, 2, 2) + substr(tz, 4) / 60 # hours + minutes (hi, India)
if (tz ~ /^-/) hours *= -1 # offset direction (east/west)
excel = $1/86400 + hours/24 + 25569 # as days, plus offset
printf "%.9f\n", excel
}'
I used echo
for this example, but you can pipe a file where the first column (for the first cell in .csv format, call it as awk -F,
) is a UNIX epoch. Alter $1
to represent your desired column/cell number or use a variable instead.
This makes a system call to date
. If you will reliably have the GNU version, you can remove the 2>/dev/null || date … +%%z
and the second , $1
. Given how common GNU is, I wouldn't recommend assuming BSD's version.
The getline
reads the time zone offset outputted by date +%z
into tz
, which is then translated into hours
. The format will be like -0700
(PDT) or +0530
(IST), so the first substring extracted is 07
or 05
, the second is 00
or 30
(then divided by 60 to be expressed in hours), and the third use of tz
sees whether our offset is negative and alters hours
if needed.
The formula given in all of the other answers on this page is used to set excel
, with the addition of the daylight-savings-aware time zone adjustment as hours/24
.
If you're on an older version of Excel for Mac, you'll need to use 24107
in place of 25569
(see the mapping above).
To convert any arbitrary non-epoch time to Excel-friendly times with GNU date:
echo "last thursday" |awk '{
cmd = sprintf("date -d \"%s\" +\"%%s %%z\"", $0)
cmd |getline
hours = substr($2, 2, 2) + substr($2, 4) / 60
if ($2 ~ /^-/) hours *= -1
excel = $1/86400 + hours/24 + 25569
printf "%.9f\n", excel
}'
This is basically the same code, but the date -d
no longer has an @
to represent unix epoch (given how capable the string parser is, I'm actually surprised the @
is mandatory; what other date format has 9-10 digits?) and it's now asked for two outputs: the epoch and the time zone offset. You could therefore use e.g. @1234567890
as an input.
Lotus 1-2-3 (the original spreadsheet software) intentionally treated 1900 as a leap year despite the fact that it was not (this reduced the codebase at a time when every byte counted). Microsoft Excel retained this bug for compatibility, skipping day 60 (the fictitious 1900/02/29), retaining Lotus 1-2-3's mapping of day 59 to 1900/02/28. LibreOffice instead assigned day 60 to 1900/02/28 and pushed all previous days back one.
Any date before 1900/03/01 could be as much as a day off:
Day Excel LibreOffice
-1 -1 1899/12/29
0 1900/01/00* 1899/12/30
1 1900/01/01 1899/12/31
2 1900/01/02 1900/01/01
…
59 1900/02/28 1900/02/27
60 1900/02/29(!) 1900/02/28
61 1900/03/01 1900/03/01
Excel doesn't acknowledge negative dates and has a special definition of the Zeroth of January (1899/12/31) for day zero. Internally, Excel does indeed handle negative dates (they're just numbers after all), but it displays them as numbers since it doesn't know how to display them as dates (nor can it convert older dates into negative numbers). Feb 29 1900, a day that never happened, is recognized by Excel but not LibreOffice.
While waiting for the adoption of CSS3 targeting by the major browsers, one could run the following sed
command once the (X)HTML has been created:
sed -i 's|href="http|target="_blank" href="http|g' index.html
It will add target="_blank"
to all external hyperlinks. Variations are also possible.
EDIT
I use this at the end of the makefile
which generates every web page on my site.
Using a table would be one (and easy) option.
Other options are all about setting fixed width on the and making it text-aligned to the right:
label {
width: 200px;
display: inline-block;
text-align: right;
}
or, as was pointed out, make them all float instead of inline.
The dat file has some lines of extra information before the actual data. Skip them with the skip
argument:
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)
An easy way to check this if you are unfamiliar with the dataset is to first use readLines
to check a few lines, as below:
readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
n=10)
# [1] "Ozone data from CZ03 2009" "Local time: GMT + 0"
# [3] "" "Date Hour Value"
# [5] "01.01.2009 00:00 34.3" "01.01.2009 01:00 31.9"
# [7] "01.01.2009 02:00 29.9" "01.01.2009 03:00 28.5"
# [9] "01.01.2009 04:00 32.9" "01.01.2009 05:00 20.5"
Here, we can see that the actual data starts at [4]
, so we know to skip the first three lines.
If you really only wanted the Value
column, you could do that by:
as.vector(
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)$Value)
Again, readLines
is useful for helping us figure out the actual name of the columns we will be importing.
But I don't see much advantage to doing that over reading the whole dataset in and extracting later.
Typescript fails in your case because it expects all the fields to be present. Use Record and Partial utility types to solve it.
Record<string, Partial<IPerson>>
interface IPerson {
firstName: string;
lastName: string;
}
var persons: Record<string, Partial<IPerson>> = {
"p1": { firstName: "F1", lastName: "L1" },
"p2": { firstName: "F2" }
};
Explanation.
Alternate.
If you wish to make last name optional you can append a ? Typescript will know that it's optional.
lastName?: string;
https://www.typescriptlang.org/docs/handbook/utility-types.html
The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
Specifically, a keyword argument looks like this: tag='insider trading!'
while a positional argument looks like this: ..., exchange, ...
. The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.
Also, when an argument has a default value, such as price=None
, that means you don't have to provide it. If you don't provide it, it will use the default value instead.
To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity)
# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)
# Some positional, some keyword (all keywords at end):
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity, tag='insider trading!')
I understand that this question is old, but there is a good solution for it in HTML5.
You can wrap it all in a <figure></figure>
tag. The code would look something like this:
<div id="wrapper">
<figure>
<a href="mailto:[email protected]">
<img id="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-
content/uploads/2012/07/email-icon-e1343123697991.jpg"/>
</a>
<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">
<img id="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-
content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/>
</a>
</figure>
</div>
and the CSS:
#wrapper{
text-align:center;
}
Now in c++11 we have
#include <string>
string s = std::to_string(123);
Link to reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string
You can only use -
on the numeric entries, so you can use decreasing and negate the ones you want in increasing order:
DT[order(x,-v,decreasing=TRUE),]
x y v
[1,] c 1 7
[2,] c 3 8
[3,] c 6 9
[4,] b 1 1
[5,] b 3 2
[6,] b 6 3
[7,] a 1 4
[8,] a 3 5
[9,] a 6 6
Rather than using the ssh://
protocol prefix, you can continue using the conventional URL form for accessing git over SSH, with one small change. As a reminder, the conventional URL is:
git@host:path/to/repo.git
To specify an alternative port, put brackets around the user@host
part, including the port:
[git@host:port]:path/to/repo.git
But if the port change is merely temporary, you can tell git to use a different SSH command instead of changing your repository’s remote URL:
export GIT_SSH_COMMAND='ssh -p port'
git clone git@host:path/to/repo.git # for instance
If you need not equal object condition use cross join sequences:
var query = from obj1 in set1
from obj2 in set2
where obj1.key1 == obj2.key2 && obj1.key3.contains(obj2.key5) [...conditions...]
See ?nchar
. For example:
> nchar("foo")
[1] 3
> set.seed(10)
> strn <- paste(sample(LETTERS, 10), collapse = "")
> strn
[1] "NHKPBEFTLY"
> nchar(strn)
[1] 10
typeOf is a C# keyword that is used when you have the name of the class. It is calculated at compile time and thus cannot be used on an instance, which is created at runtime. GetType is a method of the object class that can be used on an instance.
I think the best answer to each of those questions would be given by you and your team. It's far more important to have a naming convention then how exactly the naming convention is.
As there's no right answer to that, you should take some time (but not too much) and choose your own conventions and - here's the important part - stick to it.
Of course it's good to seek some information about standards on that, which is what you're asking, but don't get anxious or worried about the number of different answers you might get: choose the one that seems better for you.
Just in case, here are my answers:
You can also install the required packages with Help -> Install new software...
See http://www.eclipse.org/downloads/compare.php for the packages you need to install to have eclipse IDE for java EE developers
You can even simply add the parameters to the end of the url:
$http.get('path/to/script.php?param=hello').success(function(data) {
alert(data);
});
Paired with script.php:
<? var_dump($_GET); ?>
Resulting in the following javascript alert:
array(1) {
["param"]=>
string(4) "hello"
}
The official way to disable the popup is this:
Pack your extension: go to chrome://extensions
, check Developer mode and click Pack extension
Install the extension by dragging and dropping the .crx
file into the chrome://extensions
page.
You'll get an "Unsupported extensions disabled" popup if you try restarting Chrome at this point.
Then for Windows 7 or Windows 8:
[zip]\windows\admx\chrome.admx
to c:\windows\policydefinitions
[zip]\windows\admx\[yourlanguage]\chrome.adml
to c:\windows\policydefinitions\[yourlanguage]\chrome.adml
(not c:\windows\[yourlanguage]
)chrome://extensions
gpedit.msc
and hit enter.That's it!
Chrome Version 69.0.3497.100 (Official Build) (64-bit)
:Temporarily enable Developer mode in chrome://extensions
Uninstall the extension that causes the popup using the Load unpacked.
Click on Pack extension, and find and select the folder containing the extension files. Don't enter the private key file if you don't have it.
Click Pack extension. A .crx
and .pem
file will be created near the root directory of the extension. Install the extension using the .crx
file and keep the .pem
file safe.
Copy the .crx
installed extension ID to the whitelist and restart Chrome.
The popup should be gone.
I will point out that in the article linked in the top rated answer The Curse and Blessings of Dynamic SQL the author states that the answer is not to use dynamic SQL. Scroll almost to the end to see this.
From the article: "The correct method is to unpack the list into a table with a user-defined function or a stored procedure."
Of course, once the list is in a table you can use a join. I could not comment directly on the top rated answer, so I just added this comment.
As already stated, you have too many methods (more than 65k) in your project and libs.
Since often the Google Play services is one of the main suspects in "wasting" methods with its 20k+ methods. Google Play services version 6.5 or later, it is possible for you to include Google Play services in your application using a number of smaller client libraries. For example, if you only need GCM and maps you can choose to use these dependencies only:
dependencies {
compile 'com.google.android.gms:play-services-base:6.5.+'
compile 'com.google.android.gms:play-services-maps:6.5.+'
}
The full list of sub libraries and it's responsibilities can be found in the official google doc.
Update: Since Support Library v4 v24.2.0 it was split up into the following modules:
support-compat
,support-core-utils
,support-core-ui
,support-media-compat
andsupport-fragment
dependencies {
compile 'com.android.support:support-fragment:24.2.+'
}
Do note however, if you use support-fragment
, it will have dependencies to all the other modules (ie. if you use android.support.v4.app.Fragment
there is no benefit)
See here the official release notes for support-v4 lib
Since Lollipop (aka build tools 21+) it is very easy to handle. The approach is to work around the 65k methods per dex file problem to create multiple dex files for your app. Add the following to your gradle build file (this is taken from the official google doc on applications with more than 65k methods):
android {
compileSdkVersion 21
buildToolsVersion "21.1.0"
defaultConfig {
...
// Enabling multidex support.
multiDexEnabled true
}
...
}
dependencies {
compile 'com.android.support:multidex:1.0.1'
}
The second step is to either prepare your Application class or if you don't extend Application use the MultiDexApplication
in your Android Manifest:
Either add this to your Application.java
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
or use the provided application from the mutlidex lib
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.myapplication">
<application
...
android:name="android.support.multidex.MultiDexApplication">
...
</application>
</manifest>
As further tip, if you run into OutOfMemory
exceptions during the build phase you could enlarge the heap with
android {
...
dexOptions {
javaMaxHeapSize "4g"
}
}
which would set the heap to 4 gigabytes.
See this question for more detail on the dex heap memory issue.
To analyze the source of the methods the gradle plugin https://github.com/KeepSafe/dexcount-gradle-plugin can help in combination with the dependency tree provided by gradle with e.g.
.\gradlew app:dependencies
See this answer and question for more information on method count in android
This "tuple" feature it is called destructuring in EcmaScript2015 and is soon to be supported by up to date browsers. For the time being, only Firefox and Chrome support it.
But hey, you can use a transpiler.
The code would look as nice as python:
let tuple = ["Bob", 24]
let [name, age] = tuple
console.log(name)
console.log(age)
If your into Python or use Androguard, the Androguard Androaxml feature will do this conversion for you. The feature is detailed in this blog post, with additional documentation here and source here.
Usage:
$ ./androaxml.py -h
Usage: androaxml.py [options]
Options:
-h, --help show this help message and exit
-i INPUT, --input=INPUT
filename input (APK or android's binary xml)
-o OUTPUT, --output=OUTPUT
filename output of the xml
-v, --version version of the API
$ ./androaxml.py -i yourfile.apk -o output.xml
$ ./androaxml.py -i AndroidManifest.xml -o output.xml
Datetime is a datatype.
Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.
For more information:
http://www.sqlteam.com/article/timestamps-vs-datetime-data-types
In Tomcat a .java and .class file will be created for every jsp files with in the application and the same can be found from the path below,
Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\index_jsp.java
In your case the jsp name is error.jsp so the path should be something like below
Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\error_jsp.java
in line no 124 you are trying to access a null object which results in null pointer exception.
JavascriptExecutor is best to scroll down a web page
window.scrollTo
Function in JavascriptExecutor can do this
JavascriptExecutor js = ((JavascriptExecutor) driver);
js.executeScript("window.scrollTo(0,100");
Above code will scroll down by 100 y coordinates
Now to answer the question that perhaps you should have asked, like "I'm getting 100 floats form somewhere; do I need to put them in an array or list before I find the minimum?"
Answer: No, if somewhere
is a iterable, instead of doing this:
temp = []
for x in somewhere:
temp.append(x)
answer = min(temp)
you can do this:
answer = min(somewhere)
Example:
answer = min(float(line) for line in open('floats.txt'))
git filter-branch --tree-filter 'rm -f path/to/file' HEAD
worked pretty well for me, although I ran into the same problem as described here, which I solved by following this suggestion.
The pro-git book has an entire chapter on rewriting history - have a look at the filter-branch
/Removing a File from Every Commit section.
Even though the ID selector is the simplest, you can also use the name selector as below:
$('[name='submitted[first_name]']').removeAttr('required');
For more see: https://api.jquery.com/attribute-equals-selector/
Yes. ArrayList is a sequential list. So, insertion and retrieval order is the same.
If you add elements during retrieval, the order will not remain the same.
insert into TABLENAMEA (A,B,C,D)
select A::integer,B,C,D from TABLENAMEB
Custom scroll bars aren't possible with CSS, you'll need some JavaScript magic.
Some browsers support non-spec CSS rules, such as ::-webkit-scrollbar
in Webkit but is not ideal since it'll only work in Webkit. IE had something like that too, but I don't think they support it anymore.
Unless you specify a severity of 20 or higher, raiserror
will not stop execution. See the MSDN documentation.
The normal workaround is to include a return
after every raiserror
:
if @whoops = 1
begin
raiserror('Whoops!', 18, 1)
return -1
end
If you use the request body in a GET request, you're breaking the REST principle, because your GET request won't be able to be cached, because cache system uses only the URL.
What's worse, your URL can't be bookmarked, because the URL doesn't contain all the information needed to redirect the user to this page.
Use URL or Query parameters instead of request body parameters, e.g.:
/myapp?var1=xxxx&var2=xxxx
/myapp;var1=xxxx/resource;var2=xxxx
In fact, the HTTP RFC 7231 says that:
A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.
For more information take a look here.
All WebServices is API but all API is not WebServices, API which is exposed on Web is called web services.
If you have YAML that conforms to the YAML 1.2 specification (released 2009) then you should use ruamel.yaml (disclaimer: I am the author of that package). It is essentially a superset of PyYAML, which supports most of YAML 1.1 (from 2005).
If you want to be able to preserve your comments when round-tripping, you certainly should use ruamel.yaml.
Upgrading @Jon's example is easy:
import ruamel.yaml as yaml
with open("example.yaml") as stream:
try:
print(yaml.safe_load(stream))
except yaml.YAMLError as exc:
print(exc)
Use safe_load()
unless you really have full control over the input, need it (seldom the case) and know what you are doing.
If you are using pathlib Path
for manipulating files, you are better of using the new API ruamel.yaml provides:
from ruamel.yaml import YAML
from pathlib import Path
path = Path('example.yaml')
yaml = YAML(typ='safe')
data = yaml.load(path)
...and when I got one how to process it (do I need to use Fourier Transform like it was instructed in the above post)?
If you want a "tap" then I think you are interested in amplitude more than frequency. So Fourier transforms probably aren't useful for your particular goal. You probably want to make a running measurement of the short-term (say 10 ms) amplitude of the input, and detect when it suddenly increases by a certain delta. You would need to tune the parameters of:
Although I said you're not interested in frequency, you might want to do some filtering first, to filter out especially low and high frequency components. That might help you avoid some "false positives". You could do that with an FIR or IIR digital filter; Fourier isn't necessary.
Here's my solution:
@arr = ['<p>Hello World</p>', '<p>This is a test</p>']
@arr.reduce(:+)
=> <p>Hello World</p><p>This is a test</p>
UPDATE 2019:
Answer by David, is more accurate.
Typescript supports 3rd party vendor libraries, which do not use Typescript for library development, using DefinitelyTyped Repo.
You do need to declare jquery
/$
in your Component, If tsLint is On for these types of Type Checkings.
For Eg.
declare var jquery: any;
declare var $: any;
This will remove your colour as well as the underline that anchor tag exists with
a {
text-decoration: none ;
}
a:hover {
color:white;
text-decoration:none;
cursor:pointer;
}
scanf(" %[^\t\n]s",&str);
str
is the variable in which you are getting the string from.
You can use the following:
$regex = '#<\s*?code\b[^>]*>(.*?)</code\b[^>]*>#s';
\b
ensures that a typo (like <codeS>
) is not captured.[^>]*
captures the content of a tag with attributes (eg a class).s
capture content with newlines.See the result here : http://lumadis.be/regex/test_regex.php?id=1081
Another option to stream images from a webcam to a browser is via mjpeg. This is just a series of jpeg images that most modern browsers support as part of the tag. Here's a sample server written in c#:
https://www.codeproject.com/articles/371955/motion-jpeg-streaming-server
This works well over a LAN, but not as well over the internet as mjpeg is not as effcient as other video codecs (h264, VP8 etc..)
I have this version about datetimepicker https://tempusdominus.github.io/bootstrap-4/ and for any reason doesn`t work the change event with jquery but with JS vanilla it does
I figure out like this
document.getElementById('date').onchange = function(){ ...the jquery code...}
I hope work for you
some tests we did in our team show that A.class.isAssignableFrom(B.getClass())
works faster than B instanceof A
. this can be very useful if you need to check this on large number of elements.
Include the custom error page after changing the header.
You may also indicate the path to the gemfile in the same command e.g.
BUNDLE_GEMFILE="MyProject/Gemfile.ios" bundle install
I actually had this error and could not find a solution. I actually ended up not doing an ajax request. I don't know if this issue was due to this being sub domain on my server or what. Here's my jquery.
$('#deleteMeal').click(function(event) {
var theId = $(event.currentTarget).attr("data-mealId");
$(function() {
$( "#filler" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Are you sure you want to delete this Meal? Doing so will also delete this meal from other users Saved Meals.": function() {
$('#deleteMealLink').click();
// jQuery.ajax({
// url : 'http://www.mealog.com/mealtrist/meals/delete/' + theId,
// type : 'POST',
// success : function( response ) {
// $("#container").replaceWith("<h1 style='color:red'>Your Meal Has Been Deleted</h1>");
// }
// });
// similar behavior as clicking on a link
window.location.href = 'http://www.mealog.com/mealtrist/meals/delete/' + theId;
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
});
So I actually set up an anchor to go to my API rather than doing a post request, which is what I figure most applications do.
<p><a href="http://<?php echo $domain; ?>/mealtrist/meals/delete/{{ $meal->id }}" id="deleteMealLink" data-mealId="{{$meal->id}}" ></a></p>
It's your "fault" in that that's how Or
is defined, so it's the behaviour you should expect:
In a Boolean comparison, the Or operator always evaluates both expressions, which could include making procedure calls. The OrElse Operator (Visual Basic) performs short-circuiting, which means that if expression1 is True, then expression2 is not evaluated.
But you don't have to endure it. You can use OrElse
to get short-circuiting behaviour.
So you probably want:
If (example Is Nothing OrElse Not example.Item = compare.Item) Then
'Proceed
End If
I can't say it reads terribly nicely, but it should work...
You don't need function overloading, as you have the *args and **kwargs arguments.
The fact is that function overloading is based on the idea that passing different types you will execute different code. If you have a dynamically typed language like Python, you should not distinguish by type, but you should deal with interfaces and their compliance with the code you write.
For example, if you have code that can handle either an integer, or a list of integers, you can try iterating on it and if you are not able to, then you assume it's an integer and go forward. Of course it could be a float, but as far as the behavior is concerned, if a float and an int appear to be the same, then they can be interchanged.
Sometimes I use this, if I don't want it to be actually set and persisted in my db:
class Person
{
private string _name;
public string Name
{
get
{
return string.IsNullOrEmpty(_name) ? "Default Name" : _name;
}
set { _name = value; }
}
}
Obviously if it's not a string then I might make the object nullable ( double?, int? ) and check if it's null, return a default, or return the value it's set to.
Then I can make a check in my repository to see if it's my default and not persist, or make a backdoor check in to see the true status of the backing value, before saving.
Hope that helps!
this ones solved my problem
1.open command prompt in administration
then open apache bin folder like this,
c:\ cd wamp\bin\apache\apache2.4.17\bin>
then type after the above
c:\ cd wamp\bin\apache\apache2.4.17\bin> mklink php.ini d:\wamp\bin\php\php5.6.15\phpForApache.ini
thats it close the command prompt and restart the wamp and open it in admin mode.
original post : PHP: No php.ini file thanks to xiao.
If you want the password prompt to go away then use key based authentication (described here).
To run commands remotely over ssh you have to give them as an argument to ssh, like the following:
root@host:~ # ssh root@www 'ps -ef | grep apache | grep -v grep | wc -l'
A JAR is basically a ZIP file so treat it as such. Below contains an example on how to extract one file from a WAR file (also treat it as a ZIP file) and outputs the string contents. For binary you'll need to modify the extraction process, but there are plenty of examples out there for that.
public static void main(String args[]) {
String relativeFilePath = "style/someCSSFile.css";
String zipFilePath = "/someDirectory/someWarFile.war";
String contents = readZipFile(zipFilePath,relativeFilePath);
System.out.println(contents);
}
public static String readZipFile(String zipFilePath, String relativeFilePath) {
try {
ZipFile zipFile = new ZipFile(zipFilePath);
Enumeration<? extends ZipEntry> e = zipFile.entries();
while (e.hasMoreElements()) {
ZipEntry entry = (ZipEntry) e.nextElement();
// if the entry is not directory and matches relative file then extract it
if (!entry.isDirectory() && entry.getName().equals(relativeFilePath)) {
BufferedInputStream bis = new BufferedInputStream(
zipFile.getInputStream(entry));
// Read the file
// With Apache Commons I/O
String fileContentsStr = IOUtils.toString(bis, "UTF-8");
// With Guava
//String fileContentsStr = new String(ByteStreams.toByteArray(bis),Charsets.UTF_8);
// close the input stream.
bis.close();
return fileContentsStr;
} else {
continue;
}
}
} catch (IOException e) {
logger.error("IOError :" + e);
e.printStackTrace();
}
return null;
}
In this example I'm using Apache Commons I/O and if you are using Maven here is the dependency:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
This answer is from 2013 and is seriously outdated. As of Android 3.2 there are now 6 groups of screen density. This answer will be updated as soon as I am able, but with no ETA. Refer to the official documentation for all the densities at the moment (although information on specific pixel sizes is as always hard to find).
Create 4 images, one for each screen density:
Read 9-patch image introduction in Android Developer Guide
With this, Android will select the appropriate file for the device's image density, then it will stretch the image according to the 9-patch standard.
I am answering in respect to the design-related aspect of the question. I am not a developer, so I won't be able to provide code for implementing many of the solutions provided. Alas, my intent is to help designers who are as lost as I was when I helped develop my first Android App.
With Android, companies can develop their mobile phones and tables of almost any size, with almost any resolution they want. Because of that, there is no "right image size" for a splash screen, as there are no fixed screen resolutions. That poses a problem for people that want to implement a splash screen.
(On a side note, splash screens are somewhat discouraged among the usability guys. It is argued that the user already knows what app he tapped on, and branding your image with a splash screen is not necessary, as it only interrupts the user experience with an "ad". It should be used, however, in applications that require some considerable loading when initialized (5s+), including games and such, so that the user is not stuck wondering if the app crashed or not)
So, given so many different screen resolutions in the phones on the market, Google implemented some alternatives and nifty solutions that can help. The first thing you have to know is that Android separates ALL screens into 4 distinct screen densities:
What you (if you're a designer) need to know from this is that Android basically chooses from 4 images to display, depending on the device. So you basically have to design 4 different images (although more can be developed for different formats such as widescreen, portrait/landscape mode, etc).
With that in mind know this: unless you design a screen for every single resolution that is used in Android, your image will stretch to fit screen size. And unless your image is basically a gradient or blur, you'll get some undesired distortion with the stretching. So you have basically two options: create an image for each screen size/density combination, or create four 9-patch images.
The hardest solution is to design a different splash screen for every single resolution. You can start by following the resolutions in the table at the end of this page (there are more. Example: 960 x 720 is not listed there). And assuming you have some small detail in the image, such as small text, you have to design more than one screen for each resolution. For example, a 480x800 image being displayed in a medium screen might look ok, but on a smaller screen (with higher density/dpi) the logo might become too small, or some text might become unreadable.
The other solution is to create a 9-patch image. It is basically a 1-pixel-transparent-border around your image, and by drawing black pixels in the top and left area of this border you can define which portions of your image will be allowed to stretch. I won't go into the details of how 9-patch images work but, in short, the pixels that align to the markings in the top and left area are the pixels that will be repeated to stretch the image.
So you can place 1 dot on either side of your logo (in the top border), and 1 dot above and below it (on the left border), and these marked rows and columns will be the only pixels to stretch.
Here's a 9-patch image, 102x102px (100x100 final size, for app purposes):
Here's a 200% zoom of the same image:
Notice the 1px marks on top and left saying which rows/columns will expand.
Here's what this image would look like in 100x100 inside the app:
And here's what it would like if expanded to 460x140:
One last thing to consider. These images might look fine on your monitor screen and on most mobiles, but if the device has a very high image density (dpi), the image would look too small. Probably still legible, but on a tablet with 1920x1200 resolution, the image would appear as a very small square in the middle. So what's the solution? Design 4 different 9-patch launcher images, each for a different density set. To ensure that no shrinking will occur, you should design in the lowest common resolution for each density category. Shrinking is undesirable here because 9-patch only accounts for stretching, so in a shrinking process small text and other elements might lose legibility.
Here's a list of the smallest, most common resolutions for each density category:
So design four splash screens in the above resolutions, expand the images, putting a 1px transparent border around the canvas, and mark which rows/columns will be stretchable. Keep in mind these images will be used for ANY device in the density category, so your ldpi image (240 x 320) might be stretched to 1024x600 on an extra large tablet with small image density (~120 dpi). So 9-patch is the best solution for the stretching, as long as you don't want a photo or complicated graphics for a splash screen (keep in mind these limitations as you create the design).
Again, the only way for this stretching not to happen is to design one screen each resolution (or one for each resolution-density combination, if you want to avoid images becoming too small/big on high/low density devices), or to tell the image not to stretch and have a background color appear wherever stretching would occur (also remember that a specific color rendered by the Android engine will probably look different from the same specific color rendered by photoshop, because of color profiles).
I hope this made any sense. Good luck!
the case above is for a new project. I hit upon this error while editing a fork of a well established library.
the typedef was included in the file I was editing but the struct wasn't.
The end result being that I was attempting to edit the struct in the wrong place.
If you run into this in a similar way look for other places where the struct is edited and try it there.
Use preg_grep
$array = preg_grep(
'/(my\n+string\n+)/i',
array( 'file' , 'my string => name', 'this')
);
A solution I came up with when using the index was not viable ( possibly the multi-Gig .csv was too large, or I missed some technique that would allow me to reindex without crashing ).
Walk through one row at a time and add the nth row to a new dataframe.
import pandas as pd
from csv import DictReader
def make_downsampled_df(filename, interval):
with open(filename, 'r') as read_obj:
csv_dict_reader = DictReader(read_obj)
column_names = csv_dict_reader.fieldnames
df = pd.DataFrame(columns=column_names)
for index, row in enumerate(csv_dict_reader):
if index % interval == 0:
print(str(row))
df = df.append(row, ignore_index=True)
return df
My answer for your question is below
let dict = ["0": "ArrayObjectOne", "1": "ArrayObjecttwo", "2": "ArrayObjectThree"]
var error : NSError?
let jsonData = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted)
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
print(jsonString)
Answer is
{
"0" : "ArrayObjectOne",
"1" : "ArrayObjecttwo",
"2" : "ArrayObjectThree"
}
you can use style
<td colspan="2">
<div style="float:left; width:80px"><asp:Label ID="Label6" runat="server" Text="Label"></asp:Label></div>
<div style="float: right; width:100px">
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</div>
<div style="clear:both"></div>
</td>
Echo is so nineties and so fraught with perils that its use should result in core dumps no less than 4GB. Seriously, echo's problems were the reason why the Unix Standardization process finally invented the printf
utility, doing away with all the problems.
So to get a newline in a string:
FOO="hello
world"
BAR=$(printf "hello\nworld\n") # Alternative; note: final newline is deleted
printf '<%s>\n' "$FOO"
printf '<%s>\n' "$BAR"
There! No SYSV vs BSD echo madness, everything gets neatly printed and fully portable support for C escape sequences. Everybody please use printf
now and never look back.
It depends if you know the given variable Type. If you expect it to be an Object than you could check if myVar is an empty Object like this:
public isEmpty(myVar): boolean {
return (myVar && (Object.keys(myVar).length === 0));
}
Otherwise: if (!myVar) {}, should do the job
Depending on the AWK
implementation are you using ==
is ok or not.
Have you tried ~
?. For example, if you want $1 to be "hello":
awk '$1 ~ /^hello$/{ print $3; }' <infile>
^
means $1 start, and $
is $1 end.
Use something like this:
page1.php
<?php
session_start();
$_SESSION['myValue']=3; // You can set the value however you like.
?>
Any other PHP page:
<?php
session_start();
echo $_SESSION['myValue'];
?>
A few notes to keep in mind though: You need to call session_start()
BEFORE any output, HTML, echos - even whitespace.
You can keep changing the value in the session - but it will only be able to be used after the first page - meaning if you set it in page 1, you will not be able to use it until you get to another page or refresh the page.
The setting of the variable itself can be done in one of a number of ways:
$_SESSION['myValue']=1;
$_SESSION['myValue']=$var;
$_SESSION['myValue']=$_GET['YourFormElement'];
And if you want to check if the variable is set before getting a potential error, use something like this:
if(!empty($_SESSION['myValue'])
{
echo $_SESSION['myValue'];
}
else
{
echo "Session not set yet.";
}
I also struggled a lot with this issue. The answers in this thread were helpful but were not enough to resolve my error. You will need to disable Hyper-V and Device guard like the other answers have suggested. More info on that can be found in here.
I am including the changes needed to be done in addition to the answers provided above. The link that finally helped me was this.
My answer is going to summarize only the difference between the rest of the answers (i.e. Disabling Hyper-V and Device guard) and the following steps :
Delete the following registry settings:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\LSA\LsaCfgFlags HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\DeviceGuard\EnableVirtualizationBasedSecurity HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\DeviceGuard\RequirePlatformSecurityFeatures
Important : If you manually remove these registry settings, make sure to delete them all. If you don't remove them all, the device might go into BitLocker recovery.
Delete the Windows Defender Credential Guard EFI variables by using bcdedit. From an elevated command prompt(start in admin mode), type the following commands:
mountvol X: /s
copy %WINDIR%\System32\SecConfig.efi X:\EFI\Microsoft\Boot\SecConfig.efi /Y
bcdedit /create {0cb3b571-2f2e-4343-a879-d86a476d7215} /d "DebugTool" /application osloader
bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} path "\EFI\Microsoft\Boot\SecConfig.efi"
bcdedit /set {bootmgr} bootsequence {0cb3b571-2f2e-4343-a879-d86a476d7215}
bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} loadoptions DISABLE-LSA-ISO
bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} device partition=X:
mountvol X: /d
Restart the PC.
Accept the prompt to disable Windows Defender Credential Guard.
Alternatively, you can disable the virtualization-based security features to turn off Windows Defender Credential Guard.
function flatten_array($array, $preserve_keys = 0, &$out = array()) {
# Flatten a multidimensional array to one dimension, optionally preserving keys.
#
# $array - the array to flatten
# $preserve_keys - 0 (default) to not preserve keys, 1 to preserve string keys only, 2 to preserve all keys
# $out - internal use argument for recursion
foreach($array as $key => $child)
if(is_array($child))
$out = flatten_array($child, $preserve_keys, $out);
elseif($preserve_keys + is_string($key) > 1)
$out[$key] = $child;
else
$out[] = $child;
return $out;
}
Here are some common datatypes I use (I am not much of a pro though):
| Column | Data type | Note
| ---------------- | ------------- | -------------------------------------
| id | INTEGER | AUTO_INCREMENT, UNSIGNED |
| uuid | CHAR(36) | or CHAR(16) binary |
| title | VARCHAR(255) | |
| full name | VARCHAR(70) | |
| gender | TINYINT | UNSIGNED |
| description | TINYTEXT | often may not be enough, use TEXT
instead
| post body | TEXT | |
| email | VARCHAR(255) | |
| url | VARCHAR(2083) | MySQL version < 5.0.3 - use TEXT |
| salt | CHAR(x) | randomly generated string, usually of
fixed length (x)
| digest (md5) | CHAR(32) | |
| phone number | VARCHAR(20) | |
| US zip code | CHAR(5) | Use CHAR(10) if you store extended
codes
| US/Canada p.code | CHAR(6) | |
| file path | VARCHAR(255) | |
| 5-star rating | DECIMAL(3,2) | UNSIGNED |
| price | DECIMAL(10,2) | UNSIGNED |
| date (creation) | DATE/DATETIME | usually displayed as initial date of
a post |
| date (tracking) | TIMESTAMP | can be used for tracking changes in a
post |
| tags, categories | TINYTEXT | comma separated values * |
| status | TINYINT(1) | 1 – published, 0 – unpublished, … You
can also use ENUM for human-readable
values
| json data | JSON | or LONGTEXT
You can see Silverlight/WPF sets ellipse with hexadecimal colour for using a hex value:
your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)
For IE: window.close();
and self.close();
should work fine.
If you want just open the IE browser and type
javascript:self.close()
and hit enter, it should ask you for a prompt.
Note: this method doesn't work for Chrome or Firefox.
another solution is to override the join operator of the str class.
Let us define a new class my_string as follows
class my_string(str):
def join(self, l):
l_tmp = [str(x) for x in l]
return super(my_string, self).join(l_tmp)
Then you can do
class Obj:
def __str__(self):
return 'name'
list = [Obj(), Obj(), Obj()]
comma = my_string(',')
print comma.join(list)
and you get
name,name,name
BTW, by using list as variable name you are redefining the list class (keyword) ! Preferably use another identifier name.
Hope you'll find my answer useful.
This work for me:
const handleCopyLink = useCallback(() => {
const textField = document.createElement('textarea')
textField.innerText = url
document.body.appendChild(textField)
if (window.navigator.platform === 'iPhone') {
textField.setSelectionRange(0, 99999)
} else {
textField.select()
}
document.execCommand('copy')
textField.remove()
toast.success('Link successfully copied')
}, [url])
the first command is correct but change from convert to export to csv, as below,
Get-ADUser -Filter * -Properties * `
| Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,whenCreated,Enabled,Organization `
| Sort-Object -Property Name `
| Export-Csv -path C:\Users\*\Desktop\file1.csv
This post is not going to answer to Coppermill, because he have been answered long time ago. My post will be helpful for who will seeking for solution like this. First of all , I have to say " WDuffy's solution is totally correct" and it works fine, but my solution (not actually mine) will be used in other elements and it makes the presentation layer more independent from controller (because your controller depend on "value" which is used for showing label of the button, this feature is important for other languages.).
Here is my solution, give them different names:
<input type="submit" name="buttonSave" value="Save"/>
<input type="submit" name="buttonProcess" value="Process"/>
<input type="submit" name="buttonCancel" value="Cancel"/>
And you must specify the names of buttons as arguments in the action like below:
public ActionResult Register(string buttonSave, string buttonProcess, string buttonCancel)
{
if (buttonSave!= null)
{
//save is pressed
}
if (buttonProcess!= null)
{
//Process is pressed
}
if (buttonCancel!= null)
{
//Cancel is pressed
}
}
when user submits the page using one of the buttons, only one of the arguments will have value. I guess this will be helpful for others.
Update
This answer is quite old and I actually reconsider my opinion . maybe above solution is good for situation which passing parameter to model's properties. don't bother yourselves and take best solution for your project.
As an adaption of @Mike Fuchs answer, here's an even smaller solution. I'm using the Fody.AutoDependencyPropertyMarker
to reduce some of the boiler plate.
The Class
public class EventCommand : TriggerAction<DependencyObject>
{
[AutoDependencyProperty]
public ICommand Command { get; set; }
protected override void Invoke(object parameter)
{
if (Command != null)
{
if (Command.CanExecute(parameter))
{
Command.Execute(parameter);
}
}
}
}
The EventArgs
public class VisibleBoundsArgs : EventArgs
{
public Rect VisibleVounds { get; }
public VisibleBoundsArgs(Rect visibleBounds)
{
VisibleVounds = visibleBounds;
}
}
The XAML
<local:ZoomableImage>
<i:Interaction.Triggers>
<i:EventTrigger EventName="VisibleBoundsChanged" >
<local:EventCommand Command="{Binding VisibleBoundsChanged}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</local:ZoomableImage>
The ViewModel
public ICommand VisibleBoundsChanged => _visibleBoundsChanged ??
(_visibleBoundsChanged = new RelayCommand(obj => SetVisibleBounds(((VisibleBoundsArgs)obj).VisibleVounds)));
You can still use map
if you can afford to create a makeshift array:
{
new Array(this.props.level).fill(0).map((_, index) => (
<span className='indent' key={index}></span>
))
}
This works because new Array(n).fill(x)
creates an array of size n
filled with x
, which can then aid map
.
Lu55 Option 1 how to...
Add test only application.yml inside a seperated resources folder.
+-- main ¦ +-- java ¦ +-- resources ¦ +-- application.yml +-- test +-- java +-- resources +-- application.yml
In this project structure the application.yml under main is loaded if the code under main is running, the application.yml under test is used in a test.
To setup this structure add a new Package folder test/recources if not present.
Eclipse right click on your project -> Properties -> Java Build Path -> Source Tab -> (Dialog ont the rigth side) "Add Folder ..."
Inside Source Folder Selection -> mark test -> click on "Create New Folder ..." button -> type "resources" inside the Textfeld -> Click the "Finish" button.
After pushing the "Finisch" button you can see the sourcefolder {projectname}/src/test/recources (new)
Optional: Arrange folder sequence for the Project Explorer view.
Klick on Order and Export Tab mark and move {projectname}/src/test/recources to bottom.
Apply and Close
!!! Clean up Project !!!
Eclipse -> Project -> Clean ...
Now there is a separated yaml for test and the main application.
Just to add my TSQL-scripted solution:
First of all; add a new database named backup_lookup
.
Then just run this script, inserting your own databases' root path and backup filepath
USE [master]
GO
RESTORE DATABASE backup_lookup
FROM DISK = 'C:\backup.bak'
WITH REPLACE,
MOVE 'Old Database Name' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\backup_lookup.mdf',
MOVE 'Old Database Name_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\backup_lookup_log.ldf'
GO
Try setting the charset on your Content-Type:
httpCon.setRequestProperty( "Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + boundary );
Exactly what they said, it will work.
In the parent element stablish a max-height.
I'm taking sandeep example and adding the max-height and if required you can add max-width property. The text will stay where It should stay (If possible, in some cases you will need to change some values to make it stay in there)
span{
background: none repeat scroll 0 0 #F8F8F8;
border: 5px solid #DFDFDF;
color: #717171;
font-size: 13px;
height: 30px;
letter-spacing: 1px;
line-height: 30px;
margin: 0 auto;
position: relative;
text-align: center;
text-transform: uppercase;
top: -80px;
left:-30px;
display:none;
padding:0 20px;
}
span:after{
content:'';
position:absolute;
bottom:-10px;
width:10px;
height:10px;
border-bottom:5px solid #dfdfdf;
border-right:5px solid #dfdfdf;
background:#f8f8f8;
left:50%;
margin-left:-5px;
-moz-transform:rotate(45deg);
-webkit-transform:rotate(45deg);
transform:rotate(45deg);
}
p{
margin:100px;
float:left;
position:relative;
cursor:pointer;
max-height: 10px;
}
p:hover span{
display:block;
}
max-height in the p paragraph, second to last one, last line.
Test it before rating it useless.
You should try these tools :
xmlstarlet
: can edit, select, transform... Not installed by default, xpath1xmllint
: often installed by default with libxml2-utils
, xpath1 (check my wrapper to have --xpath
switch on very old releases and newlines delimited output (v < 2.9.9)xpath
: installed via perl's module XML::XPath
, xpath1xml_grep
: installed via perl's module XML::Twig
, xpath1 (limited xpath usage)xidel
: xpath3saxon-lint
: my own project, wrapper over @Michael Kay's Saxon-HE Java library, xpath3xmllint
comes with libxml2-utils
(can be used as interactive shell with the --shell
switch)
xmlstarlet
is xmlstarlet
.
xpath
comes with perl's module XML::Xpath
xml_grep
comes with perl's module XML::Twig
xidel
is xidel
saxon-lint
using SaxonHE 9.6 ,XPath 3.x (+retro compatibility)
Ex :
xmllint --xpath '//element/@attribute' file.xml
xmlstarlet sel -t -v "//element/@attribute" file.xml
xpath -q -e '//element/@attribute' file.xml
xidel -se '//element/@attribute' file.xml
saxon-lint --xpath '//element/@attribute' file.xml
.
What you need is a datetime which is 30 minutes later than your given datetime, and a datetime which is 30 minutes before a given datetime. In other words, you need a future datetime and a past datetime. Hence, classes that achieve that are called Future
and Past
. What data do they need to calculate what you need? Apparently, they must have a datetime relative to which to count those 30 minutes, and an interval itself -- 30 minutes in your case. Thus, the desired datetime looks like the following:
use Meringue\ISO8601DateTime\FromCustomFormat as DateTimeCreatedFromCustomFormat;
(new Future(
new DateTimeCreatedFromCustomFormat('H:i', '10:00'),
new NMinutes(30)
))
->value();
If you want to format it somehow, you can do:
use Meringue\ISO8601DateTime\FromCustomFormat as DateTimeCreatedFromCustomFormat;
(new ISO8601Formatted(
new Future(
new DateTimeCreatedFromCustomFormat('H:i', '10:00'),
new NMinutes(30)
),
'H:i'
))
->value();
It's more verbose, but I guess it's way less cryptic than built-in php functions.
If you liked this approach, you can learn some more about the meringue library used in this example, and the overall approach.
I'd like to add on for the #else
case:
#if 0
/* Code here will NOT be complied. */
#else
/* Code will be compiled. */
#endif
#if 1
/* Code will be complied. */
#else
/* Code will NOT be compiled. */
#endif
Promise returned from $http
can not be binded directly (I dont exactly know why).
I'm using wrapping service that works perfectly for me:
.factory('DocumentsList', function($http, $q){
var d = $q.defer();
$http.get('/DocumentsList').success(function(data){
d.resolve(data);
});
return d.promise;
});
and bind to it in controller:
function Ctrl($scope, DocumentsList) {
$scope.Documents = DocumentsList;
...
}
UPDATE!:
In Angular 1.2 auto-unwrap promises was removed. See http://docs.angularjs.org/guide/migration#templates-no-longer-automatically-unwrap-promises
The precise way to do this is it to use .project()
cursor method with the new mongodb
and nodejs
driver.
var query = await dbSchemas.SomeValue.find({}).project({ name: 1, _id: 0 })
I was using Spring Data JPA with PostgreSql and during UPDATE call it was showing errors-
Actually, I was missing two required Annotations.
With-
@Query(vlaue = " UPDATE DB.TABLE SET Col1 = ?1 WHERE id = ?2 ", nativeQuery = true)
void updateCol1(String value, long id);
I had similar problem, but in folder which I wanted to move I had files which I was not tracking.
let's say I had files
a/file1
a/untracked1
b/file2
b/untracked2
And I wanted to move only tracked files to subfolder subdir
, so the goal was:
subdir/a/file1
subdir/a/untracked1
subdir/b/file2
subdir/b/untracked2
what I had done was:
mkdir tmpdir && mv a b tmpdir
git checkout a b
mkdir subdir && mv a b subdir
git add --update
with directory change trick): git add subdir
(normally this would add even untracked files - this would require creating .gitignore
file)git status
shows now only moved filesmv tmpdir/* subdir
git status
looks like we executed git mv
:)Razor is just a templating engine.
You should create a regular class.
If you want to make a method inside of a Razor page, put them in an @functions
block.