To extract the real part of a complex-valued expression z
, use the notation as __real__ z
.
Similarly, use __imag__
attribute on the z
to extract the imaginary part.
For example;
__complex__ float z;
float r;
float i;
r = __real__ z;
i = __imag__ z;
r is the real part of the complex number "z" i is the imaginary part of the complex number "z"
In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:
>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)
The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)
The type of a complex number is complex
, and you can use the type as a constructor if you prefer:
>>> complex(2,3)
(2+3j)
A complex number has some built-in accessors:
>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)
Several built-in functions support complex numbers:
>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)
The standard module cmath
has more functions that handle complex numbers:
>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)
If you really want to eke out performance (with big arrays), numexpr can be used, which takes advantage of multiple cores.
Setup:
>>> import numpy as np
>>> Data = np.random.randn(64, 64, 64, 2)
>>> x, y = Data[...,0], Data[...,1]
With numexpr
:
>>> import numexpr as ne
>>> %timeit result = ne.evaluate("complex(x, y)")
573 µs ± 21.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Compared to fast numpy method:
>>> %timeit result = np.empty(x.shape, dtype=complex); result.real = x; result.imag = y
1.39 ms ± 5.74 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
The easiest way to match both
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
and
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
is to use alternation ((...|...)
): specify them as two mostly-separate options:
^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$
By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234
, not (123)123-1234
. So you might want to write:
^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$
(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)
First you can use a Paginator. This is as simple as:
$allUsers = User::paginate(15);
$someUsers = User::where('votes', '>', 100)->paginate(15);
The variables will contain an instance of Paginator class. all of your data will be stored under data
key.
Or you can do something like:
Old versions Laravel.
Model::all()->take(10)->get();
Newer version Laravel.
Model::all()->take(10);
For more reading consider these links:
It is important to note the following difference between the two techniques:
$Str="This is the<BR />source string<BR />ALL RIGHT"
$Str.Split("<BR />")
This
is
the
(multiple blank lines)
source
string
(multiple blank lines)
ALL
IGHT
$Str -Split("<BR />")
This is the
source string
ALL RIGHT
From this you can see that the string.split()
method:
While the -split
operator:
I believe you can set the SVN_USER
environment variable to change your SVN username.
best bet is targeting features not devices unless you have to, bootstrap do well and you can extend on their breakpoints, for instance targeting pixel density and larger screens above 1920
When you return value from server to jQuery's Ajax call you can also use the below code to indicate a server error:
return StatusCode(500, "My error");
Or
return StatusCode((int)HttpStatusCode.InternalServerError, "My error");
Or
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { responseText = "my error" });
Codes other than Http Success codes (e.g. 200[OK]) will trigger the function in front of error:
in client side (ajax).
you can have ajax call like:
$.ajax({
type: "POST",
url: "/General/ContactRequestPartial",
data: {
HashId: id
},
success: function (response) {
console.log("Custom message : " + response.responseText);
}, //Is Called when Status Code is 200[OK] or other Http success code
error: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
}, //Is Called when Status Code is 500[InternalServerError] or other Http Error code
})
Additionally you can handle different HTTP errors from jQuery side like:
$.ajax({
type: "POST",
url: "/General/ContactRequestPartial",
data: {
HashId: id
},
statusCode: {
500: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
501: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
}
})
statusCode:
is useful when you want to call different functions for different status codes that you return from server.
You can see list of different Http Status codes here:Wikipedia
Additional resources:
Use sum()
in place of count()
Try below:
SELECT
ccc_news . * ,
SUM(if(ccc_news_comments.id = 'approved', 1, 0)) AS comments
FROM
ccc_news
LEFT JOIN
ccc_news_comments
ON
ccc_news_comments.news_id = ccc_news.news_id
WHERE
`ccc_news`.`category` = 'news_layer2'
AND `ccc_news`.`status` = 'Active'
GROUP BY
ccc_news.news_id
ORDER BY
ccc_news.set_order ASC
LIMIT 20
Another relevant environment variable is:
So, on a 64-bit machine running in 32-bit (WOW64) mode:
- echo %programfiles% ==> C:\Program Files (x86)
- echo %programfiles(x86)% ==> C:\Program Files (x86)
- echo %ProgramW6432% ==> C:\Program Files
From Wikipedia:
The %ProgramFiles% variable points to the Program Files directory, which stores all the installed programs of Windows and others. The default on English-language systems is "C:\Program Files". In 64-bit editions of Windows (XP, 2003, Vista), there are also %ProgramFiles(x86)%, which defaults to "C:\Program Files (x86)", and %ProgramW6432%, which defaults to "C:\Program Files". The %ProgramFiles% itself depends on whether the process requesting the environment variable is itself 32-bit or 64-bit (this is caused by Windows-on-Windows 64-bit redirection).
Reference: http://en.wikipedia.org/wiki/Environment_variable
!=
For example,
if ("apple" != "orange")
// true, the string "apple" is not equal to the string "orange"
Means not. See also the logical operators list. Also, when you see triple characters, it's a type sensitive comparison. (e.g. if (1 === '1')
[not equal])
Ctrl + Space
or
Ctrl + J
You can also go to menu Tools ? Options ? Environment ? Keyboard and check what is assigned to these shortcuts. The command name should be Edit.CompleteWord
.
As ams said above, don't take a pointer to a member of a struct that's packed. This is simply playing with fire. When you say __attribute__((__packed__))
or #pragma pack(1)
, what you're really saying is "Hey gcc, I really know what I'm doing." When it turns out that you do not, you can't rightly blame the compiler.
Perhaps we can blame the compiler for it's complacency though. While gcc does have a -Wcast-align
option, it isn't enabled by default nor with -Wall
or -Wextra
. This is apparently due to gcc developers considering this type of code to be a brain-dead "abomination" unworthy of addressing -- understandable disdain, but it doesn't help when an inexperienced programmer bumbles into it.
Consider the following:
struct __attribute__((__packed__)) my_struct {
char c;
int i;
};
struct my_struct a = {'a', 123};
struct my_struct *b = &a;
int c = a.i;
int d = b->i;
int *e __attribute__((aligned(1))) = &a.i;
int *f = &a.i;
Here, the type of a
is a packed struct (as defined above). Similarly, b
is a pointer to a packed struct. The type of of the expression a.i
is (basically) an int l-value with 1 byte alignment. c
and d
are both normal int
s. When reading a.i
, the compiler generates code for unaligned access. When you read b->i
, b
's type still knows it's packed, so no problem their either. e
is a pointer to a one-byte-aligned int, so the compiler knows how to dereference that correctly as well. But when you make the assignment f = &a.i
, you are storing the value of an unaligned int pointer in an aligned int pointer variable -- that's where you went wrong. And I agree, gcc should have this warning enabled by default (not even in -Wall
or -Wextra
).
To download your repository as zip file via curl
:
curl -L -o master.zip http://github.com/zoul/Finch/zipball/master/
If your repository is private:
curl -u 'username' -L -o master.zip http://github.com/zoul/Finch/zipball/master/
Source: Github Help
You should implement a Comparator<Map<String, String>>
which basically extracts the "name" value from the two maps it's passed, and compares them.
Then use Collections.sort(list, comparator)
.
Are you sure a Map<String, String>
is really the best element type for your list though? Perhaps you should have another class which contains a Map<String, String>
but also has a getName()
method?
If you would like to get GMT time only with intiger: var currentTime = new Date(); var currentYear ='2010' var currentMonth = 10; var currentDay ='30' var currentHours ='20' var currentMinutes ='20' var currentSeconds ='00' var currentMilliseconds ='00'
currentTime.setFullYear(currentYear);
currentTime.setMonth((currentMonth-1)); //0is January
currentTime.setDate(currentDay);
currentTime.setHours(currentHours);
currentTime.setMinutes(currentMinutes);
currentTime.setSeconds(currentSeconds);
currentTime.setMilliseconds(currentMilliseconds);
var currentTimezone = currentTime.getTimezoneOffset();
currentTimezone = (currentTimezone/60) * -1;
var gmt ="";
if (currentTimezone !== 0) {
gmt += currentTimezone > 0 ? ' +' : ' ';
gmt += currentTimezone;
}
alert(gmt)
Using ggplot
and a little dplyr
for data manipulation:
set.seed(42)
df <- data.frame(x = rep(1:10,each=5), y = rnorm(50))
library(ggplot2)
library(dplyr)
df.summary <- df %>% group_by(x) %>%
summarize(ymin = min(y),
ymax = max(y),
ymean = mean(y))
ggplot(df.summary, aes(x = x, y = ymean)) +
geom_point(size = 2) +
geom_errorbar(aes(ymin = ymin, ymax = ymax))
If there's an additional grouping column (OP's example plot has two errorbars per x value, saying the data is sourced from two files), then you should get all the data in one data frame at the start, add the grouping variable to the dplyr::group_by
call (e.g., group_by(x, file)
if file
is the name of the column) and add it as a "group" aesthetic in the ggplot, e.g., aes(x = x, y = ymean, group = file)
.
Have a look at the example in this link :
http://docs.angularjs.org/api/ngSanitize.$sanitize
Basically, angular has a directive to insert html into pages. In your case you can insert the html using the ng-bind-html directive like so :
If you already have done all this :
// My magic HTML string function.
function htmlString (str) {
return "<h1>" + str + "</h1>";
}
function Ctrl ($scope) {
var str = "HELLO!";
$scope.htmlString = htmlString(str);
}
Ctrl.$inject = ["$scope"];
Then in your html within the scope of that controller, you could
<div ng-bind-html="htmlString"></div>
Update: you can read the more complex answer, which contains more methods and information.
There exists a couple of scripts, which can be used as simple package managers. But as far as I know, none of them allows you to upgrade packages, because it’s not an easy task on Windows since there is not possible to overwrite files in use. So you have to close all Cygwin instances first and then you can use Cygwin’s native setup.exe (which itself does the upgrade via “replace after reboot” method, when files are in use).
The best one for me. Simply because it’s one of the most recent. It works correctly for both platforms - x86 and x86_64. There exists a lot of forks with some additional features. For example the kou1okada fork is one of improved versions.
It has also command line mode. Moreover it allows you to upgrade all installed packages at once.
setup.exe-x86_64.exe -q --packages=bash,vim
Example use:
setup.exe-x86_64.exe -q --packages="bash,vim"
You can create an alias for easier use, for example:
alias cyg-get="/cygdrive/d/path/to/cygwin/setup-x86_64.exe -q -P"
Then you can for example install the Vim package with:
cyg-get vim
The --trace-ascii
option to curl will show the request headers, as well as the response headers and response body.
For example, the command
curl --trace-ascii curl.trace http://www.google.com/
produces a file curl.trace
that starts as follows:
== Info: About to connect() to www.google.com port 80 (#0)
== Info: Trying 209.85.229.104... == Info: connected
== Info: Connected to www.google.com (209.85.229.104) port 80 (#0)
=> Send header, 145 bytes (0x91)
0000: GET / HTTP/1.1
0010: User-Agent: curl/7.16.3 (powerpc-apple-darwin9.0) libcurl/7.16.3
0050: OpenSSL/0.9.7l zlib/1.2.3
006c: Host: www.google.com
0082: Accept: */*
008f:
It also got a response (a 302 response, to be precise but irrelevant) which was logged.
If you only want to save the response headers, use the --dump-header
option:
curl -D file url
curl --dump-header file url
If you need more information about the options available, use curl --help | less
(it produces a couple hundred lines of output but mentions a lot of options). Or find the manual page where there is more explanation of what the options mean.
I have created this simple function which you guys can use easily. You will need to pass the table-name ($tbl)
, table-field ($insertFieldsArr)
against your inserting data, data array ($arr)
.
insert_batch('table',array('field1','field2'),$dataArray);
function insert_batch($tbl,$insertFieldsArr,$arr){ $sql = array();
foreach( $arr as $row ) {
$strVals='';
$cnt=0;
foreach($insertFieldsArr as $key=>$val){
if(is_array($row)){
$strVals.="'".mysql_real_escape_string($row[$cnt]).'\',';
}
else{
$strVals.="'".mysql_real_escape_string($row).'\',';
}
$cnt++;
}
$strVals=rtrim($strVals,',');
$sql[] = '('.$strVals.')';
}
$fields=implode(',',$insertFieldsArr);
mysql_query('INSERT INTO `'.$tbl.'` ('.$fields.') VALUES '.implode(',', $sql));
}
Just wanted to update this thread for future developers.
JQuery >1.12 Now supports being able to change every little piece of the request through JQuery.post ($.post({...}). see second function signature in https://api.jquery.com/jquery.post/
I have used the below commands for removing any proxy set:
npm config rm proxy
npm config rm https-proxy
And it solved my problem :)
Install "vbox-ssl-cacertificate.crt" certificate from %userprofile%\\.virtualbox\
and then reboot. If you don't have .virtualbox
folder - launch "Oracle VM VirtualBox" once and this folder will appear.
I had this issue not only on my machine but on many hosts, and this certificate fixed the issue. I figured it out by chance, because nowhere said about this certificate -_-
Check encoding format of your file and use corresponding encoding format while reading file. It will solve your problem.
with open("AB.json", encoding='utf-8', errors='ignore') as json_data:
data = json.load(json_data, strict=False)
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;
protected void Button1_Click(object sender, EventArgs e)
{
//Upload and save the file
string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(excelPath);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
excel_con.Open();
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
//[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
dtExcelData.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)) });
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["dbcn"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.Table1";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("Sl", "Id");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
}
}
Copy this in web config
<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
<add name="Excel07+ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
you can also refer this link : https://athiraji.blogspot.com/2019/03/how-to-upload-excel-fle-to-database.html
If you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
../htmlfilename with .html User can do this This will solve your problem of redirection to anypage for local files.
root/
assets/
lib/-------------------------libraries--------------------
bootstrap/--------------Libraries can have js/css/images------------
css/
js/
images/
jquery/
js/
font-awesome/
css/
images/
common/--------------------common section will have application level resources
css/
js/
img/
index.html
This is how I organized my application's static resources.
You could maybe add a method to your Production object called 'SetPowerRating(int)' which sets a property in Production, and call this in your Meter object before using the property in the Production object?
The easiest way I have found to pass data between routeHandlers to use next()
no need to mess with redirect or sessions.
Optionally you could just call your homeCtrl(req,res)
instead of next()
and just pass the req
and res
var express = require('express');
var jade = require('jade');
var http = require("http");
var app = express();
var server = http.createServer(app);
/////////////
// Routing //
/////////////
// Move route middleware into named
// functions
function homeCtrl(req, res) {
// Prepare the context
var context = req.dataProcessed;
res.render('home.jade', context);
}
function categoryCtrl(req, res, next) {
// Process the data received in req.body
// instead of res.redirect('/');
req.dataProcessed = somethingYouDid;
return next();
// optionally - Same effect
// accept no need to define homeCtrl
// as the last piece of middleware
// return homeCtrl(req, res, next);
}
app.get('/', homeCtrl);
app.post('/category', categoryCtrl, homeCtrl);
No, you can't break from a closure in Groovy without throwing an exception. Also, you shouldn't use exceptions for control flow.
If you find yourself wanting to break out of a closure you should probably first think about why you want to do this and not how to do it. The first thing to consider could be the substitution of the closure in question with one of Groovy's (conceptual) higher order functions. The following example:
for ( i in 1..10) { if (i < 5) println i; else return}
becomes
(1..10).each{if (it < 5) println it}
becomes
(1..10).findAll{it < 5}.each{println it}
which also helps clarity. It states the intent of your code much better.
The potential drawback in the shown examples is that iteration only stops early in the first example. If you have performance considerations you might want to stop it right then and there.
However, for most use cases that involve iterations you can usually resort to one of Groovy's find, grep, collect, inject, etc. methods. They usually take some "configuration" and then "know" how to do the iteration for you, so that you can actually avoid imperative looping wherever possible.
The reset_index() is a pandas DataFrame method that will transfer index values into the DataFrame as columns. The default setting for the parameter is drop=False (which will keep the index values as columns).
All you have to do add .reset_index(inplace=True)
after the name of the DataFrame:
df.reset_index(inplace=True)
The ConnectTimeout option allows you to tell your ssh client how long you're willing to wait for a connection before returning an error. By setting ConnectTimeout to 1, you're effectively saying "try for at most 1 second and then fail if you haven't connected yet".
The problem is that when you connect by name, the DNS lookup can take several seconds. Connecting by IP address is much faster, and may actually work in one second or less. What sinelaw is experiencing is that every attempt to connect by DNS name is failing to occur within one second. The default setting of ConnectTimeout defers to the linux kernel connect timeout, which is usually pretty long.
There is absolutely no way to achieve what you want through CSS alone while supporting pre-flexbox user agents (mostly old IE) -- unless:
If the above are true then you can do what you want by absolutely positioning the elements --
#wrapper { position: relative; }
#firstDiv { position: absolute; height: 100px; top: 110px; }
#secondDiv { position: absolute; height: 100px; top: 0; }
Again, if you don't know the height want for at least #firstDiv, there's no way you can do what you want via CSS alone. If any of this content is dynamic, you will have to use javascript.
Just replace @latest
with the version number you want to downgrade to. I wanted to downgrade to version 3.10.10, so I used this command:
npm install -g [email protected]
If you're not sure which version you should use, look at the version history. For example, you can see that 3.10.10 is the latest version of npm 3.
You need to include the appropriate header
#include <stdio.h>
If you're not sure which header a standard function is defined in, the function's man page will state this.
Here is a complete example showing how to use the **
operator to pass values from a dictionary as keyword arguments.
>>> def f(x=2):
... print(x)
...
>>> new_x = {'x': 4}
>>> f() # default value x=2
2
>>> f(x=3) # explicit value x=3
3
>>> f(**new_x) # dictionary value x=4
4
For those who might have the same problem as me, I got this error when the DB I was using was actually master, and not the DB I should have been using.
Just put use [DBName]
on the top of your script, or manually change the DB in use in the SQL Server Management Studio GUI.
Its a bit counter-intuitive. The toolchain is called gcc-arm-linux-gnueabi. To invoke the tools execute the following: arm-linux-gnueabi-xxx
where xxx is gcc or ar or ld, etc
Or, if you are a fan of functional programming:
>>> a = [133, 53, 234, 241]
>>> "".join(map(lambda b: format(b, "02x"), a))
8535eaf1
>>>
git pull
is like running git fetch
then git merge
git pull --rebase
is like git fetch
then git rebase
git pull
is like a git fetch
+ git merge
.
"In its default mode, git pull is shorthand for
git fetch
followed bygit merge
FETCH_HEAD" More precisely,git pull
runsgit fetch
with the given parameters and then callsgit merge
to merge the retrieved branch heads into the current branch"
(Ref: https://git-scm.com/docs/git-pull)
'But what is the difference between git pull
VS git fetch
+ git rebase
'
Again, from same source:
git pull --rebase
"With --rebase, it runs git rebase instead of git merge."
'the difference between merge
and rebase
'
that is answered here too:
https://git-scm.com/book/en/v2/Git-Branching-Rebasing
(the difference between altering the way version history is recorded)
An alternative to ArgumentMatcher
is ArgumentCaptor
.
Official example:
ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName());
A captor can also be defined using the @Captor annotation:
@Captor ArgumentCaptor<Person> captor;
//... MockitoAnnotations.initMocks(this);
@Test public void test() {
//...
verify(mock).doSomething(captor.capture());
assertEquals("John", captor.getValue().getName());
}
This is my function for generating a 8-character crypto-random password:
function generatePassword() {
var buf = new Uint8Array(6);
window.crypto.getRandomValues(buf);
return btoa(String.fromCharCode.apply(null, buf));
}
What it does: Retrieves 6 crypto-random 8-bit integers and encodes them with Base64.
Since the result is in the Base64 character set the generated password may consist of A
-Z
, a
-z
, 0
-9
, +
and /
.
1. We can use aggregate function with HAVING clause not by WHERE clause e.g. min,max,avg.
2. WHERE clause eliminates the record tuple by tuple HAVING clause eliminates entire group from the collection of group
Mostly HAVING is used when you have groups of data and WHERE is used when you have data in rows.
The top border of frame is of size 30.You can write code for printing the coordinate of any point on the frame using MouseInputAdapter.You will find when the cursor is just below the top border of the frame the y coordinate is not zero , its close to 30.Hence if you give size to frame 300 * 300 , the size available for putting the components on the frame is only 300 * 270.So if you need to have size 300 * 300 ,give 300 * 330 size of the frame.
Best solution that my friend Dhanush Kumar came up with:
def second_max(loop):
glo_max = loop[0]
sec_max = float("-inf")
for i in loop:
if i > glo_max:
sec_max = glo_max
glo_max=i
elif sec_max < i < glo_max:
sec_max = i
return sec_max
#print(second_max([-1,-3,-4,-5,-7]))
assert second_max([-1,-3,-4,-5,-7])==-3
assert second_max([5,3,5,1,2]) == 3
assert second_max([1,2,3,4,5,7]) ==5
assert second_max([-3,1,2,5,-2,3,4]) == 4
assert second_max([-3,-2,5,-1,0]) == 0
assert second_max([0,0,0,1,0]) == 0
Can also use
@(time(nil)).stringValue);
for timestamp in seconds.
You can use spread syntax as follows..
var alerts = {
1: { app: 'helloworld', message: 'message' },
2: { app: 'helloagain', message: 'another message' }
}
alerts = {...alerts, 3: {app: 'hey there', message: 'another message'} }
You have written like
@Html.RadioButtonFor(model => model.gender, "Male", new { @checked = true }) and
@Html.RadioButtonFor(model => model.gender, "Female", new { @checked = true })
Here you have taken gender as a Enum
type and you have written the value for the radio button as a string
type- change "Male" to 0 and "Female" to 1.
A submodule is nothing but a clone of a git repo within another repo with some extra meta data (gitlink tree entry, .gitmodules file )
$ cd your_submodule
$ git checkout master
<hack,edit>
$ git commit -a -m "commit in submodule"
$ git push
$ cd ..
$ git add your_submodule
$ git commit -m "Updated submodule"
I have tried the following command and they work well.
bzip2 -t file.bz2
gunzip -t file.gz
However, we can found these two command are time-consuming. Maybe we need some more quick way to determine the intact of the compress files.
For whom it might concern - I tweaked around with Andreas code in order to get all errors code in a flat object for easier logging errors that might appear.
Please consider:
export function collectErrors(control: AbstractControl): any | null {
let errors = {};
let recursiveFunc = (control: AbstractControl) => {
if (isFormGroup(control)) {
return Object.entries(control.controls).reduce(
(acc, [key, childControl]) => {
const childErrors = recursiveFunc(childControl);
if (childErrors) {
if (!isFormGroup(childControl)) {
errors = { ...errors, [key]: childErrors };
}
acc = { ...acc, [key]: childErrors };
}
return acc;
},
null
);
} else {
return control.errors;
}
};
recursiveFunc(control);
return errors;
}
It's seem like people are trying emulate the C++ style using C. My take is that doing object-oriented programming C is really doing struct-oriented programming. However, you can achieve things like late binding, encapsulation, and inheritance. For inheritance you explicitly define a pointer to the base structs in your sub struct and this is obviously a form of multiple inheritance. You'll also need to determine if your
//private_class.h
struct private_class;
extern struct private_class * new_private_class();
extern int ret_a_value(struct private_class *, int a, int b);
extern void delete_private_class(struct private_class *);
void (*late_bind_function)(struct private_class *p);
//private_class.c
struct inherited_class_1;
struct inherited_class_2;
struct private_class {
int a;
int b;
struct inherited_class_1 *p1;
struct inherited_class_2 *p2;
};
struct inherited_class_1 * new_inherited_class_1();
struct inherited_class_2 * new_inherited_class_2();
struct private_class * new_private_class() {
struct private_class *p;
p = (struct private_class*) malloc(sizeof(struct private_class));
p->a = 0;
p->b = 0;
p->p1 = new_inherited_class_1();
p->p2 = new_inherited_class_2();
return p;
}
int ret_a_value(struct private_class *p, int a, int b) {
return p->a + p->b + a + b;
}
void delete_private_class(struct private_class *p) {
//release any resources
//call delete methods for inherited classes
free(p);
}
//main.c
struct private_class *p;
p = new_private_class();
late_bind_function = &implementation_function;
delete_private_class(p);
compile with c_compiler main.c inherited_class_1.obj inherited_class_2.obj private_class.obj
.
So the advice is to stick to a pure C style and not try to force into a C++ style. Also this way lends itself to a very clean way of building an API.
The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:
RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);
There, &rect
is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.
The code should create a dynamic variable:
RectInvoice *rect = new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);
There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.
Cheers
Here's another approach, in case you want split a string with a delimiter.
import pyspark.sql.functions as f
df = spark.createDataFrame([("1:a:2001",),("2:b:2002",),("3:c:2003",)],["value"])
df.show()
+--------+
| value|
+--------+
|1:a:2001|
|2:b:2002|
|3:c:2003|
+--------+
df_split = df.select(f.split(df.value,":")).rdd.flatMap(
lambda x: x).toDF(schema=["col1","col2","col3"])
df_split.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
| 1| a|2001|
| 2| b|2002|
| 3| c|2003|
+----+----+----+
I don't think this transition back and forth to RDDs is going to slow you down... Also don't worry about last schema specification: it's optional, you can avoid it generalizing the solution to data with unknown column size.
I see this is a fairly old question, but this looks like one of those times when something's been written without knowledge of a language feature. The collections
library exists to fulfill these purposes.
from collections import Counter
letter_counter = Counter()
for letter in 'The quick brown fox jumps over the lazy dog':
letter_counter[letter] += 1
>>> letter_counter
Counter({' ': 8, 'o': 4, 'e': 3, 'h': 2, 'r': 2, 'u': 2, 'T': 1, 'a': 1, 'c': 1, 'b': 1, 'd': 1, 'g': 1, 'f': 1, 'i': 1, 'k': 1, 'j': 1, 'm': 1, 'l': 1, 'n': 1, 'q': 1, 'p': 1, 's': 1, 't': 1, 'w': 1, 'v': 1, 'y': 1, 'x': 1, 'z': 1})
In this example the spaces are being counted, obviously, but whether or not you want those filtered is up to you.
As for the dict.get(a_key, default_value)
, there have been several answers to this particular question -- this method returns the value of the key, or the default_value you supply. The first argument is the key you're looking for, the second argument is the default for when that key is not present.
Short extension for Kotlin
fun Bitmap.rotate(degrees: Float): Bitmap {
val matrix = Matrix().apply { postRotate(degrees) }
return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}
And usage:
val rotatedBitmap = bitmap.rotate(90f)
Everything you write in your own stylesheet is overwriting the user agent styles - that's the point of writing your own stylesheet.
As someone else pointed out, the Web Audio API has a better timer.
But in general, if these events happen consistently, how about you put them all on the same timer? I'm thinking about how a step sequencer works.
Practically, could it looks something like this?
var timer = 0;
var limit = 8000; // 8000 will be the point at which the loop repeats
var drumInterval = 8000;
var chordInterval = 1000;
var bassInterval = 500;
setInterval(function {
timer += 500;
if (timer == drumInterval) {
// Do drum stuff
}
if (timer == chordInterval) {
// Do chord stuff
}
if (timer == bassInterval) {
// Do bass stuff
}
// Reset timer once it reaches limit
if (timer == limit) {
timer = 0;
}
}, 500); // Set the timer to the smallest common denominator
import java.util.*;
class ArrayLst
{
public static void main(String args[])
{
ArrayList<String> ar = new ArrayList<String>();
ar.add("pulak");
ar.add("sangeeta");
ar.add("sumit");
System.out.println("Enter the name:");
Scanner scan=new Scanner(System.in);
String st=scan.nextLine();
for(String lst: ar)
{
if(st.contains(lst))
{
System.out.println(st+"is here!");
break;
}
else
{
System.out.println("OOps search can't find!");
break;
}
}
}
}
The short answer: no.
The long answer:
Fixed formats work better for HTML emails. In my experience you're best off pretending it's 1999 when it comes to HTML emails. Be explicit and use HTML attributes (width="650") where ever possible in your table definitions, not CSS (style="width:650px"). Use fixed widths, no percentages. A table width of 650 pixels wide is a safe bet. Use inline CSS to set text properties.
It's not a matter of what works in "HTML emails", but rather the plethora of email clients and their limited (and sometimes deliberately so in the case of Gmail, Hotmail etc) ability to render HTML.
There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.
Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.
import Tkinter as tk
root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")
frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")
root.mainloop()
Still having problems after following the solution provided by codegeek:
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/mainpage.css') }}">
?
In Google Chrome pressing the reload button (F5) will not reload the static files. If you have followed the accepted solution but still don't see the changes you have made to CSS, then press ctrl + shift + R
to ignore cached files and reload the static files.
In Firefox pressing the reload button appears to reload the static files.
In Edge pressing the refresh button does not reload the static file. Pressing ctrl + shift + R
is supposed to ignore cached files and reload the static files. However this does not work on my computer.
This works fine for me:
while True:
answer = input('Do you want to continue?:')
if answer.lower().startswith("y"):
print("ok, carry on then")
elif answer.lower().startswith("n"):
print("sayonara, Robocop")
exit()
edit: use input
in python 3.2 instead of raw_input
var
su : string; // What we want split
si : TStringList; // Result of splitting
Delimiter : string;
...
Delimiter := ';';
si.Text := ReplaceStr(su, Delimiter, #13#10);
Lines in si list will contain splitted strings.
Create a symbolic link to OpenCV. Eg:
cd ~/.virtualenvs/cv/lib/python2.7/site-packages/
ln -s /usr/local/lib/python2.7/dist-packages/cv2.so cv2.so
ln -s /usr/local/lib/python2.7/dist-packages/cv.py cv.py
g.setFont(new Font("TimesRoman", Font.PLAIN, fontSize));
Where fontSize is a int. The API for drawString states that the x and y parameters are coordinates, and have nothing to do with the size of the text.
Yes,u can overload main method but the interpreter will always search for the correct main method syntax to begin the execution.. And yes u have to call the overloaded main method with the help of object.
class Sample{
public void main(int a,int b){
System.out.println("The value of a is " +a);
}
public static void main(String args[]){
System.out.println("We r in main method");
Sample obj=new Sample();
obj.main(5,4);
main(3);
}
public static void main(int c){
System.out.println("The value of c is" +c);
}
}
The output of the program is:
We r in main method
The value of a is 5
The value of c is 3
USE
xhr.onerror = function(e){
if (XMLHttpRequest.readyState == 4) {
// HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
}
else if (XMLHttpRequest.readyState == 0) {
// Network error (i.e. connection refused, access denied due to CORS, etc.)
selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
}
else {
selFoto.erroUploadFoto('Erro desconhecido.');
}
};
(more code below - UPLOAD IMAGE EXAMPLE)
var selFoto = {
foto: null,
upload: function(){
LoadMod.show();
var arquivo = document.frmServico.fileupload.files[0];
var formData = new FormData();
if (arquivo.type.match('image.*')) {
formData.append('upload', arquivo, arquivo.name);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'FotoViewServlet?acao=uploadFoto', true);
xhr.responseType = 'blob';
xhr.onload = function(e){
if (this.status == 200) {
selFoto.foto = this.response;
var url = window.URL || window.webkitURL;
document.frmServico.fotoid.src = url.createObjectURL(this.response);
$('#foto-id').show();
$('#div_upload_foto').hide();
$('#div_master_upload_foto').css('background-color','transparent');
$('#div_master_upload_foto').css('border','0');
Dados.foto = document.frmServico.fotoid;
LoadMod.hide();
}
else{
erroUploadFoto(XMLHttpRequest.statusText);
}
if (XMLHttpRequest.readyState == 4) {
selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
}
else if (XMLHttpRequest.readyState == 0) {
selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
}
};
xhr.onerror = function(e){
if (XMLHttpRequest.readyState == 4) {
// HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
}
else if (XMLHttpRequest.readyState == 0) {
// Network error (i.e. connection refused, access denied due to CORS, etc.)
selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
}
else {
selFoto.erroUploadFoto('Erro desconhecido.');
}
};
xhr.send(formData);
}
else{
selFoto.erroUploadFoto('');
MyCity.mensagens.push('Selecione uma imagem.');
MyCity.showMensagensAlerta();
}
},
erroUploadFoto : function(mensagem) {
selFoto.foto = null;
$('#file-upload').val('');
LoadMod.hide();
MyCity.mensagens.push('Erro ao atualizar a foto. '+mensagem);
MyCity.showMensagensAlerta();
}
};
In my case, I had a repo with:
.json
.lock
In the meantime, A,B,C had newer versions with respect when the lock was generated.
For some reason, I deleted the "vendors" and wanted to do a composer install
and failed with the message:
Warning: The lock file is not up to date with the latest changes in composer.json.
You may be getting outdated dependencies. Run update to update them.
Your requirements could not be resolved to an installable set of packages.
I tried to run the solution from Seldaek issuing a composer update vendorD/libraryD
but composer insisted to update more things, so .lock
had too changes seen my my git tool.
The solution I used was:
vendors
dir.VendorD/LibraryD
from the .json
.composer install
..json
and checkout it again from the repo (equivalent to re-adding the file, but avoiding potential whitespace changes).composer update vendorD/libraryD
It did install the library, but in addition, git
diff showed me that in the .lock
only the new things were added without editing the other ones.
(Thnx Seldaek for the pointer ;) )
you can try fancybox: http://fancyapps.com/fancybox/
you just need load jquery and fancybox.css and fancybox.js :
<!-- Add jquery -->
<script type="text/javascript" src="jquery.min.js"></script>
<!-- Add fancyBox -->
<link rel="stylesheet" href="jquery.fancybox.css" type="text/css" media="screen" />
<script type="text/javascript" src="jquery.fancybox.pack.js"></script>
and add js code in your page:
$("youBtnSelector").click(function() {
$.fancybox.open({
href : 'you html path',
type : 'iframe',
padding : 5
});
})
It is easy to do
If you want to use the distribution Ruby instead of rb-env/rvm, you can set up a GEM_HOME
for your current user. Start by creating a directory to store the Ruby gems for your user:
$ mkdir ~/.ruby
Then update your shell to use that directory for GEM_HOME
and to update your PATH
variable to include the Ruby gem bin directory.
$ echo 'export GEM_HOME=~/.ruby/' >> ~/.bashrc
$ echo 'export PATH="$PATH:~/.ruby/bin"' >> ~/.bashrc
$ source ~/.bashrc
(That last line will reload the environment variables in your current shell.)
Now you should be able to install Ruby gems under your user using the gem
command. I was able to get this working with Ruby 2.5.1 under Ubuntu 18.04. If you are using a shell that is not Bash, then you will need to edit the startup script for that shell instead of bashrc
.
A slightly prettier function based on Ansgar Wiechers's answer. Whether it's actually more useful is a matter of debate.
function Read-Choice(
[Parameter(Mandatory)][string]$Message,
[Parameter(Mandatory)][string[]]$Choices,
[Parameter(Mandatory)][string]$DefaultChoice,
[Parameter()][string]$Question='Are you sure you want to proceed?'
) {
$defaultIndex = $Choices.IndexOf($DefaultChoice)
if ($defaultIndex -lt 0) {
throw "$DefaultChoice not found in choices"
}
$choiceObj = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
foreach($c in $Choices) {
$choiceObj.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList $c))
}
$decision = $Host.UI.PromptForChoice($Message, $Question, $choiceObj, $defaultIndex)
return $Choices[$decision]
}
Example usage:
PS> $r = Read-Choice 'DANGER!!!!!!' '&apple','&blah','&car' '&blah'
DANGER!!!!!!
Are you sure you want to proceed?
[A] apple [B] blah [C] car [?] Help (default is "B"): c
PS> switch($r) { '&car' { Write-host 'caaaaars!!!!' } '&blah' { Write-Host "It's a blah day" } '&apple' { Write-Host "I'd like to eat some apples!" } }
caaaaars!!!!
Installing CocoaPods on OS X 10.11
These instructions were tested on all betas and the final release of El Capitan.
Custom GEM_HOME
This is the solution when you are receiving above error
$ mkdir -p $HOME/Software/ruby
$ export GEM_HOME=$HOME/Software/ruby
$ gem install cocoapods
[...]
1 gem installed
$ export PATH=$PATH:$HOME/Software/ruby/bin
$ pod --version
0.38.2
As discussed here, there really isn't such a thing as an HTTP connection and what httplib refers to as the HTTPConnection is really the underlying TCP connection which doesn't really know much about your requests at all. Requests abstracts that away and you won't ever see it.
The newest version of Requests does in fact keep the TCP connection alive after your request.. If you do want your TCP connections to close, you can just configure the requests to not use keep-alive.
s = requests.session()
s.config['keep_alive'] = False
N.B : IF YOU ARE USING PHPSTORM
I spent an hour trying to solve this problem, thinking that it was my php server problem, So i set 'always_populate_raw_post_data' to '-1' in php.ini and nothing worked.
Until i found out that using phpStorm built in server is what causing the problem as detailed in the answer here : Answer by LazyOne Here , So i thought about sharing it.
This approach will work ONLY when the total duration is less than 24 hours:
var now = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";
moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
// outputs: "00:39:30"
If you have 24 hours or more, the hours will reset to zero with the above approach, so it is not ideal.
If you want to get a valid response for durations of 24 hours or greater, then you'll have to do something like this instead:
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
// outputs: "48:39:30"
Note that I'm using the utc time as a shortcut. You could pull out d.minutes()
and d.seconds()
separately, but you would also have to zeropad them.
This is necessary because the ability to format a duration
objection is not currently in moment.js. It has been requested here. However, there is a third-party plugin called moment-duration-format that is specifically for this purpose:
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = d.format("hh:mm:ss");
// outputs: "48:39:30"
btnSubmit_Click(btnSubmit,EventArgs.Empty);
Is this any help?
#include <stdio.h>
#define MAX 10
int main()
{
char grid[MAX][MAX];
int i,j,row,col;
printf("Please enter your grid size: ");
scanf("%d %d", &row, &col);
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
grid[i][j] = '.';
printf("%c ", grid[i][j]);
}
printf("\n");
}
return 0;
}
I think this is related to the newer version of spring boot plus using spring data JPA just replace @Bean annotation above public LocalContainerEntityManagerFactoryBean entityManagerFactory() to @Bean(name="entityManagerFactory")
Determining the name of bean should solve the issue
The following script ensures that my_finalFunction
runs after your page has been fully loaded with images, stylesheets and external content:
<script>
document.addEventListener("load", my_finalFunction, false);
function my_finalFunction(e) {
/* things to do after all has been loaded */
}
</script>
A good explanation is provided by kirupa on running your code at the right time, see https://www.kirupa.com/html5/running_your_code_at_the_right_time.htm.
final class
can avoid breaking the public API when you add new methods
Suppose that on version 1 of your Base
class you do:
public class Base {}
and a client does:
class Derived extends Base {
public int method() { return 1; }
}
Then if in version 2 you want to add a method
method to Base
:
class Base {
public String method() { return null; }
}
it would break the client code.
If we had used final class Base
instead, the client wouldn't have been able to inherit, and the method addition wouldn't break the API.
Same problem to me and the solution was:
See this github doc to convert remote's URL from https to ssh. To check if remote's URL is ssh or https, use git remote -v. To switch from https to ssh: git remote set-url origin [email protected]:USERNAME/REPOSITORY.git @jeeYem
Make android:hardwareAccelerated="false"
to be activity specific. Hope that, this might solve the problem for freezing as well as animation issues. Like this...
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true">
.
.
.
.
<activity android:name=".NavigationItemsFolder.GridsMenuActivityClasses.WebsiteActivity"
android:windowSoftInputMode="adjustPan"
android:hardwareAccelerated="false"/>
</application>
Yes, you can input multiple items from cin
, using exactly the syntax you describe. The result is essentially identical to:
cin >> a;
cin >> b;
cin >> c;
This is due to a technique called "operator chaining".
Each call to operator>>(istream&, T)
(where T
is some arbitrary type) returns a reference to its first argument. So cin >> a
returns cin
, which can be used as (cin>>a)>>b
and so forth.
Note that each call to operator>>(istream&, T)
first consumes all whitespace characters, then as many characters as is required to satisfy the input operation, up to (but not including) the first next whitespace character, invalid character, or EOF.
I want to contribute an answer here as I too have faced the same issue - we want the $_FILES element available as part of the same post as another form. My answer is based on @mrtnmgs however notes the comments added to that question.
Firstly: Dropzone posts its data via ajax
Just because you use the formData.append
option still means that you must tackle the UX actions - i.e. this all happens behind the scenes and isn't a typical form post. Data is posted to your url
parameter.
Secondly: If you therefore want to mimic a form post you will need to store the posted data
This requires server side code to store your $_POST
or $_FILES
in a session which is available to the user on another page load as the user will not go to the page where the posted data is received.
Thirdly: You need to redirect the user to the page where this data is actioned
Now you have posted your data, stored it in a session, you need to display/action it for the user in an additional page. You need to send the user to that page as well.
So for my example:
[Dropzone code: Uses Jquery]
$('#dropArea').dropzone({
url: base_url+'admin/saveProject',
maxFiles: 1,
uploadMultiple: false,
autoProcessQueue:false,
addRemoveLinks: true,
init: function(){
dzClosure = this;
$('#projectActionBtn').on('click',function(e) {
dzClosure.processQueue(); /* My button isn't a submit */
});
// My project only has 1 file hence not sendingmultiple
dzClosure.on('sending', function(data, xhr, formData) {
$('#add_user input[type="text"],#add_user textarea').each(function(){
formData.append($(this).attr('name'),$(this).val());
})
});
dzClosure.on('complete',function(){
window.location.href = base_url+'admin/saveProject';
})
},
});
This effect is typically achieved by having some jquery logic as follows:
$(window).bind('scroll', function () {
if ($(window).scrollTop() > 50) {
$('.menu').addClass('fixed');
} else {
$('.menu').removeClass('fixed');
}
});
This says once the window has scrolled past a certain number of vertical pixels, it adds a class to the menu that changes it's position value to "fixed".
For complete implementation details see: http://jsfiddle.net/adamb/F4BmP/
You can prefix the function declaration with extern “C” keyword, e.g.
extern “C” int Mycppfunction()
{
// Code goes here
return 0;
}
For more examples you can search more on Google about “extern” keyword. You need to do few more things, but it's not difficult you'll get lots of examples from Google.
You shouldn't for security reasons. Especially if cookies are in play here. It leaves you wide open to cookie-based replay attacks.
Either way, you should use Apache control rules to tune it.
Then you can test for HTTPS being enabled and redirect as-needed where needed.
You should redirect to the pay page only using a FORM POST (no get), and accesses to the page without a POST should be directed back to the other pages. (This will catch the people just hot-jumping.)
http://joseph.randomnetworks.com/archives/2004/07/22/redirect-to-ssl-using-apaches-htaccess/
Is a good place to start, apologies for not providing more. But you really should shove everything through SSL.
It's over-protective, but at least you have less worries.
You can also wrap the output of a cmdlet (or pipeline) in @()
to ensure that what you get back is an array rather than a single item.
For instance, dir usually returns a list, but depending on the options, it might return a single object. If you are planning on iterating through the results with a foreach-object, you need to make sure you get a list back. Here's a contrived example:
$results = @( dir c:\autoexec.bat)
One more thing... an empty array (like to initialize a variable) is denoted @()
.
I noticed that when it's set to false, I'm able to see the value of an item using the debugger. When it was set to true, I was getting an error - item.FullName.GetValue The embedded interop type 'FullName' does not contain a definition for 'QBFC11Lib.IItemInventoryRet' since it was not used in the compiled assembly. Consider casting to object or changing the 'Embed Interop Types' property to true.
Solved in easy way: You should create a new emulator, before opening it for the first time follow these 3 easy steps:
1- go to "C:\Users[user].android\avd[your virtual device folder]" open "config.ini" with text editor like notepad
2- change
"PlayStore.enabled=false" to "PlayStore.enabled=true"
3- change
"mage.sysdir.1 = system-images\android-30\google_apis\x86"
to
"image.sysdir.1 = system-images\android-30\google_apis_playstore\x86"
As per the javadoc of NotEmpty, Integer is not a valid type for it to check. It's for Strings and collections. If you just want to make sure an Integer has some value, javax.validation.constraints.NotNull
is all you need.
public @interface NotEmpty
Asserts that the annotated string, collection, map or array is not null or empty.
Sorry for reponening this old question, for Java 8+ I think the best solution is the one provided by Elliott Frisch (Stream.of("str1", "str2", "str3").anyMatches(str::equalsIgnoreCase)
) but it seems like it's missing one of the simplest solution for eldest version of Java:
if(Arrays.asList("val1", "val2", "val3", ..., "val_n").contains(str.toLowerCase())){
...
}
You could apply some error prevenction by checking the non-nullity of variable str
, and by caching the list once created, using ArrayList to speed up searches for long lists:
// List of lower-case possibilities
List<String> list = new ArrayList<>(Arrays.asList("val1", "val2", "val3", ..., "val_n"));
if(str != null && list.contains(str.toLowerCase())){
}
I've been using:
new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffaacc"));
You can use -i''
(--in-place
) for sed
as already suggested. See: The -i
in-place argument, however note that -i
option is non-standard FreeBSD extensions and may not be available on other operating systems. Secondly sed
is a Stream EDitor, not a file editor.
Alternative way is to use built-in substitution in Vim Ex mode, like:
$ ex +%s/foo/bar/g -scwq file.txt
and for multiple-files:
$ ex +'bufdo!%s/foo/bar/g' -scxa *.*
To edit all files recursively you can use **/*.*
if shell supports that (enable by shopt -s globstar
).
Another way is to use gawk
and its new "inplace" extension such as:
$ gawk -i inplace '{ gsub(/foo/, "bar") }; { print }' file1
I had that problem too.
Try using Server.Transfer
instead of Response.Redirect
Worked for me.
If you are trying something similar like source <( curl -sS $url )
and getting the (23) Failed writing body
error, it is because sourcing a process substitution doesn't work in bash 3.2
(the default for macOS).
Instead, you can use this workaround.
source /dev/stdin <<<"$( curl -sS $url )"
use sep='\s*,\s*'
so that you will take care of spaces in column-names:
transactions = pd.read_csv('transactions.csv', sep=r'\s*,\s*',
header=0, encoding='ascii', engine='python')
alternatively you can make sure that you don't have unquoted spaces in your CSV file and use your command (unchanged)
prove:
print(transactions.columns.tolist())
Output:
['product_id', 'customer_id', 'store_id', 'promotion_id', 'month_of_year', 'quarter', 'the_year', 'store_sales', 'store_cost', 'unit_sales', 'fact_count']
Let's use the built in SqlDateTime class
new SqlDateTime(DateTime.Now).ToSqlString()
But still need to check for null values. This will throw overflow exception
new SqlDateTime(DateTime.MinValue).ToSqlString()
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
The accepted answer has some holes in it. The beauty of the SparseArray is that it allows gaps in the indeces. So, we could have two maps like so, in a SparseArray...
(0,true)
(250,true)
Notice the size here would be 2. If we iterate over size, we will only get values for the values mapped to index 0 and index 1. So the mapping with a key of 250 is not accessed.
for(int i = 0; i < sparseArray.size(); i++) {
int key = sparseArray.keyAt(i);
// get the object by the key.
Object obj = sparseArray.get(key);
}
The best way to do this is to iterate over the size of your data set, then check those indeces with a get() on the array. Here is an example with an adapter where I am allowing batch delete of items.
for (int index = 0; index < mAdapter.getItemCount(); index++) {
if (toDelete.get(index) == true) {
long idOfItemToDelete = (allItems.get(index).getId());
mDbManager.markItemForDeletion(idOfItemToDelete);
}
}
I think ideally the SparseArray family would have a getKeys() method, but alas it does not.
if you wish to using dplyr, for to remove row "Foo":
df %>%
filter(!C=="Foo")
Default behaviour of PowerShell is just to dump everything that falls out of a pipeline without being picked up by another pipeline element or being assigned to a variable (or redirected) into Out-Host
. What Out-Host
does is obviously host-dependent.
Just letting things fall out of the pipeline is not a substitute for Write-Host
which exists for the sole reason of outputting text in the host application.
If you want output, then use the Write-*
cmdlets. If you want return values from a function, then just dump the objects there without any cmdlet.
You will need to link to the file relative to the file that includes eventManager.php
(Page A)
Change your code from
require_once('../includes/dbconn.inc');
To
require_once('../mysite/php/includes/dbconn.inc');
This is in no way specific to std::unique_ptr
, but applies to any class that is movable. It's guaranteed by the language rules since you are returning by value. The compiler tries to elide copies, invokes a move constructor if it can't remove copies, calls a copy constructor if it can't move, and fails to compile if it can't copy.
If you had a function that accepts std::unique_ptr
as an argument you wouldn't be able to pass p to it. You would have to explicitly invoke move constructor, but in this case you shouldn't use variable p after the call to bar()
.
void bar(std::unique_ptr<int> p)
{
// ...
}
int main()
{
unique_ptr<int> p = foo();
bar(p); // error, can't implicitly invoke move constructor on lvalue
bar(std::move(p)); // OK but don't use p afterwards
return 0;
}
You could join the table against itself:
select
t.jobId, t.jobName,
count(p1.jobId) as Priority1,
count(p2.jobId) as Priority2,
count(p3.jobId) as Priority3,
count(p4.jobId) as Priority4,
count(p5.jobId) as Priority5
from
theTable t
left join theTable p1 on p1.jobId = t.jobId and p1.jobName = t.jobName and p1.Priority = 1
left join theTable p2 on p2.jobId = t.jobId and p2.jobName = t.jobName and p2.Priority = 2
left join theTable p3 on p3.jobId = t.jobId and p3.jobName = t.jobName and p3.Priority = 3
left join theTable p4 on p4.jobId = t.jobId and p4.jobName = t.jobName and p4.Priority = 4
left join theTable p5 on p5.jobId = t.jobId and p5.jobName = t.jobName and p5.Priority = 5
group by
t.jobId, t.jobName
Or you could use case inside a sum:
select
jobId, jobName,
sum(case Priority when 1 then 1 else 0 end) as Priority1,
sum(case Priority when 2 then 1 else 0 end) as Priority2,
sum(case Priority when 3 then 1 else 0 end) as Priority3,
sum(case Priority when 4 then 1 else 0 end) as Priority4,
sum(case Priority when 5 then 1 else 0 end) as Priority5
from
theTable
group by
jobId, jobName
I think the real answer is http://www.w3schools.com/HTML/default.asp.
Use .length
to count number of characters, and $.trim()
function to remove spaces, and replace(/ /g,'')
to replace multiple spaces with just one. Here is an example:
var str = " Hel lo ";
console.log(str.length);
console.log($.trim(str).length);
console.log(str.replace(/ /g,'').length);
Output:
20
7
5
Source: How to count number of characters in a string with JQuery
Try this fiddle
$(function() {
$('#datepicker').datepicker({
dateFormat: 'yy-dd-mm',
onSelect: function(datetext) {
var d = new Date(); // for now
var h = d.getHours();
h = (h < 10) ? ("0" + h) : h ;
var m = d.getMinutes();
m = (m < 10) ? ("0" + m) : m ;
var s = d.getSeconds();
s = (s < 10) ? ("0" + s) : s ;
datetext = datetext + " " + h + ":" + m + ":" + s;
$('#datepicker').val(datetext);
}
});
});
You can follow these tutorials to get started
Tutorials
Hello World Web Server (paid)
Node JS Processing Model – Single Threaded Model with Event Loop Architecture
Developer Sites
Videos
Screencasts
Books
Courses
Blogs
Podcasts
JavaScript resources
Node.js Modules
Other
start "" AcroRd32.exe /A "page=207" "C:\Users\abc\Desktop\abc xyz def\abc def xyz 2015.pdf"
You may try this, I did it finally, it works!
For what you want I would've used
app.get('/fruit/:fruitName&:fruitColor', function(request, response) {
const name = request.params.fruitName
const color = request.params.fruitColor
});
or better yet
app.get('/fruit/:fruit', function(request, response) {
const fruit = request.params.fruit
console.log(fruit)
});
where fruit is a object. So in the client app you just call
https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"}
and as a response you should see:
// client side response
// { name: My fruit name, color:The color of the fruit}
I think you wanted to do this:
while( $row = mysql_fetch_assoc( $result)){
$new_array[] = $row; // Inside while loop
}
Or maybe store id as key too
$new_array[ $row['id']] = $row;
Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5]
.
Well, after long research, i found a workaround that does what i need: http://jsfiddle.net/CqB3d/25/
CSS:
body{
margin: 0;
padding: 0;
border: 0;
overflow: hidden;
height: 100%;
max-height: 100%;
}
#caixa{
width: 800px;
margin-left: auto;
margin-right: auto;
}
#framecontentTop, #framecontentBottom{
position: absolute;
top: 0;
width: 800px;
height: 100px; /*Height of top frame div*/
overflow: hidden; /*Disable scrollbars. Set to "scroll" to enable*/
background-color: navy;
color: white;
}
#framecontentBottom{
top: auto;
bottom: 0;
height: 110px; /*Height of bottom frame div*/
overflow: hidden; /*Disable scrollbars. Set to "scroll" to enable*/
background-color: navy;
color: white;
}
#maincontent{
position: fixed;
top: 100px; /*Set top value to HeightOfTopFrameDiv*/
margin-left:auto;
margin-right: auto;
bottom: 110px; /*Set bottom value to HeightOfBottomFrameDiv*/
overflow: auto;
background: #fff;
width: 800px;
}
.innertube{
margin: 15px; /*Margins for inner DIV inside each DIV (to provide padding)*/
}
* html body{ /*IE6 hack*/
padding: 130px 0 110px 0; /*Set value to (HeightOfTopFrameDiv 0 HeightOfBottomFrameDiv 0)*/
}
* html #maincontent{ /*IE6 hack*/
height: 100%;
width: 800px;
}
HTML:
<div id="framecontentBottom">
<div class="innertube">
<h3>Sample text here</h3>
</div>
</div>
<div id="maincontent">
<div class="innertube">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed scelerisque, ligula hendrerit euismod auctor, diam nunc sollicitudin nibh, id luctus eros nibh porta tellus. Phasellus sed suscipit dolor. Quisque at mi dolor, eu fermentum turpis. Nunc posuere venenatis est, in sagittis nulla consectetur eget... //much longer text...
</div>
</div>
might not work with the horizontal thingy yet, but, it's a work in progress!
I basically dropped the "inception" boxes-inside-boxes-inside-boxes model and used fixed positioning with dynamic height and overflow properties.
Hope this might help whoever finds the question later!
EDIT: This is the final answer.
Edge (as opposed to IE11) has a better UI for Local storage / Session storage and cookies:
Add a style with the attribute text-decoration:none;
:
There are a number of different ways of doing this.
Inline style:
<a href="xxx.html" style="text-decoration:none;">goto this link</a>
Inline stylesheet:
<html>
<head>
<style type="text/css">
a {
text-decoration:none;
}
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
External stylesheet:
<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
stylesheet.css:
a {
text-decoration:none;
}
easiest way is
${string:position:length}
Where this extracts $length
substring from $string
at $position
.
This is a bash builtin so awk or sed is not required.
If you are having a code structure of something like:
SELECT 151
RETURN -151
Then use:
SELECT 151
ROLLBACK
RETURN -151
You need to make sure that the Self Signed Certificate uses the correct common name
for the domain you are setting up. If you are going to use the same certificate for multiple domains you need to either have a unique certificate for each domain, or if all of your ssl sites are subdomains of a common domain, then you can generate a certificate with a wildcard domain like *.domainname.tld
.
If you don't set up your common name
correctly in your self signed certificate then Chrome and Firefox may work, but IE might not be able to find the certificate when you load the site each time. In IE it will appear like you have added the site's cert but in fact on page load it will never be found.
how to set up SSL for Apache for a Mac so I can test Cross Domain iFrame on IE8
I wanted to display the first 300 words of a news story as a preview which unfortunately meant that if a story had an image within the first 300 words then it was displayed in the list of previews which really messed with my layout. I used the above code to hide all of the images from the string taken from my database and it works wonderfully!
$news = $row_latest_news ['content'];
$news = preg_replace("/<img[^>]+\>/i", "", $news);
if (strlen($news) > 300){
echo substr($news, 0, strpos($news,' ',300)).'...';
}
else {
echo $news;
}
To set the credentials for the entire day that is 24 hours.
git config --global credential.helper 'cache --timeout 86400'
Else for 1 hour replace the 86400 secs to 3600.
OR
all configuration options for the 'cache' authentication helper:
git help credential-cache
This was my solution. Hope my confusion can help someone else too:
My "Developer Options" was ON,
but the "USB Debbugging" was OFF.
So I turned ON the USB Debbugging and the problem was solved.
This is almost 3 times faster than explode()
, array_map()
and intval()
:
$integerIDs = json_decode('[' . $string . ']', true);
Casting in Java isn't magic, it's you telling the compiler that an Object of type A is actually of more specific type B, and thus gaining access to all the methods on B that you wouldn't have had otherwise. You're not performing any kind of magic or conversion when performing casting, you're essentially telling the compiler "trust me, I know what I'm doing and I can guarantee you that this Object at this line is actually an <Insert cast type here>." For example:
Object o = "str";
String str = (String)o;
The above is fine, not magic and all well. The object being stored in o is actually a string, and therefore we can cast to a string without any problems.
There's two ways this could go wrong. Firstly, if you're casting between two types in completely different inheritance hierarchies then the compiler will know you're being silly and stop you:
String o = "str";
Integer str = (Integer)o; //Compilation fails here
Secondly, if they're in the same hierarchy but still an invalid cast then a ClassCastException
will be thrown at runtime:
Number o = new Integer(5);
Double n = (Double)o; //ClassCastException thrown here
This essentially means that you've violated the compiler's trust. You've told it you can guarantee the object is of a particular type, and it's not.
Why do you need casting? Well, to start with you only need it when going from a more general type to a more specific type. For instance, Integer
inherits from Number
, so if you want to store an Integer
as a Number
then that's ok (since all Integers are Numbers.) However, if you want to go the other way round you need a cast - not all Numbers are Integers (as well as Integer we have Double
, Float
, Byte
, Long
, etc.) And even if there's just one subclass in your project or the JDK, someone could easily create another and distribute that, so you've no guarantee even if you think it's a single, obvious choice!
Regarding use for casting, you still see the need for it in some libraries. Pre Java-5 it was used heavily in collections and various other classes, since all collections worked on adding objects and then casting the result that you got back out the collection. However, with the advent of generics much of the use for casting has gone away - it has been replaced by generics which provide a much safer alternative, without the potential for ClassCastExceptions (in fact if you use generics cleanly and it compiles with no warnings, you have a guarantee that you'll never get a ClassCastException.)
From the root shell (e.g. adb shell), you can lock with:
echo mylockname >/sys/power/wake_lock
After which the device will stay awake, until you do:
echo mylockname >/sys/power/wake_unlock
With the same string for 'mylockname'.
Note that this will not prevent the screen from going black, but it will prevent the CPU from sleeping.
Note that /sys/power/wake_lock is read-write for user radio (1001) and group system (1000), and, of course, root.
A reference is here: http://lwn.net/Articles/479841/
#!/bin/bash
kernel="2.6.39";
distro="xyz";
cat > /etc/myconfig.conf << EOL
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4
line ...
EOL
this does what you want.
Another native solution (in coffee):
el = document.getElementsByTagName 'b'
docFrag = document.createDocumentFragment()
docFrag.appendChild el.firstChild while el.childNodes.length
el.parentNode.replaceChild docFrag, el
I don't know if it's faster than user113716's solution, but it might be easier to understand for some.
It might be possible to do this with box-shadow
however, I can't get it to actually apply to an image. Only on solid color backgrounds
body {_x000D_
background: #131418;_x000D_
color: #999;_x000D_
text-align: center;_x000D_
}_x000D_
.mycooldiv {_x000D_
width: 400px;_x000D_
height: 300px;_x000D_
margin: 2% auto;_x000D_
border-radius: 100%;_x000D_
}_x000D_
.red {_x000D_
background: red_x000D_
}_x000D_
.blue {_x000D_
background: blue_x000D_
}_x000D_
.yellow {_x000D_
background: yellow_x000D_
}_x000D_
.green {_x000D_
background: green_x000D_
}_x000D_
#darken {_x000D_
box-shadow: inset 0px 0px 400px 110px rgba(0, 0, 0, .7);_x000D_
/*darkness level control - change the alpha value for the color for darken/ligheter effect */_x000D_
}
_x000D_
Red_x000D_
<div class="mycooldiv red"></div>_x000D_
Darkened Red_x000D_
<div class="mycooldiv red" id="darken"></div>_x000D_
Blue_x000D_
<div class="mycooldiv blue"></div>_x000D_
Darkened Blue_x000D_
<div class="mycooldiv blue" id="darken"></div>_x000D_
Yellow_x000D_
<div class="mycooldiv yellow"></div>_x000D_
Darkened Yellow_x000D_
<div class="mycooldiv yellow" id="darken"></div>_x000D_
Green_x000D_
<div class="mycooldiv green"></div>_x000D_
Darkened Green_x000D_
<div class="mycooldiv green" id="darken"></div>
_x000D_
From that error, I would say that your code is fine, at least the part that calls the webservice. The error seems to be in the actual web service.
To get the error from the web server, add a try catch and catch a WebException. A WebException has a property called Response which is a HttpResponse. you can then log anything that is returned, and upload you code. Check back later in the logs and see what is actually being returned.
No, which is why so many other libraries have their own copy :)
I have a script that drops in the iframe with it's content. It also makes sure that iFrameResizer exists (it injects it as a script) and then does the resizing.
I'll drop in a simplified example below.
// /js/embed-iframe-content.js
(function(){
// Note the id, we need to set this correctly on the script tag responsible for
// requesting this file.
var me = document.getElementById('my-iframe-content-loader-script-tag');
function loadIFrame() {
var ifrm = document.createElement('iframe');
ifrm.id = 'my-iframe-identifier';
ifrm.setAttribute('src', 'http://www.google.com');
ifrm.style.width = '100%';
ifrm.style.border = 0;
// we initially hide the iframe to avoid seeing the iframe resizing
ifrm.style.opacity = 0;
ifrm.onload = function () {
// this will resize our iframe
iFrameResize({ log: true }, '#my-iframe-identifier');
// make our iframe visible
ifrm.style.opacity = 1;
};
me.insertAdjacentElement('afterend', ifrm);
}
if (!window.iFrameResize) {
// We first need to ensure we inject the js required to resize our iframe.
var resizerScriptTag = document.createElement('script');
resizerScriptTag.type = 'text/javascript';
// IMPORTANT: insert the script tag before attaching the onload and setting the src.
me.insertAdjacentElement('afterend', ifrm);
// IMPORTANT: attach the onload before setting the src.
resizerScriptTag.onload = loadIFrame;
// This a CDN resource to get the iFrameResizer code.
// NOTE: You must have the below "coupled" script hosted by the content that
// is loaded within the iframe:
// https://unpkg.com/[email protected]/js/iframeResizer.contentWindow.min.js
resizerScriptTag.src = 'https://unpkg.com/[email protected]/js/iframeResizer.min.js';
} else {
// Cool, the iFrameResizer exists so we can just load our iframe.
loadIFrame();
}
}())
Then the iframe content can be injected anywhere within another page/site by using the script like so:
<script
id="my-iframe-content-loader-script-tag"
type="text/javascript"
src="/js/embed-iframe-content.js"
></script>
The iframe content will be injected below wherever you place the script tag.
Hope this is helpful to someone.
this can be solved under MacOS X by installing pyqt with brew
brew install pyqt
With Matlab 2014b python libraries can be called directly from matlab. A prefix py.
is added to all packet names:
>> wrapped = py.textwrap.wrap("example")
wrapped =
Python list with no properties.
['example']
How are you!
#include <iostream>
#include <iomanip>
unsigned char buf0[] = {4, 85, 250, 206};
for (int i = 0;i < sizeof buf0 / sizeof buf0[0]; i++) {
std::cout << std::setfill('0')
<< std::setw(2)
<< std::uppercase
<< std::hex << (0xFF & buf0[i]) << " ";
}
Search based solutions (*, /...) move cursor, which may be unfortunate.
An alternative is to use enhanced mark.vim plugin, then complete your .vimrc
to let double-click trigger highlighting (I don't know how a keyboard selection may trigger a command) :
"Use Mark plugin to highlight selected word
map <2-leftmouse> \m
It allows multiple highlightings, persistence, etc.
To remove highlighting, either :
:Mark
(switch off until next selection):MarkClear
There is a point to only put commands and options in variables.
#! /bin/bash
if [ $# -ne 2 ]
then
echo "Usage: `basename $0` DIRECTORY BACKUP_DIRECTORY"
exit 1
fi
. standard_tools
directory=$1
backup_directory=$2
current_date=$(date +%Y-%m-%dT%H-%M-%S)
backup_file="${backup_directory}/${current_date}.backup"
${tar_create} "${directory}" | ${openssl} | ${split_1024} "$backup_file"
You can relocate the commands to another file you source, so you can reuse the same commands and options across many scripts. This is very handy when you have a lot of scripts and you want to control how they all use tools. So standard_tools would contain:
export tar_create="tar cv"
export openssl="openssl des3 -salt"
export split_1024="split -b 1024m -"
I can't comment directly in the thread since I don't have the requisite reputation yet, but the author asked the following:
the only issue is that the background is white but the clock, wireless and other text and icons are also in white .. I am not sure why!!
For anyone else who comes to this thread, here's what worked for me. The text color of the status bar is decided by the Brightness constant in flutter/material.dart
. To change this, adjust the SystemChrome
solution like so to configure the text:
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Colors.red,
statusBarBrightness: Brightness.dark,
));
Your possible values for Brightness
are Brightness.dark
and Brightness.light
.
Documentation: https://api.flutter.dev/flutter/dart-ui/Brightness-class.html https://api.flutter.dev/flutter/services/SystemUiOverlayStyle-class.html
In case using AWS-SKD for ruby V2.
s3.list_objects(bucket: bucket_name, prefix: "foo/").contents.each do |obj|
next if obj.key == "foo/"
resp = s3.delete_object({
bucket: bucket_name,
key: obj.key,
})
end
attention please, all "foo/*" under bucket will delete.
I wrote a method for this sometime back. It deletes the specified directory and returns true if the directory deletion was successful.
/**
* Delets a dir recursively deleting anything inside it.
* @param dir The dir to delete
* @return true if the dir was successfully deleted
*/
public static boolean deleteDirectory(File dir) {
if(! dir.exists() || !dir.isDirectory()) {
return false;
}
String[] files = dir.list();
for(int i = 0, len = files.length; i < len; i++) {
File f = new File(dir, files[i]);
if(f.isDirectory()) {
deleteDirectory(f);
}else {
f.delete();
}
}
return dir.delete();
}
please try to do
make clean
(instead of make
), then
make
again.
You can use jQuery serialize function along with get/post as follows:
$.get('server.php?' + $('#theForm').serialize())
$.post('server.php', $('#theform').serialize())
jQuery Serialize Documentation: http://api.jquery.com/serialize/
Simple AJAX submit using jQuery:
// this is the id of the submit button
$("#submitButtonId").click(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
You can add the plugins as suggested by @Vikramaditya. Then to generate the production build. You have to run the the command
NODE_ENV=production webpack --config ./webpack.production.config.js
If using babel
, you will also need to prefix BABEL_ENV=node
to the above command.
Use codecs module's open() to read file:
import codecs
with codecs.open(file_name, 'r', encoding='utf-8', errors='ignore') as fdata:
Others have answered re: time.time()
vs. time.clock()
.
However, if you're timing the execution of a block of code for benchmarking/profiling purposes, you should take a look at the timeit
module.
For reading REST data, at least OData Consider Microsoft Power Query. You won't be able to write data. However, you can read data very well.
If you look at the documentation for str.split
:
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].
In other words, if you're trying to figure out what to pass to split
to get '\n\tName: Jane Smith'
to ['Name:', 'Jane', 'Smith']
, just pass nothing (or None).
This almost solves your whole problem. There are two parts left.
First, you've only got two fields, the second of which can contain spaces. So, you only want one split, not as many as possible. So:
s.split(None, 1)
Next, you've still got those pesky colons. But you don't need to split on them. At least given the data you've shown us, the colon always appears at the end of the first field, with no space before and always space after, so you can just remove it:
key, value = s.split(None, 1)
key = key[:-1]
There are a million other ways to do this, of course; this is just the one that seems closest to what you were already trying.
Try using now.date()
to get a Date
object rather than a DateTime
.
If that doesn't work, then converting that to a string should work:
now = datetime.datetime(2009,5,5)
str_now = now.date().isoformat()
cursor.execute('INSERT INTO table (name, id, datecolumn) VALUES (%s,%s,%s)', ('name',4,str_now))
I think Sasxa accepted answer works for most people. However, I had a situation, where the content of the Element, that should listen to off-click events, changed dynamically. So the Elements nativeElement did not contain the event.target, when it was created dynamically. I could solve this with the following directive
@Directive({
selector: '[myOffClick]'
})
export class MyOffClickDirective {
@Output() offClick = new EventEmitter();
constructor(private _elementRef: ElementRef) {
}
@HostListener('document:click', ['$event.path'])
public onGlobalClick(targetElementPath: Array<any>) {
let elementRefInPath = targetElementPath.find(e => e === this._elementRef.nativeElement);
if (!elementRefInPath) {
this.offClick.emit(null);
}
}
}
Instead of checking if elementRef contains event.target, I check if elementRef is in the path (DOM path to target) of the event. That way it is possible to handle dynamically created Elements.
You can use hibernate lazy initializer.
Below is the code you can refer.
Here PPIDO
is the data object which I want to retrieve
Hibernate.initialize(ppiDO);
if (ppiDO instanceof HibernateProxy) {
ppiDO = (PolicyProductInsuredDO) ((HibernateProxy) ppiDO).getHibernateLazyInitializer()
.getImplementation();
ppiDO.setParentGuidObj(policyDO.getBasePlan());
saveppiDO.add(ppiDO);
proxyFl = true;
}
For me the solution was in setting the global variable path to the JDK. See here: https://appopus.wordpress.com/2012/07/11/how-to-install-jdk-java-development-kit-and-jarsigner-on-windows/
This is to merge selected columns from two tables.
If table_1
contains t1_a,t1_b,t1_c..,id,..t1_z
columns,
and table_2
contains t2_a, t2_b, t2_c..., id,..t2_z
columns,
and only t1_a, id, t2_a are required in the final table, then
mergedCSV = table_1[['t1_a','id']].merge(table_2[['t2_a','id']], on = 'id',how = 'left')
# save resulting output file
mergedCSV.to_csv('output.csv',index = False)
To concatenate strings, use the +
operator.
To insert data into a URI, encode it for URIs.
Bad:
var url = "http://localhost:8080/login?cid='username'&pwd='password'"
Good:
var url_safe_username = encodeURIComponent(username);
var url_safe_password = encodeURIComponent(password);
var url = "http://localhost:8080/login?cid=" + url_safe_username + "&pwd=" + url_safe_password;
The server will have to process the query string to make use of the data. You can't assign to arbitrary form fields.
… but don't trigger new windows or pass credentials in the URI (where they are exposed to over the shoulder attacks and may be logged).
I came across this appender here that does what you want, it can be configured to keep a specific number of files that have been rolled over by date.
Download: http://www.simonsite.org.uk/download.htm
Example (groovy):
new TimeAndSizeRollingAppender(name: 'timeAndSizeRollingAppender',
file: 'logs/app.log', datePattern: '.yyyy-MM-dd',
maxRollFileCount: 7, compressionAlgorithm: 'GZ',
compressionMinQueueSize: 2,
layout: pattern(conversionPattern: "%d [%t] %-5p %c{2} %x - %m%n"))
You have to fetch that one record, it will contain the result of Count()
$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];
Other regex answers in this page will accept an IP with a number over 255.
This regex will avoid this problem:
import re
def validate_ip(ip_str):
reg = r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
if re.match(reg, ip_str):
return True
else:
return False
Floating will result in wrapping if space is not available.
You can use display:inline
and white-space:nowrap
to achieve this. Fiddle
<div id="container" style="white-space:nowrap">
<div id="image" style="display:inline;">
<img src="tree.png"/>
</div>
<div id="texts" style="display:inline; white-space:nowrap;">
A very long text(about 300 words)
</div>
</div>?
Two entries in an array can't share a key, you'll need to change the key for the duplicate
Just put the pixel padding into the image - add 10px or whatever to the canvas size of the image in photohop and align it right in CSS.
Using the awesome psutil
library it's pretty simple:
p = psutil.Process(pid)
p.terminate() #or p.kill()
If you don't want to install a new library, you can use the os
module:
import os
import signal
os.kill(pid, signal.SIGTERM) #or signal.SIGKILL
See also the os.kill
documentation.
If you are interested in starting the command python StripCore.py
if it is not running, and killing it otherwise, you can use psutil
to do this reliably.
Something like:
import psutil
from subprocess import Popen
for process in psutil.process_iter():
if process.cmdline() == ['python', 'StripCore.py']:
print('Process found. Terminating it.')
process.terminate()
break
else:
print('Process not found: starting it.')
Popen(['python', 'StripCore.py'])
Sample run:
$python test_strip.py #test_strip.py contains the code above
Process not found: starting it.
$python test_strip.py
Process found. Terminating it.
$python test_strip.py
Process not found: starting it.
$killall python
$python test_strip.py
Process not found: starting it.
$python test_strip.py
Process found. Terminating it.
$python test_strip.py
Process not found: starting it.
Note: In previous psutil
versions cmdline
was an attribute instead of a method.
The Robot class will work much more efficiently than sending the keys through Selenium sendkeys. Please try:
Example:
Robot rb = new Robot();
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_A);
To use the above Robot class, you need to import java.awt.Robot;
'.
I encounter this problem because I did kill task to "Oracle" task in the Task Manager.
To fix it you need to open the cmd -> type: services.msc
-> the window with all services will open -> find service "OracleServiceXE
" -> right click: start.
For O(1) random access, which can not be beaten.
You need to do it directly on a server. But a better way is using PHP. I have heard that PHP has a special code that can send e-mail directly without opening the mail client.
If you want device ID information use TelephonyManager. Here is the link for that :
http://facinatingandroid.blogspot.in/2011/09/android-device-information.html
and also check this :
http://sree.cc/google/android/reading-phone-device-details-in-android
As the OP references Number of commits on branch in git I want to add that the given answers there also work with any other branch, at least since git version 2.17.1 (and seemingly more reliably than the answer by Peter van der Does):
working correctly:
git checkout current-development-branch
git rev-list --no-merges --count master..
62
git checkout -b testbranch_2
git rev-list --no-merges --count current-development-branch..
0
The last command gives zero commits as expected since I just created the branch. The command before gives me the real number of commits on my development-branch minus the merge-commit(s)
not working correctly:
git checkout current-development-branch
git rev-list --no-merges --count HEAD
361
git checkout -b testbranch_1
git rev-list --no-merges --count HEAD
361
In both cases I get the number of all commits in the development branch and master from which the branches (indirectly) descend.
Curl gives this error when there is no reply from a server, since it is an error for HTTP not to respond anything to a request.
I suspect the problem you have is that there is some piece of network infrastructure, like a firewall or a proxy, between you and the host in question. Getting this to work, therefore, will require you to discuss the issue with the people responsible for that hardware.
Best way to implement the selector is by using the xml instead of using programatic way as its more easy to implemnt with xml.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_bg_selected" android:state_selected="true"></item>
<item android:drawable="@drawable/button_bg_pressed" android:state_pressed="true"></item>
<item android:drawable="@drawable/button_bg_normal"></item>
</selector>
For more information i implemented using this link http://www.blazin.in/2016/03/how-to-use-selectors-for-botton.html
Yet another recursive directory tree archiving, implemented as an extension to ZipArchive. As a bonus, a single-statement tree compression helper function is included. Optional localname is supported, as in other ZipArchive functions. Error handling code to be added...
class ExtendedZip extends ZipArchive {
// Member function to add a whole file system subtree to the archive
public function addTree($dirname, $localname = '') {
if ($localname)
$this->addEmptyDir($localname);
$this->_addTree($dirname, $localname);
}
// Internal function, to recurse
protected function _addTree($dirname, $localname) {
$dir = opendir($dirname);
while ($filename = readdir($dir)) {
// Discard . and ..
if ($filename == '.' || $filename == '..')
continue;
// Proceed according to type
$path = $dirname . '/' . $filename;
$localpath = $localname ? ($localname . '/' . $filename) : $filename;
if (is_dir($path)) {
// Directory: add & recurse
$this->addEmptyDir($localpath);
$this->_addTree($path, $localpath);
}
else if (is_file($path)) {
// File: just add
$this->addFile($path, $localpath);
}
}
closedir($dir);
}
// Helper function
public static function zipTree($dirname, $zipFilename, $flags = 0, $localname = '') {
$zip = new self();
$zip->open($zipFilename, $flags);
$zip->addTree($dirname, $localname);
$zip->close();
}
}
// Example
ExtendedZip::zipTree('/foo/bar', '/tmp/archive.zip', ZipArchive::CREATE);
Use the basename
method of the path
module:
var path = require('path');
var filename = path.basename(__filename);
console.log(filename);
Here is the documentation the above example is taken from.
As Dan pointed out, Node is working on ECMAScript modules with the "--experimental-modules" flag. Node 12 still supports __dirname
and __filename
as above.
If you are using the --experimental-modules
flag, there is an alternative approach.
The alternative is to get the path to the current ES module:
const __filename = new URL(import.meta.url).pathname;
And for the directory containing the current module:
import path from 'path';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
Assuming Customer
has a setter for email - myList.get(3).setEmail("[email protected]")
If working with Basic4Android and looking for an easy fix to the problem, try this it works both Google maps and Openstreet even though OSM creates a bit of a messy result and thanx to [yndolok] for the google marker
GooglemLoc="https://www.google.com/maps/place/"&[Latitude]&"+"&[Longitude]&"/@"&[Latitude]&","&[Longitude]&",15z"
GooglemRute="https://www.google.co.ls/maps/dir/"&[FrmLatt]&","&[FrmLong]&"/"&[ToLatt]&","&[FrmLong]&"/@"&[ScreenX]&","&[ScreenY]&",14z/data=!3m1!4b1!4m2!4m1!3e0?hl=en" 'route ?hl=en
OpenStreetLoc="https://www.openstreetmap.org/#map=16/"&[Latitude]&"/"&[Longitude]&"&layers=N"
OpenStreetRute="https://www.openstreetmap.org/directions?engine=osrm_car&route="&[FrmLatt]&"%2C"&[FrmLong]&"%3B"&[ToLatt]&"%2C"&[ToLong]&"#Map=15/"&[ScreenX]&"/"&[Screeny]&"&layers=N"
import java.util.*;
public class ScannerExample {
public static void main(String args[]) {
int a;
String s;
Scanner scan = new Scanner(System.in);
System.out.println("enter a no");
a = scan.nextInt();
System.out.println("no is =" + a);
System.out.println("enter a string");
s = scan.next();
System.out.println("string is=" + s);
}
}
Sails.js structure looks nice and clean to me, so I use MVC style structure for my express projects, similar to sails.js.
project_root
|
|_ _ app
|_ _ |_ _ controllers
|_ _ |_ _ |_ _ UserController.js
|_ _ |_ _ middlewares
|_ _ |_ _ |_ _ error.js
|_ _ |_ _ |_ _ logger.js
|_ _ |_ _ models
|_ _ |_ _ |_ _ User.js
|_ _ |_ _ services
|_ _ |_ _ |_ _ DatabaseService.js
|
|_ _ config
|_ _ |_ _ constants.js
|_ _ |_ _ index.js
|_ _ |_ _ routes.js
|
|_ _ public
|_ _ |_ _ css
|_ _ |_ _ images
|_ _ |_ _ js
|
|_ _ views
|_ _ |_ _ user
|_ _ |_ _ |_ _ index.ejs
App folder - contains overall login for application.
Config folder - contains app configurations, constants, routes.
Public folder - contains styles, images, scripts etc.
Views folder - contains views for each model (if any)
Boilerplate project could be found here,
https://github.com/abdulmoiz251/node-express-rest-api-boilerplate
Swift 5.1 Custom Object/Type
// MARK: - NotificationName
// Extending notification name to avoid string errors.
extension Notification.Name {
static let yourNotificationName = Notification.Name("yourNotificationName")
}
// MARK: - CustomObject
class YourCustomObject {
// Any stuffs you would like to set in your custom object as always.
init() {}
}
// MARK: - Notification Sender Class
class NotificatioSenderClass {
// Just grab the content of this function and put it to your function responsible for triggering a notification.
func postNotification(){
// Note: - This is the important part pass your object instance as object parameter.
let yourObjectInstance = YourCustomObject()
NotificationCenter.default.post(name: .yourNotificationName, object: yourObjectInstance)
}
}
// MARK: -Notification Receiver class
class NotificationReceiverClass: UIViewController {
// MARK: - ViewController Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Register your notification listener
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveNotificationWithCustomObject), name: .yourNotificationName, object: nil)
}
// MARK: - Helpers
@objc private func didReceiveNotificationWithCustomObject(notification: Notification){
// Important: - Grab your custom object here by casting the notification object.
guard let yourPassedObject = notification.object as? YourCustomObject else {return}
// That's it now you can use your custom object
//
//
}
// MARK: - Deinit
deinit {
// Save your memory by releasing notification listener
NotificationCenter.default.removeObserver(self, name: .yourNotificationName, object: nil)
}
}
typeOf is a C# keyword that is used when you have the name of the class. It is calculated at compile time and thus cannot be used on an instance, which is created at runtime. GetType is a method of the object class that can be used on an instance.
For Sublime Text 3, First Install Package Control:
Type Install package and then press enter Click here to see Install Package Search Pic
After the package got installed. It may prompt to restart SublimeText
It perfectly worked for me. Hopefully, it helped you too. For any left requirements, visit https://packagecontrol.io/installation#st3 here.
I tried this on version 7.1.0
and it worked:
$PSVersionTable | Select-Object PSVersion
Output
PSVersion
---------
7.1.0
It doesn't work on version 5.1
though, so rather go for this on versions below 7:
$PSVersionTable.PSVersion
Output
Major Minor Build Revision
----- ----- ----- --------
5 1 18362 1171
This usually means that there was a network error, such as a TCP timeout. I would start by placing a sniffer (wireshark) on the connection to see if you can see any problems. If there is a TCP error, you should be able to see it. Also, you can check your router logs, if this is applicable. If wireless is involved anywhere, that is another source for these kind of errors.
According to this message on the GCC mailing list, you can use the file "nul" instead of /dev/null:
#include <stdio.h>
int main ()
{
FILE* outfile = fopen ("/dev/null", "w");
if (outfile == NULL)
{
fputs ("could not open '/dev/null'", stderr);
}
outfile = fopen ("nul", "w");
if (outfile == NULL)
{
fputs ("could not open 'nul'", stderr);
}
return 0;
}
(Credits to Danny for this code; copy-pasted from his message.)
You can also use this special "nul" file through redirection.
You can use RelativeSource
to find the parent element, like this -
Binding="{Binding Path=DataContext.CurveSpeedMustBeSpecified,
RelativeSource={RelativeSource AncestorType={x:Type local:YourParentElementType}}}"
See this SO question for more details about RelativeSource
.
This the most simple and small function JavaScript to get int ans String parameter value from URL
/* THIS FUNCTION IS TO FETCH INT PARAMETER VALUES */
function getParameterint(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=parseInt(url.replace(param+"=",""));
alert(n);
}
getParameteraint("page");
getParameteraint("pagee");
/*THIS FUNCTION IS TO FETCH STRING PARAMETER*/
function getParameterstr(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=url.replace(param+"=","");
alert(n);
}
getParameterstr("str");
Source And DEMO : http://bloggerplugnplay.blogspot.in/2012/08/how-to-get-url-parameter-in-javascript.html
If you want to stick with Jquery's .load() method, add something unique to the URL like a JavaScript timestamp. "+new Date().getTime()". Notice I had to add an "&time=" so it does not alter your pid variable.
$('#searchButton').click(function() {
$('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val()+'&time='+new Date().getTime());
});
If you're using Java 1.4, you can instead do:
System.out.println(Arrays.asList(array));
(This works in 1.5+ too, of course.)
To get the actual scrollable height of the areas scrolled by the window scrollbar, I used $('body').prop('scrollHeight')
. This seems to be the simplest working solution, but I haven't checked extensively for compatibility. Emanuele Del Grande notes on another solution that this probably won't work for IE below 8.
Most of the other solutions work fine for scrollable elements, but this works for the whole window. Notably, I had the same issue as Michael for Ankit's solution, namely, that $(document).prop('scrollHeight')
is returning undefined
.
I needed to add this functionality to a project I was working on recently and adding jQuery Mobile just to solve this problem seemed like overkill, so I came up with a solution and put it on github: bcSwipe (Bootstrap Carousel Swipe).
It's a lightweight jQuery plugin (~600 bytes minified vs jQuery Mobile touch events at 8kb), and it's been tested on Android and iOS.
This is how you use it:
$('.carousel').bcSwipe({ threshold: 50 });
Ok, try this:
Get the image with the transparent circle - http://i39.tinypic.com/15s97vd.png Put that image in a html element and change that element's background color via css. This way you get the logo with the circle in the color defined in the stylesheet.
The html
<div class="badassColorChangingLogo">
<img src="http://i39.tinypic.com/15s97vd.png" />
Or download the image and change the path to the downloaded image in your machine
</div>
The css
div.badassColorChangingLogo{
background-color:white;
}
div.badassColorChangingLogo:hover{
background-color:blue;
}
Keep in mind that this wont work on non-alpha capable browsers like ie6, and ie7. for ie you can use a js fix. Google ddbelated png fix and you can get the script.
Coverting the first letter of word capital
input:
hello world
String A = hello;
String B = world;
System.out.println(A.toUpperCase().charAt(0)+A.substring(1) + " " + B.toUpperCase().charAt(0)+B.substring(1));
Output:
Hello World
For those who use Visual Assist, vertical guidelines can be enabled from Display
section in Visual Assist's options:
It happen that after some time we need to run
'php artisan passport:install --force
again to generate a key this solved my problem ,
I recently stumbled across a new podcast named Hacker Medley. It's a short (~15 min) podcast with Nat Friedman and Alex Gravely. I found the first 3 episodes quite entertaining!
$objectQuery = "SELECT table_master.*, ((acos(sin((" . $latitude . "*pi()/180)) * sin((`latitude`*pi()/180))+cos((" . $latitude . "*pi()/180)) * cos((`latitude`*pi()/180)) * cos(((" . $longitude . "- `longtude`)* pi()/180))))*180/pi())*60*1.1515 as distance FROM `table_post_broadcasts` JOIN table_master ON table_post_broadcasts.master_id = table_master.id WHERE table_master.type_of_post ='type' HAVING distance <='" . $Radius . "' ORDER BY distance asc";
Call To the following function with argument as you file path:
private String getFileContent(String targetFilePath){
File file = new File(targetFilePath);
try {
fileInputStream = new FileInputStream(file);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e("",""+e.printStackTrace());
}
StringBuilder sb;
while(fileInputStream.available() > 0) {
if(null== sb) sb = new StringBuilder();
sb.append((char)fileInputStream.read());
}
String fileContent;
if(null!=sb){
fileContent= sb.toString();
// This is your fileContent in String.
}
try {
fileInputStream.close();
}
catch(Exception e){
// TODO Auto-generated catch block
Log.e("",""+e.printStackTrace());
}
return fileContent;
}
You can apply only to certain attribute by doing:
input[type="checkbox"] {...}
It explains it here.
EL expression:
${requestScope.Error_Message}
There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.
Since you are using an INNER JOIN you can just put the conditions in the WHERE clause, like this:
SELECT
p1.kArtikel,
p1.cName,
p1.cKurzBeschreibung,
p1.dLetzteAktualisierung,
p1.dErstellt,
p1.cSeo,
p2.kartikelpict,
p2.nNr,
p2.cPfad
FROM
tartikel AS p1 INNER JOIN tartikelpict AS p2
ON p1.kArtikel = p2.kArtikel
WHERE
DATE(dErstellt) > (NOW() - INTERVAL 7 DAY)
AND p2.nNr = 1
ORDER BY
p1.kArtikel DESC
LIMIT
100;
To get rid of symbol warnings you don't want, first you should understand how Eclipse CDT normally comes up with unknown symbol warnings in the first place. This is its process, more or less:
It might be better in the long run to fix problems with the earlier steps rather than to override their results by manually adding include directories, symbols, etc.
Toolchains
If you have GCC installed, and Eclipse has detected it, it should list that GCC as a toolchain choice that a new C++ project could use, which will also show up in Window -> Preferences -> C/C++ -> New CDT Project Wizard
on the Preferred Toolchains
tab's Toolchains
box on the right side. If it's not showing up, see the CDT FAQ's answer about compilers that need special environments (as well as MinGW and Cygwin answers for the Windows folk.)
If you have an existing Eclipse C++ project, you can change the associated toolchain by opening the project properties, and going to C/C++ Build -> Tool Chain Editor
and choosing the toolchain you want from the Current toolchain:
pulldown. (You'll have to uncheck the Display compatible toolchains only
box first if the toolchain you want is different enough from the one that was previously set in the project.)
If you added a toolchain to the system after launching Eclipse, you will need to restart it for it to detect the toolchain.
Discovery
Then, if the project's C/C++ Build -> Discovery Options -> Discovery profiles scope
is set to Per Language
, during the next build the new toolchain associated with the project will be used for auto-discovery of include paths and symbols, and will be used to update the "built-in" paths and symbols that show up in the project's C/C++ General -> Paths and Symbols
in the Includes
and Symbols
tabs.
Indexing
Sometimes you need to re-index again after setting the toolchain and doing a build to get the old symbol warnings to go away; right-click on the project folder and go to Index -> Rebuild
to do it.
(tested with Eclipse 3.7.2 / CDT 8)
Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:
git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit
If you want to still have it in your local repository and only remove it from the remote, then you can use:
git push origin +HEAD^:<name of your branch, most likely 'master'>