New command for users on macOS High Sierra as it is not possible to chown
on /usr/local
:
bash/zsh
:
sudo chown -R $(whoami) $(brew --prefix)/*
fish
:
sudo chown -R (whoami) (brew --prefix)/*
Reference: Can't chown /usr/local in High Sierra
if you want to get an attribute of an HTML element with jQuery you can use .attr();
so $('html').attr('someAttribute');
will give you the value of someAttribute
of the element html
there is a jQuery plugin here: http://plugins.jquery.com/project/getAttributes
that allows you to get all attributes from an HTML element
(Mar 2017) The accepted answer is not the best solution. It relies on manual translation using Apps Script, and the code may not be resilient, requiring maintenance. If your legacy system autogenerates CSV files, it's best they go into another folder for temporary processing (importing [uploading to Google Drive & converting] to Google Sheets files).
My thought is to let the Drive API do all the heavy-lifting. The Google Drive API team released v3 at the end of 2015, and in that release, insert()
changed names to create()
so as to better reflect the file operation. There's also no more convert flag -- you just specify MIMEtypes... imagine that!
The documentation has also been improved: there's now a special guide devoted to uploads (simple, multipart, and resumable) that comes with sample code in Java, Python, PHP, C#/.NET, Ruby, JavaScript/Node.js, and iOS/Obj-C that imports CSV files into Google Sheets format as desired.
Below is one alternate Python solution for short files ("simple upload") where you don't need the apiclient.http.MediaFileUpload
class. This snippet assumes your auth code works where your service endpoint is DRIVE
with a minimum auth scope of https://www.googleapis.com/auth/drive.file
.
# filenames & MIMEtypes
DST_FILENAME = 'inventory'
SRC_FILENAME = DST_FILENAME + '.csv'
SHT_MIMETYPE = 'application/vnd.google-apps.spreadsheet'
CSV_MIMETYPE = 'text/csv'
# Import CSV file to Google Drive as a Google Sheets file
METADATA = {'name': DST_FILENAME, 'mimeType': SHT_MIMETYPE}
rsp = DRIVE.files().create(body=METADATA, media_body=SRC_FILENAME).execute()
if rsp:
print('Imported %r to %r (as %s)' % (SRC_FILENAME, DST_FILENAME, rsp['mimeType']))
Better yet, rather than uploading to My Drive
, you'd upload to one (or more) specific folder(s), meaning you'd add the parent folder ID(s) to METADATA
. (Also see the code sample on this page.) Finally, there's no native .gsheet "file" -- that file just has a link to the online Sheet, so what's above is what you want to do.
If not using Python, you can use the snippet above as pseudocode to port to your system language. Regardless, there's much less code to maintain because there's no CSV parsing. The only thing remaining is to blow away the CSV file temp folder your legacy system wrote to.
The following CSS did the trick:
ul{
margin-left: 1em;
}
li{
list-style-position: outside;
padding-left: 0.5em;
}
Why not handle the error within the call?
i.e.
$.ajax({
type: 'POST',
url: 'loginCheck',
data: $(formLogin).serialize(),
dataType: 'json',
error: function(req, err){ console.log('my message' + err); }
});
One way - split you image into N rotating it slightly every time. I'd say 5 is enough. then create something like this in drawable
<animation-list android:id="@+id/handimation" android:oneshot="false"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/progress1" android:duration="150" />
<item android:drawable="@drawable/progress2" android:duration="150" />
<item android:drawable="@drawable/progress3" android:duration="150" />
</animation-list>
code start
progress.setVisibility(View.VISIBLE);
AnimationDrawable frameAnimation = (AnimationDrawable)progress.getDrawable();
frameAnimation.setCallback(progress);
frameAnimation.setVisible(true, true);
code stop
AnimationDrawable frameAnimation = (AnimationDrawable)progress.getDrawable();
frameAnimation.stop();
frameAnimation.setCallback(null);
frameAnimation = null;
progress.setVisibility(View.GONE);
more here
Extract private method to another class, test on that class; read more about SRP principle (Single Responsibility Principle)
It seem that you need extract to the private
method to another class; in this should be public
. Instead of trying to test on the private
method, you should test public
method of this another class.
We has the following scenario:
Class A
+ outputFile: Stream
- _someLogic(arg1, arg2)
We need to test the logic of _someLogic
; but it seem that Class A
take more role than it need(violate the SRP principle); just refactor into two classes
Class A1
+ A1(logicHandler: A2) # take A2 for handle logic
+ outputFile: Stream
Class A2
+ someLogic(arg1, arg2)
In this way someLogic
could be test on A2; in A1 just create some fake A2 then inject to constructor to test that A2 is called to the function named someLogic
.
df['new'] = 0
For in-place modification, perform direct assignment. This assignment is broadcasted by pandas for each row.
df = pd.DataFrame('x', index=range(4), columns=list('ABC'))
df
A B C
0 x x x
1 x x x
2 x x x
3 x x x
df['new'] = 'y'
# Same as,
# df.loc[:, 'new'] = 'y'
df
A B C new
0 x x x y
1 x x x y
2 x x x y
3 x x x y
If you want to add an column of empty lists, here is my advice:
object
columns are bad news in terms of performance. Rethink how your data is structured. If you must store a column of lists, ensure not to copy the same reference multiple times.
# Wrong
df['new'] = [[]] * len(df)
# Right
df['new'] = [[] for _ in range(len(df))]
df.assign(new=0)
If you need a copy instead, use DataFrame.assign
:
df.assign(new='y')
A B C new
0 x x x y
1 x x x y
2 x x x y
3 x x x y
And, if you need to assign multiple such columns with the same value, this is as simple as,
c = ['new1', 'new2', ...]
df.assign(**dict.fromkeys(c, 'y'))
A B C new1 new2
0 x x x y y
1 x x x y y
2 x x x y y
3 x x x y y
Finally, if you need to assign multiple columns with different values, you can use assign
with a dictionary.
c = {'new1': 'w', 'new2': 'y', 'new3': 'z'}
df.assign(**c)
A B C new1 new2 new3
0 x x x w y z
1 x x x w y z
2 x x x w y z
3 x x x w y z
For those of you in a .NET environment the following can be a handy way to filter non-numbers out (this example is in VB.NET, but it's probably similar in C#):
If Double.IsNaN(MyVariableName) Then
MyVariableName = 0 ' Or whatever you want to do here to "correct" the situation
End If
If you try to use a variable that has a NaN value you will get the following error:
Value was either too large or too small for a Decimal.
Also when I hit the post(Config.getURL("login"), values) the app seems to pause for a while (seems weird - thought the idea behind a service was that it runs on a different thread!)
In this case its better to use asynctask, which runs on a different thread and return result back to the ui thread on completion.
You'll need to check the contents of $_POST["JSONfullInfoArray"]
. If something doesn't parse json_decode
will just return null
. This isn't very helpful so when null
is returned you should check json_last_error()
to get more info on what went wrong.
private int pYear;
private int pMonth;
private int pDay;
static final int DATE_DIALOG_ID = 0;
/**inside oncreate */
final Calendar c = Calendar.getInstance();
pYear= c.get(Calendar.YEAR);
pMonth = c.get(Calendar.MONTH);
pDay = c.get(Calendar.DAY_OF_MONTH);
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
pYear, pMonth-1, pDay);
}
return null;
}
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DATE_DIALOG_ID:
((DatePickerDialog) dialog).updateDate(pYear, pMonth-1, pDay);
break;
}
}
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// write your code here to get the selected Date
}
};
try this it should work. Thanks
select * from v$session
where sid = to_number(substr(dbms_session.unique_session_id,1,4),'XXXX')
Pretty simple: Just put it inside a static method.
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(linkYouTube)));
In Mysql 5.7+ you can execute
select current_timestamp(6)
for more details
https://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html
The error is due to that you're only allowed to use pipeline steps inside the steps
directive. One workaround that I know is to use the script
step and wrap arbitrary pipeline script inside of it and save the result in the environment variable so that it can be used later.
So in your case:
pipeline {
agent any
stages {
stage("foo") {
steps {
script {
env.FILENAME = readFile 'output.txt'
}
echo "${env.FILENAME}"
}
}
}
}
Asynchronous downloaded images with caching
Asynchronous downloaded images with caching
Here is one more repos which can be used to download images in background
I'm pretty sure you only have to register MappingJacksonHttpMessageConverter
(the easiest way to do that is through <mvc:annotation-driven />
in XML or @EnableWebMvc
in Java)
See:
Here's a working example:
Maven POM
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>json</artifactId><packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version><name>json test</name>
<dependencies>
<dependency><!-- spring mvc -->
<groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>3.0.5.RELEASE</version>
</dependency>
<dependency><!-- jackson -->
<groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.4.2</version>
</dependency>
</dependencies>
<build><plugins>
<!-- javac --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version><configuration><source>1.6</source><target>1.6</target></configuration></plugin>
<!-- jetty --><plugin><groupId>org.mortbay.jetty</groupId><artifactId>jetty-maven-plugin</artifactId>
<version>7.4.0.v20110414</version></plugin>
</plugins></build>
</project>
in folder src/main/webapp/WEB-INF
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<servlet><servlet-name>json</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>json</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
json-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:mvc-context.xml" />
</beans>
in folder src/main/resources:
mvc-context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="test.json" />
</beans>
In folder src/main/java/test/json
TestController.java
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(method = RequestMethod.POST, value = "math")
@ResponseBody
public Result math(@RequestBody final Request request) {
final Result result = new Result();
result.setAddition(request.getLeft() + request.getRight());
result.setSubtraction(request.getLeft() - request.getRight());
result.setMultiplication(request.getLeft() * request.getRight());
return result;
}
}
Request.java
public class Request implements Serializable {
private static final long serialVersionUID = 1513207428686438208L;
private int left;
private int right;
public int getLeft() {return left;}
public void setLeft(int left) {this.left = left;}
public int getRight() {return right;}
public void setRight(int right) {this.right = right;}
}
Result.java
public class Result implements Serializable {
private static final long serialVersionUID = -5054749880960511861L;
private int addition;
private int subtraction;
private int multiplication;
public int getAddition() { return addition; }
public void setAddition(int addition) { this.addition = addition; }
public int getSubtraction() { return subtraction; }
public void setSubtraction(int subtraction) { this.subtraction = subtraction; }
public int getMultiplication() { return multiplication; }
public void setMultiplication(int multiplication) { this.multiplication = multiplication; }
}
You can test this setup by executing mvn jetty:run
on the command line, and then sending a POST request:
URL: http://localhost:8080/test/math
mime type: application/json
post body: { "left": 13 , "right" : 7 }
I used the Poster Firefox plugin to do this.
Here's what the response looks like:
{"addition":20,"subtraction":6,"multiplication":91}
Just had a similar problem, except i needed a NodeList and not a Document, here's what I came up with. It's mostly the same solution as before, augmented to get the root element down as a NodeList and using erickson's suggestion of using an InputSource instead for character encoding issues.
private String DOC_ROOT="root";
String xml=getXmlString();
Document xmlDoc=loadXMLFrom(xml);
Element template=xmlDoc.getDocumentElement();
NodeList nodes=xmlDoc.getElementsByTagName(DOC_ROOT);
public static Document loadXMLFrom(String xml) throws Exception {
InputSource is= new InputSource(new StringReader(xml));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = null;
builder = factory.newDocumentBuilder();
Document doc = builder.parse(is);
return doc;
}
use either of these codes
$('#dropDownId :selected').text();
OR
$('#dropDownId').text();
on Ubuntu Bionic (18.04), six is already install for python2 and python3 but I have the error launching Wammu. @3ygun solution worked for me to solve
ImportError: No module named six
when launching Wammu
If it's occurred for python3 program, six come with
pip3 install six
and if you don't have pip3:
apt install python3-pip
with sudo under Ubuntu!
In Swift 4:
let dict = ["Item1":2.4, "Item2": 5.4, "Item3" : 6.5]
let array = Array(dict.values)
datetime.time
can not do it - But you could use datetime.datetime.now()
start = datetime.datetime.now()
sleep(10)
end = datetime.datetime.now()
duration = end - start
string literals are non-modifiable in C
Combining Alaa Akoum and Nick Eagle's solutions allowed me to loop through a series of windows services and stop them if they're running.
# stop the following Windows services in the specified order:
[Array] $Services = 'Service1','Service2','Service3','Service4','Service5';
# loop through each service, if its running, stop it
foreach($ServiceName in $Services)
{
$arrService = Get-Service -Name $ServiceName
write-host $ServiceName
while ($arrService.Status -eq 'Running')
{
Stop-Service $ServiceName
write-host $arrService.status
write-host 'Service stopping'
Start-Sleep -seconds 60
$arrService.Refresh()
if ($arrService.Status -eq 'Stopped')
{
Write-Host 'Service is now Stopped'
}
}
}
The same can be done to start a series of service if they are not running:
# start the following Windows services in the specified order:
[Array] $Services = 'Service1','Service2','Service3','Service4','Service5';
# loop through each service, if its not running, start it
foreach($ServiceName in $Services)
{
$arrService = Get-Service -Name $ServiceName
write-host $ServiceName
while ($arrService.Status -ne 'Running')
{
Start-Service $ServiceName
write-host $arrService.status
write-host 'Service starting'
Start-Sleep -seconds 60
$arrService.Refresh()
if ($arrService.Status -eq 'Running')
{
Write-Host 'Service is now Running'
}
}
}
The use of -X [WHATEVER]
merely changes the request's method string used in the HTTP request. This is easier to understand with two examples — one with -X [WHATEVER]
and one without — and the associated HTTP request headers for each:
# curl -XPANTS -o nul -v http://neverssl.com/
* Connected to neverssl.com (13.224.86.126) port 80 (#0)
> PANTS / HTTP/1.1
> Host: neverssl.com
> User-Agent: curl/7.42.0
> Accept: */*
# curl -o nul -v http://neverssl.com/
* Connected to neverssl.com (13.33.50.167) port 80 (#0)
> GET / HTTP/1.1
> Host: neverssl.com
> User-Agent: curl/7.42.0
> Accept: */*
This will return the time-Only
For SQL Server:
SELECT convert(varchar(8), getdate(), 108)
Explanation:
getDate()
is giving current date and time.
108
is formatting/giving us the required portion i.e time in this case.
varchar(8)
gives us the number of characters from that portion.
Like:
If you wrote varchar(7)
there, it will give you 00:00:0
If you wrote varchar(6)
there, it will give you 00:00:
If you wrote varchar(15)
there, it will still give you 00:00:00
because it is giving output of just time portion.
SQLFiddle Demo
For MySQL:
SELECT DATE_FORMAT(NOW(), '%H:%i:%s')
Try this.
declare @topval int
set @topval = 5 (customized value)
SELECT TOP(@topval) * from your_database
Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:
Delivery -> Package (One -> Many)
CREATE TABLE Delivery(
Id INT IDENTITY PRIMARY KEY,
NoteNumber NVARCHAR(255) NOT NULL
)
CREATE TABLE Package(
Id INT IDENTITY PRIMARY KEY,
Status INT NOT NULL DEFAULT 0,
Delivery_Id INT NOT NULL,
CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
)
The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).
So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.
You can use the code below:
a {
display: block;
width: 113px;
margin: auto;
}
By setting, in my case, the link to display:block
, it is easier
to position the link.
This works the same when you use a <div>
tag/class.
You can pick any width
you want.
Just use in the CSS whatever you would use in a fill
attribute.
Of course, this requires that you have defined the linear gradient somewhere in your SVG.
Here is a complete example:
rect {_x000D_
cursor: pointer;_x000D_
shape-rendering: crispEdges;_x000D_
fill: url(#MyGradient);_x000D_
}
_x000D_
<svg width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
<style type="text/css">_x000D_
rect{fill:url(#MyGradient)}_x000D_
</style>_x000D_
<defs>_x000D_
<linearGradient id="MyGradient">_x000D_
<stop offset="5%" stop-color="#F60" />_x000D_
<stop offset="95%" stop-color="#FF6" />_x000D_
</linearGradient>_x000D_
</defs>_x000D_
_x000D_
<rect width="100" height="50"/>_x000D_
</svg>
_x000D_
Set the data as a vector and then place in the function.
I wrote a simple class that uses OpenCSV
and has two static public
methods.
static public File toCSVFile(Object object, String path, String name) {
File pathFile = new File(path);
pathFile.mkdirs();
File returnFile = new File(path + name);
try {
CSVWriter writer = new CSVWriter(new FileWriter(returnFile));
writer.writeNext(new String[]{"Member Name in Code", "Stored Value", "Type of Value"});
for (Field field : object.getClass().getDeclaredFields()) {
writer.writeNext(new String[]{field.getName(), field.get(object).toString(), field.getType().getName()});
}
writer.flush();
writer.close();
return returnFile;
} catch (IOException e) {
Log.e("EasyStorage", "Easy Storage toCSVFile failed.", e);
return null;
} catch (IllegalAccessException e) {
Log.e("EasyStorage", "Easy Storage toCSVFile failed.", e);
return null;
}
}
static public void fromCSVFile(Object object, File file) {
try {
CSVReader reader = new CSVReader(new FileReader(file));
String[] nextLine = reader.readNext(); // Ignore the first line.
while ((nextLine = reader.readNext()) != null) {
if (nextLine.length >= 2) {
try {
Field field = object.getClass().getDeclaredField(nextLine[0]);
Class<?> rClass = field.getType();
if (rClass == String.class) {
field.set(object, nextLine[1]);
} else if (rClass == int.class) {
field.set(object, Integer.parseInt(nextLine[1]));
} else if (rClass == boolean.class) {
field.set(object, Boolean.parseBoolean(nextLine[1]));
} else if (rClass == float.class) {
field.set(object, Float.parseFloat(nextLine[1]));
} else if (rClass == long.class) {
field.set(object, Long.parseLong(nextLine[1]));
} else if (rClass == short.class) {
field.set(object, Short.parseShort(nextLine[1]));
} else if (rClass == double.class) {
field.set(object, Double.parseDouble(nextLine[1]));
} else if (rClass == byte.class) {
field.set(object, Byte.parseByte(nextLine[1]));
} else if (rClass == char.class) {
field.set(object, nextLine[1].charAt(0));
} else {
Log.e("EasyStorage", "Easy Storage doesn't yet support extracting " + rClass.getSimpleName() + " from CSV files.");
}
} catch (NoSuchFieldException e) {
Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
} catch (IllegalAccessException e) {
Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
}
} // Close if (nextLine.length >= 2)
} // Close while ((nextLine = reader.readNext()) != null)
} catch (FileNotFoundException e) {
Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
} catch (IOException e) {
Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
} catch (IllegalArgumentException e) {
Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
}
}
I think with some simple recursion these methods could be modified to handle any Java object, but for me this was adequate.
I got the solution.
Step 3: In Library section Add Library...(google-play-services_lib)
see below buttes
<android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/
Closes should be done in reverse order of the opens.
Python slicing is an incredibly fast operation, and it's a handy way to quickly access parts of your data.
Slice notation to get the last nine elements from a list (or any other sequence that supports it, like a string) would look like this:
num_list[-9:]
When I see this, I read the part in the brackets as "9th from the end, to the end." (Actually, I abbreviate it mentally as "-9, on")
The full notation is
sequence[start:stop:step]
But the colon is what tells Python you're giving it a slice and not a regular index. That's why the idiomatic way of copying lists in Python 2 is
list_copy = sequence[:]
And clearing them is with:
del my_list[:]
(Lists get list.copy
and list.clear
in Python 3.)
You may find it useful to separate forming the slice from passing it to the list.__getitem__
method (that's what the square brackets do). Even if you're not new to it, it keeps your code more readable so that others that may have to read your code can more readily understand what you're doing.
However, you can't just assign some integers separated by colons to a variable. You need to use the slice object:
last_nine_slice = slice(-9, None)
The second argument, None
, is required, so that the first argument is interpreted as the start
argument otherwise it would be the stop
argument.
You can then pass the slice object to your sequence:
>>> list(range(100))[last_nine_slice]
[91, 92, 93, 94, 95, 96, 97, 98, 99]
islice
islice
from the itertools module is another possibly performant way to get this. islice
doesn't take negative arguments, so ideally your iterable has a __reversed__
special method - which list does have - so you must first pass your list (or iterable with __reversed__
) to reversed
.
>>> from itertools import islice
>>> islice(reversed(range(100)), 0, 9)
<itertools.islice object at 0xffeb87fc>
islice allows for lazy evaluation of the data pipeline, so to materialize the data, pass it to a constructor (like list
):
>>> list(islice(reversed(range(100)), 0, 9))
[99, 98, 97, 96, 95, 94, 93, 92, 91]
Coming late to the party, but I found this fantastic step-by-step guide on getting control of your SQLExpress instance if you don't have your sa password. I used this process to not only reset my sa password, but I also added my domain account to all the available server roles. I can now create databases, alter logins, do bulk operations, backups/restores, etc using my normal login.
To summarize, you use SQL Server Configuration Manager to put your instance into single-user mode. This elevates you to sysadmin when you connect, allowing you the ability to set everything up.
Edit: I've copied the steps below - kudos to the original author of the link above.
If you understand stack very well then you will understand how memory works in program and if you understand how memory works in program you will understand how function store in program and if you understand how function store in program you will understand how recursive function works and if you understand how recursive function works you will understand how compiler works and if you understand how compiler works your mind will works as compiler and you will debug any program very easily
Let me explain how stack works:
First you have to know how functions are represented in stack :
Heap stores dynamically allocated values.
Stack stores automatic allocation and deletion values.
Let's understand with example :
def hello(x):
if x==1:
return "op"
else:
u=1
e=12
s=hello(x-1)
e+=1
print(s)
print(x)
u+=1
return e
hello(4)
Now understand parts of this program :
Now let's see what is stack and what are stack parts:
Allocation of the stack :
Remember one thing: if any function's return condition gets satisfied, no matter it has loaded the local variables or not, it will immediately return from stack with it's stack frame. It means that whenever any recursive function get base condition satisfied and we put a return after base condition, the base condition will not wait to load local variables which are located in the “else” part of program. It will immediately return the current frame from the stack following which the next frame is now in the activation record.
See this in practice:
Deallocation of the block:
So now whenever a function encounters return statement, it delete the current frame from the stack.
While returning from the stack, values will returned in reverse of the original order in which they were allocated in stack.
In case of someone else is doing it in Python and it is not working, try to set it before do the imports of pycuda and tensorflow.
I.e.:
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
...
import pycuda.autoinit
import tensorflow as tf
...
As saw here.
In isolation, there is nothing wrong with using for-in on arrays. For-in iterates over the property names of an object, and in the case of an "out-of-the-box" array, the properties corresponds to the array indexes. (The built-in propertes like length
, toString
and so on are not included in the iteration.)
However, if your code (or the framework you are using) add custom properties to arrays or to the array prototype, then these properties will be included in the iteration, which is probably not what you want.
Some JS frameworks, like Prototype modifies the Array prototype. Other frameworks like JQuery doesn't, so with JQuery you can safely use for-in.
If you are in doubt, you probably shouldn't use for-in.
An alternative way of iterating through an array is using a for-loop:
for (var ix=0;ix<arr.length;ix++) alert(ix);
However, this have a different issue. The issue is that a JavaScript array can have "holes". If you define arr
as:
var arr = ["hello"];
arr[100] = "goodbye";
Then the array have two items, but a length of 101. Using for-in will yield two indexes, while the for-loop will yield 101 indexes, where the 99 has a value of undefined
.
You can get all 4-6gram using the code without other package below:
from itertools import chain
def get_m_2_ngrams(input_list, min, max):
for s in chain(*[get_ngrams(input_list, k) for k in range(min, max+1)]):
yield ' '.join(s)
def get_ngrams(input_list, n):
return zip(*[input_list[i:] for i in range(n)])
if __name__ == '__main__':
input_list = ['I', 'am', 'aware', 'that', 'nltk', 'only', 'offers', 'bigrams', 'and', 'trigrams', ',', 'but', 'is', 'there', 'a', 'way', 'to', 'split', 'my', 'text', 'in', 'four-grams', ',', 'five-grams', 'or', 'even', 'hundred-grams']
for s in get_m_2_ngrams(input_list, 4, 6):
print(s)
the output is below:
I am aware that
am aware that nltk
aware that nltk only
that nltk only offers
nltk only offers bigrams
only offers bigrams and
offers bigrams and trigrams
bigrams and trigrams ,
and trigrams , but
trigrams , but is
, but is there
but is there a
is there a way
there a way to
a way to split
way to split my
to split my text
split my text in
my text in four-grams
text in four-grams ,
in four-grams , five-grams
four-grams , five-grams or
, five-grams or even
five-grams or even hundred-grams
I am aware that nltk
am aware that nltk only
aware that nltk only offers
that nltk only offers bigrams
nltk only offers bigrams and
only offers bigrams and trigrams
offers bigrams and trigrams ,
bigrams and trigrams , but
and trigrams , but is
trigrams , but is there
, but is there a
but is there a way
is there a way to
there a way to split
a way to split my
way to split my text
to split my text in
split my text in four-grams
my text in four-grams ,
text in four-grams , five-grams
in four-grams , five-grams or
four-grams , five-grams or even
, five-grams or even hundred-grams
I am aware that nltk only
am aware that nltk only offers
aware that nltk only offers bigrams
that nltk only offers bigrams and
nltk only offers bigrams and trigrams
only offers bigrams and trigrams ,
offers bigrams and trigrams , but
bigrams and trigrams , but is
and trigrams , but is there
trigrams , but is there a
, but is there a way
but is there a way to
is there a way to split
there a way to split my
a way to split my text
way to split my text in
to split my text in four-grams
split my text in four-grams ,
my text in four-grams , five-grams
text in four-grams , five-grams or
in four-grams , five-grams or even
four-grams , five-grams or even hundred-grams
you can find more detail on this blog
May I suggest numbro for locale based formatting and number-format.js for the general case. A combination of the two depending on use-case may help.
You need to assign $first and $second
$first = $_POST['first'];
$second= $_POST['second'];
Also, As Travesty3 said, you need to do your arithmetic outside of the quotes:
echo $first + $second;
On windows:
py -3.4x32 -m venv venv34
or
py -2.6.2 -m venv venv26
This uses the py
launcher which will find the right python executable for you (assuming you have it installed).
Doug answered my question... But I'll explain what my problem was exactly, and how Doug helped me solve my problem which you could be encountering.
I call jquery $.post
and am replacing my div with my partial view, like so.
function AddNewAddress (paramvalue) {
$.post(url, { param: paramvalue}, function(d) {
$('#myDiv').replaceWith(d);
});
}
When doing so, for some reason when stepping into my model my selected value affiliated property was never set, only until I stepped into the view it came into scope.
So, What I had before
@Html.DropDownListUnobtrusiveFor(model => model.CustomerAddresses[i].YearsAtAddress, Model.CustomerAddresses[i].YearsAtAddressSelectList, new {onchange = "return Address.AddNewAddress(this,'" + @Url.Action("AddNewAddress", "Address") + "'," + i + ")"})
however even though Model.CustomerAddresses[i].YearsAtAddressSelectList, was set... it didn't set the selected value.
So after....
@Html.DropDownListUnobtrusiveFor(model => model.CustomerAddresses[i].YearsAtAddress, new SelectList(Model.CustomerAddresses[i].YearsAtAddressSelectList, "Value", "Text", Model.CustomerAddresses[i].YearsAtAddress), new { onchange = "return Address.AddNewAddress(this,'" + @Url.Action("AddNewAddress", "Address") + "'," + i + ")" })
and it worked!
I decided not to use DropDownListFor
as it has problem when using unobtrusive validation, which is why i reference the following if your curious in a class classed
HtmlExtensions.cs
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList)
{
return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, null /* htmlAttributes */);
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes)
{
return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, new RouteValueDictionary(htmlAttributes));
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes)
{
return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, htmlAttributes);
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel)
{
return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, optionLabel, null /* htmlAttributes */);
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes)
{
return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, optionLabel, new RouteValueDictionary(htmlAttributes));
}
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Users cannot use anonymous methods with the LambdaExpression type")]
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)
{
if (expression == null)
{
throw new ArgumentNullException("expression");
}
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
IDictionary<string, object> validationAttributes = htmlHelper
.GetUnobtrusiveValidationAttributes(ExpressionHelper.GetExpressionText(expression), metadata);
if (htmlAttributes == null)
htmlAttributes = validationAttributes;
else
htmlAttributes = htmlAttributes.Concat(validationAttributes).ToDictionary(k => k.Key, v => v.Value);
return SelectExtensions.DropDownListFor(htmlHelper, expression, selectList, optionLabel, htmlAttributes);
}
public class MainActivity extends Activity {
Bitmap b;
ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.imageView1);
information info = new information();
info.execute("");
}
public class information extends AsyncTask<String, String, String>
{
@Override
protected String doInBackground(String... arg0) {
try
{
URL url = new URL("http://10.119.120.10:80/img.jpg");
InputStream is = new BufferedInputStream(url.openStream());
b = BitmapFactory.decodeStream(is);
} catch(Exception e){}
return null;
}
@Override
protected void onPostExecute(String result) {
img.setImageBitmap(b);
}
}
}
However, I disagree the official definition of Guide to naming conventions on groupId, artifactId, and version which proposes the groupId must start with a reversed domain name you control.
com
means this project belongs to a company, and org
means this project belongs to a social organization. These are alright, but for those strange domain like xxx.tv, xxx.uk, xxx.cn, it does not make sense to name the groupId started with "tv.","cn.", the groupId should deliver the basic information of the project rather than the domain.
The location of the sitemap affects which URLs that it can include, but otherwise there is no standard. Here is a good link with more explaination: http://www.sitemaps.org/protocol.html#location
SELECT *
FROM table
WHERE date BETWEEN
ADDDATE(LAST_DAY(DATE_SUB(NOW(),INTERVAL 2 MONTH)), INTERVAL 1 DAY)
AND DATE_SUB(NOW(),INTERVAL 1 MONTH);
See the docs for info on DATE_SUB
, ADDDATE
, LAST_DAY
and other useful datetime functions.
Using UNION
automatically removes duplicate rows unless you specify UNION ALL
:
http://msdn.microsoft.com/en-us/library/ms180026(SQL.90).aspx
I've not found anything in the API, but one thing you could do is attach an event handler to the standard paginator and detect if it has changed:
$('.dataTables_length select').live('change', function(){
alert(this.value);
});
Try this:
function btnClick() {
var x = document.getElementById("mytable").getElementsByTagName("td");
x[0].innerHTML = "i want to change my cell color";
x[0].style.backgroundColor = "yellow";
}
Set from JS, backgroundColor
is the equivalent of background-color
in your style-sheet.
Note also that the .cells
collection belongs to a table row, not to the table itself. To get all the cells from all rows you can instead use getElementsByTagName()
.
explain select * from test where id in (values (1), (2));
Seq Scan on test (cost=0.00..1.38 rows=2 width=208)
Filter: (id = ANY ('{1,2}'::bigint[]))
But if try 2nd query:
explain select * from test where id = any (values (1), (2));
Hash Semi Join (cost=0.05..1.45 rows=2 width=208)
Hash Cond: (test.id = "*VALUES*".column1)
-> Seq Scan on test (cost=0.00..1.30 rows=30 width=208)
-> Hash (cost=0.03..0.03 rows=2 width=4)
-> Values Scan on "*VALUES*" (cost=0.00..0.03 rows=2 width=4)
We can see that postgres build temp table and join with it
TypeA[] array = (TypeA[]) a.toArray();
If you want to do multiple (3+) columns here is a great snippet that works perfectly and validates as valid HTML5:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Multiple Colums</title>
<!-- Styles -->
<style>
.flex-center {
width: 100%;
align-items: center;/*These two properties center vetically*/
height: 100vh;/*These two properties center vetically*/
display: flex;/*This is the attribute that separates into columns*/
justify-content: center;
text-align: center;
position: relative;
}
.spaceOut {
margin-left: 25px;
margin-right: 25px;
}
</style>
</head>
<body>
<section class="flex-center">
<h4>Tableless Columns Example</h4><br />
<div class="spaceOut">
Column 1<br />
</div>
<div class="spaceOut">
Column 2<br />
</div>
<div class="spaceOut">
Column 3<br />
</div>
<div class="spaceOut">
Column 4<br />
</div>
<div class="spaceOut">
Column 5<br />
</div>
</section>
</body>
</html>
In Jan2018 the only solution worked for me:
<?php
if (ob_get_level() == 0) ob_start();
for ($i = 0; $i<10; $i++){
echo "<br> Line to show.";
echo str_pad('',4096)."\n";
ob_flush();
flush();
sleep(2);
}
echo "Done.";
ob_end_flush();
?>
For more information about .scrollHeight
property refer to the docs:
The Element.scrollHeight read-only attribute is a measurement of the height of an element's content, including content not visible on the screen due to overflow. The scrollHeight value is equal to the minimum clientHeight the element would require in order to fit all the content in the viewpoint without using a vertical scrollbar. It includes the element padding but not its margin.
If you are working with apps, try cleaning solution. Fixed for me.
It's the ternary form of the if-else operator. The above statement basically reads like this:
if ($add_review) then {
return FALSE; //$add_review evaluated as True
} else {
return $arg //$add_review evaluated as False
}
See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/
For this problem the best solution I use is to have a CLR function in Sql Server 2005 that uses one of DateTime.Parse or ParseExact function to return the DateTime value with a specified format.
Check to make sure that the file is complete. This error message can occur if you only partially downloaded a file or if it has major issues. Check the MD5sum.
To know the package owning (or providing) an already installed file:
rpm -qf myfilename
If you are looking for an alternative way, try adding your credentials using AmazonCLI
from the terminal type:-
aws configure
then fill in your keys and region.
Your sprite is created mid way through the playerSprite function... it also goes out of scope and ceases to exist at the end of that same function. The sprite must be created where you can pass it to playerSprite to initialize it and also where you can pass it to your draw function.
Perhaps declare it above your first while
?
This answer extends on Jayson's excellent answer with some more opinionated guidance on the best approach for your use case:
Managing versions manually is probably the worst option. If you decide to manually switch versions, you can use this Bash code instead of Jayson's verbose code (code snippet from the homebrew-openjdk README:
jdk() {
version=$1
export JAVA_HOME=$(/usr/libexec/java_home -v"$version");
java -version
}
Jayson's answer provides the basic commands for SDKMAN and jenv. Here's more info on SDKMAN and more info on jenv if you'd like more background on these tools.
No need to use brute force a simple way is to find your plain text password.
goto:
C:\Users\<your username>\AndroidStudioProjects\WhatsAppDP\.gradle\2.2.1\taskArtifacts
Open:
taskArtifacts.bin
when you open taskArtifacts.bin might look encrypted, don't worry about that search for ".keyPassword" a couple times. Then you will find your password in plain text. It may resemble:
signingConfig.keyPassword¬í t <your password>Æù
Hope this was helpful.
If you are trying to use AngularJs 1.6.6 as of 21/10/2017 the following parameter works as .success and has been depleted. The .then() method takes two arguments: a response and an error callback which will be called with a response object.
$scope.login = function () {
$scope.btntext = "Please wait...!";
$http({
method: "POST",
url: '/Home/userlogin', // link UserLogin with HomeController
data: $scope.user
}).then(function (response) {
console.log("Result value is : " + parseInt(response));
data = response.data;
$scope.btntext = 'Login';
if (data == 1) {
window.location.href = '/Home/dashboard';
}
else {
alert(data);
}
}, function (error) {
alert("Failed Login");
});
The above snipit works for a login page.
for example i tried all above for characters it fails but that worked for me >> reserved a pointer then assign values
char A[];
A = new char[]{'a', 'b', 'a', 'c', 'd', 'd', 'e', 'f', 'q', 'r'};
None of the answers mentioned running on a non-main thread, so adding my 2 cents.
On main queue (main thread)
let mainQueue = DispatchQueue.main
let deadline = DispatchTime.now() + .seconds(10)
mainQueue.asyncAfter(deadline: deadline) {
// ...
}
OR
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(10)) {
// ...
}
On global queue (non main thread, based on QOS specified) .
let backgroundQueue = DispatchQueue.global()
let deadline = DispatchTime.now() + .milliseconds(100)
backgroundQueue.asyncAfter(deadline: deadline, qos: .background) {
// ...
}
OR
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + .milliseconds(100), qos: .background) {
// ...
}
No, there isn't such constant.
This answer contains 2 generators for random-based and name-based UUIDs, compliant with RFC-4122. Feel free to use and share.
RANDOM-BASED (v4)
This utility class that generates random-based UUIDs:
package your.package.name;
import java.security.SecureRandom;
import java.util.Random;
import java.util.UUID;
/**
* Utility class that creates random-based UUIDs.
*
*/
public abstract class RandomUuidCreator {
private static final int RANDOM_VERSION = 4;
/**
* Returns a random-based UUID.
*
* It uses a thread local {@link SecureRandom}.
*
* @return a random-based UUID
*/
public static UUID getRandomUuid() {
return getRandomUuid(SecureRandomLazyHolder.THREAD_LOCAL_RANDOM.get());
}
/**
* Returns a random-based UUID.
*
* It uses any instance of {@link Random}.
*
* @return a random-based UUID
*/
public static UUID getRandomUuid(Random random) {
long msb = 0;
long lsb = 0;
// (3) set all bit randomly
if (random instanceof SecureRandom) {
// Faster for instances of SecureRandom
final byte[] bytes = new byte[16];
random.nextBytes(bytes);
msb = toNumber(bytes, 0, 8); // first 8 bytes for MSB
lsb = toNumber(bytes, 8, 16); // last 8 bytes for LSB
} else {
msb = random.nextLong(); // first 8 bytes for MSB
lsb = random.nextLong(); // last 8 bytes for LSB
}
// Apply version and variant bits (required for RFC-4122 compliance)
msb = (msb & 0xffffffffffff0fffL) | (RANDOM_VERSION & 0x0f) << 12; // apply version bits
lsb = (lsb & 0x3fffffffffffffffL) | 0x8000000000000000L; // apply variant bits
// Return the UUID
return new UUID(msb, lsb);
}
private static long toNumber(final byte[] bytes, final int start, final int length) {
long result = 0;
for (int i = start; i < length; i++) {
result = (result << 8) | (bytes[i] & 0xff);
}
return result;
}
// Holds thread local secure random
private static class SecureRandomLazyHolder {
static final ThreadLocal<Random> THREAD_LOCAL_RANDOM = ThreadLocal.withInitial(SecureRandom::new);
}
/**
* For tests!
*/
public static void main(String[] args) {
System.out.println("// Using thread local `java.security.SecureRandom` (DEFAULT)");
System.out.println("RandomUuidCreator.getRandomUuid()");
System.out.println();
for (int i = 0; i < 5; i++) {
System.out.println(RandomUuidCreator.getRandomUuid());
}
System.out.println();
System.out.println("// Using `java.util.Random` (FASTER)");
System.out.println("RandomUuidCreator.getRandomUuid(new Random())");
System.out.println();
Random random = new Random();
for (int i = 0; i < 5; i++) {
System.out.println(RandomUuidCreator.getRandomUuid(random));
}
}
}
This is the output:
// Using thread local `java.security.SecureRandom` (DEFAULT)
RandomUuidCreator.getRandomUuid()
'ef4f5ad2-8147-46cb-8389-c2b8c3ef6b10'
'adc0305a-df29-4f08-9d73-800fde2048f0'
'4b794b59-bff8-4013-b656-5d34c33f4ce3'
'22517093-ee24-4120-96a5-ecee943992d1'
'899fb1fb-3e3d-4026-85a8-8a2d274a10cb'
// Using `java.util.Random` (FASTER)
RandomUuidCreator.getRandomUuid(new Random())
'4dabbbc2-fcb2-4074-a91c-5e2977a5bbf8'
'078ec231-88bc-4d74-9774-96c0b820ceda'
'726638fa-69a6-4a18-b09f-5fd2a708059b'
'15616ebe-1dfd-4f5c-b2ed-cea0ac1ad823'
'affa31ad-5e55-4cde-8232-cddd4931923a'
NAME-BASED (v3 and v5)
This utility class that generates name-based UUIDs (MD5 and SHA1):
package your.package.name;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
/**
* Utility class that creates UUIDv3 (MD5) and UUIDv5 (SHA1).
*
*/
public class HashUuidCreator {
// Domain Name System
public static final UUID NAMESPACE_DNS = new UUID(0x6ba7b8109dad11d1L, 0x80b400c04fd430c8L);
// Uniform Resource Locator
public static final UUID NAMESPACE_URL = new UUID(0x6ba7b8119dad11d1L, 0x80b400c04fd430c8L);
// ISO Object ID
public static final UUID NAMESPACE_ISO_OID = new UUID(0x6ba7b8129dad11d1L, 0x80b400c04fd430c8L);
// X.500 Distinguished Name
public static final UUID NAMESPACE_X500_DN = new UUID(0x6ba7b8149dad11d1L, 0x80b400c04fd430c8L);
private static final int VERSION_3 = 3; // UUIDv3 MD5
private static final int VERSION_5 = 5; // UUIDv5 SHA1
private static final String MESSAGE_DIGEST_MD5 = "MD5"; // UUIDv3
private static final String MESSAGE_DIGEST_SHA1 = "SHA-1"; // UUIDv5
private static UUID getHashUuid(UUID namespace, String name, String algorithm, int version) {
final byte[] hash;
final MessageDigest hasher;
try {
// Instantiate a message digest for the chosen algorithm
hasher = MessageDigest.getInstance(algorithm);
// Insert name space if NOT NULL
if (namespace != null) {
hasher.update(toBytes(namespace.getMostSignificantBits()));
hasher.update(toBytes(namespace.getLeastSignificantBits()));
}
// Generate the hash
hash = hasher.digest(name.getBytes(StandardCharsets.UTF_8));
// Split the hash into two parts: MSB and LSB
long msb = toNumber(hash, 0, 8); // first 8 bytes for MSB
long lsb = toNumber(hash, 8, 16); // last 8 bytes for LSB
// Apply version and variant bits (required for RFC-4122 compliance)
msb = (msb & 0xffffffffffff0fffL) | (version & 0x0f) << 12; // apply version bits
lsb = (lsb & 0x3fffffffffffffffL) | 0x8000000000000000L; // apply variant bits
// Return the UUID
return new UUID(msb, lsb);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Message digest algorithm not supported.");
}
}
public static UUID getMd5Uuid(String string) {
return getHashUuid(null, string, MESSAGE_DIGEST_MD5, VERSION_3);
}
public static UUID getSha1Uuid(String string) {
return getHashUuid(null, string, MESSAGE_DIGEST_SHA1, VERSION_5);
}
public static UUID getMd5Uuid(UUID namespace, String string) {
return getHashUuid(namespace, string, MESSAGE_DIGEST_MD5, VERSION_3);
}
public static UUID getSha1Uuid(UUID namespace, String string) {
return getHashUuid(namespace, string, MESSAGE_DIGEST_SHA1, VERSION_5);
}
private static byte[] toBytes(final long number) {
return new byte[] { (byte) (number >>> 56), (byte) (number >>> 48), (byte) (number >>> 40),
(byte) (number >>> 32), (byte) (number >>> 24), (byte) (number >>> 16), (byte) (number >>> 8),
(byte) (number) };
}
private static long toNumber(final byte[] bytes, final int start, final int length) {
long result = 0;
for (int i = start; i < length; i++) {
result = (result << 8) | (bytes[i] & 0xff);
}
return result;
}
/**
* For tests!
*/
public static void main(String[] args) {
String string = "JUST_A_TEST_STRING";
UUID namespace = UUID.randomUUID(); // A custom name space
System.out.println("Java's generator");
System.out.println("UUID.nameUUIDFromBytes(): '" + UUID.nameUUIDFromBytes(string.getBytes()) + "'");
System.out.println();
System.out.println("This generator");
System.out.println("HashUuidCreator.getMd5Uuid(): '" + HashUuidCreator.getMd5Uuid(string) + "'");
System.out.println("HashUuidCreator.getSha1Uuid(): '" + HashUuidCreator.getSha1Uuid(string) + "'");
System.out.println();
System.out.println("This generator WITH name space");
System.out.println("HashUuidCreator.getMd5Uuid(): '" + HashUuidCreator.getMd5Uuid(namespace, string) + "'");
System.out.println("HashUuidCreator.getSha1Uuid(): '" + HashUuidCreator.getSha1Uuid(namespace, string) + "'");
}
}
This is the output:
// Java's generator
UUID.nameUUIDFromBytes(): '9e120341-627f-32be-8393-58b5d655b751'
// This generator
HashUuidCreator.getMd5Uuid(): '9e120341-627f-32be-8393-58b5d655b751'
HashUuidCreator.getSha1Uuid(): 'e4586bed-032a-5ae6-9883-331cd94c4ffa'
// This generator WITH name space
HashUuidCreator.getMd5Uuid(): '2b098683-03c9-3ed8-9426-cf5c81ab1f9f'
HashUuidCreator.getSha1Uuid(): '1ef568c7-726b-58cc-a72a-7df173463bbb'
ALTERNATE GENERATOR
You can also use the uuid-creator
library. See these examples:
// Create a random-based UUID
UUID uuid = UuidCreator.getRandomBased();
// Create a name based UUID (SHA1)
String name = "JUST_A_TEST_STRING";
UUID uuid = UuidCreator.getNameBasedSha1(name);
Project page: https://github.com/f4b6a3/uuid-creator
The way I'm currently doing this is a bit shorter than those already suggested and as far as I can tell gives the desired result:
var index = haystack.ToList().IndexOf(needle);
It's a bit clunky, but it does the job and is fairly concise.
you could do:
file.write(your_string + '\n')
as suggested by another answer, but why using string concatenation (slow, error-prone) when you can call file.write
twice:
file.write(your_string)
file.write("\n")
note that writes are buffered so it amounts to the same thing.
Try below code to set view on specific location :-
TextView textView = new TextView(getActivity());
textView.setId(R.id.overflowCount);
textView.setText(count + "");
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
textView.setTextColor(getActivity().getResources().getColor(R.color.white));
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// to handle click
}
});
// set background
textView.setBackgroundResource(R.drawable.overflow_menu_badge_bg);
// set apear
textView.animate()
.scaleXBy(.15f)
.scaleYBy(.15f)
.setDuration(700)
.alpha(1)
.setInterpolator(new BounceInterpolator()).start();
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
layoutParams.topMargin = 100; // margin in pixels, not dps
layoutParams.leftMargin = 100; // margin in pixels, not dps
textView.setLayoutParams(layoutParams);
// add into my parent view
mainFrameLaout.addView(textView);
Go to the project explorer block ... right click on project name select "Build Path"-----------> "Configuration Build Path"
then the pop up window will get open.
in this pop up window you will find 4 tabs. 1)source 2) project 3)Library 4)order and export
Click on 1) Source
select the project (under which that file is present which you want to compile)
and then click on ok....
Go to the workspace location of the project open a bin folder and search that class file ...
you will get that java file compiled...
just to cross verify check the changed timing.
hope this will help.
Thanks.
If it is a list of parameters from existing SQL table, for example ID list from existing Table1, then you can try this:
select distinct ID
FROM Table1
where
ID in (1, 1, 1, 2, 5, 1, 6)
ORDER BY ID;
Or, if you need List of parameters as a SQL Table constant(variable), try this:
WITH Id_list AS (
select ID
FROM Table1
where
ID in (1, 1, 1, 2, 5, 1, 6)
)
SELECT distinct * FROM Id_list
ORDER BY ID;
If you are trying to clear out a receive buffer for something that receives strings I have found the best way is to use memset as described above. The reason is that no matter how big the next received string is (limited to sizeof buffer of course), it will automatically be an asciiz string if written into a buffer that has been pre-zeroed.
<input class="text-box single-line" data-val="true" data-val-required="Name is required."
id="Name1" name="Name" type="text" value="">
$('#Name1').keypress(function () {
if (this.value.length >= 5) return false;
});
I know this post is older, but haven't seen a solution that provides the actual information, so I want to share what I use for SQL Server 2012 and above. the link below leads to the screenshot showing the information.
First (so no time is wasted):
SQL Server 2000:
SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')
SQL Server 2005+
The "SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')" is not in use anymore. You can see more details on MSFT documentation: https://docs.microsoft.com/en-us/sql/t-sql/functions/serverproperty-transact-sql?view=sql-server-2017
SQL Server 2005 - 2008R2 you would have to:
Using PowerShell: https://www.ryadel.com/en/sql-server-retrieve-product-key-from-an-existing-installation/
Using TSQL (you would need to know the registry key path off hand): https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-server-registry-transact-sql?view=sql-server-2017
SQL Server 2012+
Now, you can extract SQL Server Licensing information from the SQL Server Error Log, granted it may not be formatted the way you want, but the information is there and can be parsed, along with more descriptive information that you probably didn't expect.
EXEC sp_readerrorlog @p1 = 0
,@p2 = 1
,@p3 = N'licensing'
NOTE: I tried pasting the image directly, but since I am new at stakoverflow we have to follow the link below.
There is an easy workaround for this problem
What you need to do, is format your dates as DD/MM/YYYY (or whichever way around you like)
Insert a column next to the time and date columns, put a formula in this column that adds them together. e.g. =A5+B5.
Format this inserted column into DD/MM/YYYY hh:mm:ss which can be found in the custom category on the formatting section
Plot a scatter graph
Badabing badaboom
If you are unhappy with this workaround, learn to use GNUplot :)
The syntax for creating a new table is
CREATE TABLE new_table
AS
SELECT *
FROM old_table
This will create a new table named new_table
with whatever columns are in old_table
and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.
SELECT INTO
is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.
This works for me in Swift:
navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]
For example css files are in folder named CSS
and html files are in folder HTML
, and both these are in folder named XYZ
means we refer css files in html as
<link rel="stylesheet" type="text/css" href="./../CSS/style.css" />
Here ..
moves up to HTML
and .
refers to the current directory XYZ
---by this logic you would just reference as:
<link rel="stylesheet" type="text/css" href="CSS/style.css" />
To answer the original question: yes, you can access the index value of a row in apply()
. It is available under the key name
and requires that you specify axis=1
(because the lambda processes the columns of a row and not the rows of a column).
Working example (pandas 0.23.4):
>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
b c
a
1 2 3
4 5 6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
b c index_x10
a
1 2 3 10
4 5 6 40
For Mul, this was also helpful documentation to me - http://grokbase.com/t/mysql/mysql/9987k2ew41/key-field-mul-newbie-question
"MUL means that the key allows multiple rows to have the same value. That is, it's not a UNIque key."
For example, let's say you have two models, Post and Comment. Post has a has_many relationship with Comment. It would make sense then for the Comment table to have a MUL key(Post id) because many comments can be attributed to the same Post.
.xlsx
loads 4 times longer than .xlsb
and saves 2 times longer and has 1.5 times a bigger file. I tested this on a generated worksheet with 10'000 rows * 1'000 columns = 10'000'000 (10^7) cells of simple chained =…+1
formulas:
?--------------------------------?
¦ ¦ .xlsx ¦ .xlsb ¦
¦--------------+--------+--------¦
¦ loading time ¦ 165s ¦ 43s ¦
+--------------+--------+--------¦
¦ saving time ¦ 115s ¦ 61s ¦
+--------------+--------+--------¦
¦ file size ¦ 91 MB ¦ 65 MB ¦
?--------------------------------?
(Hardware: Core2Duo 2.3 GHz, 4 GB RAM, 5.400 rpm SATA II HD; Windows 7, under somewhat heavy load from other processes.)
Beside this, there should be no differences. More precisely,
both formats support exactly the same feature set
cites this blog post from 2006-08-29. So maybe the info that .xlsb
does not support Ribbon code is newer than the upper citation, but I figure that forum source of yours is just wrong. When cracking open the binary file, it seems to condensedly mimic the OOXML file structure 1-to-1: Blog article from 2006-08-07
Put all the divs in a individual table cells and set the table style to padding: 5px;
.
E.g.
<table style="width: 100%; padding: 5px;">_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>_x000D_
<div style="background-color: red;">A</div>_x000D_
</td>_x000D_
<td>_x000D_
<div style="background-color: orange;">B</div>_x000D_
</td>_x000D_
<td>_x000D_
<div style="background-color: green;">C</div>_x000D_
</td>_x000D_
<td>_x000D_
<div style="background-color: blue;">D</div>_x000D_
</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
NoClassDefFound error is a nebulous error and is often hiding a more serious issue. It is not the same as ClassNotFoundException (which is thrown when the class is just plain not there).
NoClassDefFound may indicate the class is not there, as the javadocs indicate, but it is typically thrown when, after the classloader has loaded the bytes for the class and calls "defineClass" on them. Also carefully check your full stack trace for other clues or possible "cause" Exceptions (though your particular backtrace shows none).
The first place to look when you get a NoClassDefFoundError is in the static bits of your class i.e. any initialization that takes place during the defining of the class. If this fails it will throw a NoClassDefFoundError - it's supposed to throw an ExceptionInInitializerError and indicate the details of the problem but in my experience, these are rare. It will only do the ExceptionInInitializerError the first time it tries to define the class, after that it will just throw NoClassDefFound. So look at earlier logs.
I would thus suggest looking at the code in that HibernateTransactionInterceptor line and seeing what it is requiring. It seems that it is unable to define the class SpringFactory. So maybe check the initialization code in that class, that might help. If you can debug it, stop it at the last line above (17) and debug into so you can try find the exact line that is causing the exception. Also check higher up in the log, if you very lucky there might be an ExceptionInInitializerError.
There isn't anything built-in, but you can easily create your own extension method to do it:
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (source == null) throw new ArgumentNullException("source");
if (action == null) throw new ArgumentNullException("action");
foreach (T item in source)
{
action(item);
}
}
Since I just lost two days of my life trying to solve for tryCatch for an irr function, I thought I should share my wisdom (and what is missing). FYI - irr is an actual function from FinCal in this case where got errors in a few cases on a large data set.
Set up tryCatch as part of a function. For example:
irr2 <- function (x) {
out <- tryCatch(irr(x), error = function(e) NULL)
return(out)
}
For the error (or warning) to work, you actually need to create a function. I originally for error part just wrote error = return(NULL)
and ALL values came back null.
Remember to create a sub-output (like my "out") and to return(out)
.
I would use filter()
, take Lukasz's example:
>>> lst = [1, 2, 3, 4, 1, 4, 1]
>>> len(filter(lambda x: x==1, lst))
3
Most of the answers for this question can not helped me in 2020.
This notification from download site of Oracle may be the reason:
Important Oracle JDK License Update
The Oracle JDK License has changed for releases starting April 16, 2019.
I try to google a little bit and those tutorials below helped me a lot.
Remove completely the previous version of JVM installed on your PC.
sudo update-alternatives --remove-all java
sudo update-alternatives --remove-all javac
sudo update-alternatives --remove-all javaws
# /usr/lib/jvm/jdk1.7.0 is the path you installed the previous version of JVM on your PC
sudo rm -rf /usr/lib/jvm/jdk1.7.0
Check to see whether java is uninstalled or not
java -version
1.8.0_251
. Pay attention to this value, you may need it to edit commands in this answer when Java 8 is upgraded to another version.cd /usr/lib/jvm
sudo tar xzf ~/Downloads/jdk-8u251-linux-x64.tar.gz
sudo gedit /etc/environment
:/usr/lib/jvm/jdk1.8.0_251/bin:/usr/lib/jvm/jdk1.8.0_251/jre/bin
J2SDKDIR="/usr/lib/jvm/jdk1.8.0_251"
J2REDIR="/usr/lib/jvm/jdk1.8.0_251/jre"
JAVA_HOME="/usr/lib/jvm/jdk1.8.0_251"
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.8.0_251/bin/java" 0
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.8.0_251/bin/javac" 0
sudo update-alternatives --set java /usr/lib/jvm/jdk1.8.0_251/bin/java
sudo update-alternatives --set javac /usr/lib/jvm/jdk1.8.0_251/bin/javac
update-alternatives --list java
update-alternatives --list javac
You can also use as many classes as needed on a tag, but an id must be unique to the document. Also be careful of using too many divs, when another more semantic tag can do the job.
<p id="unique" class="x y z">Styled paragraph</p>
Using file glob also it will work. There is some syntax error in the code you posted. I have modified and tested this should work.
- name: remove web dir contents
file:
path: "{{ item }}"
state: absent
with_fileglob:
- "/home/mydata/web/*"
Use bytearray
:
with open("img.png", "rb") as image:
f = image.read()
b = bytearray(f)
print b[0]
You can also have a look at struct which can do many conversions of that kind.
All the answers here have good working explanation of hashable objects in python, but I believe one needs to understand the term Hashing first.
Hashing is a concept in computer science which is used to create high performance, pseudo random access data structures where large amount of data is to be stored and accessed quickly.
For example, if you have 10,000 phone numbers, and you want to store them in an array (which is a sequential data structure that stores data in contiguous memory locations, and provides random access), but you might not have the required amount of contiguous memory locations.
So, you can instead use an array of size 100, and use a hash function to map a set of values to same indices, and these values can be stored in a linked list. This provides a performance similar to an array.
Now, a hash function can be as simple as dividing the number with the size of the array and taking the remainder as the index.
For more detail refer to https://en.wikipedia.org/wiki/Hash_function
Here is another good reference: http://interactivepython.org/runestone/static/pythonds/SortSearch/Hashing.html
I also faced the same problem and the problem was that the libraries were missing in some of the following files.
settings.gradle, app/build.gradle, package.json, MainApplication.java
Suppose the library is react-native-vector-icons then it should be mentioned in following files;
compile project(':react-native-vector-icons')
include ':react-native-vector-icons' project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')
Import the dependency: import com.oblador.vectoricons.VectorIconsPackage;
and then add: new VectorIconsPackage() in getPackages() method.
Matching any text but those matching a pattern is usually achieved with splitting the string with the regex pattern.
Examples:
Regex.Split(text, @"red|green|blue")
or, to get rid of empty values, Regex.Split(text, @"red|green|blue").Where(x => !string.IsNullOrEmpty(x))
(see demo)Regex.Split(text, "red|green|blue")
or, to remove empty items, Regex.Split(text, "red|green|blue").Where(Function(s) Not String.IsNullOrWhitespace(s))
(see demo, or this demo where LINQ is supported)text.split(/red|green|blue/)
(no need to use g
modifier here!) (to get rid of empty values, use text.split(/red|green|blue/).filter(Boolean)
), see demotext.split("red|green|blue")
, or - to keep all trailing empty items - use text.split("red|green|blue", -1)
, or to remove all empty items use more code to remove them (see demo)text.split(/red|green|blue/)
, to get all trailing items use text.split(/red|green|blue/, -1)
and to remove all empty items use text.split(/red|green|blue/).findAll {it != ""})
(see demo)text.split(Regex("red|green|blue"))
or, to remove blank items, use text.split(Regex("red|green|blue")).filter{ !it.isBlank() }
, see demotext.split("red|green|blue")
, or to keep all trailing empty items, use text.split("red|green|blue", -1)
and to remove all empty items, use text.split("red|green|blue").filter(_.nonEmpty)
(see demo)text.split(/red|green|blue/)
, to get rid of empty values use .split(/red|green|blue/).reject(&:empty?)
(and to get both leading and trailing empty items, use -1
as the second argument, .split(/red|green|blue/, -1)
) (see demo)my @result1 = split /red|green|blue/, $text;
, or with all trailing empty items, my @result2 = split /red|green|blue/, $text, -1;
, or without any empty items, my @result3 = grep { /\S/ } split /red|green|blue/, $text;
(see demo)preg_split('~red|green|blue~', $text)
or preg_split('~red|green|blue~', $text, -1, PREG_SPLIT_NO_EMPTY)
to output no empty items (see demo)re.split(r'red|green|blue', text)
or, to remove empty items, list(filter(None, re.split(r'red|green|blue', text)))
(see demo)regexp.MustCompile("red|green|blue").Split(text, -1)
, and if you need to remove empty items, use this code. See Go demo.NOTE: If you patterns contain capturing groups, regex split functions/methods may behave differently, also depending on additional options. Please refer to the appropriate split method documentation then.
Another Solution in Case You Don't Have Control Over Dynamic Content
This works if you didn't load your element through a directive (ie. like in the example in the commented jsfiddles).
Wrap up Your Content
Wrap your content in a div so that you can select it if you are using JQuery. You an also opt to use native javascript to get your element.
<div class="selector">
<grid-filter columnname="LastNameFirstName" gridname="HomeGrid"></grid-filter>
</div>
Use Angular Injector
You can use the following code to get a reference to $compile if you don't have one.
$(".selector").each(function () {
var content = $(this);
angular.element(document).injector().invoke(function($compile) {
var scope = angular.element(content).scope();
$compile(content)(scope);
});
});
Summary
The original post seemed to assume you had a $compile reference handy. It is obviously easy when you have the reference, but I didn't so this was the answer for me.
One Caveat of the previous code
If you are using a asp.net/mvc bundle with minify scenario you will get in trouble when you deploy in release mode. The trouble comes in the form of Uncaught Error: [$injector:unpr] which is caused by the minifier messing with the angular javascript code.
Here is the way to remedy it:
Replace the prevous code snippet with the following overload.
...
angular.element(document).injector().invoke(
[
"$compile", function($compile) {
var scope = angular.element(content).scope();
$compile(content)(scope);
}
]);
...
This caused a lot of grief for me before I pieced it together.
Just start from there that in CSS, if you repeat 2 values or more, always last one gets applied, unless using !important
tag, but at the same time avoid using !important
as much as you can, so in your case that's the problem, so the second transform override the first one in this case...
So how you can do what you want then?...
Don't worry, transform accepts multiple values at the same time... So this code below will work:
li:nth-child(2) {
transform: rotate(15deg) translate(-20px, 0px); //multiple
}
If you like to play around with transform run the iframe from MDN below:
<iframe src="https://interactive-examples.mdn.mozilla.net/pages/css/transform.html" class="interactive " width="100%" frameborder="0" height="250"></iframe>
_x000D_
Look at the link below for more info:
For current ActiveRecord (4.2.4+) there is a method to_hash
on the Result
object that returns an array of hashes. You can then map over it and convert to symbolized hashes:
# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
{"id" => 2, "title" => "title_2", "body" => "body_2"},
...
]
result.to_hash.map(&:symbolize_keys)
# => [{:id => 1, :title => "title_1", :body => "body_1"},
{:id => 2, :title => "title_2", :body => "body_2"},
...
]
I suppose I should expand this answer, now that I'm older and wiser and know what's going on. Better late than never.
You can add a property to a class dynamically. But that's the catch: you have to add it to the class.
>>> class Foo(object):
... pass
...
>>> foo = Foo()
>>> foo.a = 3
>>> Foo.b = property(lambda self: self.a + 1)
>>> foo.b
4
A property
is actually a simple implementation of a thing called a descriptor. It's an object that provides custom handling for a given attribute, on a given class. Kinda like a way to factor a huge if
tree out of __getattribute__
.
When I ask for foo.b
in the example above, Python sees that the b
defined on the class implements the descriptor protocol—which just means it's an object with a __get__
, __set__
, or __delete__
method. The descriptor claims responsibility for handling that attribute, so Python calls Foo.b.__get__(foo, Foo)
, and the return value is passed back to you as the value of the attribute. In the case of property
, each of these methods just calls the fget
, fset
, or fdel
you passed to the property
constructor.
Descriptors are really Python's way of exposing the plumbing of its entire OO implementation. In fact, there's another type of descriptor even more common than property
.
>>> class Foo(object):
... def bar(self):
... pass
...
>>> Foo().bar
<bound method Foo.bar of <__main__.Foo object at 0x7f2a439d5dd0>>
>>> Foo().bar.__get__
<method-wrapper '__get__' of instancemethod object at 0x7f2a43a8a5a0>
The humble method is just another kind of descriptor. Its __get__
tacks on the calling instance as the first argument; in effect, it does this:
def __get__(self, instance, owner):
return functools.partial(self.function, instance)
Anyway, I suspect this is why descriptors only work on classes: they're a formalization of the stuff that powers classes in the first place. They're even the exception to the rule: you can obviously assign descriptors to a class, and classes are themselves instances of type
! In fact, trying to read Foo.bar
still calls property.__get__
; it's just idiomatic for descriptors to return themselves when accessed as class attributes.
I think it's pretty cool that virtually all of Python's OO system can be expressed in Python. :)
Oh, and I wrote a wordy blog post about descriptors a while back if you're interested.
The iteration order for objects follows a certain set of rules since ES2015, but it does not (always) follow the insertion order. Simply put, the iteration order is a combination of the insertion order for strings keys, and ascending order for number-like keys:
// key order: 1, foo, bar
const obj = { "foo": "foo", "1": "1", "bar": "bar" }
Using an array or a Map
object can be a better way to achieve this. Map
shares some similarities with Object
and guarantees the keys to be iterated in order of insertion, without exception:
The keys in Map are ordered while keys added to object are not. Thus, when iterating over it, a Map object returns keys in order of insertion. (Note that in the ECMAScript 2015 spec objects do preserve creation order for string and Symbol keys, so traversal of an object with ie only string keys would yield keys in order of insertion)
As a note, properties order in objects weren’t guaranteed at all before ES2015. Definition of an Object from ECMAScript Third Edition (pdf):
4.3.3 Object
An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.
pip <command> --user
changes the scope of the current pip command to work on the current user account's local python package install location, rather than the system-wide package install location, which is the default.
This only really matters on a multi-user machine. Anything installed to the system location will be visible to all users, so installing to the user location will keep that package installation separate from other users (they will not see it, and would have to install it themselves separately to use it). Because there can be version conflicts, installing a package with dependencies needed by other packages can cause problems, so it's best not to push all packages a given user uses to the system install location.
--user
location. It will be installed to a different folder, that may or may not need to be added to the path, depending on the package and how it's used (many packages install command-line tools that must be on the path to run from a shell).--user
is preferred to using root/sudo or requiring administrator installation and affecting the Python environment of every user, except in cases of general packages that the administrator wants to make available to all users by default.
apt
, rather than pip
.venv
command in the Python VENV docs.The --user
option in an active venv/virtualenv environment will install to the local user python location (same as without a virtual environment).
Packages are installed to the virtual environment by default, but if you use --user
it will force it to install outside the virtual environments, in the users python script directory (in Windows, this currently is c:\users\<username>\appdata\roaming\python\python37\scripts
for me with Python 3.7).
However, you won't be able to access a system or user install from within virtual environment (even if you used --user
while in a virtual environment).
If you install a virtual environment with the --system-site-packages
argument, you will have access to the system script folder for python. I believe this included the user python script folder as well, but I'm unsure. However, there may be unintended consequences for this and it is not the intended way to use virtual environments.
You can find the location of the user install folder for python with python -m site --user-base
. I'm finding conflicting information in Q&A's, the documentation and actually using this command on my PC as to what the defaults are, but they are underneath the user home directory (~
shortcut in *nix, and c:\users\<username>
typically for Windows).
The --user
option is not a valid for every command. For example pip uninstall
will find and uninstall packages wherever they were installed (in the user folder, virtual environment folder, etc.) and the --user
option is not valid.
Things installed with pip install --user
will be installed in a local location that will only be seen by the current user account, and will not require root access (on *nix) or administrator access (on Windows).
The --user
option modifies all pip
commands that accept it to see/operate on the user install folder, so if you use pip list --user
it will only show you packages installed with pip install --user
.
sc queryex <service name>
taskkill /F /PID <Service PID>
eg
A lot has been said already, but to make it simple, here's my take. Interfaces are intended to have method contracts to be implemented by the consumers or classes and not to have fields to store values.
You may argue that then why properties are allowed? So the simple answer is - properties are internally defined as methods only.
This is similar to the answer I posted on: Preview a Git push
Drop these functions into your Bash profile:
You can use this like:
This will work with any branch.
function parse_git_branch {
git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'
}
function gbin {
echo branch \($1\) has these commits and \($(parse_git_branch)\) does not
git log ..$1 --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local
}
function gbout {
echo branch \($(parse_git_branch)\) has these commits and \($1\) does not
git log $1.. --no-merges --format='%h | Author:%an | Date:%ad | %s' --date=local
}
If what you want is the total number of records in the table appended to each row you can do something like
SELECT *
FROM my_table
CROSS JOIN (SELECT COUNT(*) AS COUNT_OF_RECS_IN_MY_TABLE
FROM MY_TABLE)
I have a method that does it for me.
The method takes UIButton
and makes the image aspect fit.
-(void)makeImageAspectFitForButton:(UIButton*)button{
button.imageView.contentMode=UIViewContentModeScaleAspectFit;
button.contentHorizontalAlignment=UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment=UIControlContentVerticalAlignmentFill;
}
If you keep track of the tail node, you don't need to loop through every element in the list.
Just update the tail to point to the new node:
AddValueToListEnd(value) {
var node = new Node(value);
if(!this.head) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node; //point old tail to new node
}
this.tail = node; //now set the new node as the new tail
}
In plain English:
JS will think that the 0 is a string, which it actually is, to convert it to a int, use the: parseInt() function, like:
var numberAsInt = parseInt(number, 10);
// Second arg is radix, 10 is decimal.
If the number is not possible to convert to a int, it will return NaN, so I would recommend a check for that too in code used in production or at least if you are not 100% sure of the input.
Just download composer and install phpMailler autoloader.php
https://github.com/PHPMailer/PHPMailer/blob/master/composer.json
once composer is loaded use below code:
require_once("phpMailer/class.phpmailer.php");
require_once("phpMailer/PHPMailerAutoload.php");
$mail = new PHPMailer(true);
$mail->SMTPDebug = true;
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Username = 'youremail id';
$mail->Password = 'youremail password';
$mail_from = "youremail id";
$subject = "Your Subject";
$body = "email body";
$mail_to = "receiver_email";
$mail->IsSMTP();
try {
$mail->Host= "smtp.your.com";
$mail->Port = "Your SMTP Port No";// ssl port :465,
$mail->Debugoutput = 'html';
$mail->AddAddress($mail_to, "receiver_name");
$mail->SetFrom($mail_from,'AmpleChat Team');
$mail->Subject = $subject;
$mail->MsgHTML($body);
$mail->Send();
$emailreturn = 200;
} catch (phpmailerException $e) {
$emailreturn = $e->errorMessage();
} catch (Exception $e) {
$emailreturn = $e->getMessage();
}
echo $emailreturn;
Hope this will work.
This deals with computational round-off. You set the epsilon as desired:
bool IsInteger(float value)
{
return fabs(ceilf(value) - value) < EPSILON;
}
If you use file_put_contents you don't need to do a fopen -> fwrite -> fclose, the file_put_contents does all that for you. You should also check if the webserver has write rights in the directory where you are trying to write your "data.txt" file.
Depending on your PHP version (if it's old) you might not have the file_get/put_contents functions. Check your webserver log to see if any error appeared when you executed the script.
You simply have to use the filter
filter (see the documentation) :
<div id="totalPos">{{(tweets | filter:{polarity:'Positive'}).length}}</div>
<div id="totalNeut">{{(tweets | filter:{polarity:'Neutral'}).length}}</div>
<div id="totalNeg">{{(tweets | filter:{polarity:'Negative'}).length}}</div>
Make Rectangle a template and pass the typename on to Area:
template <typename T>
class Rectangle : public Area<T>
{
};
I know this is a very old question, but one guy here said that developed an extension method to use bulk insert with EF, and when I checked, I discovered that the library costs $599 today (for one developer). Maybe it makes sense for the entire library, however for just the bulk insert this is too much.
Here is a very simple extension method I made. I use that on pair with database first (do not tested with code first, but I think that works the same). Change YourEntities
with the name of your context:
public partial class YourEntities : DbContext
{
public async Task BulkInsertAllAsync<T>(IEnumerable<T> entities)
{
using (var conn = new SqlConnection(Database.Connection.ConnectionString))
{
await conn.OpenAsync();
Type t = typeof(T);
var bulkCopy = new SqlBulkCopy(conn)
{
DestinationTableName = GetTableName(t)
};
var table = new DataTable();
var properties = t.GetProperties().Where(p => p.PropertyType.IsValueType || p.PropertyType == typeof(string));
foreach (var property in properties)
{
Type propertyType = property.PropertyType;
if (propertyType.IsGenericType &&
propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propertyType = Nullable.GetUnderlyingType(propertyType);
}
table.Columns.Add(new DataColumn(property.Name, propertyType));
}
foreach (var entity in entities)
{
table.Rows.Add(
properties.Select(property => property.GetValue(entity, null) ?? DBNull.Value).ToArray());
}
bulkCopy.BulkCopyTimeout = 0;
await bulkCopy.WriteToServerAsync(table);
}
}
public void BulkInsertAll<T>(IEnumerable<T> entities)
{
using (var conn = new SqlConnection(Database.Connection.ConnectionString))
{
conn.Open();
Type t = typeof(T);
var bulkCopy = new SqlBulkCopy(conn)
{
DestinationTableName = GetTableName(t)
};
var table = new DataTable();
var properties = t.GetProperties().Where(p => p.PropertyType.IsValueType || p.PropertyType == typeof(string));
foreach (var property in properties)
{
Type propertyType = property.PropertyType;
if (propertyType.IsGenericType &&
propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propertyType = Nullable.GetUnderlyingType(propertyType);
}
table.Columns.Add(new DataColumn(property.Name, propertyType));
}
foreach (var entity in entities)
{
table.Rows.Add(
properties.Select(property => property.GetValue(entity, null) ?? DBNull.Value).ToArray());
}
bulkCopy.BulkCopyTimeout = 0;
bulkCopy.WriteToServer(table);
}
}
public string GetTableName(Type type)
{
var metadata = ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace;
var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));
var entityType = metadata
.GetItems<EntityType>(DataSpace.OSpace)
.Single(e => objectItemCollection.GetClrType(e) == type);
var entitySet = metadata
.GetItems<EntityContainer>(DataSpace.CSpace)
.Single()
.EntitySets
.Single(s => s.ElementType.Name == entityType.Name);
var mapping = metadata.GetItems<EntityContainerMapping>(DataSpace.CSSpace)
.Single()
.EntitySetMappings
.Single(s => s.EntitySet == entitySet);
var table = mapping
.EntityTypeMappings.Single()
.Fragments.Single()
.StoreEntitySet;
return (string)table.MetadataProperties["Table"].Value ?? table.Name;
}
}
You can use that against any collection that inherit from IEnumerable
, like that:
await context.BulkInsertAllAsync(items);
I would do it with awk, e.g.
awk '/[0-9]+/ { a = a $0 ";" } END { print a }' file.txt
(a disadvantage is that a is "accumulated" in memory).
EDIT
Forgot about printf! So also
awk '/[0-9]+/ { printf "%s;", $0 }' file.txt
or likely better, what it was already given in the other ans using awk.
You can use text-align: center; line-height: 65px;
CSS
.loginBtn {
background:url(images/loginBtn-center.jpg) repeat-x;
width:175px;
height:65px;
margin:20px auto;
border-radius:10px;
-webkit-border-radius:10px;
box-shadow:0 1px 2px #5e5d5b;
text-align: center; <--------- Here
line-height: 65px; <--------- Here
}
And remember to use parenthesis!
Keep in mind that &
operator takes a precedence over operators such as >
or <
etc. That is why
4 < 5 & 6 > 4
evaluates to False
. Therefore if you're using pd.loc
, you need to put brackets around your logical statements, otherwise you get an error. That's why do:
df.loc[(df['A'] > 10) & (df['B'] < 15)]
instead of
df.loc[df['A'] > 10 & df['B'] < 15]
which would result in
TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]
For the sake of completeness, let me mention that there are some places (on a Windows PC) to look for javaw.exe
in case it is not found in the path:
(Still Reimeus' suggestion should be your first attempt.)
1.
Java usually stores it's location in Registry, under the following key:
HKLM\Software\JavaSoft\Java Runtime Environement\<CurrentVersion>\JavaHome
2.
Newer versions of JRE/JDK, seem to also place a copy of javaw.exe
in 'C:\Windows\System32', so one might want to check there too (although chances are, if it is there, it will be found in the path as well).
3.
Of course there are the "usual" install locations:
[Note, that for older versions of Windows (XP, Vista(?)), this will only help on english versions of the OS. Fortunately, on later version of Windows "Program Files" will point to the directory regardless of its "display name" (which is language-specific).]
A little while back, I wrote this piece of code to check for javaw.exe
in the aforementioned places. Maybe someone finds it useful:
static protected String findJavaw() {
Path pathToJavaw = null;
Path temp;
/* Check in Registry: HKLM\Software\JavaSoft\Java Runtime Environement\<CurrentVersion>\JavaHome */
String keyNode = "HKLM\\Software\\JavaSoft\\Java Runtime Environment";
List<String> output = new ArrayList<>();
executeCommand(new String[] {"REG", "QUERY", "\"" + keyNode + "\"",
"/v", "CurrentVersion"},
output);
Pattern pattern = Pattern.compile("\\s*CurrentVersion\\s+\\S+\\s+(.*)$");
for (String line : output) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
keyNode += "\\" + matcher.group(1);
List<String> output2 = new ArrayList<>();
executeCommand(
new String[] {"REG", "QUERY", "\"" + keyNode + "\"",
"/v", "JavaHome"},
output2);
Pattern pattern2
= Pattern.compile("\\s*JavaHome\\s+\\S+\\s+(.*)$");
for (String line2 : output2) {
Matcher matcher2 = pattern2.matcher(line2);
if (matcher2.find()) {
pathToJavaw = Paths.get(matcher2.group(1), "bin",
"javaw.exe");
break;
}
}
break;
}
}
try {
if (Files.exists(pathToJavaw)) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
/* Check in 'C:\Windows\System32' */
pathToJavaw = Paths.get("C:\\Windows\\System32\\javaw.exe");
try {
if (Files.exists(pathToJavaw)) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
/* Check in 'C:\Program Files\Java\jre*' */
pathToJavaw = null;
temp = Paths.get("C:\\Program Files\\Java");
if (Files.exists(temp)) {
try (DirectoryStream<Path> dirStream
= Files.newDirectoryStream(temp, "jre*")) {
for (Path path : dirStream) {
temp = Paths.get(path.toString(), "bin", "javaw.exe");
if (Files.exists(temp)) {
pathToJavaw = temp;
// Don't "break", in order to find the latest JRE version
}
}
if (pathToJavaw != null) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
}
/* Check in 'C:\Program Files (x86)\Java\jre*' */
pathToJavaw = null;
temp = Paths.get("C:\\Program Files (x86)\\Java");
if (Files.exists(temp)) {
try (DirectoryStream<Path> dirStream
= Files.newDirectoryStream(temp, "jre*")) {
for (Path path : dirStream) {
temp = Paths.get(path.toString(), "bin", "javaw.exe");
if (Files.exists(temp)) {
pathToJavaw = temp;
// Don't "break", in order to find the latest JRE version
}
}
if (pathToJavaw != null) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
}
/* Check in 'C:\Program Files\Java\jdk*' */
pathToJavaw = null;
temp = Paths.get("C:\\Program Files\\Java");
if (Files.exists(temp)) {
try (DirectoryStream<Path> dirStream
= Files.newDirectoryStream(temp, "jdk*")) {
for (Path path : dirStream) {
temp = Paths.get(path.toString(), "jre", "bin", "javaw.exe");
if (Files.exists(temp)) {
pathToJavaw = temp;
// Don't "break", in order to find the latest JDK version
}
}
if (pathToJavaw != null) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
}
/* Check in 'C:\Program Files (x86)\Java\jdk*' */
pathToJavaw = null;
temp = Paths.get("C:\\Program Files (x86)\\Java");
if (Files.exists(temp)) {
try (DirectoryStream<Path> dirStream
= Files.newDirectoryStream(temp, "jdk*")) {
for (Path path : dirStream) {
temp = Paths.get(path.toString(), "jre", "bin", "javaw.exe");
if (Files.exists(temp)) {
pathToJavaw = temp;
// Don't "break", in order to find the latest JDK version
}
}
if (pathToJavaw != null) {
return pathToJavaw.toString();
}
} catch (Exception ignored) {}
}
return "javaw.exe"; // Let's just hope it is in the path :)
}
Alternative way (but it's not python style. It's JS style)
{{ files and 'Update' or 'Continue' }}
By adding a few more headers I was able to get the data:
import urllib2,cookielib
site= "http://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/getHistoricalData.jsp?symbol=JPASSOCIAT&fromDate=1-JAN-2012&toDate=1-AUG-2012&datePeriod=unselected&hiddDwnld=true"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
req = urllib2.Request(site, headers=hdr)
try:
page = urllib2.urlopen(req)
except urllib2.HTTPError, e:
print e.fp.read()
content = page.read()
print content
Actually, it works with just this one additional header:
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
That should work. Better if you pass a function to val
:
$('#replyBox').val(function(i, text) {
return text + quote;
});
This way you avoid searching the element and calling val
twice.
Paste following link to directly under link button click event, otherwise use javascript to call code behind function
Protected Sub lnkOpen_Click(ByVal sender As Object, ByVal e As EventArgs)
System.Diagnostics.Process.Start(FilePath)
End Sub
I was getting this exception when I was pressing back button to cancel intent chooser on my map fragment activity. I resolved this by replacing the code of onResume()(where I was initializing the fragment and committing transaction) to onStart() and the app is working fine now. Hope it helps.
You are using
States states;
where as you should use
States *states;
Your init method should be like this
-(id)init {
if( (self = [super init]) ) {
pickedGlasses = 0;
}
return self;
}
Now finally when you are going to create an object for States class you should do it like this.
State *states = [[States alloc] init];
I am not saying this is the best way of doing this. But it may help you understand the very basic use of initializing objects.
Only use git rm --cached [file]
to remove a file from the index.
git reset <filename>
can be used to remove added files from the index given the files are never committed.
% git add First.txt
% git ls-files
First.txt
% git commit -m "First"
% git ls-files
First.txt
% git reset First.txt
% git ls-files
First.txt
NOTE: git reset First.txt
has no effect on index after the commit.
Which brings me to the topic of git restore --staged <file>
. It can be used to (presumably after the first commit) remove added files from the index given the files are never committed.
% git add Second.txt
% git status
On branch master
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: Second.txt
% git ls-files
First.txt
Second.txt
% git restore --staged Second.txt
% git ls-files
First.txt
% git add Second.txt
% git commit -m "Second"
% git status
On branch master
nothing to commit, working tree clean
% git ls-files
First.txt
Second.txt
Desktop/Test% git restore --staged .
Desktop/Test% git ls-files
First.txt
Second.txt
Desktop/Test% git reset .
Desktop/Test% git ls-files
First.txt
Second.txt
% git rm --cached -r .
rm 'First.txt'
rm 'Second.txt'
% git ls-files
tl;dr Look at last 15 lines. If you don't want to be confused with first commit, second commit, before commit, after commit.... always use git rm --cached [file]
The excellent (free trial) IcoFX allows you to create and edit icons, including multiple sizes up to 256x256, PNG compression, and transparency. I highly recommend it over most of the alternates.
Get your copy here: http://icofx.ro/ . It supports Windows XP onwards.
Windows automatically chooses the proper icon from the file, depending on where it is to be displayed.
For more information on icon design and the sizes/bit depths you should include, see these references:
If you want a copy of the HashMap you need to construct a new one with.
myobjectListB = new HashMap<Integer,myObject>(myobjectListA);
This will create a (shallow) copy of the map.
You can use org.apache.commons.io.IOUtils.toString(InputStream is, Charset chs)
to do that.
e.g.
IOUtils.toString(context.getResources().openRawResource(<your_resource_id>), StandardCharsets.UTF_8)
For adding the correct library:
Add the following to your app/build.gradle file:
dependencies { compile 'org.apache.directory.studio:org.apache.commons.io:2.4' }
or for the Maven repo see -> this link
For direct jar download see-> https://commons.apache.org/proper/commons-io/download_io.cgi
In Android Studio 1.1, the simplest way is to open your project manifest file
, then point to each part of the package name
that you want to change it and press
SHIFT + F6 , then choose rename package
and write the new name in the dialog box. That's all.
The reason to prefer Promises over callback functions is to have multiple callbacks and to avoid the problems like Callback Hell.
Callback hell (for more details, refer http://callbackhell.com/): Asynchronous javascript, or javascript that uses callbacks, is hard to get right intuitively. A lot of code ends up looking like this:
asyncCall(function(err, data1){
if(err) return callback(err);
anotherAsyncCall(function(err2, data2){
if(err2) return calllback(err2);
oneMoreAsyncCall(function(err3, data3){
if(err3) return callback(err3);
// are we done yet?
});
});
});
With Promises above code can be rewritten as below:
asyncCall()
.then(function(data1){
// do something...
return anotherAsyncCall();
})
.then(function(data2){
// do something...
return oneMoreAsyncCall();
})
.then(function(data3){
// the third and final async response
})
.fail(function(err) {
// handle any error resulting from any of the above calls
})
.done();
One more option, not exactly what you asked, but can be useful:
Go to Settings
-> Editor
-> File and code templates
-> Includes
tab (on the right). There is a template header for the new files, you can use the username here:
/**
* @author myname
*/
For system username use:
/**
* @author ${USER}
*/
If you installed from source, you can issue the following command:
sudo make uninstall
If you followed the instructions on https://github.com/nodejs/node/wiki to install to your $HOME/local/node, then you have to type the following before the line above:
./configure --prefix=$HOME/local/node
There is a ToArray() function on Values:
Foo[] arr = new Foo[dict.Count];
dict.Values.CopyTo(arr, 0);
But I don't think its efficient (I haven't really tried, but I guess it copies all these values to the array). Do you really need an Array? If not, I would try to pass IEnumerable:
IEnumerable<Foo> foos = dict.Values;
Here is my totally functional approach which avoids having to read and split lines. It makes use of the itertools
module:
itertools.imap
with map
import itertools
def readwords(mfile):
byte_stream = itertools.groupby(
itertools.takewhile(lambda c: bool(c),
itertools.imap(mfile.read,
itertools.repeat(1))), str.isspace)
return ("".join(group) for pred, group in byte_stream if not pred)
Sample usage:
>>> import sys
>>> for w in readwords(sys.stdin):
... print (w)
...
I really love this new method of reading words in python
I
really
love
this
new
method
of
reading
words
in
python
It's soo very Functional!
It's
soo
very
Functional!
>>>
I guess in your case, this would be the way to use the function:
with open('words.txt', 'r') as f:
for word in readwords(f):
print(word)
See:
The Difference Between a Program and a Script
A Script is also a program but without an opaque layer hiding the (source code) whereas a program is one having clothes, you can't see it's source code unless it is decompilable.
Scripts need other programs to execute them while programs don't need one.
I was looking for the same thing for a quick operation and found this question. I needed both 32-bit and 64-bit versions.
This is an older version but the links are from the Microsoft servers, it should be safe. The link for 32-bit version is also in a previous answer but the version number i get on the install is different, maybe the same link is updated with a newer version since 2013.
Cheksums are generated both locally and on VirusTotal, they match.
Debugging Tools for Windows (x64) (6.12.2.633)(VirusTotal Scan): http://download.microsoft.com/download/A/6/A/A6AC035D-DA3F-4F0C-ADA4-37C8E5D34E3D/setup/WinSDKDebuggingTools_amd64/dbg_amd64.msi (SHA-256:2e491bb98850abf9b9d2627185b57e048ba9b2410d68303698ac68c2daad9e5d)
Debugging Tools for Windows (x86) (6.12.2.633)(VirusTotal Scan): http://download.microsoft.com/download/A/6/A/A6AC035D-DA3F-4F0C-ADA4-37C8E5D34E3D/setup/WinSDKDebuggingTools/dbg_x86.msi (SHA-256:5a0f43281e51405408a043e2f94dd51782ef29671307d3538cfdff5b0e69d115)
I tested the 64 bit debugger with a 64 bit program that was compiled some years ago (~2012) and it works. Test is done on Windows 10 Pro 64 bit (v2004 Build 19041.207).
Linear scrolling animation to bottom. Pure JS, no JQuery. Maybe my solution will be helpful for someone.
let action_count = 8;
let speed_ms = 15;
let objDiv = document.getElementsByClassName('js_y5_area3').item(0);
let scroll_height = objDiv.scrollHeight;
let window_height = objDiv.offsetHeight;
let scroll_top = objDiv.scrollTop;
let need_scroll_top = scroll_height - window_height;
if (scroll_top < need_scroll_top)
{
let step = Math.ceil((need_scroll_top - scroll_top) / action_count);
let scrollInterval = setInterval(function()
{
scroll_top += step;
objDiv.scrollTop = scroll_top;
if (scroll_top >= need_scroll_top)
{
clearInterval(scrollInterval);
}
}, speed_ms);
}
You can change variables action_count
, speed_ms
to configure scrolling animation on your taste.
You should be pointing it towards the Developer
directory, not the Xcode application bundle. Run this:
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.
You could use val()
.
var value = $('#area1').val();
$('#VAL_DISPLAY').html(value);
Use the SC command, like this (you need to be on a command prompt to execute the commands in this post):
SC STOP shortservicename
SC DELETE shortservicename
Note: You need to run the command prompt as an administrator, not just logged in as the administrator, but also with administrative rights. If you get errors above about not having the necessary access rights to stop and/or delete the service, run the command prompt as an administrator. You can do this by searching for the command prompt on your start menu and then right-clicking and selecting "Run as administrator". Note to PowerShell users: sc
is aliased to set-content
. So sc delete service
will actually create a file called delete
with the content service
. To do this in Powershell, use sc.exe delete service
instead
If you need to find the short service name of a service, use the following command to generate a text file containing a list of services and their statuses:
SC QUERY state= all >"C:\Service List.txt"
For a more concise list, execute this command:
SC QUERY state= all | FIND "_NAME"
The short service name will be listed just above the display name, like this:
SERVICE_NAME: MyService
DISPLAY_NAME: My Special Service
And thus to delete that service:
SC STOP MyService
SC DELETE MyService
If you want to match the two words in either order, use:
gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)|(Failed.*VendorEnquiry)'
If Failed always comes after VendorEnquiry on the line, just use:
gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)'
I seem to recall having to use @GeneratedValue(strategy = GenerationType.IDENTITY)
to get Hibernate to use 'serial' columns on PostgreSQL.
You can first start IIS express from command line and give it a port with /port:port-number see other options.
Considering, you have epoch_time
available,
// for eg. epoch_time = 1487086694.213
var date = new Date(epoch_time * 1000); // multiply by 1000 for milliseconds
var date_string = date.toLocaleString('en-GB'); // 24 hour format
No, they are the same. But there is a difference between:
Test t; // create a Test called t
and
Test t(); // declare a function called t which returns a Test
This is because of the basic C++ (and C) rule: If something can possibly be a declaration, then it is a declaration.
Edit: Re the initialisation issues regarding POD and non-POD data, while I agree with everything that has been said, I would just like to point out that these issues only apply if the thing being new'd or otherwise constructed does not have a user-defined constructor. If there is such a constructor it will be used. For 99.99% of sensibly designed classes there will be such a constructor, and so the issues can be ignored.
When the other solutions did not work for you (Changing JVM version on Compiler settings and adding jvmTarget
into your build.gradle
), because of your .iml
files trying to force their configurations you can change the target platform from Project Settings.
File > Project Structure
Facets
under Project Settings
+
buttonTarget Platform
to JVM 1.8
(also it's better to check Use project settings
option)You can use one of the following:
DateTime.current.midnight
DateTime.current.beginning_of_day
DateTime.current.to_date
One way to run a process from a different directory to the working directory of your Java program is to change directory and then run the process in the same command line. You can do this by getting cmd.exe
to run a command line such as cd some_directory && some_program
.
The following example changes to a different directory and runs dir
from there. Admittedly, I could just dir
that directory without needing to cd
to it, but this is only an example:
import java.io.*;
public class CmdTest {
public static void main(String[] args) throws Exception {
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && dir");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
}
Note also that I'm using a ProcessBuilder
to run the command. Amongst other things, this allows me to redirect the process's standard error into its standard output, by calling redirectErrorStream(true)
. Doing so gives me only one stream to read from.
This gives me the following output on my machine:
C:\Users\Luke\StackOverflow>java CmdTest
Volume in drive C is Windows7
Volume Serial Number is D8F0-C934
Directory of C:\Program Files\Microsoft SQL Server
29/07/2011 11:03 <DIR> .
29/07/2011 11:03 <DIR> ..
21/01/2011 20:37 <DIR> 100
21/01/2011 20:35 <DIR> 80
21/01/2011 20:35 <DIR> 90
21/01/2011 20:39 <DIR> MSSQL10_50.SQLEXPRESS
0 File(s) 0 bytes
6 Dir(s) 209,496,424,448 bytes free
You can do this using additional effects as a part of jQuery-ui
$('.show_hide').click(function () {
$(".slidingDiv").toggle("slide");
});
You could use the refcodes-console
artifact at refcodes-console on REFCODES.ORG:
Option<String> r = new StringOptionImpl( "-r", null, "opt1", "..." );
Option<String> s = new StringOptionImpl( "-S", null, "opt2", "..." );
Operand<String> arg1 = new StringOperandImpl( "arg1", "..." );
Operand<String> arg2 = new StringOperandImpl( "arg2", "..." );
Operand<String> arg3 = new StringOperandImpl( "arg3", "..." );
Operand<String> arg4 = new StringOperandImpl( "arg4", "..." );
Switch test = new SwitchImpl( null, "--test", "..." );
Option<String> a = new StringOptionImpl( "-A", null, "opt3", "..." );
Condition theRoot = new AndConditionImpl( r, s, a, arg1, arg2, arg3, arg4,
test );
Create your arguments parser ArgsParserImpl
with your root condition:
ArgsParser theArgsParser = new ArgsParserImpl( theRoot );
theArgsParser.setName( "MyProgramm" );
theArgsParser.setSyntaxNotation( SyntaxNotation.GNU_POSIX );
Above you define your syntax, below you invoke the parser:
theArgsParser.printUsage();
theArgsParser.printSeparatorLn();
theArgsParser.printOptions();
theArgsParser.evalArgs( new String[] {
"-r", "RRRRR", "-S", "SSSSS", "11111", "22222", "33333", "44444",
"--test", "-A", "AAAAA"
} );
In case you provided some good descriptions, theArgsParser.printUsage()
will even show you the pretty printed usage:
Usage: MyProgramm -r <opt1> -S <opt2> -A <opt3> arg1 arg2 arg3 arg4 --test
In the above example all defined arguments must be passed by the user, else the parser will detect a wrong usage. In case the
--test
switch is to be optional (or any other argument), assigntheRoot
as follows:
theRoot = new AndConditionImpl( r, s, a, arg1, arg2, arg3, arg4, new OptionalImpl( test ) );
Then your syntax looks as follows:
Usage: MyProgramm -r <opt1> -S <opt2> -A <opt3> arg1 arg2 arg3 arg4 [--test]
The full example for your case you find in the StackOverFlowExamle. You can use AND, OR, XOR conditions and any kind of nesting ... hope this helps.
Evaluate the parsed arguments as follows:
r.getValue() );
orif (test.getValue() == true) ...
:
LOGGER.info( "r :=" + r.getValue() );
LOGGER.info( "S :=" + s.getValue() );
LOGGER.info( "arg1 :=" + arg1.getValue() );
LOGGER.info( "arg2 :=" + arg2.getValue() );
LOGGER.info( "arg3 :=" + arg3.getValue() );
LOGGER.info( "arg4 :=" + arg4.getValue() );
LOGGER.info( "test :=" + test.getValue() + "" );
LOGGER.info( "A :=" + a.getValue() );
Modify password for role postgres:
sudo -u postgres psql postgres
alter user postgres with password 'postgres';
Now connect to pgadmin using username postgres and password postgres
Now you can create roles & databases using pgAdmin
Semicolons (like dots, commas and parentheses) tend to cause religious wars. Still, they (or some similar symbol) are useful in any programming language for various reasons.
Practical: the ability to put several short commands that belong conceptually together on the same line. A program text that looks like a narrow snake has the opposite effect of what is intended by newlines and indentation, which is highlighting structure.
Conceptual: separation of concerns between pure syntax (in this case, for a sequence of commands) from presentation (e.g. newline), in the old days called "pretty-printing".
Observation: for highlighting structure, indentation could be augmented/replaced by vertical lines in the obvious way, serving as a "visual ruler" to see where an indentation begins and ends. Different colors (e.g. following the color code for resistors) may compensate for crowding.
I'm guessing that you meant to do this:
msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
# To concatenate strings in python, use ^
Cap A is 65 so:
MsgBox Chr(ActiveCell.Column + 64)
Found in: http://www.vbaexpress.com/forum/showthread.php?6103-Solved-get-column-letter
You can use datetime.date.today()
and convert the resulting datetime.date
object to a string:
from datetime import date
today = str(date.today())
print(today) # '2017-12-26'
SQL Server 2008 R2:
For an existing database that you wish to "restore: from a backup of a different database follow these steps:
I know this is an old question, but our solution is much simpler than what I see here. We use it for WCF calls with VS2010 and up. The string url can come from app settings or another source. In my case it is a drop down list where the user picks the server. TheService was configured through VS add service reference.
private void CallTheService( string url )
{
TheService.TheServiceClient client = new TheService.TheServiceClient();
client.Endpoint.Address = new System.ServiceModel.EndpointAddress(url);
var results = client.AMethodFromTheService();
}
Well, it's clearly not a number since it has dashes in it. The error message and the two comments tell you that it is a factor but the commentators are apparently waiting and letting the message sink in. Dirk is suggesting that you do this:
EPL2011_12$Date2 <- as.Date( as.character(EPL2011_12$Date), "%d-%m-%y")
After that you can do this:
EPL2011_12FirstHalf <- subset(EPL2011_12, Date2 > as.Date("2012-01-13") )
R date functions assume the format is either "YYYY-MM-DD" or "YYYY/MM/DD". You do need to compare like classes: date to date, or character to character.
currentDay = '2019-12-06';
currentDay = new Date(currentDay).add(Date.DAY, +1).format('Y-m-d');
This site explain step by step that what you need to do Certificates, Identifiers & Profiles and as your question
"Valid Signing identity not found"?
You need the private key that were used to sign the code base with provisioning profile. . If you don't have then you can generate a new signing request on the iOS developer portal.
For Export:
Xcode -> Organizer, select your team. Click Export. Specify a filename and a password, and click Save.`
For Import:
Xcode -> Organizer, select your team. Click Import. Select the file containing your code signing assets. Enter the password for the file, and click Open.
You can list down the entries (certificates details) with the keytool and even you don't need to mention the store type.
keytool -list -v -keystore cert.p12 -storepass <password>
Keystore type: PKCS12
Keystore provider: SunJSSE
Your keystore contains 1 entry
Alias name: 1
Creation date: Jul 11, 2020
Entry type: PrivateKeyEntry
Certificate chain length: 2
You can create a method somewhere
public static <T> T[] toArray(T... ts) {
return ts;
}
then use it
m(toArray("blah", "hey", "yo"));
for better look.
With little modification but almost similar approach to get the full file path of each sub folder
dataFolderPath = 'UCR_TS_Archive_2015/';
dirData = dir(dataFolderPath); %# Get the data for the current directory
dirIndex = [dirData.isdir]; %# Find the index for directories
fileList = {dirData(~dirIndex).name}'; %'# Get a list of the files
if ~isempty(fileList)
fileList = cellfun(@(x) fullfile(dataFolderPath,x),... %# Prepend path to files
fileList,'UniformOutput',false);
end
subDirs = {dirData(dirIndex).name}; %# Get a list of the subdirectories
validIndex = ~ismember(subDirs,{'.','..'}); %# Find index of subdirectories
%# that are not '.' or '..'
for iDir = find(validIndex) %# Loop over valid subdirectories
nextDir = fullfile(dataFolderPath,subDirs{iDir}); %# Get the subdirectory path
getAllFiles = dir(nextDir);
for k = 1:1:size(getAllFiles,1)
validFileIndex = ~ismember(getAllFiles(k,1).name,{'.','..'});
if(validFileIndex)
filePathComplete = fullfile(nextDir,getAllFiles(k,1).name);
fprintf('The Complete File Path: %s\n', filePathComplete);
end
end
end
I have a list of color names in range A2:A8, in column B I want to extract a distinct list of color names.
Follow the below given steps:
=IF(COUNTIF(A$2:A2,A2)=1,A2,””)
In the MongoDB Client, type:
db.Collection.updateMany({}, $set: {field1: 'field1', field2: 'field2'})
New in version 3.2
Params::
{}: select all records updated
Keyword argument multi
not taken
Product > Profile will launch Instruments and then you there should be a "Trace Template" named "Zombies". However this trace template is only available if the current build destination is the simulator - it will not be available if you have the destination set to your iOS device.
Also another thing to note is that there is no actual Zombies instrument in the instrument library. The zombies trace template actually consists of the Allocations instrument with the "Enable NSZombie detection" launch configuration set.
In my case, I was trying to build and get APK for an old Unity 3D project (so that I can play the game in my Android phone). I was using the most recent Android Studio version, and all the SDK packages I could download via SDK Manager in Android Studio. SDK Packages was located in
C:/Users/Onat/AppData/Local/Android/Sdk And the error message I got was the same except the JDK (Java Development Kit) version "jdk-12.0.2" . JDK was located in
C:\Program Files\Java\jdk-12.0.2 And Environment Variable in Windows was JAVA_HOME : C:\Program Files\Java\jdk-12.0.2
After 3 hours of research, I found out that Unity does not support JDK 10. As told in https://forum.unity.com/threads/gradle-build-failed-error-could-not-determine-java-version-from-10-0-1.532169/ . My suggestion is:
1.Uninstall unwanted JDK if you have one installed already. https://www.java.com/tr/download/help/uninstall_java.xml
2.Head to http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
3.Login to/Open a Oracle account if not already logged in.
4.Download the older but functional JDK 8 for your computer set-up(32 bit/64 bit, Windows/Linux etc.)
5.Install the JDK. Remember the installation path. (https://docs.oracle.com/cd/E19182-01/820-7851/inst_cli_jdk_javahome_t/)
6.If you are using Windows, Open Environment Variables and change Java Path via Right click My Computer/This PC>Properties>Advanced System Settings>Environment Variables>New>Variable Name: JAVA_HOME>Variable Value: [YOUR JDK Path, Mine was "C:\Program Files\Java\jdk1.8.0_221"]
7.In Unity 3D, press Edit > Preferences > External Tools and fill in the JDK path (Mine was "C:\Program Files\Java\jdk1.8.0_221").
8.Also, in the same pop-up, edit SDK Path. (Get it from Android Studio > SDK Manager > Android SDK > Android SDK Location.)
9.If needed, restart your computer for changes to take effect.
SELECT field1
, field2
, 'Test' AS field3
FROM Test
; // replace with simple quote '
There are two ways to get variable from URL in PHP:
When your URL is: http://www.example.com/index.php?id=7
you can get this id
via $_GET['id']
or $_REQUEST['id']
command and store in $id
variable.
Lest's take a look:
// url is www.example.com?id=7
//get id from url via $_GET['id'] command:
$id = $_GET['id']
same will be:
//get id from url via $_REQUEST['id'] command:
$id = $_REQUEST['id']
the difference is that variables can be passed to file via URL or via POST method.
if variable is passed through url, then you can get it with $_GET['variable_name']
or $_REQUEST['variable_name']
but if variable is posted, then you need to you $_POST['variable_name']
or $_REQUEST['variable_name']
So as you see $_REQUEST['variable_name']
can be used in both ways.
P.S: Also remember - never do like this: $results = mysql_query("SELECT * FROM next WHERE id=$id");
it may cause MySQL Injection and your database can be hacked.
Try to use:
$results = mysql_query("SELECT * FROM next WHERE id='".mysql_real_escape_string($id)."'");
The for loop iterates over the elements of the array, not its indexes. Suppose you have a list ar = [2, 4, 6]:
When you iterate over it with for i in ar:
the values of i will be 2, 4 and 6. So, when you try to access ar[i]
for the first value, it might work (as the last position of the list is 2, a[2] equals 6), but not for the latter values, as a[4] does not exist.
If you intend to use indexes anyhow, try using for index, value in enumerate(ar):
, then theSum = theSum + ar[index]
should work just fine.
The execution process is really confusing with recursive CTE, I found the best answer at https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx and the abstract of the CTE execution process is as below.
The semantics of the recursive execution is as follows:
Windows 8 64bit runs both 32bit and 64bit applications. You want chromedriver 32bit for the 32bit version of chrome you're using.
The current release of chromedriver (v2.16) has been mentioned as running much smoother since it's older versions (there were a lot of issues before). This post mentions this and some of the slight differences between chromedriver and running the normal firefox driver:
http://seleniumsimplified.com/2015/07/recent-course-source-code-changes-for-webdriver-2-46-0/
What you mentioned about "doesn't call main method" is an odd remark. You may want to elaborate.
<html>
<body>
<script type="text/javascript">
var str="http://xyz.html?ID={0}&TId={1}&STId={2}&RId={3},14,480,3,38";
document.write(FormatString(str));
function FormatString(str) {
var args = str.split(',');
for (var i = 0; i < args.length; i++) {
var reg = new RegExp("\\{" + i + "\\}", "");
args[0]=args[0].replace(reg, args [i+1]);
}
return args[0];
}
</script>
</body>
</html>
First and simple solution:
git push -f origin master
.git pull --allow-unrelated-histories //this might give you error but nothing to worry, next cmd will fix it
git add *
git commit -m "commit message"
git push
If this doesn't work then follow along
Will Delete all your commit history
Delete .git
directory from the folder.
Then execute these commands:
git init
git add .
git commit -m "First Commit"
git remote add origin [url]
git push -u origin master
OR
git push -f origin master
Only use git push -f origin master
if -u
dont work for you.
This will solve almost any kind of errors occurring while pushing your files.
ALTER TABLE [dbo].[TableName]
DROP CONSTRAINT FK_TableName_TableName2
You can use c++ boost::property_tree::ptree for parsing json data. here is the example for your json data. this would be more easy if you shift name inside each child nodes
#include <iostream>
#include <string>
#include <tuple>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
int main () {
namespace pt = boost::property_tree;
pt::ptree loadPtreeRoot;
pt::read_json("example.json", loadPtreeRoot);
std::vector<std::tuple<std::string, std::string, std::string>> people;
pt::ptree temp ;
pt::ptree tage ;
pt::ptree tprofession ;
std::string age ;
std::string profession ;
//Get first child
temp = loadPtreeRoot.get_child("Anna");
tage = temp.get_child("age");
tprofession = temp.get_child("profession");
age = tage.get_value<std::string>();
profession = tprofession.get_value<std::string>();
std::cout << "age: " << age << "\n" << "profession :" << profession << "\n" ;
//push tuple to vector
people.push_back(std::make_tuple("Anna", age, profession));
//Get Second child
temp = loadPtreeRoot.get_child("Ben");
tage = temp.get_child("age");
tprofession = temp.get_child("profession");
age = tage.get_value<std::string>();
profession = tprofession.get_value<std::string>();
std::cout << "age: " << age << "\n" << "profession :" << profession << "\n" ;
//push tuple to vector
people.push_back(std::make_tuple("Ben", age, profession));
for (const auto& tmppeople: people) {
std::cout << "Child[" << std::get<0>(tmppeople) << "] = " << " age : "
<< std::get<1>(tmppeople) << "\n profession : " << std::get<2>(tmppeople) << "\n";
}
}
In my case there was an empty picture in the folder. After deleting the empty .jpg's it worked normally.
I got this error when my .env
file was not set up properly. Make sure you have a .env
file with valid database login credentials.
Idk if you guys solved it but I recommend another way to do it, and it works :)
ServiceUtil = ig.Class.extend({
base_url : 'someurl',
sendRequest: function(request)
{
var url = this.base_url + request;
var requestVar = new XMLHttpRequest();
dataGet = false;
$.ajax({
url: url,
async: false,
type: "get",
success: function(data){
ServiceUtil.objDataReturned = data;
}
});
return ServiceUtil.objDataReturned;
}
})
So the main idea here is that, by adding async: false, then you make everything waits until the data is retrieved. Then you assign it to a static variable of the class, and everything magically works :)
I tested and used this command in kafka confluent V4.0.0
and apache kafka V 1.0.0 and 1.0.1
/opt/kafka/confluent-4.0.0/bin/kafka-configs --zookeeper XX.XX.XX.XX:2181 --entity-type topics --entity-name test --alter --add-config retention.ms=55000
test
is the topic name.
I think it works well in other versions too
FFMpeg can do this by seeking to the given timestamp and extracting exactly one frame as an image, see for instance:
ffmpeg -i input_file.mp4 -ss 01:23:45 -vframes 1 output.jpg
Let's explain the options:
-i input file the path to the input file
-ss 01:23:45 seek the position to the specified timestamp
-vframes 1 only handle one video frame
output.jpg output filename, should have a well-known extension
The -ss
parameter accepts a value in the form HH:MM:SS[.xxx]
or as a number in seconds. If you need a percentage, you need to compute the video duration beforehand.
Change the REGEXP
to Like
SELECT * FROM table_name WHERE column_name like '%[^a-zA-Z0-9]%'
this one works fine
You can get an integer representation of your float by passing the float into the Integer initializer method.
Example:
Int(myFloat)
Keep in mind, that any numbers after the decimal point will be loss. Meaning, 3.9 is an Int of 3 and 8.99999 is an integer of 8.
The error TypeError: 'numpy.ndarray' object is not callable
means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:
In [16]: import numpy as np
In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()
TypeError: 'numpy.ndarray' object is not callable
If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean
or pd.rolling_std
to a numpy array earlier in your code.
What I mean is something like this:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan, nan, nan])
In [4]: pd.rolling_mean = np.array([1,2,3])
In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
TypeError: 'numpy.ndarray' object is not callable
So, basically you need to search the rest of your codebase for pd.rolling_mean = ...
and/or pd.rolling_std = ...
to see where you may have overwritten them.
reload(pd)
just before your snippet, which should make it run by restoring the value of pd
to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.
To whoever is reading this, check out createMany()
method.
/**
* Create a Collection of new instances of the related model.
*
* @param array $records
* @return \Illuminate\Database\Eloquent\Collection
*/
public function createMany(array $records)
{
$instances = $this->related->newCollection();
foreach ($records as $record) {
$instances->push($this->create($record));
}
return $instances;
}
This can be done. Following are the steps to setup the GUI
sudo useradd -m awsgui
sudo passwd awsgui
sudo usermod -aG admin awsgui
sudo vim /etc/ssh/sshd_config # edit line "PasswordAuthentication" to yes
sudo /etc/init.d/ssh restart
In security group open port 5901. Then ssh to the server instance. Run following commands to install ui and vnc server:
sudo apt-get update
sudo apt-get install ubuntu-desktop
sudo apt-get install vnc4server
Then run following commands and enter the login password for vnc connection:
su - awsgui
vncserver
vncserver -kill :1
vim /home/awsgui/.vnc/xstartup
Then hit the Insert key, scroll around the text file with the keyboard arrows, and delete the pound (#) sign from the beginning of the two lines under the line that says "Uncomment the following two lines for normal desktop." And on the second line add "sh" so the line reads
exec sh /etc/X11/xinit/xinitrc.
When you're done, hit Ctrl + C on the keyboard, type :wq and hit Enter.
Then start vnc server again.
vncserver
You can download xtightvncviewer
to view desktop(for Ubutnu) from here https://help.ubuntu.com/community/VNC/Clients
In the vnc client, give public DNS plus ":1" (e.g. www.example.com:1). Enter the vnc login password. Make sure to use a normal connection. Don't use the key files.
Additional guide available here: http://www.serverwatch.com/server-tutorials/setting-up-vnc-on-ubuntu-in-the-amazon-ec2-Page-3.html
Mac VNC client can be downloaded from here: https://www.realvnc.com/en/connect/download/viewer/
Port opening on console
sudo iptables -A INPUT -p tcp --dport 5901 -j ACCEPT
If the grey window issue comes. Mostly because of ".vnc/xstartup" file on different user. So run the vnc server also on same user instead of "awsgui" user.
vncserver
From the line
'key' => env('APP_KEY', 'SomeRandomString'),
APP_KEY
is a global environment variable that is present inside the .env
file.
You can replace the application key if you trigger
php artisan key:generate
command. This will always generate the new key.
The output may be like this:
Application key [Idgz1PE3zO9iNc0E3oeH3CHDPX9MzZe3] set successfully.
Application key [base64:uynE8re8ybt2wabaBjqMwQvLczKlDSQJHCepqxmGffE=] set successfully.
Base64 encoding should be the default in Laravel 5.4
Note that when you first create your Laravel application, key:generate is automatically called.
Hash::make()
will no longer be valid.You can simple make use of lapply
or sapply
builtin functions.
lapply
will return you a list
-
lapply(dataframe,class)
while sapply
will take the best possible return type ex. Vector etc -
sapply(dataframe,class)
Both the commands will return you all the column names with their respective class.
In plain english, the Tier
refers to "each in a series of rows or levels of a structure placed one above the other" whereas the Layer
refers to "a sheet, quantity, or thickness of material, typically one of several, covering a surface or body".
Tier is a physical unit, where the code / process runs. E.g.: client, application server, database server;
Layer is a logical unit, how to organize the code. E.g.: presentation (view), controller, models, repository, data access.
Tiers represent the physical separation of the presentation, business, services, and data functionality of your design across separate computers and systems.
Layers are the logical groupings of the software components that make up the application or service. They help to differentiate between the different kinds of tasks performed by the components, making it easier to create a design that supports reusability of components. Each logical layer contains a number of discrete component types grouped into sublayers, with each sublayer performing a specific type of task.
The two-tier pattern represents a client and a server.
In this scenario, the client and server may exist on the same machine, or may be located on two different machines. Figure below, illustrates a common Web application scenario where the client interacts with a Web server located in the client tier. This tier contains the presentation layer logic and any required business layer logic. The Web application communicates with a separate machine that hosts the database tier, which contains the data layer logic.
Advantages of Layers and Tiers:
Layering helps you to maximize maintainability of the code, optimize the way that the application works when deployed in different ways, and provide a clear delineation between locations where certain technology or design decisions must be made.
Placing your layers on separate physical tiers can help performance by distributing the load across multiple servers. It can also help with security by segregating more sensitive components and layers onto different networks or on the Internet versus an intranet.
A 1-Tier application could be a 3-Layer application.
Note that you can also make your Makefile simpler, at the same time:
DEBUG ?= 1
ifeq (DEBUG, 1)
CFLAGS =-g3 -gdwarf2 -DDEBUG
else
CFLAGS=-DNDEBUG
endif
CXX = g++ $(CFLAGS)
CC = gcc $(CFLAGS)
EXECUTABLE = output
OBJECTS = CommandParser.tab.o CommandParser.yy.o Command.o
LIBRARIES = -lfl
all: $(EXECUTABLE)
$(EXECUTABLE): $(OBJECTS)
$(CXX) -o $@ $^ $(LIBRARIES)
%.yy.o: %.l
flex -o $*.yy.c $<
$(CC) -c $*.yy.c
%.tab.o: %.y
bison -d $<
$(CXX) -c $*.tab.c
%.o: %.cpp
$(CXX) -c $<
clean:
rm -f $(EXECUTABLE) $(OBJECTS) *.yy.c *.tab.c
Now you don't have to repeat filenames all over the place. Any .l files will get passed through flex and gcc, any .y files will get passed through bison and g++, and any .cpp files through just g++.
Just list the .o files you expect to end up with, and Make will do the work of figuring out which rules can satisfy the needs...
for the record:
$@
The name of the target file (the one before the colon)
$<
The name of the first (or only) prerequisite file (the first one after the colon)
$^
The names of all the prerequisite files (space separated)
$*
The stem (the bit which matches the %
wildcard in the rule definition.
$.extend($.expr[':'], {
unchecked: function (obj) {
return ((obj.type == 'checkbox' || obj.type == 'radio') && !$(obj).is(':checked'));
}
});
$("input:checked")
$("input:unchecked")
def get_true_text(tag):
children = tag.find_elements_by_xpath('*')
original_text = tag.text
for child in children:
original_text = original_text.replace(child.text, '', 1)
return original_text
Print only selected element on codepen
HTML:
<div class="print">
<p>Print 1</p>
<a href="#" class="js-print-link">Click Me To Print</a>
</div>
<div class="print">
<p>Print 2</p>
<a href="#" class="js-print-link">Click Me To Print</a>
</div>
JQuery:
$('.js-print-link').on('click', function() {
var printBlock = $(this).parents('.print').siblings('.print');
printBlock.hide();
window.print();
printBlock.show();
});
Also, the ternary operator enables a form of "optional" parameter. Java does not allow optional parameters in method signatures but the ternary operator enables you to easily inline a default choice when null
is supplied for a parameter value.
For example:
public void myMethod(int par1, String optionalPar2) {
String par2 = ((optionalPar2 == null) ? getDefaultString() : optionalPar2)
.trim()
.toUpperCase(getDefaultLocale());
}
In the above example, passing null
as the String
parameter value gets you a default string value instead of a NullPointerException
. It's short and sweet and, I would say, very readable. Moreover, as has been pointed out, at the byte code level there's really no difference between the ternary operator and if-then-else. As in the above example, the decision on which to choose is based wholly on readability.
Moreover, this pattern enables you to make the String
parameter truly optional (if it is deemed useful to do so) by overloading the method as follows:
public void myMethod(int par1) {
return myMethod(par1, null);
}
Place all files need to copied in a separate folder, for ease place them in c drive.
Open Command Prompt - windows>type cmd>select command prompt.
You can see the default directory pointing - Ex : C:[Folder_Name]>. Change the directory to point to the folder which you have placed files to be copied, using ' cd [Folder_Name] ' command.
After pointing to directory - type 'dir' which shows all the files present in folder, just to make sure everything at place.
Now type : 'copy *.txt [newfile_name].txt' and press enter.
Done!
All the text in individual files will be copied to [newfile_name].txt