First thing, define a type or interface for your object, it will make things much more readable:
type Product = { productId: number; price: number; discount: number };
You used a tuple of size one instead of array, it should look like this:
let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();
So now this works fine:
myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;
I think...
Search partial value:
SELECT id FROM table_name WHERE field_name REGEXP '"key_name":"([^"])*key_word([^"])*"';
Search exact word:
SELECT id FROM table_name WHERE field_name RLIKE '"key_name":"[[:<:]]key_word[[:>:]]"';
Just for those who want to send a nested JSON object with form-data as content type.
I want to send nested custom_field in below
{ "description": "Details about the issue...", "subject": "Support Needed...", "type": "Others", "email": "[email protected]", "priority": 1, "status": 2, **"custom_fields" : { "cf_type_of_issue" : "Complaint" }**, "cc_emails": ["[email protected]","[email protected]"] }
It is ok for sure. With just few hundred of entries, it will be fast.
You can add an unique id as as primary key (int autoincrement) ans set your coupon_code as unique. So if you need to do request in other tables it's better to use int than varchar
Here is a working example
var value=200.2365455;
result=Math.round(value*100)/100 //result will be 200.24
How to get the last N rows of a pandas DataFrame?
If you are slicing by position, __getitem__
(i.e., slicing with[]
) works well, and is the most succinct solution I've found for this problem.
pd.__version__
# '0.24.2'
df = pd.DataFrame({'A': list('aaabbbbc'), 'B': np.arange(1, 9)})
df
A B
0 a 1
1 a 2
2 a 3
3 b 4
4 b 5
5 b 6
6 b 7
7 c 8
df[-3:]
A B
5 b 6
6 b 7
7 c 8
This is the same as calling df.iloc[-3:]
, for instance (iloc
internally delegates to __getitem__
).
As an aside, if you want to find the last N rows for each group, use groupby
and GroupBy.tail
:
df.groupby('A').tail(2)
A B
1 a 2
2 a 3
5 b 6
6 b 7
7 c 8
In a comment to @theodros-zelleke's answer, @j-jones asked about what to do if the index is not unique. I had to deal with such a situation. What I did was to rename the duplicates in the index before I called drop()
, a la:
dropped_indexes = <determine-indexes-to-drop>
df.index = rename_duplicates(df.index)
df.drop(df.index[dropped_indexes], inplace=True)
where rename_duplicates()
is a function I defined that went through the elements of index and renamed the duplicates. I used the same renaming pattern as pd.read_csv()
uses on columns, i.e., "%s.%d" % (name, count)
, where name
is the name of the row and count
is how many times it has occurred previously.
I guess the issue here is that you are updating INV_DISCOUNT and the INV_TOTAL uses the INV_DISCOUNT. so that is the issue here. You can use returning clause of update statement to use the new INV_DISCOUNT and use it to update INV_TOTAL.
this is a generic example let me know if this explains the point i mentioned
CREATE OR REPLACE PROCEDURE SingleRowUpdateReturn
IS
empName VARCHAR2(50);
empSalary NUMBER(7,2);
BEGIN
UPDATE emp
SET sal = sal + 1000
WHERE empno = 7499
RETURNING ename, sal
INTO empName, empSalary;
DBMS_OUTPUT.put_line('Name of Employee: ' || empName);
DBMS_OUTPUT.put_line('New Salary: ' || empSalary);
END;
Procedure successful but any outpout
Error line1: Unexpected identifier
Here is the code:
SET SERVEROUTPUT ON
DECLARE
-- Curseurs
CURSOR c1 IS
SELECT RWID FROM J_EVT
WHERE DT_SYST < TO_DATE(TO_CHAR(SYSDATE,'DD/MM') || '/' || TO_CHAR(TO_NUMBER(TO_CHAR(SYSDATE, 'YYYY')) - 3));
-- Collections
TYPE tc1 IS TABLE OF c1%RWTYPE;
-- Variables de type record
rtc1 tc1;
vCpt NUMBER:=0;
BEGIN
OPEN c1;
LOOP
FETCH c1 BULK COLLECT INTO rtc1 LIMIT 5000;
FORALL i IN 1..rtc1.COUNT
DELETE FROM J_EVT
WHERE RWID = rtc1(i).RWID;
COMMIT;
-- Nombres lus : 5025651
FOR i IN 1..rtc1.COUNT LOOP
vCpt := vCpt + SQL%BULK_RWCOUNT(i);
END LOOP;
EXIT WHEN c1%NOTFOUND;
END LOOP;
CLOSE c1;
COMMIT;
DBMS_OUTPUT.PUT_LINE ('Nombres supprimes : ' || TO_CHAR(vCpt));
END;
/
exit
The question specifically states the performance needs to be improved for ad-hoc queries, and that indexes can't be added. So taking that at face value, what can be done to improve performance on any table?
Since we're considering ad-hoc queries, the WHERE clause and the ORDER BY clause can contain any combination of columns. This means that almost regardless of what indexes are placed on the table there will be some queries that require a table scan, as seen above in query plan of a poorly performing query.
Taking this into account, let's assume there are no indexes at all on the table apart from a clustered index on the primary key. Now let's consider what options we have to maximize performance.
Defragment the table
As long as we have a clustered index then we can defragment the table using DBCC INDEXDEFRAG (deprecated) or preferably ALTER INDEX. This will minimize the number of disk reads required to scan the table and will improve speed.
Use the fastest disks possible. You don't say what disks you're using but if you can use SSDs.
Optimize tempdb. Put tempdb on the fastest disks possible, again SSDs. See this SO Article and this RedGate article.
As stated in other answers, using a more selective query will return less data, and should be therefore be faster.
Now let's consider what we can do if we are allowed to add indexes.
If we weren't talking about ad-hoc queries, then we would add indexes specifically for the limited set of queries being run against the table. Since we are discussing ad-hoc queries, what can be done to improve speed most of the time?
Edit
I've run some tests on a 'large' table of 22 million rows. My table only has six columns but does contain 4GB of data. My machine is a respectable desktop with 8Gb RAM and a quad core CPU and has a single Agility 3 SSD.
I removed all indexes apart from the primary key on the Id column.
A similar query to the problem one given in the question takes 5 seconds if SQL server is restarted first and 3 seconds subsequently. The database tuning advisor obviously recommends adding an index to improve this query, with an estimated improvement of > 99%. Adding an index results in a query time of effectively zero.
What's also interesting is that my query plan is identical to yours (with the clustered index scan), but the index scan accounts for 9% of the query cost and the sort the remaining 91%. I can only assume your table contains an enormous amount of data and/or your disks are very slow or located over a very slow network connection.
You could add the following VBA code to your sheet:
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("A1") > 0.5 Then
MsgBox "Discount too high"
End If
End Sub
Every time a cell is changed on the sheet, it will check the value of cell A1.
Notes:
Widor uses a different approach (Worksheet_Calculate
instead of Worksheet_Change
):
Conclusion: use Worksheet_Change
if A1 only depends on data located on the same sheet, use Worksheet_Calculate
if not.
You do realize this is the default behavior, right? if you add /something the results would be different.
you can do a number of things to prevent default behavior.
href="#"
:Will do nothing but anchor - not the best solution since it may jump to page top.
<a href="#">
href="javascript:void(0);"
Will do nothing at all and is perfectly legit.
<a href="javascript:void(0);"></a>
href="your-actual-intended-link"
(Best)obviously the best.
<a href="<your-actual-intended-link>"></a>
If you don't want an a
tag to go somewhere, why use an a
tag at all?
on the checkout page, look for the 'cancel_return' hidden form element:
set the value of the cancel_return form element to the URL you wish to return to:
The first thing you need to do is use the decimal
type instead of float
for the prices. Using float
is absolutely unacceptable for that because it cannot accurately represent most decimal fractions.
Once you have done that, Decimal.Round()
can be used to round to 2 places.
I know this is fairly old but I figured this was as good as any to put this. I found a post from yahoo with a good explanation:
Let's say you have two numbers, 40 and 30.
30/40*100 = 75.
So 30 is 75% of 40.
40/30*100 = 133.
So 40 is 133% of 30.
The percentage increase from 30 to 40 is:
(40-30)/30 * 100 = 33%
The percentage decrease from 40 to 30 is:
(40-30)/40 * 100 = 25%.
These calculations hold true whatever your two numbers.
The accepted answer from Paul is great. I've made a small extension to this which is very useful if you have an multidimensional array like this (which is quite common):
Array
(
[0] => Array
(
[a] => "a"
[b] => "b"
)
[1] => Array
(
[a] => "a2"
[b] => "b2"
)
[2] => Array
(
[a] => "a3"
[b] => "b3"
)
[3] => Array
(
[a] => "a4"
[b] => "b4"
)
[4] => Array
(
[a] => "a5"
[b] => "b5"
)
)
So I just took Paul's function from above:
/**
* Formats a line (passed as a fields array) as CSV and returns the CSV as a string.
* Adapted from http://us3.php.net/manual/en/function.fputcsv.php#87120
*/
function arrayToCsv( array &$fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
$output = array();
foreach ( $fields as $field ) {
if ($field === null && $nullToMysqlNull) {
$output[] = 'NULL';
continue;
}
// Enclose fields containing $delimiter, $enclosure or whitespace
if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
$output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
}
else {
$output[] = $field;
}
}
return implode( $delimiter, $output );
}
And added this:
function a2c($array, $glue = "\n")
{
$ret = [];
foreach ($array as $item) {
$ret[] = arrayToCsv($item);
}
return implode($glue, $ret);
}
So you can just call:
$csv = a2c($array);
If you want a special line ending you can use the optional parameter "glue" for this.
val() is more like a shortcut for attr('value'). For your usage use text() or html() instead
You can add the id="MyID123"
at the start of the cartHTML text appends.
The first line would therefore be:
var cartHTML = '<div id="MyID123" class="soft_add_wrapper" onmouseover="setTimer();">';
-OR-
If you want the ID to be in a variable, then something like this:
var MyIDvariable = "MyID123";
var cartHTML = '<div id="'+MyIDvariable+'" class="soft_add_wrapper" onmouseover="setTimer();">';
/* ... the rest of your code ... */
use this code this might help you to get tab like behaviour when user presses enter
Private Sub TxtSearch_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TxtSearch.KeyPress
Try
If e.KeyChar = Convert.ToChar(13) Then
nexttextbox.setfoucus
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
The simple tilde syntax works only for removing quotation marks around the command line parameters being passed into the batch files
SET xyz=%~1
Above batch file code will set xyz to whatever value is being passed as first paramter stripping away the leading and trailing quotations (if present).
But, This simple tilde syntax will not work for other variables that were not passed in as parameters
For all other variable, you need to use expanded substitution syntax that requires you to specify leading and lagging characters to be removed. Effectively we are instructing to remove strip away the first and the last character without looking at what it actually is.
@SET SomeFileName="Some Quoted file name"
@echo %SomeFileName% %SomeFileName:~1,-1%
If we wanted to check what the first and last character was actually quotation before removing it, we will need some extra code as follows
@SET VAR="Some Very Long Quoted String"
If aa%VAR:~0,1%%VAR:~-1%aa == aa""aa SET UNQUOTEDVAR=%VAR:~1,-1%
Instead of finding a way to get static variables working, I prefer to simply create a getter function. Also helpful if you need arrays belonging to a specific class, and a lot simpler to implement.
class MyClass
{
public static function getTypeList()
{
return array(
"type_a"=>"Type A",
"type_b"=>"Type B",
//... etc.
);
}
}
Wherever you need the list, simply call the getter method. For example:
if (array_key_exists($type, MyClass::getTypeList()) {
// do something important...
}
if discount.nil? || discount == 0
[do something]
end
You just need to add an "A" record in the DNS manager on Godaddy. In that "A" record put your IP from dreamhost.
I know this works since I'm doing the very same thing.
table {
border-spacing: 10px;
}
This worked for me once I removed
border-collapse: separate;
from my table tag.
@find /v "@" < %0 | sqlplus -s scott/tiger@orcl & goto :eof
select sysdate from dual;
If we are talking Visual Studio Code nowadays you set a default formatter in your settings.json
:
// Defines a default formatter which takes precedence over all other formatter settings.
// Must be the identifier of an extension contributing a formatter.
"editor.defaultFormatter": null,
Point to the identifier of any installed extension, i.e.
"editor.defaultFormatter": "esbenp.prettier-vscode"
You can also do so format-specific:
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[scss]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[sass]": {
"editor.defaultFormatter": "michelemelluso.code-beautifier"
},
Also see here.
You could also assign other keys for different formatters in your keyboard shortcuts (keybindings.json
). By default, it reads:
{
"key": "shift+alt+f",
"command": "editor.action.formatDocument",
"when": "editorHasDocumentFormattingProvider && editorHasDocumentFormattingProvider && editorTextFocus && !editorReadonly"
}
Lastly, if you decide to use the Prettier plugin and prettier.rc
, and you want for example different indentation for html, scss, json...
{
"semi": true,
"singleQuote": false,
"trailingComma": "none",
"useTabs": false,
"overrides": [
{
"files": "*.component.html",
"options": {
"parser": "angular",
"tabWidth": 4
}
},
{
"files": "*.scss",
"options": {
"parser": "scss",
"tabWidth": 2
}
},
{
"files": ["*.json", ".prettierrc"],
"options": {
"parser": "json",
"tabWidth": 4
}
}
]
}
The following command will give you a list of node processes running.
ps | grep node
To free up that port, stop the process using the following.
kill <processId>
A bit too late, but this solution is nice and neat
const arr = [[1,2,3],[4,5,6],[7,8,9,10]]
for (let i of arr) {
for (let j of i) {
console.log(j) //Should log numbers from 1 to 10
}
}
Or in your case:
const arr = [[1,2,3],[4,5,6],[7,8,9]]
for (let [d1, d2, d3] of arr) {
console.log(`${d1}, ${d2}, ${d3}`) //Should return numbers from 1 to 9
}
Note: for ... of
loop is standardised in ES6, so only use this if you have an ES5 Javascript Complier (such as Babel)
Another note: There are alternatives, but they have some subtle differences and behaviours, such as forEach()
, for...in
, for...of
and traditional for()
. It depends on your case to decide which one to use. (ES6 also has .map()
, .filter()
, .find()
, .reduce()
)
I just had this same issue. It turns out for me, mysql was already installed and working. I just didn't know how to check.
$ ps aux | grep mysql
This will show you if mysql is already running. If it is it should return something like this:
mysql 24294 0.1 1.3 550012 52784 ? Ssl 15:16 0:06 /usr/sbin/mysqld
gwang 27451 0.0 0.0 15940 924 pts/3 S+ 16:34 0:00 grep --color=auto mysql
The WhatsApp Architecture Facebook Bought For $19 Billion explains the architecture involved in design of whatsapp.
Here is the general explanation from the link
WhatsApp server is almost completely implemented in Erlang.
Server systems that do the backend message routing are done in Erlang.
Great achievement is that the number of active users is managed with a really small server footprint. Team consensus is that it is largely because of Erlang.
Interesting to note Facebook Chat was written in Erlang in 2009, but they went away from it because it was hard to find qualified programmers.
WhatsApp server has started from ejabberd
Ejabberd is a famous open source Jabber server written in Erlang.
Originally chosen because its open, had great reviews by developers, ease of start and the promise of Erlang’s long term suitability for large communication system.
The next few years were spent re-writing and modifying quite a few parts of ejabberd, including switching from XMPP to internally developed protocol, restructuring the code base and redesigning some core components, and making lots of important modifications to Erlang VM to optimize server performance.
To handle 50 billion messages a day the focus is on making a reliable system that works. Monetization is something to look at later, it’s far far down the road.
A primary gauge of system health is message queue length. The message queue length of all the processes on a node is constantly monitored and an alert is sent out if they accumulate backlog beyond a preset threshold. If one or more processes falls behind that is alerted on, which gives a pointer to the next bottleneck to attack.
Multimedia messages are sent by uploading the image, audio or video to be sent to an HTTP server and then sending a link to the content along with its Base64 encoded thumbnail (if applicable).
Some code is usually pushed every day. Often, it’s multiple times a day, though in general peak traffic times are avoided. Erlang helps being aggressive in getting fixes and features into production. Hot-loading means updates can be pushed without restarts or traffic shifting. Mistakes can usually be undone very quickly, again by hot-loading. Systems tend to be much more loosely-coupled which makes it very easy to roll changes out incrementally.
What protocol is used in Whatsapp app? SSL socket to the WhatsApp server pools. All messages are queued on the server until the client reconnects to retrieve the messages. The successful retrieval of a message is sent back to the whatsapp server which forwards this status back to the original sender (which will see that as a "checkmark" icon next to the message). Messages are wiped from the server memory as soon as the client has accepted the message
How does the registration process work internally in Whatsapp? WhatsApp used to create a username/password based on the phone IMEI number. This was changed recently. WhatsApp now uses a general request from the app to send a unique 5 digit PIN. WhatsApp will then send a SMS to the indicated phone number (this means the WhatsApp client no longer needs to run on the same phone). Based on the pin number the app then request a unique key from WhatsApp. This key is used as "password" for all future calls. (this "permanent" key is stored on the device). This also means that registering a new device will invalidate the key on the old device.
#multiple-background{_x000D_
box-sizing: border-box;_x000D_
width: 123px;_x000D_
height: 30px;_x000D_
font-size: 12pt;_x000D_
border-radius: 7px; _x000D_
background: url("https://cdn0.iconfinder.com/data/icons/woocons1/Checkbox%20Full.png"), linear-gradient(to bottom, #4ac425, #4ac425);_x000D_
background-repeat: no-repeat, repeat;_x000D_
background-position: 5px center, 0px 0px;_x000D_
background-size: 18px 18px, 100% 100%;_x000D_
color: white; _x000D_
border: 1px solid #e4f6df;_x000D_
box-shadow: .25px .25px .5px .5px black;_x000D_
padding: 3px 10px 0px 5px;_x000D_
text-align: right;_x000D_
}
_x000D_
<div id="multiple-background"> Completed </div>
_x000D_
"FOO[DOG]".replaceAll("^.*?\\[|\\].*", "");
This will return a string taking only the string inside square brackets.
This remove all string outside from square brackets.
You can test this java sample code online: http://tpcg.io/wZoFu0
You can test this regex from here: https://regex101.com/r/oUAzsS/1
I have found the problem.
The problem was that the HTML I was trying to validate was not contained within a <form>...</form>
tag.
As soon as I did that, I had a context
that was not null.
To select the node's contents call:
window.getSelection().selectAllChildren(
document.getElementById(id)
);
This works on all modern browsers including IE9+ (in standards mode).
function select(id) {_x000D_
window.getSelection()_x000D_
.selectAllChildren(_x000D_
document.getElementById("target-div") _x000D_
);_x000D_
}
_x000D_
#outer-div { padding: 1rem; background-color: #fff0f0; }_x000D_
#target-div { padding: 1rem; background-color: #f0fff0; }_x000D_
button { margin: 1rem; }
_x000D_
<div id="outer-div">_x000D_
<div id="target-div">_x000D_
Some content for the _x000D_
<br>Target DIV_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<button onclick="select(id);">Click to SELECT Contents of #target-div</button>
_x000D_
The original answer below is obsolete since window.getSelection().addRange(range);
has been deprecated
All of the examples above use:
var range = document.createRange();
range.selectNode( ... );
but the problem with that is that it selects the Node itself including the DIV tag etc.
To select the Node's text as per the OP question you need to call instead:
range.selectNodeContents( ... )
So the full snippet would be:
function selectText( containerid ) {
var node = document.getElementById( containerid );
if ( document.selection ) {
var range = document.body.createTextRange();
range.moveToElementText( node );
range.select();
} else if ( window.getSelection ) {
var range = document.createRange();
range.selectNodeContents( node );
window.getSelection().removeAllRanges();
window.getSelection().addRange( range );
}
}
<input id="fusk" type="file" name="upload" style="display: none;"
onChange=" document.getElementById('myForm').submit();"
>
Try this:
window.open(this.url+'/create-account')
No need to use '_blank'
. window.open
by default opens a link in a new tab.
When plotting a plot using matplotlib:
How to remove the box of the legend?
plt.legend(frameon=False)
How to change the color of the border of the legend box?
leg = plt.legend()
leg.get_frame().set_edgecolor('b')
How to remove only the border of the box of the legend?
leg = plt.legend()
leg.get_frame().set_linewidth(0.0)
One way to do it would be to do the hover effect when the touch starts, then remove the hover effect when the touch moves or ends.
This is what Apple has to say about touch handling in general, since you mention iPhone.
You could put it in a <div>
with overflow: hidden;
and set the <img>
to margin: -5px -10px -10px -5px;
.
img {
filter: blur(5px);
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
margin: -5px -10px -10px -5px;
}
div {
overflow: hidden;
}
?
<div><img src="http://placekitten.com/300" />?????????????????????????????????????????????</div>????????????
I dont know for the other languages but in Java ++i is a prefix increment which means: increase i by 1 and then use the new value of i in the expression in which i resides, and i++ is a postfix increment which means the following: use the current value of i in the expression and then increase it by 1. Example:
public static void main(String [] args){
int a = 3;
int b = 5;
System.out.println(++a);
System.out.println(b++);
System.out.println(b);
} and the output is:
<IfModule mod_expires.c>
# Enable expirations
ExpiresActive On
# Default directive
ExpiresDefault "access plus 1 month"
# My favicon
ExpiresByType image/x-icon "access plus 1 year"
# Images
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
# CSS
ExpiresByType text/css "access plus 1 month"
# Javascript
ExpiresByType application/javascript "access plus 1 year"
</IfModule>
I know this is old. But yeah. I prefer much shorter solution, than Giona answer
[contenteditable] {
border-bottom: 1px solid transparent;
&:focus {outline: none; border-bottom: 1px dashed #000;}
}
My solution for changing seconds (number) to string format (for example: 'mm:ss'):
const formattedSeconds = moment().startOf('day').seconds(S).format('mm:ss');
Write your seconds instead 'S' in example. And just use the 'formattedSeconds' where you need.
Since iOS 11, you can use the native framework called PDFKit for displaying and manipulating PDFs.
After importing PDFKit, you should initialize a PDFView
with a local or a remote URL and display it in your view.
if let url = Bundle.main.url(forResource: "example", withExtension: "pdf") {
let pdfView = PDFView(frame: view.frame)
pdfView.document = PDFDocument(url: url)
view.addSubview(pdfView)
}
Read more about PDFKit in the Apple Developer documentation.
for $d in $doc/element2/element3
return fn:string-join(fn:data($d/element()), ".")
.
$doc stores the Xml.
just use javascript:---- exemplale
javascript:var JFL_81371678974472 = new JotformFeedback({ formId: '81371678974472', base: 'https://form.jotform.me/', windowTitle: 'Photobook Series', background: '#e44c2a', fontColor: '#FFFFFF', type: 'false', height: 700, width: 500, openOnLoad: true })
In Windows goto task-manager >"services" and check that "MySQL" is runing. If not
Right click on it ->open services->MySQL-> startup type -> 'Automatic' -> apply and OK. this is for windows 10 MySql 5.7
This works on SQL Server 2000.
use master
select count(*) From sysxlogins WHERE NAME = 'myUsername'
on SQL 2005, change the 2nd line to
select count(*) From syslogins WHERE NAME = 'myUsername'
I'm not sure about SQL 2008, but I'm guessing that it will be the same as SQL 2005 and if not, this should give you an idea of where t start looking.
You need to return your promise to the calling function.
islogged:function(){
var cUid=sessionService.get('uid');
alert("in loginServce, cuid is "+cUid);
var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
$checkSessionServer.then(function(){
alert("session check returned!");
console.log("checkSessionServer is "+$checkSessionServer);
});
return $checkSessionServer; // <-- return your promise to the calling function
}
If you are using WAMP on you local computer (mysql version 5.7.14) Step 1: open my.ini file Step 2: un-comment this line 'skip-grant-tables' by removing the semi-colon step 3: restart mysql server step 4: launch mySQL console step 5:
UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
FLUSH PRIVILEGES;
Step 6: Problem solved!!!!
If you are using PHP in bash shell you can use:
$server_name=exec('hostname');
Because $_SERVER[] SERVER_ADDR
, HTTP_HOST
and SERVER_NAME
are not set.
Here is my solution in Enterprise 1.11 (should work in CE 1.6):
$collection->addFieldToFilter('max_item_count',
array(
array('gteq' => 10),
array('null' => true),
)
)
->addFieldToFilter('max_item_price',
array(
array('gteq' => 9.99),
array('null' => true),
)
)
->addFieldToFilter('max_item_weight',
array(
array('gteq' => 1.5),
array('null' => true),
)
);
Which results in this SQL:
SELECT `main_table`.*
FROM `shipping_method_entity` AS `main_table`
WHERE (((max_item_count >= 10) OR (max_item_count IS NULL)))
AND (((max_item_price >= 9.99) OR (max_item_price IS NULL)))
AND (((max_item_weight >= 1.5) OR (max_item_weight IS NULL)))
No mention of Merge?
DataSet newdataset = new DataSet();
newdataset.Merge( olddataset.Tables[0].Select( filterstring, sortstring ));
You could use the legend's set_visible
method:
ax.legend().set_visible(False)
draw()
This is based on a answer provided to me in response to a similar question I had some time ago here
(Thanks for that answer Jouni - I'm sorry I was unable to mark the question as answered... perhaps someone who has the authority can do so for me?)
The obvious answer wasn't there in all the responses.
PHP has a neat streaming delimiter parser available made for exactly that purpose.
$fp = fopen("/path/to/the/file", "r+");
while (($line = stream_get_line($fp, 1024 * 1024, "\n")) !== false) {
echo $line;
}
fclose($fp);
For this i made a new simple tool. You can remove alpha channel (transparency) of multiple .png files within seconds.
You can download from here http://alphachannelremover.blogspot.com
When using laravel framework, I had some issues with using a route->back() function since it erased my hash. In order to keep my hash, I created a simple function:
$(function() {
if (localStorage.getItem("hash") ){
location.hash = localStorage.getItem("hash");
}
});
and I set it in my other JS function like this:
localStorage.setItem("hash", myvalue);
You can name your local storage values any way you like; mine named hash
.
Therefore, if the hash is set on PAGE1 and then you navigate to PAGE2; the hash will be recreated on PAGE1 when you click Back on PAGE2.
I prefer this command ll -sha
.
You can use npm install --save redux-form
Im writing a simple email and submit button form, which validates email and submits form. with redux-form, form by default runs event.preventDefault() on html onSubmit action.
import React, {Component} from 'react';
import {reduxForm} from 'redux-form';
class LoginForm extends Component {
onSubmit(props) {
//do your submit stuff
}
render() {
const {fields: {email}, handleSubmit} = this.props;
return (
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<input type="text" placeholder="Email"
className={`form-control ${email.touched && email.invalid ? 'has-error' : '' }`}
{...email}
/>
<span className="text-help">
{email.touched ? email.error : ''}
</span>
<input type="submit"/>
</form>
);
}
}
function validation(values) {
const errors = {};
const emailPattern = /(.+)@(.+){2,}\.(.+){2,}/;
if (!emailPattern.test(values.email)) {
errors.email = 'Enter a valid email';
}
return errors;
}
LoginForm = reduxForm({
form: 'LoginForm',
fields: ['email'],
validate: validation
}, null, null)(LoginForm);
export default LoginForm;
instead of getting Notepad++, You can simply Open the file with Wordpad and then Save As - Plain Text document
Did you check the binding is IIS? (inetmgr.exe) It may not be registered to accept all hostnames on 8080.
For example, if you set it up for mysite.com:8080 and hit it at localhost:8080, IIS will get the request but not have a hostname binding to match so it rejects.
Outside of that, you should check the IIS logs (C:\inetpub\logs\wmsvc#) on the server and see if you are seeing your request. Then you'll know if its a problem on your client or on the server itself.
I had a similar issue, and following reply from ArtB,
I found that my user didn't have the proper configurations. so what I did:
Note: manually modifying such XML files is risky. Do it at your own risk. Since I was already locked out, I didn't have much to lose. AFAIK Worst case I would have deleted the ~/.jenkins/config.xml file as prev post mentioned.
**> 1. ssh to the jenkins machine
- cd ~/.jenkins (I guess that some installations put it under /var/lib/jenkins/config.xml, but not in my case )
- vi config.xml, and under authorizationStrategy xml tag, add the below section (just used my username instead of "put-your-username")
- restart jenkins. in my case as root service tomcat7 stop; ; service tomcat7 start
- Try to login again. (worked for me)**
under
add:
<permission>hudson.model.Computer.Build:put-your-username</permission>
<permission>hudson.model.Computer.Configure:put-your-username</permission>
<permission>hudson.model.Computer.Connect:put-your-username</permission>
<permission>hudson.model.Computer.Create:put-your-username</permission>
<permission>hudson.model.Computer.Delete:put-your-username</permission>
<permission>hudson.model.Computer.Disconnect:put-your-username</permission>
<permission>hudson.model.Hudson.Administer:put-your-username</permission>
<permission>hudson.model.Hudson.ConfigureUpdateCenter:put-your-username</permission>
<permission>hudson.model.Hudson.Read:put-your-username</permission>
<permission>hudson.model.Hudson.RunScripts:put-your-username</permission>
<permission>hudson.model.Hudson.UploadPlugins:put-your-username</permission>
<permission>hudson.model.Item.Build:put-your-username</permission>
<permission>hudson.model.Item.Cancel:put-your-username</permission>
<permission>hudson.model.Item.Configure:put-your-username</permission>
<permission>hudson.model.Item.Create:put-your-username</permission>
<permission>hudson.model.Item.Delete:put-your-username</permission>
<permission>hudson.model.Item.Discover:put-your-username</permission>
<permission>hudson.model.Item.Read:put-your-username</permission>
<permission>hudson.model.Item.Workspace:put-your-username</permission>
<permission>hudson.model.Run.Delete:put-your-username</permission>
<permission>hudson.model.Run.Update:put-your-username</permission>
<permission>hudson.model.View.Configure:put-your-username</permission>
<permission>hudson.model.View.Create:put-your-username</permission>
<permission>hudson.model.View.Delete:put-your-username</permission>
<permission>hudson.model.View.Read:put-your-username</permission>
<permission>hudson.scm.SCM.Tag:put-your-username</permission>
Now, you can go to different directions. For example I had github oauth integration, so I could have tried to replace the authorizationStrategy with something like below:
Note:, It worked in my case because I had a specific github oauth plugin that was already configured. So it is more risky than the previous solution.
<authorizationStrategy class="org.jenkinsci.plugins.GithubAuthorizationStrategy" plugin="[email protected]">
<rootACL>
<organizationNameList class="linked-list">
<string></string>
</organizationNameList>
<adminUserNameList class="linked-list">
<string>put-your-username</string>
<string>username2</string>
<string>username3</string>
<string>username_4_etc_put_username_that_will_become_administrator</string>
</adminUserNameList>
<authenticatedUserReadPermission>true</authenticatedUserReadPermission>
<allowGithubWebHookPermission>false</allowGithubWebHookPermission>
<allowCcTrayPermission>false</allowCcTrayPermission>
<allowAnonymousReadPermission>false</allowAnonymousReadPermission>
</rootACL>
</authorizationStrategy>
I don't think a message box is the best way to go with this as you would need the VB code running in a loop to check the cell contents, or unless you plan to run the macro manually. In this case I think it would be better to add conditional formatting to the cell to change the background to red (for example) if the value exceeds the upper limit.
You could simple just do the reverse by making the base of log to e.
import math
e = 2.718281
math.log(e, 10) = 2.302585093
ln(10) = 2.30258093
Another possible solution, above solution failed for me in parsing query string params.
var regex = new RegExp("^(http[s]?:\\/\\/(www\\.)?|ftp:\\/\\/(www\\.)?|www\\.){1}([0-9A-Za-z-\\.@:%_\+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?");
if(regex.test("http://google.com")){
alert("Successful match");
}else{
alert("No match");
}
In this solution please feel free to modify [-0-9A-Za-z\.@:%_\+~#=
, to match the domain/sub domain name. In this solution query string parameters are also taken care.
If you are not using RegEx
, then from the expression replace \\
by \
.
Hope this helps.
You can also try:
...
var imageName = require('relative_path_of_image_from_component_file');
...
...
class XYZ extends Component {
render(){
return(
...
<img src={imageName.default} alt="something"/>
...
)
}
}
...
Note: Make sure Image is not outside the project root folder.
As an extension to @JBNizet's answer for more technical users here's what implementation of org.w3c.dom.Node
interface in com.sun.org.apache.xerces.internal.dom.ParentNode
looks like, gives you the idea how it actually works.
public void normalize() {
// No need to normalize if already normalized.
if (isNormalized()) {
return;
}
if (needsSyncChildren()) {
synchronizeChildren();
}
ChildNode kid;
for (kid = firstChild; kid != null; kid = kid.nextSibling) {
kid.normalize();
}
isNormalized(true);
}
It traverses all the nodes recursively and calls kid.normalize()
This mechanism is overridden in org.apache.xerces.dom.ElementImpl
public void normalize() {
// No need to normalize if already normalized.
if (isNormalized()) {
return;
}
if (needsSyncChildren()) {
synchronizeChildren();
}
ChildNode kid, next;
for (kid = firstChild; kid != null; kid = next) {
next = kid.nextSibling;
// If kid is a text node, we need to check for one of two
// conditions:
// 1) There is an adjacent text node
// 2) There is no adjacent text node, but kid is
// an empty text node.
if ( kid.getNodeType() == Node.TEXT_NODE )
{
// If an adjacent text node, merge it with kid
if ( next!=null && next.getNodeType() == Node.TEXT_NODE )
{
((Text)kid).appendData(next.getNodeValue());
removeChild( next );
next = kid; // Don't advance; there might be another.
}
else
{
// If kid is empty, remove it
if ( kid.getNodeValue() == null || kid.getNodeValue().length() == 0 ) {
removeChild( kid );
}
}
}
// Otherwise it might be an Element, which is handled recursively
else if (kid.getNodeType() == Node.ELEMENT_NODE) {
kid.normalize();
}
}
// We must also normalize all of the attributes
if ( attributes!=null )
{
for( int i=0; i<attributes.getLength(); ++i )
{
Node attr = attributes.item(i);
attr.normalize();
}
}
// changed() will have occurred when the removeChild() was done,
// so does not have to be reissued.
isNormalized(true);
}
Hope this saves you some time.
To simply answer your question when you do a mvn:install, maven will create a packaged artifact based on (packaging attribute in pom.xml), After you run your maven install you can find the file with .package extension
awk -F " " '($1=="A1") {print $NF}' FILE | tail -n 1
Use awk
with field separator -F set to a space " ".
Use the pattern $1=="A1"
and action {print $NF}
, this will print the last field in every record where the first field is "A1". Pipe the result into tail and use the -n 1
option to only show the last line.
You are assigning a numeric value to a text field. You have to convert the numeric value to a string with:
String.valueOf(variable)
You can use sed. But if you know perl, that might be easier, and more useful to know in the long run:
perl -n '/(\d+\.\d+\.\d+\.\d+)/ && print "$1\n"' < file
Since Symfony 3.3 you can use binding, like
services:
_defaults:
autowire: true
autoconfigure: true
bind:
$kernelProjectDir: '%kernel.project_dir%'
After that you can use parameter $kernelProjectDir in any controller OR service. Just like
class SomeControllerOrService
{
public function someAction(...., $kernelProjectDir)
{
.....
There are several way to approach globals:
Webpack evaluates modules only once, so your instance remains global and carries changes through from module to module. So if you create something like a globals.js
and export an object of all your globals then you can import './globals'
and read/write to these globals. You can import into one module, make changes to the object from a function and import into another module and read those changes in a function. Also remember the order things happen. Webpack will first take all the imports and load them up in order starting in your entry.js
. Then it will execute entry.js
. So where you read/write to globals is important. Is it from the root scope of a module or in a function called later?
config.js
export default {
FOO: 'bar'
}
somefile.js
import CONFIG from './config.js'
console.log(`FOO: ${CONFIG.FOO}`)
Note: If you want the instance to be new
each time, then use an ES6 class. Traditionally in JS you would capitalize classes (as opposed to the lowercase for objects) like
import FooBar from './foo-bar' // <-- Usage: myFooBar = new FooBar()
Here's how you can do it using Webpack's ProvidePlugin (which makes a module available as a variable in every module and only those modules where you actually use it). This is useful when you don't want to keep typing import Bar from 'foo'
again and again. Or you can bring in a package like jQuery or lodash as global here (although you might take a look at Webpack's Externals).
Step 1) Create any module. For example, a global set of utilities would be handy:
utils.js
export function sayHello () {
console.log('hello')
}
Step 2) Alias the module and add to ProvidePlugin:
webpack.config.js
var webpack = require("webpack");
var path = require("path");
// ...
module.exports = {
// ...
resolve: {
extensions: ['', '.js'],
alias: {
'utils': path.resolve(__dirname, './utils') // <-- When you build or restart dev-server, you'll get an error if the path to your utils.js file is incorrect.
}
},
plugins: [
// ...
new webpack.ProvidePlugin({
'utils': 'utils'
})
]
}
Now just call utils.sayHello()
in any js file and it should work. Make sure you restart your dev-server if you are using that with Webpack.
Note: Don't forget to tell your linter about the global, so it won't complain. For example, see my answer for ESLint here.
If you just want to use const with string values for your globals, then you can add this plugin to your list of Webpack plugins:
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(true),
VERSION: JSON.stringify("5fa3b9"),
BROWSER_SUPPORTS_HTML5: true,
TWO: "1+1",
"typeof window": JSON.stringify("object")
})
Use it like:
console.log("Running App version " + VERSION);
if(!BROWSER_SUPPORTS_HTML5) require("html5shiv");
window.foo = 'bar' // For SPA's, browser environment.
global.foo = 'bar' // Webpack will automatically convert this to window if your project is targeted for web (default), read more here: https://webpack.js.org/configuration/node/
You'll see this commonly used for polyfills, for example: window.Promise = Bluebird
(For server side projects) The dotenv package will take a local configuration file (which you could add to your .gitignore if there are any keys/credentials) and adds your configuration variables to Node's process.env object.
// As early as possible in your application, require and configure dotenv.
require('dotenv').config()
Create a .env
file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE
. For example:
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
That's it.
process.env
now has the keys and values you defined in your .env
file.
var db = require('db')
db.connect({
host: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASS
})
Regarding Webpack's Externals, use it if you want to exclude some modules from being included in your built bundle. Webpack will make the module globally available but won't put it in your bundle. This is handy for big libraries like jQuery (because tree shaking external packages doesn't work in Webpack) where you have these loaded on your page already in separate script tags (perhaps from a CDN).
One way:
We have Month
API in Java (java.time.Month
). We can get by using Month.of(month);
Here, the Month
are indexed as numbers so either you can provide by Month.JANUARY
or provide an index in the above API such as 1, 2, 3, 4.
Second way:
ZonedDateTime.now().getMonth();
This is available in java.time.ZonedDateTime
.
Something like this:
var objects = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor",
"bar" : "amet"
}
];
var results = [];
var toSearch = "lo";
for(var i=0; i<objects.length; i++) {
for(key in objects[i]) {
if(objects[i][key].indexOf(toSearch)!=-1) {
results.push(objects[i]);
}
}
}
The results array will contain all matched objects.
If you search for 'lo', the result will be like:
[{ foo="lorem", bar="ipsum"}, { foo="dolor", bar="amet"}]
NEW VERSION - Added trim code, code to ensure no duplicates in result set.
function trimString(s) {
var l=0, r=s.length -1;
while(l < s.length && s[l] == ' ') l++;
while(r > l && s[r] == ' ') r-=1;
return s.substring(l, r+1);
}
function compareObjects(o1, o2) {
var k = '';
for(k in o1) if(o1[k] != o2[k]) return false;
for(k in o2) if(o1[k] != o2[k]) return false;
return true;
}
function itemExists(haystack, needle) {
for(var i=0; i<haystack.length; i++) if(compareObjects(haystack[i], needle)) return true;
return false;
}
var objects = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor blor",
"bar" : "amet blo"
}
];
function searchFor(toSearch) {
var results = [];
toSearch = trimString(toSearch); // trim it
for(var i=0; i<objects.length; i++) {
for(var key in objects[i]) {
if(objects[i][key].indexOf(toSearch)!=-1) {
if(!itemExists(results, objects[i])) results.push(objects[i]);
}
}
}
return results;
}
console.log(searchFor('lo '));
I redirect stderr
to stdout
and then use grep's invert-match (-v
) to exclude the warning/error string that I want to hide:
grep -r <pattern> * 2>&1 | grep -v "No such file or directory"
This example might help someone:
Note "origin
" is my alias for remote "What is on Github"
Note "mybranch
" is my alias for my branch "what is local" that I'm syncing with github
--your branch name is 'master' if you didn't create one. However, I'm using the different name mybranch
to show where the branch name parameter is used.
What exactly are my remote repos on github?
$ git remote -v
origin https://github.com/flipmcf/Playground.git (fetch)
origin https://github.com/flipmcf/Playground.git (push)
Add the "other github repository of the same code" - we call this a fork:
$ git remote add someOtherRepo https://github.com/otherUser/Playground.git
$git remote -v
origin https://github.com/flipmcf/Playground.git (fetch)
origin https://github.com/flipmcf/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (fetch)
make sure our local repo is up to date:
$ git fetch
Change some stuff locally. let's say file ./foo/bar.py
$ git status
# On branch mybranch
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: foo/bar.py
Review my uncommitted changes
$ git diff mybranch
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index b4fb1be..516323b 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.
Commit locally.
$ git commit foo/bar.py -m"I changed stuff"
[myfork 9f31ff7] I changed stuff
1 files changed, 2 insertions(+), 1 deletions(-)
Now, I'm different than my remote (on github)
$ git status
# On branch mybranch
# Your branch is ahead of 'origin/mybranch' by 1 commit.
#
nothing to commit (working directory clean)
Diff this with remote - your fork:
(this is frequently done with git diff master origin
)
$ git diff mybranch origin
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index 516323b..b4fb1be 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.
(git push to apply these to remote)
How does my remote branch differ from the remote master branch?
$ git diff origin/mybranch origin/master
How does my local stuff differ from the remote master branch?
$ git diff origin/master
How does my stuff differ from someone else's fork, master branch of the same repo?
$git diff mybranch someOtherRepo/master
In mysql server 8.0, on Windows, the location is C:\ProgramData\MySQL\MySQL Server 8.0\Data
I know this question is 8 year old, however there was and is a better solution for this purpose. It's always been there, and still is: User32.dll!MessageBoxTimeout.
This is an undocumented function used by Microsoft Windows, and it does exactly what you want and even more. It supports different languages as well.
C# Import:
[DllImport("user32.dll", SetLastError = true)]
public static extern int MessageBoxTimeout(IntPtr hWnd, String lpText, String lpCaption, uint uType, Int16 wLanguageId, Int32 dwMilliseconds);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetForegroundWindow();
How to use it in C#:
uint uiFlags = /*MB_OK*/ 0x00000000 | /*MB_SETFOREGROUND*/ 0x00010000 | /*MB_SYSTEMMODAL*/ 0x00001000 | /*MB_ICONEXCLAMATION*/ 0x00000030;
NativeFunctions.MessageBoxTimeout(NativeFunctions.GetForegroundWindow(), $"Kitty", $"Hello", uiFlags, 0, 5000);
Work smarter, not harder.
See my select for paginator
SELECT TOP @limit * FROM (
SELECT ROW_NUMBER() OVER (ORDER BY colunx ASC) offset, * FROM (
-- YOU SELECT HERE
SELECT * FROM mytable
) myquery
) paginator
WHERE offset > @offset
This solves the pagination ;)
if you want to execute the statement when number of rows are modified then it can be possible by statement level triggers.. viseversa... when you want to execute your statement each modification on your number of rows then you need to go for row level triggers..
for example: statement level triggers works for when table is modified..then more number of records are effected. and row level triggers works for when each row updation or modification..
If you reference that image just once, I don’t see a problem to embed it into your CSS file. But once you use more than one image or need to reference it multiple times in your CSS, you might consider using a single image map instead you can then crop your single images from (see CSS Sprites).
Things to check when enabling the bundle optimization;
BundleTable.EnableOptimizations = true;
and
webconfig debug = "false"
bundles.IgnoreList.Clear();
this will ignore the minified assets of your bundles like *.min.css
or *.min.js
which can cause an undefine error of your script. To fix is replace the .min
asset to original. if you do this you may not need the bundles.IgnoreList.Clear();
e.g.
bundles.Add(new ScriptBundle("~/bundles/datatablesjs")
.Include("~/Scripts/datatables.min.js") <---- change this to non minified ver.
Make sure the names of the bundles of your css and js are unique.
bundles.Add(new StyleBundle("~/bundles/datatablescss").Include( ...) );
bundles.Add(new ScriptBundle("~/bundles/datatablesjs").Include( ...) );
Make sure you use the Render name of your @Script.Render and Style.Render are the same on your bundle config. e.g.
@Styles.Render("~/bundles/datatablescss")
@Scripts.Render("~/bundles/datatablesjs")
Or, even cleaner:
when(mockFoo.someMethod()).thenReturn(obj1, obj2);
You can use this in LinearLayout
:
android:divider="?android:dividerHorizontal"
android:showDividers="middle"
For Example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="?android:dividerHorizontal"
android:showDividers="middle"
android:orientation="vertical" >
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="abcd gttff hthjj ssrt guj"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="abcd"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="abcd gttff hthjj ssrt guj"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="abcd"/>
</LinearLayout>
The default timeout is 900 second. You can specify different timeout.
-T seconds
--timeout=seconds
The default is to retry 20 times. You can specify different tries.
-t number
--tries=number
link: wget man document
From the Official Whatsapp FAQ: https://faq.whatsapp.com/en/android/26000030/
WhatsApp's Click to Chat feature allows you to begin a chat with someone without having their phone number saved in your phone's address book. As long as you know this person’s phone number, you can create a link that will allow you to start a chat with them. By clicking the link, a chat with the person automatically opens. Click to Chat works on both your phone and WhatsApp Web.
To create your own link, use https://wa.me/ where the is a full phone number in international format. Omit any zeroes, brackets or dashes when adding the phone number in international format. For a detailed explanation on international numbers, read this article. Please keep in mind that this phone number must have an active account on WhatsApp.
Use: https://wa.me/15551234567
Don't use: https://wa.me/+001-(555)1234567
When an element already has a class name defined, its influence on the element is tied to its position in the string of class names. Later classes override earlier ones, if there is a conflict.
Adding a class to an element ought to move the class name to the sharp end of the list, if it exists already.
document.addClass= function(el, css){
var tem, C= el.className.split(/\s+/), A=[];
while(C.length){
tem= C.shift();
if(tem && tem!= css) A[A.length]= tem;
}
A[A.length]= css;
return el.className= A.join(' ');
}
I am not sure if this is pythonic, but seems to work
def alternate_list(a):
return a[::2], a[1::2]
key_list,value_list = alternate_list(a)
b = dict(zip(key_list,value_list))
In Windows, first installed Python 3.7 and then Python 2.7. Then, use command prompt:
pip install python2-module-name
pip3 install python3-module-name
That's all
Had the same problem. A colleague solved this with jQuery.Globalize.
<script src="/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="/Scripts/jquery.globalize/globalize.js" type="text/javascript"></script>
<script src="/Scripts/jquery.globalize/cultures/globalize.culture.nl.js"></script>
<script type="text/javascript">
var lang = 'nl';
$(function () {
Globalize.culture(lang);
});
// fixing a weird validation issue with dates (nl date notation) and Google Chrome
$.validator.methods.date = function(value, element) {
var d = Globalize.parseDate(value);
return this.optional(element) || !/Invalid|NaN/.test(d);
};
</script>
I am using jQuery Datepicker for selecting the date.
If none of the above seem to help, in my environment was broken from a system upgrade and I could not upgrade pip. While it won't give you an accurate list you can get an idea of which libraries were installed simply by looking inside your env>lib>python(version here)>site-packages> . Here you will get a good indication of modules installed.
callLog(){
this.http.get('http://localhost:3000/getstudent/'+this.login.email+'/'+this.login.password)
.subscribe(data => {
this.getstud=data as string[];
if(this.getstud.length!==0) {
console.log(data)
this.route.navigate(['home']);// used for routing after importing Router
}
});
}
The Permanent Generation (PermGen) space has completely been removed and is kind of replaced by a new space called Metaspace.The consequences of the PermGen removal is that obviously the PermSize and MaxPermSize JVM arguments are ignored and you will never get a java.lang.OutOfMemoryError
: PermGen error.
The JDK 8 HotSpot JVM is now using native memory for the representation of class metadata and is called Metaspace. Read More>>
Nothing works in my case using the scripts above but I was able to close these figures from eclipse console bar by clicking on Terminate ALL (two red nested squares icon).
The best way to stay on the same page is to post to the same page:
<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
Since and
has lower precedence than =
you can use it in condition assignment:
if ($var = true && false) // Compare true with false and assign to $var
if ($var = true and false) // Assign true to $var and compare $var to false
I don't use PDO for MySQL and PgSQL, but I do for SQLite. Is there a way (without completely changing the dbal back) to count rows like this in PDO?
Accordingly to this comment, the SQLite issue was introduced by an API change in 3.x.
That said, you might want to inspect how PDO actually implements the functionality before using it.
I'm not familiar with its internals but I'd be suspicious at the idea that PDO parses your SQL (since an SQL syntax error would appear in the DB's logs) let alone tries to make the slightest sense of it in order to count rows using an optimal strategy.
Assuming it doesn't indeed, realistic strategies for it to return a count of all applicable rows in a select statement include string-manipulating the limit clause out of your SQL statement, and either of:
A much better way to count, however, would be to execute the fully optimized query that will do so. More often than not, this means rewriting meaningful chunks of the initial query you're trying to paginate -- stripping unneeded fields and order by operations, etc.
Lastly, if your data sets are large enough that counts any kind of lag, you might also want to investigate returning the estimate derived from the statistics instead, and/or periodically caching the result in Memcache. At some point, having precisely correct counts is no longer useful...
You can get a list of the first element in each tuple using a list comprehension:
>>> my_tuples = [(1, 2, 3), ('a', 'b', 'c', 'd', 'e'), (True, False), 'qwerty']
>>> first_elts = [x[0] for x in my_tuples]
>>> first_elts
[1, 'a', True, 'q']
In our case, in 2020 using Python3, the solution to this problem was to move the Python installation to the cloud-init
startup script which instantiated the VM.
We had been encountering this same error when we had been trying to install Python using scripts that were called by users later in the VM's life cycle, but moving the same Python installation code to the cloud-init
script eliminated this problem.
To clarify, you should use HTTP error codes where they fit with the protocol, and not use HTTP status codes to send business logic errors.
Errors like insufficient balance, no cabs available, bad user/password qualify for HTTP status 200
with application specific error handling in the response body.
See this software engineering answer:
I would say it is better to be explicit about the separation of protocols. Let the HTTP server and the web browser do their own thing, and let the app do its own thing. The app needs to be able to make requests, and it needs the responses--and its logic as to how to request, how to interpret the responses, can be more (or less) complex than the HTTP perspective.
The ErrorDocument
directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot
. In your case, this means that the actual path to the ErrorDocument
is
ErrorDocument 404 /hellothere/error/404page.html
I was looking for something similar and came across this. It looks like in the first option you mentioned
r = requests.get('<MY_URI>', auth=('<MY_TOKEN>'))
"auth" takes two parameters: username and password, so the actual statement should be
r=requests.get('<MY_URI>', auth=('<YOUR_USERNAME>', '<YOUR_PASSWORD>'))
In my case, there was no password, so I left the second parameter in auth field empty as shown below:
r=requests.get('<MY_URI', auth=('MY_USERNAME', ''))
Hope this helps somebody :)
In some use cases, 307 redirects might be abused by an attacker to learn the victim's credentials.
Further information can be found in section 3.1 of A Comprehensive Formal Security Analysis of OAuth 2.0.
The authors of the above paper suggest the following:
Fix. Contrary to the current wording in the OAuth standard, the exact method of the redirect is not an implementation detail but essential for the security of OAuth. In the HTTP standard (RFC 7231), only the 303 redirect is defined unambigiously to drop the body of an HTTP POST request. All other HTTP redirection status codes, including the most commonly used 302, leave the browser the option to preserve the POST request and the form data. In practice, browsers typically rewrite to a GET request, thereby dropping the form data, except for 307 redirects. Therefore, the OAuth standard should require 303 redirects for the steps mentioned above in order to fix this problem.
If anyone is still unable to solve the issue, please check following thread and follow callmebob's answer.
PHPMailer - SMTP ERROR: Password command failed when send mail from my server
Firstly freq_series.plot
returns an axis not a figure so to make my answer a little more clear I've changed your given code to refer to it as ax
rather than fig
to be more consistent with other code examples.
You can get the list of the bars produced in the plot from the ax.patches
member. Then you can use the technique demonstrated in this matplotlib
gallery example to add the labels using the ax.text
method.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)
x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)
rects = ax.patches
# Make some labels.
labels = ["label%d" % i for i in xrange(len(rects))]
for rect, label in zip(rects, labels):
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2, height + 5, label,
ha='center', va='bottom')
This produces a labeled plot that looks like:
The kernel is part of the operating system and closer to the hardware it provides low level services like:
An operating system also includes applications like the user interface (shell, gui, tools, and services).
As far as I can tell, there is no way to write a setter for a class property without creating a new metaclass.
I have found that the following method works. Define a metaclass with all of the class properties and setters you want. IE, I wanted a class with a title
property with a setter. Here's what I wrote:
class TitleMeta(type):
@property
def title(self):
return getattr(self, '_title', 'Default Title')
@title.setter
def title(self, title):
self._title = title
# Do whatever else you want when the title is set...
Now make the actual class you want as normal, except have it use the metaclass you created above.
# Python 2 style:
class ClassWithTitle(object):
__metaclass__ = TitleMeta
# The rest of your class definition...
# Python 3 style:
class ClassWithTitle(object, metaclass = TitleMeta):
# Your class definition...
It's a bit weird to define this metaclass as we did above if we'll only ever use it on the single class. In that case, if you're using the Python 2 style, you can actually define the metaclass inside the class body. That way it's not defined in the module scope.
The main benefit of "".equals(s)
is you don't need the null check (equals
will check its argument and return false
if it's null), which you seem to not care about. If you're not worried about s
being null (or are otherwise checking for it), I would definitely use s.isEmpty()
; it shows exactly what you're checking, you care whether or not s
is empty, not whether it equals the empty string
You can use lambda function, an example for 1D array:
import numpy as np
a = [np.nan, 2, 3]
map(lambda v:0 if np.isnan(v) == True else v, a)
This will give you the result:
[0, 2, 3]
Just throw everything you read into a MemoryStream
and get the byte array in the end. As noted, you should be reading from the underlying stream to get the raw bytes.
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
var buffer = new byte[512];
var bytesRead = default(int);
while ((bytesRead = reader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
memstream.Write(buffer, 0, bytesRead);
bytes = memstream.ToArray();
}
Or if you don't want to manage the buffers:
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
reader.BaseStream.CopyTo(memstream);
bytes = memstream.ToArray();
}
Yes, there does seem to be 3rd libraries (none in Java Math). Two that have come up are:
http://www.iro.umontreal.ca/~simardr/ssj/indexe.html
but, it is actually not that difficult to write your own methods to calculate mean, median, mode and range.
MEAN
public static double mean(double[] m) {
double sum = 0;
for (int i = 0; i < m.length; i++) {
sum += m[i];
}
return sum / m.length;
}
MEDIAN
// the array double[] m MUST BE SORTED
public static double median(double[] m) {
int middle = m.length/2;
if (m.length%2 == 1) {
return m[middle];
} else {
return (m[middle-1] + m[middle]) / 2.0;
}
}
MODE
public static int mode(int a[]) {
int maxValue, maxCount;
for (int i = 0; i < a.length; ++i) {
int count = 0;
for (int j = 0; j < a.length; ++j) {
if (a[j] == a[i]) ++count;
}
if (count > maxCount) {
maxCount = count;
maxValue = a[i];
}
}
return maxValue;
}
UPDATE
As has been pointed out by Neelesh Salpe, the above does not cater for multi-modal collections. We can fix this quite easily:
public static List<Integer> mode(final int[] numbers) {
final List<Integer> modes = new ArrayList<Integer>();
final Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();
int max = -1;
for (final int n : numbers) {
int count = 0;
if (countMap.containsKey(n)) {
count = countMap.get(n) + 1;
} else {
count = 1;
}
countMap.put(n, count);
if (count > max) {
max = count;
}
}
for (final Map.Entry<Integer, Integer> tuple : countMap.entrySet()) {
if (tuple.getValue() == max) {
modes.add(tuple.getKey());
}
}
return modes;
}
ADDITION
If you are using Java 8 or higher, you can also determine the modes like this:
public static List<Integer> getModes(final List<Integer> numbers) {
final Map<Integer, Long> countFrequencies = numbers.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
final long maxFrequency = countFrequencies.values().stream()
.mapToLong(count -> count)
.max().orElse(-1);
return countFrequencies.entrySet().stream()
.filter(tuple -> tuple.getValue() == maxFrequency)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
Request.Form is a NameValueCollection. In NameValueCollection you can find the GetAllValues() method.
By the way the LINQ method also works.
function onMouseOut(event) {
//this is the original element the event handler was assigned to
var e = event.toElement || event.relatedTarget;
if (e.parentNode == this || e == this) {
return;
}
alert('MouseOut');
// handle mouse event here!
}
document.getElementById('parent').addEventListener('mouseout',onMouseOut,true);
I made a quick JsFiddle demo, with all the CSS and HTML needed, check it out...
EDIT FIXED link for cross-browser support http://jsfiddle.net/RH3tA/9/
NOTE that this only checks the immediate parent, if the parent div had nested children then you have to somehow traverse through the elements parents looking for the "Orginal element"
EDIT example for nested children
EDIT Fixed for hopefully cross-browser
function makeMouseOutFn(elem){
var list = traverseChildren(elem);
return function onMouseOut(event) {
var e = event.toElement || event.relatedTarget;
if (!!~list.indexOf(e)) {
return;
}
alert('MouseOut');
// handle mouse event here!
};
}
//using closure to cache all child elements
var parent = document.getElementById("parent");
parent.addEventListener('mouseout',makeMouseOutFn(parent),true);
//quick and dirty DFS children traversal,
function traverseChildren(elem){
var children = [];
var q = [];
q.push(elem);
while (q.length > 0) {
var elem = q.pop();
children.push(elem);
pushAll(elem.children);
}
function pushAll(elemArray){
for(var i=0; i < elemArray.length; i++) {
q.push(elemArray[i]);
}
}
return children;
}
And a new JSFiddle, EDIT updated link
I had a similar issue, but I was able to solve mine by specifying explicitly the app_label using Meta Class in my models class
class Meta:
app_label = 'name_of_my_app'
Since you are going to use this in a login page. Here is a code I used in a Login page using Material-UI
<Grid
container
spacing={0}
direction="column"
alignItems="center"
justify="center"
style={{ minHeight: '100vh' }}
>
<Grid item xs={3}>
<LoginForm />
</Grid>
</Grid>
this will make this login form at the center of the screen.
But still IE doesn't support the Material-UI Grid and you will see some misplaced content in IE.
Hope this will help you.
I use this handy function:
By downloading it with a 4094 byte step it will not full your memory
function download($file_source, $file_target) {
$rh = fopen($file_source, 'rb');
$wh = fopen($file_target, 'w+b');
if (!$rh || !$wh) {
return false;
}
while (!feof($rh)) {
if (fwrite($wh, fread($rh, 4096)) === FALSE) {
return false;
}
echo ' ';
flush();
}
fclose($rh);
fclose($wh);
return true;
}
Usage:
$result = download('http://url','path/local/file');
You can then check if everything is ok with:
if (!$result)
throw new Exception('Download error...');
You can provide one or multiple event types separated by a space.
So hover
equals mouseenter mouseleave
.
This is my sugession:
$("#foo").on("mouseenter mouseleave", function() {
// do some stuff
});
You typically want to render templates like this:
app.get('/', function(req, res){
res.render('index.ejs');
});
However you can also deliver static content - to do so use:
app.use(express.static(__dirname + '/public'));
Now everything in the /public
directory of your project will be delivered as static content at the root of your site e.g. if you place default.htm
in the public folder if will be available by visiting /default.htm
Take a look through the express API and Connect Static middleware docs for more info.
Here's the solution you're looking for:
>>> foos = [1.0, 2.0, 3.0, 4.0, 5.0]
>>> bars = [1, 2, 3]
>>> [(x, bars) for x in foos]
[(1.0, [1, 2, 3]), (2.0, [1, 2, 3]), (3.0, [1, 2, 3]), (4.0, [1, 2, 3]), (5.0, [
1, 2, 3])]
I'd recommend using a list comprehension (the [(x, bars) for x in foos]
part) over using map as it avoids the overhead of a function call on every iteration (which can be very significant). If you're just going to use it in a for loop, you'll get better speeds by using a generator comprehension:
>>> y = ((x, bars) for x in foos)
>>> for z in y:
... print z
...
(1.0, [1, 2, 3])
(2.0, [1, 2, 3])
(3.0, [1, 2, 3])
(4.0, [1, 2, 3])
(5.0, [1, 2, 3])
The difference is that the generator comprehension is lazily loaded.
UPDATE In response to this comment:
Of course you know, that you don't copy bars, all entries are the same bars list. So if you modify any one of them (including original bars), you modify all of them.
I suppose this is a valid point. There are two solutions to this that I can think of. The most efficient is probably something like this:
tbars = tuple(bars)
[(x, tbars) for x in foos]
Since tuples are immutable, this will prevent bars from being modified through the results of this list comprehension (or generator comprehension if you go that route). If you really need to modify each and every one of the results, you can do this:
from copy import copy
[(x, copy(bars)) for x in foos]
However, this can be a bit expensive both in terms of memory usage and in speed, so I'd recommend against it unless you really need to add to each one of them.
Let's set the terms. The Aggregation is a metaterm in the UML standard, and means BOTH composition and shared aggregation, simply named shared. Too often it is named incorrectly "aggregation". It is BAD, for composition is an aggregation, too. As I understand, you mean "shared".
Further from UML standard:
composite - Indicates that the property is aggregated compositely, i.e., the composite object has responsibility for the existence and storage of the composed objects (parts).
So, University to cathedras association is a composition, because cathedra doesn't exist out of University (IMHO)
Precise semantics of shared aggregation varies by application area and modeler.
I.e., all other associations can be drawn as shared aggregations, if you are only following to some principles of yours or of somebody else. Also look here.
I know the question explicitly says JS or jQuery, but anyway using lodash is always on the table for other searchers I suppose.
From the source docs:
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false }
];
_.filter(users, function(o) { return !o.active; });
// => objects for ['fred']
// The `_.matches` iteratee shorthand.
_.filter(users, { 'age': 36, 'active': true });
// => objects for ['barney']
// The `_.matchesProperty` iteratee shorthand.
_.filter(users, ['active', false]);
// => objects for ['fred']
// The `_.property` iteratee shorthand.
_.filter(users, 'active');
// => objects for ['barney']
So the solution for the original question would be just one liner:
var result = _.filter(data, ['website', 'yahoo']);
What about using a HashMap
? Insertion, deletion, and retrieval are all O(1) operations. If you wanted to sort everything, you could grab a List of the values in the Map and run them through an O(n log n) sorting algorithm.
edit
A quick search has found LinkedHashMap, which maintains insertion order of your keys. It's not an exact solution, but it's pretty close.
It's because your statement does not produce output.
Besides all the warnings of Darin and lazy (they are right); the question still offerst something to learn.
If you want to execute methods that don't directly produce output, you do:
@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}
This is also true for rendering partials like:
@{ Html.RenderPartial("_MyPartial"); }
If you set id in your database to be primary key and autoincrement, then this line of code is wrong:
user.setId(1);
Try with this:
public static void main(String[] args){
UserBean user = new UserBean();
user.setUserName("name1");
user.setPassword("passwd1");
em.persist(user);
}
You can use .present? which comes included with ActiveSupport.
@city = @user.city.present?
# etc ...
You could even write it like this
def show
%w(city state bio contact twitter mail).each do |attr|
instance_variable_set "@#{attr}", @user[attr].present?
end
end
It's worth noting that if you want to test if something is blank, you can use .blank?
(this is the opposite of .present?
)
Also, don't use foo == nil
. Use foo.nil?
instead.
In C# Predicates are simply delegates that return booleans. They're useful (in my experience) when you're searching through a collection of objects and want something specific.
I've recently run into them in using 3rd party web controls (like treeviews) so when I need to find a node within a tree, I use the .Find() method and pass a predicate that will return the specific node I'm looking for. In your example, if 'a' mod 2 is 0, the delegate will return true. Granted, when I'm looking for a node in a treeview, I compare it's name, text and value properties for a match. When the delegate finds a match, it returns the specific node I was looking for.
My working code
public View onCreateView(...){
mWebView = (WebView) view.findViewById(R.id.webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
...
...
...
CookieSyncManager.createInstance(mWebView.getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
//cookieManager.removeSessionCookie(); // remove
cookieManager.removeAllCookie(); //remove
// Recommended "hack" with a delay between the removal and the installation of "Cookies"
SystemClock.sleep(1000);
cookieManager.setCookie("https://my.app.site.com/", "cookiename=" + value + "; path=/registration" + "; secure"); // ;
CookieSyncManager.getInstance().sync();
mWebView.loadUrl(sp.getString("url", "") + end_url);
return view;
}
To debug the query, "cookieManager.setCookie (....);" I recommend you to look through the contents of the database webviewCookiesChromium.db (stored in "/data/data/my.app.webview/database") There You can see the correct settings.
Disabling "cookieManager.removeSessionCookie();" and/or "cookieManager.removeAllCookie();"
//cookieManager.removeSessionCookie();
// and/or
//cookieManager.removeAllCookie();"
Compare the set value with those that are set by the browser. Adjust the request for the installation of the cookies before until "flags" browser is not installed will fit with what You decide. I found that a query can be "flags":
// You may want to add the secure flag for https:
+ "; secure"
// In case you wish to convert session cookies to have an expiration:
+ "; expires=Thu, 01-Jan-2037 00:00:10 GMT"
// These flags I found in the database:
+ "; path=/registration"
+ "; domain=my.app.site.com"
If you are like me using ubuntu 10.10 & cant find the lastest version which is now
this is where you can get it http://www.ubuntuupdates.org/package/brightbox_ruby_ng_experimental/maverick/main/base/ruby1.9.3
or download the *.deb file :)
& remember that it wont alter you old version of ruby
Another solution:
public class CountryInfoResponse {
private List<Object> geonames;
}
Usage of a generic Object-List solved my problem, as there were other Datatypes like Boolean too.
Try StickyList
from Cactoos:
List<String> list = new StickyList<>(iterable);
Disclaimer: I'm one of the developers.
Found this documentation for the TYPE command:
Convert an ASCII (Windows1252) file into a Unicode (UCS-2 le) text file:
For /f "tokens=2 delims=:" %%G in ('CHCP') do Set _codepage=%%G
CHCP 1252 >NUL
CMD.EXE /D /A /C (SET/P=ÿþ)<NUL > unicode.txt 2>NUL
CMD.EXE /D /U /C TYPE ascii_file.txt >> unicode.txt
CHCP %_codepage%
The technique above (based on a script by Carlos M.) first creates a file with a Byte Order Mark (BOM) and then appends the content of the original file. CHCP is used to ensure the session is running with the Windows1252 code page so that the characters 0xFF and 0xFE (ÿþ) are interpreted correctly.
From a command line you could run:
watch --interval=[your-interval-in-seconds] "mysqladmin -u root -p[your-root-pw] processlist | grep [your-db-name]"
Replace the values [x] with your values.
Or even better:
mysqladmin -u root -p -i 1 processlist;
You could add a span before the link with a specific class like so:
<div class="btn btn_red"><span class="icon"></span><a href="#">Crimson</a><span></span></div>
And then give that a specific width and a background image just like you are doing with the button itself.
.btn span.icon {
background: url(imgs/icon.png) no-repeat;
float: left;
width: 10px;
height: 40px;
}
I am no CSS guru but off the top of my head I think that should work.
If you are using Python, I would suggest by exploring the request object:
dir(request)
Since the object support the method dict:
request.__dict__
It can be printed or saved. I use it to log 404 codes in Flask:
@app.errorhandler(404)
def not_found(e):
with open("./404.csv", "a") as f:
f.write(f'{datetime.datetime.now()},{request.__dict__}\n')
return send_file('static/images/Darknet-404-Page-Concept.png', mimetype='image/png')
You can't - in theory. The whole point of a hash is that it's one way only. This means that if someone manages to get the list of hashes, they still can't get your password. Additionally it means that even if someone uses the same password on multiple sites (yes, we all know we shouldn't, but...) anyone with access to the database of site A won't be able to use the user's password on site B.
The fact that MD5 is a hash also means it loses information. For any given MD5 hash, if you allow passwords of arbitrary length there could be multiple passwords which produce the same hash. For a good hash it would be computationally infeasible to find them beyond a pretty trivial maximum length, but it means there's no guarantee that if you find a password which has the target hash, it's definitely the original password. It's astronomically unlikely that you'd see two ASCII-only, reasonable-length passwords that have the same MD5 hash, but it's not impossible.
MD5 is a bad hash to use for passwords:
I'm not a security expert, so won't make a concrete recommendation beyond "Don't roll your own authentication system." Find one from a reputable supplier, and use that. Both the design and implementation of security systems is a tricky business.
First of all create on file and then convert your xml data in array and retrieve that data in json format for ajax success response.
Try as below:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "sample.php",
success: function (response) {
var obj = $.parseJSON(response);
for(var i=0;i<obj.length;i++){
// here you can add html through loop
}
}
});
});
sample.php
$xml = "YOUR XML FILE PATH";
$json = json_encode((array)simplexml_load_string($xml)),1);
echo $json;
Here's a concrete example:
Suppose you have a function that calculates the gravitational force acting on an object. If you don't know the formula, you can find it here. This function takes in the three necessary parameters as arguments.
Now, being on the earth, you only want to calculate forces for objects on this planet. In a functional language, you could pass in the mass of the earth to the function and then partially evaluate it. What you'd get back is another function that takes only two arguments and calculates the gravitational force of objects on earth. This is called currying.
Yes this post is 8 years old, but incase someone comes on here also looking for an answer: you can now just use semicolons. However, you cannot use if/elif/else staments, for/while loops, and you can't define functions. The main use of this would be when using imported modules where you don't have to define any functions or use any if/elif/else/for/while statements/loops.
Here's an example that takes the artist of a song, the song name, and searches genius for the lyrics:
import bs4, requests; song = input('Input artist then song name\n'); print(bs4.BeautifulSoup(requests.get(f'https://genius.com/{song.replace(" ", "-")}-lyrics').text,'html.parser').select('.lyrics')[0].text.strip())
find
has a -delete
action:
find . -maxdepth 1 -name '*.pdf' -delete
Please try this code
new_column=df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).count()
df['count_it']=new_column
df
I think that code will add a column called 'count it' which count of each group
My own version of Kim T's code above which combines with some jQuery and allows for targeting of specific iframes.
$(function() {
callPlayer($('#iframe')[0], 'unMute');
});
function callPlayer(iframe, func, args) {
if ( iframe.src.indexOf('youtube.com/embed') !== -1) {
iframe.contentWindow.postMessage( JSON.stringify({
'event': 'command',
'func': func,
'args': args || []
} ), '*');
}
}
There are three different conventions (it could be said that those are de facto standards) to set and display a line break:
carriage return
+ line feed
line feed
carriage return
In some text editors, it is possible to exchange one for the other:
The simplest thing is to normalize to line feed
and then split.
final String[] lines = contents.replace("\r\n", "\n")
.replace("\r", "\n")
.split("\n", -1);
Adding a step-by-step guide to @Codeply-er's answer above for SASS/SCSS newbies like me.
btnCustom.scss
./* import the necessary Bootstrap files */
@import 'bootstrap';
/* Define color */
$mynewcolor:#77cccc;
.btn-custom {
@include button-variant($mynewcolor, darken($mynewcolor, 7.5%), darken($mynewcolor, 10%), lighten($mynewcolor,5%), lighten($mynewcolor, 10%), darken($mynewcolor,30%));
}
.btn-outline-custom {
@include button-outline-variant($mynewcolor, #222222, lighten($mynewcolor,5%), $mynewcolor);
}
_bootstrap.scss
file as below. This will allow the compiler to access the Bootstrap functions and variables.@import "bootstrap/scss/functions";
@import "bootstrap/scss/variables";
@import "bootstrap/scss/mixins";
@import "bootstrap/scss/root";
@import "bootstrap/scss/reboot";
@import "bootstrap/scss/type";
@import "bootstrap/scss/images";
@import "bootstrap/scss/grid";
@import "bootstrap/scss/tables";
@import "bootstrap/scss/forms";
@import "bootstrap/scss/buttons";
@import "bootstrap/scss/utilities";
btnCustom.scss
with the previously downloaded compiler to css.I got it. It worked fine
Thank you for your help:
EXEC sp_addlinkedserver @server='Servername'
EXEC sp_addlinkedsrvlogin 'Servername', 'false', NULL, 'username', 'password@123'
All of these options work depending on your situation, but you may not see any of them work if you're using SSMS (as mentioned in some comments SSMS hides CR/LFs)
So rather than driving yourself round the bend, Check this setting in
Tools
|
Options
In my case I was running Tensorflow Docker container in Ubuntu 20.04 :Run your docker container in One terminal , I ran it with
docker run -it od
And then started another terminal and ran below docker ps
with sudo:
sudo docker ps
I successfully got container id:
CONTAINER ID IMAGE COMMAND CREATED
STATUS PORTS NAMES
e4ca1ad20b84 od "/bin/bash" 18 minutes ago
Up 18 minutes unruffled_stonebraker
Im using the following code in order to access generated find methods from my custom implementation. Getting the implementation through the bean factory prevents circular bean creation problems.
public class MyRepositoryImpl implements MyRepositoryExtensions, BeanFactoryAware {
private BrandRepository myRepository;
public MyBean findOne(int first, int second) {
return myRepository.findOne(new Id(first, second));
}
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
myRepository = beanFactory.getBean(MyRepository.class);
}
}
You can do like below to achieve your result:
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
....
....
#use filter with plot
#or
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') | (df1['Retailer country']=='France')], kind='count')
fg.set_xlabels('Retailer country')
plt.show()
#also
#and
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') & (df1['Year']=='2013')], kind='count')
fg.set_xlabels('Retailer country')
plt.show()
Seems like an old question but still relevant.
I think it is a blocked update issue.
The main problem is the new URL (route) is supposed to be rendered by the same component(Costumers
) as you are currently in (current URL).
So solution is rather simple, make the window url as a prop, so react has a chance to detect the prop change (therefore the url change), and act accordingly.
A nice usecase described in the official react blog called Recommendation: Fully uncontrolled component with a key.
So the solution is to change from
render() {
return(
<ul>
to
render() {
return(
<ul key={this.props.location.pathname}>
So whenever the location changed by react-router, the component got scrapped (by react) and a new one gets initiated with the right values (by react).
Oh, and pass the location
as prop to the component(Costumers
) where the redirect will happen if it is not passed already.
Hope it helps someone.
First. You have mistake in using function strtotime
see PHP documentation
int strtotime ( string $time [, int $now = time() ] )
You need modify your code to pass integer timestamp into this function.
Second. You use format d.m.Y H:i that includes time part. If you wish to compare only dates, you must remove time part, e.g. `$date = date("d.m.Y");``
Third. I am not sure if it works in the same way for you, but my PHP doesn't understand date format from $timestamp
and returns 01.01.1970 02:00 into $match_date
$timestamp = "2014.09.02T13:34";
date('d.m.Y H:i', strtotime($timestamp)) === "01.01.1970 02:00";
You need to check if strtotime($timestamp)
returns correct date string. If no, you need to specify format which is used in $timestamp
variable. You can do this using one of functions date_parse_from_format
or DateTime::createFromFormat
This is a work example:
$timestamp = "2014.09.02T13:34";
$today = new DateTime(); // This object represents current date/time
$today->setTime( 0, 0, 0 ); // reset time part, to prevent partial comparison
$match_date = DateTime::createFromFormat( "Y.m.d\\TH:i", $timestamp );
$match_date->setTime( 0, 0, 0 ); // reset time part, to prevent partial comparison
$diff = $today->diff( $match_date );
$diffDays = (integer)$diff->format( "%R%a" ); // Extract days count in interval
switch( $diffDays ) {
case 0:
echo "//Today";
break;
case -1:
echo "//Yesterday";
break;
case +1:
echo "//Tomorrow";
break;
default:
echo "//Sometime";
}
Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.
Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.
// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>
#include "unzip.h"
#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192
int main( int argc, char **argv )
{
if ( argc < 2 )
{
printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
return -1;
}
// Open the zip file
unzFile *zipfile = unzOpen( argv[ 1 ] );
if ( zipfile == NULL )
{
printf( "%s: not found\n" );
return -1;
}
// Get info about the zip file
unz_global_info global_info;
if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
{
printf( "could not read file global info\n" );
unzClose( zipfile );
return -1;
}
// Buffer to hold data read from the zip file.
char read_buffer[ READ_SIZE ];
// Loop to extract all files
uLong i;
for ( i = 0; i < global_info.number_entry; ++i )
{
// Get info about current file.
unz_file_info file_info;
char filename[ MAX_FILENAME ];
if ( unzGetCurrentFileInfo(
zipfile,
&file_info,
filename,
MAX_FILENAME,
NULL, 0, NULL, 0 ) != UNZ_OK )
{
printf( "could not read file info\n" );
unzClose( zipfile );
return -1;
}
// Check if this entry is a directory or file.
const size_t filename_length = strlen( filename );
if ( filename[ filename_length-1 ] == dir_delimter )
{
// Entry is a directory, so create it.
printf( "dir:%s\n", filename );
mkdir( filename );
}
else
{
// Entry is a file, so extract it.
printf( "file:%s\n", filename );
if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
{
printf( "could not open file\n" );
unzClose( zipfile );
return -1;
}
// Open a file to write out the data.
FILE *out = fopen( filename, "wb" );
if ( out == NULL )
{
printf( "could not open destination file\n" );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
int error = UNZ_OK;
do
{
error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
if ( error < 0 )
{
printf( "error %d\n", error );
unzCloseCurrentFile( zipfile );
unzClose( zipfile );
return -1;
}
// Write data to file.
if ( error > 0 )
{
fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
}
} while ( error > 0 );
fclose( out );
}
unzCloseCurrentFile( zipfile );
// Go the the next entry listed in the zip file.
if ( ( i+1 ) < global_info.number_entry )
{
if ( unzGoToNextFile( zipfile ) != UNZ_OK )
{
printf( "cound not read next file\n" );
unzClose( zipfile );
return -1;
}
}
}
unzClose( zipfile );
return 0;
}
I built and tested it with MinGW/MSYS on Windows like this:
contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/zlib-125.zip
Adding another answer that uses switch
... There are more comprehensive examples out there, but this will give you the idea.
In example, t
becomes the specified data type within each case
scope. Note, you have to provide a case
for only one type at a type, otherwise t
remains an interface
.
package main
import "fmt"
func main() {
var val interface{} // your starting value
val = 4
var i int // your final value
switch t := val.(type) {
case int:
fmt.Printf("%d == %T\n", t, t)
i = t
case int8:
fmt.Printf("%d == %T\n", t, t)
i = int(t) // standardizes across systems
case int16:
fmt.Printf("%d == %T\n", t, t)
i = int(t) // standardizes across systems
case int32:
fmt.Printf("%d == %T\n", t, t)
i = int(t) // standardizes across systems
case int64:
fmt.Printf("%d == %T\n", t, t)
i = int(t) // standardizes across systems
case bool:
fmt.Printf("%t == %T\n", t, t)
// // not covertible unless...
// if t {
// i = 1
// } else {
// i = 0
// }
case float32:
fmt.Printf("%g == %T\n", t, t)
i = int(t) // standardizes across systems
case float64:
fmt.Printf("%f == %T\n", t, t)
i = int(t) // standardizes across systems
case uint8:
fmt.Printf("%d == %T\n", t, t)
i = int(t) // standardizes across systems
case uint16:
fmt.Printf("%d == %T\n", t, t)
i = int(t) // standardizes across systems
case uint32:
fmt.Printf("%d == %T\n", t, t)
i = int(t) // standardizes across systems
case uint64:
fmt.Printf("%d == %T\n", t, t)
i = int(t) // standardizes across systems
case string:
fmt.Printf("%s == %T\n", t, t)
// gets a little messy...
default:
// what is it then?
fmt.Printf("%v == %T\n", t, t)
}
fmt.Printf("i == %d\n", i)
}
HTML
<div id="footer"></div>
CSS
#footer {
position:absolute;
bottom:0;
width:100%;
height:100px;
background:blue;//optional
}
<a target="_blank" title="Share this page" href="http://www.sharethis.com/share?url=[INSERT URL]&title=[INSERT TITLE]&summary=[INSERT SUMMARY]&img=[INSERT IMAGE URL]&pageInfo=%7B%22hostname%22%3A%22[INSERT DOMAIN NAME]%22%2C%22publisher%22%3A%22[INSERT PUBLISHERID]%22%7D"><img width="86" height="25" alt="Share this page" src="http://w.sharethis.com/images/share-classic.gif"></a>
Instructions
First, insert these lines wherever you want within your newsletter code. Then:
If you are using this on an email newsletter, make sure you add our sharing buttons to the destination page. This will ensure that you get complete sharing analytics for your page. Make sure you replace "INSERT PUBLISHERID" with your own.
You can achieve what you want if you preprocess your .css files through php. ...
$something='color:red;'
$else='display:inline;';
echo '.something {'. $something .'}';
echo '.else {'. $something .'}';
echo '.somethingelse {'. $something .$else '}';
...
I am days into the MVC4 world.
For what its worth, I have a SitesAPIController, and I needed a custom method, that could be called like:
http://localhost:9000/api/SitesAPI/Disposition/0
With different values for the last parameter to get record with different dispositions.
What Finally worked for me was:
The method in the SitesAPIController:
// GET api/SitesAPI/Disposition/1
[ActionName("Disposition")]
[HttpGet]
public Site Disposition(int disposition)
{
Site site = db.Sites.Where(s => s.Disposition == disposition).First();
return site;
}
And this in the WebApiConfig.cs
// this was already there
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// this i added
config.Routes.MapHttpRoute(
name: "Action",
routeTemplate: "api/{controller}/{action}/{disposition}"
);
For as long as I was naming the {disposition} as {id} i was encountering:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:9000/api/SitesAPI/Disposition/0'.",
"MessageDetail": "No action was found on the controller 'SitesAPI' that matches the request."
}
When I renamed it to {disposition} it started working. So apparently the parameter name is matched with the value in the placeholder.
Feel free to edit this answer to make it more accurate/explanatory.
EDIT: Check if the api you’re interacting with is set to Content-Type: application/json
, &/or if your client http library is both stringify-ing and parsing the http request body behind the scenes. My client library was generated by swagger, and was the reason I needed to apply these hacks, as the client library was stringifying my pre-stringified body (body: “jsonString”
, instead of body: { ...normal payload }
). All I had to do was change the api to Content-Type: text/plain
, which removed the JSON stringify/parsing on that route, and then none of these hacks were needed. You can also change only the "consumes" or "produces" portion of the api, see here.
ORIGINAL: If your Googles keep landing you here and your api throws errors unless your JSON double quotes are escaped ("{\"foo\": true}"
), all you need to do is stringify twice e.g. JSON.stringify(JSON.stringify(bar))
I had trouble with the accepted answer due to no type hinting on the "document" variable: var document = ...
So I'm posting what worked for me as an alternative in case anybody else is having trouble.
public ActionResult DownloadFile()
{
string filename = "File.pdf";
string filepath = AppDomain.CurrentDomain.BaseDirectory + "/Path/To/File/" + filename;
byte[] filedata = System.IO.File.ReadAllBytes(filepath);
string contentType = MimeMapping.GetMimeMapping(filepath);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = true,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(filedata, contentType);
}
The question is: How do you define if a week is in 2012 or in 2013? Your supposition, I guess, is that since 6 days of the week are in 2013, this week should be marked as the first week of 2013.
Not sure if this is the right way to go. That week started on 2012 (On monday 31th Dec), so it should be marked as the last week of 2012, therefore it should be the 53rd of 2012. The first week of 2013 should start on monday the 7th.
Now, you can handle the particular case of edge weeks (first and last week of the year) using the day of week information. It all depends on your logic.
I found an app for Mac OSX called ICOBundle that allows you to easily drop a selection of ico files in different sizes onto the ICOBundle.app, prompts you for a folder destination and file name, and it creates the multi-icon .ico file.
Now if it were only possible to mix-in an animated gif version into that one file it'd be a complete icon set, sadly not possible and requires a separate file and code snippet.
I found the problem that was causing the HTTP error.
In the setFalse()
function that is triggered by the Save button my code was trying to submit the form that contained the button.
function setFalse(){
document.getElementById("hasId").value ="false";
document.deliveryForm.submit();
document.submitForm.submit();
when I remove the document.submitForm.submit();
it works:
function setFalse(){
document.getElementById("hasId").value ="false";
document.deliveryForm.submit()
@Roger Lindsjö Thank you for spotting my error where I wasn't passing on the right parameter!
The simpliest way to understand it is that DateTime is a struct. When you initialize a struct it's initialize to it's minimum value : DateTime.Min
Therefore there is no difference between default(DateTime)
and new DateTime()
and DateTime.Min
You should use as_json
method which converts ActiveRecord objects to Ruby Hashes despite its name
tasks_records = TaskStoreStatus.all
tasks_records = tasks_records.as_json
# You can now add new records and return the result as json by calling `to_json`
tasks_records << TaskStoreStatus.last.as_json
tasks_records << { :task_id => 10, :store_name => "Koramanagala", :store_region => "India" }
tasks_records.to_json
You can also convert any ActiveRecord objects to a Hash with serializable_hash
and you can convert any ActiveRecord results to an Array with to_a
, so for your example :
tasks_records = TaskStoreStatus.all
tasks_records.to_a.map(&:serializable_hash)
And if you want an ugly solution for Rails prior to v2.3
JSON.parse(tasks_records.to_json) # please don't do it
BundleConfig
is nothing more than bundle configuration moved to separate file. It used to be part of app startup code (filters, bundles, routes used to be configured in one class)
To add this file, first you need to add the Microsoft.AspNet.Web.Optimization
nuget package to your web project:
Install-Package Microsoft.AspNet.Web.Optimization
Then under the App_Start folder create a new cs file called BundleConfig.cs
. Here is what I have in my mine (ASP.NET MVC 5, but it should work with MVC 4):
using System.Web;
using System.Web.Optimization;
namespace CodeRepository.Web
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
Then modify your Global.asax and add a call to RegisterBundles()
in Application_Start()
:
using System.Web.Optimization;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
A closely related question: How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app
Create a .c file containing just the line:
_MSC_VER
or
CompilerVersion=_MSC_VER
then pre-process with
cl /nologo /EP <filename>.c
It is easy to parse the output.
echo 'junk "Foo Bar" not empty one "" this "but this" and this neither' | sed 's/[^\"]*\"\([^\"]*\)\"[^\"]*/>\1</g'
This will result in: >Foo Bar<><>but this<
Here I showed the result string between ><'s for clarity, also using the non-greedy version with this sed command we first throw out the junk before and after that ""'s and then replace this with the part between the ""'s and surround this by ><'s.
This one was your solution.
$x = 0;
while($row = mysqli_fetch_array($result)) {
$posts[$x]['post_id'] = $row['post_id'];
$posts[$x]['post_title'] = $row['post_title'];
$posts[$x]['type'] = $row['type'];
$posts[$x]['author'] = $row['author'];
$x++;
}
I know this question is old, but the solution to my application, was different to the already suggested answers. If anyone else like me still have this issue, and none of the above answers works, this might be the problem:
I used a Network Credentials object to parse a windows username+password to a third party SOAP webservice. I had set the username="domainname\username", password="password" and domain="domainname". Now this game me that strange Ntlm and not NTLM error. To solve the problems, make sure not to use the domain parameter on the NetworkCredentials object if the domain name is included in the username with the backslash. So either remove domain name from the username and parse in domain parameter, or leave out the domain parameter. This solved my issue.
I am using ASP.NET MVC3 with SSRS 2008 and I couldn't get @Adrian's to work 100% for me when trying to get reports from a remote server.
Finally, I found that I needed to change the Page_Load method in ViewUserControl1.ascx to look like this:
ReportViewer1.ProcessingMode = ProcessingMode.Remote;
ServerReport serverReport = ReportViewer1.ServerReport;
serverReport.ReportServerUrl = new Uri("http://<Server Name>/reportserver");
serverReport.ReportPath = "/My Folder/MyReport";
serverReport.Refresh();
I had been missing the ProcessingMode.Remote.
References:
http://msdn.microsoft.com/en-us/library/aa337091.aspx - ReportViewer
Although there is an accepted answer I would want to add that as of Hive 0.14, record level operations are allowed. The correct syntax and query would be:
INSERT INTO TABLE tweet_table VALUES ('data');
Addition to @jwize's answer
Because angular.element(document).injector()
was giving error injector is not defined
So, I have created function that you can run after AJAX call or when DOM is changed using jQuery.
function compileAngularElement( elSelector) {
var elSelector = (typeof elSelector == 'string') ? elSelector : null ;
// The new element to be added
if (elSelector != null ) {
var $div = $( elSelector );
// The parent of the new element
var $target = $("[ng-app]");
angular.element($target).injector().invoke(['$compile', function ($compile) {
var $scope = angular.element($target).scope();
$compile($div)($scope);
// Finally, refresh the watch expressions in the new element
$scope.$apply();
}]);
}
}
use it by passing just new element's selector. like this
compileAngularElement( '.user' ) ;
Combining Daniel's and snnsnn's answers:
let ids = ['id1','id2','id3']
let data = await MyModel.find(
{'_id': { $in: ids}}
);
_x000D_
Simple and clean code. It works and tested against:
"mongodb": "^3.6.0", "mongoose": "^5.10.0",
You can use nsolve
of sympy
, meaning numerical solver
.
Example snippet:
from sympy import *
L = 4.11 * 10 ** 5
nu = 1
rho = 0.8175
mu = 2.88 * 10 ** -6
dP = 20000
eps = 4.6 * 10 ** -5
Re, D, f = symbols('Re, D, f')
nsolve((Eq(Re, rho * nu * D / mu),
Eq(dP, f * L / D * rho * nu ** 2 / 2),
Eq(1 / sqrt(f), -1.8 * log ( (eps / D / 3.) ** 1.11 + 6.9 / Re))),
(Re, D, f), (1123, -1231, -1000))
where (1123, -1231, -1000)
is the initial vector to find the root. And it gives out:
The imaginary part are very small, both at 10^(-20), so we can consider them zero, which means the roots are all real. Re ~ 13602.938, D ~ 0.047922 and f~0.0057.
for this small example:
import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send(**b**'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
while True:
data = mysock.recv(512)
if ( len(data) < 1 ) :
break
print (data);
mysock.close()
adding the "b" before 'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n' solved my problem
To avoid including a large framework, I think a simple homemade class can do the trick.
Example of class to handle named parameters:
public class NamedParamStatement {
public NamedParamStatement(Connection conn, String sql) throws SQLException {
int pos;
while((pos = sql.indexOf(":")) != -1) {
int end = sql.substring(pos).indexOf(" ");
if (end == -1)
end = sql.length();
else
end += pos;
fields.add(sql.substring(pos+1,end));
sql = sql.substring(0, pos) + "?" + sql.substring(end);
}
prepStmt = conn.prepareStatement(sql);
}
public PreparedStatement getPreparedStatement() {
return prepStmt;
}
public ResultSet executeQuery() throws SQLException {
return prepStmt.executeQuery();
}
public void close() throws SQLException {
prepStmt.close();
}
public void setInt(String name, int value) throws SQLException {
prepStmt.setInt(getIndex(name), value);
}
private int getIndex(String name) {
return fields.indexOf(name)+1;
}
private PreparedStatement prepStmt;
private List<String> fields = new ArrayList<String>();
}
Example of calling the class:
String sql;
sql = "SELECT id, Name, Age, TS FROM TestTable WHERE Age < :age OR id = :id";
NamedParamStatement stmt = new NamedParamStatement(conn, sql);
stmt.setInt("age", 35);
stmt.setInt("id", 2);
ResultSet rs = stmt.executeQuery();
Please note that the above simple example does not handle using named parameter twice. Nor does it handle using the : sign inside quotes.
It's kind of hackish, but I've been in the same situation before. I was dynamically generating a text file in javascript and wanted to provide it for download by encoding it with the data-URI.
This is possible with minormajor user intervention. Generate a link <a href="data:...">right-click me and select "Save Link As..." and save as "example.txt"</a>
. As I said, this is inelegant, but it works if you do not need a professional solution.
This could be made less painful by using flash to copy the name into the clipboard first. Of course if you let yourself use Flash or Java (now with less and less browser support I think?), you could probably find a another way to do this.
print((df.count(), len(df.columns)))
is easier for smaller datasets.
However if the dataset is huge, an alternative approach would be to use pandas and arrows to convert the dataframe to pandas df and call shape
spark.conf.set("spark.sql.execution.arrow.enabled", "true")
spark.conf.set("spark.sql.crossJoin.enabled", "true")
print(df.toPandas().shape)
HTML
<input [(ngModel)] = "searchTerm" (ngModelChange) = "search()"/>
<div *ngFor = "let item of items">{{item.name}}</div>
Component
search(): void {
let term = this.searchTerm;
this.items = this.itemsCopy.filter(function(tag) {
return tag.name.indexOf(term) >= 0;
});
}
Note that this.itemsCopy is equal to this.items and should be set before doing the search.
This is a BAD way to do it! I'm only leaving this answer in case it solves other weird problems. These better methods are the probably partly the result of newer data.table versions... so it's worth while to document this hard way. Plus, this is a nice syntax example for eval
substitute
syntax.
library(data.table)
dt <- data.table(ID = c(rep("A", 5), rep("B",5)),
fac1 = c(1:5, 1:5),
fac2 = c(1:5, 1:5) * 2,
val1 = rnorm(10),
val2 = rnorm(10))
names_factors = c('fac1', 'fac2')
names_values = c('val1', 'val2')
for (col in names_factors){
e = substitute(X := as.factor(X), list(X = as.symbol(col)))
dt[ , eval(e)]
}
for (col in names_values){
e = substitute(X := as.numeric(X), list(X = as.symbol(col)))
dt[ , eval(e)]
}
str(dt)
which gives you
Classes ‘data.table’ and 'data.frame': 10 obs. of 5 variables:
$ ID : chr "A" "A" "A" "A" ...
$ fac1: Factor w/ 5 levels "1","2","3","4",..: 1 2 3 4 5 1 2 3 4 5
$ fac2: Factor w/ 5 levels "2","4","6","8",..: 1 2 3 4 5 1 2 3 4 5
$ val1: num 0.0459 2.0113 0.5186 -0.8348 -0.2185 ...
$ val2: num -0.0688 0.6544 0.267 -0.1322 -0.4893 ...
- attr(*, ".internal.selfref")=<externalptr>
Do you have a lot of applications running when you are trying this? I encounter weird behavior at work sometimes because my system runs out of GDI Handles as I have so many windows open (our apps use alot).
When this happens, windows and context menus no long appear until I close something to free up some GDI handles.
The default limit in XP and Vista is 10000. It is not uncommon for my DevStudio to have 1500 GDI handles, so if you have a couple of copies of Dev studio open, it can eat them up pretty quickly. You can add a column in TaskManager to see how many handles are being used by each process.
There is a registry tweak you can do to increase the limit.
For more information see http://msdn.microsoft.com/en-us/library/ms724291(VS.85).aspx
I ran into this problem after a firewall change to restrict access between our internal network and the database server reporting the error located in the DMZ. Communication was working fine until the change, and system and database restarts were of no help. In my case both Oracle XE11gR2 installations are on Windows.
After day of struggle I found http://edstevensdba.wordpress.com/2011/07/30/exploring-the-local_listener-parameter/ and solved the problem with:
alter system set local_listener='(ADDRESS=(PROTOCOL=tcp)(HOST=[my server's ip])(PORT=1521))' scope=both;
alter system register;
it may be that this worked simply because of the 'alter system register' as suggested by ik_zelf. I did have the IP already set in relevant places in listener.ora and tnsnames.ora.
Java doesn't natively allow building of an exe, that would defeat its purpose of being cross-platform.
AFAIK, these are your options:
Make a runnable JAR. If the system supports it and is configured appropriately, in a GUI, double clicking the JAR will launch the app. Another option would be to write a launcher shell script/batch file which will start your JAR with the appropriate parameters
There also executable wrappers - see How can I convert my Java program to an .exe file?
Adding to @Kerrek's answer;
Authentication is Generalized form (All employees can login in to the machine )
Authorization is Specialized form (But admin only can install/uninstall the application in Machine)
The modern way to do this is with flexbox, adding align-items: flex-end;
on the container.
With this content:
<div class="Container">
<div>one</div>
<div>two</div>
</div>
Use this style:
.Container {
display: flex;
align-items: flex-end;
}
This is because the CHARINDEX-1 is returning a -ive value if the look-up for " " (space) is 0. The simplest solution would be to avoid '-ve' by adding
ABS(CHARINDEX(' ', PostCode ) -1))
which will return only +ive values for your length even if CHARINDEX(' ', PostCode ) -1)
is a -ve value. Correct me if I'm wrong!
Be sure to use quotes if there are spaces in the file path:
move "C:\Users\MyName\My Old Folder\*" "C:\Users\MyName\My New Folder"
That will move the contents of C:\Users\MyName\My Old Folder\
to C:\Users\MyName\My New Folder
Appears you can somewhat accomplish something similar with the Notification API. You can't control how long it stays visible (probably an OS preference of some kind--unless you specify requireInteraction true, then it stays up forever or until dismissed or until you close it), and it requires the user to click "allow notifications" (unfortunately) first, but here it is:
If you want it to close after 1s (all OS's leave it open 1s at least):
var notification = new Notification("Hi there!", {body: "some text"});
setTimeout(function() {notification.close()}, 1000);
If you wanted to show it longer than the "default" you could bind to the onclose callback and show another repeat notification I suppose, to replace it.
Ref: inspired by this answer, though that answer doesn't work in modern Chrome anymore, but the Notification API does.
Jersey makes the process very easy, my service class worked well with JSON, all I had to do is to add the dependencies in the pom.xml
@Path("/customer")
public class CustomerService {
private static Map<Integer, Customer> customers = new HashMap<Integer, Customer>();
@POST
@Path("save")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public SaveResult save(Customer c) {
customers.put(c.getId(), c);
SaveResult sr = new SaveResult();
sr.sucess = true;
return sr;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
public Customer getCustomer(@PathParam("id") int id) {
Customer c = customers.get(id);
if (c == null) {
c = new Customer();
c.setId(id * 3);
c.setName("unknow " + id);
}
return c;
}
}
And in the pom.xml
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.7</version>
</dependency>
You should be able to transfer the Application to another Username. You would need all your old user information to transfer it. The application would remove it's self from old account to new account. Also you could put a limit on how many times you where allowed to transfer it. If you transfer it to the application could expire after a year and force to buy update.
For auto commit off then use the below command for sure. Set below in my.cnf
file:
[mysqld]
autocommit=0
I think this question has been answered, click here for more information. Below is the short answer it is posted.
throw new Error("Stop script");
You can also used your browser to add break points, every browser is similar, check info below for your browser.
For Chrome break points info click here
For Firefox break points info click here
For Explorer break points info click
For Safari break points info click here
Chain both class selectors (without a space in between):
.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}
If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar
in this case) instead, regardless of what other classes you list.
To illustrate how other browsers and IE6 interpret this, consider this CSS:
* {
color: black;
}
.foo.bar {
color: red;
}
Output on supported browsers is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Not selected, black text [3] -->
Output on IE6 is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Selected, red text [2] -->
Footnotes:
foo
.foo
and bar
.bar
.
bar
.bar
, regardless of any other classes listed.We had a similar situation, but in our case Infosec agreed to allow any to 1, so we didnt had to fix the slave port, rather fixing the master to high level JNLP port 49187 worked ("Configure Global Security" -> "TCP port for JNLP slave agents").
TCP
49187 - Fixed jnlp port
8080 - jenkins http port
Other ports needed to launch slave as a windows service
TCP
135
139
445
UDP
137
138
Just in case someone is looking to this too. In .net core 3+ most of this is obsolete. The update way is:
public void Configure(
IApplicationBuilder app,
IWebHostEnvironment env,
ILogger<Startup> logger)
{
if (env.EnvironmentName == Environments.Development)
{
// logger.LogInformation("In Development environment");
}
}
user8657661's answer is closest to my needs (of lining things up across several lines). However, I couldn't get the example code to work as provided, but I needed to change it as follows:
<html>
<head>
<style>
.tab9 {position:absolute;left:150px; }
</style>
</head>
<body>
Dog Food: <span class="tab9"> $30</span><br/>
Milk of Magnesia:<span class="tab9"> $30</span><br/>
Pizza Kit:<span class="tab9"> $5</span><br/>
Mt Dew <span class="tab9"> $1.75</span><br/>
</body>
</html>
If you need right-aligned numbers you can change left:150px
to right:150px
, but you'll need to alter the number based on the width of the screen (as written the numbers would be 150 pixels from the right edge of the screen).
This LINQ below will generate the SQL for a left outer join and then take all of the results that don't find a match in your exclusion list.
List<Person> filteredResults =from p in people
join e in exclusions on p.compositeKey equals e.compositeKey into temp
from t in temp.DefaultIfEmpty()
where t.compositeKey == null
select p
let me know if it works!
In short: no. The first problem is access to the filesystem, which in most browsers is set to no by default due to security reasons. Modern browsers sometimes support minimalistic storage in the form of a database, or you can ask the user to enable file access.
If you have access to the filesystem then saving as HTML is not that hard (see the file object in the JS documentation) - but PDF is not so easy. PDF is a quite advanced file-format that really is ill suited for Javascript. It requires you to write information in datatypes not directly supported by Javascript, such as words and quads. You also need to pre-define a dictionary lookup system that must be saved to the file. Im sure someone could make it work, but the effort and time involved would be better spent learning C++ or Delphi.
HTML export however should be possible if the user gives you non restricted access
We can use Closures for this purpose. Try the following
func loadHealthCareList(completionClosure: (indexes: NSMutableArray)-> ()) {
//some code here
completionClosure(indexes: list)
}
At some point we can call this function as given below.
healthIndexManager.loadHealthCareList { (indexes) -> () in
print(indexes)
}
Please refer the following link for more information regarding Closures.
The Easiest way is this way :
from csv import reader
# open file in read mode
with open('file.csv', 'r') as read_obj:
# pass the file object to reader() to get the reader object
csv_reader = reader(read_obj)
# Iterate over each row in the csv using reader object
for row in csv_reader:
# row variable is a list that represents a row in csv
print(row)
output:
['Year:', 'Dec:', 'Jan:']
['1', '50', '60']
['2', '25', '50']
['3', '30', '30']
['4', '40', '20']
['5', '10', '10']
Queue
is an interface that extends Collection
in Java. It has all the functions needed to support FIFO
architecture.
For concrete implementation you may use LinkedList
. LinkedList implements Deque
which in turn implements Queue
. All of these are a part of java.util
package.
For details about method with sample example you can refer FIFO based Queue implementation in Java.
PS: Above link goes to my personal blog that has additional details on this.
You give the name of your file, the path of the directory to search, and let it make the job.
private static String getPath(String drl, String whereIAm) {
File dir = new File(whereIAm); //StaticMethods.currentPath() + "\\src\\main\\resources\\" +
for(File e : dir.listFiles()) {
if(e.isFile() && e.getName().equals(drl)) {return e.getPath();}
if(e.isDirectory()) {
String idiot = getPath(drl, e.getPath());
if(idiot != null) {return idiot;}
}
}
return null;
}
Perfect Solution that goes further to the goal
Goal: Disable the blinking curser when EditText
is not in focus, and enable the blinking curser when EditText
is in focus. Below also opens keyboard when EditText
is clicked, and hides it when you press done in the keyboard.
1) Set in your xml under your EditText
:
android:cursorVisible="false"
2) Set onClickListener:
iEditText.setOnClickListener(editTextClickListener);
OnClickListener editTextClickListener = new OnClickListener()
{
public void onClick(View v)
{
if (v.getId() == iEditText.getId())
{
iEditText.setCursorVisible(true);
}
}
};
3) then onCreate
, capture the event when done is pressed using OnEditorActionListener
to your EditText
, and then setCursorVisible(false)
.
//onCreate...
iEditText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
iEditText.setCursorVisible(false);
if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(iEditText.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
}
return false;
}
});
You can go from String (hex)
to byte array
to String as UTF-8(?)
. Make sure your hex string does not have leading spaces and stuff.
public static byte[] hexStringToByteArray(String hex) {
int l = hex.length();
byte[] data = new byte[l / 2];
for (int i = 0; i < l; i += 2) {
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i + 1), 16));
}
return data;
}
Usage:
String b = "0xfd00000aa8660b5b010006acdc0100000101000100010000";
byte[] bytes = hexStringToByteArray(b);
String st = new String(bytes, StandardCharsets.UTF_8);
System.out.println(st);
Here are some:
"Ali".eql? "Ali"
=> true
The spaceship (<=>
) method can be used to compare two strings in relation to their alphabetical ranking. The <=> method returns 0 if the strings are identical, -1 if the left hand string is less than the right hand string, and 1 if it is greater:
"Apples" <=> "Apples"
=> 0
"Apples" <=> "Pears"
=> -1
"Pears" <=> "Apples"
=> 1
A case insensitive comparison may be performed using the casecmp method which returns the same values as the <=> method described above:
"Apples".casecmp "apples"
=> 0
In Angular use 'extends' to define the interface for an 'Array' of objects.
Using an indexer will give you an error as its not an Array interface so doesn't contain the properties and methods.
e.g
error TS2339: Property 'find' does not exist on type 'ISelectOptions2'.
// good
export interface ISelectOptions1 extends Array<ISelectOption> {}
// bad
export interface ISelectOptions2 {
[index: number]: ISelectOption;
}
interface ISelectOption {
prop1: string;
prop2?: boolean;
}
The easiest way to understand the difference is to think of the different possibilities. There are two objects to consider, the pointer and the object pointed to (in this case 'a' is the name of the pointer, the object pointed to is unnamed, of type char). The possibilities are:
These different possibilities can be expressed in C as follows:
I hope this illustrates the possible differences
It's like this:
$('.tag.clickedTag').click(function (){
// this will catch with two classes
}
$('.tag.clickedTag.otherclass').click(function (){
// this will catch with three classes
}
$('.tag:not(.clickedTag)').click(function (){
// this will catch tag without clickedTag
}
You can either: Write a server-side script page like PHP, JSP, ASP.net etc to generate this HTML dynamically
or
Setup the web-server that you are using (e.g. Apache) to do exactly that automatically for directories that doesn't contain welcome-page (e.g. index.html)
Specifically in apache read more here: Edit the httpd.conf: http://justlinux.com/forum/showthread.php?s=&postid=502789#post502789 (updated link: https://forums.justlinux.com/showthread.php?94230-Make-apache-list-directory-contents&highlight=502789)
or add the autoindex mod: http://httpd.apache.org/docs/current/mod/mod_autoindex.html
To create a new object you can either use placement new, as mentioned above, or have your class implement a clone() method that creates a copy of the object. You can then call this clone method using a member function pointer as explained above to create new instances of the object. The advantage of clone is that sometimes you may be working with a pointer to a base class where you don't know the type of the object. In this case a clone() method can be easier to use. Also, clone() will let you copy the state of the object if that is what you want.
I just lost few hours trying all solutions. I was sure, problem is in my code - apk starting but some errors when working with different classes and activities.
Only way working with my project:
For me it works, only solution.
you can use convert function :
Select convert(int,[Column1])
Laravel Framework 5.6.26
return more than one array then we use compact('array1', 'array2', 'array3', ...)
to return view.
viewblade
is the frontend (view) blade.
return view('viewblade', compact('view1','view2','view3','view4'));
You have 2 options delete
and truncate
:
delete from mytable
This will delete all the content of the table, not reseting the autoincremental id, this process is very slow. If you want to delete specific records append a where clause at the end.
truncate myTable
This will reset the table i.e. all the auto incremental fields will be reset. Its a DDL and its very fast. You cannot delete any specific record through truncate
.
You can use if(addr && (addr = $.trim(addr)))
This has the advantage of actually removing any outer whitespace from addr
instead of just ignoring it when performing the check.
Reference: http://api.jquery.com/jQuery.trim/
rbenv help shell
"Sets a shell-specific Ruby version by setting the 'RBENV_VERSION' environment variable in your shell. This version overrides localapplication-specific versions and the global version. should be a string matching a Ruby version known to rbenv.The special version string 'system' will use your default system Ruby. Run rbenv versions' for a list of available Ruby versions."
Provided rbenv was installed correctly, ruby -v will correspond to
rbenv shell 1.9.3-p125
Also you can use HRTime package. It has a class StopWatch.
const x = 'some string';_x000D_
console.log(x.substring(0, 1));
_x000D_
i have alreay 2 situations where directives and services/factories didnt play well.
the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).
in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.
i even tried to make a directive with a controller and an isolated-scope
only when i moved everything to a controller and it worked like magic.
example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS