CakePHP was intended to be used as Ruby on Rails framework clone, done in PHP, so any reverse-engineering of underlying database is pointless. EER diagrams should be reverse-engineered from Model layer.
Such tools do exist for Ruby Here you can see Redmine database EER diagrams reverse-engineered from Models. Not from database. http://redminecookbook.com/Redmine-erd-diagrams.html
With following tools: http://rails-erd.rubyforge.org/ http://railroady.prestonlee.com/
Adding to the accepted answer, you can used DATABASE_DEFAULT
as encoding.
This allows database to make choice for you and your code becomes more portable.
SELECT MyColumn
FROM
FirstTable a
INNER JOIN SecondTable b
ON a.MyID COLLATE DATABASE_DEFAULT = b.YourID COLLATE DATABASE_DEFAULT
The best example is this one, No hiding, No jQuery, It's completely pure CSS
http://css-tricks.com/snippets/css/custom-file-input-styling-webkitblink/
.custom-file-input::-webkit-file-upload-button {_x000D_
visibility: hidden;_x000D_
}_x000D_
_x000D_
.custom-file-input::before {_x000D_
content: 'Select some files';_x000D_
display: inline-block;_x000D_
background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);_x000D_
border: 1px solid #999;_x000D_
border-radius: 3px;_x000D_
padding: 5px 8px;_x000D_
outline: none;_x000D_
white-space: nowrap;_x000D_
-webkit-user-select: none;_x000D_
cursor: pointer;_x000D_
text-shadow: 1px 1px #fff;_x000D_
font-weight: 700;_x000D_
font-size: 10pt;_x000D_
}_x000D_
_x000D_
.custom-file-input:hover::before {_x000D_
border-color: black;_x000D_
}_x000D_
_x000D_
.custom-file-input:active::before {_x000D_
background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);_x000D_
}
_x000D_
<input type="file" class="custom-file-input">
_x000D_
According to scikit-learn documentation,
By definition a confusion matrix C is such that C[i, j]
is equal to the number of observations known to be in group i
but predicted to be in group j
.
Thus in binary classification, the count of true negatives is C[0,0]
, false negatives is C[1,0]
, true positives is C[1,1]
and false positives is C[0,1]
.
CM = confusion_matrix(y_true, y_pred)
TN = CM[0][0]
FN = CM[1][0]
TP = CM[1][1]
FP = CM[0][1]
Try paint.setStyle(Paint.Style.STROKE)
?
We can do this using data() method. C++11 provides this method.
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
vector<int>v = {7, 8, 9, 10, 11};
int *arr = v.data();
for(int i=0; i<v.size(); i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
I have used this to remove unwanted words from text files:
bad_words = ['abc', 'def', 'ghi', 'jkl']
with open('List of words.txt') as badfile, open('Clean list of words.txt', 'w') as cleanfile:
for line in badfile:
clean = True
for word in bad_words:
if word in line:
clean = False
if clean == True:
cleanfile.write(line)
Or to do the same for all files in a directory:
import os
bad_words = ['abc', 'def', 'ghi', 'jkl']
for root, dirs, files in os.walk(".", topdown = True):
for file in files:
if '.txt' in file:
with open(file) as filename, open('clean '+file, 'w') as cleanfile:
for line in filename:
clean = True
for word in bad_words:
if word in line:
clean = False
if clean == True:
cleanfile.write(line)
I'm sure there must be a more elegant way to do it, but this did what I wanted it to.
This is where the window function row_number()
comes in handy:
SELECT s.siteName, s.siteIP, h.date
FROM sites s INNER JOIN
(select h.*, row_number() over (partition by siteName order by date desc) as seqnum
from history h
) h
ON s.siteName = h.siteName and seqnum = 1
ORDER BY s.siteName, h.date
There are two options:
This is the suggested option. It ensures your fonts go through the build pipeline, get hashes during compilation so that browser caching works correctly, and that you get compilation errors if the files are missing.
As described in “Adding Images, Fonts, and Files”, you need to have a CSS file imported from JS. For example, by default src/index.js
imports src/index.css
:
import './index.css';
A CSS file like this goes through the build pipeline, and can reference fonts and images. For example, if you put a font in src/fonts/MyFont.woff
, your index.css
might include this:
@font-face {
font-family: 'MyFont';
src: local('MyFont'), url(./fonts/MyFont.woff) format('woff');
}
Notice how we’re using a relative path starting with ./
. This is a special notation that helps the build pipeline (powered by Webpack) discover this file.
Normally this should be enough.
public
FolderIf for some reason you prefer not to use the build pipeline, and instead do it the “classic way”, you can use the public
folder and put your fonts there.
The downside of this approach is that the files don’t get hashes when you compile for production so you’ll have to update their names every time you change them, or browsers will cache the old versions.
If you want to do it this way, put the fonts somewhere into the public
folder, for example, into public/fonts/MyFont.woff
. If you follow this approach, you should put CSS files into public
folder as well and not import them from JS because mixing these approaches is going to be very confusing. So, if you still want to do it, you’d have a file like public/index.css
. You would have to manually add <link>
to this stylesheet from public/index.html
:
<link rel="stylesheet" href="%PUBLIC_URL%/index.css">
And inside of it, you would use the regular CSS notation:
@font-face {
font-family: 'MyFont';
src: local('MyFont'), url(fonts/MyFont.woff) format('woff');
}
Notice how I’m using fonts/MyFont.woff
as the path. This is because index.css
is in the public
folder so it will be served from the public path (usually it’s the server root, but if you deploy to GitHub Pages and set your homepage
field to http://myuser.github.io/myproject
, it will be served from /myproject
). However fonts
are also in the public
folder, so they will be served from fonts
relatively (either http://mywebsite.com/fonts
or http://myuser.github.io/myproject/fonts
). Therefore we use the relative path.
Note that since we’re avoiding the build pipeline in this example, it doesn’t verify that the file actually exists. This is why I don’t recommend this approach. Another problem is that our index.css
file doesn’t get minified and doesn’t get a hash. So it’s going to be slower for the end users, and you risk the browsers caching old versions of the file.
Go with the first method (“Using Imports”). I only described the second one since that’s what you attempted to do (judging by your comment), but it has many problems and should only be the last resort when you’re working around some issue.
Anyway you need 'Year'.
In some engineering fields, you have fixed day and month and year can be variable. But that day and month are important for beginning calculation without considering which year you are. Your user, for example, only should select a day and a month and providing year is up to you.
You can create a custom combobox using this: Customizable ComboBox Drop-Down.
1- In VS create a user control.
2- See the code in the link above for impelemnting that control.
3- Create another user control and place in it 31 button or label and above them place a label to show months.
4- Place the control in step 3 in your custom combobox.
5- Place the control in setp 4 in step 1.
You now have a control with only days and months. You can use any year that you have in your database or ....
You can do this as:
WITH abc AS( select
FROM ...)
, XYZ AS(select
From abc ....) /*This one uses "abc" multiple times*/
Select
From XYZ.... /*using abc, XYZ multiple times*/
You can read a CSV file with headers into a NumPy structured array with np.genfromtxt. For example:
import numpy as np
csv_fname = 'file.csv'
with open(csv_fname, 'w') as fp:
fp.write("""\
"A","B","C","D","E","F","timestamp"
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12
""")
# Read the CSV file into a Numpy record array
r = np.genfromtxt(csv_fname, delimiter=',', names=True, case_sensitive=True)
print(repr(r))
which looks like this:
array([(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111196e+12),
(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111311e+12),
(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29112065e+12)],
dtype=[('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ('D', '<f8'), ('E', '<f8'), ('F', '<f8'), ('timestamp', '<f8')])
You can access a named column like this r['E']
:
array([1715.37476, 1715.37476, 1715.37476])
Note: this answer previously used np.recfromcsv to read the data into a NumPy record array. While there was nothing wrong with that method, structured arrays are generally better than record arrays for speed and compatibility.
For those using Bootstrap and not wanting to lose the responsivness just do not set the width of the container. The following code is based on gillytech post.
<div id="image_preview" class="row">
<div class='crop col-xs-12 col-sm-6 col-md-6 '>
<img class="col-xs-12 col-sm-6 col-md-6"
id="preview0" src='img/preview_default.jpg'/>
</div>
<div class="col-xs-12 col-sm-6 col-md-6">
more stuff
</div>
</div> <!-- end image preview -->
/*images with the same width*/
.crop {
height: 300px;
/*width: 400px;*/
overflow: hidden;
}
.crop img {
height: auto;
width: 100%;
}
/*images with the same height*/
.crop {
height: 300px;
/*width: 400px;*/
overflow: hidden;
}
.crop img {
height: 100%;
width: auto;
}
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="MyButtonClick" />
</ItemTemplate>
and your method
protected void MyButtonClick(object sender, System.EventArgs e)
{
//Get the button that raised the event
Button btn = (Button)sender;
//Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}
if you still stuck or you get this
C:\\\Users\\\name of your\\\AppData\\\Local\\\Programs\\\Python\\\Python36
simply do this replace 2 \ with one
C:\Users\akshay\AppData\Local\Programs\Python\Python36
another easy way and more flexible , after loading data into Datagrid
Private Sub Button_Export_Click(sender As Object, e As EventArgs) Handles Button_Export.Click
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\1\Myfile.csv", True)
If DataGridView1.Rows.Count = 0 Then GoTo loopend
' collect the header's names
Dim Headerline As String
For k = 0 To DataGridView1.Columns.Count - 1
If k = DataGridView1.Columns.Count - 1 Then ' last column dont put , separate
Headerline = Headerline & DataGridView1.Columns(k).HeaderText
Else
Headerline = Headerline & DataGridView1.Columns(k).HeaderText & ","
End If
Next
file.WriteLine(Headerline) ' this will write header names at the first line
' collect the data
For i = 0 To DataGridView1.Rows.Count - 1
Dim DataRow As String
For k = 0 To DataGridView1.Columns.Count - 1
If k = DataGridView1.Columns.Count - 1 Then
DataRow = DataRow & DataGridView1.Rows(i).Cells(k).Value ' last column dont put , separate
End If
DataRow = DataRow & DataGridView1.Rows(i).Cells(k).Value & ","
Next
file.WriteLine(DataRow)
DataRow = ""
Next
loopend:
file.Close()
End Sub
I keep thinking there must be a better idiom, but for subtraction of columns by name, I tend to do the following:
df <- data.frame(a=1:10, b=1:10, c=1:10, d=1:10)
# return everything except a and c
df <- df[,-match(c("a","c"),names(df))]
df
this worked for me fine!
shell_command = "ls -l"
subprocess.call(shell_command.split())
In order for a bot to send a message, you need <client>.send()
, the client
is where the bot will send a message to(A channel, everywhere in the server, or a PM). Since you want the bot to PM a certain user, you can use message.author
as your client
. (you can replace author
as mentioned user in a message or something, etc)
Hence, the answer is: message.author.send("Your message here.")
I recommend looking up the Discord.js documentation about a certain object's properties whenever you get stuck, you might find a particular function that may serve as your solution.
This worked for me Visual C++ Redistributable Packages
group_concat() sounds like what you're looking for.
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
since you're on mssql, i just googled "group_concat mssql" and found a bunch of hits to recreate group_concat functionality. here's one of the hits i found:
Solution for Windows:
.box
filevagrant box add --name name_of_my_box 'name_of_my_box.box'
vagrant box list
should show the new box in the listSolution for MAC:
.box
filevagrant box add --name name_of_my_box "./name_of_my_box.box"
vagrant box list
should show the new box in the listThere is a new spec called the Native File System API that allows you to do this properly like this:
const result = await window.chooseFileSystemEntries({ type: "save-file" });
There is a demo here, but I believe it is using an origin trial so it may not work in your own website unless you sign up or enable a config flag, and it obviously only works in Chrome. If you're making an Electron app this might be an option though.
I believe you intended it more this way:
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());
TaskStart.ToString("dd-MMMM-yyyy");
rpt.SetParameterValue("TaskStartDate", TaskStart);
}
}
You always accessed your first row in your dataset.
Use basic programming composition: create a method and pass the same function to click
and hover
as a callback.
var hoverOrClick = function () {
// do something common
}
$('#target').click(hoverOrClick).hover(hoverOrClick);
Second way: use bind
on
:
$('#target').on('click mouseover', function () {
// Do something for both
});
jQuery('#target').bind('click mouseover', function () {
// Do something for both
});
I reached here for the problem Kudo mentioned.
I'm sharing my experience for others.
orElse
, or orElseGet
, that is the question:static String B() {
System.out.println("B()...");
return "B";
}
public static void main(final String... args) {
System.out.println(Optional.of("A").orElse(B()));
System.out.println(Optional.of("A").orElseGet(() -> B()));
}
prints
B()...
A
A
orElse
evaluates the value of B() interdependently of the value of the optional. Thus, orElseGet
is lazy.
you can use Glide for load and transform into blur image, 1) for only one view,
val requestOptions = RequestOptions()
requestOptions.transform(BlurTransformation(50)) // 0-100
Glide.with(applicationContext).setDefaultRequestOptions(requestOptions)
.load(imageUrl).into(view)
2) if you are using the adapter to load an image in the item, you should write your code in the if-else block, otherwise, it will make all your images blurry.
if(isBlure){
val requestOptions = RequestOptions()
requestOptions.transform(BlurTransformation(50))
Glide.with(applicationContext).setDefaultRequestOptions(requestOptions)
.load(imageUrl).into(view )
}else{
val requestOptions = RequestOptions()
Glide.with(applicationContext).setDefaultRequestOptions(requestOptions).load(imageUrl).into(view)
}
Take a look of following image:
Java->Code style->Formatter-> Edit
Try to find .npmrc in C:\Users\.npmrc
then open (notepad), write, and save inside :
proxy=http://<username>:<pass>@<proxyhost>:<port>
PS : remove "<" and ">" please !!
It used to be installed with the .NET framework. MsBuild v12.0 (2013) is now bundled as a stand-alone utility and has it's own installer.
http://www.microsoft.com/en-us/download/confirmation.aspx?id=40760
To reference the location of MsBuild.exe from within an MsBuild script, use the default $(MsBuildToolsPath) property.
You are comparing strings. If an arguments are omitted, %1
expands to a blank so the commands become IF =="-b" GOTO SPECIFIC
for example (which is a syntax error). Wrap your strings in quotes (or square brackets).
REM this is ok
IF [%1]==[/?] GOTO BLANK
REM I'd recommend using quotes exclusively
IF "%1"=="-b" GOTO SPECIFIC
IF NOT "%1"=="-b" GOTO UNKNOWN
s.index(x[, i[, j]])
index of the first occurrence of x in s (at or after index i and before index j)
Required here
<div class="outer">Outer Text
<div class="inner"> Inner Text</div>
</div>
added by
$(document).ready(function(){
$('.inner').prepend('<div class="middle">New Text Middle</div>');
});
If you find by alphabet in plist, it should be "Application supports iTunes file sharing".
What I have done in this case is pass an array, where the key is the parameter name, and the value is the value.
$optional = array(
"param" => $param1,
"param2" => $param2
);
function func($required, $requiredTwo, $optional) {
if(isset($optional["param2"])) {
doWork();
}
}
I tested the following procedure under macOS Mojave 10.14.6 (18G3020).
Launch Automator. Create a document of type “Quick Action”:
(In older versions of macOS, use the “Service” template.)
In the new Automator document, add a “Run AppleScript” action. (You can type “run applescript” into the search field at the top of the action list to find it.) Here's the AppleScript to paste into the action:
on run {input, parameters}
tell application "Terminal"
if it is running then
do script ""
end if
activate
end tell
end run
Set the “Workflow receives” popup to “no input”. It should look like this overall:
Save the document with the name “New Terminal”. Then go to the Automator menu (or the app menu in any running application) and open the Services submenu. You should now see the “New Terminal” quick action:
If you click the “New Terminal” menu item, you'll get a dialog box:
Click OK to allow the action to run. You'll see this dialog once in each application that's frontmost when you use the action. In other words, the first time you use the action while Finder is frontmost, you'll see the dialog. And the first time you use the action while Safari is frontmost, you'll see the dialog. And so on.
After you click OK in the dialog, Terminal should open a new window.
To assign a keyboard shortcut to the quick action, choose the “Services Preferences…” item from the Services menu. (Or launch System Preferences, choose the Keyboard pane, then choose the Shortcuts tab, then choose Services from the left-hand list.) Scroll to the bottom of the right-hand list and find the New Terminal service. Click it and you should see an “Add Shortcut” button:
Click the button and press your preferred keyboard shortcut. Then, scratch your head, because (when I tried it) the Add Shortcut button reappears. But click the button again and you should see your shortcut:
Now you should be able to press your keyboard shortcut in most circumstances to get a new terminal window.
In PowerShell 3 and above I use the Copy-Item with New-Item.
copy-item -Path $file -Destination (new-item -type directory -force ("C:\Folder\sub\sub\" + $newSub)) -force -ea 0
I haven't tried it in ver 2.
I finally solved this myself. If anyone else is having this problem, here is my solution:
I created a new method:
public function curl_del($path)
{
$url = $this->__url.$path;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $result;
}
Update 2
Since this seems to help some people, here is my final curl DELETE method, which returns the HTTP response in JSON decoded object:
/**
* @desc Do a DELETE request with cURL
*
* @param string $path path that goes after the URL fx. "/user/login"
* @param array $json If you need to send some json with your request.
* For me delete requests are always blank
* @return Obj $result HTTP response from REST interface in JSON decoded.
*/
public function curl_del($path, $json = '')
{
$url = $this->__url.$path;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result = json_decode($result);
curl_close($ch);
return $result;
}
Or just use Control.SuspendLayout()
and Control.ResumeLayout()
.
I just got the solution to this problem from a friend. he said: Add ob_start(); under your session code. You can add exit(); under the header. I tried it and it worked. Hope this helps
This is for those on a rented Hosting sever who do not have access to php.init file.
angular-cli resolves this by providing an --output-hashing
flag for the build command (versions 6/7, for later versions see here). Example usage:
ng build --output-hashing=all
Bundling & Tree-Shaking provides some details and context. Running ng help build
, documents the flag:
--output-hashing=none|all|media|bundles (String)
Define the output filename cache-busting hashing mode.
aliases: -oh <value>, --outputHashing <value>
Although this is only applicable to users of angular-cli, it works brilliantly and doesn't require any code changes or additional tooling.
Update
A number of comments have helpfully and correctly pointed out that this answer adds a hash to the .js
files but does nothing for index.html
. It is therefore entirely possible that index.html
remains cached after ng build
cache busts the .js
files.
At this point I'll defer to How do we control web page caching, across all browsers?
The following vim plugin handles that automatically through its "Bracketed Paste" mode: https://github.com/wincent/terminus
Sets up "Bracketed Paste" mode, which means you can forget about manually setting the 'paste' option and simply go ahead and paste in any mode.
You can use an anonymous function to pass the matches to your function:
$result = preg_replace_callback(
"/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
$result
);
Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e
would convert a double quote "
into \"
.
Another approach that is really fast is the MSS module. It is different from other solutions in the way that it uses only the ctypes
standard module, so it does not require big dependencies. It is OS independant and its use is made easy:
from mss import mss
with mss() as sct:
sct.shot()
And just find the screenshot.png
file containing the screen shot of the first monitor. There are a lot of possibile customizations, you can play with ScreenShot
objects and OpenCV/Numpy/PIL/etc..
I read this post Why String is Immutable or Final in Java and suppose that following may be the most important reason:
String is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all another client.
adb was not detecting connected nexus 5 device. Switched on the phone, enabled developer options, Enabled USB debugging mode, Now visible with adb. Also, USB configuration is still MTP. Hope this helps.
Look in the manual http://www.php.net/manual/en/mysqli.query.php
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
printf("Table myCity successfully created.\n");
}
/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
}
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {
/* Note, that we can't execute any functions which interact with the
server until result set was closed. All calls will return an
'out of sync' error */
if (!$mysqli->query("SET @a:='this will not work'")) {
printf("Error: %s\n", $mysqli->error);
}
$result->close();
}
$mysqli->close();
?>
Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.
thread apply all bt
Set CSS display
to none
for textarea
<textarea name="hide" style="display:none;"></textarea>
In a nutshell it means.. You are trying to access an object without instantiating it.. You might need to use the "new" keyword to instantiate it first i.e create an instance of it.
For eg:
public class MyClass
{
public int Id {get; set;}
}
MyClass myClass;
myClass.Id = 0; <----------- An error will be thrown here.. because myClass is null here...
You will have to use:
myClass = new MyClass();
myClass.Id = 0;
Hope I made it clear..
Alternative: Use a generic HTTP handler (.ashx) and use your favorite json library to manually serialize and deserialize your JSON.
I've found that complete control over the handling of a request and generating a response beats anything else .NET offers for simple, RESTful web services.
Use setDataAndType on the Intent
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(newVideoPath), "video/mp4");
startActivity(intent);
Use "video/mp4" as MIME or use "video/*" if you don't know the type.
From the context, the conflict was caused by the version of the package.
Let's take a look the manual about rpm
:
--force
Same as using --replacepkgs, --replacefiles, and --oldpackage.
--oldpackage
Allow an upgrade to replace a newer package with an older one.
So, you can execute the command rpm -Uvh info-4.13a-2.rpm --force
to solve your issue.
Ensure that all dependencies of your own dll are present near the dll, or in System32
.
Since you are using WebSocket, spender is correct. After recieving the initial data from the WebSocket, you need to send the handshake message from the C# server before any further information can flow.
HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: websocket
Connection: Upgrade
WebSocket-Origin: example
WebSocket-Location: something.here
WebSocket-Protocol: 13
Something along those lines.
You can do some more research into how WebSocket works on w3 or google.
Here is a protocol specifcation: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76#section-1.3
List of working examples:
Found this issue, because I had a similar problem when trying to generate a PDF from a html output in Google Apps Script where background-colors are also not "printed".
The -webkit-print-color-adjust:exact;
and !important
solutions of course did not work, but the box-shadow: inset 0 0 0 1000px gold;
did... great hack, thank you very much :)
Android studio 3.0 and Above
Disable the instant Run
You can do something like:
module.exports = {
method: function() {},
otherMethod: function() {},
};
Or just:
exports.method = function() {};
exports.otherMethod = function() {};
Then in the calling script:
const myModule = require('./myModule.js');
const method = myModule.method;
const otherMethod = myModule.otherMethod;
// OR:
const {method, otherMethod} = require('./myModule.js');
For future readers, this should help:
public void show() {
if(mContext instanceof Activity) {
Activity activity = (Activity) mContext;
if (!activity.isFinishing() && !activity.isDestroyed()) {
dialog.show();
}
}
}
Could it be that your file is not ISO-8859-15 encoded? You should be able to check with the file command:
file YourFile.txt
Also, you can use iconv without providing the encoding of the original file:
iconv -t UTF-8 YourFile.txt
I encapsulate the jQuery Ajax to a method:
var http_util = function (type, url, params, success_handler, error_handler, base_url) {
if(base_url) {
url = base_url + url;
}
var success = arguments[3]?arguments[3]:function(){};
var error = arguments[4]?arguments[4]:function(){};
$.ajax({
type: type,
url: url,
dataType: 'json',
data: params,
success: function (data, textStatus, xhr) {
if(textStatus === 'success'){
success(xhr.code, data); // there returns the status code
}
},
error: function (xhr, error_text, statusText) {
error(xhr.code, xhr); // there returns the status code
}
})
}
Usage:
http_util('get', 'http://localhost:8000/user/list/', null, function (status_code, data) {
console(status_code, data)
}, function(status_code, err){
console(status_code, err)
})
In the simplest cases type hinting should work:
$json = json_encode( (array)$object );
A good rule of thumb is ".h files should have declarations [potentially] used by multiple source files, but no code that gets run."
This query will use index if you have it for signup_date
field
SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d')
FROM users
WHERE signup_date >= CURDATE() && signup_date < (CURDATE() + INTERVAL 1 DAY)
That's ok not a big problem . thing is u got to find the proportional width and height
like if size is 2048.0 x 1360.0 which has to be resized to 320 x 480 resolution then the resulting image size should be 722.0 x 480.0
here is the formulae to do that . if w,h is original and x,y are resulting image.
w/h=x/y
=>
x=(w/h)*y;
submitting w=2048,h=1360,y=480 => x=722.0 ( here width>height. if height>width then consider x to be 320 and calculate y)
U can submit in this web page . ARC
Confused ? alright , here is category for UIImage which will do the thing for you.
@interface UIImage (UIImageFunctions)
- (UIImage *) scaleToSize: (CGSize)size;
- (UIImage *) scaleProportionalToSize: (CGSize)size;
@end
@implementation UIImage (UIImageFunctions)
- (UIImage *) scaleToSize: (CGSize)size
{
// Scalling selected image to targeted size
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, size.width, size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
CGContextClearRect(context, CGRectMake(0, 0, size.width, size.height));
if(self.imageOrientation == UIImageOrientationRight)
{
CGContextRotateCTM(context, -M_PI_2);
CGContextTranslateCTM(context, -size.height, 0.0f);
CGContextDrawImage(context, CGRectMake(0, 0, size.height, size.width), self.CGImage);
}
else
CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), self.CGImage);
CGImageRef scaledImage=CGBitmapContextCreateImage(context);
CGColorSpaceRelease(colorSpace);
CGContextRelease(context);
UIImage *image = [UIImage imageWithCGImage: scaledImage];
CGImageRelease(scaledImage);
return image;
}
- (UIImage *) scaleProportionalToSize: (CGSize)size1
{
if(self.size.width>self.size.height)
{
NSLog(@"LandScape");
size1=CGSizeMake((self.size.width/self.size.height)*size1.height,size1.height);
}
else
{
NSLog(@"Potrait");
size1=CGSizeMake(size1.width,(self.size.height/self.size.width)*size1.width);
}
return [self scaleToSize:size1];
}
@end
-- the following is appropriate call to do this if img is the UIImage instance.
img=[img scaleProportionalToSize:CGSizeMake(320, 480)];
If want to totally delete it use del
:
del your_variable
Or otherwise, to make the value None
:
your_variable = None
If it's a mutable iterable (lists, sets, dictionaries, etc, but not tuples because they're immutable), you can make it empty like:
your_variable.clear()
Then your_variable
will be empty
At some point, you're trying to convert an nvarchar
column to a varchar
column (or vice-versa).
Moreover, why is everything (supposedly) nvarchar(max)
? That's a code smell if I ever saw one. Are you aware of how SQL Server stores those columns? They use pointers to where the column is stored from the actual rows, since they don't fit within the 8k pages.
Yes, that is a good question. I don't understand it fully yet, but:
I understand that ENTRYPOINT
is the binary that is being executed. You can overide entrypoint by --entrypoint="".
docker run -t -i --entrypoint="/bin/bash" ubuntu
CMD is the default argument to container. Without entrypoint, default argument is command that is executed. With entrypoint, cmd is passed to entrypoint as argument. You can emulate a command with entrypoint.
# no entrypoint
docker run ubuntu /bin/cat /etc/passwd
# with entry point, emulating cat command
docker run --entrypoint="/bin/cat" ubuntu /etc/passwd
So, main advantage is that with entrypoint you can pass arguments (cmd) to your container. To accomplish this, you need to use both:
# Dockerfile
FROM ubuntu
ENTRYPOINT ["/bin/cat"]
and
docker build -t=cat .
then you can use:
docker run cat /etc/passwd
# ^^^^^^^^^^^
# CMD
# ^^^
# image (tag)- using the default ENTRYPOINT
It would be better to just fetch the data into array like this:
<?php
$shop = array( array("title"=>"rose", "price"=>1.25 , "number"=>15),
array("title"=>"daisy", "price"=>0.75 , "number"=>25),
array("title"=>"orchid", "price"=>1.15 , "number"=>7)
);
?>
And then do something like this, which should work well even when you add more columns to your table in the database later.
<?php if (count($shop) > 0): ?>
<table>
<thead>
<tr>
<th><?php echo implode('</th><th>', array_keys(current($shop))); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($shop as $row): array_map('htmlentities', $row); ?>
<tr>
<td><?php echo implode('</td><td>', $row); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
You can't bind an event to the element before it exists, so you should do it in the onload
event:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
document.getElementById('foo').addEventListener('click', function (e) {
var img = document.createElement('img');
img.setAttribute('src', 'http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png');
e.target.appendChild(img);
});
};
</script>
</head>
<body>
<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
</body>
</html>
use can try this:
$('iframe').load( function() {
$('iframe').contents().find("head")
.append($("<style type='text/css'> .my-class{display:none;} </style>"));
});
You need to use the square brackets notation to have values sent as an array:
<form method='post' id='userform' action='thisform.php'>
<tr>
<td>Trouble Type</td>
<td>
<input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
<input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
<input type='checkbox' name='checkboxvar[]' value='Option Three'>3
</td>
</tr>
</table>
<input type='submit' class='buttons'>
</form>
Please note though, that only the values of only checked checkboxes will be sent.
Unnamed namespaces are a utility to make an identifier translation unit local. They behave as if you would choose a unique name per translation unit for a namespace:
namespace unique { /* empty */ }
using namespace unique;
namespace unique { /* namespace body. stuff in here */ }
The extra step using the empty body is important, so you can already refer within the namespace body to identifiers like ::name
that are defined in that namespace, since the using directive already took place.
This means you can have free functions called (for example) help
that can exist in multiple translation units, and they won't clash at link time. The effect is almost identical to using the static
keyword used in C which you can put in in the declaration of identifiers. Unnamed namespaces are a superior alternative, being able to even make a type translation unit local.
namespace { int a1; }
static int a2;
Both a
's are translation unit local and won't clash at link time. But the difference is that the a1
in the anonymous namespace gets a unique name.
Read the excellent article at comeau-computing Why is an unnamed namespace used instead of static? (Archive.org mirror).
I think you do not need to use shape if I understood you.
If you are looking as shown in following image then use following layout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#1bd4f6"
android:paddingBottom="4dp" >
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:background="#ababb2"
android:padding="5dp"
android:text="Hello Android" />
</RelativeLayout>
</RelativeLayout>
EDIT
play with these properties you will get result
android:top="dimension"
android:right="dimension"
android:bottom="dimension"
android:left="dimension"
try like this
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#1bd4f6" />
</shape>
</item>
<item android:top="20px"
android:left="0px">
<shape android:shape="line" >
<padding android:bottom="1dp" />
<stroke
android:dashGap="10px"
android:dashWidth="10px"
android:width="1dp"
android:color="#ababb2" />
</shape>
</item>
</layer-list>
To easily apply the comm command to unsorted files, use Bash's process substitution:
$ bash --version
GNU bash, version 3.2.51(1)-release
Copyright (C) 2007 Free Software Foundation, Inc.
$ cat > abc
123
567
132
$ cat > def
132
777
321
So the files abc and def have one line in common, the one with "132". Using comm on unsorted files:
$ comm abc def
123
132
567
132
777
321
$ comm -12 abc def # No output! The common line is not found
$
The last line produced no output, the common line was not discovered.
Now use comm on sorted files, sorting the files with process substitution:
$ comm <( sort abc ) <( sort def )
123
132
321
567
777
$ comm -12 <( sort abc ) <( sort def )
132
Now we got the 132 line!
When I tried to include the JSTL Core Library in my JSP:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
I got the following error in Eclipse (Indigo):
Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"
I went to the Project Properties -> Targeted Runtimes, and then checked the Server I was using (Geronimo 3.0). Most people would be using Tomcat. This solved my problem. Hope it helps!
I had the same issue in 14.04, but I fixed it by these steps:
It worked like charm :)
I had this same problem - some users could pull from git and everything ran fine. Some would pull and get a very similar exception:
Could not load file or assembly '..., Version=..., Culture=neutral, PublicKeyToken=...' or one of its dependencies. The system cannot find the file specified.
In my particular case it was AjaxMin, so the actual error looked like this but the details don't matter:
Could not load file or assembly 'AjaxMin, Version=4.95.4924.12383, Culture=neutral, PublicKeyToken=21ef50ce11b5d80f' or one of its dependencies. The system cannot find the file specified.
It turned out to be a result of the following actions on a Solution:
NuGet Package Restore was turned on for the Solution.
A Project was added, and a Nuget package was installed into it (AjaxMin in this case).
The Project was moved to different folder in the Solution.
The Nuget package was updated to a newer version.
And slowly but surely this bug started showing up for some users.
The reason was the Solution-level packages/respositories.config kept the old Project reference, and now had a new, second entry for the moved Project. In other words it had this before the reorg:
<repository path="..\Old\packages.config" />
And this after the reorg:
<repository path="..\Old\packages.config" />
<repository path="..\New\packages.config" />
So the first line now refers to a Project that, while on disk, is no longer part of my Solution.
With Nuget Package Restore on, both packages.config files were being read, which each pointed to their own list of Nuget packages and package versions. Until a Nuget package was updated to a newer version however, there weren't any conflicts.
Once a Nuget package was updated, however, only active Projects had their repositories listings updated. NuGet Package Restore chose to download just one version of the library - the first one it encountered in repositories.config, which was the older one. The compiler and IDE proceeded as though it chose the newer one. The result was a run-time exception saying the DLL was missing.
The answer obviously is to delete any lines from this file that referenced Projects that aren't in your Solution.
if playing with psql inside docker exec it like this:
docker exec -e "PGOPTIONS=--search_path=<your_schema>" -it docker_pg psql -U user db_name
The artifact has been moved from net.sourceforge.findbugs
to
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.0</version>
</dependency>
A word of caution, all you hard-charging programmers: applying "use strict"
to existing code can be hazardous! This thing is not some feel-good, happy-face sticker that you can slap on the code to make it 'better'. With the "use strict"
pragma, the browser will suddenly THROW exceptions in random places that it never threw before just because at that spot you are doing something that default/loose JavaScript happily allows but strict JavaScript abhors! You may have strictness violations hiding in seldom used calls in your code that will only throw an exception when they do eventually get run - say, in the production environment that your paying customers use!
If you are going to take the plunge, it is a good idea to apply "use strict"
alongside comprehensive unit tests and a strictly configured JSHint build task that will give you some confidence that there is no dark corner of your module that will blow up horribly just because you've turned on Strict Mode. Or, hey, here's another option: just don't add "use strict"
to any of your legacy code, it's probably safer that way, honestly. DEFINITELY DO NOT add "use strict"
to any modules you do not own or maintain, like third party modules.
I think even though it is a deadly caged animal, "use strict"
can be good stuff, but you have to do it right. The best time to go strict is when your project is greenfield and you are starting from scratch. Configure JSHint/JSLint
with all the warnings and options cranked up as tight as your team can stomach, get a good build/test/assert system du jour rigged like Grunt+Karma+Chai
, and only THEN start marking all your new modules as "use strict"
. Be prepared to cure lots of niggly errors and warnings. Make sure everyone understands the gravity by configuring the build to FAIL if JSHint/JSLint
produces any violations.
My project was not a greenfield project when I adopted "use strict"
. As a result, my IDE is full of red marks because I don't have "use strict"
on half my modules, and JSHint complains about that. It's a reminder to me about what refactoring I should do in the future. My goal is to be red mark free due to all of my missing "use strict"
statements, but that is years away now.
This is a feature, not a bug.
See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.
Changing my listening port from 3000 to (process.env.PORT || 5000)
solved the problem.
If the cookie is generated from script, then you can send the cookie manually along with the cookie from the file(using cookie-file option). For example:
# sending manually set cookie
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));
# sending cookies from file
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);
In this case curl will send your defined cookie along with the cookies from the file.
If the cookie is generated through javascrript, then you have to trace it out how its generated and then you can send it using the above method(through http-header).
The utma utmc, utmz
are seen when cookies are sent from Mozilla. You shouldn't bet worry about these things anymore.
Finally, the way you are doing is alright. Just make sure you are using absolute path for the file names(i.e. /var/dir/cookie.txt
) instead of relative one.
Always enable the verbose mode when working with curl. It will help you a lot on tracing the requests. Also it will save lot of your times.
curl_setopt($ch, CURLOPT_VERBOSE, true);
Starting from support library version 24.0.0 you can call FragmentTransaction.commitNow()
method which commits this transaction synchronously instead of calling commit()
followed by executePendingTransactions()
First uninstall your application from the emulator:
adb -e uninstall your.application.package.name
Then try to install the application again.
If one works with embedded processing, eventually the underlying hardware (e.g. FPGA or some specific processor / microcontroller model) will have float implemented optimally in hardware whereas double will use software routines. So if the precision of a float is enough to handle the needs, the program will execute some times faster with float then double. As noted on other answers, beware of accumulation errors.
Yes You can compile and execute without main method By using static block. But after static block executed (printed) you will get an error saying no main method found.
And Latest INFO --> YOU cant Do this with JAVA 7 version. IT will not execute.
{
static
{
System.out.println("Hello World!");
System.exit(0); // prevents “main method not found” error
}
}
But this will not execute with JAVA 7 version.
First, all collections in .NET implement IEnumerable.
Second, a lot of the collections are duplicates because generics were added in version 2.0 of the framework.
So, although the generic collections likely add features, for the most part:
Arrays are a fixed size collection that you can change the value stored at a given index.
SortedDictionary is an IDictionary that is sorted based on the keys. SortedList is an IDictionary that is sorted based on a required IComparer.
So, the IDictionary implementations (those supporting KeyValuePairs) are: * Hashtable * Dictionary * SortedList * SortedDictionary
Another collection that was added in .NET 3.5 is the Hashset. It is a collection that supports set operations.
Also, the LinkedList is a standard linked-list implementation (the List is an array-list for faster retrieval).
https://limxtop.blogspot.com/2019/05/app-log.html
Read this article please, where provides complete implement:
setprop log.tag.<YOUR_LOG_TAG> <LEVEL>
in running time.Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. For example, calculations such as square root, or transcendentals such as sine and cosine, result in a value whose precision requires a floating-point type. Java implements the standard (IEEE–754) set of floatingpoint types and operators. There are two kinds of floating-point types, float and double, which represent single- and double-precision numbers, respectively. Their width and ranges are shown here:
Name Width in Bits Range
double 64 1 .7e–308 to 1.7e+308
float 32 3 .4e–038 to 3.4e+038
float
The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some processors and takes half as much space as double precision, but will become imprecise when the values are either very large or very small. Variables of type float are useful when you need a fractional component, but don't require a large degree of precision.
Here are some example float variable declarations:
float hightemp, lowtemp;
double
Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations. All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values. When you need to maintain accuracy over many iterative calculations, or are manipulating large-valued numbers, double is the best choice.
A more general approach that will attempt to check for both integers and integers given as strings will be
def isInt(anyNumberOrString):
try:
int(anyNumberOrString) #to check float and int use "float(anyNumberOrString)"
return True
except ValueError :
return False
isInt("A") #False
isInt("5") #True
isInt(8) #True
isInt("5.88") #False *see comment above on how to make this True
In matplotlib a color map isn't a list, but it contains the list of its colors as colormap.colors
. And the module matplotlib.colors
provides a function ListedColormap()
to generate a color map from a list. So you can reverse any color map by doing
colormap_r = ListedColormap(colormap.colors[::-1])
Add this is work for me
<repositories>
<!-- Repository for ORACLE JDBC Driver -->
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
Remember there are two independent git repos we are talking about. Your local repo with your code and the remote running somewhere else.
Your are right, when you change a branch, HEAD points to your current branch. All of this is happening on your local git repo. Not the remote repo, which could be owned by another developer, or siting on a sever in your office, or github, or another directory on the filesystem, or etc...
Your computer (local repo) has no business changing the HEAD pointer on the remote git repo. It could be owned by a different developer for example.
One more thing, what your computer calls origin/XXX is your computer's understanding of the state of the remote at the time of the last fetch.
So what would "organically" update origin/HEAD? It would be activity on the remote git repo. Not your local repo.
People have mentioned
git symbolic-ref HEAD refs/head/my_other_branch
Normally, that is used when there is a shared central git repo on a server for use by the development team. It would be a command executed on the remote computer. You would see this as activity on the remote git repo.
Or, you could do it the really simple way.
Dim OpenCMD
OpenCMD = CreateObject("wscript.shell")
OpenCMD.run("Command Goes Here")
Just use the -jrm
option to remove the file and directory
structures
zip -jrm /path/to/file.zip /path/to/file
For other people reading this:
This can happen is if the .Net version that you have registered isn't the one selected under the 'Basic Settings' of the application pool attached to your website. For instance, your sites application pool has .Net v2.0 selected but you registered v4.0
The getimagesize() should be the most definite way of working out whether the file is an image:
if(@is_array(getimagesize($mediapath))){
$image = true;
} else {
$image = false;
}
because this is a sample getimagesize() output:
Array (
[0] => 800
[1] => 450
[2] => 2
[3] => width="800" height="450"
[bits] => 8
[channels] => 3
[mime] => image/jpeg)
Using parameter --force:
npm i -f
There could be an error earlier in the CSS file that is causing your (correct) CSS to not work.
Couple of questions:
That said, I wrote some Java a while ago to talk to a couple of IP-enabled power strips (BayTech RPC3s) which might be of use to you. If you're interested I'll see if I can dig it up and post it someplace.
For following error,
COPY failed: stat /<**path**> :no such file or directory
I got it around by restarting docker service.
sudo service docker restart
The first is the most concise, I would go with that. The first two are the same, but the first is just that little bit shorter, so you'll save on bytes. The third is plain wrong, because that condition will always evaluate true because the object will never be null or falsy for that matter.
If you already have the data "for (Parcelable currentHeadline : allHeadlines)," then why are you doing that in a separate thread?
You should poll the data in a separate thread, and when it's finished gathering it, then call your populateTables method on the UI thread:
private void populateTable() {
runOnUiThread(new Runnable(){
public void run() {
//If there are stories, add them to the table
for (Parcelable currentHeadline : allHeadlines) {
addHeadlineToTable(currentHeadline);
}
try {
dialog.dismiss();
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
}
});
}
require(stringr)
Define a very simple function
str_words <- function(sentence) {
str_count(sentence, " ") + 1
}
Check
str_words(This is a sentence with six words)
In JavaScript functions are objects.
document.getElementById('foo').onclick = function(){
prompt('Hello world');
}
I've had to do this before using Paramiko in a case where I wanted to run a dynamic, local PyQt4 script on a host running an ssh server that has connected my OpenVPN server and ask for their routing preference (split tunneling).
So long as the ssh server you are connecting to has all of the required dependencies of your script (PyQt4 in my case), you can easily encapsulate the data by encoding it in base64 and use the exec()
built-in function on the decoded message. If I remember correctly my one-liner for this was:
stdout = client.exec_command('python -c "exec(\\"' + open('hello.py','r').read().encode('base64').strip('\n') + '\\".decode(\\"base64\\"))"' )[1]
It is hard to read and you have to escape the escape sequences because they are interpreted twice (once by the sender and then again by the receiver). It also may need some debugging, I've packed up my server to PCS or I'd just reference my OpenVPN routing script.
The difference in doing it this way as opposed to sending a file is that it never touches the disk on the server and is run straight from memory (unless of course they log the command). You'll find that encapsulating information this way (although inefficient) can help you package data into a single file.
For instance, you can use this method to include raw data from external dependencies (i.e. an image) in your main script.
Your meta tag should look like this:
<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>
And it has to be placed on the page you want to share (this is unclear in your question).
If you have shared the page before the image (or the meta tag) was present, then it is possible, that facebook has the page in its "memory" without an image. In this case simply enter the URL of your page in the debug tool http://developers.facebook.com/tools/debug. After that, the image should be present when the page is shared the next time.
You can use File.WriteAllBytes
The behavior you're trying to produce is not really best done using AJAX. AJAX would be best used if you wanted to only update a portion of the page, not completely redirect to some other page. That defeats the whole purpose of AJAX really.
I would suggest to just not use AJAX with the behavior you're describing.
Alternatively, you could try using jquery Ajax, which would submit the request and then you specify a callback when the request completes. In the callback you could determine if it failed or succeeded, and redirect to another page on success. I've found jquery Ajax to be much easier to use, especially since I'm already using the library for other things anyway.
You can find documentation about jquery ajax here, but the syntax is as follows:
jQuery.ajax( options )
jQuery.get( url, data, callback, type)
jQuery.getJSON( url, data, callback )
jQuery.getScript( url, callback )
jQuery.post( url, data, callback, type)
Another possibility, is the machine has an older version of xlrd installed separately, and it's not in the "..:\Python27\Scripts.." folder.
In another word, there are 2 different versions of xlrd in the machine.
when you check the version below, it reads the one not in the "..:\Python27\Scripts.." folder, no matter how updated you done with pip.
print xlrd.__version__
Delete the whole redundant sub-folder, and it works. (in addition to xlrd, I had another library encountered the same)
All answers seem to work fine. If you need to do this many times, be aware that writing
hs.write(name + "\n")
constructs a new string in memory and appends that to the file.
More efficient would be
hs.write(name)
hs.write("\n")
which does not create a new string, just appends to the file.
If you are using the ADT version 22, you need to check the android dependencies and android private libraries in the order&Export tab in the project build path
Fast and good hash functions can be composed from fast permutations with lesser qualities, like
To yield a hashing function with superior qualities, like demonstrated with PCG for random number generation.
This is in fact also the recipe rrxmrrxmsx_0 and murmur hash are using, knowingly or unknowingly.
I personally found
uint64_t xorshift(const uint64_t& n,int i){
return n^(n>>i);
}
uint64_t hash(const uint64_t& n){
uint64_t p = 0x5555555555555555ull; // pattern of alternating 0 and 1
uint64_t c = 17316035218449499591ull;// random uneven integer constant;
return c*xorshift(p*xorshift(n,32),32);
}
to be good enough.
A good hash function should
Let's first look at the identity function. It satisfies 1. but not 2. :
Input bit n determines output bit n with a correlation of 100% (red) and no others, they are therefore blue, giving a perfect red line across.
A xorshift(n,32) is not much better, yielding one and half a line. Still satisfying 1., because it is invertible with a second application.
A multiplication with an unsigned integer ("Knuth's multiplicative method") is much better, cascading more strongly and flipping more output bits with a probability of 0.5, which is what you want, in green. It satisfies 1. as for each uneven integer there is a multiplicative inverse.
Combining the two gives the following output, still satisfying 1. as the composition of two bijective functions yields another bijective function.
A second application of multiplication and xorshift will yield the following:
Or you can use Galois field multiplications like GHash, they have become reasonably fast on modern CPUs and have superior qualities in one step.
uint64_t const inline gfmul(const uint64_t& i,const uint64_t& j){
__m128i I{};I[0]^=i;
__m128i J{};J[0]^=j;
__m128i M{};M[0]^=0xb000000000000000ull;
__m128i X = _mm_clmulepi64_si128(I,J,0);
__m128i A = _mm_clmulepi64_si128(X,M,0);
__m128i B = _mm_clmulepi64_si128(A,M,0);
return A[0]^A[1]^B[1]^X[0]^X[1];
}
I like assylias' answer, however I would refactor it as follows:
Sub test()
Dim origNum As String
Dim creditOrDebit As String
origNum = "30062600006"
creditOrDebit = "D"
If creditOrDebit = "D" Then
If origNum = "006260006" Then
MsgBox "OK"
ElseIf origNum = "30062600006" Then
MsgBox "OK"
End If
End If
End Sub
This might save you some CPU cycles since if creditOrDebit
is <> "D"
there is no point in checking the value of origNum
.
I used the following procedure to test my theory that my procedure is faster:
Public Declare Function timeGetTime Lib "winmm.dll" () As Long
Sub DoTests2()
Dim startTime1 As Long
Dim endTime1 As Long
Dim startTime2 As Long
Dim endTime2 As Long
Dim i As Long
Dim msg As String
Const numberOfLoops As Long = 10000
Const origNum As String = "006260006"
Const creditOrDebit As String = "D"
startTime1 = timeGetTime
For i = 1 To numberOfLoops
If creditOrDebit = "D" Then
If origNum = "006260006" Then
' do something here
Debug.Print "OK"
ElseIf origNum = "30062600006" Then
' do something here
Debug.Print "OK"
End If
End If
Next i
endTime1 = timeGetTime
startTime2 = timeGetTime
For i = 1 To numberOfLoops
If (origNum = "006260006" Or origNum = "30062600006") And _
creditOrDebit = "D" Then
' do something here
Debug.Print "OK"
End If
Next i
endTime2 = timeGetTime
msg = "number of iterations: " & numberOfLoops & vbNewLine
msg = msg & "JP proc: " & Format$((endTime1 - startTime1), "#,###") & _
" ms" & vbNewLine
msg = msg & "assylias proc: " & Format$((endTime2 - startTime2), "#,###") & _
" ms"
MsgBox msg
End Sub
I must have a slow computer because 1,000,000 iterations took nowhere near ~200 ms as with assylias' test. I had to limit the iterations to 10,000 -- hey, I have other things to do :)
After running the above procedure 10 times, my procedure is faster only 20% of the time. However, when it is slower it is only superficially slower. As assylias pointed out, however, when creditOrDebit
is <>"D"
, my procedure is at least twice as fast. I was able to reasonably test it at 100 million iterations.
And that is why I refactored it - to short-circuit the logic so that origNum
doesn't need to be evaluated when creditOrDebit <> "D"
.
At this point, the rest depends on the OP's spreadsheet. If creditOrDebit
is likely to equal D, then use assylias' procedure, because it will usually run faster. But if creditOrDebit
has a wide range of possible values, and D
is not any more likely to be the target value, my procedure will leverage that to prevent needlessly evaluating the other variable.
As Mingyu pointed out, there is a problem in formatting. Other than that, I would strongly recommend not using the Derived class's name while calling super()
since it makes your code inflexible (code maintenance and inheritance issues). In Python 3, Use super().__init__
instead. Here is the code after incorporating these changes :
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
class ElectricCar(Car):
def __init__(self, battery_type, model, color, mpg):
self.battery_type=battery_type
super().__init__(model, color, mpg)
Thanks to Erwin Mayer for pointing out the issue in using __class__
with super()
Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' })
to get the page scrolled with a smooth effect.
const btn = document.getElementById('elem');_x000D_
_x000D_
btn.addEventListener('click', () => window.scrollTo({_x000D_
top: 400,_x000D_
behavior: 'smooth',_x000D_
}));
_x000D_
#x {_x000D_
height: 1000px;_x000D_
background: lightblue;_x000D_
}
_x000D_
<div id='x'>_x000D_
<button id='elem'>Click to scroll</button>_x000D_
</div>
_x000D_
You can do something like this:
var btn = document.getElementById('x');_x000D_
_x000D_
btn.addEventListener("click", function() {_x000D_
var i = 10;_x000D_
var int = setInterval(function() {_x000D_
window.scrollTo(0, i);_x000D_
i += 10;_x000D_
if (i >= 200) clearInterval(int);_x000D_
}, 20);_x000D_
})
_x000D_
body {_x000D_
background: #3a2613;_x000D_
height: 600px;_x000D_
}
_x000D_
<button id='x'>click</button>
_x000D_
ES6 recursive approach:
const btn = document.getElementById('elem');_x000D_
_x000D_
const smoothScroll = (h) => {_x000D_
let i = h || 0;_x000D_
if (i < 200) {_x000D_
setTimeout(() => {_x000D_
window.scrollTo(0, i);_x000D_
smoothScroll(i + 10);_x000D_
}, 10);_x000D_
}_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', () => smoothScroll());
_x000D_
body {_x000D_
background: #9a6432;_x000D_
height: 600px;_x000D_
}
_x000D_
<button id='elem'>click</button>
_x000D_
Maybe this is a no-brainer for the xslt-professional, but for me at beginner/intermediate level, this got me puzzled. I wanted to do exactly the same thing, but I had to test a responsetime value from an xml instead of a plain number. Following this thread, I tried this:
<xsl:when test="responsetime/@value >= 5000 and responsetime/@value <= 8999">
which generated an error. This works:
<xsl:when test="number(responsetime/@value) >= 5000 and number(responsetime/@value) <= 8999">
Don't really understand why it doesn't work without number(), though. Could it be that without number() the value is treated as a string and you can't compare numbers with a string?
Anyway, hope this saves someone a lot of searching...
For @Joe above, "This is giving me a redirect loop. Before I added the code it worked fine. Any suggestions? – Joe Nov 8 '11 at 4:13"
This was happening to me as well and what I believe was happening is that there was a load balancer terminating the SSL request in front of the Web server. So, my Web site was always thinking the request was "http", even if the original browser requested it to be "https".
I admit this is a bit hacky, but what worked for me was to implement a "JustRedirected" property that I could leverage to figure out the person was already redirected once. So, I test for specific conditions that warrant the redirect and, if they are met, I set this property (value stored in session) prior to the redirection. Even if the http/https conditions for redirection are met the second time, I bypass the redirection logic and reset the "JustRedirected" session value to false. You'll need your own conditional test logic, but here's a simple implementation of the property:
public bool JustRedirected
{
get
{
if (Session[RosadaConst.JUSTREDIRECTED] == null)
return false;
return (bool)Session[RosadaConst.JUSTREDIRECTED];
}
set
{
Session[RosadaConst.JUSTREDIRECTED] = value;
}
}
Try this...
You don't need to override onCreateOptionsMenu() in your Fragment class again. Menu items visibility can be changed by overriding onPrepareOptionsMenu() method available in Fragment class.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.action_search).setVisible(false);
super.onPrepareOptionsMenu(menu);
}
Change your positioning a bit:
.container {
border: 1px solid #DDDDDD;
width: 200px;
height: 200px;
position:relative;
}
.tag {
float: left;
position: absolute;
left: 0px;
top: 0px;
background-color: green;
}
You need to set relative positioning on the container and then absolute on the inner tag div. The inner tag's absolute positioning will be with respect to the outer relatively positioned div. You don't even need the z-index rule on the tag div.
May be this helps some one who are looking for multiple date formats one after the other by willingly or unexpectedly. Please find the code: I am using moment.js format function on a current date as (today is 29-06-2020) var startDate = moment(new Date()).format('MM/DD/YY'); Result: 06/28/20
what happening is it retains only the year part :20 as "06/28/20", after If I run the statement : new Date(startDate) The result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)",
Then, when I use another format on "06/28/20": startDate = moment(startDate ).format('MM-DD-YYYY'); Result: 06-28-1920, in google chrome and firefox browsers it gives correct date on second attempt as: 06-28-2020. But in IE it is having issues, from this I understood we can apply one dateformat on the given date, If we want second date format, it should be apply on the fresh date not on the first date format result. And also observe that for first time applying 'MM-DD-YYYY' and next 'MM-DD-YY' is working in IE. For clear understanding please find my question in the link: Date went wrong when using Momentjs date format in IE 11
Here's a couple of functions (based on Brian Bondy's example) that use WideCharToMultiByte and MultiByteToWideChar to convert between std::wstring and std::string using utf8 to not lose any data.
// Convert a wide Unicode string to an UTF8 string
std::string utf8_encode(const std::wstring &wstr)
{
if( wstr.empty() ) return std::string();
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
std::string strTo( size_needed, 0 );
WideCharToMultiByte (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
return strTo;
}
// Convert an UTF8 string to a wide Unicode String
std::wstring utf8_decode(const std::string &str)
{
if( str.empty() ) return std::wstring();
int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
std::wstring wstrTo( size_needed, 0 );
MultiByteToWideChar (CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
return wstrTo;
}
Here is a function that will work for numeric or string indices. Pass the array as first parameter, then the index to the element that needs to be moved and finally set the direction to -1 to move the element up and to 1 to move it down. Example: Move(['first'=>'Peter','second'=>'Paul','third'=>'Kate'],'second',-1) will move Paul up and Peter down.
function Move($a,$element,$direction)
{
$temp = [];
$index = 0;
foreach($a as $key=>$value)
{
$temp[$index++] = $key;
}
$index = array_search($element,$temp);
$newpos = $index+$direction;
if(isset($temp[$newpos]))
{
$value2 = $temp[$newpos];
$temp[$newpos]=$element;
$temp[$index]=$value2;
}
else
{
# move is not possible
return $a; # returns the array unchanged
}
$final = [];
foreach($temp as $next)
{
$final[$next]=$a[$next];
}
return $final;
}
Adding an answer because none of the existing answers specifically address the confusion in the official literature.
Generator functions are ordinary functions defined using yield
instead of return
. When called, a generator function returns a generator object, which is a kind of iterator - it has a next()
method. When you call next()
, the next value yielded by the generator function is returned.
Either the function or the object may be called the "generator" depending on which Python source document you read. The Python glossary says generator functions, while the Python wiki implies generator objects. The Python tutorial remarkably manages to imply both usages in the space of three sentences:
Generators are a simple and powerful tool for creating iterators. They are written like regular functions but use the yield statement whenever they want to return data. Each time next() is called on it, the generator resumes where it left off (it remembers all the data values and which statement was last executed).
The first two sentences identify generators with generator functions, while the third sentence identifies them with generator objects.
Despite all this confusion, one can seek out the Python language reference for the clear and final word:
The yield expression is only used when defining a generator function, and can only be used in the body of a function definition. Using a yield expression in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.
When a generator function is called, it returns an iterator known as a generator. That generator then controls the execution of a generator function.
So, in formal and precise usage, "generator" unqualified means generator object, not generator function.
The above references are for Python 2 but Python 3 language reference says the same thing. However, the Python 3 glossary states that
generator ... Usually refers to a generator function, but may refer to a generator iterator in some contexts. In cases where the intended meaning isn’t clear, using the full terms avoids ambiguity.
If you leave out the brackets then PHP will assign the keys by default.
Try this:
$votes = $row['votes_up'];
$votes = $row['votes_down'];
Steps I have followed to fix the issue as follows,
Analyze -> Code Cleanup
File -> Project Structures -> Select project from the list and update the gradle version to latest.
Build -> Clean Project
Build -> Make Project
Now the issue related to the build may get reported like using compile instead of implementation etc.
Please fix those and hopefully it should fix the issue.
Even if its not inline-block
based, this solution might worth consideration (allows nearly same formatting control from upper levels).
ul {
display: table;
}
ul li {
display: table-cell;
}
</li><li>
)Dirk Eddelbuettel's answer is the best; here I just note that you can get away with not pre-specifying the dataframe dimensions or data types, which is sometimes useful if you have multiple data types and lots of columns:
row1<-list("a",1,FALSE) #use 'list', not 'c' or 'cbind'!
row2<-list("b",2,TRUE)
df<-data.frame(row1,stringsAsFactors = F) #first row
df<-rbind(df,row2) #now this works as you'd expect.
If you just want an array of month names from the beginning of the year to the end e.g. to populate a drop-down select, I would just use the following;
for ($i = 0; $i < 12; ++$i) {
$months[$m] = $m = date("F", strtotime("January +$i months"));
}
Thanks to RandomUs 1r for this observation:
changing it to display:inline-block; solves that issue. – RandomUs1r May 14 '13 at 21:59
I tried it myself for a top navigation menu bar, as follows:
First style the "li" element as follows:
display: inline-block;
width: 7em;
text-align: center;
Then style the "a"> element as follows:
width: 100%;
Now the navigation links are all equal width with text centered in each link.
I came up with this one, which turns out to work only in zsh, but I think the general approach is nice.
arr=( "hello world" "find me" "what?" )
if [[ "${arr[@]/#%find me/}" != "${arr[@]}" ]]; then
echo "found!"
else
echo "not found!"
fi
You take out your pattern from each element only if it starts ${arr[@]/#pattern/}
or ends ${arr[@]/%pattern/}
with it. These two substitutions work in bash, but both at the same time ${arr[@]/#%pattern/}
only works in zsh.
If the modified array is equal to the original, then it doesn't contain the element.
Edit:
This one works in bash:
function contains () {
local arr=(${@:2})
local el=$1
local marr=(${arr[@]/#$el/})
[[ "${#arr[@]}" != "${#marr[@]}" ]]
}
After the substitution it compares the length of both arrays. Obly if the array contains the element the substitution will completely delete it, and the count will differ.
There's no need to use onAuthStateChanged() function in this scenario.
You can easily detect if the user is logged or not by executing:
var user = firebase.auth().currentUser;
For those who face the "returning null" issue, it's just because you are not waiting for the firebase call to complete.
Let's suppose you perform the login action on Page A and then you invoke Page B, on Page B you can call the following JS code to test the expected behavior:
var config = {
apiKey: "....",
authDomain: "...",
databaseURL: "...",
projectId: "..",
storageBucket: "..",
messagingSenderId: ".."
};
firebase.initializeApp(config);
$( document ).ready(function() {
console.log( "testing.." );
var user = firebase.auth().currentUser;
console.log(user);
});
If the user is logged then "var user" will contain the expected JSON payload, if not, then it will be just "null"
And that's all you need.
Regards
The classes of problem that are well suited for a mapreduce style solution are problems of aggregation. Of extracting data from a dataset. In C#, one could take advantage of LINQ to program in this style.
From the following article: http://codecube.net/2009/02/mapreduce-in-c-using-linq/
the GroupBy method is acting as the map, while the Select method does the job of reducing the intermediate results into the final list of results.
var wordOccurrences = words
.GroupBy(w => w)
.Select(intermediate => new
{
Word = intermediate.Key,
Frequency = intermediate.Sum(w => 1)
})
.Where(w => w.Frequency > 10)
.OrderBy(w => w.Frequency);
For the distributed portion, you could check out DryadLINQ: http://research.microsoft.com/en-us/projects/dryadlinq/default.aspx
You can also use forEach:
var maximum = Number.MIN_SAFE_INTEGER;_x000D_
_x000D_
var array = [-3, -2, 217, 9, -8, 46];_x000D_
array.forEach(function(value){_x000D_
if(value > maximum) {_x000D_
maximum = value;_x000D_
}_x000D_
});_x000D_
_x000D_
console.log(maximum); // 217
_x000D_
You can acheive this with CSS but you are not techinically changing the arrow itself.
In this example I am actually hiding the default arrow and displaying my own arrow instead.
.styleSelect select {_x000D_
background: transparent;_x000D_
width: 168px;_x000D_
padding: 5px;_x000D_
font-size: 16px;_x000D_
line-height: 1;_x000D_
border: 0;_x000D_
border-radius: 0;_x000D_
height: 34px;_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
appearance: none;_x000D_
color: #000;_x000D_
}_x000D_
_x000D_
.styleSelect {_x000D_
width: 140px;_x000D_
height: 34px;_x000D_
overflow: hidden;_x000D_
background: url("images/downArrow.png") no-repeat right #fff;_x000D_
border: 2px solid #000;_x000D_
}
_x000D_
<div class="styleSelect">_x000D_
<select class="units">_x000D_
<option value="Metres">Metres</option>_x000D_
<option value="Feet">Feet</option>_x000D_
<option value="Fathoms">Fathoms</option>_x000D_
</select>_x000D_
</div>
_x000D_
I had faced similar issue with Angular4 and Jasmine unit tests; below given solution worked for me
Add below import statement
import { APP_BASE_HREF } from '@angular/common';
Add below statement for TestBed configuration:
TestBed.configureTestingModule({
providers: [
{ provide: APP_BASE_HREF, useValue : '/' }
]
})
For start date of current year:
SELECT DATEADD(DD,-DATEPART(DY,GETDATE())+1,GETDATE())
For end date of current year:
SELECT DATEADD(DD,-1,DATEADD(YY,DATEDIFF(YY,0,GETDATE())+1,0))
A simple function that blits an image front
onto an image back
and returns the result. It works with both 3 and 4-channel images and deals with the alpha channel. Overlaps are handled as well.
The output image has the same size as back, but always 4 channels.
The output alpha channel is given by (u+v)/(1+uv) where u,v are the alpha channels of the front and back image and -1 <= u,v <= 1. Where there is no overlap with front, the alpha value from back is taken.
import cv2
def merge_image(back, front, x,y):
# convert to rgba
if back.shape[2] == 3:
back = cv2.cvtColor(back, cv2.COLOR_BGR2BGRA)
if front.shape[2] == 3:
front = cv2.cvtColor(front, cv2.COLOR_BGR2BGRA)
# crop the overlay from both images
bh,bw = back.shape[:2]
fh,fw = front.shape[:2]
x1, x2 = max(x, 0), min(x+fw, bw)
y1, y2 = max(y, 0), min(y+fh, bh)
front_cropped = front[y1-y:y2-y, x1-x:x2-x]
back_cropped = back[y1:y2, x1:x2]
alpha_front = front_cropped[:,:,3:4] / 255
alpha_back = back_cropped[:,:,3:4] / 255
# replace an area in result with overlay
result = back.copy()
print(f'af: {alpha_front.shape}\nab: {alpha_back.shape}\nfront_cropped: {front_cropped.shape}\nback_cropped: {back_cropped.shape}')
result[y1:y2, x1:x2, :3] = alpha_front * front_cropped[:,:,:3] + alpha_back * back_cropped[:,:,:3]
result[y1:y2, x1:x2, 3:4] = (alpha_front + alpha_back) / (1 + alpha_front*alpha_back) * 255
return result
Yes, it's a standard practice to commit package-lock.json
.
The main reason for committing package-lock.json
is that everyone in the project is on the same package version.
Pros:
Cons:
npm install
won't make sure that everyone in the project is on the same package version. npm ci
will help with this.
In SQL Server Management Studio, turn on SQLCMD mode from the Query menu. Then at the top of your script, type in the command below
:Connect server_name[\instance_name] [-l timeout] [-U user_name [-P password]
If you are connecting to multiple servers, be sure to insert GO
between connections; otherwise your T-SQL won't execute on the server you're thinking it will.
I would go with
i = np.min(np.where(V >= x))
where V
is vector (1d array), x
is the value and i
is the resulting index.
I needed a more flexible solution for working on multiple git repositories so I wrote the following sh code based on 1 and 2. You can use your server address instead of gitlab.com and your port in replace of 22.
SERVER=gitlab.com
PORT=22
nc -z -v -w5 $SERVER $PORT
result1=$?
#Do whatever you want
if [ "$result1" != 0 ]; then
echo 'port 22 is closed'
else
echo 'port 22 is open'
fi
The mailto:
URL scheme is defined in RFC 2368. Also, the convention for encoding information into URLs and URIs is defined in RFC 1738 and then RFC 3986. These prescribe how to include the body
and subject
headers into a URL (URI):
mailto:[email protected]?subject=current-issue&body=send%20current-issue
Specifically, you must percent-encode the email address, subject, and body and put them into the format above. Percent-encoded text is legal for use in HTML, however this URL must be entity encoded for use in an href
attribute, according to the HTML4 standard:
<a href="mailto:[email protected]?subject=current-issue&body=send%20current-issue">Send email</a>
And most generally, here is a simple PHP script that encodes per the above.
<?php
$encodedTo = rawurlencode($message->to);
$encodedSubject = rawurlencode($message->subject);
$encodedBody = rawurlencode($message->body);
$uri = "mailto:$encodedTo?subject=$encodedSubject&body=$encodedBody";
$encodedUri = htmlspecialchars($uri);
echo "<a href=\"$encodedUri\">Send email</a>";
?>
Try this:
[Authorize]
public ActionResult SomeAction()
{
var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;
...
}
i tend to use this calculation a lot in things i make, so i like to add it to the Math object:
Math.dist=function(x1,y1,x2,y2){
if(!x2) x2=0;
if(!y2) y2=0;
return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
Math.dist(0,0, 3,4); //the output will be 5
Math.dist(1,1, 4,5); //the output will be 5
Math.dist(3,4); //the output will be 5
Update:
this approach is especially happy making when you end up in situations something akin to this (i often do):
varName.dist=Math.sqrt( ( (varName.paramX-varX)/2-cx )*( (varName.paramX-varX)/2-cx ) + ( (varName.paramY-varY)/2-cy )*( (varName.paramY-varY)/2-cy ) );
that horrid thing becomes the much more manageable:
varName.dist=Math.dist((varName.paramX-varX)/2, (varName.paramY-varY)/2, cx, cy);
along with below command line parameters ,
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
Sometimes in the linux servers , imx connection doesn't get succeeded. that is because , in cloud linux host, in /etc/hosts so that the hostname resolves to the host address.
the best way to fix it is, ping the particular linux server from other machine in network and use that host IP address in the
-Djava.rmi.server.hostname=IP address that obtained when you ping that linux server.
But never rely on the ipaddress that you get from linux server using ifconfig.me. the ip that you get there is masked one which is present in the host file.
So - the solution of providing a base works given that all of the paths have the same base path. But if you want to provide different base paths, this still won't work.
One way I solved this problem was by making the beginning of the path relative. For your case:
gulp.src([
'index.php',
'*css/**/*',
'*js/**/*',
'*src/**/*',
])
.pipe(gulp.dest('/var/www/'));
The reason this works is that Gulp sets the base to be the end of the first explicit chunk - the leading * causes it to set the base at the cwd (which is the result that we all want!)
This only works if you can ensure your folder structure won't have certain paths that could match twice. For example, if you had randomjs/
at the same level as js
, you would end up matching both.
This is the only way that I have found to include these as part of a top-level gulp.src function. It would likely be simple to create a plugin/function that could separate out each of those globs so you could specify the base directory for them, however.
Try this, add this lines in the web.config.
<system.webServer>
<staticContent>
<mimeMap fileExtension=".woff" mimeType="application/octet-stream" />
</staticContent>
</system.webServer>
I would like to advertise the existence of the automatic introspection/reflection toolkit "IDK". It uses a meta-compiler like Qt's and adds meta information directly into object files. It is claimed to be easy to use. No external dependencies. It even allows you to automatically reflect std::string and then use it in scripts. Please look at IDK
Check kube-controller logs. I was able to solve this issue by setting the clusterID tags to the ec2 instance I deployed the cluster on.
the issue happened with me, I resolved by removing the scope tag only and built successfully.
public class ArrayDuplicate {
private static Scanner sc;
static int totalCount = 0;
public static void main(String[] args) {
int n, num;
sc = new Scanner(System.in);
System.out.print("Enter the size of array: ");
n =sc.nextInt();
int[] a = new int[n];
for(int i=0;i<n;i++){
System.out.print("Enter the element at position "+i+": ");
num = sc.nextInt();
a[enter image description here][1][i]=num;
}
System.out.print("Elements in array are: ");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
duplicate(a);
System.out.println("There are "+totalCount+" repeated numbers:");
}
public static void duplicate(int[] a){
int j = 0,count, recount, temp;
for(int i=0; i<a.length;i++){
count = 0;
recount = 0;
j=i+1;
while(j<a.length){
if(a[i]==a[j])
count++;
j++;
}
if(count>0){
temp = a[i];
for(int x=0;x<i;x++){
if(a[x]==temp)
recount++;
}
if(recount==0){
totalCount++;
System.out.println(+a[i]+" : "+count+" times");
}
}
}
}
}
To get the address of p do:
int **pp = &p;
and you can go on:
int ***ppp = &pp;
int ****pppp = &ppp;
...
or, only in C++11, you can do:
auto pp = std::addressof(p);
To print the address in C, most compilers support %p
, so you can simply do:
printf("addr: %p", pp);
otherwise you need to cast it (assuming a 32 bit platform)
printf("addr: 0x%u", (unsigned)pp);
In C++ you can do:
cout << "addr: " << pp;
For me the problem was solved by stocking my datas into an object (here "datas").
NgApp.controller('MyController', function($scope) {_x000D_
_x000D_
$scope.my_title = ""; // This don't work in ng-click function called_x000D_
_x000D_
$scope.datas = {_x000D_
'my_title' : "",_x000D_
};_x000D_
_x000D_
$scope.doAction = function() {_x000D_
console.log($scope.my_title); // bad value_x000D_
console.log($scope.datas.my_title); // Good Value binded by'ng-model'_x000D_
}_x000D_
_x000D_
_x000D_
});
_x000D_
I Hop it will help
Also download and unzip "Dependencies" into same folder where you put the wget.exe from
http://gnuwin32.sourceforge.net/packages/wget.htm
You will then have some lib*.dll files as well as wget.exe in the same folder and it should work fine.
(I also answered here https://superuser.com/a/873531/146668 which I originally found.)
Try this one:
<body onload="imageRefreshBig();">
Also you might want to check Javascript console for errors (in Chrome it's under Shift + Ctrl + J).
Use database column nullble() in Laravel. You can choose the default value or nullable value in database.
I found that when you use the action buttons in expanded notifications, you have to write extra code and you are more constrained.
You have to manually cancel your notification when the user clicks an action button. The notification is only cancelled automatically for the default action.
Also if you start a broadcast receiver from the button, the notification drawer doesn't close.
I ended up creating a new NotificationActivity to address these issues. This intermediary activity without any UI cancels the notification and then starts the activity I really wanted to start from the notification.
I've posted sample code in a related post Clicking Android Notification Actions does not close Notification drawer.
The @Url.Action()
method is proccess on the server-side
, so you cannot pass a client-side
value to this function as a parameter. You can concat the client-side
variables with the server-side
url generated by this method, which is a string on the output. Try something like this:
var firstname = "abc";
var username = "abcd";
location.href = '@Url.Action("Display", "Customer")?uname=' + firstname + '&name=' + username;
The @Url.Action("Display", "Customer")
is processed on the server-side
and the rest of the string is processed on the client-side
, concatenating the result of the server-side
method with the client-side
.
There is no way to delete or read the past history.
You could try going around it by emulating history in your own memory and calling history.pushState
everytime window popstate
event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:
So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.
Implemented this using python-os-walk. (http://www.pythonforbeginners.com/code-snippets-source-code/python-os-walk/)
import os
print("root prints out directories only from what you specified")
print("dirs prints out sub-directories from root")
print("files prints out all files from root and directories")
print("*" * 20)
for root, dirs, files in os.walk("/var/log"):
print(root)
print(dirs)
print(files)
Non VBA Solution:
Use Conditional Formatting rule with formula: =ISNA(A1)
(to highlight cells with all errors - not only #N/A
, use =ISERROR(A1)
)
VBA Solution:
Your code loops through 50 mln cells. To reduce number of cells, I use .SpecialCells(xlCellTypeFormulas, 16)
and .SpecialCells(xlCellTypeConstants, 16)
to return only cells with errors (note, I'm using If cell.Text = "#N/A" Then
)
Sub ColorCells()
Dim Data As Range, Data2 As Range, cell As Range
Dim currentsheet As Worksheet
Set currentsheet = ActiveWorkbook.Sheets("Comparison")
With currentsheet.Range("A2:AW" & Rows.Count)
.Interior.Color = xlNone
On Error Resume Next
'select only cells with errors
Set Data = .SpecialCells(xlCellTypeFormulas, 16)
Set Data2 = .SpecialCells(xlCellTypeConstants, 16)
On Error GoTo 0
End With
If Not Data2 Is Nothing Then
If Not Data Is Nothing Then
Set Data = Union(Data, Data2)
Else
Set Data = Data2
End If
End If
If Not Data Is Nothing Then
For Each cell In Data
If cell.Text = "#N/A" Then
cell.Interior.ColorIndex = 4
End If
Next
End If
End Sub
Note, to highlight cells witn any error (not only "#N/A"
), replace following code
If Not Data Is Nothing Then
For Each cell In Data
If cell.Text = "#N/A" Then
cell.Interior.ColorIndex = 3
End If
Next
End If
with
If Not Data Is Nothing Then Data.Interior.ColorIndex = 3
UPD: (how to add CF rule through VBA)
Sub test()
With ActiveWorkbook.Sheets("Comparison").Range("A2:AW" & Rows.Count).FormatConditions
.Delete
.Add Type:=xlExpression, Formula1:="=ISNA(A1)"
.Item(1).Interior.ColorIndex = 3
End With
End Sub
$start_date = date('Y-m-d h:m:s');
$end_date = date('Y-m-d h:m:s', strtotime($start_date . "+".$userSubscription['duration']." months") );
$user_subscription_array = array(
array(
'user_id' => $request->input('user_id'),
'user_subscription_plan_id' => $request->input('subscription_plan_id'),
'name' => $userSubscription['name'],
'description' => $userSubscription['description'],
'duration' => $userSubscription['duration'],
'start_datetime' => $start_date,
'end_datetime' => $end_date,
'amount' => $userSubscription['amount'],
'invoice_id' => '',
'transection_datetime' => '',
'created_by' => '1',
'status_id' => '1', ),
array(
'user_id' => $request->input('user_id'),
'user_subscription_plan_id' => $request->input('subscription_plan_id'),
'name' => $userSubscription['name'],
'description' => $userSubscription['description'],
'duration' => $userSubscription['duration'],
'start_datetime' => $start_date,
'end_datetime' => $end_date,
'amount' => $userSubscription['amount'],
'invoice_id' => '',
'transection_datetime' => '',
'created_by' => '1',
'status_id' => '1', )
);
dd(UserSubscription::insert($user_subscription_array));
UserSubscription
is my model name.
This will return "true" if insert successfully else "false".
you could see this info
for i in /var/run/*;do echo -n "$i "; find $i| wc -l;done | column -t
I landed here seeking to consume this...
[global]
spys = [email protected], [email protected]
The answer is to split it on the comma and strip the spaces:
SPYS = [e.strip() for e in parser.get('global', 'spys').split(',')]
To get a list result:
['[email protected]', '[email protected]']
It may not answer the OP's question exactly but might be the simple answer some people are looking for.
A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.
Consider the following code:
void Foo(int i, float f)
{
// Do things
}
void Bar()
{
int anInt = 1;
Foo(anInt, 2.0);
}
Here i
and f
are the parameters, and anInt
and 2.0
are the arguments.
use the include is the easiest way as per
http://www.vistax64.com/powershell/168315-get-childitem-filter-files-multiple-extensions.html
input(char_val,current_date_format);
You can specify any date format at display time, like set char_val=date9.;
First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.
For example,
> z <- factor(letters[c(3, 2, 3, 4)])
# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d
# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"
here, z
has 4 elements.
The index is 2, 1, 2, 3
in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.
Then, as.numeric
converts simply the index part of factor into numeric.
as.character
handles the index and levels, and generates character vector expressed by its level.
?as.numeric
says that Factors are handled by the default method.
Try this one,
{
"address": "colombo",
"username": "hesh",
"password": "123",
"registetedDate": "2015-4-3",
"firstname": "hesh",
"contactNo": "07762",
"accountNo": "16161",
"lastName": "jay",
"skill":[1436517454492,1436517476993]
}
you need to call thread.isAlive()
to find out if the thread is still running
You can use Map.
- A new data structure introduced in JavaScript ES6.
- Alternative to JavaScript Object for storing key/value pairs.
- Has useful methods for iteration over the key/value pairs.
var map = new Map();
map.set('name', 'John');
map.set('id', 11);
// Get the full content of the Map
console.log(map); // Map { 'name' => 'John', 'id' => 11 }
Get value of the Map using key
console.log(map.get('name')); // John
console.log(map.get('id')); // 11
Get size of the Map
console.log(map.size); // 2
Check key exists in Map
console.log(map.has('name')); // true
console.log(map.has('age')); // false
Get keys
console.log(map.keys()); // MapIterator { 'name', 'id' }
Get values
console.log(map.values()); // MapIterator { 'John', 11 }
Get elements of the Map
for (let element of map) {
console.log(element);
}
// Output:
// [ 'name', 'John' ]
// [ 'id', 11 ]
Print key value pairs
for (let [key, value] of map) {
console.log(key + " - " + value);
}
// Output:
// name - John
// id - 11
Print only keys of the Map
for (let key of map.keys()) {
console.log(key);
}
// Output:
// name
// id
Print only values of the Map
for (let value of map.values()) {
console.log(value);
}
// Output:
// John
// 11
Normally in Visual Studio 2015 you should create the dll project as a C++ -> CLR project from Visual Studio's templates, but you can technically enable it after the fact:
The critical property is called Common Language Runtime Support
set in your project's configuration. It's found under Configuration Properties > General > Common Language Runtime Support
.
When doing this, VS will probably not update the 'Target .NET Framework' option (like it should). You can manually add this by unloading your project, editing the your_project.xxproj file, and adding/updating the Target .NET framework Version
XML tag.
For a sample, I suggest creating a new solution as a C++ CLR project and examining the XML there, perhaps even diffing it to make sure there's nothing very important that's out of the ordinary.
I found the solution for the above program, which had the goal of signing in to http://rediff.com
public class Handle_popupNAlert
{
public static void main(String[] args ) throws InterruptedException
{
WebDriver driver= new FirefoxDriver();
driver.get("http://www.rediff.com/");
WebElement sign = driver.findElement(By.xpath("//html/body/div[3]/div[3]/span[4]/span/a"));
sign.click();
Set<String> windowId = driver.getWindowHandles(); // get window id of current window
Iterator<String> itererator = windowId.iterator();
String mainWinID = itererator.next();
String newAdwinID = itererator.next();
driver.switchTo().window(newAdwinID);
System.out.println(driver.getTitle());
Thread.sleep(3000);
driver.close();
driver.switchTo().window(mainWinID);
System.out.println(driver.getTitle());
Thread.sleep(2000);
WebElement email_id= driver.findElement(By.xpath("//*[@id='c_uname']"));
email_id.sendKeys("hi");
Thread.sleep(5000);
driver.close();
driver.quit();
}
}
I'm sorry to do this, but I couldn't use any of the other answers as-is and haven't time to duke it out in the comments.
Uses C# 6 syntax.
static class EnumExtensions
{
/// returns the localized Name, if a [Display(Name="Localised Name")] attribute is applied to the enum member
/// returns null if there isnt an attribute
public static string DisplayNameOrEnumName(this Enum value)
// => value.DisplayNameOrDefault() ?? value.ToString()
{
// More efficient form of ^ based on http://stackoverflow.com/a/17034624/11635
var enumType = value.GetType();
var enumMemberName = Enum.GetName(enumType, value);
return enumType
.GetEnumMemberAttribute<DisplayAttribute>(enumMemberName)
?.GetName() // Potentially localized
?? enumMemberName; // Or fall back to the enum name
}
/// returns the localized Name, if a [Display] attribute is applied to the enum member
/// returns null if there is no attribute
public static string DisplayNameOrDefault(this Enum value) =>
value.GetEnumMemberAttribute<DisplayAttribute>()?.GetName();
static TAttribute GetEnumMemberAttribute<TAttribute>(this Enum value) where TAttribute : Attribute =>
value.GetType().GetEnumMemberAttribute<TAttribute>(value.ToString());
static TAttribute GetEnumMemberAttribute<TAttribute>(this Type enumType, string enumMemberName) where TAttribute : Attribute =>
enumType.GetMember(enumMemberName).Single().GetCustomAttribute<TAttribute>();
}
If there are no spaces in paths, and you are interested, like I was, in files of specific extension only, you can use
git checkout otherBranch -- $(git ls-tree --name-only -r otherBranch | egrep '*.java')
Here is a more useful example:
pcregrep -Mi "<title>(.*\n){0,5}</title>" afile.html
It searches the title tag in a html file even if it spans up to 5 lines.
Here is an example of unlimited lines:
pcregrep -Mi "(?s)<title>.*</title>" example.html
Use the modulus (%
) operator:
6 % 3 == 0
7 % 3 == 1
You can fix the errors by appending to the cmake
command the -DPYTHON_LIBRARY
and -DPYTHON_INCLUDE_DIR
flags filled with the respective folders.
Thus, the trick is to fill those parameters with the returned information from the python interpreter, which is the most reliable. This may work independently of your python location/version (also for Anaconda users):
$ cmake .. \
-DPYTHON_INCLUDE_DIR=$(python -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") \
-DPYTHON_LIBRARY=$(python -c "import distutils.sysconfig as sysconfig; print(sysconfig.get_config_var('LIBDIR'))")
If the version of python that you want to link against cmake is Python3.X and the default python symlink points to Python2.X, python3 -c ...
can be used instead of python -c ...
.
In case that the error persists, you may need to update the cmake
to a higher version as stated by @pdpcosta and repeat the process again.
You should not need to access Maven-specific files to get the version information of any given library/class.
You can simply use getClass().getPackage().getImplementationVersion()
to get the version information that is stored in a .jar-files MANIFEST.MF
. Luckily Maven is smart enough Unfortunately Maven does not write the correct information to the manifest as well by default!
Instead one has to modify the <archive>
configuration element of the maven-jar-plugin
to set addDefaultImplementationEntries
and addDefaultSpecificationEntries
to true
, like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>
Ideally this configuration should be put into the company pom
or another base-pom.
Detailed documentation of the <archive>
element can be found in the Maven Archive documentation.
I encountered this issue while doing a git pull
.
I tried git gc
and it resolved my problem.
HTML in line styling example:
<td style='text-align:center; vertical-align:middle'></td>
CSS file example:
td {
text-align: center;
vertical-align: middle;
}
https://github.com/abdmob/x2js - my own library (updated URL from http://code.google.com/p/x2js/):
This library provides XML to JSON (JavaScript Objects) and vice versa javascript conversion functions. The library is very small and doesn't require any other additional libraries.
API functions
- new X2JS() - to create your instance to access all library functionality. Also you could specify optional configuration options here
- X2JS.xml2json - Convert XML specified as DOM Object to JSON
- X2JS.json2xml - Convert JSON to XML DOM Object
- X2JS.xml_str2json - Convert XML specified as string to JSON
- X2JS.json2xml_str - Convert JSON to XML string
Online Demo on http://jsfiddle.net/abdmob/gkxucxrj/1/
var x2js = new X2JS();
function convertXml2JSon() {
$("#jsonArea").val(JSON.stringify(x2js.xml_str2json($("#xmlArea").val())));
}
function convertJSon2XML() {
$("#xmlArea").val(x2js.json2xml_str($.parseJSON($("#jsonArea").val())));
}
convertXml2JSon();
convertJSon2XML();
$("#convertToJsonBtn").click(convertXml2JSon);
$("#convertToXmlBtn").click(convertJSon2XML);
I solved this with Access options.
Go to the Office Button --> Access Options --> Trust Center --> Trust Center Settings Button --> Message Bar
In the right hand pane I selected the radio button "Show the message bar in all applications when content has been blocked."
Closed Access, reopened the database and got the warning for blocked content again.
You don't need to use arrays.
JSON values can be arrays, objects, or primitives (numbers or strings).
You can write JSON like this:
{
"stuff": {
"onetype": [
{"id":1,"name":"John Doe"},
{"id":2,"name":"Don Joeh"}
],
"othertype": {"id":2,"company":"ACME"}
},
"otherstuff": {
"thing": [[1,42],[2,2]]
}
}
You can use it like this:
obj.stuff.onetype[0].id
obj.stuff.othertype.id
obj.otherstuff.thing[0][1] //thing is a nested array or a 2-by-2 matrix.
//I'm not sure whether you intended to do that.
You just need to provide object reference . Please provide your class name in the position.
private static void data2()
{
<classname> c1 = new <classname>();
c1. data1();
}
It's not perfect, but I wrote this helper for my tests in C#:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Proto.Promises.Tests.Threading
{
public class ThreadHelper
{
public static readonly int multiThreadCount = Environment.ProcessorCount * 100;
private static readonly int[] offsets = new int[] { 0, 10, 100, 1000 };
private readonly Stack<Task> _executingTasks = new Stack<Task>(multiThreadCount);
private readonly Barrier _barrier = new Barrier(1);
private int _currentParticipants = 0;
private readonly TimeSpan _timeout;
public ThreadHelper() : this(TimeSpan.FromSeconds(10)) { } // 10 second timeout should be enough for most cases.
public ThreadHelper(TimeSpan timeout)
{
_timeout = timeout;
}
/// <summary>
/// Execute the action multiple times in parallel threads.
/// </summary>
public void ExecuteMultiActionParallel(Action action)
{
for (int i = 0; i < multiThreadCount; ++i)
{
AddParallelAction(action);
}
ExecutePendingParallelActions();
}
/// <summary>
/// Execute the action once in a separate thread.
/// </summary>
public void ExecuteSingleAction(Action action)
{
AddParallelAction(action);
ExecutePendingParallelActions();
}
/// <summary>
/// Add an action to be run in parallel.
/// </summary>
public void AddParallelAction(Action action)
{
var taskSource = new TaskCompletionSource<bool>();
lock (_executingTasks)
{
++_currentParticipants;
_barrier.AddParticipant();
_executingTasks.Push(taskSource.Task);
}
new Thread(() =>
{
try
{
_barrier.SignalAndWait(); // Try to make actions run in lock-step to increase likelihood of breaking race conditions.
action.Invoke();
taskSource.SetResult(true);
}
catch (Exception e)
{
taskSource.SetException(e);
}
}).Start();
}
/// <summary>
/// Runs the pending actions in parallel, attempting to run them in lock-step.
/// </summary>
public void ExecutePendingParallelActions()
{
Task[] tasks;
lock (_executingTasks)
{
_barrier.SignalAndWait();
_barrier.RemoveParticipants(_currentParticipants);
_currentParticipants = 0;
tasks = _executingTasks.ToArray();
_executingTasks.Clear();
}
try
{
if (!Task.WaitAll(tasks, _timeout))
{
throw new TimeoutException($"Action(s) timed out after {_timeout}, there may be a deadlock.");
}
}
catch (AggregateException e)
{
// Only throw one exception instead of aggregate to try to avoid overloading the test error output.
throw e.Flatten().InnerException;
}
}
/// <summary>
/// Run each action in parallel multiple times with differing offsets for each run.
/// <para/>The number of runs is 4^actions.Length, so be careful if you don't want the test to run too long.
/// </summary>
/// <param name="expandToProcessorCount">If true, copies each action on additional threads up to the processor count. This can help test more without increasing the time it takes to complete.
/// <para/>Example: 2 actions with 6 processors, runs each action 3 times in parallel.</param>
/// <param name="setup">The action to run before each parallel run.</param>
/// <param name="teardown">The action to run after each parallel run.</param>
/// <param name="actions">The actions to run in parallel.</param>
public void ExecuteParallelActionsWithOffsets(bool expandToProcessorCount, Action setup, Action teardown, params Action[] actions)
{
setup += () => { };
teardown += () => { };
int actionCount = actions.Length;
int expandCount = expandToProcessorCount ? Math.Max(Environment.ProcessorCount / actionCount, 1) : 1;
foreach (var combo in GenerateCombinations(offsets, actionCount))
{
setup.Invoke();
for (int k = 0; k < expandCount; ++k)
{
for (int i = 0; i < actionCount; ++i)
{
int offset = combo[i];
Action action = actions[i];
AddParallelAction(() =>
{
for (int j = offset; j > 0; --j) { } // Just spin in a loop for the offset.
action.Invoke();
});
}
}
ExecutePendingParallelActions();
teardown.Invoke();
}
}
// Input: [1, 2, 3], 3
// Ouput: [
// [1, 1, 1],
// [2, 1, 1],
// [3, 1, 1],
// [1, 2, 1],
// [2, 2, 1],
// [3, 2, 1],
// [1, 3, 1],
// [2, 3, 1],
// [3, 3, 1],
// [1, 1, 2],
// [2, 1, 2],
// [3, 1, 2],
// [1, 2, 2],
// [2, 2, 2],
// [3, 2, 2],
// [1, 3, 2],
// [2, 3, 2],
// [3, 3, 2],
// [1, 1, 3],
// [2, 1, 3],
// [3, 1, 3],
// [1, 2, 3],
// [2, 2, 3],
// [3, 2, 3],
// [1, 3, 3],
// [2, 3, 3],
// [3, 3, 3]
// ]
private static IEnumerable<int[]> GenerateCombinations(int[] options, int count)
{
int[] indexTracker = new int[count];
int[] combo = new int[count];
for (int i = 0; i < count; ++i)
{
combo[i] = options[0];
}
// Same algorithm as picking a combination lock.
int rollovers = 0;
while (rollovers < count)
{
yield return combo; // No need to duplicate the array since we're just reading it.
for (int i = 0; i < count; ++i)
{
int index = ++indexTracker[i];
if (index == options.Length)
{
indexTracker[i] = 0;
combo[i] = options[0];
if (i == rollovers)
{
++rollovers;
}
}
else
{
combo[i] = options[index];
break;
}
}
}
}
}
}
Example usage:
[Test]
public void DeferredMayBeBeResolvedAndPromiseAwaitedConcurrently_void0()
{
Promise.Deferred deferred = default(Promise.Deferred);
Promise promise = default(Promise);
int invokedCount = 0;
var threadHelper = new ThreadHelper();
threadHelper.ExecuteParallelActionsWithOffsets(false,
// Setup
() =>
{
invokedCount = 0;
deferred = Promise.NewDeferred();
promise = deferred.Promise;
},
// Teardown
() => Assert.AreEqual(1, invokedCount),
// Parallel Actions
() => deferred.Resolve(),
() => promise.Then(() => { Interlocked.Increment(ref invokedCount); }).Forget()
);
}
To reset a specific file as git status suggests:
git checkout <filename>
To reset a folder
git checkout <foldername>/*
>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])
For implementing the timeout on the function, this stackoverflow thread has answers on that.
Imho this is a flaw in many c compilers. I know for a fact that the compilers i worked with do not store a "static const"variable at an adress but replace the use in the code by the very constant. This can be verified as you will get the same checksum for the produced code when you use a preprocessors #define directive and when you use a static const variable.
Either way you should use static const variables instead of #defines whenever possible as the static const is type safe.
You can only use one color but as many images as you want, here is the format:
background: [ <bg-layer> , ]* <final-bg-layer>
<bg-layer> = <bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2}
<final-bg-layer> = <bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2} || <background-color>
or
background: url(image1.png) center bottom no-repeat, url(image2.png) left top no-repeat;
If you need more colors, make an image of a solid color and use it. I know it’s not what you want to hear, but I hope it helps.
The format is from http://www.css3.info/preview/multiple-backgrounds/
I don't know PHP, so I don't know if this is possible, but the best solution would be to read the file as UTF-8 rather than some other encoding. The BOM is actually a ZERO WIDTH NO BREAK SPACE. This is whitespace, so if the file were being read in the correct encoding (UTF-8), then the BOM would be interpreted as whitespace and it would be ignored in the resulting CSS file.
Also, another advantage of reading the file in the correct encoding is that you don't have to worry about characters being misinterpreted. Your editor is telling you that the code page you want to save it in won't do all the characters that you need. If PHP is then reading the file in the incorrect encoding, then it is very likely that other characters besides the BOM are being silently misinterpreted. Use UTF-8 everywhere, and these problems disappear.
I know this is an old question but it's worth noting that BlackBerry doesn't support overflow-x
or overflow-y
.
See my post here
In my case, the issue was that the main table already had records in it and I was forcing the new column to not be NULL. So adding a ->nullable() to the new column did the trick. In the question's example would be something like this:
$table->integer('user_id')->unsigned()->nullable();
or:
$table->unsignedInteger('user_id')->nullable();
Hope this helps somebody!
Your comparison function is not even wrong.
Its arguments should be the type stored in the range, i.e. std::pair<K,V>
, not const void*
.
It should return bool
not a positive or negative value. Both (bool)1
and (bool)-1
are true
so your function says every object is ordered before every other object, which is clearly impossible.
You need to model the less-than operator, not strcmp
or memcmp
style comparisons.
See StrictWeakOrdering which describes the properties the function must meet.