download the zip file according to your OS (e.g.: protoc-3.7.0-osx-x86_64.zip). This applies also to other OS.
Move the executable in protoc-3/bin/protoc to one of your directories in PATH. In Mac I suggest to put it into /usr/local/bin
(optional) There is also an include file, you can add. This is a snippet of the README.md
If you intend to use the included well known types then don't forget to
copy the contents of the 'include' directory somewhere as well, for example
into '/usr/local/include/'.
Please refer to our official github site for more installation instructions:
https://github.com/protocolbuffers/protobuf
this happened to me when I was listening on the wrong port
I changed my listen() to "process.env.PORT" so:
http.listen((process.env.PORT || 5000), function(){
console.log('listening on *:5000');
});
instead of
http.listen(5000, function(){
console.log('listening on *:5000');
});
Make sure you import the @Test
annotation from the correct library:
import org.junit.jupiter.api.Test
not
import org.junit.Test
try this:
Dim ws as Worksheet
Set ws = Thisworkbook.Sheets("Sheet2")
With ws
.Range("E2").Formula = "=VLOOKUP(D2,Sheet1!$A:$C,1,0)"
End With
End Sub
This just the simplified version of what you want.
No need to use Application
if you will just output the answer in the Range("E2")
.
If you want to stick with your logic, declare the variables.
See below for example.
Sub Test()
Dim rng As Range
Dim ws1, ws2 As Worksheet
Dim MyStringVar1 As String
Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
Set rng = ws2.Range("D2")
With ws2
On Error Resume Next 'add this because if value is not found, vlookup fails, you get 1004
MyStringVar1 = Application.WorksheetFunction.VLookup(rng, ws1.Range("A1:C65536").Value, 1, False)
On Error GoTo 0
If MyStringVar1 = "" Then MsgBox "Item not found" Else MsgBox MyStringVar1
End With
End Sub
Hope this get's you started.
I'm pretty certain that it cannot be done.
Pretty much anything else than PDF works, even Flash. (Tested on Safari, Firefox 3, IE 7)
Too bad.
List<String> oldList = Arrays.asList("a", "b", "c", "d", "e", "f");
List<String> modifiedList = Arrays.asList("a", "b", "c", "d", "e", "g");
List<String> added = new HashSet<>(modifiedList);
List<String> removed = new HashSet<>(oldList);
modifiedList.stream().filter(removed::remove).forEach(added::remove);
// added items
System.out.println(added);
// removed items
System.out.println(removed);
Rather than using percentages to make the modal responsive, I find there can be more control taken from using the columns and other responsive elements already built into bootstrap.
To make the modal responsive/the size of any amount of columns:
1) Add an extra div around the modal-dialog div with a class of .container -
<div class="container">
<div class="modal-dialog">
</div>
</div>
2) Add a little CSS to make the modal full width -
.modal-dialog {
width: 100% }
3) Alternatively add in an extra class if you have other modals -
<div class="container">
<div class="modal-dialog modal-responsive">
</div>
</div>
.modal-responsive.modal-dialog {
width: 100% }
4) Add in a row/columns if you want various sized modals -
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="modal-dialog modal-responsive">
...
</div>
</div>
</div>
</div>
next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.
nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.
Read article :Difference between next() and nextLine()
Replace your while loop with :
while(r.hasNext()) {
scan = r.next();
System.out.println(scan);
if(scan.length()==0) {continue;}
//treatment
}
Using hasNext()
and next()
methods will resolve the issue.
Open in new tab using javascript
<button onclick="window.open('https://www.our-url.com')" id="myButton"
class="btn request-callback" >Explore More </button>
This is the improved answer of atomizer.
Note 2 calls of update()
and 200 ms
delay between them. They protect freezing applications due to an unstable state of the clipboard:
from Tkinter import Tk
import time
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('some string')
r.update()
time.sleep(.2)
r.update()
r.destroy()
if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...
That looks fine, unless you want to pass it as Model string
public class HomeController : Controller
{
public ActionResult Index()
{
string model = "<HTML></HTML>";
return View(model);
}
}
@model string
@{
ViewBag.Title = "Index";
}
@Html.Raw(Model)
use <meta http-equiv="X-Frame-Options" content="allow">
in the one to show in the iframe to allow it.
#include <stdio.h>
Int main ()
{
float f=56.75;
int a=(int)f;
int result=(f-a)*100;
printf ("integer = %d\n decimal part to integer
=%d\n",result);
}
Output:-
integer =56
decimal part to integer = 75
A common way of manipulating the first responder is to use nil targeted actions. This is a way of sending an arbitrary message to the responder chain (starting with the first responder), and continuing down the chain until someone responds to the message (has implemented a method matching the selector).
For the case of dismissing the keyboard, this is the most effective way that will work no matter which window or view is first responder:
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
This should be more effective than even [self.view.window endEditing:YES]
.
(Thanks to BigZaphod for reminding me of the concept)
To get around sandboxing of SCM stored Groovy scripts, I recommend to run the script as Groovy Command (instead of Groovy Script file):
import hudson.FilePath
final GROOVY_SCRIPT = "workspace/relative/path/to/the/checked/out/groovy/script.groovy"
evaluate(new FilePath(build.workspace, GROOVY_SCRIPT).read().text)
in such case, the groovy script is transferred from the workspace to the Jenkins Master where it can be executed as a system Groovy Script
. The sandboxing is suppressed as long as the Use Groovy Sandbox is not checked.
Careful with rewriting URLs, though. I'm using this, so it keeps URLs rewritten.
Response.Redirect(Request.RawUrl);
Assuming dateTime1
and dateTime2
are DateTime
values:
var diffInSeconds = (dateTime1 - dateTime2).TotalSeconds;
In your case, you 'd use DateTime.Now
as one of the values and the time in the list as the other. Be careful of the order, as the result can be negative if dateTime1
is earlier than dateTime2
.
The thing is that the printf function needs a pointer as parameter. However a char is a variable that you have directly acces. A string is a pointer on the first char of the string, so you don't have to add the * because * is the identifier for the pointer of a variable.
It would work as given below :
insert into Gengl_Del Select Tdate,DocNo,Book,GlCode,OpGlcode,Amt,Narration
from Gengl where BOOK='" & lblBook.Caption & "' AND DocNO=" & txtVno.Text & ""
Uncomment the line extension=php_mysql.dll
in your "php.ini" file and restart Apache.
Additionally, "libmysql.dll" file must be available to Apache, i.e., it must be either in available in Windows systems PATH or in Apache working directory.
See more about installing MySQL extension in manual.
P.S. I would advise to consider MySQL extension as deprecated and to use MySQLi or even PDO for working with databases (I prefer PDO).
In format function your can use timestamp_format function. Example, if the format is YYYYMMDD you can do it :
select TIMESTAMP_FORMAT(yourcolumnchar, 'YYYYMMDD') as YouTimeStamp
from yourtable
you can then adapt then format with elements format foundable here
Verify that you have the latest version of Node installed (or, at least 13.2.0+). Then do one of the following, as described in the documentation:
Option 1
In the nearest parent package.json
file, add the top-level "type"
field with a value of "module"
. This will ensure that all .js
and .mjs
files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs
extension.
// package.json
{
"type": "module"
}
Option 2
Explicitly name files with the .mjs
extension. All other files, such as .js
will be interpreted as CommonJS, which is the default if type
is not defined in package.json
.
You want to use "multiline".
$string =~ /(START)(.+?)(END)/m;
If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user
, picked from your example), then the syntax is quite simple:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('a.user', 'u')
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
Since you are applying a condition on the joined result here, using a LEFT JOIN
or simply JOIN
is the same.
If no association is available, then the query looks like following
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin(
'User\Entity\User',
'u',
\Doctrine\ORM\Query\Expr\Join::WITH,
'a.user = u.id'
)
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
This will produce a resultset that looks like following:
array(
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
// ...
)
I just knocked up a quick procedure to do this. It only works for a single row, so I create a temporary view that just selects the row I want, and then replace the pg_temp.temp_view with the actual table that I want to insert into.
CREATE OR REPLACE FUNCTION dv_util.gen_insert_statement(IN p_schema text, IN p_table text)
RETURNS text AS
$BODY$
DECLARE
selquery text;
valquery text;
selvalue text;
colvalue text;
colrec record;
BEGIN
selquery := 'INSERT INTO ' || quote_ident(p_schema) || '.' || quote_ident(p_table);
selquery := selquery || '(';
valquery := ' VALUES (';
FOR colrec IN SELECT table_schema, table_name, column_name, data_type
FROM information_schema.columns
WHERE table_name = p_table and table_schema = p_schema
ORDER BY ordinal_position
LOOP
selquery := selquery || quote_ident(colrec.column_name) || ',';
selvalue :=
'SELECT CASE WHEN ' || quote_ident(colrec.column_name) || ' IS NULL' ||
' THEN ''NULL''' ||
' ELSE '''' || quote_literal('|| quote_ident(colrec.column_name) || ')::text || ''''' ||
' END' ||
' FROM '||quote_ident(p_schema)||'.'||quote_ident(p_table);
EXECUTE selvalue INTO colvalue;
valquery := valquery || colvalue || ',';
END LOOP;
-- Replace the last , with a )
selquery := substring(selquery,1,length(selquery)-1) || ')';
valquery := substring(valquery,1,length(valquery)-1) || ')';
selquery := selquery || valquery;
RETURN selquery;
END
$BODY$
LANGUAGE plpgsql VOLATILE;
Invoked thus:
SELECT distinct dv_util.gen_insert_statement('pg_temp_' || sess_id::text,'my_data')
from pg_stat_activity
where procpid = pg_backend_pid()
I haven't tested this against injection attacks, please let me know if the quote_literal call isn't sufficient for that.
Also it only works for columns that can be simply cast to ::text and back again.
Also this is for Greenplum but I can't think of a reason why it wouldn't work on Postgres, CMIIW.
I spent the better part of a day struggling without success to get the simplest Spring.NET example working. Could never figure out how to get it to find my assembly from the XML file. In about 2 hours, on the other hand, I was able to get Ninject working, including testing integration with both NUnit and MSTest.
If the above solution does not work for you, try this:
#1.1 Do NOT ignore file pattern in any subdirectory
!*/config.php
#1.2 ...only ignore it in the current directory
/config.php
##########################
# 2.1 Ignore file pattern everywhere
config.php
# 2.2 ...but NOT in the current directory
!/config.php
Ultimately you want to review the datetime documentation and become familiar with the formatting variables, but here are some examples to get you started:
import datetime
print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Date now: %s' % datetime.datetime.now())
print('Date today: %s' % datetime.date.today())
today = datetime.date.today()
print("Today's date is {:%b, %d %Y}".format(today))
schedule = '{:%b, %d %Y}'.format(today) + ' - 6 PM to 10 PM Pacific'
schedule2 = '{:%B, %d %Y}'.format(today) + ' - 1 PM to 6 PM Central'
print('Maintenance: %s' % schedule)
print('Maintenance: %s' % schedule2)
The output:
Timestamp: 2014-10-18 21:31:12
Timestamp: 2014-Oct-18 21:31:12
Date now: 2014-10-18 21:31:12.318340
Date today: 2014-10-18
Today's date is Oct, 18 2014
Maintenance: Oct, 18 2014 - 6 PM to 10 PM Pacific
Maintenance: October, 18 2014 - 1 PM to 6 PM Central
Reference link: https://docs.python.org/3.4/library/datetime.html#strftime-strptime-behavior
You have to put the second div on top of the first one because the both have an z-index of zero so that the order in the dom will decide which is on top. This also affects the relative positioned div because its z-index relates to elements inside the parent div.
<div class="absolute" style="top: 54px"></div>
<div class="absolute">
<div id="relative"></div>
</div>
Css stays the same.
You can use window.location.reload();
in your componentDidMount()
lifecycle method. If you are using react-router
, it has a refresh method to do that.
Edit: If you want to do that after a data update, you might be looking to a re-render
not a reload
and you can do that by using this.setState(). Here is a basic example of it to fire a re-render
after data is fetched.
import React from 'react'
const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const url = `${ROOT_URL}/users`;
class MyComponent extends React.Component {
state = {
users: null
}
componentDidMount() {
fetch(url)
.then(response => response.json())
.then(users => this.setState({users: users}));
}
render() {
const {users} = this.state;
if (users) {
return (
<ul>
{users.map(user => <li>{user.name}</li>)}
</ul>
)
} else {
return (<h1>Loading ...</h1>)
}
}
}
export default MyComponent;
I had a similar problem where the SelectedItem-binding did not update when I selected something in the combobox. My problem was that I had to set UpdateSourceTrigger=PropertyChanged for the binding.
<ComboBox ItemsSource="{Binding SalesPeriods}"
SelectedItem="{Binding SelectedItem, UpdateSourceTrigger=PropertyChanged}" />
hey guys i think what you are looking for is this one using select command. With this you can specify a RANGE GREATER THAN(>) OR LESSER THAN(<) IN MySQL WITH THIS:::::
select* from <**TABLE NAME**> where year(**COLUMN NAME**) > **DATE** OR YEAR(COLUMN NAME )< **DATE**;
FOR EXAMPLE:
select name, BIRTH from pet1 where year(birth)> 1996 OR YEAR(BIRTH)< 1989;
+----------+------------+
| name | BIRTH |
+----------+------------+
| bowser | 1979-09-11 |
| chirpy | 1998-09-11 |
| whistler | 1999-09-09 |
+----------+------------+
FOR SIMPLE RANGE LIKE USE ONLY GREATER THAN / LESSER THAN
mysql> select COLUMN NAME from <TABLE NAME> where year(COLUMN NAME)> 1996;
FOR EXAMPLE mysql>
select name from pet1 where year(birth)> 1996 OR YEAR(BIRTH)< 1989;
+----------+
| name |
+----------+
| bowser |
| chirpy |
| whistler |
+----------+
3 rows in set (0.00 sec)
mylist=['abc','def','ghi','abc']
pattern=re.compile(r'abc')
pattern.findall(mylist)
I wrote a small lib for this. https://www.npmjs.com/package/@inf3rno/promise.exposed
I used the factory method approach others wrote, but I overrode the then
, catch
, finally
methods too, so you can resolve the original promise by those as well.
Resolving Promise without executor from outside:
const promise = Promise.exposed().then(console.log);
promise.resolve("This should show up in the console.");
Racing with the executor's setTimeout from outside:
const promise = Promise.exposed(function (resolve, reject){
setTimeout(function (){
resolve("I almost fell asleep.")
}, 100000);
}).then(console.log);
setTimeout(function (){
promise.resolve("I don't want to wait that much.");
}, 100);
There is a no-conflict mode if you don't want to pollute the global namespace:
const createExposedPromise = require("@inf3rno/promise.exposed/noConflict");
const promise = createExposedPromise().then(console.log);
promise.resolve("This should show up in the console.");
First answer on SO.
I have encountered the same problem and found @alex 's code very helpful. I have made some simple modifications in order to pass in as many parameters as needed through HashMap, and have basically copied parseNetworkResponse()
from StringRequest. I have searched online and so surprised to find out that such a common task is so rarely answered. Anyway, I wish the code could help:
public class MultipartRequest extends Request<String> {
private MultipartEntity entity = new MultipartEntity();
private static final String FILE_PART_NAME = "image";
private final Response.Listener<String> mListener;
private final File file;
private final HashMap<String, String> params;
public MultipartRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener, File file, HashMap<String, String> params)
{
super(Method.POST, url, errorListener);
mListener = listener;
this.file = file;
this.params = params;
buildMultipartEntity();
}
private void buildMultipartEntity()
{
entity.addPart(FILE_PART_NAME, new FileBody(file));
try
{
for ( String key : params.keySet() ) {
entity.addPart(key, new StringBody(params.get(key)));
}
}
catch (UnsupportedEncodingException e)
{
VolleyLog.e("UnsupportedEncodingException");
}
}
@Override
public String getBodyContentType()
{
return entity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
entity.writeTo(bos);
}
catch (IOException e)
{
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
/**
* copied from Android StringRequest class
*/
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
@Override
protected void deliverResponse(String response)
{
mListener.onResponse(response);
}
And you may use the class as following:
HashMap<String, String> params = new HashMap<String, String>();
params.put("type", "Some Param");
params.put("location", "Some Param");
params.put("contact", "Some Param");
MultipartRequest mr = new MultipartRequest(url, new Response.Listener<String>(){
@Override
public void onResponse(String response) {
Log.d("response", response);
}
}, new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Request Error", error.getLocalizedMessage());
}
}, f, params);
Volley.newRequestQueue(this).add(mr);
I rewrote c++ solution in first answer in powershell script. Script can determine this types of .exe and .dll files:
#Description C# compiler switch PE type machine corflags
#MSIL /platform:anycpu (default) PE32 x86 ILONLY
#MSIL 32 bit pref /platform:anycpu32bitpreferred PE32 x86 ILONLY | 32BITREQUIRED | 32BITPREFERRED
#x86 managed /platform:x86 PE32 x86 ILONLY | 32BITREQUIRED
#x86 mixed n/a PE32 x86 32BITREQUIRED
#x64 managed /platform:x64 PE32+ x64 ILONLY
#x64 mixed n/a PE32+ x64
#ARM managed /platform:arm PE32 ARM ILONLY
#ARM mixed n/a PE32 ARM
this solution has some advantages over corflags.exe and loading assembly via Assembly.Load in C# - you will never get BadImageFormatException or message about invalid header.
function GetActualAddressFromRVA($st, $sec, $numOfSec, $dwRVA)
{
[System.UInt32] $dwRet = 0;
for($j = 0; $j -lt $numOfSec; $j++)
{
$nextSectionOffset = $sec + 40*$j;
$VirtualSizeOffset = 8;
$VirtualAddressOffset = 12;
$SizeOfRawDataOffset = 16;
$PointerToRawDataOffset = 20;
$Null = @(
$curr_offset = $st.BaseStream.Seek($nextSectionOffset + $VirtualSizeOffset, [System.IO.SeekOrigin]::Begin);
[System.UInt32] $VirtualSize = $b.ReadUInt32();
[System.UInt32] $VirtualAddress = $b.ReadUInt32();
[System.UInt32] $SizeOfRawData = $b.ReadUInt32();
[System.UInt32] $PointerToRawData = $b.ReadUInt32();
if ($dwRVA -ge $VirtualAddress -and $dwRVA -lt ($VirtualAddress + $VirtualSize)) {
$delta = $VirtualAddress - $PointerToRawData;
$dwRet = $dwRVA - $delta;
return $dwRet;
}
);
}
return $dwRet;
}
function Get-Bitness2([System.String]$path, $showLog = $false)
{
$Obj = @{};
$Obj.Result = '';
$Obj.Error = $false;
$Obj.Log = @(Split-Path -Path $path -Leaf -Resolve);
$b = new-object System.IO.BinaryReader([System.IO.File]::Open($path,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read, [System.IO.FileShare]::Read));
$curr_offset = $b.BaseStream.Seek(0x3c, [System.IO.SeekOrigin]::Begin)
[System.Int32] $peOffset = $b.ReadInt32();
$Obj.Log += 'peOffset ' + "{0:X0}" -f $peOffset;
$curr_offset = $b.BaseStream.Seek($peOffset, [System.IO.SeekOrigin]::Begin);
[System.UInt32] $peHead = $b.ReadUInt32();
if ($peHead -ne 0x00004550) {
$Obj.Error = $true;
$Obj.Result = 'Bad Image Format';
$Obj.Log += 'cannot determine file type (not x64/x86/ARM) - exit with error';
};
if ($Obj.Error)
{
$b.Close();
Write-Host ($Obj.Log | Format-List | Out-String);
return $false;
};
[System.UInt16] $machineType = $b.ReadUInt16();
$Obj.Log += 'machineType ' + "{0:X0}" -f $machineType;
[System.UInt16] $numOfSections = $b.ReadUInt16();
$Obj.Log += 'numOfSections ' + "{0:X0}" -f $numOfSections;
if (($machineType -eq 0x8664) -or ($machineType -eq 0x200)) { $Obj.Log += 'machineType: x64'; }
elseif ($machineType -eq 0x14c) { $Obj.Log += 'machineType: x86'; }
elseif ($machineType -eq 0x1c0) { $Obj.Log += 'machineType: ARM'; }
else{
$Obj.Error = $true;
$Obj.Log += 'cannot determine file type (not x64/x86/ARM) - exit with error';
};
if ($Obj.Error) {
$b.Close();
Write-Output ($Obj.Log | Format-List | Out-String);
return $false;
};
$curr_offset = $b.BaseStream.Seek($peOffset+20, [System.IO.SeekOrigin]::Begin);
[System.UInt16] $sizeOfPeHeader = $b.ReadUInt16();
$coffOffset = $peOffset + 24;#PE header size is 24 bytes
$Obj.Log += 'coffOffset ' + "{0:X0}" -f $coffOffset;
$curr_offset = $b.BaseStream.Seek($coffOffset, [System.IO.SeekOrigin]::Begin);#+24 byte magic number
[System.UInt16] $pe32 = $b.ReadUInt16();
$clr20headerOffset = 0;
$flag32bit = $false;
$Obj.Log += 'pe32 magic number: ' + "{0:X0}" -f $pe32;
$Obj.Log += 'size of optional header ' + ("{0:D0}" -f $sizeOfPeHeader) + " bytes";
#COMIMAGE_FLAGS_ILONLY =0x00000001,
#COMIMAGE_FLAGS_32BITREQUIRED =0x00000002,
#COMIMAGE_FLAGS_IL_LIBRARY =0x00000004,
#COMIMAGE_FLAGS_STRONGNAMESIGNED =0x00000008,
#COMIMAGE_FLAGS_NATIVE_ENTRYPOINT =0x00000010,
#COMIMAGE_FLAGS_TRACKDEBUGDATA =0x00010000,
#COMIMAGE_FLAGS_32BITPREFERRED =0x00020000,
$COMIMAGE_FLAGS_ILONLY = 0x00000001;
$COMIMAGE_FLAGS_32BITREQUIRED = 0x00000002;
$COMIMAGE_FLAGS_32BITPREFERRED = 0x00020000;
$offset = 96;
if ($pe32 -eq 0x20b) {
$offset = 112;#size of COFF header is bigger for pe32+
}
$clr20dirHeaderOffset = $coffOffset + $offset + 14*8;#clr directory header offset + start of section number 15 (each section is 8 byte long);
$Obj.Log += 'clr20dirHeaderOffset ' + "{0:X0}" -f $clr20dirHeaderOffset;
$curr_offset = $b.BaseStream.Seek($clr20dirHeaderOffset, [System.IO.SeekOrigin]::Begin);
[System.UInt32] $clr20VirtualAddress = $b.ReadUInt32();
[System.UInt32] $clr20Size = $b.ReadUInt32();
$Obj.Log += 'clr20VirtualAddress ' + "{0:X0}" -f $clr20VirtualAddress;
$Obj.Log += 'clr20SectionSize ' + ("{0:D0}" -f $clr20Size) + " bytes";
if ($clr20Size -eq 0) {
if ($machineType -eq 0x1c0) { $Obj.Result = 'ARM native'; }
elseif ($pe32 -eq 0x10b) { $Obj.Result = '32-bit native'; }
elseif($pe32 -eq 0x20b) { $Obj.Result = '64-bit native'; }
$b.Close();
if ($Obj.Result -eq '') {
$Obj.Error = $true;
$Obj.Log += 'Unknown type of file';
}
else {
if ($showLog) { Write-Output ($Obj.Log | Format-List | Out-String); };
return $Obj.Result;
}
};
if ($Obj.Error) {
$b.Close();
Write-Host ($Obj.Log | Format-List | Out-String);
return $false;
};
[System.UInt32]$sectionsOffset = $coffOffset + $sizeOfPeHeader;
$Obj.Log += 'sectionsOffset ' + "{0:X0}" -f $sectionsOffset;
$realOffset = GetActualAddressFromRVA $b $sectionsOffset $numOfSections $clr20VirtualAddress;
$Obj.Log += 'real IMAGE_COR20_HEADER offset ' + "{0:X0}" -f $realOffset;
if ($realOffset -eq 0) {
$Obj.Error = $true;
$Obj.Log += 'cannot find COR20 header - exit with error';
$b.Close();
return $false;
};
if ($Obj.Error) {
$b.Close();
Write-Host ($Obj.Log | Format-List | Out-String);
return $false;
};
$curr_offset = $b.BaseStream.Seek($realOffset + 4, [System.IO.SeekOrigin]::Begin);
[System.UInt16] $majorVer = $b.ReadUInt16();
[System.UInt16] $minorVer = $b.ReadUInt16();
$Obj.Log += 'IMAGE_COR20_HEADER version ' + ("{0:D0}" -f $majorVer) + "." + ("{0:D0}" -f $minorVer);
$flagsOffset = 16;#+16 bytes - flags field
$curr_offset = $b.BaseStream.Seek($realOffset + $flagsOffset, [System.IO.SeekOrigin]::Begin);
[System.UInt32] $flag32bit = $b.ReadUInt32();
$Obj.Log += 'CorFlags: ' + ("{0:X0}" -f $flag32bit);
#Description C# compiler switch PE type machine corflags
#MSIL /platform:anycpu (default) PE32 x86 ILONLY
#MSIL 32 bit pref /platform:anycpu32bitpreferred PE32 x86 ILONLY | 32BITREQUIRED | 32BITPREFERRED
#x86 managed /platform:x86 PE32 x86 ILONLY | 32BITREQUIRED
#x86 mixed n/a PE32 x86 32BITREQUIRED
#x64 managed /platform:x64 PE32+ x64 ILONLY
#x64 mixed n/a PE32+ x64
#ARM managed /platform:arm PE32 ARM ILONLY
#ARM mixed n/a PE32 ARM
$isILOnly = ($flag32bit -band $COMIMAGE_FLAGS_ILONLY) -eq $COMIMAGE_FLAGS_ILONLY;
$Obj.Log += 'ILONLY: ' + $isILOnly;
if ($machineType -eq 0x1c0) {#if ARM
if ($isILOnly) { $Obj.Result = 'ARM managed'; }
else { $Obj.Result = 'ARM mixed'; }
}
elseif ($pe32 -eq 0x10b) {#pe32
$is32bitRequired = ($flag32bit -band $COMIMAGE_FLAGS_32BITREQUIRED) -eq $COMIMAGE_FLAGS_32BITREQUIRED;
$is32bitPreffered = ($flag32bit -band $COMIMAGE_FLAGS_32BITPREFERRED) -eq $COMIMAGE_FLAGS_32BITPREFERRED;
$Obj.Log += '32BIT: ' + $is32bitRequired;
$Obj.Log += '32BIT PREFFERED: ' + $is32bitPreffered
if ($is32bitRequired -and $isILOnly -and $is32bitPreffered) { $Obj.Result = 'AnyCpu 32bit-preffered'; }
elseif ($is32bitRequired -and $isILOnly -and !$is32bitPreffered){ $Obj.Result = 'x86 managed'; }
elseif (!$is32bitRequired -and !$isILOnly -and $is32bitPreffered) { $Obj.Result = 'x86 mixed'; }
elseif ($isILOnly) { $Obj.Result = 'AnyCpu'; }
}
elseif ($pe32 -eq 0x20b) {#pe32+
if ($isILOnly) { $Obj.Result = 'x64 managed'; }
else { $Obj.Result = 'x64 mixed'; }
}
$b.Close();
if ($showLog) { Write-Host ($Obj.Log | Format-List | Out-String); }
if ($Obj.Result -eq ''){ return 'Unknown type of file';};
$flags = '';
if ($isILOnly) {$flags += 'ILONLY';}
if ($is32bitRequired) {
if ($flags -ne '') {$flags += ' | ';}
$flags += '32BITREQUIRED';
}
if ($is32bitPreffered) {
if ($flags -ne '') {$flags += ' | ';}
$flags += '32BITPREFERRED';
}
if ($flags -ne '') {$flags = ' (' + $flags +')';}
return $Obj.Result + $flags;
}
usage example:
#$filePath = "C:\Windows\SysWOW64\regedit.exe";#32 bit native on 64bit windows
$filePath = "C:\Windows\regedit.exe";#64 bit native on 64bit windows | should be 32 bit native on 32bit windows
Get-Bitness2 $filePath $true;
you can omit second parameter if you don't need to see details
Try the following:
POJO pojo = mapper.convertValue(singleObject, POJO.class);
or:
List<POJO> pojos = mapper.convertValue(
listOfObjects,
new TypeReference<List<POJO>>() { });
See conversion of LinkedHashMap for more information.
Another possibility for this warning (and, most likely, problems with app behavior) is that the original author of the app relied on session.auto_start
being on (defaults to off)
If you don't want to mess with the code and just need it to work, you can always change php configuration and restart php-fpm (if this is a web app):
/etc/php.d/my-new-file.ini :
session.auto_start = 1
(This is correct for CentOS 8, adjust for your OS/packaging)
in home directory you will find a file called ".vimrc" in that file add this code "set nu" and save and exit and open new vi file and you will find line numbers on that.
always Until you fully understand the differences and implications of using the ==
and ===
operators, use the ===
operator since it will save you from obscure (non-obvious) bugs and WTFs. The "regular" ==
operator can have very unexpected results due to the type-coercion internally, so using ===
is always the recommended approach.
For insight into this, and other "good vs. bad" parts of Javascript read up on Mr. Douglas Crockford and his work. There's a great Google Tech Talk where he summarizes lots of good info: http://www.youtube.com/watch?v=hQVTIJBZook
Update:
The You Don't Know JS series by Kyle Simpson is excellent (and free to read online). The series goes into the commonly misunderstood areas of the language and explains the "bad parts" that Crockford suggests you avoid. By understanding them you can make proper use of them and avoid the pitfalls.
The "Up & Going" book includes a section on Equality, with this specific summary of when to use the loose (==
) vs strict (===
) operators:
To boil down a whole lot of details to a few simple takeaways, and help you know whether to use
==
or===
in various situations, here are my simple rules:
- If either value (aka side) in a comparison could be the
true
orfalse
value, avoid==
and use===
.- If either value in a comparison could be of these specific values (
0
,""
, or[]
-- empty array), avoid==
and use===
.- In all other cases, you're safe to use
==
. Not only is it safe, but in many cases it simplifies your code in a way that improves readability.
I still recommend Crockford's talk for developers who don't want to invest the time to really understand Javascript—it's good advice for a developer who only occasionally works in Javascript.
Select Into functionality only works for PL/SQL Block, when you use Execute immediate , oracle interprets v_query_str as a SQL Query string so you can not use into .will get keyword missing Exception. in example 2 ,we are using begin end; so it became pl/sql block and its legal.
This is something I face regularly, & I've generalised the script Wolfgang provided above to work with any branch
I also added an "are you sure" prompt, & some feedback output
#!/bin/bash
# reset the current repository
# WF 2012-10-15
# AT 2012-11-09
# see http://stackoverflow.com/questions/1628088/how-to-reset-my-local-repository-to-be-just-like-the-remote-repository-head
timestamp=`date "+%Y-%m-%d-%H_%M_%S"`
branchname=`git rev-parse --symbolic-full-name --abbrev-ref HEAD`
read -p "Reset branch $branchname to origin (y/n)? "
[ "$REPLY" != "y" ] ||
echo "about to auto-commit any changes"
git commit -a -m "auto commit at $timestamp"
if [ $? -eq 0 ]
then
echo "Creating backup auto-save branch: auto-save-$branchname-at-$timestamp"
git branch "auto-save-$branchname-at-$timestamp"
fi
echo "now resetting to origin/$branchname"
git fetch origin
git reset --hard origin/$branchname
Include comments if you choose; strip them out with a minifier before parsing or transmitting.
I just released JSON.minify() which strips out comments and whitespace from a block of JSON and makes it valid JSON that can be parsed. So, you might use it like:
JSON.parse(JSON.minify(my_str));
When I released it, I got a huge backlash of people disagreeing with even the idea of it, so I decided that I'd write a comprehensive blog post on why comments make sense in JSON. It includes this notable comment from the creator of JSON:
Suppose you are using JSON to keep configuration files, which you would like to annotate. Go ahead and insert all the comments you like. Then pipe it through JSMin before handing it to your JSON parser. - Douglas Crockford, 2012
Hopefully that's helpful to those who disagree with why JSON.minify() could be useful.
Check out the language reference:
http://msdn.microsoft.com/en-us/library/aa195811(office.11).aspx
expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)
As others have mentioned you have to consume stderr and stdout.
Compared to the other answers, since Java 1.7 it is even more easy. You do not have to create threads yourself anymore to read stderr and stdout.
Just use the ProcessBuilder
and use the methods redirectOutput
in combination with either redirectError
or redirectErrorStream
.
String directory = "/working/dir";
File out = new File(...); // File to write stdout to
File err = new File(...); // File to write stderr to
ProcessBuilder builder = new ProcessBuilder();
builder.directory(new File(directory));
builder.command(command);
builder.redirectOutput(out); // Redirect stdout to file
if(out == err) {
builder.redirectErrorStream(true); // Combine stderr into stdout
} else {
builder.redirectError(err); // Redirect stderr to file
}
Process process = builder.start();
log in as root user:
sudo su
password:
then go and do what you want to do in var/www
You can just use the pipe on its own:
"string1|string2"
for example:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));
Output:
blah, blah, string3
The main reason to use parentheses is to limit the scope of the alternatives:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));
has the same output. but if you just do this:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));
you get:
blah, stringblah, string3
because you've said "string1" or "2".
If you don't want to capture that part of the expression use ?:
:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));
LINQ solution:
// Use the first value in group
var _people = personList
.GroupBy(p => p.FirstandLastName, StringComparer.OrdinalIgnoreCase)
.ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);
// Use the last value in group
var _people = personList
.GroupBy(p => p.FirstandLastName, StringComparer.OrdinalIgnoreCase)
.ToDictionary(g => g.Key, g => g.Last(), StringComparer.OrdinalIgnoreCase);
If you prefer a non-LINQ solution then you could do something like this:
// Use the first value in list
var _people = new Dictionary<string, Person>(StringComparer.OrdinalIgnoreCase);
foreach (var p in personList)
{
if (!_people.ContainsKey(p.FirstandLastName))
_people[p.FirstandLastName] = p;
}
// Use the last value in list
var _people = new Dictionary<string, Person>(StringComparer.OrdinalIgnoreCase);
foreach (var p in personList)
{
_people[p.FirstandLastName] = p;
}
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_query('SET character_set_results=utf8');
mysql_query('SET names=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_results=utf8');
mysql_query('SET collation_connection=utf8_general_ci');
mysql_select_db('onlinetest',$con);
$nith = "CREATE TABLE IF NOT EXISTS `TAMIL` (
`data` varchar(1000) character set utf8 collate utf8_bin default NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1";
if (!mysql_query($nith,$con))
{
die('Error: ' . mysql_error());
}
$nithi = "INSERT INTO `TAMIL` VALUES ('??????? ???????? ?????????')";
if (!mysql_query($nithi,$con))
{
die('Error: ' . mysql_error());
}
$result = mysql_query("SET NAMES utf8");//the main trick
$cmd = "select * from TAMIL";
$result = mysql_query($cmd);
while($myrow = mysql_fetch_row($result))
{
echo ($myrow[0]);
}
?>
</body>
</html>
I was facing the same issue for one of my PhoneGap project (Android studio 3.0.1). To resolve this I have followed, the following step
1) Right click on Project name (In my Case android), select "Open Module Settings"
2) Select modules (android and CordovaLib)
3) Click properties on top
4) Chose Compile SDK version (I have chosen API 26: Android 8.0 )
5) Choose Build Tools Version (I have chosen 26.0.2)
6) Source Compatibility ( 1.6)
7) Target Compatibility ( 1.6)
Click Ok and rebuild project.
The following link shows my setting for step I have followed
https://app.box.com/s/o11xc8dy0c2c7elsaoppa0kwe1d94ogh https://app.box.com/s/ofdcg0a8n0zalumvpyju58he402ag1th
These are terms usually used when describing a "FIFO" queue, that is "first in, first out". This works like a line. You decide to go to the movies. There is a long line to buy tickets, you decide to get into the queue to buy tickets, that is "Enqueue". at some point you are at the front of the line, and you get to buy a ticket, at which point you leave the line, that is "Dequeue".
Simply in one line:
var result = table.First(x => x.Status == table.Max(y => y.Status));
Notice that there are two action. the inner action is for finding the max value, the outer action is for get the desired object.
In regards to veggerby's solution, if you are trying to implement it on a VB app, be careful trying to run the supplied code through a translator. The following will work:
Imports System.Web
Imports System.Web.Services
Imports System.Web.SessionState
Public Class SessionHeartbeatHttpHandler
Implements IHttpHandler
Implements IRequiresSessionState
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Session("Heartbeat") = DateTime.Now
End Sub
End Class
Also, instead of calling like heartbeat() function like:
setTimeout("heartbeat()", 300000);
Instead, call it like:
setInterval(function () { heartbeat(); }, 300000);
Number one, setTimeout only fires once whereas setInterval will fire repeatedly. Number two, calling heartbeat() like a string didn't work for me, whereas calling it like an actual function did.
And I can absolutely 100% confirm that this solution will overcome GoDaddy's ridiculous decision to force a 5 minute apppool session in Plesk!
it is compatible with all the browsers, change values to fit your application
background: #fdfdfd;
background: -moz-linear-gradient(top, #fdfdfd 0%, #f6f6f6 60%, #f2f2f2 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fdfdfd), color-stop(60%,#f6f6f6), color-stop(100%,#f2f2f2));
background: -webkit-linear-gradient(top, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
background: -o-linear-gradient(top, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
background: -ms-linear-gradient(top, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
background: linear-gradient(to bottom, #fdfdfd 0%,#f6f6f6 60%,#f2f2f2 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fdfdfd', endColorstr='#f2f2f2',GradientType=0
Buttons like <button>Click to do something</button>
are submit buttons.
You must add type
You definitely need to put in the column order, otherwise how is SQL Server supposed to know which one goes first? Here's what you would need to do in your code:
public class MyTable
{
[Key, Column(Order = 0)]
public string SomeId { get; set; }
[Key, Column(Order = 1)]
public int OtherId { get; set; }
}
You can also look at this SO question. If you want official documentation, I would recommend looking at the official EF website. Hope this helps.
EDIT: I just found a blog post from Julie Lerman with links to all kinds of EF 6 goodness. You can find whatever you need here.
Set WorkingDirectory or specify the full path of the python script in the Argument
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "C:\\Python27\\python.exe";
//start.WorkingDirectory = @"D:\script";
start.Arguments = string.Format("D:\\script\\test.py -a {0} -b {1} ", "some param", "some other param");
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
Misconception Common misconception with column ordering is that, I should (or could) do the pushing and pulling on mobile devices, and that the desktop views should render in the natural order of the markup. This is wrong.
Reality Bootstrap is a mobile first framework. This means that the order of the columns in your HTML markup should represent the order in which you want them displayed on mobile devices. This mean that the pushing and pulling is done on the larger desktop views. not on mobile devices view..
Brandon Schmalz - Full Stack Web Developer Have a look at full description here
In my case it was due to 'lower_case_table_names' parameter.
The error number 39 thrown out when I tried to drop the databases which consists upper case table names with lower_case_table_names parameter is enabled.
This is fixed by reverting back the lower case parameter changes to the previous state.
This behaviour is terminal-specific and specified by the terminal emulator you use (e.g. xterm
) and the semantics of terminal that it provides. The terminal behaviour has been very stable for the last 20 years, and you can reasonably rely on the semantics of \b
.
This is a stab in the dark, but maybe do you need to wrap your JSON arguments; like say something like this:
data: "{'Ids':[{'Id1':'2'},{'Id2':'2'}]}"
Make sure your JSON is properly formed?
Is it that
success()
returns earlier thancomplete()
?
Yes; the AJAX success()
method runs before the complete()
method.
Below is a diagram illustrating the process flow:
It is important to note that
The success()
(Local Event) is only called if the request was successful (no errors from the server, no errors with the data).
On the other hand, the complete()
(Local Event) is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.
... more details on AJAX Events here.
If you have a class on your element, then you can try the following:
if( $('.exists_content').hasClass('exists_content') ){
//element available
}
I wanted to do the same, and I had first problems with the split function, then problems with installing pandas 0.15.2, so I went back to my old version, and wrote a little function that works very well. I hope this can help!
# input - df: a Dataframe, chunkSize: the chunk size
# output - a list of DataFrame
# purpose - splits the DataFrame into smaller chunks
def split_dataframe(df, chunk_size = 10000):
chunks = list()
num_chunks = len(df) // chunk_size + 1
for i in range(num_chunks):
chunks.append(df[i*chunk_size:(i+1)*chunk_size])
return chunks
You need to tell it that you are using SSL:
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
In case you miss anything, here is working code:
String d_email = "[email protected]",
d_uname = "Name",
d_password = "urpassword",
d_host = "smtp.gmail.com",
d_port = "465",
m_to = "[email protected]",
m_subject = "Indoors Readable File: " + params[0].getName(),
m_text = "This message is from Indoor Positioning App. Required file(s) are attached.";
Properties props = new Properties();
props.put("mail.smtp.user", d_email);
props.put("mail.smtp.host", d_host);
props.put("mail.smtp.port", d_port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SMTPAuthenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
try {
msg.setSubject(m_subject);
msg.setFrom(new InternetAddress(d_email));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
Transport transport = session.getTransport("smtps");
transport.connect(d_host, Integer.valueOf(d_port), d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (AddressException e) {
e.printStackTrace();
return false;
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
I have same problem. I solved install this setup. (I use vs 2015 (4.6))
Additional to the above - the QEMU website has good documentation about setting up an ARM based emulator: http://qemu.weilnetz.de/qemu-doc.html#ARM-System-emulator
Get First Day of Last Month
Select ADDDATE(LAST_DAY(ADDDATE(now(), INTERVAL -2 MONTH)), INTERVAL 1 DAY);
Get Last Day of Last Month
Select LAST_DAY(ADDDATE(now(), INTERVAL -1 MONTH));
For any CSS3-enabled browser you can use an adjacent sibling selector for styling your labels
input:checked + label {
color: white;
}
MDN's browser compatibility table says essentially all of the current, popular browsers (Chrome, IE, Firefox, Safari), on both desktop and mobile, are compatible.
Here's a list of all the ways I could think of to counting unique elements:
M = randi([1 7], [1500 1]);
t = tabulate(M);
counts1 = t(t(:,2)~=0, 2);
counts2_1 = hist( M, numel(unique(M)) );
counts2_2 = histc( M, unique(M) );
counts3 = accumarray(M, ones(size(M)), [], @sum);
%# or simply: accumarray(M, 1);
[MM idx] = unique( sort(M) );
counts4 = diff([0;idx]);
counts5 = arrayfun( @(x)sum(M==x), unique(M) );
counts6 = sum( bsxfun(@eq, M, unique(M)') )';
counts7 = full(sparse(M,1,1));
You need to go through SimpleDateFormat.format
in order to format the date as a string.
Here's an example that goes from String
-> Date
-> String
.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("31/05/2011");
System.out.println(dateFormat.format(date)); // prints 31/05/2011
// ^^^^^^
So you can use the following :
td {
white-space: normal !important; // To consider whitespace.
}
If this doesn't work:
td {
white-space: normal !important;
word-wrap: break-word;
}
table {
table-layout: fixed;
}
//Here pdate is the string date time
var date1=GetDate(pdate);
function GetDate(a){
var dateString = a.substr(6);
var currentTime = new Date(parseInt(dateString ));
var month =("0"+ (currentTime.getMonth() + 1)).slice(-2);
var day =("0"+ currentTime.getDate()).slice(-2);
var year = currentTime.getFullYear();
var date = day + "/" + month + "/" + year;
return date;
}
This is tricky here. In my case, the folder structure was:
com/appName/rateUS/models/FileName.java
The package name, which I had specified in the file FileName.java was:
package com.appName.rateUs.models;
Notice the subtle difference between the package name: it should have been rateUS instead of rateUs
Hope this helps someone!
def prime(x):
# check that number is greater that 1
if x > 1:
for i in range(2, x + 1):
# check that only x and 1 can evenly divide x
if x % i == 0 and i != x and i != 1:
return False
else:
return True
else:
return False # if number is negative
Hello there: If you need more control on where the link should redirect to, you could use this solution.
Ie. If the user is clicking in the CHECKOUT link, but you want to send him/her to checkout page if its registered(logged in) or registration page if he/she isn't.
You could use JSTL core LIKE:
<!--include the library-->
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<%--create a var to store link--%>
<core:set var="linkToRedirect">
<%--test the condition you need--%>
<core:choose>
<core:when test="${USER IS REGISTER}">
checkout.jsp
</core:when>
<core:otherwise>
registration.jsp
</core:otherwise>
</core:choose>
</core:set>
EXPLAINING: is the same as...
//pseudo code
if(condition == true)
set linkToRedirect = checkout.jsp
else
set linkToRedirect = registration.jsp
THEN: in simple HTML...
<a href="your.domain.com/${linkToRedirect}">CHECKOUT</a>
during train test split you might have done a mistake
x_train,x_test,y_train,y_test=sklearn.model_selection.train_test_split(X,Y,test_size)
The above code is correct
You might have done like below which is wrong
x_train,y_train,x_test,y_test=sklearn.model_selection.train_test_split(X,Y,test_size)
if you need a unique global temp table, create your own with a Uniqueidentifier Prefix/Suffix and drop post execution if an if object_id(.... The only drawback is using Dynamic sql and need to drop explicitly.
>>> chr(97)
'a'
>>> ord('a')
97
In MacOS Mojave, the location is:
/Library/Java/JavaVirtualMachines/jdk1.8.0_192.jdk/Contents/Home/jre/lib/security/cacerts
If using sdkman to manage java versions, the cacerts is in
~/.sdkman/candidates/java/current/jre/lib/security
TL;DR: You should add a JProperty to a JObject. Simple. The index query returns a JValue, so figure out how to get the JProperty instead :)
The accepted answer is not answering the question as it seems. What if I want to specifically add a JProperty after a specific one? First, lets start with terminologies which really had my head worked up.
"name":"value"
.Now, when you query Json item using the index [], you are getting the JToken without the identifier, which might be a JContainer or a JValue (requires casting), but you cannot add anything after it, because it is only a value. You can change it itself, query more deep values, but you cannot add anything after it for example.
What you actually want to get is the property as whole, and then add another property after it as desired. For this, you use JOjbect.Property("name")
, and then create another JProperty of your desire and then add it after this using AddAfterSelf
method. You are done then.
For more info: http://www.newtonsoft.com/json/help/html/ModifyJson.htm
This is the code I modified.
public class Program
{
public static void Main()
{
try
{
string jsonText = @"
{
""food"": {
""fruit"": {
""apple"": {
""colour"": ""red"",
""size"": ""small""
},
""orange"": {
""colour"": ""orange"",
""size"": ""large""
}
}
}
}";
var foodJsonObj = JObject.Parse(jsonText);
var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");
var fruitJObject = foodJsonObj["food"]["fruit"] as JObject;
fruitJObject.Property("orange").AddAfterSelf(new JProperty("banana", fruitJObject));
Console.WriteLine(foodJsonObj.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
}
}
}
You could also use default
argument for example:
def myconverter(o):
if isinstance(o, np.float32):
return float(o)
json.dump(data, default=myconverter)
toast is a bad idea, it's far too "complex" to print the value of a variable. use log or s.o.p, and as drawnonward already said, their output goes to logcat. it only makes sense if you want to expose this information to the end-user...
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
String jsonText = readAll(inputofyourjsonstream);
JSONObject json = new JSONObject(jsonText);
JSONArray arr = json.getJSONArray("Compemployes");
Your arr would looks like: [ { "id":1001, "name":"jhon" }, { "id":1002, "name":"jhon" } ] You can use:
arr.getJSONObject(index)
to get the objects inside of the array.
If you are using select as inline to other component, then you can also use like given below.
<select onChange={(val) => this.handlePeriodChange(val.target.value)} className="btn btn-sm btn-outline-secondary dropdown-toggle">
<option value="TODAY">Today</option>
<option value="THIS_WEEK" >This Week</option>
<option value="THIS_MONTH">This Month</option>
<option value="THIS_YEAR">This Year</option>
<option selected value="LAST_AVAILABLE_DAY">Last Availabe NAV Day</option>
</select>
And on the component where select is used, define the function to handle onChange like below:
handlePeriodChange(selVal) {
this.props.handlePeriodChange(selVal);
}
Have you tried to increase output_buffering in your php.ini?
if( char.toUpperCase() != char.toLowerCase() )
Will return true only in case of letter
As point out in below comment, if your character is non English, High Ascii or double byte range then you need to add check for code point.
if( char.toUpperCase() != char.toLowerCase() || char.codePointAt(0) > 127 )
Go into the mysql data directory and run du -h --max-depth=1 | grep databasename
The only three literal characters which are treated specially in the replace clause are /
(to close the clause), \
(to escape characters, backreference, &c.), and &
(to include the match in the replacement). Therefore, all you need to do is escape those three characters:
sed "s/KEYWORD/$(echo $REPLACE | sed -e 's/\\/\\\\/g; s/\//\\\//g; s/&/\\\&/g')/g"
Example:
$ export REPLACE="'\"|\\/><&!"
$ echo fooKEYWORDbar | sed "s/KEYWORD/$(echo $REPLACE | sed -e 's/\\/\\\\/g; s/\//\\\//g; s/&/\\\&/g')/g"
foo'"|\/><&!bar
My favorite method to use would be the BorderLayout method. Here are the five examples with each position the component could go in. The example is for if the component were a button. We will add it to a JPanel, p. The button will be called b.
//To align it to the left
p.add(b, BorderLayout.WEST);
//To align it to the right
p.add(b, BorderLayout.EAST);
//To align it at the top
p.add(b, BorderLayout.NORTH);
//To align it to the bottom
p.add(b, BorderLayout.SOUTH);
//To align it to the center
p.add(b, BorderLayout.CENTER);
Don't forget to import it as well by typing:
import java.awt.BorderLayout;
There are also other methods in the BorderLayout class involving things like orientation, but you can do your own research on that if you curious about that. I hope this helped!
Thanks - your suggestion about $JAVA_HOME
lead me to a similar solution:
prompt$ unset JAVA_HOME
before invoking R.
/
means the root of the current drive;
./
means the current directory;
../
means the parent of the current directory.
Not sure if you found an answer but I had this problem and needed to upgrade TLS version to 1.2
private HttpsURLConnection getSSlConnection(String url, String username, String password){
SSLContext sc = SSLContext.getInstance("TLSv1.2")
// Create a trust manager that accepts all SSL sites
TrustManager[] trustAllCerts = new TrustManager[1]
def tm = new X509TrustManager(){
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0]
}
}
trustAllCerts[0] = tm
sc.init(null, trustAllCerts, new SecureRandom())
HttpsURLConnection connection = (HttpsURLConnection) getConnection(url, username, password)
connection.setSSLSocketFactory(sc.getSocketFactory())
return connection
}
To surpass samthebest and the contributors before him, I have improved the naming and conciseness:
def using[A <: {def close() : Unit}, B](resource: A)(f: A => B): B =
try f(resource) finally resource.close()
def writeStringToFile(file: File, data: String, appending: Boolean = false) =
using(new FileWriter(file, appending))(_.write(data))
As I can see the array is of String only.For each loop can be used to get individual element of the array and put them in local inner class for use.
Below is the code snippet for it :
//WorkAround
for (String color : colors ){
String pos = Character.toUpperCase(color.charAt(0)) + color.substring(1);
JMenuItem Jmi =new JMenuItem(pos);
Jmi.setIcon(new IconA(color));
Jmi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JMenuItem item = (JMenuItem) e.getSource();
IconA icon = (IconA) item.getIcon();
// HERE YOU USE THE String color variable and no errors!!!
Color kolorIkony = getColour(color);
textArea.setForeground(kolorIkony);
}
});
mnForeground.add(Jmi);
}
}
Other answers already show that you can use split() to get the values into a list. If you were asking about Python's arrays, here is one solution:
import array
s = '42 0'
a = array.array('i')
for n in s.split():
a.append(int(n))
Edit: A more concise solution:
import array
s = '42 0'
a = array.array('i', (int(t) for t in s.split()))
var firstFiveItems = myList.Take(5);
Or to slice:
var secondFiveItems = myList.Skip(5).Take(5);
And of course often it's convenient to get the first five items according to some kind of order:
var firstFiveArrivals = myList.OrderBy(i => i.ArrivalTime).Take(5);
You've got what rebase
does backwards. git rebase master
does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master
, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master
on top of the current branch.
In SQL Server 2017 STRING_AGG is added:
SELECT t.name,STRING_AGG (c.name, ',') AS csv
FROM sys.tables t
JOIN sys.columns c on t.object_id = c.object_id
GROUP BY t.name
ORDER BY 1
Also, STRING_SPLIT is usefull for the opposite case and available in SQL Server 2016
What you're looking for is date --date='06/12/2012 07:21:22' +"%s"
. Keep in mind that this assumes you're using GNU coreutils, as both --date
and the %s
format string are GNU extensions. POSIX doesn't specify either of those, so there is no portable way of making such conversion even on POSIX compliant systems.
Consult the appropriate manual page for other versions of date
.
Note: bash --date
and -d
option expects the date in US or ISO8601 format, i.e. mm/dd/yyyy
or yyyy-mm-dd
, not in UK, EU, or any other format.
Just do this:
import pandas as pd
import pyodbc
cnxn = pyodbc.connect("Driver={SQL Server}\
;Server=SERVER_NAME\
;Database=DATABASE_NAME\
;Trusted_Connection=yes")
df = pd.read_sql("SELECT * FROM myTableName", cnxn)
df.head()
var str = '[basic_salary]+100/[basic_salary]';
var arr = str.split('');
var myArr = [];
for(var i=0;i<arr.length;i++){
if(arr[i] == '['){
var a = '';
for(var j=i+1;j<arr.length;j++){
if(arr[j] == ']'){
var i = j-1;
break;
}else{
a += arr[j];
}
}
myArr.push(a);
}
var operatorsArr = ['+','-','*','/','%'];
if(operatorsArr.includes(arr[i])){
myArr.push(arr[i]);
}
var numbArr = ['0','1','2','3','4','5','6','7','8','9'];
if(numbArr.includes(arr[i])){
var a = '';
for(var j=i;j<arr.length;j++){
if(numbArr.includes(arr[j])){
a += arr[j];
}else{
var i = j-1;
break;
}
}
myArr.push(a);
}
}
myArr = ["basic_salary", "+", "100", "/", "basic_salary"]
While compiling in RHEL 6.2 (x86_64), I installed both 32bit and 64bit libstdc++-dev packages, but I had the "c++config.h no such file or directory" problem.
Resolution:
The directory /usr/include/c++/4.4.6/x86_64-redhat-linux
was missing.
I did the following:
cd /usr/include/c++/4.4.6/
mkdir x86_64-redhat-linux
cd x86_64-redhat-linux
ln -s ../i686-redhat-linux 32
I'm now able to compile 32bit binaries on a 64bit OS.
Try following code to get count of files in the folder
string strDocPath = Server.MapPath('Enter your path here');
int docCount = Directory.GetFiles(strDocPath, "*",
SearchOption.TopDirectoryOnly).Length;
Make the code say if (msg.content === ('trigger') msg.author.send('text')}
When you write x = 0
, x
is an int...so you can't do x[age1]
because x
is int
Why you are using row.Cells[row.Index]. You need to specify index of column you want to search (Problem #2). For example, you need to change row.Cells[row.Index] to row.Cells[2] where 2 is index of your column:
private void btnSearch_Click(object sender, EventArgs e)
{
string searchValue = textBox1.Text;
dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
foreach (DataGridViewRow row in dgvProjects.Rows)
{
if (row.Cells[2].Value.ToString().Equals(searchValue))
{
row.Selected = true;
break;
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
I have adapted the answer from @Alex above and wrote the following to fix the code for Java 9.
$ cat ~/.jdk
#!/bin/bash
#list available jdks
alias jdks="/usr/libexec/java_home -V"
# jdk version switching - e.g. `jdk 6` will switch to version 1.6
function jdk() {
echo "Switching java version $1";
requestedVersion=$1
oldStyleVersion=8
# Set the version
if [ $requestedVersion -gt $oldStyleVersion ]; then
export JAVA_HOME=$(/usr/libexec/java_home -v $1);
else
export JAVA_HOME=`/usr/libexec/java_home -v 1.$1`;
fi
echo "Setting JAVA_HOME=$JAVA_HOME"
which java
java -version;
}
$ jdk 8
Switching java version 8
Setting JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home
/usr/bin/java
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
$ jdk 9
Switching java version 9
Setting JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home
/usr/bin/java
java version "9.0.1"
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)
A complete example for scripted pipepline:
stage('Build'){
withEnv(["GOPATH=/ws","PATH=/ws/bin:${env.PATH}"]) {
sh 'bash build.sh'
}
}
You can use AudioStream this way as well:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
public class AudioWizz extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L; //you like your cereal and the program likes their "serial"
static AudioWizz a;
static JButton playBuddon;
static JFrame frame;
public static void main(String arguments[]){
frame= new JFrame("AudioWizz");
frame.setSize(300,300);
frame.setVisible(true);
a= new AudioWizz();
playBuddon= new JButton("PUSH ME");
playBuddon.setBounds(10,10,80,30);
playBuddon.addActionListener(a);
frame.add(playBuddon);
frame.add(a);
}
public void actionPerformed(ActionEvent e){ //an eventListener
if (e.getSource() == playBuddon) {
try {
InputStream in = new FileInputStream("*.wav");
AudioStream sound = new AudioStream(in);
AudioPlayer.player.start(sound);
} catch(FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
It worked for = I just removed "archetypes" folder from below location
C:\Users\Lenovo.m2\repository\org\apache\maven
But you may change following for experiment - download latest binary zip of Maven, add to you C:\ drive and change following....
Change Proxy
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username></username>
<password></password>
<host>10.23.73.253</host>
<port>8080</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
Giphy Gotcha
After following the 2 requirements listed above (must end in .gif
and using the image syntax), if you are having trouble with a gif from giphy:
Be sure you have the correct giphy url! You can't just add .gif
to the end of this one and have it work.
If you just copy the url from a browser, you will get something like:
https://giphy.com/gifs/gol-automaton-game-of-life-QfsvYoBSSpfbtFJIVo
You need to instead click on "Copy Link" and then grab the "GIF Link" specifically. Notice the correct one points to media.giphy.com
instead of just giphy.com
:
cmd.Parameters.Add(String parameterName, Object value)
is deprecated now. Instead use cmd.Parameters.AddWithValue(String parameterName, Object value)
There is no difference in terms of functionality. The reason they deprecated the
cmd.Parameters.Add(String parameterName, Object value)
in favor ofAddWithValue(String parameterName, Object value)
is to give more clarity. Here is the MSDN reference for the same
private void button1_Click(object sender, EventArgs e) {
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
cmd.Parameters.AddWithValue("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.
I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"s","l","m"}, {-1,1,0})
and it started working when I did this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"l","m","s"}, {1,0,-1})
I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.
Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.
you can append the file with >> sign. It insert the contents at the last of the file which we are using.e.g if file let its name is myfile contains xyz then cat >> myfile abc ctrl d
after the above process the myfile contains xyzabc.
Try this code in jquery
$(document).ready(function(){
$("a").click(function(){
var id=$(this).attr('href');
var value=$(id).text();
$(".target").text(value);
});
});
In case someone is using ASP.NET Core for model binding,
https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding
There's is built in support for retrieving values from the header using the [FromHeader] attribute
public string Test([FromHeader]string Host, [FromHeader]string Content-Type )
{
return $"Host: {Host} Content-Type: {Content-Type}";
}
From this post:
To get the entire PC CPU and Memory usage:
using System.Diagnostics;
Then declare globally:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Processor", "% Processor Time", "_Total");
Then to get the CPU time, simply call the NextValue()
method:
this.theCPUCounter.NextValue();
This will get you the CPU usage
As for memory usage, same thing applies I believe:
private PerformanceCounter theMemCounter =
new PerformanceCounter("Memory", "Available MBytes");
Then to get the memory usage, simply call the NextValue()
method:
this.theMemCounter.NextValue();
For a specific process CPU and Memory usage:
private PerformanceCounter theCPUCounter =
new PerformanceCounter("Process", "% Processor Time",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
private PerformanceCounter theMemCounter =
new PerformanceCounter("Process", "Working Set",
Process.GetCurrentProcess().ProcessName);
where Process.GetCurrentProcess().ProcessName
is the process name you wish to get the information about.
Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?
To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters
The difference between Processor\% Processor Time
and Process\% Processor Time
is Processor
is from the PC itself and Process
is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters
An alternative to using the Performance Counter
Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.
As you've figured out, Entity Framework can't actually run your C# code as part of its query. It has to be able to convert the query to an actual SQL statement. In order for that to work, you will have to restructure your query expression into an expression that Entity Framework can handle.
public System.Linq.Expressions.Expression<Func<Charity, bool>> IsSatisfied()
{
string name = this.charityName;
string referenceNumber = this.referenceNumber;
return p =>
(string.IsNullOrEmpty(name) ||
p.registeredName.ToLower().Contains(name.ToLower()) ||
p.alias.ToLower().Contains(name.ToLower()) ||
p.charityId.ToLower().Contains(name.ToLower())) &&
(string.IsNullOrEmpty(referenceNumber) ||
p.charityReference.ToLower().Contains(referenceNumber.ToLower()));
}
You are getting Floating point exception because Number % i
, when i
is 0
:
int Is_Prime( int Number ){
int i ;
for( i = 0 ; i < Number / 2 ; i++ ){
if( Number % i != 0 ) return -1 ;
}
return Number ;
}
Just start the loop at i = 2
. Since i = 1
in Number % i
it always be equal to zero, since Number is a int.
Now we can! As this is the first result on google, I thought I'd update this to the latest standing. With the advent of git 1.7.9.5, we have the git archive
command which will allow you to retrieve a single file from a remote host.
git archive --remote=git://git.foo.com/project.git HEAD:path/in/repo filename | tar -x
See answer in full here https://stackoverflow.com/a/5324532/290784
Use this command for Angular 6 to build
ng build --prod --configuration=dev
Ok so the key for me was to use the .FlattenHierarchy BindingFlag. I don't really know why I just added it on a hunch and it started working. So the final solution that allows me to get Public Instance or Static Properties is:
obj.GetType.GetProperty(propName, Reflection.BindingFlags.Public _
Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or _
Reflection.BindingFlags.FlattenHierarchy)
You can use a third party library, such as PSI:
PSI is a Python package providing real-time access to processes and other miscellaneous system information such as architecture, boottime and filesystems. It has a pythonic API which is consistent accross all supported platforms but also exposes platform-specific details where desirable.
why not just pass an data an object with your key/value pairs then you don't have to worry about encoding
$.ajax({
type: "Post",
url: "getdata.php",
data:{
timestamp: timestamp,
uid: id,
uname: name
},
async: true,
cache: false,
success: function(data) {
};
}?);?
My instance of this problem ended up being a missing reference. An assembly was referred to in the app.config but didn't have a reference in the project.
Post build event for Visual Studio
echo >RevisionNumber.cs static class Git { public static int RevisionNumber =
git >>RevisionNumber.cs rev-list --count HEAD
echo >>RevisionNumber.cs ; }
For Eclipse Users. If you have a Run Configuration that does clean package for example.
In the Run Configuration panel there is a JRE tab where you can specify against which runtime it should run. Note that this configuration overrides whatever is in the pom.xml.
The kernel space means a memory space can only be touched by kernel. On 32bit linux it is 1G(from 0xC0000000 to 0xffffffff as virtual memory address).Every process created by kernel is also a kernel thread, So for one process, there are two stacks: one stack in user space for this process and another in kernel space for kernel thread.
the kernel stack occupied 2 pages(8k in 32bit linux), include a task_struct(about 1k) and the real stack(about 7k). The latter is used to store some auto variables or function call params or function address in kernel functions. Here is the code(Processor.h (linux\include\asm-i386)):
#define THREAD_SIZE (2*PAGE_SIZE)
#define alloc_task_struct() ((struct task_struct *) __get_free_pages(GFP_KERNEL,1))
#define free_task_struct(p) free_pages((unsigned long) (p), 1)
__get_free_pages(GFP_KERNEL,1)) means alloc memory as 2^1=2 pages.
But the process stack is another thing, its address is just bellow 0xC0000000(32bit linux), the size of it can be quite bigger, used for the user space function calls.
So here is a question come for system call, it is running in kernel space but was called by process in user space, how does it work? Will linux put its params and function address in kernel stack or process stack? Linux's solution: all system call are triggered by software interruption INT 0x80. Defined in entry.S (linux\arch\i386\kernel), here is some lines for example:
ENTRY(sys_call_table)
.long SYMBOL_NAME(sys_ni_syscall) /* 0 - old "setup()" system call*/
.long SYMBOL_NAME(sys_exit)
.long SYMBOL_NAME(sys_fork)
.long SYMBOL_NAME(sys_read)
.long SYMBOL_NAME(sys_write)
.long SYMBOL_NAME(sys_open) /* 5 */
.long SYMBOL_NAME(sys_close)
Try my way :
robocopy.exe "Desktop\Test folder 1" "Desktop\Test folder 2" /XD "C:\Users\Steve\Desktop\Test folder 2\XXX dont touch" /MIR
Had to put /XD
before /MIR
while including the full Destination Source directly after /XD
.
Alternative: Use a generic HTTP handler (.ashx) and use your favorite json library to manually serialize and deserialize your JSON.
I've found that complete control over the handling of a request and generating a response beats anything else .NET offers for simple, RESTful web services.
But in my opinion one important thing.
The "char(number)" it's lenght of variable.
If we've got table with "Names" like for example [Test1..Test200] and we declare char(5) in SELECT like:
DECLARE @variable char(5)
SET @variable = 'Test1%'
SELECT * FROM table WHERE Name like @variable
the result will be only - "Test1"! (char(5) - 5 chars in lenght; Test11 is 6 )
The rest of potential interested data like [Test11..Test200] will not be returned in the result.
It's ok if we want to limit the SELECT by this way. But if it's not intentional way of doing it could return incorrect results from planned ( Like "all Names begining with Test1..." ).
In my opinion if we don't know the precise lenght of a SELECTed value, a better solution could be something like this one:
DECLARE @variable varchar(max)
SET @variable = 'Test1%'
SELECT * FROM <table> WHERE variable1 like @variable
This returns (Test1 but also Test11..Test19 and Test100..Test199).
Edit: Thanks Marc, read up on the struct vs class issue and you're right, thank you!
I tend to use the following method for doing what you describe, using a static method of JSon.Net:
MyObject deserializedObject = JsonConvert.DeserializeObject<MyObject>(json);
Link: Serializing and Deserializing JSON with Json.NET
For the Objects list, may I suggest using generic lists out made out of your own small class containing attributes
and position
class. You can use the Point
struct in System.Drawing
(System.Drawing.Point
or System.Drawing.PointF
for floating point numbers) for you X and Y.
After object creation it's much easier to get the data you're after vs. the text parsing you're otherwise looking at.
Set<T> mySet = new HashSet<T>();
Collections.addAll(mySet, myArray);
That's Collections.addAll(java.util.Collection, T...) from JDK 6.
Additionally: what if our array is full of primitives?
For JDK < 8, I would just write the obvious for
loop to do the wrap and add-to-set in one pass.
For JDK >= 8, an attractive option is something like:
Arrays.stream(intArray).boxed().collect(Collectors.toSet());
Should be
<input type="button" class="btn btn-success"
style="font-weight: bold;display: inline;"
value="Close"
onclick="closeMe()">
<script>
function closeMe()
{
window.opener = self;
window.close();
}
</script>
SELECT *
FROM
(
SELECT * FROM TABLE_A
UNION ALL
SELECT * FROM TABLE_B
) dum
-- ORDER BY .....
but if you want to have all records from Table_A
on the top of the result list, the you can add user define value which you can use for ordering,
SELECT *
FROM
(
SELECT *, 1 sortby FROM TABLE_A
UNION ALL
SELECT *, 2 sortby FROM TABLE_B
) dum
ORDER BY sortby
According to Yashu's instructions, I wrote the following function (it's PL/SQL code, but it should be easily adaptable to any other language).
FUNCTION field(str IN VARCHAR2) RETURN VARCHAR2 IS
C_NEWLINE CONSTANT CHAR(1) := '
'; -- newline is intentional
v_aux VARCHAR2(32000);
v_has_double_quotes BOOLEAN;
v_has_comma BOOLEAN;
v_has_newline BOOLEAN;
BEGIN
v_has_double_quotes := instr(str, '"') > 0;
v_has_comma := instr(str,',') > 0;
v_has_newline := instr(str, C_NEWLINE) > 0;
IF v_has_double_quotes OR v_has_comma OR v_has_newline THEN
IF v_has_double_quotes THEN
v_aux := replace(str,'"','""');
ELSE
v_aux := str;
END IF;
return '"'||v_aux||'"';
ELSE
return str;
END IF;
END;
You can use Thread.getCurrentThread.getId(), but why would you want to do that when LogRecord objects managed by the logger already have the thread Id. I think you are missing a configuration somewhere that logs the thread Ids for your log messages.
try below:
var temp_datetime_obj = new Date();
collection.find({
start_date:{
$gte: new Date(temp_datetime_obj.toISOString())
}
}).toArray(function(err, items) {
/* you can console.log here */
});
When I had an error Access Error: 404 -- Not Found
I fixed it by doing the following:
8080
and look at its PID
number/code.PID
number. Then right click it and stop the process.Considering the question's environment.
And quoting from: http://php.net/manual/en/function.mkdir.php
bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = FALSE [, resource $context ]]] )
Manual says that the only required parameter is the $pathname
!
so, We can simply code:
<?php
error_reporting(0);
if(!mkdir('wp-content/uploads')){
// todo
}
?>
We don't have to pass any parameter or check if folder exists or even pass mode parameter unless needed; for the following reasons:
mode
is ignored on Windows Hosting running PHP.mkdir
command has build in checker if folder exists; so we need to check the return only True|False ; and its not an error, its a warning only, and Warning is disabled in hosting servers by default.This is just another way to look into the question and not claiming a better or most optimal solution.
Tested on PHP7, Production Server, Linux
You don't need to write a converter, just do this in your handler/codebehind:
int i = Convert.ToInt32(txtMyTextBox.Text);
OR
int i = int.Parse(txtMyTextBox.Text);
The Text
property of your textbox is a String
type, so you have to perform the conversion in the code.
You can also do it on the worksheet level captured in the worksheet's change event. If that suites your needs better. Allows for dynamic locking based on values, criteria, ect...
Private Sub Worksheet_Change(ByVal Target As Range)
'set your criteria here
If Target.Column = 1 Then
'must disable events if you change the sheet as it will
'continually trigger the change event
Application.EnableEvents = False
Application.Undo
Application.EnableEvents = True
MsgBox "You cannot do that!"
End If
End Sub
If it's OK to make a new array it's this:
$result = array();
foreach ( $array as $key => $val )
$result[ $key+1 ] = $val;
If you need reversal in-place, you need to run backwards so you don't stomp on indexes that you need:
for ( $k = count($array) ; $k-- > 0 ; )
$result[ $k+1 ] = $result[ $k ];
unset( $array[0] ); // remove the "zero" element
Here is the code to create a simple one second timer tick:
using System;
using System.Threading;
class TimerExample
{
static public void Tick(Object stateInfo)
{
Console.WriteLine("Tick: {0}", DateTime.Now.ToString("h:mm:ss"));
}
static void Main()
{
TimerCallback callback = new TimerCallback(Tick);
Console.WriteLine("Creating timer: {0}\n",
DateTime.Now.ToString("h:mm:ss"));
// create a one second timer tick
Timer stateTimer = new Timer(callback, null, 0, 1000);
// loop here forever
for (; ; )
{
// add a sleep for 100 mSec to reduce CPU usage
Thread.Sleep(100);
}
}
}
And here is the resulting output:
c:\temp>timer.exe
Creating timer: 5:22:40
Tick: 5:22:40
Tick: 5:22:41
Tick: 5:22:42
Tick: 5:22:43
Tick: 5:22:44
Tick: 5:22:45
Tick: 5:22:46
Tick: 5:22:47
EDIT: It is never a good idea to add hard spin loops into code as they consume CPU cycles for no gain. In this case that loop was added just to stop the application from closing, allowing the actions of the thread to be observed. But for the sake of correctness and to reduce the CPU usage a simple Sleep call was added to that loop.
Use the TRIM SQL function.
If you are using SQL Server try :
SELECT LTRIM(RTRIM(YourColumn)) FROM YourTable
Go to terminal
$ adb -s UDID shell
$ ip addr | grep inet
or
$ netcfg | grep inet
Consider using the jQuery validation plugin instead. It may be slightly overkill for simple required fields, but it mature enough that it handles edge cases you haven't even thought of yet (nor would any of us until we ran into them).
You can tag the required fields with a class of "required", run a $('form').validate() in $(document).ready() and that's all it takes.
It's even hosted on the Microsoft CDN too, for speedy delivery: http://www.asp.net/ajaxlibrary/CDN.ashx
string str = @"""Hi, "" I am programmer";
OUTPUT - "Hi, " I am programmer
In my case this was a syntax issue in the .yml file. I had:
@Value("${spring.kafka.bootstrap-servers}")
public List<String> BOOTSTRAP_SERVERS_LIST;
and the list in my .yml file:
bootstrap-servers:
- s1.company.com:9092
- s2.company.com:9092
- s3.company.com:9092
was not reading into the @Value-annotated field. When I changed the syntax in the .yml file to:
bootstrap-servers >
s1.company.com:9092
s2.company.com:9092
s3.company.com:9092
it worked fine.
Specify the name of columns in the CSV in the load data infile statement.
The code is like this:
LOAD DATA INFILE '/path/filename.csv'
INTO TABLE table_name
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
(column_name3, column_name5);
Here you go with adding data to only two columns(you can choose them with the name of the column) to the table.
The only thing you have to take care is that you have a CSV file(filename.csv) with two values per line(row). Otherwise please mention. I have a different solution.
Thank you.
Use ROUND
but with num_digits
= -1
=ROUND(A1,-1)
Also applies to ROUNDUP
and ROUNDDOWN
From Excel help:
EDIT:
To get the numbers to always round up use =ROUNDUP(A1,-1)
Elastic Search 7 changed the configurations for cluster initialisation. What is important to note is the ES instances communicate internally using the Transport layer(TCP) and not the HTTP protocol which is normally used to perform ops on the indices. Below is sample config for 2 machines cluster.
cluster.name: cluster-new
node.name: node-1
node.master: true
node.data: true
bootstrap.memory_lock: true
network.host: 0.0.0.0
http.port: 9200
transport.host: 102.123.322.211
transport.tcp.port: 9300
discovery.seed_hosts: [“102.123.322.211:9300”,"102.123.322.212:9300”]
cluster.initial_master_nodes:
- "node-1"
- "node-2”
Machine 2 config:-
cluster.name: cluster-new
node.name: node-2
node.master: true
node.data: true
bootstrap.memory_lock: true
network.host: 0.0.0.0
http.port: 9200
transport.host: 102.123.322.212
transport.tcp.port: 9300
discovery.seed_hosts: [“102.123.322.211:9300”,"102.123.322.212:9300”]
cluster.initial_master_nodes:
- "node-1"
- "node-2”
cluster.name: This has be same across all the machines that are going to be part of a cluster.
node.name : Identifier for the ES instance. Defaults to machine name if not given.
node.master: specifies whether this ES instance is going to be master or not
node.data: specifies whether this ES instance is going to be data node or not(hold data)
bootsrap.memory_lock: disable swapping.You can start the cluster without setting this flag. But its recommended to set the lock.More info: https://www.elastic.co/guide/en/elasticsearch/reference/master/setup-configuration-memory.html
network.host: 0.0.0.0 if you want to expose the ES instance over network. 0.0.0.0 is different from 127.0.0.1( aka localhost or loopback address). It means all IPv4 addresses on the machine. If machine has multiple ip addresses with a server listening on 0.0.0.0, the client can reach the machine from any of the IPv4 addresses.
http.port: port on which this ES instance will listen to for HTTP requests
transport.host: The IPv4 address of the host(this will be used to communicate with other ES instances running on different machines). More info: https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-transport.html
transport.tcp.port: 9300 (the port where the machine will accept the tcp connections)
discovery.seed_hosts: This was changed in recent versions. Initialise all the IPv4 addresses with TCP port(important) of ES instances that are going to be part of this cluster. This is going to be same across all ES instances that are part of this cluster.
cluster.initial_master_nodes: node names(node.name) of the ES machines that are going to participate in master election.(Quorum based decision making :- https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-discovery-quorums.html#modules-discovery-quorums)
Other configurable Spark option relating to jars and classpath, in case of yarn
as deploy mode are as follows
From the spark documentation,
spark.yarn.jars
List of libraries containing Spark code to distribute to YARN containers. By default, Spark on YARN will use Spark jars installed locally, but the Spark jars can also be in a world-readable location on HDFS. This allows YARN to cache it on nodes so that it doesn't need to be distributed each time an application runs. To point to jars on HDFS, for example, set this configuration to hdfs:///some/path. Globs are allowed.
spark.yarn.archive
An archive containing needed Spark jars for distribution to the YARN cache. If set, this configuration replaces spark.yarn.jars and the archive is used in all the application's containers. The archive should contain jar files in its root directory. Like with the previous option, the archive can also be hosted on HDFS to speed up file distribution.
Users can configure this parameter to specify their jars, which inturn gets included in Spark driver's classpath.
Add the following as a additional linker option:
/ignore:4099
This is in Properties->Linker->Command Line
Following up on ios-lizard's idea:
I found out that the controls on the video are about 35 pixels. This is what I did:
$(this).on("click", function(event) {
console.log("clicked");
var offset = $(this).offset();
var height = $(this).height();
var y = (event.pageY - offset.top - height) * -1;
if (y > 35) {
this.paused ? this.play() : this.pause();
}
});
Basically, it finds the position of the click relative to the element. I multiplied it by -1 to make it positive. If the value was greater than 35 (the height of the controls) that means that the user click somewhere else than the controls Therefore we pause or play the video.
Use asymptote instead!
This is what it can look like:
https://asymptote.sourceforge.io/gallery/3Dgraphs/helix.html
This is the code: https://asymptote.sourceforge.io/gallery/3Dgraphs/helix.asy
Asymptote can also read in data files.
And the full gallery: https://asymptote.sourceforge.io/gallery/index.html
To use asymptote from within Python:
https://ctan.org/tex-archive/graphics/asymptote/base/asymptote.py
The size of an array can't be modified. If you want a bigger array you have to instantiate a new one.
A better solution would be to use an ArrayList
which can grow as you need it. The method ArrayList.toArray( T[] a )
gives you back your array if you need it in this form.
List<String> where = new ArrayList<String>();
where.add( ContactsContract.Contacts.HAS_PHONE_NUMBER+"=1" );
where.add( ContactsContract.Contacts.IN_VISIBLE_GROUP+"=1" );
If you need to convert it to a simple array...
String[] simpleArray = new String[ where.size() ];
where.toArray( simpleArray );
But most things you do with an array you can do with this ArrayList, too:
// iterate over the array
for( String oneItem : where ) {
...
}
// get specific items
where.get( 1 );
If I may add a comment here...
<c:out value="${param.accountID}"></c:out>
doesn't work for me (it prints a 0).
Instead, this works:
<c:out value="${param['accountID']}"></c:out>
struct A {};
struct B : A {};
struct C {};
int main()
{
A* a = new A;
int i = 10;
a = (A*) (&i); // NO ERROR! FAIL!
//a = static_cast<A*>(&i); ERROR! SMART!
A* b = new B;
B* b2 = static_cast<B*>(b); // NO ERROR! SMART!
C* c = (C*)(b); // NO ERROR! FAIL!
//C* c = static_cast<C*>(b); ERROR! SMART!
}
You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.
I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).
To install it, you can either download it from the linked website or use the command:
pip install pyinstaller
...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:
pyinstaller myscript.py
You can find more information about how to use Pyinstaller and customize the build process via the documentation.
You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.
Just use the ES6 find()
function in a functional way:
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];
let country = data.find(el => el.code === "AL");
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
_x000D_
or Lodash _.find:
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];
let country = _.find(data, ["code", "AL"]);
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
You can use following css to make an element middle aligned styled with position: absolute
:
.element {
transform: translateX(-50%);
position: absolute;
left: 50%;
}
With CSS having only left: 50%
we will have following effect:
While combining left: 50%
with transform: translate(-50%)
we will have following:
.hero { _x000D_
background-color: #e15915;_x000D_
position: relative;_x000D_
height: 320px;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
_x000D_
.hero:after {_x000D_
border-right: solid 50px transparent;_x000D_
border-left: solid 50px transparent;_x000D_
border-top: solid 50px #e15915;_x000D_
transform: translateX(-50%);_x000D_
position: absolute;_x000D_
z-index: -1;_x000D_
content: '';_x000D_
top: 100%;_x000D_
left: 50%;_x000D_
height: 0;_x000D_
width: 0;_x000D_
}
_x000D_
<div class="hero">_x000D_
_x000D_
</div>
_x000D_
php's email()
function hands the email over to a underlying mail transfer agent
which is usually postfix
on linux systems
so the preferred method on linux is to configure your postfix to use a relayhost, which is done by a line of
relayhost = smtp.example.com
in /etc/postfix/main.cf
however in the OP's scenario I somehow suspect that it's a job that his hosting team
should have done
lets assume that your pem file and somefile.txt you want to send is in Downloads folder
scp -i ~/Downloads/mykey.pem ~/Downloads/somefile.txt [email protected]:~/
let me know if it doesn't work
.navbar-nav {
float: left;
margin: 0;
margin-left: 40%;
}
.navbar-nav.navbar-right:last-child {
margin-right: -15px;
margin-left: 0;
}
Since You Have used the float
property we don't have many options except to adjust it manually.
Try using the success()
call back
$http.get('/Documents/DocumentsList/' + caseId).success(function (result) {
$scope.Documents = result;
});
But now since Documents
is an array and not a promise, remove the ()
<li ng-repeat="document in Documents" ng-class="IsFiltered(document.Filtered)"> <span>
<input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" />
</span>
<span>{{document.Name}}</span>
</li>
There are some very good suggestions in the previous answer, but if you are having an issue with TortoiseSVN on Windows (a good product, but ...) always fallback to the command line and do a simple "svn cleanup" first.
In many circumstances the Windows client will not run the cleanup command, but cleanup works fine using thing the SVN command line utility.
You're instantiating the Random
object inside your method.
The Random
object is seeded from the system clock, which means that if you call your method several times in quick succession it'll use the same seed each time, which means that it'll generate the same sequence of random numbers, which means that you'll get the same string.
To solve the problem, move your Random
instance outside of the method itself (and while you're at it you could get rid of that crazy sequence of calls to Convert
and Floor
and NextDouble
):
private readonly Random _rng = new Random();
private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private string RandomString(int size)
{
char[] buffer = new char[size];
for (int i = 0; i < size; i++)
{
buffer[i] = _chars[_rng.Next(_chars.Length)];
}
return new string(buffer);
}
For me it worked best to export all data with this command:
mysqldump -u USERNAME -p --all-databases --complete-insert --extended-insert=FALSE --compatible=mssql > backup.sql
--extended-insert=FALSE is needed to avoid mssql 1000 rows import limit.
I created my tables with my migration tool, so I'm not sure if the CREATE from the backup.sql file will work.
In MSSQL's SSMS I had to imported the data table by table with the IDENTITY_INSERT ON to write the ID fields:
SET IDENTITY_INSERT dbo.app_warehouse ON;
GO
INSERT INTO "app_warehouse" ("id", "Name", "Standort", "Laenge", "Breite", "Notiz") VALUES (1,'01','Bremen',250,120,'');
SET IDENTITY_INSERT dbo.app_warehouse OFF;
GO
If you have relationships you have to import the child first and than the table with the foreign key.
This can be solved by using https://twitter.com/intent/tweet
instead of http://www.twitter.com/share
. Using the intent/tweet
function, you simply URL encode your entire URL and it works like a charm.
For an automatic letterbox/pillarbox in a fixed-size rectangle, use the object-fit
CSS property. That is usually what I want, and it avoids using code to figure out which is the dominant dimension or — what I used to do — embedding an <SVG>
element with an <image>
child to wrap the content with its nice preserveAspectRatio
options.
<!DOCTYPE html>
<html>
<head>
<style>
:root
{
--box-side : min( 42vmin, 480px ) ;
}
body
{
align-items : center ;
display : flex ;
flex-wrap : wrap ;
justify-content : center ;
}
body,html
{
height : 100% ;
width : 100% ;
}
img
{
background : grey ;
border : 1px solid black ;
height : var( --box-side ) ;
object-fit : contain ;
width : var( --box-side ) ;
}
</style>
<title>object-fit</title>
</head>
<body>
<img src="https://alesmith.com/wp-content/uploads/logos/ALESMITH-MasterLogoShadow01-MULTI-A.png" />
<img src="https://ballastpoint.com/wp-content/themes/ballastpoint/assets/img/bp-logo-color.svg" />
<img src="https://d2lchr2s24ssh5.cloudfront.net/wp-content/uploads/2014/01/GF19_PrimaryLogo_RGB.png" />
<img src="https://s3-us-west-1.amazonaws.com/paradeigm-social/NeFAAJ7RlCreLCi9Uk9u_pizza-port-logo.svg">
<img src="https://s3-us-west-2.amazonaws.com/lostabbey-prod/Logos/Logo_Port_SM_Circle_White.png" />
</body>
</html>
_x000D_
Also relevant, but specially to excel, look at this answer and this other one that suggests, inserting a line at the beginning of the CSV with
"sep=,"
To inform excel which separator to expect
IMHO here are some improvements to anon's answer.
#include <windows.h>
#include <string>
#include <iostream>
std::string GetExeFileName()
{
char buffer[MAX_PATH];
GetModuleFileName( NULL, buffer, MAX_PATH );
return std::string(buffer);
}
std::string GetExePath()
{
std::string f = GetExeFileName();
return f.substr(0, f.find_last_of( "\\/" ));
}
I have this working well using JPA2.0 and MySQL 5.5.10, for cases where I only care about the last time the row was modified. MySQL will create a timestamp on first insertion, and every time UPDATE is called on the row. (NOTE: this will be problematic if I cared whether or not the UPDATE actually made a change).
The "timestamp" column in this example is like a "last-touched" column.x`
The code below uses a separate column "version" for optimistic locking.
private long version;
private Date timeStamp
@Version
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
// columnDefinition could simply be = "TIMESTAMP", as the other settings are the MySQL default
@Column(name="timeStamp", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
@Temporal(TemporalType.TIMESTAMP)
public Date getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(Date timeStamp) {
this.timeStamp = timeStamp;
}
(NOTE: @Version doesn't work on a MySQL "DATETIME" column, where the attribute type is "Date" in the Entity class. This was because Date was generating a value down to the millisecond, however MySQL was not storing the millisecond, so when it did a comparison between what was in the database, and the "attached" entity, it thought they had different version numbers)
From the MySQL manual regarding TIMESTAMP :
With neither DEFAULT nor ON UPDATE clauses, it is the same as DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP.
To me it seems @atomicules has the simplest answer, but I think it can be simplified a little more. You need to put an @
before anything you want to be global, so that it compiles to this.anything
and this
refers to the global object.
@bawbag = (x, y) ->
z = (x * y)
bawbag(5, 10)
this.bawbag = function(x, y) {
var z;
return z = x * y;
};
bawbag(5, 10);
(function() {
this.bawbag = function(x, y) {
var z;
return z = x * y;
};
console.log(bawbag(5,13)) // works here
}).call(this);
console.log(bawbag(5,11)) // works here
Works even if the default value is a boolean value:
var setVariable = ( (b = 0) => b )( localStorage.getItem('value') );
I have to add an important difference between using node's build in cluster mode VS a process manager like PM2's cluster mode.
PM2 allows zero down time reloads when you are running.
pm2 start app.js -i 2 --wait-ready
In your codes add the following
process.send('ready');
When you call
pm2 reload app
after code updates, PM2 will reload the first instance of the app, wait for the 'ready' call, then it move on to reloads the next instance, ensuring you always have an app active to respond to requests.
While if you use nodejs' cluster, there will be down time when you restart and waiting for server to be ready.
sudo apt-get install libmysqlclient-dev sudo apt-get install python-dev sudo apt-get install MySQL-python
NOtice you should install python-dev as well, the packages like MySQL-python are compiled from source. The pythonx.x-dev packages contain the necessary header files for linking against python. Why does installing numpy require python-dev in Kubuntu 12.04
You may be interested in std::vector<bool>
(that is bit-packed) and std::bitset
It should be the simplest as requested.
#include <iostream>
#include <bitset>
using namespace std;
int main() {
bitset<8> bs = 5;
bitset<8> rev;
for(int ii=0; ii!= bs.size(); ++ii)
rev[bs.size()-ii-1] = bs[ii];
cerr << bs << " " << rev << endl;
}
Other options may be faster.
EDIT: I owe you a solution using std::vector<bool>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<bool> b{0,0,0,0,0,1,0,1};
reverse(b.begin(), b.end());
copy(b.begin(), b.end(), ostream_iterator<int>(cerr));
cerr << endl;
}
The second example requires c++0x extension (to initialize the array with {...}
). The advantage of using a bitset
or a std::vector<bool>
(or a boost::dynamic_bitset
) is that you are not limited to bytes or words but can reverse an arbitrary number of bits.
HTH
Assuming you're able to use ECMAScript 2017 you can emulate similar behaviour by using async/await and setTimeout. Here's an example sleep function:
async function sleep(msec) {
return new Promise(resolve => setTimeout(resolve, msec));
}
You can then use the sleep function in any other async function like this:
async function testSleep() {
console.log("Waiting for 1 second...");
await sleep(1000);
console.log("Waiting done."); // Called 1 second after the first console.log
}
This is nice because it avoids needing a callback. The down side is that it can only be used in async functions. Behind the scenes the testSleep function is paused, and after the sleep completes it is resumed.
From MDN:
The await expression causes async function execution to pause until a Promise is fulfilled or rejected, and to resume execution of the async function after fulfillment.
For a full explanation see:
Depends on what your native code does, but v7a has support for hardware floating point operations, which makes a huge difference. armeabi will work fine on all devices, but will be a lot slower, and won't take advantage of newer devices' CPU capabilities. Do take some benchmarks for your particular application, but removing the armeabi-v7a binaries is generally not a good idea. If you need to reduce size, you might want to have two separate apks for older (armeabi) and newer (armeabi-v7a) devices.
If you get an error indicating that you must call makeText, the following code will fix it:
Toast toast= Toast.makeText(getApplicationContext(),
"Your string here", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
PreparedStatements are the way to go, because they make SQL injection impossible. Here's a simple example taking the user's input as the parameters:
public insertUser(String name, String email) {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = setupTheDatabaseConnectionSomehow();
stmt = conn.prepareStatement("INSERT INTO person (name, email) values (?, ?)");
stmt.setString(1, name);
stmt.setString(2, email);
stmt.executeUpdate();
}
finally {
try {
if (stmt != null) { stmt.close(); }
}
catch (Exception e) {
// log this error
}
try {
if (conn != null) { conn.close(); }
}
catch (Exception e) {
// log this error
}
}
}
No matter what characters are in name and email, those characters will be placed directly in the database. They won't affect the INSERT statement in any way.
There are different set methods for different data types -- which one you use depends on what your database fields are. For example, if you have an INTEGER column in the database, you should use a setInt
method. The PreparedStatement documentation lists all the different methods available for setting and getting data.
I have a huge database with no (separate) index.
Any time I query by the primary key the results are, for all intensive purposes, instant.
For 1-hot-encoding
one_hot_encode=pandas.get_dummies(array)
ENJOY CODING
I faced a similar issue while copying a sheet to another workbook. I prefer to avoid using 'activesheet' though as it has caused me issues in the past. Hence I wrote a function to perform this inline with my needs. I add it here for those who arrive via google as I did:
The main issue here is that copying a visible sheet to the last index position results in Excel repositioning the sheet to the end of the visible sheets. Hence copying the sheet to the position after the last visible sheet sorts this issue. Even if you are copying hidden sheets.
Function Copy_WS_to_NewWB(WB As Workbook, WS As Worksheet) As Worksheet
'Creates a copy of the specified worksheet in the specified workbook
' Accomodates the fact that there may be hidden sheets in the workbook
Dim WSInd As Integer: WSInd = 1
Dim CWS As Worksheet
'Determine the index of the last visible worksheet
For Each CWS In WB.Worksheets
If CWS.Visible Then If CWS.Index > WSInd Then WSInd = CWS.Index
Next CWS
WS.Copy after:=WB.Worksheets(WSInd)
Set Copy_WS_to_NewWB = WB.Worksheets(WSInd + 1)
End Function
To use this function for the original question (ie in the same workbook) could be done with something like...
Set test = Copy_WS_to_NewWB(Workbooks(1), Workbooks(1).Worksheets(1))
test.name = "test sheet name"
EDIT 04/11/2020 from –user3598756 Adding a slight refactoring of the above code
Function CopySheetToWorkBook(targetWb As Workbook, shToBeCopied As Worksheet, copiedSh As Worksheet) As Boolean
'Creates a copy of the specified worksheet in the specified workbook
' Accomodates the fact that there may be hidden sheets in the workbook
Dim lastVisibleShIndex As Long
Dim iSh As Long
On Error GoTo SafeExit
With targetWb
'Determine the index of the last visible worksheet
For iSh = .Sheets.Count To 1 Step -1
If .Sheets(iSh).Visible Then
lastVisibleShIndex = iSh
Exit For
End If
Next
shToBeCopied.Copy after:=.Sheets(lastVisibleShIndex)
Set copiedSh = .Sheets(lastVisibleShIndex + 1)
End With
CopySheetToWorkBook = True
Exit Function
SafeExit:
End Function
other than using different (more descriptive?) variable names, the refactoring manily deals with:
turning the Function type into a `Boolean while including returned (copied) worksheet within function parameters list this, to let the calling Sub hande possible errors, like
Dim WB as Workbook: Set WB = ThisWorkbook ' as an example
Dim sh as Worksheet: Set sh = ActiveSheet ' as an example
Dim copiedSh as Worksheet
If CopySheetToWorkBook(WB, sh, copiedSh) Then
' go on with your copiedSh sheet
Else
Msgbox "Error while trying to copy '" & sh.Name & "'" & vbcrlf & err.Description
End If
having the For - Next loop stepping from last sheet index backwards and exiting at first visible sheet occurence, since we're after the "last" visible one
TryGetValue
will already assign the default value for the type to the dictionary, so you can just use:
dictionary.TryGetValue(key, out value);
and just ignore the return value. However, that really will just return default(TValue)
, not some custom default value (nor, more usefully, the result of executing a delegate). There's nothing more powerful built into the framework. I would suggest two extension methods:
public static TValue GetValueOrDefault<TKey, TValue>
(this IDictionary<TKey, TValue> dictionary,
TKey key,
TValue defaultValue)
{
TValue value;
return dictionary.TryGetValue(key, out value) ? value : defaultValue;
}
public static TValue GetValueOrDefault<TKey, TValue>
(this IDictionary<TKey, TValue> dictionary,
TKey key,
Func<TValue> defaultValueProvider)
{
TValue value;
return dictionary.TryGetValue(key, out value) ? value
: defaultValueProvider();
}
(You may want to put argument checking in, of course :)
On Windows you can use CRT debug heap.
Is there any standard or procedure one should follow to ensure there is no memory leak in the program.
Yeah, don't use manual memory management (if you ever call delete
or delete[]
manually, then you're doing it wrong). Use RAII and smart pointers, limit heap allocations to the absolute minimum (most of the time, automatic variables will suffice).
After looking for an answer for myself for some time, i could find something. in general if we are using it for just one property it appears same even if we do a "View Source" of generated HTML Below is generated HTML for example, when i want to display only Name property for my class
<td>
myClassNameProperty
</td>
<td>
myClassNameProperty, This is direct from Item
</td>
This is the generated HTML from below code
<td>
@Html.DisplayFor(modelItem=>item.Genre.Name)
</td>
<td>
@item.Genre.Name, This is direct from Item
</td>
At the same time now if i want to display all properties in one statement for my class "Genre" in this case, i can use @Html.DisplayFor() to save on my typing, for least
i can write @Html.DisplayFor(modelItem=>item.Genre) in place of writing a separate statement for each property of Genre as below
@item.Genre.Name
@item.Genre.Id
@item.Genre.Description
and so on depending on number of properties.
I have had issues in the past when attempting to perform a POST (not sure if that is exactly what you are doing, but I recall when passing an array in, traditional must be set to true.
var arrayOfValues = new Array();
//Populate arrayOfValues
$.ajax({
type: "POST",
url: "<%= Url.Action("MyAction","Controller")%>",
traditional: true,
data: { 'arrayOfValues': arrayOfValues }
});
I had a similar error..This might be due to two reasons. a) If you have used variables, re-evaluate the expressions in which variables are used and make sure the expression is evaluated without errors. b) If you are deleting the excel sheet and creating excel sheet on the fly in your package.
It seems you need DataFrame.var
:
Normalized by N-1 by default. This can be changed using the ddof argument
var1 = credit_card.var()
Sample:
#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
A B C D E
0 8 8 3 7 7
1 0 4 2 5 2
2 2 2 1 0 8
3 4 0 9 6 2
4 4 1 5 3 4
var1 = credit_card.var()
print (var1)
A 8.8
B 10.0
C 10.0
D 7.7
E 7.8
dtype: float64
var2 = credit_card.var(axis=1)
print (var2)
0 4.3
1 3.8
2 9.8
3 12.2
4 2.3
dtype: float64
If need numpy solutions with numpy.var
:
print (np.var(credit_card.values, axis=0))
[ 7.04 8. 8. 6.16 6.24]
print (np.var(credit_card.values, axis=1))
[ 3.44 3.04 7.84 9.76 1.84]
Differences are because by default ddof=1
in pandas
, but you can change it to 0
:
var1 = credit_card.var(ddof=0)
print (var1)
A 7.04
B 8.00
C 8.00
D 6.16
E 6.24
dtype: float64
var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0 3.44
1 3.04
2 7.84
3 9.76
4 1.84
dtype: float64
Simple:
Use <section>
.
and use <a href="page.html#tips">Visit the Useful Tips Section</a>