python -m pip install -r requirements.txt
Referece: How to install packages using pip according to the requirements.txt file from a local directory?
You can use jstat, like :
jstat -gc pid
Full docs here : http://docs.oracle.com/javase/7/docs/technotes/tools/share/jstat.html
With jQuery it will be something like that:
$(document).ready(function() {
$('#yourDiv').on('mousedown', function(e) {
e.preventDefault();
});
});
In my case I wanted to disable the user from drop text in the inputs so I used "drop" instead "mousedown".
$(document).ready(function() {
$('input').on('drop', function(event) {
event.preventDefault();
});
});
Instead event.preventDefault() you can return false. Here's the difference.
And the code:
$(document).ready(function() {
$('input').on('drop', function() {
return false;
});
});
what if your wrapping div was 100% and you used padding for a pixel amount, then if the padding # needs to be dynamic, you can easily use jQuery to modify your padding amount when your events fire.
In Java this would be System.in.read()
What if there is & in URL parameter like filename="p&g.html"&uid=66
In this case the 1st function will not work properly. So I modified the code
function getUrlParameter(sParam) {
var sURLVariables = window.location.search.substring(1).split('&'), sParameterName, i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
}
IMPORTANT: It is safe to remove the workspace for a given Jenkins job as long as the job is not currently running!
NOTE: I am assuming your $JENKINS_HOME
is set to the default: /var/jenkins_home
.
rm -rf /var/jenkins_home/workspaces/<workspace>
rm -rf /var/jenkins_home/workspaces/*
This one uses grep to create a whitelist:
ls /var/jenkins_home/workspace \
| grep -v -E '(job-to-skip|another-job-to-skip)$' \
| xargs -I {} rm -rf /var/jenkins_home/workspace/{}
This one uses du and sort to list workspaces in order of largest to smallest. Then, it uses head to grab the first 10:
du -d 1 /var/jenkins_home/workspace \
| sort -n -r \
| head -n 10 \
| xargs -I {} rm -rf /var/jenkins_home/workspace/{}
You may directly right-click on the table name - that also shows the "Import Data.." option.Then you can follow few simple steps & succeed.
Do anyone know how to import a new table with data from excel?
Can also use here document and vi, the below script generates a FILE.txt with 3 lines and variable interpolation
VAR=Test
vi FILE.txt <<EOFXX
i
#This is my var in text file
var = $VAR
#Thats end of text file
^[
ZZ
EOFXX
Then file will have 3 lines as below. "i" is to start vi insert mode and similarly to close the file with Esc and ZZ.
#This is my var in text file
var = Test
#Thats end of text file
Here ya go..
List<string> list = new List<string>() { "1", "2", "3" };
List<string> remove = new List<string>() { "2" };
list.ForEach(s =>
{
if (remove.Contains(s))
{
list.Remove(s);
}
});
You can easily customize the android Navigation drawer once you know how its implemented. here is a nice tutorial where you can set it up.
This will be the structure of your mainXML:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<ListView
android:id="@+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="right"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector"
android:background="@color/list_background"/>
</android.support.v4.widget.DrawerLayout>
You can customize this listview to your liking by adding the header. And radiobuttons.
Counting rows in big tables is known to be slow in PostgreSQL. To get a precise number it has to do a full count of rows due to the nature of MVCC. There is a way to speed this up dramatically if the count does not have to be exact like it seems to be in your case.
Instead of getting the exact count (slow with big tables):
SELECT count(*) AS exact_count FROM myschema.mytable;
You get a close estimate like this (extremely fast):
SELECT reltuples::bigint AS estimate FROM pg_class where relname='mytable';
How close the estimate is depends on whether you run ANALYZE
enough. It is usually very close.
See the PostgreSQL Wiki FAQ.
Or the dedicated wiki page for count(*) performance.
The article in the PostgreSQL Wiki is was a bit sloppy. It ignored the possibility that there can be multiple tables of the same name in one database - in different schemas. To account for that:
SELECT c.reltuples::bigint AS estimate
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relname = 'mytable'
AND n.nspname = 'myschema'
SELECT reltuples::bigint AS estimate
FROM pg_class
WHERE oid = 'myschema.mytable'::regclass;
Faster, simpler, safer, more elegant. See the manual on Object Identifier Types.
Use to_regclass('myschema.mytable')
in Postgres 9.4+ to avoid exceptions for invalid table names:
TABLESAMPLE SYSTEM (n)
in Postgres 9.5+SELECT 100 * count(*) AS estimate FROM mytable TABLESAMPLE SYSTEM (1);
Like @a_horse commented, the newly added clause for the SELECT
command might be useful if statistics in pg_class
are not current enough for some reason. For example:
autovacuum
running.INSERT
or DELETE
.TEMPORARY
tables (which are not covered by autovacuum
).This only looks at a random n % (1
in the example) selection of blocks and counts rows in it. A bigger sample increases the cost and reduces the error, your pick. Accuracy depends on more factors:
FILLFACTOR
occupy space per block. If unevenly distributed across the table, the estimate may be off.In most cases the estimate from pg_class
will be faster and more accurate.
First, I need to know the number of rows in that table, if the total count is greater than some predefined constant,
And whether it ...
... is possible at the moment the count pass my constant value, it will stop the counting (and not wait to finish the counting to inform the row count is greater).
Yes. You can use a subquery with LIMIT
:
SELECT count(*) FROM (SELECT 1 FROM token LIMIT 500000) t;
Postgres actually stops counting beyond the given limit, you get an exact and current count for up to n rows (500000 in the example), and n otherwise. Not nearly as fast as the estimate in pg_class
, though.
You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend
import matplotlib.pyplot as plt
plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)
plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
MySQL has 4 levels of collation: server, database, table, column. If you change the collation of the server, database or table, you don't change the setting for each column, but you change the default collations.
E.g if you change the default collation of a database, each new table you create in that database will use that collation, and if you change the default collation of a table, each column you create in that table will get that collation.
In DJango 3.0 the default value of a BooleanField in model.py is set like this:
class model_name(models.Model):
example_name = models.BooleanField(default=False)
Note: This assumes that you will declare constants for row and column indexes named COLUMN_HEADING_ROW
, FIRST_COL
, and LAST_COL
, and that _xlSheet
is the name of the ExcelSheet
(using Microsoft.Interop.Excel
)
First, define the range:
var columnHeadingsRange = _xlSheet.Range[
_xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
_xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];
Then, set the background color of that range:
columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;
Finally, set the font color:
columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;
And here's the code combined:
var columnHeadingsRange = _xlSheet.Range[
_xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
_xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];
columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;
columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;
You can combine attribute selectors this way:
$("[attr1=val][attr2=val]")...
so that an element has to satisfy both conditions. Of course you can use this for more than two. Also, don't do [type=checkbox]
. jQuery has a selector for that, namely :checkbox
so the end result is:
$("input:checkbox[name=ProductCode]")...
Attribute selectors are slow however so the recommended approach is to use ID and class selectors where possible. You could change your markup to:
<input type="checkbox" class="ProductCode" name="ProductCode"value="396P4">
<input type="checkbox" class="ProductCode" name="ProductCode"value="401P4">
<input type="checkbox" class="ProductCode" name="ProductCode"value="F460129">
allowing you to use the much faster selector of:
$("input.ProductCode")...
IP + "User Agent" could be a better for unique visitor.
Google "Freeware MSI installer".
e.g. https://www.advancedinstaller.com/
Several options here:
http://rbytes.net/software/development_c/install-and-setup_s/
Though being Windows, most are "shareware" rather than truly free and open source.
Since strptime
returns a datetime object which has tzinfo
attribute, We can simply replace it with desired timezone.
>>> import datetime
>>> date_time_str = '2018-06-29 08:15:27.243860'
>>> date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f').replace(tzinfo=datetime.timezone.utc)
>>> date_time_obj.tzname()
'UTC'
With CSS tables, you could wrap a div around the two you have there and use this css/html structure:
<style type="text/css">
.container { display:table; width:100%; height:100%; }
#div1 { display:table-row; height:50px; background-color:red; }
#div2 { display:table-row; background-color:blue; }
</style>
<div class="container">
<div id="div1"></div>
<div id="div2"></div>
</div>
Depends on what browsers support these display types, however. I don't think IE8 and below do. EDIT: Scratch that-- IE8 does support CSS tables.
It all depends on how its going to be used. If you will want to switch back and forth between these two panels then use a CardLayout. If you are only switching from the first to the second once and (and not going back) then I would use telcontars suggestion and just replace it. Though if the JPanel isn't the only thing in your frame I would use remove(java.awt.Component) instead of removeAll.
If you are somewhere in between these two cases its basically a time-space tradeoff. The CardLayout will save you time but take up more memory by having to keep this whole other panel in memory at all times. But if you just replace the panel when needed and construct it on demand, you don't have to keep that meory around but it takes more time to switch.
Also you can try a JTabbedPane to use tabs instead (its even easier than CardLayout because it handles the showing/hiding automitically)
There are five methods to choose from:
You can use clear(), this method when invoked clears the entire storage of all records for that domain. It does not receive any parameters.
window.localStorage.clear();
You can use <LinearLayout>
to group elements horizontaly. Also you should use style to set margins, background and other properties. This will allow you not to repeat code for every label you use.
Here is an example:
<LinearLayout
style="@style/FormItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
style="@style/FormLabel"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:text="@string/name_label"
/>
<EditText
style="@style/FormText.Editable"
android:id="@+id/cardholderName"
android:layout_width="wrap_content"
android:layout_height="@dimen/default_element_height"
android:layout_weight="1"
android:gravity="right|center_vertical"
android:hint="@string/card_name_hint"
android:imeOptions="actionNext"
android:singleLine="true"
/>
</LinearLayout>
Also you can create a custom view base on the layout above. Have you looked at Creating custom view ?
If you use Spring-jpa
, this is a supplement to the answers and this question. Please correct this if any flaws. I have mainly used three methods to achieve "mapping result Object[]
to a pojo" based on what practical need I meet:
sql
with its Entity
are enough.The former 2 failed, and I have to use a nativeQuery
.
Here are the examples.
The pojo expected:
public class Antistealingdto {
private String secretKey;
private Integer successRate;
// GETTERs AND SETTERs
public Antistealingdto(String secretKey, Integer successRate) {
this.secretKey = secretKey;
this.successRate = successRate;
}
}
Method 1: Change the pojo into an interface:
public interface Antistealingdto {
String getSecretKey();
Integer getSuccessRate();
}
And repository:
interface AntiStealingRepository extends CrudRepository<Antistealing, Long> {
Antistealingdto findById(Long id);
}
Method 2: Repository:
@Query("select new AntistealingDTO(secretKey, successRate) from Antistealing where ....")
Antistealing whatevernamehere(conditions);
Note: parameter sequence of POJO constructor must be identical in both POJO definition and sql.
Method 3:
Use @SqlResultSetMapping
and @NamedNativeQuery
in Entity
as the example in Edwin Dalorzo's answer.
The first two methods would call many in-the-middle handlers, like customized converters. For example, AntiStealing
defines a secretKey
, before it is persisted, a converter is inserted to encrypt it. This would result in the first 2 methods returning a converted back secretKey
which is not what I want. While the method 3 would overcome the converter, and returned secretKey
would be the same as it is stored (an encrypted one).
There two ways, what I found either go to the directory where kernels are residing and delete from there. Secondly, using this command below
List all kernels and grap the name of the kernel you want to remove
jupyter kernelspec list
to get the paths of all your kernels.
Then simply uninstall your unwanted-kernel
jupyter kernelspec remove kernel_name
You can use the overloaded < or > operators.
For example:
DateTime d1 = new DateTime(2008, 1, 1);
DateTime d2 = new DateTime(2008, 1, 2);
if (d1 < d2) { ...
5623125698541159
is treated as a single number (out of range of int
on most architecture). You need to write numbers in your file as
5 6 2 3 1 2 5 6 9 8 5 4 1 1 5 9
for 16 numbers.
If your file has input
5,6,2,3,1,2,5,6,9,8,5,4,1,1,5,9
then change %d
specifier in your fscanf
to %d,
.
fscanf(myFile, "%d,", &numberArray[i] );
Here is your full code after few modifications:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *myFile;
myFile = fopen("somenumbers.txt", "r");
//read file into array
int numberArray[16];
int i;
if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < 16; i++){
fscanf(myFile, "%d,", &numberArray[i] );
}
for (i = 0; i < 16; i++){
printf("Number is: %d\n\n", numberArray[i]);
}
fclose(myFile);
return 0;
}
My Previous answer is not scalable. Here is what I think is good approach-
Your Routes-
<Switch>
<Route
exact path="/"
component={matchStateToProps(InitialAppState, {
routeOpen: true // no auth is needed to access this route
})} />
<Route
exact path="/profile"
component={matchStateToProps(Profile, {
routeOpen: false // can set it false or just omit this key
})} />
<Route
exact path="/login"
component={matchStateToProps(Login, {
routeOpen: true
})} />
<Route
exact path="/forgot-password"
component={matchStateToProps(ForgotPassword, {
routeOpen: true
})} />
<Route
exact path="/dashboard"
component={matchStateToProps(DashBoard)} />
</Switch>
Idea is to use a wrapper in component
props which would return original component if no auth is required or already authenticated otherwise would return default component e.g. Login.
const matchStateToProps = function(Component, defaultProps) {
return (props) => {
let authRequired = true;
if (defaultProps && defaultProps.routeOpen) {
authRequired = false;
}
if (authRequired) {
// check if loginState key exists in localStorage (Your auth logic goes here)
if (window.localStorage.getItem(STORAGE_KEYS.LOGIN_STATE)) {
return <Component { ...defaultProps } />; // authenticated, good to go
} else {
return <InitialAppState { ...defaultProps } />; // not authenticated
}
}
return <Component { ...defaultProps } />; // no auth is required
};
};
If you use position: absolute;
and jQuery, you could use
$("#mydiv").css("height", $(document).height() + "px");
Under "Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions" add _CRT_SECURE_NO_WARNINGS
Instead of changing the default table-hover class, make a new class ( anotherhover ) and apply it to the table that you need this effect for.
Code as below;
.anotherhover tbody tr:hover td { background: CornflowerBlue; }
I know it is old but if you want to get this from an URL you could simply use:
document.location.pathname.substring(document.location.pathname.lastIndexOf('/.') + 1);
document.location.pathname
gets the pathname from the current URL.
lastIndexOf
get the index of the last occurrence of the following Regex, in our case is /.
. The dot means any character, thus, it will not count if the /
is the last character on the URL.
substring
will cut the string between two indexes.
Seeing that it appears you are running using the SQL syntax, try with the correct wild card.
SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4;
View Demo which is using angularjs
and see your's browser log
<!DOCTYPE html>
<html ng-app="Application_TimeOut">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>
<body>
</body>
<script>
var app = angular.module('Application_TimeOut', []);
app.run(function($rootScope, $timeout, $document) {
console.log('starting run');
// Timeout timer value
var TimeOutTimerValue = 5000;
// Start a timeout
var TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
var bodyElement = angular.element($document);
/// Keyboard Events
bodyElement.bind('keydown', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('keyup', function (e) { TimeOut_Resetter(e) });
/// Mouse Events
bodyElement.bind('click', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('mousemove', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('DOMMouseScroll', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('mousewheel', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('mousedown', function (e) { TimeOut_Resetter(e) });
/// Touch Events
bodyElement.bind('touchstart', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('touchmove', function (e) { TimeOut_Resetter(e) });
/// Common Events
bodyElement.bind('scroll', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('focus', function (e) { TimeOut_Resetter(e) });
function LogoutByTimer()
{
console.log('Logout');
///////////////////////////////////////////////////
/// redirect to another page(eg. Login.html) here
///////////////////////////////////////////////////
}
function TimeOut_Resetter(e)
{
console.log('' + e);
/// Stop the pending timeout
$timeout.cancel(TimeOut_Thread);
/// Reset the timeout
TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
}
})
</script>
</html>
Below code is pure javascript version
<html>
<head>
<script type="text/javascript">
function logout(){
console.log('Logout');
}
function onInactive(millisecond, callback){
var wait = setTimeout(callback, millisecond);
document.onmousemove =
document.mousedown =
document.mouseup =
document.onkeydown =
document.onkeyup =
document.focus = function(){
clearTimeout(wait);
wait = setTimeout(callback, millisecond);
};
}
</script>
</head>
<body onload="onInactive(5000, logout);"></body>
</html>
I updated my solution as @Tom suggestion.
<!DOCTYPE html>
<html ng-app="Application_TimeOut">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>
<body>
</body>
<script>
var app = angular.module('Application_TimeOut', []);
app.run(function($rootScope, $timeout, $document) {
console.log('starting run');
// Timeout timer value
var TimeOutTimerValue = 5000;
// Start a timeout
var TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
var bodyElement = angular.element($document);
angular.forEach(['keydown', 'keyup', 'click', 'mousemove', 'DOMMouseScroll', 'mousewheel', 'mousedown', 'touchstart', 'touchmove', 'scroll', 'focus'],
function(EventName) {
bodyElement.bind(EventName, function (e) { TimeOut_Resetter(e) });
});
function LogoutByTimer(){
console.log('Logout');
///////////////////////////////////////////////////
/// redirect to another page(eg. Login.html) here
///////////////////////////////////////////////////
}
function TimeOut_Resetter(e){
console.log(' ' + e);
/// Stop the pending timeout
$timeout.cancel(TimeOut_Thread);
/// Reset the timeout
TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
}
})
</script>
</html>
you have forgotten width of parent
.parent {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
position: absolute;_x000D_
width:100%_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">text</div>_x000D_
</div>
_x000D_
I needed to break some text into paragraphs ("p" tags), so I created a simple helper using some of the recommendations in previous answers (thank you guys).
public static MvcHtmlString ToParagraphs(this HtmlHelper html, string value)
{
value = html.Encode(value).Replace("\r", String.Empty);
var arr = value.Split('\n').Where(a => a.Trim() != string.Empty);
var htmlStr = "<p>" + String.Join("</p><p>", arr) + "</p>";
return MvcHtmlString.Create(htmlStr);
}
Usage:
@Html.ToParagraphs(Model.Comments)
Here is a function using recursion which will work on any arbitrary nested list.
def flatten(nested_lst):
""" Return a list after transforming the inner lists
so that it's a 1-D list.
>>> flatten([[[],["a"],"a"],[["ab"],[],"abc"]])
['a', 'a', 'ab', 'abc']
"""
if not isinstance(nested_lst, list):
return(nested_lst)
res = []
for l in nested_lst:
if not isinstance(l, list):
res += [l]
else:
res += flatten(l)
return(res)
>>> flatten([[[],["a"],"a"],[["ab"],[],"abc"]])
['a', 'a', 'ab', 'abc']
if you have generic types in your class you should use TypeReference
with convertValue()
.
final ObjectMapper mapper = new ObjectMapper();
final MyPojo<MyGenericType> pojo = mapper.convertValue(map, new TypeReference<MyPojo<MyGenericType>>() {});
Also you can use that to convert a pojo to java.util.Map
back.
final ObjectMapper mapper = new ObjectMapper();
final Map<String, Object> map = mapper.convertValue(pojo, new TypeReference<Map<String, Object>>() {});
Obviously, you'll need a rooted android device. Then set up an FTP server and transfer the files.
Please try this out to take into account all possible scenarios:
awk '{print $(NF-1)"\t"$NF}' file
or
awk 'BEGIN{OFS="\t"}' file
or
awk '{print $(NF-1), $NF} {print $(NF-1), $NF}' file
First of all I'd like to note that you cannot even rely on the fact that (-1) % 8 == -1
. the only thing you can rely on is that (x / y) * y + ( x % y) == x
. However whether or not the remainder is negative is implementation-defined.
Now why use templates here? An overload for ints and longs would do.
int mod (int a, int b)
{
int ret = a % b;
if(ret < 0)
ret+=b;
return ret;
}
and now you can call it like mod(-1,8) and it will appear to be 7.
Edit: I found a bug in my code. It won't work if b is negative. So I think this is better:
int mod (int a, int b)
{
if(b < 0) //you can check for b == 0 separately and do what you want
return -mod(-a, -b);
int ret = a % b;
if(ret < 0)
ret+=b;
return ret;
}
Reference: C++03 paragraph 5.6 clause 4:
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.
<!-- Drop Shadow Stack -->
<item>
<shape android:shape="oval">
<padding
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="#00CCCCCC" />
<corners android:radius="3dp" />
</shape>
</item>
<item>
<shape android:shape="oval">
<padding
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="#10CCCCCC" />
<corners android:radius="3dp" />
</shape>
</item>
<item>
<shape android:shape="oval">
<padding
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="#20CCCCCC" />
<corners android:radius="3dp" />
</shape>
</item>
<item>
<shape android:shape="oval">
<padding
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="#30CCCCCC" />
<corners android:radius="3dp" />
</shape>
</item>
<item>
<shape android:shape="oval">
<padding
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" />
<solid android:color="#50CCCCCC" />
<corners android:radius="3dp" />
</shape>
</item>
<!-- Background -->
<item>
<shape android:shape="oval">
<gradient
android:startColor="@color/colorAccent_1"
android:centerColor="@color/colorAccent_2"
android:endColor="@color/colorAccent_3"
android:angle="45"
/>
<corners android:radius="3dp" />
</shape>
</item>
<color name="colorAccent_1">#6f64d6</color>
<color name="colorAccent_2">#7668F8</color>
<color name="colorAccent_3">#6F63FF</color>
I think it was not possible earlier but I recently heard about PyMob, which seems interesting because the apps are written in Python and the final outputs are native source codes in various platforms (Obj-C for iOS, Java for Android etc). This is certainly quite unique. This webpage explains it in more detail.
I haven't given it a shot yet, but will take a look soon.
For code mirror divs refer to the manual, these sections might be useful to you:
http://codemirror.net/demo/fullscreen.html
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
theme: "night",
extraKeys: {
"F11": function(cm) {
cm.setOption("fullScreen", !cm.getOption("fullScreen"));
},
"Esc": function(cm) {
if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
}
}
});
And also take a look at:
http://codemirror.net/demo/resize.html
Also a comment:
Inline styling is horrible you should avoid this at all costs, not only will it confuse you, it's poor practice.
eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ for i in `find . -name "*.jar"`; do
> echo $i
> done
./slf4j-api-1.7.2.jar
./zookeeper-3.3.4.jar
./kafka_2.10-0.8.1.1-javadoc.jar
./kafka_2.10-0.8.1.1-sources.jar
The accepted answer by Francisco Spaeth works and is easy to follow. However, I think that method of building JSON sucks! This was really driven home for me as I converted some Python to Java where I could use dictionaries and nested lists, etc. to build JSON with ridiculously greater ease.
What I really don't like is having to instantiate separate objects (and generally even name them) to build up these nestings. If you have a lot of objects or data to deal with, or your use is more abstract, that is a real pain!
I tried getting around some of that by attempting to clear and reuse temp json objects and lists, but that didn't work for me because all the puts and gets, etc. in these Java objects work by reference not value. So, I'd end up with JSON objects containing a bunch of screwy data after still having some ugly (albeit differently styled) code.
So, here's what I came up with to clean this up. It could use further development, but this should help serve as a base for those of you looking for more reasonable JSON building code:
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONObject;
// create and initialize an object
public static JSONObject buildObject( final SimpleEntry... entries ) {
JSONObject object = new JSONObject();
for( SimpleEntry e : entries ) object.put( e.getKey(), e.getValue() );
return object;
}
// nest a list of objects inside another
public static void putObjects( final JSONObject parentObject, final String key,
final JSONObject... objects ) {
List objectList = new ArrayList<JSONObject>();
for( JSONObject o : objects ) objectList.add( o );
parentObject.put( key, objectList );
}
Implementation example:
JSONObject jsonRequest = new JSONObject();
putObjects( jsonRequest, "parent1Key",
buildObject(
new SimpleEntry( "child1Key1", "someValue" )
, new SimpleEntry( "child1Key2", "someValue" )
)
, buildObject(
new SimpleEntry( "child2Key1", "someValue" )
, new SimpleEntry( "child2Key2", "someValue" )
)
);
C# Thread.Abort is NOT guaranteed to abort the thread instantaneously. It will probably work when a thread calls Abort on itself but not when a thread calls on another.
Please refer to the documentation: http://msdn.microsoft.com/en-us/library/ty8d3wta.aspx
I have faced this problem writing tools that interact with hardware - you want immediate stop but it is not guaranteed. I typically use some flags or other such logic to prevent execution of parts of code running on a thread (and which I do not want to be executed on abort - tricky).
Just make sure put single space before and after "and" Keyword..
I tried to develop an elegant solution to this problem described here. And you can find the demo here. The usage looks like this:
var out = def({
'int': function(a) {
alert('Here is int '+a);
},
'float': function(a) {
alert('Here is float '+a);
},
'string': function(a) {
alert('Here is string '+a);
},
'int,string': function(a, b) {
alert('Here is an int '+a+' and a string '+b);
},
'default': function(obj) {
alert('Here is some other value '+ obj);
}
});
out('ten');
out(1);
out(2, 'robot');
out(2.5);
out(true);
The methods used to achieve this:
var def = function(functions, parent) {
return function() {
var types = [];
var args = [];
eachArg(arguments, function(i, elem) {
args.push(elem);
types.push(whatis(elem));
});
if(functions.hasOwnProperty(types.join())) {
return functions[types.join()].apply(parent, args);
} else {
if (typeof functions === 'function')
return functions.apply(parent, args);
if (functions.hasOwnProperty('default'))
return functions['default'].apply(parent, args);
}
};
};
var eachArg = function(args, fn) {
var i = 0;
while (args.hasOwnProperty(i)) {
if(fn !== undefined)
fn(i, args[i]);
i++;
}
return i-1;
};
var whatis = function(val) {
if(val === undefined)
return 'undefined';
if(val === null)
return 'null';
var type = typeof val;
if(type === 'object') {
if(val.hasOwnProperty('length') && val.hasOwnProperty('push'))
return 'array';
if(val.hasOwnProperty('getDate') && val.hasOwnProperty('toLocaleTimeString'))
return 'date';
if(val.hasOwnProperty('toExponential'))
type = 'number';
if(val.hasOwnProperty('substring') && val.hasOwnProperty('length'))
return 'string';
}
if(type === 'number') {
if(val.toString().indexOf('.') > 0)
return 'float';
else
return 'int';
}
return type;
};
document.getElementById(currentInputChoosen).value -= +-100;
Works in my case, if you run into the same problem like me and can't find a solution for that case and find this SO question.
Sorry for little bit off-topic, but as i just found out that this works, i thought it might be worth sharing.
Don't know if it is a dirty workaround, or actually legit.
I don't have Python 2.7 installed, but in Python 3.3 calling Popen
with stdout
set to sys.stdout
worked just fine. Not before I had escaped the backslashes in the path, though.
>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_
On Ubuntu 14.04, it is in /usr/lib/jvm/default-java
.
By the time the query gets to SQL you have to have already expanded the list. The easy way of doing this, if you're using IDs from some internal, trusted data source, where you can be 100% certain they're integers (e.g., if you selected them from your database earlier) is this:
$sql = 'SELECT * WHERE id IN (' . implode(',', $ids) . ')';
If your data are coming from the user, though, you'll need to ensure you're getting only integer values, perhaps most easily like so:
$sql = 'SELECT * WHERE id IN (' . implode(',', array_map('intval', $ids)) . ')';
Another option is to change the version number in the packages.config
file. This will cause NuGet to download the dlls for that version the next time you build.
Using the following code in your .htaccess file automatically redirects visitors to the HTTPS version of your site:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
I found a better answer by Kenneth Fisher. The following query returns only currently running jobs:
SELECT
ja.job_id,
j.name AS job_name,
ja.start_execution_date,
ISNULL(last_executed_step_id,0)+1 AS current_executed_step_id,
Js.step_name
FROM msdb.dbo.sysjobactivity ja
LEFT JOIN msdb.dbo.sysjobhistory jh ON ja.job_history_id = jh.instance_id
JOIN msdb.dbo.sysjobs j ON ja.job_id = j.job_id
JOIN msdb.dbo.sysjobsteps js
ON ja.job_id = js.job_id
AND ISNULL(ja.last_executed_step_id,0)+1 = js.step_id
WHERE
ja.session_id = (
SELECT TOP 1 session_id FROM msdb.dbo.syssessions ORDER BY agent_start_date DESC
)
AND start_execution_date is not null
AND stop_execution_date is null;
You can get more information about a job by adding more columns from msdb.dbo.sysjobactivity
table in select clause.
In case the file keeps showing up even after doing everything mentioned here, make sure that this checkbox in Xcode settings is unchecked:
I tried this on the command.it is working for me.
if "$(OutDir)"=="bin\Debug\" goto Visual
:TFSBuild
goto exit
:Visual
xcopy /y "$(TargetPath)$(TargetName).dll" "$(ProjectDir)..\Demo"
xcopy /y "$(TargetDir)$(TargetName).pdb" "$(ProjectDir)..\Demo"
goto exit
:exit
Set the seed using srand(). Also, you're not specifying the max value in rand(), so it's using RAND_MAX. I'm not sure if it's actually 10000... why not just specify it. Although, we don't know what your "expected results" are. It's a random number generator. What are you expecting, and what are you seeing?
As noted in another comment, SA() isn't returning anything explicitly.
http://pubs.opengroup.org/onlinepubs/009695399/functions/rand.html http://www.thinkage.ca/english/gcos/expl/c/lib/rand.html
Edit:
From Generating random number between [-1, 1] in C?
((float)rand())/RAND_MAX
returns a floating-point number in [0,1]
Select (Select count(y.au_lname) from dbo.authors y
where y.au_lname + y.au_fname <= x.au_lname + y.au_fname) as Counterid,
x.au_lname,x.au_fname from authors x group by au_lname,au_fname
order by Counterid --Alternatively that can be done which is equivalent as above..
You can access the inactive tags array with (assuming $myArray contains the array)
$myArray['inactiveTags'];
Your question doesn't seem to go beyond accessing the contents of the inactiveTags key so I can only speculate with what your final goal is.
The first key:value pair in the inactiveTags array is
array ('195' => array(
'id' => 195,
'tag' => 'auto')
)
To access the tag value, you would use
$myArray['inactiveTags'][195]['tag']; // auto
If you want to loop through each inactiveTags element, I would suggest:
foreach($myArray['inactiveTags'] as $value) {
print $value['id'];
print $value['tag'];
}
This will print all the id and tag values for each inactiveTag
Edit:: For others to see, here is a var_dump of the array provided in the question since it has not readible
array 'languages' => array 76 => array 'id' => string '76' (length=2) 'tag' => string 'Deutsch' (length=7) 'targets' => array 81 => array 'id' => string '81' (length=2) 'tag' => string 'Deutschland' (length=11) 'tags' => array 7866 => array 'id' => string '7866' (length=4) 'tag' => string 'automobile' (length=10) 17800 => array 'id' => string '17800' (length=5) 'tag' => string 'seat leon' (length=9) 17801 => array 'id' => string '17801' (length=5) 'tag' => string 'seat leon cupra' (length=15) 'inactiveTags' => array 195 => array 'id' => string '195' (length=3) 'tag' => string 'auto' (length=4) 17804 => array 'id' => string '17804' (length=5) 'tag' => string 'coupès' (length=6) 17805 => array 'id' => string '17805' (length=5) 'tag' => string 'fahrdynamik' (length=11) 901 => array 'id' => string '901' (length=3) 'tag' => string 'fahrzeuge' (length=9) 17802 => array 'id' => string '17802' (length=5) 'tag' => string 'günstige neuwagen' (length=17) 1991 => array 'id' => string '1991' (length=4) 'tag' => string 'motorsport' (length=10) 2154 => array 'id' => string '2154' (length=4) 'tag' => string 'neuwagen' (length=8) 10660 => array 'id' => string '10660' (length=5) 'tag' => string 'seat' (length=4) 17803 => array 'id' => string '17803' (length=5) 'tag' => string 'sportliche ausstrahlung' (length=23) 74 => array 'id' => string '74' (length=2) 'tag' => string 'web 2.0' (length=7) 'categories' => array 16082 => array 'id' => string '16082' (length=5) 'tag' => string 'Auto & Motorrad' (length=15) 51 => array 'id' => string '51' (length=2) 'tag' => string 'Blogosphäre' (length=11) 66 => array 'id' => string '66' (length=2) 'tag' => string 'Neues & Trends' (length=14) 68 => array 'id' => string '68' (length=2) 'tag' => string 'Privat' (length=6)
Have you tried ALTER SYSTEM KILL SESSION? Get the SID and SERIAL# from V$SESSION for each session in the given schema, then do
ALTER SCHEMA KILL SESSION sid,serial#;
const fs = require('fs');
fs.stat('input.txt', function (err, stats) {
if(err){
console.log(err);
} else {
console.log(stats);
console.log('Completed Reading File');
}
});
'fs' is a node module which helps you to read file. Callback function will make sure that your file named 'input.txt' is completely read before it gets executed. fs.stat() function is to get file information like file size, date created and date modified.
You can use JsonBuilder for that.
Example Code:
import groovy.json.JsonBuilder
class Person {
String name
String address
}
def o = new Person( name: 'John Doe', address: 'Texas' )
println new JsonBuilder( o ).toPrettyString()
I wanted to show how powerful it can be aside from just checking "-lt".
Example: I used it to calculate time differences take from Windows event view Application log:
Get the difference between the two date times:
PS> $Obj = ((get-date "10/22/2020 12:51:1") - (get-date "10/22/2020 12:20:1 "))
Object created:
PS> $Obj
Days : 0
Hours : 0
Minutes : 31
Seconds : 0
Milliseconds : 0
Ticks : 18600000000
TotalDays : 0.0215277777777778
TotalHours : 0.516666666666667
TotalMinutes : 31
TotalSeconds : 1860
TotalMilliseconds : 1860000
Access an item directly:
PS> $Obj.Minutes
31
argv
and argc
are how command line arguments are passed to main()
in C and C++.
argc
will be the number of strings pointed to by argv
. This will (in practice) be 1 plus the number of arguments, as virtually all implementations will prepend the name of the program to the array.
The variables are named argc
(argument count) and argv
(argument vector) by convention, but they can be given any valid identifier: int main(int num_args, char** arg_strings)
is equally valid.
They can also be omitted entirely, yielding int main()
, if you do not intend to process command line arguments.
Try the following program:
#include <iostream>
int main(int argc, char** argv) {
std::cout << "Have " << argc << " arguments:" << std::endl;
for (int i = 0; i < argc; ++i) {
std::cout << argv[i] << std::endl;
}
}
Running it with ./test a1 b2 c3
will output
Have 4 arguments:
./test
a1
b2
c3
you should add the path to your migration file to refresh just this table and run
php artisan migrate:refresh --path=/database/migrations/fileName.php
If you want to pull a particular file from another branch just do
git checkout branch1 -- filenamefoo.txt
This will pull a version of the file from one branch into the current tree
I ran into this problem as well, and figured out that the problem is in the browser. When you refresh the browser is re-populating the form with the same values as before, ignoring the checked field. If you view source, you'll see the checked value is correct. Or put your cursor in your browser's URL field and hit enter. That will re-load the form from scratch.
As for the page, I'm working on a higher order component that uses basically the above methods to do exactly this. It actually takes just a bit of time when you get down to the subtleties like initial layout and content changes. I won't claim to have done it 'correctly', but in some sense I'd consider the correct answer to use component that does this carefully and consistently.
See: react-native-paged-scroll-view. Would love feedback, even if it's that I've done it all wrong!
The line below would hide the index column of DataFrame when you print
df.style.hide_index()
Update: tested w Python 3.7
You can use GCHandleType.Weak instead of Pinned. On the other hand, there is another way to get a pointer to an object:
object o = new object();
TypedReference tr = __makeref(o);
IntPtr ptr = **(IntPtr**)(&tr);
Requires unsafe block and is very, very dangerous and should not be used at all. ?
Back in the day when by-ref locals weren't possible in C#, there was one undocumented mechanism that could accomplish a similar thing – __makeref
.
object o = new object();
ref object r = ref o;
//roughly equivalent to
TypedReference tr = __makeref(o);
There is one important difference in that TypedReference is "generic"; it can be used to store a reference to a variable of any type. Accessing such a reference requires to specify its type, e.g. __refvalue(tr, object)
, and if it doesn't match, an exception is thrown.
To implement the type checking, TypedReference must have two fields, one with the actual address to the variable, and one with a pointer to its type representation. It just so happens that the address is the first field.
Therefore, __makeref
is used first to obtain a reference to the variable o
. The cast (IntPtr**)(&tr)
treats the structure as an array (represented via a pointer) of IntPtr*
(pointers to a generic pointer type), accessed via a pointer to it. The pointer is first dereferenced to obtain the first field, then the pointer there is dereferenced again to obtain the value actually stored in the variable o
– the pointer to the object itself.
However, since 2012, I have come up with a better and safer solution:
public static class ReferenceHelpers
{
public static readonly Action<object, Action<IntPtr>> GetPinnedPtr;
static ReferenceHelpers()
{
var dyn = new DynamicMethod("GetPinnedPtr", typeof(void), new[] { typeof(object), typeof(Action<IntPtr>) }, typeof(ReferenceHelpers).Module);
var il = dyn.GetILGenerator();
il.DeclareLocal(typeof(object), true);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Conv_I);
il.Emit(OpCodes.Call, typeof(Action<IntPtr>).GetMethod("Invoke"));
il.Emit(OpCodes.Ret);
GetPinnedPtr = (Action<object, Action<IntPtr>>)dyn.CreateDelegate(typeof(Action<object, Action<IntPtr>>));
}
}
This creates a dynamic method that first pins the object (so its storage doesn't move in the managed heap), then executes a delegate that receives its address. During the execution of the delegate, the object is still pinned and thus safe to be manipulated via the pointer:
object o = new object();
ReferenceHelpers.GetPinnedPtr(o, ptr => Console.WriteLine(Marshal.ReadIntPtr(ptr) == typeof(object).TypeHandle.Value)); //the first pointer in the managed object header in .NET points to its run-time type info
This is the easiest way to pin an object, since GCHandle requires the type to be blittable in order to pin it. It has the advantage of not using implementation details, undocumented keywords and memory hacking.
The key is to rewrite this query so that it can be used as a subquery.
SELECT firstname,
lastname,
list.address
FROM list
INNER JOIN (SELECT address
FROM list
GROUP BY address
HAVING COUNT(id) > 1) dup
ON list.address = dup.address;
Kirk's answer is right on. As a rule, you're not going to have any luck with type inference when your method signature has fewer types of parameters than it has generic type parameters.
In your particular case, it seems you could possibly move the T
type parameter to the class level and then get type inference on your Get
method:
class ServiceGate<T>
{
public IAccess<S, T> Get<S>(S sig) where S : ISignatur<T>
{
throw new NotImplementedException();
}
}
Then the code you posted with the CS0411 error could be rewritten as:
static void Main()
{
// Notice: a bit more cumbersome to write here...
ServiceGate<SomeType> service = new ServiceGate<SomeType>();
// ...but at least you get type inference here.
IAccess<Signatur, SomeType> access = service.Get(new Signatur());
}
try this:
import sys
sys.argv = ['arg1', 'arg2']
execfile('abc.py')
Note that when abc.py
finishes, control will be returned to the calling program. Note too that abc.py
can call quit()
if indeed finished.
In the case you need to manually 'exit' a transaction through code (be it through an exception or simply checking an error state) you shouldn't use DB::transaction()
but instead wrap your code in DB::beginTransaction
and DB::commit
/DB::rollback()
:
DB::beginTransaction();
try {
DB::insert(...);
DB::insert(...);
DB::insert(...);
DB::commit();
// all good
} catch (\Exception $e) {
DB::rollback();
// something went wrong
}
See the transaction docs.
If it is possible in your environment, you could also set the user's default schema to your desired schema:
ALTER USER user_name SET search_path to 'schema'
The !important rule is a way to make your CSS cascade but also have the rules you feel are most crucial always be applied. A rule that has the !important property will always be applied no matter where that rule appears in the CSS document.
So, if you have the following:
.class {
color: red !important;
}
.outerClass .class {
color: blue;
}
the rule with the important will be the one applied (not counting specificity)
I believe !important
appeared in CSS1 so every browser supports it (IE4 to IE6 with a partial implementation, IE7+ full)
Also, it's something that you don't want to use pretty often, because if you're working with other people you can override other properties.
Previous answers have covered the use of git rebase -i
to edit the commit that you want to split, and committing it in parts.
This works well when splitting the files into different commits, but if you want to break apart changes to the individual files, there's more you need to know.
Having got to the commit you want to split, using rebase -i
and marking it for edit
, you have two options.
After using git reset HEAD~
, go through the patches individually using git add -p
to select the ones you want in each commit
Edit the working copy to remove the changes you do not want; commit that interim state; and then pull back the full commit for the next round.
Option 2 is useful if you're splitting a large commit, as it lets you check that the interim versions build and run properly as part of the merge. This proceeds as follows.
After using rebase -i
and edit
ing the commit, use
git reset --soft HEAD~
to undo the commit, but leave the committed files in the index. You can also do a mixed reset by omitting --soft, depending on how close to the final result your initial commit is going to be. The only difference is whether you start with all the changes staged or with them all unstaged.
Now go in and edit the code. You can remove changes, delete added files, and do whatever you want to construct the first commit of the series you're looking for. You can also build it, run it, and confirm that you have a consistent set of source.
Once you're happy, stage/unstage the files as needed (I like to use git gui
for this), and commit the changes through the UI or the command line
git commit
That's the first commit done. Now you want to restore your working copy to the state it had after the commit you are splitting, so that you can take more of the changes for your next commit. To find the sha1 of the commit you're editing, use git status
. In the first few lines of the status you'll see the rebase command that is currently executing, in which you can find the sha1 of your original commit:
$ git status
interactive rebase in progress; onto be83b41
Last commands done (3 commands done):
pick 4847406 US135756: add debugging to the file download code
e 65dfb6a US135756: write data and download from remote
(see more in file .git/rebase-merge/done)
...
In this case, the commit I'm editing has sha1 65dfb6a
. Knowing that, I can check out the content of that commit over my working directory using the form of git checkout
which takes both a commit and a file location. Here I use .
as the file location to replace the whole working copy:
git checkout 65dfb6a .
Don't miss the dot on the end!
This will check out, and stage, the files as they were after the commit you're editing, but relative to the previous commit you made, so any changes you already committed won't be part of the commit.
You can either go ahead now and commit it as-is to finish the split, or go around again, deleting some parts of the commit before making another interim commit.
If you want to reuse the original commit message for one or more commits, you can use it straight from the rebase's working files:
git commit --file .git/rebase-merge/message
Finally, once you've committed all the changes,
git rebase --continue
will carry on and complete the rebase operation.
lol 54 answers and not one of them is my solution. Talk about a common error.
In my case it was because I had a picker object on my VC and had not set an outlet and action for it.
I often leave buttons etc unconnected when I am just looking to see how the layout looks. But it seems you cannot do this for a picker.
I know this is a bit of an old question, but I've ended up making my own little class for it.
Might be useful to someone so I'll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:
class consolePrinter():
'''
Class to write to the console
Objective is to make it easy to write to console, with user able to
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------
#Class variables
stringLen = 0
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteFlag=False):
import sys
#Get length of stringIn and update stringLen if needed
if len(stringIn) > consolePrinter.stringLen:
consolePrinter.stringLen = len(stringIn)+1
ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"
if overwriteFlag:
sys.stdout.write("\r" + ctrlString.format(stringIn))
else:
sys.stdout.write("\n" + stringIn)
sys.stdout.flush()
return
Which then is called via:
consolePrinter.writeline("text here", True)
If you want to overwrite the previous line, or
consolePrinter.writeline("text here",False)
if you don't.
Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.
I had the same problem. It might differ depending on how You put the data to the db, but try what worked for me:
$str = json_encode($data);
$str = addslashes($str);
Do this before saving data to db.
I modified the css, as i am using bootstrap 3.3.6
.form-group.required label:after{
color: #d00;
font-family: 'FontAwesome';
font-weight: normal;
font-size: 10px;
content: "\f069";
top:4px;
position: absolute;
margin-left: 8px;
}
the HTML
<div class="form-group required">
<label for="return_notes"><?= _lang('notes') ?></label>
<textarea class="form-control" name="return_notes" id="return_notes" required="required"></textarea>
</div>
This worked for me. I made a function. Put this in your shell script:
sshcmd(){
ssh $1@$2 $3
}
sshcmd USER HOST COMMAND
If you have multiple machines that you want to do the same command on you would repeat that line with a semi colon. For example, if you have two machines you would do this:
sshcmd USER HOST COMMAND ; sshcmd USER HOST COMMAND
Replace USER with the user of the computer. Replace HOST with the name of the computer. Replace COMMAND with the command you want to do on the computer.
Hope this helps!
File -> Preferences -> Settings or just press Ctrl + , and search for spaces, then just deactivate this option:
I had to reopen the file so the changes would take effect.
Change to:
SELECT
CASE
WHEN FRUIT = 'A' THEN 'APPLE'
WHEN FRUIT = 'B' THEN 'BANANA'
END
FROM FRUIT_TABLE;
There's a simpler way than a whole bunch of if statements. Use the or (||) operator.
function getBrowserDimensions() {
return {
width: (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth),
height: (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight)
};
}
var browser_dims = getBrowserDimensions();
alert("Width = " + browser_dims.width + "\nHeight = " + browser_dims.height);
I figured it out already:
as.data.frame.matrix(mytable)
does what I need -- apparently, the table needs to somehow be converted to a matrix in order to be appropriately translated into a data frame. I found more details on this as.data.frame.matrix() function for contingency tables at the Computational Ecology blog.
Microsoft offers a #pragma
to reference the correct library at link time;
#pragma comment(lib, "libname.lib")
In addition to the library path including the directory of the library, this should be the full name of the library.
You can't wrap a <td>
element with an <a>
tag, but you can accomplish similar functionality by using the onclick
event to call a function. An example is found here, something like this function:
<script type="text/javascript">
function DoNav(url)
{
document.location.href = url;
}
</script>
And add it to your table like this:
<tr onclick="DoNav('http://stackoverflow.com/')"><td></td></tr>
Does someone know how I can use a String constant or String[] constant to supply value to an annotation?
Unfortunately, you can't do this with arrays. With non-array variables, the value must be final static.
Isn't scope more important than type these days, e.g.
* l for local
* a for argument
* m for member
* g for global
* etc
With modern techniques of refactoring old code, search and replace of a symbol because you changed its type is tedious, the compiler will catch type changes, but often will not catch incorrect use of scope, sensible naming conventions help here.
Just use the following code. It is really useful to send email via Java, and it works:
import java.util.*;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.*;
import javax.mail.Provider;
import javax.mail.internet.*;
public class Main {
public static void main(String[] args) {
final String username="[email protected]";
final String password="password";
Properties prop=new Properties();
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
String body="Dear Renish Khunt Welcome";
String htmlBody = "<strong>This is an HTML Message</strong>";
String textBody = "This is a Text Message.";
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("[email protected]"));
message.setSubject("Testing Subject");
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
message.setText(htmlBody);
message.setContent(textBody, "text/html");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Above most of the answers having a trivial problem is that the int variable possibly might overflow.
Refer to http://articles.leetcode.com/palindrome-number/
boolean isPalindrome(int x) {
if (x < 0)
return false;
int div = 1;
while (x / div >= 10) {
div *= 10;
}
while (x != 0) {
int l = x / div;
int r = x % 10;
if (l != r)
return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}
i'm running electron app and i can get the parent folder by path.resolve()
parent 1 level:path.resolve(__dirname, '..') + '/'
parent 2 levels:path.resolve(__dirname, '..', '..') + '/'
Here's a minor update to the solution provided by Dave Sexton. Many times you need multiple filters. The Filter parameter can only take a single string whereas the -Include parameter can take a string array. if you have a large file tree it also makes sense to only get the date to compare with once, not for each file. Here's my updated version:
$compareDate = (Get-Date).AddDays(-3)
@(Get-ChildItem -Path c:\pstbak\*.* -Filter '*.pst','*.mdb' -Recurse | Where-Object { $_.LastWriteTime -gt $compareDate}).Count
To make part of your text underlined and colored
in your strings.xml
<string name="text_with_colored_underline">put the text here and <u><font color="#your_hexa_color">the underlined colored part here<font><u></string>
then in the activity
yourTextView.setText(Html.fromHtml(getString(R.string.text_with_colored_underline)));
and for clickable links:
<string name="text_with_link"><![CDATA[<p>text before link<a href=\"http://www.google.com\">title of link</a>.<p>]]></string>
and in your activity:
yourTextView.setText(Html.fromHtml(getString(R.string.text_with_link)));
yourTextView.setMovementMethod(LinkMovementMethod.getInstance());
More easy, light (32k), and many more performance:
Android Asynchronous Http Client library: http://loopj.com/android-async-http/
Implementation:
How to send a “multipart/form-data” POST in Android with Volley
I don't think there's type-safe method that can do what you want.
The connection string is a string of the form:
postgres://[user[:password]@][host][:port][/dbname]
(where the parts in [...]
can optionally be included or excluded)
Some examples of valid connection strings include:
postgres://localhost
postgres://localhost:5432
postgres://localhost/mydb
postgres://user@localhost
postgres://user:secret_password@localhost
If you've just started a database on your local machine, the connection string postgres://localhost
will typically work, as that uses the default port number, username, and no password. If the database was started with a specific account, you might find you need to use postgres://pg@localhost
or postgres://postgres@localhost
If none of these work, and you have installed docker, another option is to run npx @databases/pg-test start
. This will start a postgres server in a docker container and then print out the connection string for you. The pg-test
databases are only intended for testing though, so you will loose all your data if your computer restarts.
You can connect to the database and issue queries using @databases/pg
:
const createPool = require('@databases/pg');
const {sql} = require('@databases/pg');
// If you're using TypeScript or Babel, you can swap
// the two `require` calls for this import statement:
// import createPool, {sql} from '@databases/pg';
// create a "pool" of connections, you can think of this as a single
// connection, the pool is just used behind the scenes to improve
// performance
const db = createPool('postgres://localhost');
// wrap code in an `async` function so we can use `await`
async function run() {
// we can run sql by tagging it as "sql" and then passing it to db.query
await db.query(sql`
CREATE TABLE IF NOT EXISTS beatles (
name TEXT NOT NULL,
height INT NOT NULL,
birthday DATE NOT NULL
);
`);
const beatle = {
name: 'George',
height: 70,
birthday: new Date(1946, 02, 14),
};
// If we need to pass values, we can use ${...} and they will
// be safely & securely escaped for us
await db.query(sql`
INSERT INTO beatles (name, height, birthday)
VALUES (${beatle.name}, ${beatle.height}, ${beatle.birthday});
`);
console.log(
await db.query(sql`SELECT * FROM beatles;`)
);
}
run().catch(ex => {
// It's a good idea to always report errors using
// `console.error` and set the process.exitCode if
// you're calling an async function at the top level
console.error(ex);
process.exitCode = 1;
}).then(() => {
// For this little demonstration, we'll dispose of the
// connection pool when we're done, so that the process
// exists. If you're building a web server/backend API
// you probably never need to call this.
return db.dispose();
});
You can find a more complete guide to querying Postgres using node.js at https://www.atdatabases.org/docs/pg
select SUBSTRING_INDEX(supplier_reference,'=',-1) from ps_product;
Please use http://www.w3resource.com/mysql/string-functions/mysql-substring_index-function.php for further reference.
a piece of code who work with python to read rs232 just in case somedoby else need it
ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()
Using CSS:
.button {_x000D_
display: block;_x000D_
width: 115px;_x000D_
height: 25px;_x000D_
background: #4E9CAF;_x000D_
padding: 10px;_x000D_
text-align: center;_x000D_
border-radius: 5px;_x000D_
color: white;_x000D_
font-weight: bold;_x000D_
line-height: 25px;_x000D_
}
_x000D_
<a class="button">Add Problem</a>
_x000D_
I have similar problem and similar resolution:
1) Size
in the xml you have TabLayout,
<android.support.design.widget.TabLayout
...
app:tabTextAppearance="@style/CustomTextStyle"
...
/>
then in style,
<style name="CustomTextStyle" parent="@android:style/TextAppearance.Widget.TabWidget">
<item name="android:textSize">16sp</item>
<item name="android:textAllCaps">true</item>
</style>
If you do not want the characters in uppercase put false in "android:textAllCaps"
2) Text color of selected or unselected Tabs,
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
tabLayout.setTabTextColors(getResources().getColorStateList(R.color.tab_selector,null));
} else {
tabLayout.setTabTextColors(getResources().getColorStateList(R.color.tab_selector));
}
then in res/color/tab_selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/white" android:state_selected="true" />
<item android:color="@color/white" />
This will remove first match wherever it is found i.e., start or middle or end.
$str = substr($str, 0, strpos($str, $prefix)).substr($str, strpos($str, $prefix)+strlen($prefix));
When you have multiple files, an idea is to show only the first file and the number of the hidden file names.
$('.custom-file input').change(function() {
var $el = $(this),
files = $el[0].files,
label = files[0].name;
if (files.length > 1) {
label = label + " and " + String(files.length - 1) + " more files"
}
$el.next('.custom-file-label').html(label);
});
Several possibilities:
exec()
is working, and then only on executables in safe_mode_exec_dir
exec
and shell_exec
are disabled in php.iniexec(dirname(__FILE__) . '/myscript.sh');
No need to use a macro. Supposing your first string is in A1.
=RIGHT(A1, 4)
Drag this down and you will get your four last characters.
Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()
=RIGHT(TRIMSPACES(A1), 4)
Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:
=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))
Already very good solution came. I'm just puting the total code so that a newbie get total help
<?php
extract($_GET); //you can send some parameter by query variable. I have sent table name in *table* variable
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$table.csv");
header("Pragma: no-cache");
header("Expires: 0");
require_once("includes/functions.php"); //necessary mysql connection functions here
//first of all I'll get the column name to put title of csv file.
$query = "SHOW columns FROM $table";
$headers = mysql_query($query) or die(mysql_error());
$csv_head = array();
while ($row = mysql_fetch_array($headers, MYSQL_ASSOC))
{
$csv_head[] = $row['Field'];
}
echo implode(",", $csv_head)."\n";
//now I'll bring the data.
$query = "SELECT * FROM $table";
$select_c = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
foreach ($row as $key => $value) {
//there may be separator (here I have used comma) inside data. So need to put double quote around such data.
if(strpos($value, ',') !== false || strpos($value, '"') !== false || strpos($value, "\n") !== false) {
$row[$key] = '"' . str_replace('"', '""', $value) . '"';
}
}
echo implode(",", $row)."\n";
}
?>
I have saved this code in csv-download.php
Now see how I have used this data to download csv file
<a href="csv-download.php?table=tbl_vfm"><img title="Download as Excel" src="images/Excel-logo.gif" alt="Download as Excel" /><a/>
So when I have clicked the link it download the file without taking me to csv-download.php page on browser.
Use strtotime()
and date()
:
$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));
(See the strtotime and date documentation on the PHP site.)
Note that this was a quick solution to the original question. For more extensive conversions, you should really be using the DateTime
class to parse and format :-)
As others have mentioned, the NET::ERR_CERT_COMMON_NAME_INVALID
error is occurring because the generated certificate does not include the SAN (subjectAltName
) field.
RFC2818 has deprecated falling back to the commonName
field since May of 2000. The use of the subjectAltName
field has been enforced in Chrome since version 58 (see Chrome 58 deprecations).
OpenSSL accepts x509v3 configuration files to add extended configurations to certificates (see the subjectAltName field for configuration options).
I created a self-signed-tls bash script with straightforward options to make it easy to generate certificate authorities and sign x509 certificates with OpenSSL (valid in Chrome using the subjectAltName
field).
The script will guide you through a series of questions to include the necessary information (including the subjectAltName
field). You can reference the README.md for more details and options for automation.
Be sure to restart chrome after installing new certificates.
chrome://restart
In fact, xargs
can run commands in parallel for you. There is a special -P max_procs
command-line option for that. See man xargs
.
Using ? is much cleaner.
var ? function_if_exists() : function_if_doesnt_exist();
I try to avoid TABLEs as much as possible, but when we are designing complex forms that mix multiple control types and different caption positions with pretty strict controls on grouping, using DIVs is unreliable or often near impossible.
Now, I will not argue that these forms could not be redesigned to better accommodate a DIV based layout, but for some of them our customer is adamant about not changing the existing layouts from the previous version (written in classic ASP) because it parallels a paper form that their users are familiar with.
Because the presentation of the forms is dynamic (where the display of some sections is based on the state of the case or the permissions of the user), we use sets of stacked DIVs, each containing a TABLE of logically grouped form elements. Each column of the TABLE is classed so that they can be controlled by CSS. That way we can turn off different sections of the form without the problem of not being table to wrap rows in DIVs.
This is (essentially) incorrect in most cases:
var array = [];
array["Main"] = "Main page";
That creates a non-element property on the array with the name Main
. Although arrays are objects, normally you don't want to create non-element properties on them.
If you want to index into array
by those names, typically you'd use a Map
or a plain object, not an array.
With a Map
(ES2015+), which I'll call map
because I'm creative:
let map = new Map();
map.set("Main", "Main page");
you then iterate it using the iterators from its values
, keys
, or entries
methods, for instance:
for (const value of map.values()) {
// Here, `value` will be `"Main page"`, etc.
}
Using a plain object, which I'll creatively call obj
:
let obj = Object.create(null); // Creates an object with no prototype
obj.Main = "Main page"; // Or: `obj["Main"] = "Main page";`
you'd then iterate its contents using Object.keys
, Object.values
, or Object.entries
, for instance:
for (const value of Object.values(proches_X)) {
// Here, `value` will be `"Main page"`, etc.
}
This should resolve your problem: chmod go-w {/path/of/user}
Appears you can somewhat accomplish something similar with the Notification API. You can't control how long it stays visible (probably an OS preference of some kind--unless you specify requireInteraction true, then it stays up forever or until dismissed or until you close it), and it requires the user to click "allow notifications" (unfortunately) first, but here it is:
If you want it to close after 1s (all OS's leave it open 1s at least):
var notification = new Notification("Hi there!", {body: "some text"});
setTimeout(function() {notification.close()}, 1000);
If you wanted to show it longer than the "default" you could bind to the onclose callback and show another repeat notification I suppose, to replace it.
Ref: inspired by this answer, though that answer doesn't work in modern Chrome anymore, but the Notification API does.
use kubeadm reset
command. this will un-configure the kubernetes cluster.
Instead of
var bottom = $(window).height() - link.height();
bottom = offset.top - bottom;
Why aren't you doing
var bottom = $(window).height() - top - link.height();
Edit: Your mistake is that you're doing
bottom = offset.top - bottom;
instead of
bottom = bottom - offset.top; // or bottom -= offset.top;
Just another example where the value of a column from table 1 is inserted into a column in table 2:
UPDATE Address
SET Phone1 = sp.Phone
FROM Address ad LEFT JOIN Speaker sp
ON sp.AddressID = ad.ID
WHERE sp.Phone <> ''
I had the same issue in Flask
and after trying the first 2 solutions which are the same (Authorization: Bearer <token>
), and getting this:
{
"description": "Unsupported authorization type",
"error": "Invalid JWT header",
"status_code": 401
}
I managed to finally solve it by using:
Authorization: jwt <token>
Thought it might save some time to people who encounter the same thing.
I have made a variant solution based on paxdiablo's post
Place the following code in Waitlink.cmd
@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
:loop
set state=up
ping -n 1 !ipaddr! >nul: 2>nul:
if not !errorlevel!==0 set state=down
echo.Link is !state!
if "!state!"=="up" (
goto :endloop
)
ping -n 6 127.0.0.1 >nul: 2>nul:
goto :loop
:endloop
endlocal
For example use it from another batch file like this
call Waitlink someurl.com
net use o: \\someurl.com\myshare
The call to waitlink will only return when a ping was succesful. Thanks to paxdiablo and Gabe. Hope this helps someone else.
There is a way to create war file of your project from eclipse.
First a create an xml file with the following code,
Replace HistoryCheck with your project name.
<?xml version="1.0" encoding="UTF-8"?>
<project name="HistoryCheck" basedir="." default="default">
<target name="default" depends="buildwar,deploy"></target>
<target name="buildwar">
<war basedir="war" destfile="HistoryCheck.war" webxml="war/WEB-INF/web.xml">
<exclude name="WEB-INF/**" />
<webinf dir="war/WEB-INF/">
<include name="**/*.jar" />
</webinf>
</war>
</target>
<target name="deploy">
<copy file="HistoryCheck.war" todir="." />
</target>
</project>
Now, In project explorer right click on that xml file and Run as-> ant build
You can see the war file of your project in your project folder.
When the user exits the FE attempt to rename the backend MDB preferably with todays date in the name in yyyy-mm-dd format. Ensure you close all bound forms, including hidden forms, and reports before doing this. If you get an error message, oops, its busy so don't bother. If it is successful then compact it back.
See my Backup, do you trust the users or sysadmins? tips page for more info.
grep "pattern" <(head -n 10 filename)
At least one item in your list is either not three dimensional, or its second or third dimension does not match the other elements. If only the first dimension does not match, the arrays are still matched, but as individual objects, no attempt is made to reconcile them into a new (four dimensional) array. Some examples are below:
That is, the offending element's shape != (?, 224, 3)
,
or ndim != 3
(with the ?
being non-negative integer).
That is what is giving you the error.
You'll need to fix that, to be able to turn your list into a four (or three) dimensional array. Without context, it is impossible to say if you want to lose a dimension from the 3D items or add one to the 2D items (in the first case), or change the second or third dimension (in the second case).
Here's an example of the error:
>>> a = [np.zeros((224,224,3)), np.zeros((224,224,3)), np.zeros((224,224))]
>>> np.array(a)
ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)
or, different type of input, but the same error:
>>> a = [np.zeros((224,224,3)), np.zeros((224,224,3)), np.zeros((224,224,13))]
>>> np.array(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)
Alternatively, similar but with a different error message:
>>> a = [np.zeros((224,224,3)), np.zeros((224,224,3)), np.zeros((224,100,3))]
>>> np.array(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (224,224,3) into shape (224)
But the following will work, albeit with different results than (presumably) intended:
>>> a = [np.zeros((224,224,3)), np.zeros((224,224,3)), np.zeros((10,224,3))]
>>> np.array(a)
# long output omitted
>>> newa = np.array(a)
>>> newa.shape
3 # oops
>>> newa.dtype
dtype('O')
>>> newa[0].shape
(224, 224, 3)
>>> newa[1].shape
(224, 224, 3)
>>> newa[2].shape
(10, 224, 3)
>>>
jQuery has a built-in method for this:
$(window).resize(function () { /* do something */ });
For the sake of UI responsiveness, you might consider using a setTimeout to call your code only after some number of milliseconds, as shown in the following example, inspired by this:
function doSomething() {
alert("I'm done resizing for the moment");
};
var resizeTimer;
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(doSomething, 100);
});
I'm not sure that the method that you give is really inefficient, but an alternate way, as long as it doesn't have to be flexible in the length or padding character, would be (assuming that you want to pad it with "0" to 10 characters:
DECLARE
@pad_characters VARCHAR(10)
SET @pad_characters = '0000000000'
SELECT RIGHT(@pad_characters + @str, 10)
Suppose your screen id has a pattern. Then you can use the following code to kill all the attached screen at once.
result=$(screen -ls | grep 'pattern_of_screen_id' -o)
for i in $result;
do
`screen -X -S $i quit`;
done
There are two options. Ayman's approach is the most simple, but I would add one extra note to it. You should really cache jQuery selections, there is no reason to call $("#input-field-id")
twice:
var input = $( "#input-field-id" );
input.val( input.val() + "more text" );
The other option, .val()
can also take a function as an argument. This has the advantange of easily working on multiple inputs:
$( "input" ).val( function( index, val ) {
return val + "more text";
});
There is even a better way to create a Map along with initialization:
Map<String, String> rightHereMap = new HashMap<String, String>()
{
{
put("key1", "value1");
put("key2", "value2");
}
};
For more options take a look here How can I initialise a static Map?
MYSQL: To get column values as one comma separated value use GROUP_CONCAT( )
function as
GROUP_CONCAT( `column_name` )
for example
SELECT GROUP_CONCAT( `column_name` )
FROM `table_name`
WHERE 1
LIMIT 0 , 30
This is much easier than you're making it. The text node will not have the literal string " "
in it, it'll have have the corresponding character with code 160.
function replaceNbsps(str) {
var re = new RegExp(String.fromCharCode(160), "g");
return str.replace(re, " ");
}
textNode.nodeValue = replaceNbsps(textNode.nodeValue);
UPDATE
Even easier:
textNode.nodeValue = textNode.nodeValue.replace(/\u00a0/g, " ");
Integer.valueOf(android.os.Build.VERSION.SDK);
Values are:
Platform Version API Level
Android 9.0 28
Android 8.1 27
Android 8.0 26
Android 7.1 25
Android 7.0 24
Android 6.0 23
Android 5.1 22
Android 5.0 21
Android 4.4W 20
Android 4.4 19
Android 4.3 18
Android 4.2 17
Android 4.1 16
Android 4.0.3 15
Android 4.0 14
Android 3.2 13
Android 3.1 12
Android 3.0 11
Android 2.3.3 10
Android 2.3 9
Android 2.2 8
Android 2.1 7
Android 2.0.1 6
Android 2.0 5
Android 1.6 4
Android 1.5 3
Android 1.1 2
Android 1.0 1
CAUTION: don't use android.os.Build.VERSION.SDK_INT
if <uses-sdk android:minSdkVersion="3" />
.
You will get exception on all devices with Android 1.5 and lower because Build.VERSION.SDK_INT
is since SDK 4 (Donut 1.6).
After a certain amount of time, your access token expires.
To prevent this, you can request the 'offline_access' permission during the authentication, as noted here: Do Facebook Oauth 2.0 Access Tokens Expire?
In C/C++, pointers and arrays are (almost) equivalent.
int *a; a[0];
will return *a
, and a[1];
will return *(a + 1)
But array can't change the pointer it points to while pointer can.
new int[n]
will allocate some spaces for the "array"
For those who found this on google - there is a solution for this right now:
Socket.disconnect()
kicks the client (server-side). No chance for the client to stay connected :)
If you are serious about maintaining interoperability with other JVM languages (e.g. Java) then the best option is to write Java enums. Those work transparently from both Scala and Java code, which is more than can be said for scala.Enumeration
or case objects. Let's not have a new enumerations library for every new hobby project on GitHub, if it can be avoided!
As you can see in the below source code, BeanUtils.copyProperties internally uses reflection and there's additional internal cache lookup steps as well which is going to add cost wrt performance
private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
@Nullable String... ignoreProperties) throws BeansException {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
Class<?> actualEditable = target.getClass();
if (editable != null) {
if (!editable.isInstance(target)) {
throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
"] not assignable to Editable class [" + editable.getName() + "]");
}
actualEditable = editable;
}
**PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);**
List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
for (PropertyDescriptor targetPd : targetPds) {
Method writeMethod = targetPd.getWriteMethod();
if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
if (sourcePd != null) {
Method readMethod = sourcePd.getReadMethod();
if (readMethod != null &&
ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
try {
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, value);
}
catch (Throwable ex) {
throw new FatalBeanException(
"Could not copy property '" + targetPd.getName() + "' from source to target", ex);
}
}
}
}
}
}
So it's better to use plain setters given the cost reflection
We have been solving the same problem just today, and all you need to do is to increase the runtime version of .NET
4.5.2 didn't work for us with the above problem, while 4.6.1 was OK
If you need to keep the .NET version, then set
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
If you want to quit without saving in Vim and have Vim return a non-zero exit code, you can use :cq
.
I use this all the time because I can't be bothered to pinky shift for !
. I often pipe things to Vim which don't need to be saved in a file. We also have an odd SVN wrapper at work which must be exited with a non-zero value in order to abort a checkin.
A DATE
column does not have a format. You cannot specify a format for it.
You can use DateStyle
to control how PostgreSQL emits dates, but it's global and a bit limited.
Instead, you should use to_char
to format the date when you query it, or format it in the client application. Like:
SELECT to_char("date", 'DD/MM/YYYY') FROM mytable;
e.g.
regress=> SELECT to_char(DATE '2014-04-01', 'DD/MM/YYYY');
to_char
------------
01/04/2014
(1 row)
The answer of Uttam didnt work for me. I just got null when I do:
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);
In my case, bitmapdata only has the buffer of the pixels, so it is imposible for the function decodeByteArray to guess which the width, the height and the color bits use. So I tried this and it worked:
//Create bitmap with width, height, and 4 bytes color (RGBA)
Bitmap bmp = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
ByteBuffer buffer = ByteBuffer.wrap(bitmapdata);
bmp.copyPixelsFromBuffer(buffer);
Check https://developer.android.com/reference/android/graphics/Bitmap.Config.html for different color options
Use this Code in code behind
Div_Card.Style["background-image"] = Page.ResolveUrl(Session["Img_Path"].ToString());
I know you didn't want to use floats and the question was just theory but in case anyone finds this useful, here's a solution using floats.
Add a class of left to your li
elements that you want to float:
<li class="left"><img src="http://phrogz.net/tmp/alphaball.png">Smells Good</li>
and amend your CSS as follows:
li { text-align:center; float: left; clear: left; padding:0.1em 1em }
.left {float: left; clear: none;}
http://jsfiddle.net/chut319/xJ3pe/
You don't need to specify widths or inline-blocks and works as far back as IE6.
wget is capable of doing what you are asking. Just try the following:
wget -p -k http://www.example.com/
The -p
will get you all the required elements to view the site correctly (css, images, etc).
The -k
will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.
From the Wget docs:
‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.
Each link will be changed in one of the two ways:
The links to files that have been downloaded by Wget will be changed to refer
to the file they point to as a relative link.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
downloaded, then the link in doc.html will be modified to point to
‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
combinations of directories.
The links to files that have not been downloaded by Wget will be changed to
include host name and absolute path of the location they point to.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
../bar/img.gif), then the link in doc.html will be modified to point to
http://hostname/bar/img.gif.
Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.
Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads.
/**
* @Route("/category/{id}", name="_category")
* @Route("/category/{id}/{active}", name="_be_activatecategory")
* @Template()
*/
public function categoryAction($id, $active = null)
{ .. }
May works.
To answer this point:
I want Sleep to be an async method so it can await other methods
you can maybe rewrite the Sleep
function like this:
private static async Task<int> Sleep(int ms)
{
Console.WriteLine("Sleeping for " + ms);
var task = Task.Run(() => Thread.Sleep(ms));
await task;
Console.WriteLine("Sleeping for " + ms + "END");
return ms;
}
static void Main(string[] args)
{
Console.WriteLine("Starting");
var task1 = Sleep(2000);
var task2 = Sleep(1000);
int totalSlept = task1.Result +task2.Result;
Console.WriteLine("Slept for " + totalSlept + " ms");
Console.ReadKey();
}
running this code will output :
Starting
Sleeping for 2000
Sleeping for 1000
*(one second later)*
Sleeping for 1000END
*(one second later)*
Sleeping for 2000END
Slept for 3000 ms
This compiles fine on gcc version 4.3.3 (Ubuntu 4.3.3-5ubuntu4).
const char s[] = "cheese";
int main()
{
return 0;
}
<p><input type="checkbox" name="ch1" checked="checked" /> First Name</p>
....
<td class="ch1">...</td>
<script>
$(document).ready(function() {
$('#demo').multiselect();
});
$("input:checkbox:not(:checked)").each(function() {
var column = "table ." + $(this).attr("name");
$(column).hide();
});
$("input:checkbox").click(function(){
var column = "table ." + $(this).attr("name");
$(column).toggle();
});
</script>
EDIT: previous answer was backwards of what you wanted. Use str_replace.
replace <br>
with \n
echo str_replace('<br>', "\n", $var1);
When I now just use the command: mysql
I get: Command 'mysql' not found, but can be installed with:
sudo apt install mysql-client-core-8.0 # version 8.0.22-0ubuntu0.20.04.2, or sudo apt install mariadb-client-core-10.3 # version 1:10.3.25-0ubuntu0.20.04.1
Very helpfull.
For HSQLDB:
ALTER TABLE tableName ALTER COLUMN columnName SET NULL;
/tmp/a/b/c $ . ./test.sh
/tmp/a/b/c
/tmp/a/b/c $ . /tmp/a/b/c/test.sh
/tmp/a/b/c
/tmp/a/b/c $ ./test.sh
/tmp/a/b/c
/tmp/a/b/c $ /tmp/a/b/c/test.sh
/tmp/a/b/c
/tmp/a/b/c $ cd
~ $ . /tmp/a/b/c/test.sh
/tmp/a/b/c
~ $ . ../../tmp/a/b/c/test.sh
/tmp/a/b/c
~ $ /tmp/a/b/c/test.sh
/tmp/a/b/c
~ $ ../../tmp/a/b/c/test.sh
/tmp/a/b/c
#!/usr/bin/env bash
# snagged from: https://stackoverflow.com/a/51264222/26510
function toAbsPath {
local target
target="$1"
if [ "$target" == "." ]; then
echo "$(pwd)"
elif [ "$target" == ".." ]; then
echo "$(dirname "$(pwd)")"
else
echo "$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"
fi
}
function getScriptDir(){
local SOURCED
local RESULT
(return 0 2>/dev/null) && SOURCED=1 || SOURCED=0
if [ "$SOURCED" == "1" ]
then
RESULT=$(dirname "$1")
else
RESULT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
fi
toAbsPath "$RESULT"
}
SCRIPT_DIR=$(getScriptDir "$0")
echo "$SCRIPT_DIR"
Add a -v flag with your git command . e.g.
git pull -v
v stands for verify .
Remember that each Add
will check the capacity of the collection and resize it whenever necessary (slower). With AddRange
, the collection will be set the capacity and then added the items (faster). This extension method will be extremely slow, but will work.
Lots of options here, but one of the easiest to follow is subset
. Consider:
> set.seed(43)
> df <- data.frame(name = sample(letters, 100, TRUE), date = sample(1:500, 100, TRUE))
>
> subset(df, date > 5 & date < 15)
name date
11 k 10
67 y 12
86 e 8
You can also insert logic directly into the index for your data.frame. The comma separates the rows from columns. We just have to remember that R indexes rows first, then columns. So here we are saying rows with date > 5 & < 15 and then all columns:
df[df$date > 5 & df$date < 15 ,]
I'd also recommend checking out the help pages for subset, ?subset
and the logical operators ?"&"
Use 'event.currentTarget.performance.navigation.type' to determine the type of navigation. This is working in IE, FF and Chrome.
function CallbackFunction(event) {
if(window.event) {
if (window.event.clientX < 40 && window.event.clientY < 0) {
alert("back button is clicked");
}else{
alert("refresh button is clicked");
}
}else{
if (event.currentTarget.performance.navigation.type == 2) {
alert("back button is clicked");
}
if (event.currentTarget.performance.navigation.type == 1) {
alert("refresh button is clicked");
}
}
}
Your question is missing most of the necessary information, so I'm going to make some assumptions:
The answer would be:
=IF(COUNTBLANK(F16:G16)<>2,H15+G16-F16,"")
COUNTBLANK
tells you how many cells are unfilled or set to "".
IF
lets you conditionally do one of two things based on whether the first statement is true or false. The second comma separated argument is what to do if it's true, the third comma separated argument is what to do if it's false.
<>
means "not equal to".
The equation says that if the number of blank cells in the range F16:G16
(your credit and debit cells) is not 2, which means both aren't blank, then calculate the equation you provided in your question. Otherwise set the cell to blank(""
).
When you copy this equation to new cells in column H other than H16
, it will update the row references so the proper rows for the credit and debit amounts are looked at.
CAVEAT: This equation is useful if you are just adding entries for credits and debits to the end of a list and want the running total to update automatically. You'd fill this equation down to some arbitrary long length well past the end of actual data. You wouldn't see the running total past the end of the credit/debit entries then, it would just be blank until you filled in a new credit/debit entry. If you left a blank row in your credit debit entries though, the reference to the previous total, H15
, would report blank, which is treated like a 0 in this case.
Quick solution without downloading anything is to use online editors that has "Magic Wand Tool".
Attach your variable to the req
object, not res
.
Instead of
res.somevariable = variable1;
Have:
req.somevariable = variable1;
As others have pointed out, res.locals
is the recommended way of passing data through middleware.
I faced same issue but fix it by the changing the package file section command. The whole step that i followed was:
At first try with this command: sudo apt-get install -y mongodb
This is the unofficial mongodb package provided by Ubuntu and it is not maintained by MongoDB and conflict with MongoDB’s offically supported packages.
If the above command not working then you can fix the issue by one of the bellow procedure:
#Step 1: Import the MongoDB public key
#In Ubuntu 18.*+, you may get invalid signatures. --recv value may need to be updated to EA312927.
#See here for more details on the invalid signature issue: [https://stackoverflow.com/questions/34733340/mongodb-gpg-invalid-signatures][1]
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
#Step 2: Generate a file with the MongoDB repository url
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
#Step 3: Refresh the local database with the packages
sudo apt-get update
#Step 4: Install the last stable MongoDB version and all the necessary packages on our system
sudo apt-get install mongodb-org
#Or
# The unofficial mongodb package provided by Ubuntu is not maintained by MongoDB and conflict with MongoDB’s offically supported packages. Use the official MongoDB mongodb-org packages, which are kept up-to-date with the most recent major and minor MongoDB releases.
sudo apt-get install -y mongodb
Hope this will work for you also. You can follow this MongoDB
Update
The above instruction will install mongodb 2.6 version, if you want to install latest version for Uubuntu 12.04
then just replace above step 2
and follow bellow instruction instead of that:
#Step 2: Generate a file with the MongoDB repository url
echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb.list
If you are using Ubuntu 14.04
then use bellow step instead of above step 2
#Step 2: Generate a file with the MongoDB repository url
echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list
The easiest way to add and remove ranges in a string is to use the StringBuilder
.
var theString = "ABCDEFGHIJ";
var aStringBuilder = new StringBuilder(theString);
aStringBuilder.Remove(3, 2);
aStringBuilder.Insert(3, "ZX");
theString = aStringBuilder.ToString();
An alternative is to use String.Substring
, but I think the StringBuilder
code gets more readable.
IE9 currently lacks CSS3 gradient support. However, here is a nice workaround solution using PHP to return an SVG (vertical linear) gradient instead, which allows us to keep our design in our stylesheets.
<?php
$from_stop = isset($_GET['from']) ? $_GET['from'] : '000000';
$to_stop = isset($_GET['to']) ? $_GET['to'] : '000000';
header('Content-type: image/svg+xml; charset=utf-8');
echo '<?xml version="1.0"?>
';
?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%">
<defs>
<linearGradient id="linear-gradient" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" stop-color="#<?php echo $from_stop; ?>" stop-opacity="1"/>
<stop offset="100%" stop-color="#<?php echo $to_stop; ?>" stop-opacity="1"/>
</linearGradient>
</defs>
<rect width="100%" height="100%" fill="url(#linear-gradient)"/>
</svg>
Simply upload it to your server and call the URL like so:
gradient.php?from=f00&to=00f
This can be used in conjunction with your CSS3 gradients like this:
.my-color {
background-color: #f00;
background-image: url(gradient.php?from=f00&to=00f);
background-image: -webkit-gradient(linear, left top, left bottom, from(#f00), to(#00f));
background-image: -webkit-linear-gradient(top, #f00, #00f);
background-image: -moz-linear-gradient(top, #f00, #00f);
background-image: linear-gradient(top, #f00, #00f);
}
If you need to target below IE9, you can still use the old proprietary 'filter' method:
.ie7 .my-color, .ie8 .my-color {
filter: progid:DXImageTransform.Microsoft.Gradient(startColorStr="#ff0000", endColorStr="#0000ff");
}
Of course you can amend the PHP code to add more stops on the gradient, or make it more sophisticated (radial gradients, transparency etc.) but this is great for those simple (vertical) linear gradients.
on Mojave, this did the trick :
sudo chmod go-w /usr/local/share
With Xcode 7.2.1, if you are certain that your provisioning profile is correct (it has the correct App ID and certificate, and the corresponding certificate exists in your Keychain Access) then set the Code Signing Identity and set the Provisioning Profile to Automatic.
import java.util.Scanner;
class TestClass {
public static void main(String args[]) throws Exception {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (Character.isUpperCase(ch[i])) {
ch[i] = Character.toLowerCase(ch[i]);
} else {
ch[i] = Character.toUpperCase(ch[i]);
}
}
System.out.println(ch);
}
}
Try
var fu1 = document.getElementById("FileUpload1").value;
You can create table variables:
DECLARE @result1 TABLE (a INT, b INT, c INT)
INSERT INTO @result1
SELECT a, b, c
FROM table1
SELECT a AS val FROM @result1
UNION
SELECT b AS val FROM @result1
UNION
SELECT c AS val FROM @result1
This should be fine for what you need.
VAR=$VAR"$VARTOADD(STRING)"
echo $VAR
I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.
Here is an example:
mysql> PREPARE stmt FROM
-> 'select count(*)
-> from information_schema.schemata
-> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt
-> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
| 2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;
The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.
Here is a good link about this:
Don't forget to deallocate the stmt
using the last line!
Good Luck!
One notable difference is that if you pass a .c
file to gcc it will compile as C.
The default behavior of g++ is to treat .c
files as C++ (unless -x c
is specified).
you use the scrollTop attribute
var position = document.getElementById('id').scrollTop;
I had faced the same issue because of some dll files were missing from References of VS13. I went to the location http://scn.sap.com/docs/DOC-7824 and installed the newest pack. It resolved the issue.
Try this one. It is working for me.
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Set up the projection (we only need the ID)
String[] projection = { MediaStore.Images.Media._ID };
// Match on the file path
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[] { imageFile.getAbsolutePath() };
// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = getActivity().getContentResolver();
Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
if (c != null) {
if (c.moveToFirst()) {
// We found the ID. Deleting the item via the content provider will also remove the file
long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
Uri deleteUri = ContentUris.withAppendedId(queryUri, id);
contentResolver.delete(deleteUri, null, null);
} else {
// File not found in media store DB
}
c.close();
}
}
}, 5000);
I have been using windows for the last 13 years. I found this solution to be truly working for me. I recommend you to follow these steps:
let's start by deleting this folder
C:\Users\Your-name\AppData\Roaming\syntevo
Completely uninstall smart git from the control panel, uninstall programs.
Again re-install the smart git and change the default position of installing directory.
While configuring smart git, make sure that the non-commercial option is selected that will help you to use the latest as well as a free version for lifetime.
<input type="text" [ngModel]="mymodel" (keypress)="mymodel=$event.target.value"/>
{{mymodel}}
If you are only looking for a refresh rate for the GOOGLEFINANCE
function, keep in mind that data delays can be up to 20 minutes (per Google Finance Disclaimer).
GoogleClock
)Here is a modified version of the refresh action, taking the data delay into consideration, to save on unproductive refresh cycles.
=GoogleClock(GOOGLEFINANCE(symbol,"datadelay"))
For example, with:
then
=GoogleClock(GOOGLEFINANCE("GOOG","datadelay"))
Results in a dynamic data-based refresh rate of:
=GoogleClock(15)
GoogleClock
)If your sheet contains a number of rows of symbols, you could add a datadelay
column for each symbol and use the lowest value, for example:
=GoogleClock(MIN(dataDelayValuesNamedRange))
Where dataDelayValuesNamedRange
is the absolute reference or named reference of the range of cells that contain the data delay values for each symbol (assuming these values are different).
GoogleClock()
The GoogleClock()
function was removed in 2014 and replaced with settings setup for refreshing sheets. At present, I have confirmed that replacement settings is only on available in Sheets from when accessed from a desktop browser, not the mobile app (I'm using Google's mobile Sheets app updated 2016-03-14).
(This part of the answer is based on, and portions copied from, Google Docs Help)
To change how often "some" Google Sheets functions update:
NOTE External data functions recalculate at the following intervals:
The references in earlier sections to the display and use of the datadelay
attribute still apply, as well as the concepts for more efficient coding of sheets.
On a positive note, the new refresh option continues to be refreshed by Google servers regardless of whether you have the sheet loaded or not. That's a positive for shared sheets for sure; even more so for Google Apps Scripts (GAS), where GAS is used in workflow code or referenced data is used as a trigger for an event.
[*] in my understanding so far (I am currently testing this)
It looks like not.
Put a breakpoint, when it stops switch to the console, try to set the variable. It does not error when you assign it a different value, but if you read it after the assignment, it's unmodified. :-/
I know this is quite old, but I recently had to do something very similar, and came up with a much simpler solution.
It boils down to the following steps:
See this post for the full example: Handling click events on a drawable within an EditText
In Windows 7 and later, this will do the trick for you
The menu item Copy as Path is not available in Windows XP.
I was facing the same error today, what I was doing wrong was that I was not adding Password tag in the connection string. As soon as I added the Password tag with correct password the error went away. Hope it helps someone.
Try the jQuery starts-with
selector, '^=', eg
[id^="jander"]
I have to ask though, why don't you want to do this using classes?
Given that Windows has no sys/socket.h, you might consider just doing something like this:
#ifdef __WIN32__
# include <winsock2.h>
#else
# include <sys/socket.h>
#endif
I know you indicated that you won't use WinSock, but since WinSock is how TCP networking is done under Windows, I don't see that you have any alternative. Even if you use a cross-platform networking library, that library will be calling WinSock internally. Most of the standard BSD sockets API calls are implemented in WinSock, so with a bit of futzing around, you can make the same sockets-based program compile under both Windows and other OS's. Just don't forget to do a
#ifdef __WIN32__
WORD versionWanted = MAKEWORD(1, 1);
WSADATA wsaData;
WSAStartup(versionWanted, &wsaData);
#endif
at the top of main()... otherwise all of your socket calls will fail under Windows, because the WSA subsystem wasn't initialized for your process.
Let's take a look at what happens when you select a file and submit your form (I've truncated the headers for brevity):
POST /upload?upload_progress_id=12344 HTTP/1.1
Host: localhost:3000
Content-Length: 1325
Origin: http://localhost:3000
... other headers ...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryePkpFF7tjBAqx29L
------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="MAX_FILE_SIZE"
100000
------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="uploadedfile"; filename="hello.o"
Content-Type: application/x-object
... contents of file goes here ...
------WebKitFormBoundaryePkpFF7tjBAqx29L--
NOTE: each boundary string must be prefixed with an extra --
, just like in the end of the last boundary string. The example above already includes this, but it can be easy to miss. See comment by @Andreas below.
Instead of URL encoding the form parameters, the form parameters (including the file data) are sent as sections in a multipart document in the body of the request.
In the example above, you can see the input MAX_FILE_SIZE
with the value set in the form, as well as a section containing the file data. The file name is part of the Content-Disposition
header.
The full details are here.
You can use peek
to do that.
List<Fruit> newList = fruits.stream()
.peek(f -> f.setName(f.getName() + "s"))
.collect(Collectors.toList());
This is my solution. From my point of view, you can not bypass the <a>
.
function export2json() {_x000D_
const data = {_x000D_
a: '111',_x000D_
b: '222',_x000D_
c: '333'_x000D_
};_x000D_
const a = document.createElement("a");_x000D_
a.href = URL.createObjectURL(_x000D_
new Blob([JSON.stringify(data, null, 2)], {_x000D_
type: "application/json"_x000D_
})_x000D_
);_x000D_
a.setAttribute("download", "data.json");_x000D_
document.body.appendChild(a);_x000D_
a.click();_x000D_
document.body.removeChild(a);_x000D_
}
_x000D_
<button onclick="export2json()">Export data to json file</button>
_x000D_
Regarding the accepted answer, it is important to use toSerialize.GetType()
instead of typeof(T)
in XmlSerializer
constructor: if you use the first one the code covers all possible scenarios, while using the latter one fails sometimes.
Here is a link with some example code that motivate this statement, with XmlSerializer
throwing an Exception when typeof(T)
is used, because you pass an instance of a derived type to a method that calls SerializeObject<T>()
that is defined in the derived type's base class: http://ideone.com/1Z5J1. Note that Ideone uses Mono to execute code: the actual Exception you would get using the Microsoft .NET runtime has a different Message than the one shown on Ideone, but it fails just the same.
For the sake of completeness I post the full code sample here for future reference, just in case Ideone (where I posted the code) becomes unavailable in the future:
using System;
using System.Xml.Serialization;
using System.IO;
public class Test
{
public static void Main()
{
Sub subInstance = new Sub();
Console.WriteLine(subInstance.TestMethod());
}
public class Super
{
public string TestMethod() {
return this.SerializeObject();
}
}
public class Sub : Super
{
}
}
public static class TestExt {
public static string SerializeObject<T>(this T toSerialize)
{
Console.WriteLine(typeof(T).Name); // PRINTS: "Super", the base/superclass -- Expected output is "Sub" instead
Console.WriteLine(toSerialize.GetType().Name); // PRINTS: "Sub", the derived/subclass
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
StringWriter textWriter = new StringWriter();
// And now...this will throw and Exception!
// Changing new XmlSerializer(typeof(T)) to new XmlSerializer(subInstance.GetType());
// solves the problem
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
To expand on the answer I came here to get a better understanding so I wrote this that can explain it and helped me too.
It has the setlocal DisableDelayedExpansion
in there so you can locally set this as you wish between the setlocal EnableDelayedExpansion
and it.
@echo off
title %~nx0
for /f "tokens=*" %%A in ("Some Thing") do (
setlocal EnableDelayedExpansion
set z=%%A
echo !z! Echoing the assigned variable in setlocal scope.
echo %%A Echoing the variable in local scope.
setlocal DisableDelayedExpansion
echo !z! &rem !z! Neither of these now work, which makes sense.
echo %z% &rem ECHO is off. Neither of these now work, which makes sense.
echo %%A Echoing the variable in its local scope, will always work.
)
This one works on X11, and perhaps on Windows too (someone, please check). Needs PyQt4:
import sys
from PyQt4.QtGui import QPixmap, QApplication
app = QApplication(sys.argv)
QPixmap.grabWindow(QApplication.desktop().winId()).save('test.png', 'png')
how about
var top = $('html').scrollTop() || $('body').scrollTop();
I used this in my code:
<div class="sticky-top h-100">
<nav id="sidebar" class="vh-100">
....
this cause your sidebar height become 100% and fixed at top.
Here you can find some public REST services for encryption and security related things: http://security.jelastic.servint.net
Just been implementing something similar in Mongo v3.2.3 using Node v0.12.7 and v4.4.4 and used:
{ $gte: new Date(dateVar).toISOString() }
I'm passing in an ISODate (e.g. 2016-04-22T00:00:00Z) and this works for a .find() query with or without the toISOString function. But when using in an .aggregate() $match query it doesn't like the toISOString function!
It's possible to argue that using SSHs key to authenticate is less secure because we tend to change our password more periodically than we generate new SSH keys.
Servers that limit the lifespan for which they'll honor given SSH keys can help force users toward the practice of refreshing SSH-keys periodically.
JavaScript, as defined in your question, can't directly work with MySql. This is because it isn't running on the same computer.
JavaScript runs on the client side (in the browser), and databases usually exist on the server side. You'll probably need to use an intermediate server-side language (like PHP, Java, .Net, or a server-side JavaScript stack like Node.js) to do the query.
Here's a tutorial on how to write some code that would bind PHP, JavaScript, and MySql together, with code running both in the browser, and on a server:
http://www.w3schools.com/php/php_ajax_database.asp
And here's the code from that page. It doesn't exactly match your scenario (it does a query, and doesn't store data in the DB), but it might help you start to understand the types of interactions you'll need in order to make this work.
In particular, pay attention to these bits of code from that article.
Bits of Javascript:
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
Bits of PHP code:
mysql_select_db("ajax_demo", $con);
$result = mysql_query($sql);
// ...
$row = mysql_fetch_array($result)
mysql_close($con);
Also, after you get a handle on how this sort of code works, I suggest you use the jQuery JavaScript library to do your AJAX calls. It is much cleaner and easier to deal with than the built-in AJAX support, and you won't have to write browser-specific code, as jQuery has cross-browser support built in. Here's the page for the jQuery AJAX API documentation.
HTML/Javascript code:
<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
PHP code:
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
I haven't found a clear answer, without checks if it is negative or positive, that uses two's complement (negative numbers included). For that, I show my solution to one byte:
((0xFF + number +1) & 0x0FF).toString(16);
You can use this instruction to any number bytes, only you add FF
in respective places. For example, to two bytes:
((0xFFFF + number +1) & 0x0FFFF).toString(16);
If you want cast an array integer to string hexadecimal:
s = "";
for(var i = 0; i < arrayNumber.length; ++i) {
s += ((0xFF + arrayNumber[i] +1) & 0x0FF).toString(16);
}
I fought this problem for HOURS.
I tried to update requests. Then I updated certifi. I pointed verify to certifi.where() (The code does this by default anyways). Nothing worked.
Finally I updated my version of python to python 2.7.11. I was on Python 2.7.5 which had some incompatibilities with the way that the certificates are verified. Once I updated Python (and a handful of other dependencies) it started working.
The problem occurred due to the Control validator. Just Add the J Query reference to your web page as follows and then add the Validation Settings in your web.config file to overcome the problem. I too faced the same problem and the below gave the solution to my problem.
Step1:
Step2 :
It will resolve your problem.
Use StringBuilder
class, like so:
StringBuilder meme = new StringBuilder(" ");
// Convert and append your double variable
meme.append(String.valueOf(doubleVariable));
// Convert string builder to string
jTextField9.setText(meme.toString());
You will get you desired output.
If this ()Unsupported method: BaseConfig.getApplicationIdSuffix Android Project is old and you have updated Android Studio, what I did was simply CLOSE PROJECT and ran it again. It solved the issue for me. Did not add any dependencies or whatever as described by other answers.
$str = '';
$str_len = 8;
for($i = 0, $i < $str_len; $i++){
//97 is ascii code for 'a' and 122 is ascii code for z
$str .= chr(rand(97, 122));
}
return $str