Add "-static" to other linker options solves this problem. I was just having the same issue after I tested this on another system, but not on my own, so even if you haven't noticed this on your development system, you should check that you have this set if you're statically linking.
Another note, copying the DLL into the same folder as the executable is not a solution as it defeats the idea of statically linking.
Another option is to use the TDM version of MinGW which solves this problem.
Update edit: this may not solve the problem for everyone. Another reason I recently discovered for this is when you use a library compiled by someone else, in my case it was SFML which was improperly compiled and so required a DLL that did not exist as it was compiled with a different version of MinGW than what I use. I use a dwarf build, this used another one, so I didn't have the DLL anywhere and of course, I didn't want it as it was a static build. The solution may be to find another build of the library, or build it yourself.
The thing all other have forgot is that you cant check image size before it loads. When the author checks all of posted methods it will work probably only on localhost. Since jQuery could be used here, remember that 'ready' event is fired before images are loaded. $('#xxx').width() and .height() should be fired in onload event or later.
Straight after the $wpdb->insert()
that does the insert, do this:
$lastid = $wpdb->insert_id;
More information about how to do things the WordPress way can be found in the WordPress codex. The details above were found here on the wpdb class page
You can set the datagridview
DataSource
to null
and rebind it again.
private void button1_Click(object sender, EventArgs e)
{
myAccesscon.ConnectionString = connectionString;
dataGridView.DataSource = null;
dataGridView.Update();
dataGridView.Refresh();
OleDbCommand cmd = new OleDbCommand(sql, myAccesscon);
myAccesscon.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable bookings = new DataTable();
da.Fill(bookings);
dataGridView.DataSource = bookings;
myAccesscon.Close();
}
I had the "No module named PyQt4.QtCore" error and installing the python-qt4 package fixed it only partially: I could run
from PyQt4.QtCore import SIGNAL
from a python interpreter but only without activating my virtualenv.
The only solution I've found till now to use a virtualenv is to copy the PyQt4 folder and the sip.so file into my virtualenv as explained here: Is it possible to add PyQt4/PySide packages on a Virtualenv sandbox?
Late to the party, but in case this happens with a WORDPRESS
installation :
#1273 - Unknown collation: 'utf8mb4_unicode_520_ci
In phpmyadmin, under export method
> Format-specific options
( custom export )
Set to : MYSQL40
If you will try to import now, you now might get another error message :
1064 - You have an error in your SQL syntax; .....
That is because The older TYPE
option that was synonymous with ENGINE
was removed in MySQL 5.5.
Open your .sql
file , search and replace all instances
from TYPE=
to ENGINE=
Now the import should go smoothly.
Let me add this one, because sometimes you just want the single digit representation
( x
can be lower, 'x', or uppercase, 'X', the choice determines if the output letters are upper or lower.):
'{:x}'.format(15)
> f
And now with the new f''
format strings you can do:
f'{15:x}'
> f
To add 0 padding you can use 0>n
:
f'{2034:0>4X}'
> 07F2
NOTE: the initial 'f' in
f'{15:x}'
is to signify a format string
I had this problem. Code worked fine when running locally but not when on server. Using psPing (https://technet.microsoft.com/en-us/sysinternals/psping.aspx) I realised the applications port wasn't returning anything. Turned out to be a firewall issue. I hadn't enabled my applications port in the Windows Firewall.
Administrative Tools > Windows Firewall with Advanced Security added my applications port to the Inbound Rules and it started working.
Somehow the application port number had got changed, so took a while to figure out what was going on - so thought I'd share this possibility in case it saves someone else time...
We can update GTF answer to update timestamps easily
$data = array(
array(
'name'=>'Coder 1', 'rep'=>'4096',
'created_at'=>date('Y-m-d H:i:s'),
'modified_at'=> date('Y-m-d H:i:s')
),
array(
'name'=>'Coder 2', 'rep'=>'2048',
'created_at'=>date('Y-m-d H:i:s'),
'modified_at'=> date('Y-m-d H:i:s')
),
//...
);
Coder::insert($data);
Update: to simplify the date we can use carbon as @Pedro Moreira suggested
$now = Carbon::now('utc')->toDateTimeString();
$data = array(
array(
'name'=>'Coder 1', 'rep'=>'4096',
'created_at'=> $now,
'modified_at'=> $now
),
array(
'name'=>'Coder 2', 'rep'=>'2048',
'created_at'=> $now,
'modified_at'=> $now
),
//...
);
Coder::insert($data);
UPDATE2: for laravel 5 , use updated_at
instead of modified_at
$now = Carbon::now('utc')->toDateTimeString();
$data = array(
array(
'name'=>'Coder 1', 'rep'=>'4096',
'created_at'=> $now,
'updated_at'=> $now
),
array(
'name'=>'Coder 2', 'rep'=>'2048',
'created_at'=> $now,
'updated_at'=> $now
),
//...
);
Coder::insert($data);
One more thing... If you already ignored those files through Eclipse (with Team -> Ignored resources) you have to undo these settings so the files are controlled by Subclipse again and "Add to svn:ignore" option reappears
If you're able to upgrade to Postgresql 9.5, the jsonb_set
command is available, as others have mentioned.
In each of the following SQL statements, I've omitted the where
clause for brevity; obviously, you'd want to add that back.
Update name:
UPDATE test SET data = jsonb_set(data, '{name}', '"my-other-name"');
Replace the tags (as oppose to adding or removing tags):
UPDATE test SET data = jsonb_set(data, '{tags}', '["tag3", "tag4"]');
Replacing the second tag (0-indexed):
UPDATE test SET data = jsonb_set(data, '{tags,1}', '"tag5"');
Append a tag (this will work as long as there are fewer than 999 tags; changing argument 999 to 1000 or above generates an error. This no longer appears to be the case in Postgres 9.5.3; a much larger index can be used):
UPDATE test SET data = jsonb_set(data, '{tags,999999999}', '"tag6"', true);
Remove the last tag:
UPDATE test SET data = data #- '{tags,-1}'
Complex update (delete the last tag, insert a new tag, and change the name):
UPDATE test SET data = jsonb_set(
jsonb_set(data #- '{tags,-1}', '{tags,999999999}', '"tag3"', true),
'{name}', '"my-other-name"');
It's important to note that in each of these examples, you're not actually updating a single field of the JSON data. Instead, you're creating a temporary, modified version of the data, and assigning that modified version back to the column. In practice, the result should be the same, but keeping this in mind should make complex updates, like the last example, more understandable.
In the complex example, there are three transformations and three temporary versions: First, the last tag is removed. Then, that version is transformed by adding a new tag. Next, the second version is transformed by changing the name
field. The value in the data
column is replaced with the final version.
You forgot about Action-Domain-Responder (ADR).
As explained in some graphics above, there's a direct relation/link between the Model and the View in MVC. An action is performed on the Controller, which will execute an action on the Model. That action in the Model, will trigger a reaction in the View. The View, is always updated when the Model's state changes.
Some people keep forgetting, that MVC was created in the late 70", and that the Web was only created in late 80"/early 90". MVC wasn't originally created for the Web, but for Desktop applications instead, where the Controller, Model and View would co-exist together.
Because we use web frameworks (eg:. Laravel) that still use the same naming conventions (model-view-controller), we tend to think that it must be MVC, but it's actually something else.
Instead, have a look at Action-Domain-Responder.
In ADR, the Controller gets an Action, which will perform an operation in the Model/Domain. So far, the same.
The difference is, it then collects that operation's response/data, and pass it to a Responder (eg:. view()
) for rendering.
When a new action is requested on the same component, the Controller is called again, and the cycle repeats itself.
In ADR, there's no connection between the Model/Domain and the View (Reponser's response).
Note: Wikipedia states that "Each ADR action, however, is represented by separate classes or closures.". This is not necessarily true. Several Actions can be in the same Controller, and the pattern is still the same.
The suggested edit queue is full for @tibor-udvari's excellent fetch answer, so I'll post my suggested edits as a new answer.
This function gets the content type from the header if returned, otherwise falls back on a settable default type.
async function getFileFromUrl(url, name, defaultType = 'image/jpeg'){
const response = await fetch(url);
const data = await response.blob();
return new File([data], name, {
type: response.headers.get('content-type') || defaultType,
});
}
// `await` can only be used in an async body, but showing it here for simplicity.
const file = await getFileFromUrl('https://example.com/image.jpg', 'example.jpg');
You can use strtotime() for time calculation. Here is an example:
$checkTime = strtotime('09:00:59');
echo 'Check Time : '.date('H:i:s', $checkTime);
echo '<hr>';
$loginTime = strtotime('09:01:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!'; echo '<br>';
echo 'Time diff in sec: '.abs($diff);
echo '<hr>';
$loginTime = strtotime('09:00:59');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
echo '<hr>';
$loginTime = strtotime('09:00:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';
Check the already-asked question - how to get time difference in minutes:
Subtract the past-most one from the future-most one and divide by 60.
Times are done in unix format so they're just a big number showing the number of seconds from January 1 1970 00:00:00 GMT
Using simple html,
<div>
<object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
</object>
</div>
Or jquery,
<script>
$("#mydiv")
.html('<object data="http://your-website-domain"/>');
</script>
I came up with a similar example. Again, the rotation keyword is.. well, it's key.
from pylab import *
fig = figure()
ax = fig.add_subplot(111)
ax.bar( [0,1,2], [1,3,5] )
ax.set_xticks( [ 0.5, 1.5, 2.5 ] )
ax.set_xticklabels( ['tom','dick','harry'], rotation=45 ) ;
According to Javax's persistence documentation:
Whether the column is included in SQL UPDATE statements generated by the persistence provider.
It would be best to understand from the official documentation here.
I also put dsym, app bundle, and crash log together in the same directory before running symbolicate crash
Then I use this function defined in my .profile to simplify running symbolicatecrash:
function desym
{
/Developer/Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/DTDeviceKit.framework/Versions/A/Resources/symbolicatecrash -A -v $1 | more
}
The arguments added there may help you.
You can check to make sure spotlight "sees" your dysm files by running the command:
mdfind 'com_apple_xcode_dsym_uuids = *'
Look for the dsym you have in your directory.
NOTE: As of the latest Xcode, there is no longer a Developer directory. You can find this utility here:
/Applications/Xcode.app/Contents/SharedFrameworks/DTDeviceKitBase.framework/Vers??ions/A/Resources/symbolicatecrash
In my experience, this has been a surprisingly frequent problem with new vagrant machines. By far the easiest way to solve it, instead of altering the configuration itself, has been creating the required ssh keys manually on the client, then using the private key on the host.
vagrant ssh
, use default password vagrant
.ssh-keygen -t rsa -b 4096 -C "vagrant"
(as adviced by GitHub's relevant guide).mv .ssh/id_rsa.pub .ssh/authorized_keys
.sudo service ssh reload
.cat .ssh/id_rsa
, paint and copy (better ways must exist, go invent one!).logout
.vagrant ssh-config
(look for instance ÌdentityFile "/[...]/private_key".nano /[...]/private_key
and paste from the clipboard, if all else fails. (Note, however, that if your private_key is not project specific but shared by multiple vagrant machines, you better configure the path yourself in order to not break other perfectly working machines! Changing the path is as simple as adding a line config.ssh.private_key_path = "path/to/private_key"
into the Vagrantfile.) Furthermore, if you are using PuPHPet generated machine, you can store your private key to file puphpet/files/dot/ssh/id_rsa
and it will be added to Vagrantfile's ssh config automatically.vagrant ssh
should now work.Should that be the case, congratulate yourself, logout
, run vagrant provision
if needed and carry on with the meaningful task at hand.
If you still face problems, it may come handy to add verbose flag to ssh command to ease debugging. You can pass that (or any other option, for that matter) after double dash. For example, typing vagrant ssh -- -v
. Feel free to add as many v's as you need, each will give you more information.
If you want to update branch that is not currently checked out you can do:
git fetch -f origin rbranch:lbranch
Explode is very high speed function, source alhoritm get from TStrings component. I use next test for explode: Explode 134217733 bytes of data, i get 19173962 elements, time of work: 2984 ms.
Implode is very low speed function, but i write it easy.
{ ****************************************************************************** }
{ Explode/Implode (String <> String array) }
{ ****************************************************************************** }
function Explode(S: String; Delimiter: Char): Strings; overload;
var I, C: Integer; P, P1: PChar;
begin
SetLength(Result, 0);
if Length(S) = 0 then Exit;
P:=PChar(S+Delimiter); C:=0;
while P^ <> #0 do begin
P1:=P;
while (P^ <> Delimiter) do P:=CharNext(P);
Inc(C);
while P^ in [#1..' '] do P:=CharNext(P);
if P^ = Delimiter then begin
repeat
P:=CharNext(P);
until not (P^ in [#1..' ']);
end;
end;
SetLength(Result, C);
P:=PChar(S+Delimiter); I:=-1;
while P^ <> #0 do begin
P1:=P;
while (P^ <> Delimiter) do P:=CharNext(P);
Inc(I); SetString(Result[I], P1, P-P1);
while P^ in [#1..' '] do P:=CharNext(P);
if P^ = Delimiter then begin
repeat
P:=CharNext(P);
until not (P^ in [#1..' ']);
end;
end;
end;
function Explode(S: String; Delimiter: Char; Index: Integer): String; overload;
var I: Integer; P, P1: PChar;
begin
if Length(S) = 0 then Exit;
P:=PChar(S+Delimiter); I:=1;
while P^ <> #0 do begin
P1:=P;
while (P^ <> Delimiter) do P:=CharNext(P);
SetString(Result, P1, P-P1);
if (I <> Index) then Inc(I) else begin
SetString(Result, P1, P-P1); Exit;
end;
while P^ in [#1..' '] do P:=CharNext(P);
if P^ = Delimiter then begin
repeat
P:=CharNext(P);
until not (P^ in [#1..' ']);
end;
end;
end;
function Implode(S: Strings; Delimiter: Char): String;
var iCount: Integer;
begin
Result:='';
if (Length(S) = 0) then Exit;
for iCount:=0 to Length(S)-1 do
Result:=Result+S[iCount]+Delimiter;
System.Delete(Result, Length(Result), 1);
end;
Try git fetch
so that your local repository gets all the new info from github. It just takes the information about new branches and no actual code. After that the git checkout
should work fine.
Try this out. Hope this helps
<div id="single" dir="rtl">
<div class="common">Single</div>
</div>
<div id="both" dir="ltr">
<div class="common">Both</div>
</div>
#single, #both{
width: 100px;
height: 100px;
overflow: auto;
margin: 0 auto;
border: 1px solid gray;
}
.common{
height: 150px;
width: 150px;
}
This issue occurs with me while I was trying to upgrade pip version. It was resolved with the following commands:
python -m ensurepip
The above command restores the pip and below mentioned upgrades it.
python -m pip install --upgrade pip
set /a countfiles-=%countfiles%
This will set countfiles to 0. I think you want to decrease it by 1, so use this instead:
set /a countfiles-=1
I'm not sure if the for loop will work, better try something like this:
:loop
cscript /nologo c:\deletefile.vbs %BACKUPDIR%
set /a countfiles-=1
if %countfiles% GTR 21 goto loop
The coordinate system on the screen is left-handed, i.e. the x coordinate increases from left to right and the y coordinate increases from top to bottom. The origin, O(0, 0) is at the upper left corner of the screen.
A clockwise rotation around the origin of a point with coordinates (x, y) is given by the following equations:
where (x', y') are the coordinates of the point after rotation and angle theta, the angle of rotation (needs to be in radians, i.e. multiplied by: PI / 180).
To perform rotation around a point different from the origin O(0,0), let's say point A(a, b) (pivot point). Firstly we translate the point to be rotated, i.e. (x, y) back to the origin, by subtracting the coordinates of the pivot point, (x - a, y - b). Then we perform the rotation and get the new coordinates (x', y') and finally we translate the point back, by adding the coordinates of the pivot point to the new coordinates (x' + a, y' + b).
Following the above description:
Using your function prototype: (x, y) -> (p.x, p.y); (a, b) -> (cx, cy); theta -> angle:
POINT rotate_point(float cx, float cy, float angle, POINT p){
return POINT(cos(angle) * (p.x - cx) - sin(angle) * (p.y - cy) + cx,
sin(angle) * (p.x - cx) + cos(angle) * (p.y - cy) + cy);
}
Just like in Java, using CommonsIO library:
FileUtils.readFileToString(file, StandardCharsets.UTF_8)
Also, many answers here forget Charset. It's better to always provide it explicitly, or it will hit one day.
You can also do this without using jQuery. Override XMLHttpRequest's send method and add the header there:
XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) {
this.setRequestHeader('x-my-custom-header', 'some value');
this.realSend(vData);
};
XMLHttpRequest.prototype.send = newSend;
If you do not want to destroy .idea, you can try :
As an alternative to using a trigger, you might like to consider creating a stored procedure to handle the INSERT
s that takes most of the columns as arguments and gets the CURRENT_TIMESTAMP
which it includes in the final INSERT
to the database. You could do the same for the CREATE
. You may also be able to set things up so that users cannot execute INSERT
and CREATE
statements other than via the stored procedures.
I have to admit that I haven't actually done this myself so I'm not at all sure of the details.
SELECT * FROM items WHERE `items.xml` LIKE '%123456%'
The %
operator in LIKE
means "anything can be here".
The best bet with these types of questions is to see exactly what python does. The dis
module is incredibly informative:
>>> import dis
>>> dis.dis("val != None")
1 0 LOAD_NAME 0 (val)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 3 (!=)
6 RETURN_VALUE
>>> dis.dis("not (val is None)")
1 0 LOAD_NAME 0 (val)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE
>>> dis.dis("val is not None")
1 0 LOAD_NAME 0 (val)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE
Notice that the last two cases reduce to the same sequence of operations, Python reads not (val is None)
and uses the is not
operator. The first uses the !=
operator when comparing with None
.
As pointed out by other answers, using !=
when comparing with None
is a bad idea.
You could just use an even simpler typedef
:
typedef char *string;
Then, your malloc would look like a usual malloc:
string s = malloc(maxStringLength);
One con I can think of is if you need really fast access to your data in your view (for example, game animation data like bone positions.) It is very inefficient to keep a layer of separation in this case.
Otherwise, for most other applications which are more data driven than graphics driven, it seems like a logical way to drive a UI.
You can't beat the simplicity of a locked message queue. I say don't waste your time with anything more complex.
Read up on the lock statement.
EDIT
Here is an example of the Microsoft Queue object wrapped so all actions against it are thread safe.
public class Queue<T>
{
/// <summary>Used as a lock target to ensure thread safety.</summary>
private readonly Locker _Locker = new Locker();
private readonly System.Collections.Generic.Queue<T> _Queue = new System.Collections.Generic.Queue<T>();
/// <summary></summary>
public void Enqueue(T item)
{
lock (_Locker)
{
_Queue.Enqueue(item);
}
}
/// <summary>Enqueues a collection of items into this queue.</summary>
public virtual void EnqueueRange(IEnumerable<T> items)
{
lock (_Locker)
{
if (items == null)
{
return;
}
foreach (T item in items)
{
_Queue.Enqueue(item);
}
}
}
/// <summary></summary>
public T Dequeue()
{
lock (_Locker)
{
return _Queue.Dequeue();
}
}
/// <summary></summary>
public void Clear()
{
lock (_Locker)
{
_Queue.Clear();
}
}
/// <summary></summary>
public Int32 Count
{
get
{
lock (_Locker)
{
return _Queue.Count;
}
}
}
/// <summary></summary>
public Boolean TryDequeue(out T item)
{
lock (_Locker)
{
if (_Queue.Count > 0)
{
item = _Queue.Dequeue();
return true;
}
else
{
item = default(T);
return false;
}
}
}
}
EDIT 2
I hope this example helps. Remember this is bare bones. Using these basic ideas you can safely harness the power of threads.
public class WorkState
{
private readonly Object _Lock = new Object();
private Int32 _State;
public Int32 GetState()
{
lock (_Lock)
{
return _State;
}
}
public void UpdateState()
{
lock (_Lock)
{
_State++;
}
}
}
public class Worker
{
private readonly WorkState _State;
private readonly Thread _Thread;
private volatile Boolean _KeepWorking;
public Worker(WorkState state)
{
_State = state;
_Thread = new Thread(DoWork);
_KeepWorking = true;
}
public void DoWork()
{
while (_KeepWorking)
{
_State.UpdateState();
}
}
public void StartWorking()
{
_Thread.Start();
}
public void StopWorking()
{
_KeepWorking = false;
}
}
private void Execute()
{
WorkState state = new WorkState();
Worker worker = new Worker(state);
worker.StartWorking();
while (true)
{
if (state.GetState() > 100)
{
worker.StopWorking();
break;
}
}
}
the solution to the typescript:
Step1:
npm install jquery
npm install --save-dev @types/jquery
step2: in Angular.json add:
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
]
or in index.html add:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
step3: in *.component.ts where you want to use jquery
import * as $ from 'jquery'; // dont need "declare let $"
Then you can use jquery the same as javaScript. This way, VScode supports auto-suggestion by Typescript
You should first add a new route in global.asax:
routes.MapRoute(
"MyNewRoute",
"{controller}/{action}/{date}",
new { controller="YourControllerName", action="YourActionName", date = "" }
);
The on your Controller:
public ActionResult MyActionName(DateTime date)
{
}
Remember to keep your default route at the bottom of the RegisterRoutes method. Be advised that the engine will try to cast whatever value you send in {date} as a DateTime example, so if it can't be casted then an exception will be thrown. If your date string contains spaces or : you could HTML.Encode them so the URL could be parsed correctly. If no, then you could have another DateTime representation.
You can do it in this way with Swift 3.0:
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)
let year = components.year
let month = components.month
let day = components.day
print(year)
print(month)
print(day)
Me too got the same error but in my case I was calling url with blank spaces.
Then, I fixed it by parsing like below.
String url = "Your URL Link";
url = url.replaceAll(" ", "%20");
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new com.android.volley.Response.Listener<String>() {
@Override
public void onResponse(String response) {
...
...
...
Answered by the OP:
Add this to your CSS file.
html,
body {
height: 100%;
/* The html and body elements cannot have any padding or margin. */
}
/* Wrapper for page content to push down footer */
#wrap {
min-height: 100%;
height: auto !important;
height: 100%;
/* Negative indent footer by it's height */
margin: 0 auto -60px;
}
/* Set the fixed height of the footer here */
#push,
#footer {
height: 60px;
}
#footer {
background-color: #eee;
}
/* Lastly, apply responsive CSS fixes as necessary */
@media (max-width: 767px) {
#footer {
margin-left: -20px;
margin-right: -20px;
padding-left: 20px;
padding-right: 20px;
}
}
BEGIN
FOR r IN (select sid,serial# from v$session where username='user')
LOOP
EXECUTE IMMEDIATE 'alter system kill session ''' || r.sid || ',' || r.serial# || '''';
END LOOP;
END;
/
It works for me.
INSERT OVERWRITE LOCAL DIRECTORY '/home/lvermeer/temp' ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' select * from table;
is the correct answer.
If the number of records is really big, based on the number of files generated
the following command would give only partial result.
hive -e 'select * from some_table' > /home/yourfile.csv
Float each div and set clear;both for the row. No need to set widths if you dont want to. Works in Chrome 41,Firefox 37, IE 11
<div class="stack">
<div class="row">
<div class="col">
One
</div>
<div class="col">
Two
</div>
</div>
<div class="row">
<div class="col">
One
</div>
<div class="col">
Two
</div>
<div class="col">
Three
</div>
</div>
</div>
.stack .row {
clear:both;
}
.stack .row .col {
float:left;
border:1px solid;
}
The <pre>
tag in HTML, used with JSON.pretty_generate
, will render the JSON pretty in your view. I was so happy when my illustrious boss showed me this:
<% if @data.present? %>
<pre><%= JSON.pretty_generate(@data) %></pre>
<% end %>
You would simply need to do this in your onClick
:
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
I don't know from where you saw that you need DialogFragment for simply showing an alert.
Hope this helps.
I think you want to cast your dt
to a date
and fix the format of your date literal:
SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
Or the standard version:
SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
The extract
function doesn't understand "date" and it returns a number.
.size()
is not a native JS function of Array
(at least not in any browser that I know of).
.length
should be used.
.size()
does work on your page, make sure you do not have any extra libraries included like prototype that is mucking with the Array
prototype.
There might be some plugin on your browser that is mucking with the Array
prototype.
There are third-party implementations of interfaces for Python (most popular is Zope's, also used in Twisted), but more commonly Python coders prefer to use the richer concept known as an "Abstract Base Class" (ABC), which combines an interface with the possibility of having some implementation aspects there too. ABCs are particularly well supported in Python 2.6 and later, see the PEP, but even in earlier versions of Python they're normally seen as "the way to go" -- just define a class some of whose methods raise NotImplementedError
so that subclasses will be on notice that they'd better override those methods!-)
foreach (ModelState modelState in ViewData.ModelState.Values) {
foreach (ModelError error in modelState.Errors) {
DoSomethingWith(error);
}
}
See also How do I get the collection of Model State Errors in ASP.NET MVC?.
If you're simply sharing a counter, consider using an AtomicInteger or another suitable class from the java.util.concurrent.atomic package:
public class Test {
private final static AtomicInteger count = new AtomicInteger(0);
public void foo() {
count.incrementAndGet();
}
}
ES-6 Solution
Below is a sample code which uses aync/await to have an actual delay.
There are many constraints and this may not be useful, but just posting here for fun..
function delay(delayInms) {
return new Promise(resolve => {
setTimeout(() => {
resolve(2);
}, delayInms);
});
}
async function sample() {
console.log('a');
console.log('waiting...')
let delayres = await delay(3000);
console.log('b');
}
sample();
_x000D_
From man githooks
:
pre-commit
This hook is invoked by git commit, and can be bypassed with --no-verify option. It takes no parameter, and is invoked before obtaining the proposed commit log message and making a commit. Exiting with non-zero status from this script causes the git commit to abort.
Based on Why does FtpWebRequest download files from the root directory? Can this cause a 553 error?, I wrote a PowerShell script that enabled to download a file from a FTP-Server via explicit FTP over TLS:
# Config
$Username = "USERNAME"
$Password = "PASSWORD"
$LocalFile = "C:\PATH_TO_DIR\FILNAME.EXT"
#e.g. "C:\temp\somefile.txt"
$RemoteFile = "ftp://PATH_TO_REMOTE_FILE"
#e.g. "ftp://ftp.server.com/home/some/path/somefile.txt"
try{
# Create a FTPWebRequest
$FTPRequest = [System.Net.FtpWebRequest]::Create($RemoteFile)
$FTPRequest.Credentials = New-Object System.Net.NetworkCredential($Username,$Password)
$FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$FTPRequest.UseBinary = $true
$FTPRequest.KeepAlive = $false
$FTPRequest.EnableSsl = $true
# Send the ftp request
$FTPResponse = $FTPRequest.GetResponse()
# Get a download stream from the server response
$ResponseStream = $FTPResponse.GetResponseStream()
# Create the target file on the local system and the download buffer
$LocalFileFile = New-Object IO.FileStream ($LocalFile,[IO.FileMode]::Create)
[byte[]]$ReadBuffer = New-Object byte[] 1024
# Loop through the download
do {
$ReadLength = $ResponseStream.Read($ReadBuffer,0,1024)
$LocalFileFile.Write($ReadBuffer,0,$ReadLength)
}
while ($ReadLength -ne 0)
}catch [Exception]
{
$Request = $_.Exception
Write-host "Exception caught: $Request"
}
import java.util.Scanner;
public class v{
public static void main(String args[]){
Scanner in=new Scanner(System.in);
String str;
int l;
int flag=0;
System.out.println("Enter the String:");
str=in.nextLine();
str=str.toLowerCase();
str=str.replaceAll("\\s","");
char[] ch=str.toCharArray();
l=str.length();
for(int i=0;i<l;i++){
if ((ch[i] >= 'a' && ch[i]<= 'z') || (ch[i] >= 'A' && ch[i] <= 'Z')){
flag=0;
}
else
flag++;
break;
}
if(flag==0)
System.out.println("Onlt char");
}
}
Another way using 'awk'
awk NR==$((${RANDOM} % `wc -l < file.name` + 1)) file.name
There also exists a UNIQUE KEY. The main difference between PRIMARY KEY and UNIQUE KEY is that the PRIMARY KEY never takes NULL value while a UNIQUE KEY may take NULL value. Also, there can be only one PRIMARY KEY in a table while UNIQUE KEY may be more than one.
Math.sqrt returns a double so you'll have to cast it to int as well
distance = (int)Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
As others have pointed out, accessing dicts in Python is fast. They are probably the best-oiled data structure in the language, given their central role. The problem lies elsewhere.
How many tuples are you memoizing? Have you considered the memory footprint? Perhaps you are spending all your time in the memory allocator or paging memory.
if ($done)
{
header("Location: /url/to/the/other/page");
exit;
}
JSX:
<select value={ this.state.foo } onChange={this.handleFooChange}>
<option value="A">A</option>
<option value="B">B</option>
</select>
TypeScript:
private handleFooChange = (event: React.FormEvent<HTMLSelectElement>) => {
const element = event.target as HTMLSelectElement;
this.setState({ foo: element.value });
}
Remove the multiple="multiple" attribute and add SIZE=6 with the number of elements you want
you may want to check this site
I think it is too early to give a "best practices" answer for this as there hasn't been enough time to use it in practice. If this was asked about throw specifiers right after they came out then the answers would be very different to now.
Having to think about whether or not I need to append
noexcept
after every function declaration would greatly reduce programmer productivity (and frankly, would be a pain).
Well, then use it when it's obvious that the function will never throw.
When can I realistically expect to observe a performance improvement after using
noexcept
? [...] Personally, I care aboutnoexcept
because of the increased freedom provided to the compiler to safely apply certain kinds of optimizations.
It seems like the biggest optimization gains are from user optimizations, not compiler ones due to the possibility of checking noexcept
and overloading on it. Most compilers follow a no-penalty-if-you-don't-throw exception handling method, so I doubt it would change much (or anything) on the machine code level of your code, although perhaps reduce the binary size by removing the handling code.
Using noexcept
in the big four (constructors, assignment, not destructors as they're already noexcept
) will likely cause the best improvements as noexcept
checks are 'common' in template code such as in std
containers. For instance, std::vector
won't use your class's move unless it's marked noexcept
(or the compiler can deduce it otherwise).
Download java-json.jar from here, which contains org.json.JSONArray
http://www.java2s.com/Code/JarDownload/java/java-json.jar.zip
nzip and add to your project's library: Project > Build Path > Configure build path> Select Library tab > Add External Libraries > Select the java-json.jar file.
Test Data
DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)
Query
SELECT ID
,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
FROM @Table1
WHERE ID = t.ID
FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
SQL Server 2017 and Later Versions
If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:
DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);
SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
it seems that the ubuntu community has completed the documentation on installing openCV,
so all you have to do now is to download the installation script from here and execute it.
don't forget to make it executable:
chmod +x opencv_latest.sh
then
./opencv_latest.sh
There is a comand to directly do that:
Create a new kubectl rollout restart
command that does a rolling restart of a deployment.
The pull request got merged. It is part of the version 1.15
(changelog) or higher.
'Create Excel
Set objExcel = Wscript.CreateObject("Excel.Application")
objExcel.visible = True
Set objWb = objExcel.Workbooks.Add
objWb.Saveas("D:\Example.xlsx")
objExcel.Quit
From here
<nul set /p =Testing testing
and also to echo beginning with spaces use
echo.Message goes here
I had to make a flexible array function to add "records" to it as i needed and to be able to update them and do whatever calculations e needed before i sent it to a database for further processing. Here's the code, hope it helps :).
function Add2List(clmn1, clmn2, clmn3) {
aColumns.push(clmn1,clmn2,clmn3); // Creates array with "record"
aLine.splice(aPos, 0,aColumns); // Inserts new "record" at position aPos in main array
aColumns = []; // Resets temporary array
aPos++ // Increments position not to overlap previous "records"
}
Feel free to optimize and / or point out any bugs :)
There's many useful things in Python's unicodedata
library. One of them is the .normalize()
function.
Try:
new_str = unicodedata.normalize("NFKD", unicode_str)
Replacing NFKD with any of the other methods listed in the link above if you don't get the results you're after.
In C language, character literal is not a char
type. C considers character literal as integer. So, there is no difference between sizeof('a')
and sizeof(1)
.
So, the sizeof character literal is equal to sizeof integer in C.
In C++ language, character literal is type of char
. The cppreference say's:
1) narrow character literal or ordinary character literal, e.g.
'a'
or'\n'
or'\13'
. Such literal has typechar
and the value equal to the representation of c-char in the execution character set. If c-char is not representable as a single byte in the execution character set, the literal has type int and implementation-defined value.
So, in C++ character literal is a type of char
. so, size of character literal in C++ is one byte.
Alos, In your programs, you have used wrong format specifier for sizeof
operator.
C11 §7.21.6.1 (P9) :
If a conversion specification is invalid, the behavior is undefined.275) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
So, you should use %zu
format specifier instead of %d
, otherwise it is undefined behaviour in C.
this issue can be resolved using 2 ways:
netstat -ao | find "8080" Taskkill /PID 1342 /F
server.port=8081
Use org.junit.Assert's method assertArrayEquals
:
import org.junit.Assert;
...
Assert.assertArrayEquals( expectedResult, result );
If this method is not available, you may have accidentally imported the Assert class from junit.framework
.
Execute the pip binary directly.
First locate the version of PIP you want.
jon-mint python3.3 # whereis ip
ip: /bin/ip /sbin/ip /usr/share/man/man8/ip.8.gz /usr/share/man/man7/ip.7.gz
Then execute.
jon-mint python3.3 # pip3.3 install pexpect
Downloading/unpacking pexpect
Downloading pexpect-3.2.tar.gz (131kB): 131kB downloaded
Running setup.py (path:/tmp/pip_build_root/pexpect/setup.py) egg_info for package pexpect
Installing collected packages: pexpect
Running setup.py install for pexpect
Successfully installed pexpect
Cleaning up...
I think the problem is that you load
isfar
data.frame but you overwrite it by value returned by load
.
Try either:
load("C:/Users/isfar.RData")
head(isfar)
Or more general way
load("C:/Users/isfar.RData", ex <- new.env())
ls.str(ex)
Slight tweak to answer from @divbyzero above to fix sonar security warnings
CloseableHttpClient getInsecureHttpClient() throws GeneralSecurityException {
TrustStrategy trustStrategy = (chain, authType) -> true;
HostnameVerifier hostnameVerifier = (hostname, session) -> hostname.equalsIgnoreCase(session.getPeerHost());
return HttpClients.custom()
.setSSLSocketFactory(new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(trustStrategy).build(), hostnameVerifier))
.build();
}
Exactly what you're looking for in these plugins:
It sounds to me as if you actually mean "linux guests" and not "linux hosts".
But in any case, I suspect you did not install the VMWare Tools: doubleclick on that icon on the Desktop that can be seen on your screenshot. It will install some drivers that communicate with VMWare that, among other things, allow to adjust the screen resolution dynamically.
When the installation process is finished, you'll most likely have to reboot the VM.
I encountered the same problem. The easiest thing is to install the free Visual Studio Community 2015 as answered in this question Is MFC only available with Visual Studio, and not Visual C++ Express?
I know this post is old but it was the first one that popped up when I did a search. I tried @Kim Kling RegExp but it failed miserably. Also prior to finding this forum I had tried almost all the other variations listed here. In the end, none of them worked except this one I created; it works fine, plus it is es6:
const regex = new RegExp(/[^0-9]/, 'g');
const val = document.forms["myForm"]["age"].value;
if (val.match(regex)) {
alert("Must be a valid number");
}
Pandas magic at work. All logic is out.
The error message "ValueError: If using all scalar values, you must pass an index"
Says you must pass an index.
This does not necessarily mean passing an index makes pandas do what you want it to do
When you pass an index, pandas will treat your dictionary keys as column names and the values as what the column should contain for each of the values in the index.
a = 2
b = 3
df2 = pd.DataFrame({'A':a,'B':b}, index=[1])
A B
1 2 3
Passing a larger index:
df2 = pd.DataFrame({'A':a,'B':b}, index=[1, 2, 3, 4])
A B
1 2 3
2 2 3
3 2 3
4 2 3
An index is usually automatically generated by a dataframe when none is given. However, pandas does not know how many rows of 2
and 3
you want. You can however be more explicit about it
df2 = pd.DataFrame({'A':[a]*4,'B':[b]*4})
df2
A B
0 2 3
1 2 3
2 2 3
3 2 3
The default index is 0 based though.
I would recommend always passing a dictionary of lists to the dataframe constructor when creating dataframes. It's easier to read for other developers. Pandas has a lot of caveats, don't make other developers have to experts in all of them in order to read your code.
Had same problem - it was somewhere in the ca certificate, so I used the ca bundle used for curl, and it worked. You can download the curl ca bundle here: https://curl.haxx.se/docs/caextract.html
For encryption and security issues see this helpful article:
https://www.venditan.com/labs/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/432
Here is the example:
$url = 'https://www.example.com/api/list';
$cn_match = 'www.example.com';
$data = array (
'apikey' => '[example api key here]',
'limit' => intval($limit),
'offset' => intval($offset)
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
, 'ssl' => array(
'verify_peer' => true,
'cafile' => [path to file] . "cacert.pem",
'ciphers' => 'HIGH:TLSv1.2:TLSv1.1:TLSv1.0:!SSLv3:!SSLv2',
'CN_match' => $cn_match,
'disable_compression' => true,
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
Hope that helps
I don't like $.inArray(..)
, it's the kind of ugly, jQuery-ish solution that most sane people wouldn't tolerate. Here's a snippet which adds a simple contains(str)
method to your arsenal:
$.fn.contains = function (target) {
var result = null;
$(this).each(function (index, item) {
if (item === target) {
result = item;
}
});
return result ? result : false;
}
Similarly, you could wrap $.inArray
in an extension:
$.fn.contains = function (target) {
return ($.inArray(target, this) > -1);
}
You can try these some steps:
Stop Mysql Service 1st
sudo /etc/init.d/mysql stop
Login as root without password
sudo mysqld_safe --skip-grant-tables &
After login mysql terminal you should need execute commands more:
use mysql;
UPDATE mysql.user SET authentication_string=PASSWORD('solutionclub3@*^G'), plugin='mysql_native_password' WHERE User='root';
flush privileges;
sudo mysqladmin -u root -p -S /var/run/mysqld/mysqld.sock shutdown
After you restart your mysql server If you still facing error you must visit : Reset MySQL 5.7 root password Ubuntu 16.04
I wouldn't use function from one controller into another. A better approach would be to move the common function to a service and then inject the service in both controllers.
You can access the window object as an associative array and set it that way
window["onlyVideo"] = "TEST";
document.write(onlyVideo);
You want to use DATEADD, using a negative duration. e.g.
DATEADD(minute, -15, '2000-01-01 08:30:00')
I found one more answer when there is a constraint layout inside the scroll view then we need to put
android:fillViewport="true"
to the scroll view
and
android:layout_height="0dp"
in the constraint layout
Example:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="0dp">
// Rest of the views
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
For windows users you can use following batch script that counts added/removed lines for specified author
@echo off
set added=0
set removed=0
for /f "tokens=1-3 delims= " %%A in ('git log --pretty^=tformat: --numstat --author^=%1') do call :Count %%A %%B %%C
@echo added=%added%
@echo removed=%removed%
goto :eof
:Count
if NOT "%1" == "-" set /a added=%added% + %1
if NOT "%2" == "-" set /a removed=%removed% + %2
goto :eof
https://gist.github.com/zVolodymyr/62e78a744d99d414d56646a5e8a1ff4f
its better to bind a click handler to the entire table and then use event.target to get the clicked TD. Thats all i can add to this as its 1:20am
This should work
<a href="javascript:window.open('document.aspx','mywindowtitle','width=500,height=150')">open window</a>
Summarising @Rasmi Ranjan Nayak and @nogard answers and adding another option:
You should use the flag --gtest_filter
, like
--gtest_filter=Test_Cases1*
(You can also do this in Properties|Configuration Properties|Debugging|Command Arguments)
You should set the variable GTEST_FILTER
like
export GTEST_FILTER = "Test_Cases1*"
You should set a flag filter
, like
::testing::GTEST_FLAG(filter) = "Test_Cases1*";
such that your main function becomes something like
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
::testing::GTEST_FLAG(filter) = "Test_Cases1*";
return RUN_ALL_TESTS();
}
See section Running a Subset of the Tests for more info on the syntax of the string you can use.
I know this is old, but I had a similar issue with no real answers, where I wanted to remove all keydown
event listeners from the document. Instead of removing them, I override the addEventListener
to ignore them before they were even added, similar to Toms answer above, by adding this before any other scripts are loaded:
<script type="text/javascript">
var current = document.addEventListener;
document.addEventListener = function (type, listener) {
if(type =="keydown")
{
//do nothing
}
else
{
var args = [];
args[0] = type;
args[1] = listener;
current.apply(this, args);
}
};
</script>
original *= -1;
Simple line of code, original is any int you want it to be.
I hope this complete example will help you.
This is the TaxiInfo class which holds information about a taxi ride:
namespace Taxi.Models
{
public class TaxiInfo
{
public String Driver { get; set; }
public Double Fare { get; set; }
public Double Distance { get; set; }
public String StartLocation { get; set; }
public String EndLocation { get; set; }
}
}
We also have a convenience model which holds a List of TaxiInfo(s):
namespace Taxi.Models
{
public class TaxiInfoSet
{
public List<TaxiInfo> TaxiInfoList { get; set; }
public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
{
TaxiInfoList = new List<TaxiInfo>();
foreach(var TaxiInfo in TaxiInfos)
{
TaxiInfoList.Add(TaxiInfo);
}
}
}
}
Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:
public ActionResult Index()
{
var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };
return View(new TaxiInfoSet(taxi1,taxi2));
}
The code for the view is as follows:
@model Taxi.Models.TaxiInfoSet
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach(var TaxiInfo in Model.TaxiInfoList){
<form>
<h1>Cost: [email protected]</h1>
<h2>Distance: @(TaxiInfo.Distance) km</h2>
<p>
Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
</p>
@Html.ActionLink("Home","Booking",TaxiInfo)
</form>
}
The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:
public ActionResult Booking(TaxiInfo Taxi)
{
return View(Taxi);
}
This returns a the following view:
@model Taxi.Models.TaxiInfo
@{
ViewBag.Title = "Booking";
}
<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>
A visual tour:
Here's one way you can do this:
var escape = document.createElement('textarea');
function escapeHTML(html) {
escape.textContent = html;
return escape.innerHTML;
}
function unescapeHTML(html) {
escape.innerHTML = html;
return escape.textContent;
}
One-liner (java8):
list.removeIf(s -> s.equals("acbd")); // removes all instances, not just the 1st one
(does all the iterating implicitly)
extends
The wildcard declaration of List<? extends Number> foo3
means that any of these are legal assignments:
List<? extends Number> foo3 = new ArrayList<Number>(); // Number "extends" Number (in this context)
List<? extends Number> foo3 = new ArrayList<Integer>(); // Integer extends Number
List<? extends Number> foo3 = new ArrayList<Double>(); // Double extends Number
Reading - Given the above possible assignments, what type of object are you guaranteed to read from List foo3
:
Number
because any of the lists that could be assigned to foo3
contain a Number
or a subclass of Number
.Integer
because foo3
could be pointing at a List<Double>
.Double
because foo3
could be pointing at a List<Integer>
.Writing - Given the above possible assignments, what type of object could you add to List foo3
that would be legal for all the above possible ArrayList
assignments:
Integer
because foo3
could be pointing at a List<Double>
.Double
because foo3
could be pointing at a List<Integer>
.Number
because foo3
could be pointing at a List<Integer>
.You can't add any object to List<? extends T>
because you can't guarantee what kind of List
it is really pointing to, so you can't guarantee that the object is allowed in that List
. The only "guarantee" is that you can only read from it and you'll get a T
or subclass of T
.
super
Now consider List <? super T>
.
The wildcard declaration of List<? super Integer> foo3
means that any of these are legal assignments:
List<? super Integer> foo3 = new ArrayList<Integer>(); // Integer is a "superclass" of Integer (in this context)
List<? super Integer> foo3 = new ArrayList<Number>(); // Number is a superclass of Integer
List<? super Integer> foo3 = new ArrayList<Object>(); // Object is a superclass of Integer
Reading - Given the above possible assignments, what type of object are you guaranteed to receive when you read from List foo3
:
Integer
because foo3
could be pointing at a List<Number>
or List<Object>
.Number
because foo3
could be pointing at a List<Object>
.Object
or subclass of Object
(but you don't know what subclass).Writing - Given the above possible assignments, what type of object could you add to List foo3
that would be legal for all the above possible ArrayList
assignments:
Integer
because an Integer
is allowed in any of above lists.Integer
because an instance of a subclass of Integer
is allowed in any of the above lists.Double
because foo3
could be pointing at an ArrayList<Integer>
.Number
because foo3
could be pointing at an ArrayList<Integer>
.Object
because foo3
could be pointing at an ArrayList<Integer>
.Remember PECS: "Producer Extends, Consumer Super".
"Producer Extends" - If you need a List
to produce T
values (you want to read T
s from the list), you need to declare it with ? extends T
, e.g. List<? extends Integer>
. But you cannot add to this list.
"Consumer Super" - If you need a List
to consume T
values (you want to write T
s into the list), you need to declare it with ? super T
, e.g. List<? super Integer>
. But there are no guarantees what type of object you may read from this list.
If you need to both read from and write to a list, you need to declare it exactly with no wildcards, e.g. List<Integer>
.
Note this example from the Java Generics FAQ. Note how the source list src
(the producing list) uses extends
, and the destination list dest
(the consuming list) uses super
:
public class Collections {
public static <T> void copy(List<? super T> dest, List<? extends T> src) {
for (int i = 0; i < src.size(); i++)
dest.set(i, src.get(i));
}
}
Also see How can I add to List<? extends Number> data structures?
select CPaymentType, sum(CAmount)
from TableOrderPayment
where (CPaymentType = 'Cash' and CStatus = 'Active')
or (CPaymentType = 'Check' and CDate <= bsysdatetime() abd CStatus = 'Active')
group by CPaymentType
Cheers -
Try this Bash syntax instead of trying to use an external program expr
:
count=$((FIRSTV-SECONDV))
BTW, the correct syntax of using expr
is:
count=$(expr $FIRSTV - $SECONDV)
But keep in mind using expr
is going to be slower than the internal Bash syntax I provided above.
Harry Martyrossian mentions in a comment on his own answer that the
Get-ItemPropertyValue cmdlet was introduced in Powershell v5, which solves the problem:
PS> Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' 'ProgramFilesDir'
C:\Program Files
Alternatives for PowerShell v4-:
Here's an attempt to retain the efficiency while eliminating the need for repetition of the value name, which, however, is still a little cumbersome:
& { (Get-ItemProperty `
-LiteralPath HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion `
-Name $args `
).$args } 'ProgramFilesDir'
By using a script block, the value name can be passed in once as a parameter, and the parameter variable ($args
) can then simply be used twice inside the block.
Alternatively, a simple helper function can ease the pain:
function Get-RegValue([String] $KeyPath, [String] $ValueName) {
(Get-ItemProperty -LiteralPath $KeyPath -Name $ValueName).$ValueName
}
Note: All solutions above bypass the problem described in Ian Kemp's's answer - the need to use explicit quoting for certain value names when used as property names; e.g., .'15.0'
- because the value names are passed as parameters and property access happens via a variable; e.g., .$ValueName
As for the other answers:
I encountered this issue while trying to fix $_SESSION's blocking behavior.
http://konrness.com/php5/how-to-prevent-blocking-php-requests/
The session file remains locked until the script completes or the session is manually closed.
So, by default, a page should open a session in read-only mode. But once it's open in read-only, it has to be closed-and-reopened in to get it into write mode.
const SESSION_DEFAULT_COOKIE_LIFETIME = 86400;
/**
* Open _SESSION read-only
*/
function OpenSessionReadOnly() {
session_start([
'cookie_lifetime' => SESSION_DEFAULT_COOKIE_LIFETIME,
'read_and_close' => true, // READ ACCESS FAST
]);
// $_SESSION is now defined. Call WriteSessionValues() to write out values
}
/**
* _SESSION is read-only by default. Call this function to save a new value
* call this function like `WriteSessionValues(["username"=>$login_user]);`
* to set $_SESSION["username"]
*
* @param array $values_assoc_array
*/
function WriteSessionValues($values_assoc_array) {
// this is required to close the read-only session and
// not get a warning on the next line.
session_abort();
// now open the session with write access
session_start([ 'cookie_lifetime' => SESSION_DEFAULT_COOKIE_LIFETIME ]);
foreach ($values_assoc_array as $key => $value) {
$_SESSION[ $key ] = $value;
}
session_write_close(); // Write session data and end session
OpenSessionReadOnly(); // now reopen the session in read-only mode.
}
OpenSessionReadOnly(); // start the session for this page
Then when you go to write some value:
WriteSessionValues(["username"=>$login_user]);
The function takes an array of key=>value pairs to make it even more efficient.
In the "Understanding Crashes and Crash Logs" session 414 of the 2018 WWDC they show the following way using DispatchQueues with sync.
In swift 4 should be something like the following:
class ImageCache {
private let queue = DispatchQueue(label: "sync queue")
private var storage: [String: UIImage] = [:]
public subscript(key: String) -> UIImage? {
get {
return queue.sync {
return storage[key]
}
}
set {
queue.sync {
storage[key] = newValue
}
}
}
}
Anyway you can also make reads faster using concurrent queues with barriers. Sync and async reads are performed concurrently and writing a new value waits for previous operations to finish.
class ImageCache {
private let queue = DispatchQueue(label: "with barriers", attributes: .concurrent)
private var storage: [String: UIImage] = [:]
func get(_ key: String) -> UIImage? {
return queue.sync { [weak self] in
guard let self = self else { return nil }
return self.storage[key]
}
}
func set(_ image: UIImage, for key: String) {
queue.async(flags: .barrier) { [weak self] in
guard let self = self else { return }
self.storage[key] = image
}
}
}
James K, I'm sorry I was wrong in a fair portion of what I said. The test I did was the following:
@ECHO OFF
(
:: But
: neither
:: does
: this
:: also.
)
This meets your description of alternating but fails with a ") was unexpected at this time." error message.
I did some farther testing today and found that alternating isn't the key but it appears the key is having an even number of lines, not having any two lines in a row starting with double colons (::) and not ending in double colons. Consider the following:
@ECHO OFF
(
: But
: neither
: does
: this
: cause
: problems.
)
This works!
But also consider this:
@ECHO OFF
(
: Test1
: Test2
: Test3
: Test4
: Test5
ECHO.
)
The rule of having an even number of comments doesn't seems to apply when ending in a command.
Unfortunately this is just squirrelly enough that I'm not sure I want to use it.
Really, the best solution, and the safest that I can think of, is if a program like Notepad++ would read REM as double colons and then would write double colons back as REM statements when the file is saved. But I'm not aware of such a program and I'm not aware of any plugins for Notepad++ that does that either.
Well, data.str().c_str()
yields a char const*
but your function Printfunc()
wants to have char*
s. Based on the name, it doesn't change the arguments but merely prints them and/or uses them to name a file, in which case you should probably fix your declaration to be
void Printfunc(int a, char const* loc, char const* stream)
The alternative might be to turn the char const*
into a char*
but fixing the declaration is preferable:
Printfunc(num, addr, const_cast<char*>(data.str().c_str()));
If you need to perform this List.contains(Object with field value equal to x)
repeatedly, a simple and efficient workaround would be:
List<field obj type> fieldOfInterestValues = new ArrayList<field obj type>;
for(Object obj : List) {
fieldOfInterestValues.add(obj.getFieldOfInterest());
}
Then the List.contains(Object with field value equal to x)
would be have the same result as fieldOfInterestValues.contains(x);
it is because of using web address, You can not use http to write data. don't use : http:// or https:// in your location for upload files or save data or somting like that. instead of of using $_SERVER["HTTP_REFERER"] use $_SERVER["DOCUMENT_ROOT"]. for example :
wrong :
move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["HTTP_REFERER"].'/uploads/images/1.jpg')
correct:
move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["DOCUMENT_ROOT"].'/uploads/images/1.jpg')
You have to add Button to excel sheet(say sheet1
) from which you can go to another sheet(say sheet2
).
Button can be added from Developer tab in excel. If developer tab is not there follow below steps to enable.
GOTO file -> options -> Customize Ribbon -> enable checkbox of developer on right panel -> Done.
To Add button :-
Developer Tab -> Insert -> choose first item button -> choose location of button-> Done.
To give name for button :-
Right click on button -> edit text.
To add code for going to sheet2 :-
Right click on button -> Assign Macro -> New -> (microsoft visual basic will open to code for button) -> paste below code
Worksheets("Sheet2").Visible = True
Worksheets("Sheet2").Activate
Save the file using 'Excel Macro Enable Template(*.xltm)' By which the code is appended with excel sheet.
Push SVG element to last, so that its z-index will be in top. In SVG, there s no property called z-index. try below javascript to bring the element to top.
var Target = document.getElementById(event.currentTarget.id);
var svg = document.getElementById("SVGEditor");
svg.insertBefore(Target, svg.lastChild.nextSibling);
Target: Is an element for which we need to bring it to top svg: Is the container of elements
Use this code:
HttpContext.Current.Server.MapPath("~")
Detailed Reference:
Server.MapPath
specifies the relative or virtual path to map to a physical directory.
Server.MapPath(".")
returns the current physical directory of the
file (e.g. aspx) being executedServer.MapPath("..")
returns the parent directoryServer.MapPath("~")
returns the physical path to the root of the
applicationServer.MapPath("/")
returns the physical path to the root of the
domain name (is not necessarily the same as the root of the
application)An example:
Let's say you pointed a web site application (http://www.example.com/) to
C:\Inetpub\wwwroot
and installed your shop application (sub web as virtual directory in IIS, marked as application) in
D:\WebApps\shop
For example, if you call Server.MapPath
in following request:
http://www.example.com/shop/products/GetProduct.aspx?id=2342
then:
Server.MapPath(".") returns D:\WebApps\shop\products
Server.MapPath("..") returns D:\WebApps\shop
Server.MapPath("~") returns D:\WebApps\shop
Server.MapPath("/") returns C:\Inetpub\wwwroot
Server.MapPath("/shop") returns D:\WebApps\shop
If Path starts with either a forward (/) or backward slash (), the MapPath
method returns a path as if Path were a full, virtual path.
If Path doesn't start with a slash, the MapPath
method returns a path relative to the directory of the request being processed.
Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.
Footnotes
Server.MapPath(null)
and Server.MapPath("")
will produce this effect too.
You can give it a property display block; so it will behave like a div and have its own line
CSS:
.feature_desc {
display: block;
....
}
I just looked again into the iOS 5.0 lib reference and found this section titled "Moving Content That Is Located Under the Keyboard": TextAndWebiPhoneOS KeyboardManagement
Is this new since iOS 5, perhaps? I haven't read into it yet as I'm in the middle of something else, but perhaps others know more and can enlighten me and others here.
Does the Apple doc supersede what's been discussed here or is the information here still useful to iOS 5 SDK users?
What you asked for is:
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
BEGIN
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
END
ELSE
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
BEGIN
DROP TABLE ##TEMP_CLIENTS_KEYWORD
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
END
ELSE
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
Since you're always going to create the table, regardless of whether the table is deleted or not; a slightly optimised solution is:
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD') IS NOT NULL
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD(client_id int)
IF OBJECT_ID('tempdb..##TEMP_CLIENTS_KEYWORD') IS NOT NULL
DROP TABLE ##TEMP_CLIENTS_KEYWORD
CREATE TABLE ##TEMP_CLIENTS_KEYWORD(client_id int)
A simple function drawing a circle on the middle of your window frame, using a multiplicator percentage
/// CGFloat is a multiplicator from self.view.frame.width
func drawCircle(withMultiplicator coefficient: CGFloat) {
let radius = self.view.frame.width / 2 * coefficient
let circlePath = UIBezierPath(arcCenter: self.view.center, radius: radius, startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
//change the fill color
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = UIColor.darkGray.cgColor
shapeLayer.lineWidth = 2.0
view.layer.addSublayer(shapeLayer)
}
Actually, I use both variants.
There are situations, where you first check for the validity of a pointer, and if it is NULL, you just return/exit out of a function. (I know this can lead to the discussion "should a function have only one exit point")
Most of the time, you check the pointer, then do what you want and then resolve the error case. The result can be the ugly x-times indented code with multiple if's.
Python Tutor is an online single-step debugger meant for novices. You can put in code on the edit page then click "Visualize Execution" to start it running.
Among other things, it supports:
However it also doesn't support a lot of things, for example:
io.StringIO
and io.BytesIO
instead: demoApple hand three categories of certificates: Trusted
, Always Ask
and Blocked
. You'll encounter the issue if your certificate's type on the Blocked
and Always Ask
list. On Safari it show’s like:
And you can find the type of Always Ask
certificates on Settings > General > About > Certificate Trust Setting
There is the List of available trusted root certificates in iOS 11
This it what you are looking for:
<input type="checkbox" [(ngModel)]="isChecked" (change)="checkValue(isChecked?'A':'B')" />
Inside your class:
checkValue(event: any){
console.log(event);
}
Also include FormsModule in app.module.ts
to make ngModel work !
Hope it Helps!
I met these warnings on mempcpy
function. Man page says this function is a GNU extension and synopsis shows:
#define _GNU_SOURCE
#include <string.h>
When #define
is added to my source before the #include
, declarations for the GNU extensions are made visible and warnings disappear.
I use this Swift 5, pure Core Graphics extension that correctly handles non-zero origins in image rects:
extension CGContext {
/// Draw `image` flipped vertically, positioned and scaled inside `rect`.
public func drawFlipped(_ image: CGImage, in rect: CGRect) {
self.saveGState()
self.translateBy(x: 0, y: rect.origin.y + rect.height)
self.scaleBy(x: 1.0, y: -1.0)
self.draw(image, in: CGRect(origin: CGPoint(x: rect.origin.x, y: 0), size: rect.size))
self.restoreGState()
}
}
You can use it exactly like CGContext
's regular draw(: in:)
method:
ctx.drawFlipped(myImage, in: myRect)
Copied directly from this answer:
You could write a script in any language you want to automate this (even using nodejs) and then just install a shortcut to that script in the user's %appdata%\Microsoft\Windows\Start Menu\Programs\Startup folder
Since TypeScript 1.8+
you can use simple simple import
statement like:
import { ClassName } from '../relative/path/to/file';
or the wildcard version:
import * as YourName from 'global-or-relative';
Read more: https://www.typescriptlang.org/docs/handbook/modules.html
Using the {# #}
notation, like so:
{# Everything you see here is a comment. It won't show up in the HTML output. #}
Handles either type of line break
str.replace(new RegExp('\r?\n','g'), '<br />');
Use this if you want to reset the select to the option which has the "selected" attribute. Works similar to the form.reset() inbuilt javascript function to the select.
$("#name").val($("#name option[selected]").val());
The standard Java classloader is a stickler for directory structure. Each entry in the classpath is a directory or jar file (or zip file, really), which it then searches for the given class file. For example, if your classpath is ".;my.jar", it will search for com.example.Foo in the following locations:
./com/example/
my.jar:/com/example/
That is, it will look in the subdirectory that has the 'modified name' of the package, where '.' is replaced with the file separator.
Also, it is noteworthy that you cannot nest .jar files.
I know this is an old question but I did try all the above answers but didnt work in my case. What ultimately helped me out is
SHOW PARAMETER instance_name
(DEMO)
Codes:
.backimage {width:99%; height:98%; position:absolute; background:transparent url("http://upload.wikimedia.org/wikipedia/commons/4/41/Brickwall_texture.jpg") repeat scroll 0% 0%; }
and
<div>
<div class="backimage"></div>
YOUR OTHER CONTENTTT
</div>
Please refer the link from JQuery
http://api.jquery.com/keypress/
It says
The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser.
That means you can not use keypress in case of arrows.
Please note this is from 2008. Today I would argue that the serializer should be built in and that you can probably use swagger + attributes to inform consumers about your endpoint and return data.
Iwould argue that you shouldn't be serializing an anonymous type. I know the temptation here; you want to quickly generate some throw-away types that are just going to be used in a loosely type environment aka Javascript in the browser. Still, I would create an actual type and decorate it as Serializable. Then you can strongly type your web methods. While this doesn't matter one iota for Javascript, it does add some self-documentation to the method. Any reasonably experienced programmer will be able to look at the function signature and say, "Oh, this is type Foo! I know how that should look in JSON."
Having said that, you might try JSON.Net to do the serialization. I have no idea if it will work
table align="center" ... this aligns the table center of page.
Using td align="center" centers the content inside that td, useful for centered aligned text but you will have issues with some email clients centering content in sub level tables so using using td align as a top level method of centering your "container" table on the page is not the way to do it. Use table align instead.
Still use your 100% wrapper table too, purely as a wrapper for the body, as some email clients don't display body background colors but it will show it with the 100% table, so add your body color to both body and the 100% table.
I could go on and on for ages about all the quirks of html email dev. All I can say is test test and test again. Litmus.com is a great tool for testing emails.
The more you do the more you will learn about what works in what email clients.
Hope this helps.
And if you don't want to use the entire framework like Express, but you also need different kinds of forms, including uploads, then formaline may be a good choice.
It is listed in Node.js modules
You don't need that sort of solution for string literals, since they are concatenated at the language level, and it wouldn't work anyway because "s""1" isn't a valid preprocessor token.
[Edit: In response to the incorrect "Just for the record" comment below that unfortunately received several upvotes, I will reiterate the statement above and observe that the program fragment
#define PPCAT_NX(A, B) A ## B
PPCAT_NX("s", "1")
produces this error message from the preprocessing phase of gcc: error: pasting ""s"" and ""1"" does not give a valid preprocessing token
]
However, for general token pasting, try this:
/*
* Concatenate preprocessor tokens A and B without expanding macro definitions
* (however, if invoked from a macro, macro arguments are expanded).
*/
#define PPCAT_NX(A, B) A ## B
/*
* Concatenate preprocessor tokens A and B after macro-expanding them.
*/
#define PPCAT(A, B) PPCAT_NX(A, B)
Then, e.g., both PPCAT_NX(s, 1)
and PPCAT(s, 1)
produce the identifier s1
, unless s
is defined as a macro, in which case PPCAT(s, 1)
produces <macro value of s>1
.
Continuing on the theme are these macros:
/*
* Turn A into a string literal without expanding macro definitions
* (however, if invoked from a macro, macro arguments are expanded).
*/
#define STRINGIZE_NX(A) #A
/*
* Turn A into a string literal after macro-expanding it.
*/
#define STRINGIZE(A) STRINGIZE_NX(A)
Then,
#define T1 s
#define T2 1
STRINGIZE(PPCAT(T1, T2)) // produces "s1"
By contrast,
STRINGIZE(PPCAT_NX(T1, T2)) // produces "T1T2"
STRINGIZE_NX(PPCAT_NX(T1, T2)) // produces "PPCAT_NX(T1, T2)"
#define T1T2 visit the zoo
STRINGIZE(PPCAT_NX(T1, T2)) // produces "visit the zoo"
STRINGIZE_NX(PPCAT(T1, T2)) // produces "PPCAT(T1, T2)"
As per my observation like two cases, if a table has less then 100,000 records then the join will work fast.
But in the case that a table has more than 100,000 records then a subquery is best result.
I have one table that has 500,000 records on that I created below query and its result time is like
SELECT *
FROM crv.workorder_details wd
inner join crv.workorder wr on wr.workorder_id = wd.workorder_id;
Result : 13.3 Seconds
select *
from crv.workorder_details
where workorder_id in (select workorder_id from crv.workorder)
Result : 1.65 Seconds
This also happens when the Response-Type is not public! I returned an internal class as I used Visual Studio to generate me the type.
internal class --> public class
First, activate CORS in your S3 bucket. Use this code as a guidance:
<CORSConfiguration>
<CORSRule>
<AllowedOrigin>http://www.example1.com</AllowedOrigin>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
<CORSRule>
<AllowedOrigin>http://www.example2.com</AllowedOrigin>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
</CORSRule>
</CORSConfiguration>
2) If it still not working, make sure to also add a "crossorigin" with a "*" value to your img tags. Put this in your html file:
let imagenes = document.getElementsByTagName("img");
for (let i = 0; i < imagenes.length; i++) {
imagenes[i].setAttribute("crossorigin", "*");
In my case i have no values-v21 file in my res directory. Then i created it and added in it following codes:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
"Am i doing it right?Is there better/smarter way to achieve the output this code gave me?"
Generally speaking, yes, you're doing it right. Tkinter has no native scrollable container other than the canvas. As you can see, it's really not that difficult to set up. As your example shows, it only takes 5 or 6 lines of code to make it work -- depending on how you count lines.
"Why must i use grid method?(i tried place method, but none of the labels appear on the canvas?)"
You ask about why you must use grid. There is no requirement to use grid. Place, grid and pack can all be used. It's simply that some are more naturally suited to particular types of problems. In this case it looks like you're creating an actual grid -- rows and columns of labels -- so grid is the natural choice.
"What so special about using anchor='nw' when creating window on canvas?"
The anchor tells you what part of the window is positioned at the coordinates you give. By default, the center of the window will be placed at the coordinate. In the case of your code above, you want the upper left ("northwest") corner to be at the coordinate.
In addition to @Malk, I wanted to clear all fields in the popup, except the hidden fields. To do that just use this:
$('.modal').on('hidden.bs.modal', function () {
$(this)
.find("input:not([type=hidden]),textarea,select")
.val('')
.end()
.find("input[type=checkbox], input[type=radio]")
.prop("checked", "")
.end();
});
This will clear all fields, except the hidden ones.
In my Case: I have put the correct path for Android and java but still getting the error.
The problem was that I have added the Android platform using sudo command.sudo ionic cordova platform android
.
To solve my problem: First I have removed the platform android by running command
sudo ionic cordova platform rm android
then add the android platform again with out sudoionic cordova platform add android
but i get the error of permissions.
To resolve the error run command
sudo chmod -R 777 {Path-of-your-project}
in my case sudo chmod -R 777 ~/codebase/IonicProject
Then run command
ionic cordova platform add android
or
ionic cordova run android
The answer is System.exit(), but not a good thing to do as this aborts the program. Any cleaning up, destroy that you intend to do will not happen.
If you already committed the changes than you would have to revert changes.
If you didn't commit yet, just do a clean checkout git checkout .
It should be as simple as using a list of receiving variables:
scanf("%i %i %i", &var1, &var2, &var3);
** Update ** A scalars converter has been added to retrofit that allows for a String
response with less ceremony than my original answer below.
Example interface --
public interface GitHubService {
@GET("/users/{user}")
Call<String> listRepos(@Path("user") String user);
}
Add the ScalarsConverterFactory
to your retrofit builder. Note: If using ScalarsConverterFactory
and another factory, add the scalars factory first.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
You will also need to include the scalars converter in your gradle file --
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- Original Answer (still works, just more code) ---
I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject
land. I suspect your specific problem might be better solved using a custom gson TypeAdapter
or a retrofit Converter
if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call
API. Instead of sending an object to convert as the type parameter, use ResponseBody
from okhttp --
public interface GitHubService {
@GET("/users/{user}")
Call<ResponseBody> listRepos(@Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string()
on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream()
instead. See the ResponseBody
docs.
Eclipse Neon (4.6), release date June 2016, includes word wrap for text editors. It's disabled by default, and can be activated and deactivated using the key shortcut Alt+Shift+Y
(on Mac OS, Cmd-Opt-Y
). Some editors also supply a tool bar button for activating word wrap.
See the 4.6 M4 New and Noteworthy
You can use an argument of type Type - iow, pass typeof(int). You can also use generics for a (probably more efficient) approach.
Make Rectangle a template and pass the typename on to Area:
template <typename T>
class Rectangle : public Area<T>
{
};
The primary purpose is to avoid chained indexing and eliminate the SettingWithCopyWarning
.
Here chained indexing is something like dfc['A'][0] = 111
The document said chained indexing should be avoided in Returning a view versus a copy. Here is a slightly modified example from that document:
In [1]: import pandas as pd
In [2]: dfc = pd.DataFrame({'A':['aaa','bbb','ccc'],'B':[1,2,3]})
In [3]: dfc
Out[3]:
A B
0 aaa 1
1 bbb 2
2 ccc 3
In [4]: aColumn = dfc['A']
In [5]: aColumn[0] = 111
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
In [6]: dfc
Out[6]:
A B
0 111 1
1 bbb 2
2 ccc 3
Here the aColumn
is a view and not a copy from the original DataFrame, so modifying aColumn
will cause the original dfc
be modified too. Next, if we index the row first:
In [7]: zero_row = dfc.loc[0]
In [8]: zero_row['A'] = 222
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
In [9]: dfc
Out[9]:
A B
0 111 1
1 bbb 2
2 ccc 3
This time zero_row
is a copy, so the original dfc
is not modified.
From these two examples above, we see it's ambiguous whether or not you want to change the original DataFrame. This is especially dangerous if you write something like the following:
In [10]: dfc.loc[0]['A'] = 333
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
In [11]: dfc
Out[11]:
A B
0 111 1
1 bbb 2
2 ccc 3
This time it didn't work at all. Here we wanted to change dfc
, but we actually modified an intermediate value dfc.loc[0]
that is a copy and is discarded immediately. It’s very hard to predict whether the intermediate value like dfc.loc[0]
or dfc['A']
is a view or a copy, so it's not guaranteed whether or not original DataFrame will be updated. That's why chained indexing should be avoided, and pandas generates the SettingWithCopyWarning
for this kind of chained indexing update.
Now is the use of .copy()
. To eliminate the warning, make a copy to express your intention explicitly:
In [12]: zero_row_copy = dfc.loc[0].copy()
In [13]: zero_row_copy['A'] = 444 # This time no warning
Since you are modifying a copy, you know the original dfc
will never change and you are not expecting it to change. Your expectation matches the behavior, then the SettingWithCopyWarning
disappears.
Note, If you do want to modify the original DataFrame, the document suggests you use loc
:
In [14]: dfc.loc[0,'A'] = 555
In [15]: dfc
Out[15]:
A B
0 555 1
1 bbb 2
2 ccc 3
In javascript:
document.getElementById("myDIV").style.display = "none";
and in jquery:
$("#myDIV").css({display: "none"});
$("#myDIV").css({display: "block"});
and you can use:
$('#myDIV').hide();
$('#myDIV').show();
You shouldn't design your application based on specific lifetimes of access tokens. Just assume they are (very) short lived.
However, after a successful completion of the OAuth2 installed application flow, you will get back a refresh token. This refresh token never expires, and you can use it to exchange it for an access token as needed. Save the refresh tokens, and use them to get access tokens on-demand (which should then immediately be used to get access to user data).
EDIT: My comments above notwithstanding, there are two easy ways to get the access token expiration time:
expires_in
)when you exchange your refresh token (using /o/oauth2/token endpoint). More details.There is also an API that returns the remaining lifetime of the access_token:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}
This will return a json array that will contain an expires_in
parameter, which is the number of seconds left in the lifetime of the token.
As my usecase involves dozens of columns, I expanded @jahroy's answer a bit. (also just realized @charles-clayton had the same idea.)
I pass the parameter I want to sort by, and the sort function is redefined with the desired index for the comparison to take place on.
var ID_COLUMN=0
var URL_COLUMN=1
findings.sort(compareByColumnIndex(URL_COLUMN))
function compareByColumnIndex(index) {
return function(a,b){
if (a[index] === b[index]) {
return 0;
}
else {
return (a[index] < b[index]) ? -1 : 1;
}
}
}
Learn more about how to navigate through the parse tree in BeautifulSoup
. Parse tree has got tags
and NavigableStrings
(as THIS IS A TEXT). An example
from BeautifulSoup import BeautifulSoup
doc = ['<html><head><title>Page title</title></head>',
'<body><p id="firstpara" align="center">This is paragraph <b>one</b>.',
'<p id="secondpara" align="blah">This is paragraph <b>two</b>.',
'</html>']
soup = BeautifulSoup(''.join(doc))
print soup.prettify()
# <html>
# <head>
# <title>
# Page title
# </title>
# </head>
# <body>
# <p id="firstpara" align="center">
# This is paragraph
# <b>
# one
# </b>
# .
# </p>
# <p id="secondpara" align="blah">
# This is paragraph
# <b>
# two
# </b>
# .
# </p>
# </body>
# </html>
To move down the parse tree you have contents
and string
.
contents is an ordered list of the Tag and NavigableString objects contained within a page element
if a tag has only one child node, and that child node is a string, the child node is made available as tag.string, as well as tag.contents[0]
For the above, that is to say you can get
soup.b.string
# u'one'
soup.b.contents[0]
# u'one'
For several children nodes, you can have for instance
pTag = soup.p
pTag.contents
# [u'This is paragraph ', <b>one</b>, u'.']
so here you may play with contents
and get contents at the index you want.
You also can iterate over a Tag, this is a shortcut. For instance,
for i in soup.body:
print i
# <p id="firstpara" align="center">This is paragraph <b>one</b>.</p>
# <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>
foreach($shipmentarr as $index=>$val){
$additionalService = array();
foreach($additionalService[$index] as $key => $value) {
array_push($additionalService,$value);
}
}
I would solve it using Extension methods
, Math.Pow
function and Enums
:
public static class MyExtension
{
public enum SizeUnits
{
Byte, KB, MB, GB, TB, PB, EB, ZB, YB
}
public static string ToSize(this Int64 value, SizeUnits unit)
{
return (value / (double)Math.Pow(1024, (Int64)unit)).ToString("0.00");
}
}
and use it like:
string h = x.ToSize(MyExtension.SizeUnits.KB);
For whom it needs it, check firewall port 3306 is open too, if your firewall service is running.
You can install it by first extracting all the files from the ISO and then overwriting those files with the files from the ZIP. Then you can run the batch file as administrator to do the installation. Most of the packages install on windows 7, but I haven't tested yet how well they work.
JAX-RS implementations automatically support marshalling/unmarshalling of classes based on discoverable JAXB annotations, but because your payload is declared as Object
, I think the created JAXBContext
misses the Department
class and when it's time to marshall it it doesn't know how.
A quick and dirty fix would be to add a XmlSeeAlso
annotation to your response class:
@XmlRootElement
@XmlSeeAlso({Department.class})
public class Response implements Serializable {
....
or something a little more complicated would be "to enrich" the JAXB context for the Response
class by using a ContextResolver
:
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
@Provider
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public class ResponseResolver implements ContextResolver<JAXBContext> {
private JAXBContext ctx;
public ResponseResolver() {
try {
this.ctx = JAXBContext.newInstance(
Response.class,
Department.class
);
} catch (JAXBException ex) {
throw new RuntimeException(ex);
}
}
public JAXBContext getContext(Class<?> type) {
return (type.equals(Response.class) ? ctx : null);
}
}
If you are in a domain environment, you can also use:
winrs -r:PCNAME cmd
This will open a remote command shell.
You could do $stmt->queryString
to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.
String s1 = "";
means that the empty String
is assigned to s1
.
In this case, s1.length()
is the same as "".length()
, which will yield 0
as expected.
String s2 = null;
means that (null
) or "no value at all" is assigned to s2
. So this one, s2.length()
is the same as null.length()
, which will yield a NullPointerException
as you can't call methods on null
variables (pointers, sort of) in Java.
Also, a point, the statement
String s1;
Actually has the same effect as:
String s1 = null;
Whereas
String s1 = "";
Is, as said, a different thing.
This is simple way to Display Div using:-
$("#musicinfo").show(); //or
$("#musicinfo").css({'display':'block'}); //or
$("#musicinfo").toggle("slow"); //or
$("#musicinfo").fadeToggle(); //or
size
of all deleted fileas well as the associated SHA
git log --all --stat --diff-filter=D --oneline
add a -p to see the contents too
git log --all --stat --diff-filter=D -p
To narrow down to any file simply pipe to grep and search for file name
git log --all --stat --diff-filter=D --oneline | grep someFileName
You might also like this one if you know where the file is
git log --all --full-history -- someFileName
I had a very similar issue today - I needed to copy a big table(5 millions rows) from MySql into MS SQL.
Here are the steps I've done(under Ubuntu Linux):
Created a table in MS SQL which structure matches the source table in MySql.
Installed MS SQL command line: https://docs.microsoft.com/en-us/sql/linux/sql-server-linux-setup-tools#ubuntu
Dumped table from MySql to a file:
mysqldump \ --compact \ --complete-insert \ --no-create-info \ --compatible=mssql \ --extended-insert=FALSE \ --host "$MYSQL_HOST" \ --user "$MYSQL_USER" \ -p"$MYSQL_PASS" \ "$MYSQL_DB" \ "$TABLE" > "$FILENAME"
In my case the dump file was quite large, so I decided to split it into a number of small pieces(1000 lines each) - split --lines=1000 "$FILENAME" part-
Finally I iterated over these small files, did some text replacements, and executed the pieces one by one against MS SQL server:
export SQLCMD=/opt/mssql-tools/bin/sqlcmd x=0 for file in part-* do echo "Exporting file [$file] into MS SQL. $x thousand(s) processed" # replaces \' with '' sed -i "s/\\\'/''/g" "$file" # removes all " sed -i 's/"//g' "$file" # allows to insert records with specified PK(id) sed -i "1s/^/SET IDENTITY_INSERT $TABLE ON;\n/" "$file" "$SQLCMD" -S "$AZURE_SERVER" -d "$AZURE_DB" -U "$AZURE_USER" -P "$AZURE_PASS" -i "$file" echo "" echo "" x=$((x+1)) done echo "Done"
Of course you'll need to replace my variables like $AZURE_SERVER
, $TABLE
, e.t.c. with yours.
Hope that helps.
maybe this one can help, you, that's how I did for my website, it works like a charm :
$protocol = $_SERVER["HTTP_CF_VISITOR"];
if (!strstr($protocol, 'https')){
header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
exit();
}
If you're removing a commit and don't want to keep its changes @ferit has a good solution.
If you want to add that commit to the current branch, but doesn't make sense to be part of the current pr, you can do the following instead:
git rebase -i HEAD~n
git reset HEAD^ --soft
to uncommit the changes and get them back in a staged state.git push --force
to update the remote branch without your removed commit.Now you'll have removed the commit from your remote, but will still have the changes locally.
The directory 'node_modules' may not be in current directory, so you should resolve the path dynamically.
var bootstrap_dir = require.resolve('bootstrap')
.match(/.*\/node_modules\/[^/]+\//)[0];
app.use('/scripts', express.static(bootstrap_dir + 'dist/'));
use simplejson or cjson for speedups
import simplejson as json
json.loads(obj)
or
cjson.decode(obj)
I am not sure if you got this resolved. To follow up on "CommonsWare's" comment.
That is not a valid string representation of a Uri. A Uri has a scheme, and "/external/images/media/470939" does not have a scheme.
Change
Uri uri=Uri.parse("/external/images/media/470939");
to
Uri uri=Uri.parse("content://external/images/media/470939");
in my case
Uri uri = Uri.parse("content://media/external/images/media/6562");
Maybe you can script/control winscp?
Update: winscp now has a .NET library available as a nuget package that supports SFTP, SCP, and FTPS
@Service vs @Controller
@Service : class is a "Business Service Facade" (in the Core J2EE patterns sense), or something similar.
@Controller : Indicates that an annotated class is a "Controller" (e.g. a web controller).
----------Find Usefull notes on Major Stereotypes http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/Component.html
@interface Component
@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
public @interface Component
Indicates that an annotated class is a component. Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.
@interface Controller
@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Component
public @interface Controller
Indicates that an annotated class is a "Controller" (e.g. a web controller).
@interface Service
@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Component
public @interface Service
Indicates that an annotated class is a "Service", originally defined by Domain-Driven Design (Evans, 2003) as "an operation offered as an interface that stands alone in the model, with no encapsulated state." May also indicate that a class is a "Business Service Facade" (in the Core J2EE patterns sense), or something similar. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.
@interface Repository
@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Component
public @interface Repository
Indicates that an annotated class is a "Repository", originally defined by Domain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects". Teams implementing traditional J2EE patterns such as "Data Access Object" may also apply this stereotype to DAO classes, though care should be taken to understand the distinction between Data Access Object and DDD-style repositories before doing so. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.
A class thus annotated is eligible for Spring DataAccessException translation when used in conjunction with a PersistenceExceptionTranslationPostProcessor. The annotated class is also clarified as to its role in the overall application architecture for the purpose of tooling, aspects, etc.
As of Spring 2.5, this annotation also serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).
With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15
To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:
SELECT * FROM tbl LIMIT 95,18446744073709551615;
With one argument, the value specifies the number of rows to return from the beginning of the result set:
SELECT * FROM tbl LIMIT 5; # Retrieve first 5 rows
In other words, LIMIT row_count is equivalent to LIMIT 0, row_count.
All details on: http://dev.mysql.com/doc/refman/5.0/en/select.html
Try adding System.Web
as a reference to your project.
You alread removed the active class from all the tabs but then you add the active class, again, to all the tabs. You should only add the active class to the currently selected tab like so http://jsfiddle.net/QFnRa/
$(".tab").removeClass("active");
$(this).addClass("active");
You can just create your own .white
class and add it to the glyphicon element.
.white, .white a {
color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>
I doubt lambda will go away. See Guido's post about finally giving up trying to remove it. Also see an outline of the conflict.
You might check out this post for more of a history about the deal behind Python's functional features: http://python-history.blogspot.com/2009/04/origins-of-pythons-functional-features.html
Curiously, the map, filter, and reduce functions that originally motivated the introduction of lambda and other functional features have to a large extent been superseded by list comprehensions and generator expressions. In fact, the reduce function was removed from list of builtin functions in Python 3.0. (However, it's not necessary to send in complaints about the removal of lambda, map or filter: they are staying. :-)
My own two cents: Rarely is lambda worth it as far as clarity goes. Generally there is a more clear solution that doesn't include lambda.
If you want to click on all elements selected by some class, you can use this example (used on last.fm on the Loved tracks page to Unlove all).
var divs = document.querySelectorAll('.love-button.love-button--loved');
for (i = 0; i < divs.length; ++i) {
divs[i].click();
};
With ES6 and Babel (cannot be run in the browser console directly)
[...document.querySelectorAll('.love-button.love-button--loved')]
.forEach(div => { div.click(); })
With the constructor:
// create a vector with 20 integer elements
std::vector<int> arr(20);
for(int x = 0; x < 20; ++x)
arr[x] = x;
A log of your commands may be available in your shell history.
history
If seeing the list of executed commands fly by isn't for you, export the list into a file.
history > path/to/file
You can restrict the exported dump to only show commands with "git" in them by piping it with grep
history | grep "git " > path/to/file
The history may contain lines formatted as such
518 git status -s
519 git commit -am "injects sriracha to all toppings, as required"
Using the number you can re-execute the command with an exclamation mark
$ !518
git status -s
I can second the previous posters enthusiasm for the Gideros Lua game engine, whilst focusing currently on Mobile (iOS and Android - Windows phone 8 is in the works), desktop support for Mac, PC (possibly Linux) is also planned for the not too distant future.
Google for "Gideros Mobile"
This returns True
if one and only one of the three conditions is True
. Probably what you wanted in your example code.
if sum(1 for x in (a,b,c) if x) == 1:
Here is an answer that's simple so you can see how it works, small and cross-platform.
It only uses built-in modules (os
, sys
and inspect
) so should work
on any operating system (OS) because Python is designed for that.
from inspect import getsourcefile
import os.path as path, sys
current_dir = path.dirname(path.abspath(getsourcefile(lambda:0)))
sys.path.insert(0, current_dir[:current_dir.rfind(path.sep)])
import my_module # Replace "my_module" here with the module name.
sys.path.pop(0)
For less lines than this, replace the second line with import os.path as path, sys, inspect
,
add inspect.
at the start of getsourcefile
(line 3) and remove the first line.
- however this imports all of the module so could need more time, memory and resources.
from inspect import getsourcefile
import os.path
import sys
current_path = os.path.abspath(getsourcefile(lambda:0))
current_dir = os.path.dirname(current_path)
parent_dir = current_dir[:current_dir.rfind(os.path.sep)]
sys.path.insert(0, parent_dir)
import my_module # Replace "my_module" here with the module name.
It uses an example from a Stack Overflow answer How do I get the path of the current
executed file in Python? to find the source (filename) of running code with a built-in tool.
from inspect import getsourcefile from os.path import abspath
Next, wherever you want to find the source file from you just use:
abspath(getsourcefile(lambda:0))
My code adds a file path to sys.path
, the python path list
because this allows Python to import modules from that folder.
After importing a module in the code, it's a good idea to run sys.path.pop(0)
on a new line
when that added folder has a module with the same name as another module that is imported
later in the program. You need to remove the list item added before the import, not other paths.
If your program doesn't import other modules, it's safe to not delete the file path because
after a program ends (or restarting the Python shell), any edits made to sys.path
disappear.
My answer doesn't use the __file__
variable to get the file path/filename of running
code because users here have often described it as unreliable. You shouldn't use it
for importing modules from parent folder in programs used by other people.
Some examples where it doesn't work (quote from this Stack Overflow question):
• it can't be found on some platforms • it sometimes isn't the full file path
py2exe
doesn't have a__file__
attribute, but there is a workaround- When you run from IDLE with
execute()
there is no__file__
attribute- OS X 10.6 where I get
NameError: global name '__file__' is not defined
Use a concrete list type, e.g. ArrayList
instead of just List
.
Remember that each Add
will check the capacity of the collection and resize it whenever necessary (slower). With AddRange
, the collection will be set the capacity and then added the items (faster). This extension method will be extremely slow, but will work.
SELECT art.* , sec.section.title, cat.title, use1.name, use2.name as modifiedby
FROM article art
INNER JOIN section sec ON art.section_id = sec.section.id
INNER JOIN category cat ON art.category_id = cat.id
INNER JOIN user use1 ON art.author_id = use1.id
LEFT JOIN user use2 ON art.modified_by = use2.id
WHERE art.id = '1';
Hope This Might Help
cgi.escape
should be good to escape HTML in the limited sense of escaping the HTML tags and character entities.
But you might have to also consider encoding issues: if the HTML you want to quote has non-ASCII characters in a particular encoding, then you would also have to take care that you represent those sensibly when quoting. Perhaps you could convert them to entities. Otherwise you should ensure that the correct encoding translations are done between the "source" HTML and the page it's embedded in, to avoid corrupting the non-ASCII characters.
As @page with pagenumbers don't work in browsers for now I was looking for alternatives.
I've found an answer posted by Oliver Kohll.
I'll repost it here so everyone could find it more easily:
For this answer we are not using @page, which is a pure CSS answer, but work in FireFox 20+ versions. Here is the link of an example.
The CSS is:
#content {
display: table;
}
#pageFooter {
display: table-footer-group;
}
#pageFooter:after {
counter-increment: page;
content: counter(page);
}
And the HTML code is:
<div id="content">
<div id="pageFooter">Page </div>
multi-page content here...
</div>
This way you can customize your page number by editing parametrs to #pageFooter. My example:
#pageFooter:after {
counter-increment: page;
content:"Page " counter(page);
left: 0;
top: 100%;
white-space: nowrap;
z-index: 20;
-moz-border-radius: 5px;
-moz-box-shadow: 0px 0px 4px #222;
background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);
}
This trick worked for me fine. Hope it will help you.
Simply put these codes at top of your PHP/index file:
error_reporting(E_ALL); // Error/Exception engine, always use E_ALL
ini_set('ignore_repeated_errors', TRUE); // always use TRUE
ini_set('display_errors', FALSE); // Error/Exception display, use FALSE only in production environment or real server. Use TRUE in development environment
ini_set('log_errors', TRUE); // Error/Exception file logging engine.
ini_set('error_log', 'your/path/to/errors.log'); // Logging file path
this fails:
DECLARE @vPortalUID NVARCHAR(32)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
PRINT @nPortalUID
this works
DECLARE @vPortalUID NVARCHAR(36)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
PRINT @nPortalUID
the difference is NVARCHAR(36)
, your input parameter is too small!
Your meta tag should look like this:
<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>
And it has to be placed on the page you want to share (this is unclear in your question).
If you have shared the page before the image (or the meta tag) was present, then it is possible, that facebook has the page in its "memory" without an image. In this case simply enter the URL of your page in the debug tool http://developers.facebook.com/tools/debug. After that, the image should be present when the page is shared the next time.
While there is no technical difference, I have seen the two used to denote slightly different things.
For a template that should accept any type as T, including built-ins (such as an array )
template<typename T>
class Foo { ... }
For a template that will only work where T is a real class.
template<class T>
class Foo { ... }
But keep in mind that this is purely a style thing some people use. Not mandated by the standard or enforced by compilers
Use [String.getBytes()][1]
to convert to bytes and use [String(byte[] data)][2]
constructor to convert back to string.
This will do. Pretty trustworthy. : )
""+number;
Just to clarify, this works and acceptable to use unless you are looking for micro optimization.
Remove the spaces before the autoplay=1:
src="https://www.youtube.com/embed/-SFcIUEvNOQ?autoplay=1&;enablejsapi=1"
memset could be inlined by compiler as a series of efficient opcodes, unrolled for a few cycles. For very large memory blocks, like 4000x2000 64bit framebuffer, you can try optimizing it across several threads (which you prepare for that sole task), each setting its own part. Note that there is also bzero(), but it is more obscure, and less likely to be as optimized as memset, and the compiler will surely notice you pass 0.
What compiler usually assumes, is that you memset large blocks, so for smaller blocks it would likely be more efficient to just do *(uint64_t*)p = 0
, if you init large number of small objects.
Generally, all x86 CPUs are different (unless you compile for some standardized platform), and something you optimize for Pentium 2 will behave differently on Core Duo or i486. So if you really into it and want to squeeze the last few bits of toothpaste, it makes sense to ship several versions your exe compiled and optimized for different popular CPU models. From personal experience Clang -march=native boosted my game's FPS from 60 to 65, compared to no -march.
You can use os.sep:
>>> import os
>>> os.sep
'/'
With pandas >= 1.0 there is now a dedicated string datatype:
1) You can convert your column to this pandas string datatype using .astype('string'):
df['zipcode'] = df['zipcode'].astype('string')
2) This is different from using str
which sets the pandas object datatype:
df['zipcode'] = df['zipcode'].astype(str)
3) For changing into categorical datatype use:
df['zipcode'] = df['zipcode'].astype('category')
You can see this difference in datatypes when you look at the info of the dataframe:
df = pd.DataFrame({
'zipcode_str': [90210, 90211] ,
'zipcode_string': [90210, 90211],
'zipcode_category': [90210, 90211],
})
df['zipcode_str'] = df['zipcode_str'].astype(str)
df['zipcode_string'] = df['zipcode_str'].astype('string')
df['zipcode_category'] = df['zipcode_category'].astype('category')
df.info()
# you can see that the first column has dtype object
# while the second column has the new dtype string
# the third column has dtype category
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 zipcode_str 2 non-null object
1 zipcode_string 2 non-null string
2 zipcode_category 2 non-null category
dtypes: category(1), object(1), string(1)
The 'string' extension type solves several issues with object-dtype NumPy arrays:
You can accidentally store a mixture of strings and non-strings in an object dtype array. A StringArray can only store strings.
object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text, but still object-dtype columns.
When reading code, the contents of an object dtype array is less clear than string.
More info on working with the new string datatype can be found here: https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html
Actually, I had this problem same as you. You can get the "Forbidden" error if your commit includes different directories ; Like external items.
And i solved in one step. Just commit external items in another case.
Additionally, I advise you to read articles on External Items in Subversion and VisualSVN Server:
VisualSVN Team's article about Daily Use Guide External Items. It explains the principles of External Items in SVN.
https://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-externals.html