Here's my solution
# ...
RUN mkdir -p /opt
ADD initd.sh /opt/
RUN chmod +x /opt/initd.sh
ENTRYPOINT ["/opt/initd.sh"]
initd.sh
file#!/bin/bash
...
/etc/init.d/gearman-job-server start
/etc/init.d/supervisor start
#very important!!!
/bin/bash
exec
or attach
:Use exec (preferred) and run:
docker run --name $CONTAINER_NAME -dt $IMAGE_NAME
then
docker exec -it $CONTAINER_NAME /bin/bash
and use CTRL + D to detach
Use attach and run:
docker run --name $CONTAINER_NAME -dit $IMAGE_NAME
then
docker attach $CONTAINER_NAME
and use CTRL + P and CTRL + Q to detach
Note: The difference between options is in parameter -i
You can make a union using .addAll(), and an intersection using .retainAll(), of the two sets and use .removeIf(), to remove the intersection (or the duplicated element) from the union.
HashSet union = new HashSet(group1);
union.addAll(group2);
System.out.println("Union: " + union);
HashSet intersection = new HashSet(group1);
intersection.retainAll(group2);
System.out.println("Intersection: " + intersection);
HashSet difference = new HashSet(union);
difference.removeIf(n -> (difference.contains(intersection)));
System.out.println("Difference: " + difference);
Please refer below answer for ripple effect.
ripple on Textview or view :
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackgroundBorderless"
ripple on Button or Imageview :
android:foreground="?android:attr/selectableItemBackgroundBorderless"
'\r' = carriage return and '\n' = line feed.
In fact, there are some different behaviors when you use them in different OSes. On Unix it is '\n', but it is '\r''\n' on Windows.
If you are using tcsh, then edit your ~/.cshrc
file to include the lines:
setenv CLICOLOR 1
setenv LSCOLORS dxfxcxdxbxegedabagacad
Where, like Martin says, LSCOLORS specifies the color scheme you want to use.
To generate the LSCOLORS you want to use, checkout this site
I found the cleanest way of doing it is this.
Tested on Django 3.1.5
class MyForm(forms.Form):
my_boolean = forms.BooleanField(required=False, initial=True)
This worked for me when i have userdefined Interface 'TopSectionListener', its object activitycommander:
//This method gets called whenever we attach fragment to the activity
@Override
public void onAttach(Context context) {
super.onAttach(context);
Activity a=getActivity();
try {
if(context instanceof Activity)
this.activitycommander=(TopSectionListener)a;
}catch (ClassCastException e){
throw new ClassCastException(a.toString());}
}
You're looking for Enumerable#select (also called find_all
):
@fathers.select {|father| father["age"] > 35 }
# => [ { "age" => 40, "father" => "Bob" },
# { "age" => 50, "father" => "Batman" } ]
Per the documentation, it "returns an array containing all elements of [the enumerable, in this case @fathers
] for which block is not false."
I was able to install libc6 2.17
in Debian Wheezy
by editing the recommendations in perror's answer:
IMPORTANT
You need to exit out of your display manager by pressing CTRL-ALT-F1.
Then you can stop x (slim
) with sudo /etc/init.d/slim stop
(replace slim with mdm
or lightdm
or whatever)
Add the following line to the file /etc/apt/sources.list
:
deb http://ftp.debian.org/debian experimental main
Should be changed to:
deb http://ftp.debian.org/debian sid main
Then follow the rest of perror's post:
Update your package database:
apt-get update
Install the eglibc
package:
apt-get -t sid install libc6-amd64 libc6-dev libc6-dbg
IMPORTANT
After done updating libc6
, restart computer, and you should comment out or remove the sid source you just added (deb http://ftp.debian.org/debian sid main
), or else you risk upgrading your whole distro to sid.
Hope this helps. It took me a while to figure out.
As an alternative, you could add it as a script parameter for input as part of script execution
param(
[Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value1,
[Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value2
)
To stop the service we must use the method stopService()
:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
//startService(myService);
stopService(myService);
then the method onDestroy()
in the service is called:
@Override
public void onDestroy() {
Log.i(TAG, "onCreate() , service stopped...");
}
Here is a complete example including how to stop the service.
I think the exact answer is: for api 11 or higher:
getActionBar().setDisplayShowHomeEnabled(false);
otherwise:
getSupportActionBar().setDisplayShowHomeEnabled(false);
(because it need a support library.)
You can use any of the below code to get the controller name
@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
If you are using MVC 3 you can use
@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
UPDATE 9 July 2012 - Looks like this is fixed in RTM.
^
and $
so you don't need to add them. (It doesn't appear to be a problem to include them, but you don't need them)View source shows the following:
data-val-regex-pattern="([a-zA-Z0-9 .&'-]+)" <-- MVC 3
data-val-regex-pattern="([a-zA-Z0-9 .&amp;&#39;-]+)" <-- MVC 4/Beta
It looks like we're double encoding.
If you have already defined your view in layout(xml) file and only want to change the weight pro grammatically, then then creating new LayoutParams overwrites other params defined in you xml file.
So first you should use "getLayoutParams" and then setLayoutParams
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mButton.getLayoutParams();
params.weight = 4f;
mButton.setLayoutParams(params);
Old post, but maybe this helps someone out:
To complete until it ends up with 4 non-blank characters:
SELECT RIGHT ('0000'+COLUMNNAME, 4) FROM TABLENAME;
To complete until 10:
SELECT RIGHT ('0000000000'+COLUMNNAME, 10) FROM TABLENAME;
In case the column is numeric, convert it to varchar first with such code:
Select RIGHT('0000'+Convert(nvarchar(20), COLUMNNAME), 4)
From TABLENAME
And to complete until 10 with a numeric field:
SELECT RIGHT ('0000000000'+Convert(nvarchar(20), COLUMNNAME), 10) FROM TABLENAME;
If there is already a nbproject folder it means you can open it straight ahead without importing it as a project with existing sources (ctrl+shift+o) or (cmd+shift+o)
Here's what I've been doing to cope with the situation.
I use global imports on a new test class.
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;
When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;
This allows you to code away without getting 'stuck' trying to find the correct package to import.
One simple way of doing this is:
var data = [{_x000D_
"Total": 34,_x000D_
"Version": "1.0.4",_x000D_
"Office": "New York"_x000D_
}, {_x000D_
"Total": 67,_x000D_
"Version": "1.1.0",_x000D_
"Office": "Paris"_x000D_
}];_x000D_
_x000D_
drawTable(data);_x000D_
_x000D_
function drawTable(data) {_x000D_
_x000D_
// Get Table headers and print_x000D_
var head = $("<tr />")_x000D_
$("#DataTable").append(head);_x000D_
for (var j = 0; j < Object.keys(data[0]).length; j++) {_x000D_
head.append($("<th>" + Object.keys(data[0])[j] + "</th>"));_x000D_
}_x000D_
_x000D_
// Print the content of rows in DataTable_x000D_
for (var i = 0; i < data.length; i++) {_x000D_
drawRow(data[i]);_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
function drawRow(rowData) {_x000D_
var row = $("<tr />")_x000D_
$("#DataTable").append(row);_x000D_
row.append($("<td>" + rowData["Total"] + "</td>"));_x000D_
row.append($("<td>" + rowData["Version"] + "</td>"));_x000D_
row.append($("<td>" + rowData["Office"] + "</td>"));_x000D_
}
_x000D_
table {_x000D_
border: 1px solid #666;_x000D_
width: 100%;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
th {_x000D_
background: #f8f8f8;_x000D_
font-weight: bold;_x000D_
padding: 2px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<table id="DataTable"></table>
_x000D_
The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.
Use the ll (el-el) long-long modifier with the u (unsigned) conversion. (Works in windows, GNU).
printf("%llu", 285212672);
I've needed this and after some research I came up with this (jQuery needed):
First, right after the <body>
tag add this:
<div id="loading">
<img id="loading-image" src="images/ajax-loader.gif" alt="Loading..." />
</div>
Then add the style class for the div and image to your CSS:
#loading {
width: 100%;
height: 100%;
top: 0;
left: 0;
position: fixed;
display: block;
opacity: 0.7;
background-color: #fff;
z-index: 99;
text-align: center;
}
#loading-image {
position: absolute;
top: 100px;
left: 240px;
z-index: 100;
}
Then, add this javascript to your page (preferably at the end of your page, before your closing </body>
tag, of course):
<script>
$(window).load(function() {
$('#loading').hide();
});
</script>
Finally, adjust the position of the loading image and the background-colour
of the loading div with the style class.
This is it, should work just fine. But of course you have to have an ajax-loader.gif
somewhere. Freebies here. (Right-click > Save Image As...)
I use WinMerge. It is free and works pretty well (works for files and directories).
If you want to use version 3.1 you need to use the following schema:
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd
Note that 3.0 and 3.1 are different: in 3.1 there's no Sun mentioned, so simply changing 3_0.xsd
to 3_1.xsd
won't work.
This is how it should look like:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:web="http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee">
</web-app>
Also, make sure you're depending on the latest versions in your pom.xml
. That is,
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
...
</configuration>
</plugin>
and
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
Finally, you should compile with Java 7 or 8:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
testField.getText()
See the java doc for JTextField
Sample code can be:
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String textFieldValue = testField.getText();
// .... do some operation on value ...
}
})
Make sure the following lines are not in your wp.config
define( 'FORCE_SSL_LOGIN', true );
define( 'FORCE_SSL_ADMIN', true );
define( 'DISALLOW_FILE_EDIT', true );
I got locked out after deactivating iThemes security plugin
Use the LocationManager
.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
The call to getLastKnownLocation()
doesn't block - which means it will return null
if no position is currently available - so you probably want to have a look at passing a LocationListener
to the requestLocationUpdates()
method instead, which will give you asynchronous updates of your location.
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
You'll need to give your application the ACCESS_FINE_LOCATION
permission if you want to use GPS.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You may also want to add the ACCESS_COARSE_LOCATION
permission for when GPS isn't available and select your location provider with the getBestProvider()
method.
Can try this too, almost similar previous answers.
d = {'filename': ['M66_MI_NSRh35d32kpoints.dat', 'F71_sMI_DMRI51d.dat', 'F62_sMI_St22d7.dat', 'F41_Car_HOC498d.dat', 'F78_MI_547d.dat'], 'alpha1': [0.8016, 0.0, 1.721, 1.167, 1.897], 'alpha2': [0.9283, 0.0, 3.833, 2.809, 5.459], 'gamma1': [1.0, np.nan, 0.23748000000000002, 0.36419, 0.095319], 'gamma2': [0.074804, 0.0, 0.15, 0.3, np.nan], 'chi2min': [39.855990000000006, 1e+25, 10.91832, 7.966335000000001, 25.93468]}
df = pd.DataFrame(d).set_index('filename')
Count of null values in each column.
df.isnull().sum()
df.isnull().any(axis=1)
In most of the companies they required a common functionality for multiple dropdownlist for all the pages. Just call the functions or pass your (DropDownID,JsonData,KeyValue,textValue)
<script>
$(document).ready(function(){
GetData('DLState',data,'stateid','statename');
});
var data = [{"stateid" : "1","statename" : "Mumbai"},
{"stateid" : "2","statename" : "Panjab"},
{"stateid" : "3","statename" : "Pune"},
{"stateid" : "4","statename" : "Nagpur"},
{"stateid" : "5","statename" : "kanpur"}];
var Did=document.getElementById("DLState");
function GetData(Did,data,valkey,textkey){
var str= "";
for (var i = 0; i <data.length ; i++){
console.log(data);
str+= "<option value='" + data[i][valkey] + "'>" + data[i][textkey] + "</option>";
}
$("#"+Did).append(str);
}; </script>
</head>
<body>
<select id="DLState">
</select>
</body>
</html>
In my case I faced this issue in my simulator because my computer's date was behind of current date. So do check this case too when you face SSL error.
try doing var_dump($_GLOBALS)
.
A potential cause could be that there is a script running before yours which unsets the global variables. Such as:
unset($_REQUEST);
or even.
unset($GLOBALS);
This could be done via the auto_prepend_file option in the php.ini configuration.
Your "bad" output is UTF-8 displayed as CP1252.
On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:
df.to_csv('file.csv',encoding='utf-8-sig')
That encoder will add the BOM.
The average function you can do is:
const getAverage = (arr) => arr.reduce((p, c) => p + c, 0) / arr.length
Also, I suggest that use the popoular open source tool, eg. Lodash
:
const _ = require('lodash')
const getAverage = (arr) => _.chain(arr)
.sum()
.divide(arr.length)
.round(1)
.value()
As mentioned by @Brent in the comment of @maxymoo's answer, you can try
df.limit(10).toPandas()
to get a prettier table in Jupyter. But this can take some time to run if you are not caching the spark dataframe. Also, .limit()
will not keep the order of original spark dataframe.
Run it on a single command line like so:
powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile
-WindowStyle Hidden -Command "Get-AppLockerFileInformation -Directory <folderpath>
-Recurse -FileType <type>"
Based on another solutions. I have use this:
IntPtr xAsIntPtr = new IntPtr(excelObj.Application.Hwnd);
excelObj.ActiveWorkbook.Close();
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("Excel");
foreach (System.Diagnostics.Process p in process)
{
if (p.MainWindowHandle == xAsIntPtr)
{
try
{
p.Kill();
}
catch { }
}
}
Using the "MainWindowHandle" to identify the process and close him.
excelObj: This is my Application Interop excel objecto
Assume that you have 2 branches,
"branchA" : includes commits you want to copy (from "commitA" to "commitB"
"branchB" : the branch you want the commits to be transferred from "branchA"
1)
git checkout <branchA>
2) get the IDs of "commitA" and "commitB"
3)
git checkout <branchB>
4)
git cherry-pick <commitA>^..<commitB>
5) In case you have a conflict, solve it and type
git cherry-pick --continue
to continue the cherry-pick process.
A supplemental visual view of pd.concat([df0, df1], kwargs)
.
Notice that, kwarg axis=0
or axis=1
's meaning is not as intuitive as df.mean()
or df.apply(func)
>>> test
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> ncol = test.shape[1]
>>> ncol
5L
Then you can select the 2nd - 4th column this way:
>>> test[0:, 1:(ncol - 1)]
array([[1, 2, 3],
[6, 7, 8]])
??
should be preferred to ||
because it checks only for nulls and undefined.
All The expressions below are true:
(null || 'x') === 'x' ;
(undefined || 'x') === 'x' ;
//Most of the times you don't want the result below
('' || 'x') === 'x' ;
(0 || 'x') === 'x' ;
(false || 'x') === 'x' ;
//-----
//Using ?? is preferred
(null ?? 'x') === 'x' ;
(undefined ?? 'x') === 'x' ;
//?? works only for null and undefined, which is in general safer
('' ?? 'x') === '' ;
(0 ?? 'x') === 0 ;
(false ?? 'x') === false ;
Bottom line:
int j=i ?? 10;
is perfectly fine to use in javascript also. Just replace int
with let
.
Asterisk: Check browser compatibility and if you really need to support these other browsers use babel.
Updated Answer:
The documentation for SmtpClient
, the class used in this answer, now reads, 'Obsolete("SmtpClient and its network of types are poorly designed, we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead")'.
Source: https://www.infoq.com/news/2017/04/MailKit-MimeKit-Official
Original Answer:
Using the MailDefinition class is the wrong approach. Yes, it's handy, but it's also primitive and depends on web UI controls--that doesn't make sense for something that is typically a server-side task.
The approach presented below is based on MSDN documentation and Qureshi's post on CodeProject.com.
NOTE: This example extracts the HTML file, images, and attachments from embedded resources, but using other alternatives to get streams for these elements are fine, e.g. hard-coded strings, local files, and so on.
Stream htmlStream = null;
Stream imageStream = null;
Stream fileStream = null;
try
{
// Create the message.
var from = new MailAddress(FROM_EMAIL, FROM_NAME);
var to = new MailAddress(TO_EMAIL, TO_NAME);
var msg = new MailMessage(from, to);
msg.Subject = SUBJECT;
msg.SubjectEncoding = Encoding.UTF8;
// Get the HTML from an embedded resource.
var assembly = Assembly.GetExecutingAssembly();
htmlStream = assembly.GetManifestResourceStream(HTML_RESOURCE_PATH);
// Perform replacements on the HTML file (if you're using it as a template).
var reader = new StreamReader(htmlStream);
var body = reader
.ReadToEnd()
.Replace("%TEMPLATE_TOKEN1%", TOKEN1_VALUE)
.Replace("%TEMPLATE_TOKEN2%", TOKEN2_VALUE); // and so on...
// Create an alternate view and add it to the email.
var altView = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
msg.AlternateViews.Add(altView);
// Get the image from an embedded resource. The <img> tag in the HTML is:
// <img src="pid:IMAGE.PNG">
imageStream = assembly.GetManifestResourceStream(IMAGE_RESOURCE_PATH);
var linkedImage = new LinkedResource(imageStream, "image/png");
linkedImage.ContentId = "IMAGE.PNG";
altView.LinkedResources.Add(linkedImage);
// Get the attachment from an embedded resource.
fileStream = assembly.GetManifestResourceStream(FILE_RESOURCE_PATH);
var file = new Attachment(fileStream, MediaTypeNames.Application.Pdf);
file.Name = "FILE.PDF";
msg.Attachments.Add(file);
// Send the email
var client = new SmtpClient(...);
client.Credentials = new NetworkCredential(...);
client.Send(msg);
}
finally
{
if (fileStream != null) fileStream.Dispose();
if (imageStream != null) imageStream.Dispose();
if (htmlStream != null) htmlStream.Dispose();
}
You can move to desired activity on button click. just add
android:onClick="timerApp"this line.
xml:
<Button
android:id="@+id/timer_app"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="timerApp"
android:text="Click To run Timer Activity" />
In your main activity just add this method:
public void timerApp(View view){
Intent intent= new Intent(MainActivity.this,TimerActivity.class);
startActivity(intent);
}
OR in onCreate() method add below code
Button btn =findViewById(R.id.timer_app);//Don't need to type casting in android studio 3
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, TimerActivity.class);
startActivity(intent);
}
});
You can create a delay using the following example
setInterval(function(){alert("Hello")},3000);
Replace 3000 with # of milliseconds
You can place the content of what you want executed inside the function.
For people using JQuery:
Sometimes, when you have nested elements, one of them with the event attached to it, it can be confusing to understand what your browser sees as the parent. Here, you can specify which parent.
You take the mouse position, and then subtract it from the parent element's offset position.
var x = evt.pageX - $('#element').offset().left;
var y = evt.pageY - $('#element').offset().top;
If you're trying to get the mouse position on a page inside a scrolling pane:
var x = (evt.pageX - $('#element').offset().left) + self.frame.scrollLeft();
var y = (evt.pageY - $('#element').offset().top) + self.frame.scrollTop();
Or the position relative to the page:
var x = (evt.pageX - $('#element').offset().left) + $(window).scrollLeft();
var y = (evt.pageY - $('#element').offset().top) + $(window).scrollTop();
Note the following performance optimisation:
var offset = $('#element').offset();
// Then refer to
var x = evt.pageX - offset.left;
In this way, JQuery does not have to look up #element
for each line.
There is a newer, JavaScript-only version in an answer by @anytimecoder -- see also browser support for getBoundingClientRect().
The best solution is: from positive to negative or from negative to positive
For negative:
SELECT ABS(a) * -1 AS AbsoluteA, ABS(b) * -1 AS AbsoluteB
FROM YourTable
For positive:
SELECT ABS(a) AS AbsoluteA, ABS(b) AS AbsoluteB
FROM YourTable
Instead of using unsupported and problematic outline just use
Example:
HTML:
<img src="http://cdn3.thumbs.common.smcloud.net/common/8/6/s/863444wpPN.jpg/r-0,500-n-863444wpPN.jpg" alt="malkovich" />
CSS:
img {
padding: 1px;
background: yellow;
border:1px solid black;
}
TEST(JSFiddle):
img {_x000D_
padding: 1px;_x000D_
background: yellow;_x000D_
border: 1px solid black;_x000D_
}
_x000D_
<img src="http://cdn3.thumbs.common.smcloud.net/common/8/6/s/863444wpPN.jpg/r-0,500-n-863444wpPN.jpg" alt="malkovich" />
_x000D_
It worked using PSCP. Instructions:
set PATH=<path to the pscp.exe file>
pscp
use the following command to copy file form remote server to the local system
pscp [options] [user@]host:source target
So to copy the file /etc/hosts
from the server example.com
as user fred
to the file
c:\temp\example-hosts.txt
, you would type:
pscp [email protected]:/etc/hosts c:\temp\example-hosts.txt
My tomcat7 implementation is accepting strings as ISO-8859-1; despite the content-type of the HTTP request. The following solution worked for me when trying to correctly interpret characters like 'é' .
byte[] b1 = szP1.getBytes("ISO-8859-1");
System.out.println(b1.toString());
String szUT8 = new String(b1, "UTF-8");
System.out.println(szUT8);
When trying to interpret the string as US-ASCII, the byte info wasn't correctly interpreted.
b1 = szP1.getBytes("US-ASCII");
System.out.println(b1.toString());
You can use Object.assign()
to merge them into a new object:
const response = {_x000D_
lat: -51.3303,_x000D_
lng: 0.39440_x000D_
}_x000D_
_x000D_
const item = {_x000D_
id: 'qwenhee-9763ae-lenfya',_x000D_
address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
}_x000D_
_x000D_
const newItem = Object.assign({}, item, { location: response });_x000D_
_x000D_
console.log(newItem );
_x000D_
You can also use object spread, which is a Stage 4 proposal for ECMAScript:
const response = {_x000D_
lat: -51.3303,_x000D_
lng: 0.39440_x000D_
}_x000D_
_x000D_
const item = {_x000D_
id: 'qwenhee-9763ae-lenfya',_x000D_
address: '14-22 Elder St, London, E1 6BT, UK'_x000D_
}_x000D_
_x000D_
const newItem = { ...item, location: response }; // or { ...response } if you want to clone response as well_x000D_
_x000D_
console.log(newItem );
_x000D_
Mozilla recently released the awesome L20n or localization 2.0. In their own words L20n is
an open source, localization-specific scripting language used to process gender, plurals, conjugations, and most of the other quirky elements of natural language.
Their js implementation is on the github L20n repository.
A todo list example which loops over object by ng-repeat
:
var app = angular.module('toDolistApp', []);_x000D_
app.controller('toDoListCntrl', function() {_x000D_
var self = this;_x000D_
self.toDoListItems = {};// []; //dont use square brackets if keys are string rather than numbers._x000D_
self.doListCounter = 0;_x000D_
_x000D_
self.addToDoList = function() { _x000D_
var newToDoItem = {};_x000D_
newToDoItem.title = self.toDoEntry;_x000D_
newToDoItem.completed = false; _x000D_
_x000D_
var keyIs = "key_" + self.doListCounter++; _x000D_
_x000D_
self.toDoListItems[keyIs] = newToDoItem; _x000D_
self.toDoEntry = ""; //after adding the item make the input box blank._x000D_
};_x000D_
});_x000D_
_x000D_
app.filter('propsCounter', function() {_x000D_
return function(input) {_x000D_
return Object.keys(input).length;_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<body ng-app="toDolistApp"> _x000D_
<div ng-controller="toDoListCntrl as toDoListCntrlAs">_x000D_
Total Items: {{toDoListCntrlAs.toDoListItems | propsCounter}}<br />_x000D_
Enter todo Item: <input type="text" ng-model="toDoListCntrlAs.toDoEntry"/>_x000D_
<span>{{toDoListCntrlAs.toDoEntry}}</span>_x000D_
<button ng-click="toDoListCntrlAs.addToDoList()">Add Item</button> <br/>_x000D_
<div ng-repeat="(key, prop) in toDoListCntrlAs.toDoListItems"> _x000D_
<span>{{$index+1}} : {{key}} : Title = {{ prop.title}} : Status = {{ prop.completed}} </span>_x000D_
</div> _x000D_
</div> _x000D_
</body>
_x000D_
This article here nicely explains it. Essentially, you can look at it as such:
CREATE TABLE t AS
SELECT 'a' v FROM dual UNION ALL
SELECT 'a' FROM dual UNION ALL
SELECT 'a' FROM dual UNION ALL
SELECT 'b' FROM dual UNION ALL
SELECT 'c' FROM dual UNION ALL
SELECT 'c' FROM dual UNION ALL
SELECT 'd' FROM dual UNION ALL
SELECT 'e' FROM dual;
SELECT
v,
ROW_NUMBER() OVER (ORDER BY v) row_number,
RANK() OVER (ORDER BY v) rank,
DENSE_RANK() OVER (ORDER BY v) dense_rank
FROM t
ORDER BY v;
The above will yield:
+---+------------+------+------------+
| V | ROW_NUMBER | RANK | DENSE_RANK |
+---+------------+------+------------+
| a | 1 | 1 | 1 |
| a | 2 | 1 | 1 |
| a | 3 | 1 | 1 |
| b | 4 | 4 | 2 |
| c | 5 | 5 | 3 |
| c | 6 | 5 | 3 |
| d | 7 | 7 | 4 |
| e | 8 | 8 | 5 |
+---+------------+------+------------+
In words
ROW_NUMBER()
attributes a unique value to each rowRANK()
attributes the same row number to the same value, leaving "holes"DENSE_RANK()
attributes the same row number to the same value, leaving no "holes"try
<div style="width:100%;">
<div style="width:50px; float: left;"><img src="myleftimage" /></div>
<div style="width:50px; float: right;"><img src="myrightimage" /></div>
<div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
</div>
or
<div style="width:100%; border:2px solid #dadada;">
<div style="width:50px; float: left;"><img src="myleftimage" /></div>
<div style="width:50px; float: right;"><img src="myrightimage" /></div>
<div style="display:block; margin-left:auto; margin-right: auto;">Content Goes Here</div>
<div style="clear:both"></div>
</div>
Put the date in single quotes and move the parenthesis (after the 'yes'
) to the end:
INSERT INTO custorder
VALUES ('Kevin', 'yes' , STR_TO_DATE('1-01-2012', '%d-%m-%Y') ) ;
^ ^
---parenthesis removed--| and added here ------|
But you can always use dates without STR_TO_DATE()
function, just use the (Y-m-d) '20120101'
or '2012-01-01'
format. Check the MySQL docs: Date and Time Literals
INSERT INTO custorder
VALUES ('Kevin', 'yes', '2012-01-01') ;
Some people may not like it, but this is what I do:
private void StartBackgroundWork() {
if (Application.RenderWithVisualStyles)
progressBar.Style = ProgressBarStyle.Marquee;
else {
progressBar.Style = ProgressBarStyle.Continuous;
progressBar.Maximum = 100;
progressBar.Value = 0;
timer.Enabled = true;
}
backgroundWorker.RunWorkerAsync();
}
private void timer_Tick(object sender, EventArgs e) {
if (progressBar.Value < progressBar.Maximum)
progressBar.Increment(5);
else
progressBar.Value = progressBar.Minimum;
}
The Marquee style requires VisualStyles to be enabled, but it continuously scrolls on its own without needing to be updated. I use that for database operations that don't report their progress.
This should work:
count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, NULL))
count()
only check if the value exists or not. 0 is equivalent to an existent value, so it counts one more, while NULL is like a non-existent value, so is not counted.
You can combine your counts like you were doing before, but then you could sum them all up a number of ways, one of which is shown below:
SELECT SUM(A)
FROM
(
SELECT 1 AS A
UNION ALL
SELECT 1 AS A
UNION ALL
SELECT 1 AS A
UNION ALL
SELECT 1 AS A
) AS B
You can use IIF
(I think from SQL Server 2012)
SELECT IIF(B.[STAT] IS NULL, C.[EVENT DATE]+10, '-') AS [DATE]
While this question is rather old, and has been answered, I thought I'd take the time to offer a couple of options that are, as yet, not addressed in other answers.
Given the corrected HTML (camelCasing the id
attribute-value) of:
<label year="2010" month="6" id="currentMonth"> June 2010</label>
You could use regular expressions to extract the month-name, and year:
// gets the eleent with an id equal to 'currentMonth',
// retrieves its text-content,
// uses String.prototype.trim() to remove leading and trailing white-space:
var labelText = $('#currentMonth').text().trim(),
// finds the sequence of one, or more, letters (a-z, inclusive)
// at the start (^) of the string, and retrieves the first match from
// the array returned by the match() method:
month = labelText.match(/^[a-z]+/i)[0],
// finds the sequence of numbers (\d) of length 2-4 ({2,4}) characters,
// at the end ($) of the string:
year = labelText.match(/\d{2,4}$/)[0];
var labelText = $('#currentMonth').text().trim(),_x000D_
month = labelText.match(/^[a-z]+/i)[0],_x000D_
year = labelText.match(/\d{2,4}$/)[0];_x000D_
_x000D_
console.log(month, year);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label year="2010" month="6" id="currentMonth"> June 2010</label>
_x000D_
Rather than regular expressions, though, you could instead use custom data-*
attributes (which work in HTML 4.x, despite being invalid under the doctype, but are valid under HTML 5):
var label = $('#currentMonth'),_x000D_
month = label.data('month'),_x000D_
year = label.data('year');_x000D_
_x000D_
console.log(month, year);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label data-year="2010" data-month="6" id="currentMonth"> June 2010</label>
_x000D_
Note that this will output 6
(for the data-month
), rather than 'June'
as in the previous example, though if you use an array to tie numbers to month-names, that can be solved easily:
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],_x000D_
label = $('#currentMonth'),_x000D_
month = monthNames[+label.data('month') - 1],_x000D_
year = label.data('year');_x000D_
_x000D_
console.log(month, year);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label data-year="2010" data-month="6" id="currentMonth"> June 2010</label>
_x000D_
Similarly, the above could be easily transcribed to the native DOM (in compliant browsers):
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],_x000D_
label = document.getElementById('currentMonth'),_x000D_
month = monthNames[+label.dataset.month - 1],_x000D_
year = label.dataset.year;_x000D_
_x000D_
console.log(month, year);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label data-year="2010" data-month="6" id="currentMonth"> June 2010</label>
_x000D_
References:
I think this is a feature currently missing right now.
I noticed when I was making a guide for the keyboard shortcut differences between it and Sublime.
It's a new editor though, I wouldn't be surprised if they added it back in a new version.
Here is the code from Mohsen's answer in C# if anyone else wants it. Note: Color
is a custom class and Vector4
is from OpenTK. Both are easy to replace with something else of your choosing.
/// <summary>
/// Converts an HSL color value to RGB.
/// Input: Vector4 ( X: [0.0, 1.0], Y: [0.0, 1.0], Z: [0.0, 1.0], W: [0.0, 1.0] )
/// Output: Color ( R: [0, 255], G: [0, 255], B: [0, 255], A: [0, 255] )
/// </summary>
/// <param name="hsl">Vector4 defining X = h, Y = s, Z = l, W = a. Ranges [0, 1.0]</param>
/// <returns>RGBA Color. Ranges [0, 255]</returns>
public static Color HslToRgba(Vector4 hsl)
{
float r, g, b;
if (hsl.Y == 0.0f)
r = g = b = hsl.Z;
else
{
var q = hsl.Z < 0.5f ? hsl.Z * (1.0f + hsl.Y) : hsl.Z + hsl.Y - hsl.Z * hsl.Y;
var p = 2.0f * hsl.Z - q;
r = HueToRgb(p, q, hsl.X + 1.0f / 3.0f);
g = HueToRgb(p, q, hsl.X);
b = HueToRgb(p, q, hsl.X - 1.0f / 3.0f);
}
return new Color((int)(r * 255), (int)(g * 255), (int)(b * 255), (int)(hsl.W * 255));
}
// Helper for HslToRgba
private static float HueToRgb(float p, float q, float t)
{
if (t < 0.0f) t += 1.0f;
if (t > 1.0f) t -= 1.0f;
if (t < 1.0f / 6.0f) return p + (q - p) * 6.0f * t;
if (t < 1.0f / 2.0f) return q;
if (t < 2.0f / 3.0f) return p + (q - p) * (2.0f / 3.0f - t) * 6.0f;
return p;
}
/// <summary>
/// Converts an RGB color value to HSL.
/// Input: Color ( R: [0, 255], G: [0, 255], B: [0, 255], A: [0, 255] )
/// Output: Vector4 ( X: [0.0, 1.0], Y: [0.0, 1.0], Z: [0.0, 1.0], W: [0.0, 1.0] )
/// </summary>
/// <param name="rgba"></param>
/// <returns></returns>
public static Vector4 RgbaToHsl(Color rgba)
{
float r = rgba.R / 255.0f;
float g = rgba.G / 255.0f;
float b = rgba.B / 255.0f;
float max = (r > g && r > b) ? r : (g > b) ? g : b;
float min = (r < g && r < b) ? r : (g < b) ? g : b;
float h, s, l;
h = s = l = (max + min) / 2.0f;
if (max == min)
h = s = 0.0f;
else
{
float d = max - min;
s = (l > 0.5f) ? d / (2.0f - max - min) : d / (max + min);
if (r > g && r > b)
h = (g - b) / d + (g < b ? 6.0f : 0.0f);
else if (g > b)
h = (b - r) / d + 2.0f;
else
h = (r - g) / d + 4.0f;
h /= 6.0f;
}
return new Vector4(h, s, l, rgba.A / 255.0f);
}
If you need a drive letter (some applications don't like UNC style paths that start with a machine-name) you can "map a drive" to a UNC path. Right-click on "My Computer" and select Map Network Drive... or use this command line:
NET USE z: \server\c$\folder1\folder2
NET USE y: \server\d$
Note that you can map drive-to-drive or drill down and map to sub-folder.
If you built Python from source, this is just a matter of dependencies: since you miss OpenSSL lib installed, python silently fails installing the _ssl module. You can see it in the final report of the make command:
Python build finished, but the necessary bits to build these modules were not found:
_bsddb _sqlite3 _ssl
_tkinter bsddb185 dbm
dl gdbm imageop
sunaudiodev
To find the necessary bits, look in setup.py in detect_modules() for the module's name.
Installing OpenSSL lib in any of the standard lib paths (/usr/lib
, /usr/local/lib
...) should do the trick. Anyway this is how I did :-)
In my case, I already had a period(.)
and also a comma(,)
, so what worked for me was to replace
the comma(,)
with an empty string like below:
parseFloat('3,000.78'.replace(',', ''))
This is assuming that the amount from the existing database is 3,000.78. The results are: 3000.78
without the initial comma(,)
.
Yes, with features of C99 you may do this. This works without defining new data structures or so and without the function having to decide at runtime how it was called, and without any computational overhead.
For a detailed explanation see my post at
http://gustedt.wordpress.com/2010/06/03/default-arguments-for-c99/
Jens
A successful ping on your local network can be trapped using ERRORLEVEL
.
@ECHO OFF
PING 10.0.0.123
IF ERRORLEVEL 1 GOTO NOT-THERE
ECHO IP ADDRESS EXISTS
PAUSE
EXIT
:NOT-THERE
ECHO IP ADDRESS NOT NOT EXIST
PAUSE
EXIT
Use the Microsoft.VisualBasic.FileIO.TextFieldParser
class. This will handle parsing a delimited file, TextReader
or Stream
where some fields are enclosed in quotes and some are not.
For example:
using Microsoft.VisualBasic.FileIO;
string csv = "2,1016,7/31/2008 14:22,Geoff Dalgas,6/5/2011 22:21,http://stackoverflow.com,\"Corvallis, OR\",7679,351,81,b437f461b3fd27387c5d8ab47a293d35,34";
TextFieldParser parser = new TextFieldParser(new StringReader(csv));
// You can also read from a file
// TextFieldParser parser = new TextFieldParser("mycsvfile.csv");
parser.HasFieldsEnclosedInQuotes = true;
parser.SetDelimiters(",");
string[] fields;
while (!parser.EndOfData)
{
fields = parser.ReadFields();
foreach (string field in fields)
{
Console.WriteLine(field);
}
}
parser.Close();
This should result in the following output:
2 1016 7/31/2008 14:22 Geoff Dalgas 6/5/2011 22:21 http://stackoverflow.com Corvallis, OR 7679 351 81 b437f461b3fd27387c5d8ab47a293d35 34
See Microsoft.VisualBasic.FileIO.TextFieldParser for more information.
You need to add a reference to Microsoft.VisualBasic
in the Add References .NET tab.
I had one long table td cell, this forced the table to the edges of the browser and looked ugly. I just wanted that column to be fixed size only and break the words when it reaches the specified width. So this worked well for me:
<td><div style='width: 150px;'>Text to break here</div></td>
You don't need to specify any kind of style to table, tr elements. You may also use overflow:hidden; as suggested by other answers but it causes for the excess text to disappear.
Git requires a commit to have a comment, otherwise it wont accept the commit.
You can configure a default template with git as your default commit message or can look up the --allow-empty-message flag in git. I think (not 100% sure) you can reconfigure git to accept empty commit messages (which isn´t such a good idea). Normally each commit should be a bit of work which is described by your message.
To exclude all type of stop-words including nltk stop-words, you could do something like this:
from stop_words import get_stop_words
from nltk.corpus import stopwords
stop_words = list(get_stop_words('en')) #About 900 stopwords
nltk_words = list(stopwords.words('english')) #About 150 stopwords
stop_words.extend(nltk_words)
output = [w for w in word_list if not w in stop_words]
text-align: center will only work for horizontal centering. For it to be in the complete center, vertical and horizontal you can do the following :
div
{
position: relative;
}
div img
{
position: absolute;
top: 50%;
left: 50%;
margin-left: [-50% of your image's width];
margin-top: [-50% of your image's height];
}
You can use datetime's strftime function to get this. The problem is that time's strftime accepts a timetuple that does not carry microsecond information.
from datetime import datetime
datetime.now().strftime("%H:%M:%S.%f")
Should do the trick!
Try using for Clean XSS
xss_clean($data): "><script>alert(String.fromCharCode(74,111,104,116,111,32,82,111,98,98,105,101))</script>
Try the following :
Make sure you add M2_HOME
variable to your environment variables. It looks like you might have set M2_HOME
temporarily in a cmd
window and not as a permanent environment variable. Also append M2_HOME
to the PATH
variable.
Go to the m2
folder in your user directory.
Example: On Windows, for user bot
, the .m2
directory will be under C:\Users\bot
. Look for the settings.xml
file in this directory and look for the repository url within this file. See if you are able to hit this url from your browser. If not, you probably need to point to a different maven repository or use a proxy.
If you are able to hit the repository url from the browser, then check if the repository contains the maven-resource-plugin
version 2.6. This can be found by navigating to org.apache.maven.plugins
folder in the browser. It's possible that your pom
has hard-coded the dependency of the plugin to 2.6 but it is not available in the repository. This can be fixed by changing the depndency version to the one available in the repository.
For me none of the simple solutions above worked, however by changing only the hover I was able to get it to work:
:hover {
color: inherit;
text-decoration: none;
}
cuDNN causes my problem. PATH variable doesn't work for me. I have to copy the files in my cuDNN folders into respectful CUDA 8.0 folder structure.
If you don't have anything overflowing horizontally, you can also just use
overflow: auto;
and it will only show scrollbars when needed.
import re
s = '''
text1
text2
http://url.com/bla1/blah1/
text3
text4
http://url.com/bla2/blah2/
text5
text6
http://url.com/bla3/blah3/'''
g = re.findall(r'(text\d+)',s)
print ('list',g)
for i in g:
print (i)
Out
list ['text1', 'text2', 'text3', 'text4', 'text5', 'text6']
text1
text2
text3
text4
text5
text6 ?
If you are only interested in the domain name and want to ignore the subdomain then you need to parse it out of host
and hostname
.
The following code does this:
var firstDot = window.location.hostname.indexOf('.');
var tld = ".net";
var isSubdomain = firstDot < window.location.hostname.indexOf(tld);
var domain;
if (isSubdomain) {
domain = window.location.hostname.substring(firstDot == -1 ? 0 : firstDot + 1);
}
else {
domain = window.location.hostname;
}
I had this issue as well on Windows 10. Closing all my Jupyter Notebook sessions and re-running the pip install --upgrade
commands as an administrator made the issue go away.
Your questions seems to be about deleting entire keys in a database. In this case you should try:
redis-cli
(if running on port 6379), else you will have to specify the port number also.select {Index}
)flushdb
If you want to flush keys in all databases, then you should try flushall
.
You should extend the scope of the component-scan e.g. <context:component-scan base-package="at.naviclean" />
since you placed the entities in package at.naviclean.domain;
This should help you to get rid the exeption: Not an managed type: class at.naviclean.domain.Kassa
For further debugging you could try to dump the application context (see javadoc) to explore which classes have been detected by the component-scan if some are still no recognized check their annotation (@Service, @Component etc.)
EDIT:
You also need to add the classes to your persistence.xml
<persistence-unit>
<class>at.naviclean.domain.Kassa</class>
...
</persistence-unit>
If the value contains non-numeric characters, you can convert the value to an integer as follows:
SELECT CASE WHEN <column>~E'^\\d+$' THEN CAST (<column> AS INTEGER) ELSE 0 END FROM table;
The CASE operator checks the < column>, if it matches the integer pattern, it converts the rate into an integer, otherwise it returns 0
$(element).prop('disabled', true); //true|disabled will work on all
$(element).attr('disabled', true);
element.disabled = true;
element.setAttribute('disabled', true);
All of the above are perfectly valid solutions. Choose the one that fits your needs best.
google.com is not responding to HTTP HEAD
requests, which is why you are seeing a hang for the first command.
It does respond to GET
requests, which is why the third command works.
As for the second, curl just prints the headers from a standard request.
MySQL is different from most DBMSs use of +
or ||
for concatenation. It uses the CONCAT
function:
SELECT CONCAT(first_name, " ", last_name) AS Name FROM test.student
As @eggyal pointed out in comments, you can enable string concatenation with the ||
operator in MySQL by setting the PIPES_AS_CONCAT
SQL mode.
IIRC Canvas is a raster style bitmap. it wont be zoomable because there's no stored information to zoom to.
Your best bet is to keep two copies in memory (zoomed and non) and swap them on mouse click.
I found the error because i was new to git you must check whether you have entered the correct syntax
i made a mistake and wrote
git commit
and got the same error
use
git commit -m 'some comment'
and you wont be seeing the page with
if you just want to add timeout as an additional option for the entire existing script, you can make it test for the timeout-option, and then make it call it self recursively without that option.
example.sh:
#!/bin/bash
if [ "$1" == "-t" ]; then
timeout 1m $0 $2
else
#the original script
echo $1
sleep 2m
echo YAWN...
fi
running this script without timeout:
$./example.sh -other_option # -other_option
# YAWN...
running it with a one minute timeout:
$./example.sh -t -other_option # -other_option
git pull --recurse-submodules
This will pull all the latest commits.
I am Using this
String timeStamp = new SimpleDateFormat("dd/MM/yyyy_HH:mm:ss").format(Calendar.getInstance().getTime());
System.out.println(timeStamp);
I have tried to use AjaxableResponseMixin in my project, but had ended up with the following error message:
ImproperlyConfigured: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.
That is because the CreateView will return a redirect response instead of returning a HttpResponse when you to send JSON request to the browser. So I have made some changes to the AjaxableResponseMixin
. If the request is an ajax request, it will not call the super.form_valid
method, just call the form.save()
directly.
from django.http import JsonResponse
from django import forms
from django.db import models
class AjaxableResponseMixin(object):
success_return_code = 1
error_return_code = 0
"""
Mixin to add AJAX support to a form.
Must be used with an object-based FormView (e.g. CreateView)
"""
def form_invalid(self, form):
response = super(AjaxableResponseMixin, self).form_invalid(form)
if self.request.is_ajax():
form.errors.update({'result': self.error_return_code})
return JsonResponse(form.errors, status=400)
else:
return response
def form_valid(self, form):
# We make sure to call the parent's form_valid() method because
# it might do some processing (in the case of CreateView, it will
# call form.save() for example).
if self.request.is_ajax():
self.object = form.save()
data = {
'result': self.success_return_code
}
return JsonResponse(data)
else:
response = super(AjaxableResponseMixin, self).form_valid(form)
return response
class Product(models.Model):
name = models.CharField('product name', max_length=255)
class ProductAddForm(forms.ModelForm):
'''
Product add form
'''
class Meta:
model = Product
exclude = ['id']
class PriceUnitAddView(AjaxableResponseMixin, CreateView):
'''
Product add view
'''
model = Product
form_class = ProductAddForm
No unfortunately there is not. At the raw level files do not work on a line number basis. Instead they work at a position / offset basis. The root filesystem has no concept of lines. It's a concept added by higher level components.
So there is no way to tell the operating system, please open file at line blah. Instead you have to open the file and skip around counting new lines until you've passed the specified number. Then store the next set of bytes into an array until you hit the next new line.
Or use the XmlSerializer class.
XmlSerializer xs = new XmlSerializer(objectType);
obj = xs.Deserialize(new StringReader(yourXmlString));
Deleting or corrupting the pom.xml file can cause this error.
Use boost::filesystem. It will be incorporated into the next standard anyway so you may as well get used to it.
If you aren't referencing your FK's that often and using MySQL (and InnoDB) then you can just let MySQL name the FK for you.
At a later time you can find the FK name you need by running a query.
You have empty $entry_database
variable. As you see in error: ListEmail, Title FROM WHERE ID
bewteen FROM and WHERE should be name of table. Proper syntax of SELECT:
SELECT columns FROM table [optional things as WHERE/ORDER/GROUP/JOIN etc]
which in your way should become:
SELECT ID, ListStID, ListEmail, Title FROM some_table_you_got WHERE ID = '4'
Take a look at the write.csv
or the write.table
functions. You just have to supply the file name the user selects to the file
parameter, and the dataframe to the x
parameter:
write.csv(x=df, file="myFileName")
For HTTP things, the current choice should be: Requests- HTTP for Humans
In your example, you can break the string into two pieces:
alert ( "Please Select file"
+ " to delete");
Or, when it's a string, as in your case, you can use a backslash as @Gumbo suggested:
alert ( "Please Select file\
to delete");
Note that this backslash approach is not necessarily preferred, and possibly not universally supported (I had trouble finding hard data on this). It is not in the ECMA 5.1 spec.
When working with other code (not in quotes), line breaks are ignored, and perfectly acceptable. For example:
if(SuperLongConditionWhyIsThisSoLong
&& SuperLongConditionOnAnotherLine
&& SuperLongConditionOnThirdLineSheesh)
{
// launch_missiles();
}
str = "count a character occurance"
List = list(str)
print (List)
Uniq = set(List)
print (Uniq)
for key in Uniq:
print (key, str.count(key))
If you are using a webkit browser you can change the color of the caret by following the next CSS snippet. I'm not sure if It's possible to change the format with CSS.
input,
textarea {
font-size: 24px;
padding: 10px;
color: red;
text-shadow: 0px 0px 0px #000;
-webkit-text-fill-color: transparent;
}
input::-webkit-input-placeholder,
textarea::-webkit-input-placeholder {
color:
text-shadow: none;
-webkit-text-fill-color: initial;
}
Here is an example: http://jsfiddle.net/8k1k0awb/
A @ViewScoped
bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null
or void
(and thus navigates back to the same view). Once you refresh the page, or return a non-null
string (even an empty string!) navigation outcome, then the view scope will end.
A @RequestScoped
bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.
A @ViewScoped
bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped
one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped
bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped
bean. Every view has its own unique @ViewScoped
bean.
fork()
- creates a new child process, which is a complete copy of the parent process. Child and parent processes use different virtual address spaces, which is initially populated by the same memory pages. Then, as both processes are executed, the virtual address spaces begin to differ more and more, because the operating system performs a lazy copying of memory pages that are being written by either of these two processes and assigns an independent copies of the modified pages of memory for each process. This technique is called Copy-On-Write (COW).vfork()
- creates a new child process, which is a "quick" copy of the parent process. In contrast to the system call fork()
, child and parent processes share the same virtual address space. NOTE! Using the same virtual address space, both the parent and child use the same stack, the stack pointer and the instruction pointer, as in the case of the classic fork()
! To prevent unwanted interference between parent and child, which use the same stack, execution of the parent process is frozen until the child will call either exec()
(create a new virtual address space and a transition to a different stack) or _exit()
(termination of the process execution). vfork()
is the optimization of fork()
for "fork-and-exec" model. It can be performed 4-5 times faster than the fork()
, because unlike the fork()
(even with COW kept in the mind), implementation of vfork()
system call does not include the creation of a new address space (the allocation and setting up of new page directories).clone()
- creates a new child process. Various parameters of this system call, specify which parts of the parent process must be copied into the child process and which parts will be shared between them. As a result, this system call can be used to create all kinds of execution entities, starting from threads and finishing by completely independent processes. In fact, clone()
system call is the base which is used for the implementation of pthread_create()
and all the family of the fork()
system calls.exec()
- resets all the memory of the process, loads and parses specified executable binary, sets up new stack and passes control to the entry point of the loaded executable. This system call never return control to the caller and serves for loading of a new program to the already existing process. This system call with fork()
system call together form a classical UNIX process management model called "fork-and-exec".If you don't care about the actual key, a concise way to iterate over all the Map's values would be to use its values()
method
Map<String, List<String>> myMap;
for ( List<String> stringList : myMap.values() ) {
for ( String myString : stringList ) {
// process the string here
}
}
The values()
method is part of the Map interface and returns a Collection view of the values in the map.
If you don't explicitly cast one of the two values to a float before doing the division then an integer division will be used (so that's why you get 0). You just need one of the two operands to be a floating point value, so that the normal division is used (and other integer value is automatically turned into a float).
Just try with
float completed = 50000.0f;
and it will be fine.
I've tried using flask instead of a simple apscheduler what you need to install is
pip3 install flask_apscheduler
Below is the sample of my code:
from flask import Flask
from flask_apscheduler import APScheduler
app = Flask(__name__)
scheduler = APScheduler()
def scheduleTask():
print("This test runs every 3 seconds")
if __name__ == '__main__':
scheduler.add_job(id = 'Scheduled Task', func=scheduleTask, trigger="interval", seconds=3)
scheduler.start()
app.run(host="0.0.0.0")
There are at least two ways to do it:
Use nowrap attribute inside the "td" tag:
<th nowrap="nowrap">Really long column heading</th>
Use non-breakable spaces between your words:
<th>Really long column heading</th>
just use jQuery prop
$(".radio-button").prop("disabled", false);
$(".radio-button").prop("disabled", true); // disable
The best way is to store the dates as a number, received by using the Calendar command.
//Building the table includes:
StringBuilder query=new StringBuilder();
query.append("CREATE TABLE "+TABLE_NAME+ " (");
query.append(COLUMN_ID+"int primary key autoincrement,");
query.append(COLUMN_DATETIME+" int)");
//And inserting the data includes this:
values.put(COLUMN_DATETIME, System.currentTimeMillis());
Why do this? First of all, getting values from a date range is easy. Just convert your date into milliseconds, and then query appropriately. Sorting by date is similarly easy. The calls to convert among various formats are also likewise easy, as I included. Bottom line is, with this method, you can do anything you need to do, no problems. It will be slightly difficult to read a raw value, but it more than makes up that slight disadvantage with being easily machine readable and usable. And in fact, it is relatively easy to build a reader (And I know there are some out there) that will automatically convert the time tag to date as such for easy of reading.
It's worth mentioning that the values that come out of this should be long, not int. Integer in sqlite can mean many things, anything from 1-8 bytes, but for almost all dates 64 bits, or a long, is what works.
EDIT: As has been pointed out in the comments, you have to use the cursor.getLong()
to properly get the timestamp if you do this.
Use dispatch group
dispatchGroup.enter()
FirstOperation(completion: { _ in
dispatchGroup.leave()
})
dispatchGroup.enter()
SecondOperation(completion: { _ in
dispatchGroup.leave()
})
dispatchGroup.wait() // Waits here on this thread until the two operations complete executing.
I had the same problem and tried most of the solutions suggested above, but none worked for me. Eventually, I rebuild my entire com.springframework (maven) repository (by simply deleting .m2/org/springworkframework directory).
It worked for me.
Hit F6
Insert::
npp_open $(PLUGINS_CONFIG_DIR)\..\..\shortcuts.xml
Click OK
You now have the file opened in your editor.
Before altering things checkout the related docs:
OK!
The code below is written using ES6 syntaxes but could just as easily be written in ES5 or even less. ES6 is not a requirement to create a "mechanism to loop x times"
If you don't need the iterator in the callback, this is the most simple implementation
const times = x => f => {_x000D_
if (x > 0) {_x000D_
f()_x000D_
times (x - 1) (f)_x000D_
}_x000D_
}_x000D_
_x000D_
// use it_x000D_
times (3) (() => console.log('hi'))_x000D_
_x000D_
// or define intermediate functions for reuse_x000D_
let twice = times (2)_x000D_
_x000D_
// twice the power !_x000D_
twice (() => console.log('double vision'))
_x000D_
If you do need the iterator, you can use a named inner function with a counter parameter to iterate for you
const times = n => f => {_x000D_
let iter = i => {_x000D_
if (i === n) return_x000D_
f (i)_x000D_
iter (i + 1)_x000D_
}_x000D_
return iter (0)_x000D_
}_x000D_
_x000D_
times (3) (i => console.log(i, 'hi'))
_x000D_
Stop reading here if you don't like learning more things ...
But something should feel off about those...
if
statements are ugly — what happens on the other branch ?undefined
— indication of impure, side-effecting function"Isn't there a better way ?"
There is. Let's first revisit our initial implementation
// times :: Int -> (void -> void) -> void
const times = x => f => {
if (x > 0) {
f() // has to be side-effecting function
times (x - 1) (f)
}
}
Sure, it's simple, but notice how we just call f()
and don't do anything with it. This really limits the type of function we can repeat multiple times. Even if we have the iterator available, f(i)
isn't much more versatile.
What if we start with a better kind of function repetition procedure ? Maybe something that makes better use of input and output.
Generic function repetition
// repeat :: forall a. Int -> (a -> a) -> a -> a_x000D_
const repeat = n => f => x => {_x000D_
if (n > 0)_x000D_
return repeat (n - 1) (f) (f (x))_x000D_
else_x000D_
return x_x000D_
}_x000D_
_x000D_
// power :: Int -> Int -> Int_x000D_
const power = base => exp => {_x000D_
// repeat <exp> times, <base> * <x>, starting with 1_x000D_
return repeat (exp) (x => base * x) (1)_x000D_
}_x000D_
_x000D_
console.log(power (2) (8))_x000D_
// => 256
_x000D_
Above, we defined a generic repeat
function which takes an additional input which is used to start the repeated application of a single function.
// repeat 3 times, the function f, starting with x ...
var result = repeat (3) (f) (x)
// is the same as ...
var result = f(f(f(x)))
Implementing times
with repeat
Well this is easy now; almost all of the work is already done.
// repeat :: forall a. Int -> (a -> a) -> a -> a_x000D_
const repeat = n => f => x => {_x000D_
if (n > 0)_x000D_
return repeat (n - 1) (f) (f (x))_x000D_
else_x000D_
return x_x000D_
}_x000D_
_x000D_
// times :: Int -> (Int -> Int) -> Int _x000D_
const times = n=> f=>_x000D_
repeat (n) (i => (f(i), i + 1)) (0)_x000D_
_x000D_
// use it_x000D_
times (3) (i => console.log(i, 'hi'))
_x000D_
Since our function takes i
as an input and returns i + 1
, this effectively works as our iterator which we pass to f
each time.
We've fixed our bullet list of issues too
if
statementsundefined
JavaScript comma operator, the
In case you're having trouble seeing how the last example is working, it depends on your awareness of one of JavaScript's oldest battle axes; the comma operator – in short, it evaluates expressions from left to right and returns the value of the last evaluated expression
(expr1 :: a, expr2 :: b, expr3 :: c) :: c
In our above example, I'm using
(i => (f(i), i + 1))
which is just a succinct way of writing
(i => { f(i); return i + 1 })
Tail Call Optimisation
As sexy as the recursive implementations are, at this point it would be irresponsible for me to recommend them given that no JavaScript VM I can think of supports proper tail call elimination – babel used to transpile it, but it's been in "broken; will reimplement" status for well over a year.
repeat (1e6) (someFunc) (x)
// => RangeError: Maximum call stack size exceeded
As such, we should revisit our implementation of repeat
to make it stack-safe.
The code below does use mutable variables n
and x
but note that all mutations are localized to the repeat
function – no state changes (mutations) are visible from outside of the function
// repeat :: Int -> (a -> a) -> (a -> a)_x000D_
const repeat = n => f => x =>_x000D_
{_x000D_
let m = 0, acc = x_x000D_
while (m < n)_x000D_
(m = m + 1, acc = f (acc))_x000D_
return acc_x000D_
}_x000D_
_x000D_
// inc :: Int -> Int_x000D_
const inc = x =>_x000D_
x + 1_x000D_
_x000D_
console.log (repeat (1e8) (inc) (0))_x000D_
// 100000000
_x000D_
This is going to have a lot of you saying "but that's not functional !" – I know, just relax. We can implement a Clojure-style loop
/recur
interface for constant-space looping using pure expressions; none of that while
stuff.
Here we abstract while
away with our loop
function – it looks for a special recur
type to keep the loop running. When a non-recur
type is encountered, the loop is finished and the result of the computation is returned
const recur = (...args) =>_x000D_
({ type: recur, args })_x000D_
_x000D_
const loop = f =>_x000D_
{_x000D_
let acc = f ()_x000D_
while (acc.type === recur)_x000D_
acc = f (...acc.args)_x000D_
return acc_x000D_
}_x000D_
_x000D_
const repeat = $n => f => x =>_x000D_
loop ((n = $n, acc = x) =>_x000D_
n === 0_x000D_
? acc_x000D_
: recur (n - 1, f (acc)))_x000D_
_x000D_
const inc = x =>_x000D_
x + 1_x000D_
_x000D_
const fibonacci = $n =>_x000D_
loop ((n = $n, a = 0, b = 1) =>_x000D_
n === 0_x000D_
? a_x000D_
: recur (n - 1, b, a + b))_x000D_
_x000D_
console.log (repeat (1e7) (inc) (0)) // 10000000_x000D_
console.log (fibonacci (100)) // 354224848179262000000
_x000D_
create java file with below code
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildLayoutPosition(childView));
return true;
}
return false;
}
@Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
and just use the listener on your RecyclerView object.
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {
@Override public void onItemClick(View view, int position) {
// TODO Handle item click
}
}));
The problem here is that the "on" is applied to all elements that exists AT THE TIME. When you create an element dynamically, you need to run the on again:
$('form').on('submit',doFormStuff);
createNewForm();
// re-attach to all forms
$('form').off('submit').on('submit',doFormStuff);
Since forms usually have names or IDs, you can just attach to the new form as well. If I'm creating a lot of dynamic stuff, I'll include a setup or bind function:
function bindItems(){
$('form').off('submit').on('submit',doFormStuff);
$('button').off('click').on('click',doButtonStuff);
}
So then whenever you create something (buttons usually in my case), I just call bindItems to update everything on the page.
createNewButton();
bindItems();
I don't like using 'body' or document elements because with tabs and modals they tend to hang around and do things you don't expect. I always try to be as specific as possible unless its a simple 1 page project.
You can also use equals:
Integer a = 0;
if (a.equals(0)) {
// a == 0
}
which is equivalent to:
if (a.intValue() == 0) {
// a == 0
}
and also:
if (a == 0) {
}
(the Java compiler automatically adds intValue())
Note that autoboxing/autounboxing can introduce a significant overhead (especially inside loops).
add this css
body.disable-scroll {
overflow: hidden;
}
and when to disable run this code
$("body").addClass("disable-scroll");
and when to enabled run this code
$("body").removeClass("disable-scroll")
Expires
and Cache-Control
are "strong caching headers"
Last-Modified
and ETag
are "weak caching headers"
First the browser check Expires/Cache-Control
to determine whether or not to make a request to the server
If have to make a request, it will send Last-Modified/ETag
in the HTTP request. If the Etag
value of the document matches that, the server will send a 304 code instead of 200, and no content. The browser will load the contents from its cache.
Bill's answer is very good, but you may want to do some things with the request like compression or user-agents. The following code shows how you can various types of compression to your requests.
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Cast shouldn't fail
HttpURLConnection.setFollowRedirects(true);
// allow both GZip and Deflate (ZLib) encodings
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
String encoding = conn.getContentEncoding();
InputStream inStr = null;
// create the appropriate stream wrapper based on
// the encoding type
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
inStr = new GZIPInputStream(conn.getInputStream());
} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
inStr = new InflaterInputStream(conn.getInputStream(),
new Inflater(true));
} else {
inStr = conn.getInputStream();
}
To also set the user-agent add the following code:
conn.setRequestProperty ( "User-agent", "my agent name");
Somewhat related - I was looking for a solution to do the same for directories.
Unfortunately the -j
option does not work for this :(
Here is a good solution on how to get it done: https://superuser.com/questions/119649/avoid-unwanted-path-in-zip-file
The move
instruction copies a value from one register to another. The li
instruction loads a specific numeric value into that register.
For the specific case of zero, you can use either the constant zero or the zero register to get that:
move $s0, $zero
li $s0, 0
There's no register that generates a value other than zero, though, so you'd have to use li
if you wanted some other number, like:
li $s0, 12345678
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(urls[0])
.build();
Response responses = null;
try {
responses = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
String jsonData = responses.body().string();
JSONObject Jobject = new JSONObject(jsonData);
JSONArray Jarray = Jobject.getJSONArray("employees");
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
}
}
Example add to your columns:
JCol employees = new employees();
colums.Setid(object.getInt("firstName"));
columnlist.add(lastName);
def get_code(str)
str.sub(/^(Z_.*): .*/, '\1')
end
get_code('Z_foo: bar!') # => "Z_foo"
Instead of just doing an import ...
, do this :
from <MySubFolder> import <MyFile>
MyFile is inside the MySubFolder.
The most correct way to perform a case sensitive string comparison without changing the collation of the column being queried is to explicitly specify a character set and collation for the value that the column is being compared to.
select * from `table` where `column` = convert('value' using utf8mb4) collate utf8mb4_bin;
binary
?Using the binary
operator is inadvisable because it compares the actual bytes of the encoded strings. If you compare the actual bytes of two strings encoded using the different character sets two strings that should be considered the same they may not be equal. For example if you have a column that uses the latin1
character set, and your server/session character set is utf8mb4
, then when you compare the column with a string containing an accent such as 'café' it will not match rows containing that same string! This is because in latin1
é is encoded as the byte 0xE9
but in utf8
it is two bytes: 0xC3A9
.
convert
as well as collate
?Collations must match the character set. So if your server or session is set to use the latin1
character set you must use collate latin1_bin
but if your character set is utf8mb4
you must use collate utf8mb4_bin
. Therefore the most robust solution is to always convert the value into the most flexible character set, and use the binary collation for that character set.
convert
and collate
to the value and not the column?When you apply any transforming function to a column before making a comparison it prevents the query engine from using an index if one exists for the column, which could dramatically slow down your query. Therefore it is always better to transform the value instead where possible. When a comparison is performed between two string values and one of them has an explicitly specified collation, the query engine will use the explicit collation, regardless of which value it is applied to.
It is important to note that MySql is not only case insensitive for columns using an _ci
collation (which is typically the default), but also accent insensitive. This means that 'é' = 'e'
. Using a binary collation (or the binary
operator) will make string comparisons accent sensitive as well as case sensitive.
utf8mb4
?The utf8
character set in MySql is an alias for utf8mb3
which has been deprecated in recent versions because it does not support 4 byte characters (which is important for encoding strings like ). If you wish to use the UTF8 character encoding with MySql then you should be using the utf8mb4
charset.
The Ubuntu package docker
actually refers to a GUI application, not the beloved DevOps tool we've come out to look for.
The instructions for docker can be followed per instructions on the docker page here: https://docs.docker.com/engine/install/ubuntu/
=== UPDATED (thanks @Scott Stensland) ===
You now run the following install script to get docker:
`sudo curl -sSL https://get.docker.com/ | sh`
This will run a script that installs docker. Note the last part of the script:
If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:
`sudo usermod -aG docker stens`
Remember that you will have to log out and back in for this to take effect!
To update Docker run:
`sudo apt-get update && sudo apt-get upgrade`
For more details on what's going on, See the docker install documentation or @Scott Stensland's answer below
.
=== UPDATE: For those uncomfortable w/ sudo | sh ===
Some in the comments have mentioned that it a risk to run an arbitrary script as sudo. The above option is a convenience script from docker to make the task simple. However, for those that are security-focused but don't want to read the script you can do the following:
sudo apt-get update; \
sudo apt-get install \
apt-transport-https \
ca-certificates \
curl \
gnupg-agent \
software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
(Security check, verify key fingerprint 9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88
$ sudo apt-key fingerprint 0EBFCD88
pub rsa4096 2017-02-22 [SCEA]
9DC8 5822 9FC7 DD38 854A E2D8 8D81 803C 0EBF CD88
uid [ unknown] Docker Release (CE deb) <[email protected]>
sub rsa4096 2017-02-22 [S]
)
sudo add-apt-repository \
"deb [arch=amd64] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) \
stable"
sudo apt-get update; \
sudo apt-get install docker-ce docker-ce-cli containerd.io
If you want to verify that it worked run:
sudo docker run hello-world
The following explains why it is named like this: Why install docker on ubuntu should be `sudo apt-get install docker.io`?
to check input and get confirm by check box ,use this script...
$(document).on("change", ".inputClass", function () {
if($(this).is(':checked')){
confirm_message = $(this).data('confirm');
var confirm_status = confirm(confirm_message);
if (confirm_status == true) {
//doing somethings...
}
}});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label> check action </lable>
<input class="inputClass" type="checkbox" data-confirm="are u sure to do ...?" >
_x000D_
If you want to find the last populated cell in a particular column, the best method is:
Range("A" & Rows.Count).End(xlUp).Row
This code uses the very last cell in the entire column (65536 for Excel 2003, 1048576 in later versions), and then find the first populated cell above it. This has the ability to ignore "breaks" in your data and find the true last row.
This is short, fast, safe, and usable...
public static List<string> ToExcelsSheetList(string excelFilePath)
{
List<string> sheets = new List<string>();
using (OleDbConnection connection =
new OleDbConnection((excelFilePath.TrimEnd().ToLower().EndsWith("x"))
? "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + excelFilePath + "';" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'"
: "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + excelFilePath + "';Extended Properties=Excel 8.0;"))
{
connection.Open();
DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow drSheet in dt.Rows)
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
string s = drSheet["TABLE_NAME"].ToString();
sheets.Add(s.StartsWith("'")?s.Substring(1, s.Length - 3): s.Substring(0, s.Length - 1));
}
connection.Close();
}
return sheets;
}
Many CAs will provide a cert in PKCS7 format.
According to Oracle documentation, the keytool commmand can handle PKCS#7 but sometimes it fails
The keytool command can import X.509 v1, v2, and v3 certificates, and PKCS#7 formatted certificate chains consisting of certificates of that type. The data to be imported must be provided either in binary encoding format or in printable encoding format (also known as Base64 encoding) as defined by the Internet RFC 1421 standard. In the latter case, the encoding must be bounded at the beginning by a string that starts with -----BEGIN, and bounded at the end by a string that starts with -----END.
If the PKCS7 file can't be imported try to transform it from PKCS7 to X.509:
openssl pkcs7 -print_certs -in certificate.p7b -out certificate.cer
I cracked open Reflector to have a look at this as there seems to be a bit of confusion about SortedList
. It is in fact not a binary search tree, it is a sorted (by key) array of key-value pairs. There is also a TKey[] keys
variable which is sorted in sync with the key-value pairs and used to binary search.
Here is some source (targeting .NET 4.5) to backup my claims.
Private members
// Fields
private const int _defaultCapacity = 4;
private int _size;
[NonSerialized]
private object _syncRoot;
private IComparer<TKey> comparer;
private static TKey[] emptyKeys;
private static TValue[] emptyValues;
private KeyList<TKey, TValue> keyList;
private TKey[] keys;
private const int MaxArrayLength = 0x7fefffff;
private ValueList<TKey, TValue> valueList;
private TValue[] values;
private int version;
SortedList.ctor(IDictionary, IComparer)
public SortedList(IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer) : this((dictionary != null) ? dictionary.Count : 0, comparer)
{
if (dictionary == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
dictionary.Keys.CopyTo(this.keys, 0);
dictionary.Values.CopyTo(this.values, 0);
Array.Sort<TKey, TValue>(this.keys, this.values, comparer);
this._size = dictionary.Count;
}
SortedList.Add(TKey, TValue) : void
public void Add(TKey key, TValue value)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
int num = Array.BinarySearch<TKey>(this.keys, 0, this._size, key, this.comparer);
if (num >= 0)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
}
this.Insert(~num, key, value);
}
SortedList.RemoveAt(int) : void
public void RemoveAt(int index)
{
if ((index < 0) || (index >= this._size))
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
}
this._size--;
if (index < this._size)
{
Array.Copy(this.keys, index + 1, this.keys, index, this._size - index);
Array.Copy(this.values, index + 1, this.values, index, this._size - index);
}
this.keys[this._size] = default(TKey);
this.values[this._size] = default(TValue);
this.version++;
}
In my case I had special instruction into nginx configuration file:
location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
try_files $uri =404;
}
All clients have received '404' because nginx nothing known about Flask.
I hope it help someone.
I use ImageProcessorCore, mostly because it works .Net Core.
And it have more option such as converting types, cropping images and more
Here is another use case which worked well for me.
Code: Swift 5.3
// Assuming you have a view named "targeView"
scrollView.scroll(to: CGPoint(x:targeView.frame.minX, y:targeView.frame.minY), animated: true)
As you can guess if you want to scroll to make a bottom part of your target view visible then use maxX and minY.
For someone who is new to IPC and Named Pipes, I found the following NuGet package to be a great help.
GitHub: Named Pipe Wrapper for .NET 4.0
To use first install the package:
PS> Install-Package NamedPipeWrapper
Then an example server (copied from the link):
var server = new NamedPipeServer<SomeClass>("MyServerPipe");
server.ClientConnected += delegate(NamedPipeConnection<SomeClass> conn)
{
Console.WriteLine("Client {0} is now connected!", conn.Id);
conn.PushMessage(new SomeClass { Text: "Welcome!" });
};
server.ClientMessage += delegate(NamedPipeConnection<SomeClass> conn, SomeClass message)
{
Console.WriteLine("Client {0} says: {1}", conn.Id, message.Text);
};
server.Start();
Example client:
var client = new NamedPipeClient<SomeClass>("MyServerPipe");
client.ServerMessage += delegate(NamedPipeConnection<SomeClass> conn, SomeClass message)
{
Console.WriteLine("Server says: {0}", message.Text);
};
client.Start();
Best thing about it for me is that unlike the accepted answer here it supports multiple clients talking to a single server.
As I'm going back to this question every now and then and because this question is old, I'm posting a benchmark for the most voted answers.
Note, that for @Ian's and @John's answers I created another version. Instead of using length(x)
, I used sum(!is.na(x))
(to avoid NAs).
I used a vector of 10^6, with 1,000 repetitions.
library(microbenchmark)
set.seed(123)
myVec <- rnorm(10^6)
IanStd <- function(x) sd(x)/sqrt(length(x))
JohnSe <- function(x) sqrt(var(x)/length(x))
IanStdisNA <- function(x) sd(x)/sqrt(sum(!is.na(x)))
JohnSeisNA <- function(x) sqrt(var(x)/sum(!is.na(x)))
AranStderr <- function(x, na.rm=FALSE) {
if (na.rm) x <- na.omit(x)
sqrt(var(x)/length(x))
}
mbm <- microbenchmark(
"plotrix" = {plotrix::std.error(myVec)},
"IanStd" = {IanStd(myVec)},
"JohnSe" = {JohnSe(myVec)},
"IanStdisNA" = {IanStdisNA(myVec)},
"JohnSeisNA" = {JohnSeisNA(myVec)},
"AranStderr" = {AranStderr(myVec)},
times = 1000)
mbm
Results:
Unit: milliseconds
expr min lq mean median uq max neval cld
plotrix 10.3033 10.89360 13.869947 11.36050 15.89165 125.8733 1000 c
IanStd 4.3132 4.41730 4.618690 4.47425 4.63185 8.4388 1000 a
JohnSe 4.3324 4.41875 4.640725 4.48330 4.64935 9.4435 1000 a
IanStdisNA 8.4976 8.99980 11.278352 9.34315 12.62075 120.8937 1000 b
JohnSeisNA 8.5138 8.96600 11.127796 9.35725 12.63630 118.4796 1000 b
AranStderr 4.3324 4.41995 4.634949 4.47440 4.62620 14.3511 1000 a
library(ggplot2)
autoplot(mbm)
http://developer.android.com/reference/android/provider/MediaStore.Audio.AudioColumns.html
Try changing the line contentResolver.query
//change it to the columns you need
String[] columns = new String[]{MediaStore.Audio.AudioColumns.DATA};
Cursor cursor = contentResolver.query(uri, columns, null, null, null);
public static final String MEDIA_CONTENT_CONTROL
Not for use by third-party applications due to privacy of media consumption
http://developer.android.com/reference/android/Manifest.permission.html#MEDIA_CONTENT_CONTROL
try to remove the <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/>
first and try again?
Clear improperly cached compile errors.
All Projects Locations in Eclipse
workspace\.metadata\.plugins\org.eclipse.core.resources\.projects\<project>\
Another way is to use the DateTime class, this way you can also specify the timezone. Note: PHP 5.3 or higher.
// For the current date
function isTodayWeekend() {
$currentDate = new DateTime("now", new DateTimeZone("Europe/Amsterdam"));
return $currentDate->format('N') >= 6;
}
If you need to be able to check a certain date string, you can use DateTime::createFromFormat
function isWeekend($date) {
$inputDate = DateTime::createFromFormat("d-m-Y", $date, new DateTimeZone("Europe/Amsterdam"));
return $inputDate->format('N') >= 6;
}
The beauty of this way is that you can specify the timezone without changing the timezone globally in PHP, which might cause side-effects in other scripts (for ex. Wordpress).
Doing it with hooks. I ran into a similar problem, but I was using react-redux with hooks. I did not want to lard up my interface code (i.e., react components) with lots of code dedicated to retrieving/sending information from/to the store. Rather, I wanted functions with generic names to retrieve and update the data. My path was to put the app's
const store = createSore(
allReducers,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
into a module named store.js
and adding export
before const
and adding the usual react-redux imports in the store.js. file. Then, I imported to index.js
at the app level, which I then imported into index.js with the usual import {store} from "./store.js"
The child components then accessed the store using the useSelector()
and useDispatch()
hooks.
To access the store in non-component front end code, I used the analogous import (i.e., import {store} from "../../store.js"
) and then used store.getState()
and store.dispatch({*action goes here*})
to handled retrieving and updating (er, sending actions to) the store.
In short, I don't have the implementation, but the explanation.
Google did not make offline speech recognition available to third party apps. Offline recognition is only accessable via the keyboard. Ben Randall (the developer of utter!) explains his workaround in an article at Android Police:
I had implemented my own keyboard and was switching between Google Voice Typing and the users default keyboard with an invisible edit text field and transparent Activity to get the input. Dirty hack!
This was the only way to do it, as offline Voice Typing could only be triggered by an IME or a system application (that was my root hack) . The other type of recognition API … didn't trigger it and just failed with a server error. … A lot of work wasted for me on the workaround! But at least I was ready for the implementation...
From Utter! Claims To Be The First Non-IME App To Utilize Offline Voice Recognition In Jelly Bean
We can select the parent tag with the help of Selenium as follows:
driver.findElement(By.xpath("//table[@id='abc']//div/nobr[.='abc']/../.."));
this will help you to find the grandparent of the known Element. Just Remove one (/..) to find the immediate Parent Element.
Like:
driver.findElement(By.xpath("//table[@id='abc']//div/nobr[.='abc']/..));
There are some other ways to implement this, but it worked fine for me.
from django.core.urlresolvers import reverse
def url_to_edit_object(obj):
url = reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.model_name), args=[obj.id] )
return u'<a href="%s">Edit %s</a>' % (url, obj.__unicode__())
This is similar to hansen_j's solution except that it uses url namespaces, admin: being the admin's default application namespace.
It tells the browser to read the css file as UTF-8. This is handy if your CSS contains unicode characters and not only ASCII.
Using it in the meta tag is fine, but only for pages that include that meta tag.
Read about the rules for character set resolution of CSS files at the w3c spec for CSS 2.
as a quick fix to this question, make sure your compile Sdk verion, your buildtoolsversion, your appcompat, and finally your support library are all running on the same sdk version, for further clarity take a look at the image i just uploaded. Cheers. Follow the red annotations and get rid of that trouble.
Also, you can use external_app_launcher: https://pub.dev/packages/external_app_launcher
To know if is installed:
await LaunchApp.isAppInstalled(androidPackageName: 'com.google.android.maps.MapView', iosUrlScheme: 'comgooglemaps://');
To open:
await LaunchApp.openApp(
androidPackageName: 'com.google.android.maps.MapView',
iosUrlScheme: 'comgooglemaps://',
);
Given command is the best possible solution I suggest.
git subtree add --prefix=MY_PROJECT git://github.com/project/my_project.git master
You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick
.
Which whitespace character? The most common is the normal space, which is between each word in my sentences. This is just " "
.
This is really just an expansion on @mjolinor simple answer [Use Task Scheduler].
I knew "Task Scheduler" was the correct way, but it took a bit of effort to get it running the way I wanted and thought I'd post my finding for others.
Issues including:
Note: You must have permission to run script see ExecutionPolicy
Then in Task Scheduler, the most important/tricky part is the Action
It should be Start a Program
Program/Script:
powershell
Add arguments (optional) :
-windowstyle hidden -command full\path\script.ps1 >> "%TEMP%\StartupLog.txt" 2>&1
Note:
If you see -File
on the internet, it will work, but understand nothing can be after -File
except the File Path, IE: The redirect is taken to be part of the file path and it fails, you must use -command
in conjunction with redirect, but you can prepend additional commands/arguments such as -windowstyle hidden
to not show PowerShell window.
I had to adjust all Write-Host
to Write-Output
in my script as well.
(n & 1) will check if 'n' is odd or even, this is similar to (n%2).
In case 'n' is odd (n & 1) will return true/1;
Else it will return back false/0;
The '>>' in (n>>=1) is a bitwise operator called "Right shift", this operator will modify the value of 'n', the formula is:
(n >>= m) => (n = n>>m) => (n = n/2^m)
Go through GeeksforGeek's article on "Bitwise Operator's", recommended!
Use CSS :
input[type=submit] {
background:url("BUTTON1.jpg");
}
For HTML :
<input type="submit" value="Login" style="background:url("BUTTON1.jpg");">
Note: if you're using(importing) org.json.simple.JSONArray
, you have to use JSONArray.size()
to get the data you want. But use JSONArray.length()
if you're using org.json.JSONArray
.
I wanted to support apps pre api 23 and instead of using checkSelfPermission
I used a try / catch
try {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
} catch (SecurityException e) {
dialogGPS(this.getContext()); // lets the user know there is a problem with the gps
}
Here's another 2020 solution, inspired by @Sandeep's. Using the MinimalSplitDateTimeMultiWidget found in this gist, in our Form as below, we can use modern browser date and time selectors (via eg 'type': 'date'). We don't need any JS.
class EditAssessmentBaseForm(forms.ModelForm):
class Meta:
model = Assessment
fields = '__all__'
begin = DateTimeField(widget=MinimalSplitDateTimeMultiWidget())
The problem here is in your explode statement
//$item['date'] presumably = 20120514. Do a print of this
$eventDate = trim($item['date']);
//This explodes on , but there is no , in $eventDate
//You also have a limit of 2 set in the below explode statement
$myarray = (explode(',', $eventDate, 2));
//$myarray is currently = to '20'
foreach ($myarray as $value) {
//Now you are iterating through a string
echo $value;
}
Try changing your initial $item['date'] to be 2012,04,30 if that's what you're trying to do. Otherwise I'm not entirely sure what you're trying to print.
You don't have that kind of control with a bare a
tag. But you can hook up the tag's onclick
handler to call window.open(...)
with the right parameters. See here for examples:
https://developer.mozilla.org/En/DOM/Window.open
I still don't think you can force window over tab directly though-- that depends on the browser and the user's settings.
Same pdo error in sql query while trying to insert into database value from multidimential array:
$sql = "UPDATE test SET field=arr[$s][a] WHERE id = $id";
$sth = $db->prepare($sql);
$sth->execute();
Extracting array arr[$s][a]
from sql query, using instead variable containing it fixes the problem.
You could use a subselect combined with a UNION. Whenever you can return the same fields for more than one condition use OR with the parenthesis as in this example:
SELECT * FROM
(SELECT val1, val2 FROM table1 WHERE (condition1 is true)
OR (condition2 is true))
UNION
SELECT * FROM
(SELECT val5, val6 FROM table7 WHERE (condition9 is true)
OR (condition4 is true))
I figured out that I was not generating Credentials for the right app type.
If you're using Postman to test Google oAuth 2 APIs, select
Credentials -> Add credentials -> OAuth2.0 client ID -> Web Application.
For date:
#!/usr/bin/ruby -w
date = Time.new
#set 'date' equal to the current date/time.
date = date.day.to_s + "/" + date.month.to_s + "/" + date.year.to_s
#Without this it will output 2015-01-10 11:33:05 +0000; this formats it to display DD/MM/YYYY
puts date
#output the date
The above will display, for example, 10/01/15
And for time
time = Time.new
#set 'time' equal to the current time.
time = time.hour.to_s + ":" + time.min.to_s
#Without this it will output 2015-01-10 11:33:05 +0000; this formats it to display hour and minute
puts time
#output the time
The above will display, for example, 11:33
Then to put it together, add to the end:
puts date + " " + time
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(11);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
});
I posted this in another question, but I find using tables with iTextSharp offers a great level of precision.
document.Add(BlankLineDoc(16));
public static PdfPTable BlankLineDoc(int height)
{
var table = new PdfPTable(1) {WidthPercentage = 100};
table = BlankLineTable(table, height);
return table;
}
public static PdfPTable BlankLineTable(PdfPTable table, int height, int border = Rectangle.NO_BORDER)
{
var cell = new PdfPCell(new Phrase(" "))
{
Border = border,
Colspan = table.NumberOfColumns,
FixedHeight = height
};
table.AddCell(cell);
return table;
}
BlankLineTable can be used directly when working with tables
For starters, you could start more than one process:
tar -ztf file.tar.gz | while read FILENAME
do
(if tar -zxf file.tar.gz "$FILENAME" -O | grep -l "string"
then
echo "$FILENAME contains string"
fi) &
done
The ( ... ) &
creates a new detached (read: the parent shell does not wait for the child)
process.
After that, you should optimize the extracting of your archive. The read is no problem, as the OS should have cached the file access already. However, tar needs to unpack the archive every time the loop runs, which can be slow. Unpacking the archive once and iterating over the result may help here:
local tempPath=`tempfile`
mkdir $tempPath && tar -zxf file.tar.gz -C $tempPath &&
find $tempPath -type f | while read FILENAME
do
(if grep -l "string" "$FILENAME"
then
echo "$FILENAME contains string"
fi) &
done && rm -r $tempPath
find
is used here, to get a list of files in the target directory of tar
, which we're iterating over, for each file searching for a string.
Edit: Use grep -l
to speed up things, as Jim pointed out. From man grep
:
-l, --files-with-matches
Suppress normal output; instead print the name of each input file from which output would
normally have been printed. The scanning will stop on the first match. (-l is specified
by POSIX.)
Another date format
select datediff(day,'20110101','20110301')
I agree with sunetos that you'll have to use the $.ajax function in order to pass request headers. In order to do that, you'll have to write a function for the beforeSend event handler, which is one of the $.ajax() options. Here's a quick sample on how to do that:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'service.svc/Request',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
xhr.setRequestHeader('securityCode', 'Foo');
xhr.setRequestHeader('passkey', 'Bar');
}
</script>
</head>
<body>
<h1>Some Text</h1>
</body>
</html>
If you run the code above and watch the traffic in a tool like Fiddler, you'll see two requests headers passed in:
The setHeader function could also be inline in the $.ajax options, but I wanted to call it out.
Hope this helps!
Also check this post: Google Map Android Api V2 Sample Code not working, if you are completely sure you did the right steps then follow the second answer, the authentication gets cached somewhere, try to uninstall the application manually (just like you do with a normal application) then "Run" again the project
Building and simplifying @kindall's answer, here's what I typically use:
v_print = None
def main()
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbosity', action="count",
help="increase output verbosity (e.g., -vv is more than -v)")
args = parser.parse_args()
if args.verbosity:
def _v_print(*verb_args):
if verb_args[0] > (3 - args.verbosity):
print verb_args[1]
else:
_v_print = lambda *a: None # do-nothing function
global v_print
v_print = _v_print
if __name__ == '__main__':
main()
This then provides the following usage throughout your script:
v_print(1, "INFO message")
v_print(2, "WARN message")
v_print(3, "ERROR message")
And your script can be called like this:
% python verbose-tester.py -v
ERROR message
% python verbose=tester.py -vv
WARN message
ERROR message
% python verbose-tester.py -vvv
INFO message
WARN message
ERROR message
A couple notes:
3
that sets the upper bound for your logging, but I accept that as a compromise for simplicity.v_print
to work throughout your program, you have to do the junk with the global. It's no fun, but I challenge somebody to find a better way.I was getting similar bugs on library not found. Ultimately this is how I was able to resolve it
$ yum install -y yum-utils
$ repoquery -l packagename
If FName and LName contain NULL values, then you will need special handling to avoid unnecessary extra preceeding, trailing, and middle spaces. Also, if Address1 contains NULL values, then you need to have special handling to prevent adding unnecessary ', ' at the beginning of your address string.
If you are using SQL Server 2012, then you can use CONCAT (NULLs are automatically treated as empty strings) and IIF:
INSERT INTO TblStuff (FullName, Address, City, Zip)
SELECT FullName = REPLACE(RTRIM(LTRIM(CONCAT(FName, ' ', Middle, ' ', LName))), ' ', ' ')
, Address = CONCAT(Address1, IIF(Address2 IS NOT NULL, CONCAT(', ', Address2), ''))
, City
, Zip
FROM tblImport (NOLOCK);
Otherwise, this will work:
INSERT INTO TblStuff (FullName, Address, City, Zip)
SELECT FullName = REPLACE(RTRIM(LTRIM(ISNULL(FName, '') + ' ' + ISNULL(Middle, '') + ' ' + ISNULL(LName, ''))), ' ', ' ')
, Address = ISNULL(Address1, '') + CASE
WHEN Address2 IS NOT NULL THEN ', ' + Address2
ELSE '' END
, City
, Zip
FROM tblImport (NOLOCK);
Open Sublime Text console ? paste in opened field:
sublime.packages_path()
? Enter. You get result in console output.
This answer is relevant for April 2018. In the future, the data of this answer may be obsolete.
I'm not recommended @osiris answer. Arguments:
Packages
folder.I have the same error and it fixed it including in the file the following
#include <stdint.h>
at the beginning of your file.
use
console.log(variable)
and if you using google chrome open Console by using Ctrl+Shift+j
Goto >> Console
pip install wheel
worked for me, but you can also add this
setup(
...
setup_requires=['wheel']
)
to setup.py and save yourself a pip install command
So it turns out that if I add the Handler Mappings on the Website and Application level, everything works beautifully. I was only adding them on the server level, thus IIS did not know to map the asp pages to the IsapiModule.
So to resolve this issue, go to the website you want to add your application to, then double click on Handler Mappings. Click "Add Script Map" and enter in the following information:
RequestPath: *.asp
Executable: C:\Windows\System32\inetsrv\asp.dll
Name: Classic ASP (this can be anything you want it to be
Optional
api provides methods for getting the values. You can check isPresent()
for the presence of the value and then make a call to get()
or you can make a call to get()
chained with orElse()
and provide a default value.
The last thing you can try doing is using @Query()
over a custom method.
You just simply needs to add JAVA_HOME environment variable and provide the complete path of the latest JDK folder on your computer.
Re launch the installer and it would work.
In my opinion, it's much cleaner and easier to understand if you extract the retrieval of environment variables into a utility (you probably want to include a check to fail fast if an environment variable is not set anyway), and then you can just mock the utility.
// util.js
exports.getEnv = (key) => {
const value = process.env[key];
if (value === undefined) {
throw new Error(`Missing required environment variable ${key}`);
}
return value;
};
// app.test.js
const util = require('./util');
jest.mock('./util');
util.getEnv.mockImplementation(key => `fake-${key}`);
test('test', () => {...});
The following is my configuration:
cmake_minimum_required(VERSION 2.8)
set(Boost_INCLUDE_DIR /usr/local/src/boost_1_46_1)
set(Boost_LIBRARY_DIR /usr/local/src/boost_1_46_1/stage/lib)
find_package(Boost COMPONENTS system filesystem REQUIRED)
include_directories(${Boost_INCLUDE_DIR})
link_directories(${Boost_LIBRARY_DIR})
add_executable(main main.cpp)
target_link_libraries( main ${Boost_LIBRARIES} )
Unfortunately node does not support for each ... in
, even though it is specified in JavaScript 1.6. Chrome uses the same JavaScript engine and is reported as having a similar shortcoming.
You'll have to settle for array.forEach(function(item) { /* etc etc */ })
.
EDIT: From Google's official V8 website:
V8 implements ECMAScript as specified in ECMA-262.
On the same MDN website where it says that for each ...in
is in JavaScript 1.6, it says that it is not in any ECMA version - hence, presumably, its absence from Node.
This is really weird, why nobody is mentioning the /IM switch ?! I've been using it for a long time in backup jobs. But I tried googling just now and I couldn't land on a single web page that says anything about it even on MS website !!! Also found so many user posts complaining about the same issue!!
Anyway.. to use Robocopy to overwrite EVERYTHING what ever size or time in source or distination you must include these three switches in your command (/IS /IT /IM)
/IS :: Include Same files. (Includes same size files)
/IT :: Include Tweaked files. (Includes same files with different Attributes)
/IM :: Include Modified files (Includes same files with different times).
This is the exact command I use to transfer few TeraBytes of mostly 1GB+ files (ISOs - Disk Images - 4K Videos):
robocopy B:\Source D:\Destination /E /J /COPYALL /MT:1 /DCOPY:DATE /IS /IT /IM /X /V /NP /LOG:A:\ROBOCOPY.LOG
I did a small test for you .. and here is the result:
Total Copied Skipped Mismatch FAILED Extras
Dirs : 1028 1028 0 0 0 169
Files : 8053 8053 0 0 0 1
Bytes : 649.666 g 649.666 g 0 0 0 1.707 g
Times : 2:46:53 0:41:43 0:00:00 0:41:44
Speed : 278653398 Bytes/sec.
Speed : 15944.675 MegaBytes/min.
Ended : Friday, August 21, 2020 7:34:33 AM
Dest, Disk: WD Gold 6TB (Compare the write speed with my result)
Even with those "Extras", that's for reporting only because of the "/X" switch. As you can see nothing was Skipped and Total number and size of all files are equal to the Copied. Sometimes It will show small number of skipped files when I abuse it and cancel it multiple times during operation but even with that the values in the first 2 columns are always Equal. I also confirmed that once before by running a PowerShell script that scans all files in destination and generate a report of all time-stamps.
Some performance tips from my history with it and so many tests & troubles!:
. Despite of what most users online advise to use maximum threads "/MT:128" like it's a general trick to get the best performance ... PLEASE DON'T USE "/MT:128" WITH VERY LARGE FILES ... that's a big mistake and it will decrease your drive performance dramatically after several runs .. it will create very high fragmentation or even cause the files system to fail in some cases and you end up spending valuable time trying to recover a RAW partition and all that nonsense. And above all that, It will perform 4-6 times slower!!
Example in arrow functions:
let somethingTrue = true
[1,2,3,4,5].map(i=>somethingTrue && i*2)
In promises:
Promise.resolve()
.then(_=>checkTrueFalse && asyncFunc())
.then(_=>{ .. })
Otherwise:
if(somethingTrue) thenDo()
If it's just a simple conditional, I prefer using if(value) whenever possible because the word if in the beginning of the statement says more about what's happening than paranthesis and questionmarks.
There are actually three things here: origin master
is two separate things, and origin/master
is one thing. Three things total.
Two branches:
master
is a local branchorigin/master
is a remote branch (which is a local copy of the branch named "master" on the remote named "origin")One remote:
origin
is a remoteSince origin/master
is a branch, you can merge it. Here's a pull in two steps:
Step one, fetch master
from the remote origin
. The master
branch on origin
will be fetched and the local copy will be named origin/master
.
git fetch origin master
Then you merge origin/master
into master
.
git merge origin/master
Then you can push your new changes in master
back to origin
:
git push origin master
You can fetch multiple branches by name...
git fetch origin master stable oldstable
You can merge multiple branches...
git merge origin/master hotfix-2275 hotfix-2276 hotfix-2290
If you instead had a data.frame (df) that had multiple columns and you want to vectorize you can do
as.matrix(df, ncol=1)
I know this question is very old, but I was making similar thing in my kotlin app recently. So here is an example if anyone needs it:
val dfs = DecimalFormatSymbols.getInstance(Locale.getDefault())
val bigD = BigDecimal("1e+30")
val formattedBigD = DecimalFormat("#,##0.#",dfs).format(bigD)
Result displaying $formattedBigD:
1,000,000,000,000,000,000,000,000,000,000
Newer versions of Android support vector graphics, which is preferred over PNG icons. Android Studio 2.1.2 (and probably earlier versions) comes with Vector Asset Studio, which will automatically create PNG files for vector graphics that you add.
The Vector Asset Studio supports importing vector icons from the SDK, as well as your own SVG files.
This article describes Vector Asset Studio: https://developer.android.com/studio/write/vector-asset-studio.html
Summary for how to add a vector graphic with PNG files (partially copied from that URL):
app/build/generated/res/pngs/debug/
folder.Since the driver.window_handles
is not in order , a better solution is this.
first switch to the first tab using the shortcut
Control + X
to switch to the 'x' th tab in the browser window .
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "1");
# goes to 1st tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "4");
# goes to 4th tab if its exists or goes to last tab.
You can generate Application Encryption Key using this command:
php artisan key:generate
Then, create a cache file for faster configuration loading using this command:
php artisan config:cache
Or, serve the application on the PHP development server using this command:
php artisan serve
That's it!
This probably isnt relevant here. But to eliminate these html entites from an entire document, you can do something like this: (Assume document = page and please forgive the sloppy code, but if you have ideas as to how to make it better, Im all ears - Im new to this).
import re
import HTMLParser
regexp = "&.+?;"
list_of_html = re.findall(regexp, page) #finds all html entites in page
for e in list_of_html:
h = HTMLParser.HTMLParser()
unescaped = h.unescape(e) #finds the unescaped value of the html entity
page = page.replace(e, unescaped) #replaces html entity with unescaped value
However, if you want to do it anyway, search for regex pattern
<primaryAddress>[\s\S]*?<\/primaryAddress>
and replace it with empty string...
For multi-selects:
$("#yourdropdownid :selected").map(function(i, v) { return $.trim($(v).text()); }
Http is stateless. In order to authorize you, you have to "sign" every single request you're sending to server.
Token authentication
A request to the server is signed by a "token" - usually it means setting specific http headers, however, they can be sent in any part of the http request (POST body, etc.)
Pros:
<img src="http://bank.com?withdraw=1000&to=myself" />
, and if you're logged in via cookie authentication to bank.com, and bank.com doesn't have any means of XSRF protection, I'll withdraw money from your account simply by the fact that your browser will trigger an authorized GET request to that url.) Note there are anti forgery measure you can do with cookie-based authentication - but you have to implement those.Cookie authentication
Overall, I'd say tokens give you better flexibility, (since you're not bound to single domain). The downside is you have to do quite some coding by yourself.
The big difference is perfectly explained here.
Basically, lightweight tags are just pointers to specific commits. No further information is saved; on the other hand, annotated tags are regular objects, which have an author and a date and can be referred because they have their own SHA key.
If knowing who tagged what and when is relevant for you, then use annotated tags. If you just want to tag a specific point in your development, no matter who and when did that, then lightweight tags are good enough.
Normally you'd go for annotated tags, but it is really up to the Git master of the project.
First off:
public class ProfileCollection implements Iterable<Profile> {
Second:
return m_Profiles.get(m_ActiveProfile);
You could simply add a click listener on the map inside the function that creates the InfoWindow
google.maps.event.addListener(marker, 'click', function() {
var infoWindow = createInfoWindowForMarker(marker);
infoWindow.open(map, marker);
google.maps.event.addListener(map, 'click', function() {
infoWindow.close();
});
});