id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23534900
|
import SwiftUI
struct MeasurementReading: View, Equatable {
@ObservedObject var ble: BluetoothConnectionmanager
@GestureState var isDetectTap = false
@State var MyText:String = "Wait"
static func == (lhs: MeasurementReading, rhs: MeasurementReading)->Bool{
return lhs.MyText == rhs.MyText
}
var body: some View {
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
return HStack {
Spacer()
VStack{
Button(action:{
self.MyText = "\(self.ble.getValue()!) mV"
print("Text is \(self.MyText as NSString)")
}, label: {
Text(MyText)
.font(.system(size: 40))
.bold()
.foregroundColor(Color.black)
.padding(.trailing, 15)
.frame(height: 100)
})
Button(action: {
self.MyText = "\(self.ble.getValue()!) mV"
print("Text is \(self.MyText as NSString)")
}, label: {
Text(MyText)
.font(.system(size: 25))
.padding(.top, -20)
.padding(.bottom, 20)
.foregroundColor(Color.black)
})
}
}.onReceive(timer)
{ _ in // TIMER FUNCTIONALITY HERE
self.MyText = "\(self.ble.getValue()!) mV"
print("Text is \(self.MyText)")
}
}
}
struct MeasurementReading_Previews: PreviewProvider {
static var previews: some View {
MeasurementReading(ble: BluetoothConnectionmanager())
}
}
Every 1 second the correct value read from the BLE system is assigned to MyText and then MyText is printed to the debug output properly with the updated value.
The problem here is that view MeasurementReading does not update. Also, using a closure on any item also has the same behavior (variable is updated, it is output properly but no view update) ex .onTap{....} will have the same behavior or any other .onXXXX closure. The only way I could get the view to update at all with new values for the MyText state is to put the behavior in a Button.
My question is this: Why does the view not update even when the state variable changes via Timer or .onXXXX closure?
A: You need to be setting the ble value to the updated timer value:
Without testing this properly. I also think your BluetoothConnectionmanager needs to be a @State property for this to work.
@State var ble: BluetoothConnectionmanager
.onReceive(timer) { value in // value is the updated value
self.ble.value = value
self.MyText = "\(self.ble.getValue()!) mV"
print("Text is \(self.MyText)")
}
Take a look at this example to see how a timer works with a Date() object.
| |
doc_23534901
|
bind(ExternalSystemAccessor.class).to(ExternalSystemAccessorStub.class).in(Singleton.class);
Now one of my tests needs to use the productive implementation, so I tried to bind it back the default with an override:
injector = Guice.createInjector(Modules.override(new TestModule()).with(new AbstractModule() {
@Override
protected void configure() {
bind(ExternalSystemAccessor.class).to(ExternalSystemAccessor.class);
}
}));
However, this leads to a Guice error:
com.google.inject.CreationException: Guice creation errors:
1) Binding points to itself.
So how can I get back to the default binding with an override?
A: Just found the answer while typing the question. The solution is to omit the to method:
@Override
protected void configure() {
bind(ExternalSystemAccessor.class); // re-enable default binding
}
| |
doc_23534902
|
I've currently got this which works
^[jJ]{2}[\-\s]{0,1}[0-9]{2}[\-\s]{0,1}[0-9]{2}[\-\s]{0,1}[0-9]{2}[\-\s]{0,1}[a-zA-Z]$
but I was wondering if there is a shorter version for exmaple
^[jJ]{2} [ [\-\s]{0,1}[0-9]{2} ]{3} [\-\s]{0,1}[a-zA-Z]$
So repeat the [-\s]{0,1}[0-9]{2} 3 by wrapping it in some sort of group [ * ]{3}
A: If i got you right, your insurance numbers are always two letters, 6 numbers, and a final letter, A,B,C or D? Wouldn't it be the easiest way to try sth. like that
/\w{2}\d{6}[A-D]/
you catch 2 letters at first with \w{2} , then you get 6 numbers with \d{6} and you end with a letter from A to D by [A-D]
Or, if blanks are impontant, try this
/\w{2}\d\d \d\d \d\d [A-D]/
I dont think that shorten it much more would be possible, since when you are trying to use (\d\d ){3} it would only repeat the same pattern three times, e.g. 23 23 23
If you really want to learn RegEx, i suggest you this tutorial, it helped me a lot in the beginning of Regular Expressions
A: A simple research for a regex tutorial in your favorite search engine (duckduckgo for sure) would give you the answer faster than asking in a forum!
So what you are looking for is a non-capturing group (?:...). You can rewrite your pattern like this:
^[jJ]{2}(?:[-\s]?[0-9]{2}){3}[-\s]?[a-zA-Z]$
or like this if you use a case insensitive flag/option:
^J{2}(?:[-\s]?[0-9]{2}){3}[-\s]?[A-Z]$
An other possible way consists to remove all that is not a letter or a digit before (and eventually to use an uppercase function). Then you only need:
^J{2}[0-9]{6}[A-Z]$
As an aside, I don't understand why you start your pattern with J for the first two letters, since many others letters are allowed according to this article: https://en.wikipedia.org/wiki/National_Insurance_number
Other thing, short and efficient are two different things in computing.
for example this pattern will be efficient too and more restrictive:
^(?!N[KT]|BG|GB|[KT]N|ZZ)[ABCEGHJ-PRSTW-Z][ABCEGHJ-NPRSTW-Z][0-9][0-9][-\s]?[0-9][0-9][-\s]?[0-9][0-9][-\s]?[A-D]$
A: A shorter version:
/^j{2}(?:[-\s]?\d{2}){3}[-\s]?[a-zA-Z]$/i
See the regex online demo
Note that
*
*you do not need to escape - inside the character class if it is at the beginning or end of the class (see Metacharacters Inside Character Classes)
*you can use a \d as a shorthand character class for a digit (see Shorthand Character Classes)
*{0,1} limiting quantifier can usually be represented as a ? quantifier (1 or zero occurrences) (see Limiting Repetition)
*The /i (or inline modifier version (?i) - depending on the engine) can be used to turn [jJ] to just j or J (see Specifying Modes Inside The Regular Expression)
*A limiting quantifier can be applied to a whole (better non-capturing) group: (?:[-\s]?\d{2}){3} (see Limiting Repetition)
| |
doc_23534903
|
My code like this:
import win32gui, win32ui, win32con, win32api
screen_w = 2880
screen_h = 1800
x0 = int(screen_w * 0.866)
y0 = int(screen_h * 0.14)
ww = 220
hh = 70
def window_capture(filename):
hwnd = 0
hwndDC = win32gui.GetWindowDC(hwnd)
mfcDC = win32ui.CreateDCFromHandle(hwndDC)
saveDC = mfcDC.CreateCompatibleDC()
saveBitMap = win32ui.CreateBitmap()
saveBitMap.CreateCompatibleBitmap(mfcDC, ww, hh)
saveDC.SelectObject(saveBitMap)
saveDC.BitBlt((0, 0), (ww, hh), mfcDC, (x0, y0), win32con.SRCCOPY)
saveBitMap.SaveBitmapFile(saveDC, filename)
#------------------
win32gui.DeleteObject(saveBitMap.GetHandle())
saveDC.DeleteDC()
mfcDC.DeleteDC()
win32gui.ReleaseDC(hwnd, hwndDC)
#------------------
count = 0
while 1:
window_capture('temp.png')
count += 1
if int(count/1000) == float(count/1000):
print(count)
Firstly, I didn`t add DeleteObject and DeleteDC to release memory. The process will stop after about 10000 times window_capture.
But after I add them, I still can see the memory increase in task manager. Finally, after about 130000 times, the process stop again.
Does that mean I haven`t release all the memories? In my project, I need capture screen shot for a long time. How can I solve this problem?
Thank you!
A: Caveat: I don't know Python.
From Win32 perspective, you should not delete a GDI object while it is still selected into any DC (Device Context). You are doing precisely that here:
win32gui.DeleteObject(saveBitMap.GetHandle())
The typical Win32 scenario is to save a handle of the object previously selected into DC (any of the Select...() functions return that), and re-select it into the DC when you are done with your own object.
Alternatively, you can use SaveDC / RestoreDC pair if you need to restore multiple objects.
| |
doc_23534904
|
I don't know why it display only four first posts.
Can you help me change this code to display all posts from my table, to retrieve data I'm using .each loop so I think this is not the main problem.
A: I've created a dynamic one with the example you gave, I calculate through JS the amount of li and then I calculate what's the % of the keyframe by dividing 100 for the number of li's inside the ul. You can check the example here:
https://jsfiddle.net/erv1b8nh/2/
The js is the following:
var style = document.documentElement.appendChild(document.createElement("style")),
rule1 = " ticker { 0% { margin-top:0; }";
rule2 = " 100% { margin-top:0; } }";
var n = $('#news li').length;
var rule3 = "";
var help = 1;
var nSpin = (100/n).toFixed(2);
while(n > 1)
{
rule3 = rule3 + " " + nSpin*help + "% { margin-top:" + help*-27 + "px; }";
help = help + 1;
n = n - 1;
}
rule = rule1 + rule3 + rule2;
if (CSSRule.KEYFRAMES_RULE) { // W3C
style.sheet.insertRule("@keyframes" + rule, 0);
} else if (CSSRule.WEBKIT_KEYFRAMES_RULE) { // WebKit
style.sheet.insertRule("@-webkit-keyframes" + rule, 0);
}
Of course then based on the amount of elements you should adjust the animation time.
Hope it will help you :)
| |
doc_23534905
|
function oldestAges(ages){
if (ages == []){
return [0,0];
}else{
var max = Math.max.apply(null, ages);
ages.splice(ages.indexOf(max), 1);
var max2 = Math.max.apply(null, ages);
return [max2,max];
}
}
However, when testing [] as ages, the expected was '[0, 0]', instead got: '[-Infinity, -Infinity]'
Also, is there a much easier way to accomplish the same task? I ask because using R I could get the same result in much less number of lines. I am noob in javascript still.
A: A simple (not sure about the most optimal) way to achieve this:
const input = [5, 150, 2, 8, 58, 4];
const result = input.sort((x, y) => y - x).slice(0, 2);
console.log(result);
A: You can sort your array in descending order so that the first two elements contain the highest values.
ages.sort((a, b) => b - a);
Now ages[0] and ages[1] contain the two biggest numbers.
A: ages.length == 0 is what you can use to see if the number of the elements in the array is zero.
Your code has an error where you say if (ages == []).
Try this,
function oldestAges(ages){
if (ages.length == 0){
return [0,0];
}else{
var max = Math.max.apply(null, ages);
ages.splice(ages.indexOf(max), 1);
var max2 = Math.max.apply(null, ages);
return [max2,max];
}
}
| |
doc_23534906
|
I was trying to findout why dequeue Thread gets duplicated data even there are no duplicated data in ConcurrentQueue.
What will be the possible problem?
Enqueue Thread Code
private void Server_MulticastReceiveThread()
{
Socket mcastSocket;
ReceiveDataType InsertQueue; // To insert Queue
byte[] data = new byte[1024]; // Receive Data
InsertQueue.data = data;
int recv;
while (true)
{
try
{
recv = mcastSocket.ReceiveFrom(~ ,ref remoteEndPoint);
Server_Queue.Enqueue(InsertQueue);
}
catch (Exception e)
{
Thread.Sleep(INTERVAL_30);
continue;
}
string path = @"C:\Users\SAN\Downloads\Enqueue.txt";
string Test = Encoding.Default.GetString(InsertQueue.data);
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(Test);
}
}
}
Dequeue Thread Code. ExtractQueue.data is just byte array.
private void Server_MulticastDequeueThread()
{
string rxSentence = ""; // received entire Sentence
string tagblockSentence = ""; // For Tagblock ONLY
string nmeaSentence = ""; // For NMEA-Sentence ONLY
int queuecount = 0;
string _dataReceiveTime;
while (true)
{
while (Server_Queue.TryDequeue(out ExtractQueue))
{
try
{
if (ExtractQueue.data == null)
continue;
rxSentence = Encoding.Default.GetString(ExtractQueue.data);
string path = @"C:\Users\SAN\Downloads\Dequeue.txt";
string Test = rxSentence;
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(Test);
}
}
catch (Exception e)
{
Log.SaveLog(LogLevel.ZERO, " " + e.Message);
}
}
Thread.Sleep(1);
}
}
Enqueue.txt Result.
UdPbC \s:SI0005,d:IC0001,n:123,t:220710060010.542*19\$ERUID,12,148*71
UdPbC \s:SI0004,d:IC0001,n:123,t:220710060010.553*18\$ERUID,11,147*7D
UdPbC \s:SI0005,d:IC0001,n:123,t:220710060010.572*1a\$ERUID,12,148*71
UdPbC \s:SI0004,d:IC0001,n:123,t:220710060010.596*11\$ERUID,11,147*7D
UdPbC \s:SI0005,d:IC0001,n:123,t:220710060010.605*19\$ERUID,12,148*71
UdPbC \s:SI0004,d:IC0001,n:123,t:220710060010.627*18\$ERUID,11,147*7D
UdPbC \s:SI0005,d:IC0001,n:123,t:220710060010.638*17\$ERUID,12,148*71
UdPbC \s:SI0003,d:IC0001,n:123,t:220710060010.649*17\$ERUID,7,141*4C
UdPbC \s:SI0003,d:IC0001,n:123,t:220710060010.649*17\$ERUID,8,142*40
UdPbC \s:SI0003,d:IC0001,n:123,t:220710060010.649*17\$ERUID,9,143*40
UdPbC \s:SI0003,d:IC0001,n:123,t:220710060010.649*17\$ERUID,10,144*7F
UdPbC \s:SI0004,d:IC0001,n:123,t:220710060010.649*10\$ERUID,11,147*7D
UdPbC \s:SI0005,d:IC0001,n:123,t:220710060010.660*1a\$ERUID,12,148*71
UdPbC \s:SI0004,d:IC0001,n:123,t:220710060010.670*1a\$ERUID,11,147*7D
UdPbC0\s:IC0001,d:SI0011*2a\$ICHBT,,A,*39
10.670*1a\$ERUID,11,147*7D
Dequeue.txt Result
UdPbC \s:SI0005,d:IC0001,n:123,t:220710060010.572*1a\$ERUID,12,148*71
UdPbC \s:SI0005,d:IC0001,n:123,t:220710060010.572*1a\$ERUID,12,148*71
UdPbC \s:SI0004,d:IC0001,n:123,t:220710060010.627*18\$ERUID,11,147*7D
UdPbC \s:SI0004,d:IC0001,n:123,t:220710060010.670*1a\$ERUID,11,147*7D
UdPbC \s:SI0004,d:IC0001,n:123,t:220710060010.670*1a\$ERUID,11,147*7D
UdPbC \s:SI0004,d:IC0001,n:123,t:220710060010.670*1a\$ERUID,11,147*7D
UdPbC0\s:IC0001,d:SI0011*2a\$ICHBT,,A,*39
10.670*1a\$ERUID,11,147*7D
UdPbC \s:SI0005,d:IC0001,n:123,t:220710060010.691*14\$ERUID,12,148*71
UdPbC \s:SI0004,d:IC0001,n:123,t:220710060010.692*16\$ERUID,11,147*7D
UdPbC \s:SI0004,d:IC0001,n:123,t:220710060010.745*1d\$ERUID,11,147*7D
UdPbC \s:SI0004,d:IC0001,n:123,t:220710060010.777*1c\$ERUID,11,147*7D
| |
doc_23534907
|
But what I need to do, is filter two columns, and name it by the same principles, so I modified it.
Somehow on second value in first loop, it doesnt start loop in other loop.
Why does it give me blanks in second loop?
Sub datu_sagrupesana()
Dim x As Range, y As Range, rng As Range, last As Long, sht As Worksheet
Application.ScreenUpdating = False
'datu vieta
Set sht = ThisWorkbook.Worksheets("Test")
'apgabals
last = sht.Cells(Rows.Count, "A").End(xlUp).Row
Set rng = sht.Range("A1:C" & last)
sht.Range("A1:A" & last).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("H1"), Unique:=True 'produkta filtrs
sht.Range("C1:C" & last).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("J1"), Unique:=True 'valodas filtrs
For Each y In Range([J2], Cells(Rows.Count, "J").End(xlUp))
For Each x In Range([H2], Cells(Rows.Count, "H").End(xlUp))
With rng
.AutoFilter
.AutoFilter Field:=3, Criteria1:=y.Value
.AutoFilter Field:=1, Criteria1:=x.Value
.SpecialCells(xlCellTypeVisible).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = y.Value & x.Value
ActiveSheet.Paste
End With
Next x
Next y
'nonemt filtru
sht.AutoFilterMode = False
With Application
.CutCopyMode = False
.ScreenUpdating = True
End With
End Sub
A: SOLVED by myself
Sub datu_sagrupesana()
Dim x As Long, y As Range, rng As Range, last As Long, sht As Worksheet
Application.ScreenUpdating = False
'datu vieta
Set sht = ThisWorkbook.Worksheets("Test")
'apgabals
last = sht.Cells(Rows.Count, "A").End(xlUp).Row
Set rng = sht.Range("A1:C" & last)
sht.Range("A1:A" & last).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("H1"), Unique:=True 'produkta filtrs
sht.Range("C1:C" & last).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("I1"), Unique:=True 'valodas filtrs
pr = Application.WorksheetFunction.CountA(sht.Columns("H"))
va = Application.WorksheetFunction.CountA(sht.Columns("I"))
For j = 2 To va
For i = 2 To pr
valoda = sht.Cells(j, "I").Value
produkts = sht.Cells(i, "H").Value
'
'For Each y In Range("J2", Cells(Rows.Count, "J").End(xlUp))
'
'
'For Each x In Range("H2", Cells(Rows.Count, "H").End(xlUp))
'
With rng
.AutoFilter
.AutoFilter Field:=3, Criteria1:=valoda
.AutoFilter Field:=1, Criteria1:=produkts
.SpecialCells(xlCellTypeVisible).Copy
Sheets.Add(After:=Sheets(Sheets.Count)).Name = valoda & produkts
ActiveSheet.Paste
End With
'
'Next x
'Next y
Next i
Next j
'nonemt filtru
sht.AutoFilterMode = False
With Application
.CutCopyMode = False
.ScreenUpdating = True
End With
End Sub
| |
doc_23534908
|
I'm seeing the API to search Common Crawl for a given domain.
How can I search common crawl for a given search term?
A: you can't currently search the content of the web pages. There was commonsearch which used the CC datasets but I am not sure how up to date it is.
If you are looking for a limited set of keywords you could use Mapreduce or Spark to filter the pages but if you are dealing with an open or arbitrary set of queries then the best approach would be to index the datasets into Elasticsearch or SOLR yourself.
| |
doc_23534909
|
<!DOCTYPE html>
<ui:composition
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<div id="crb_header">
<br/>
<h4 align="right">Welcome : #{homebean.user}</h4>
<br/>
</div>
</ui:composition>
The above page is attached to the main page usingui:include and the following warning messages are visible at the end of the main page.
Warning: This page calls for XML namespace declared with prefix div but no taglibrary exists for that namespace.
Warning: This page calls for XML namespace declared with prefix h4 but no taglibrary exists for that namespace.
Warning: This page calls for XML namespace declared with prefix br but no taglibrary exists for that namespace.
Warning: This page calls for XML namespace declared with prefix br but no taglibrary exists for that namespace.
Can't we use html tags inside this ui:composition files?
A: Didn't you miss to include the xhtml namespace inside the ui:composition?
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
| |
doc_23534910
|
the data structure is like this
I am trying to write a for loop in React to pull all the garages information to my webpage in list format.
My code:
MyComponents.Garage = React.createClass({
render: function() {
var garage = this.props.garage
console.log(garage)
return (
<li className="card-content">
TODO: This is a component about a garage whose
raw data is //{JSON.stringify(this.props.garage)}
<MyComponents.GarageTitle
title={this.props.garage.friendlyName}/>
<MyComponents.GarageSpaces
open={this.props.garage.open_spaces}
total={this.props.garage.total_spaces}/>
<MyComponents.GarageRates
rates={this.props.garage.rates}/>
<MyComponents.GarageHours
hours={this.props.garage.hours}/>
</li>
);
}
});
MyComponents.Garages = React.createClass({
render: function(){
console.log(this.props.garage)
for (var key in this.props.garage){
console.log(this.props.garage[key])
return (
<ul>
<MyComponents.Garage garage={this.props.garage[key]}/>
</ul>
);
}
}
});
I first pass the Json data to Mycomponent.Garages and run the for loop inside and call Mycomponent.Garage for each detail information of that Garage.
But My problem is that I can only run through the first Garage, it won't keep looping the remaining Garages.
Can anyone help me with my task?
Thanks
A: Using return in your for in loop will not work, but you're close to getting it right! Instead, try creating an array of garages nodes:
MyComponents.Garages = React.createClass({
render: function(){
garageNodes = [];
for (var key in this.props.garage){
console.log(this.props.garage[key])
garageNodes.push(
<ul>
<MyComponents.Garage garage={this.props.garage[key]}/>
</ul>
);
}
return garageNodes;
}
});
| |
doc_23534911
|
I've created a struct that stores the data:
typedef struct {
/*Start Size Description */
int signatute; /* 0 4 Local file header signature = 0x04034b50 */
short int version; /* 4 2 Version needed to extract (minimum) */
short int bit_flag; /* 6 2 General purpose bit flag */
short int compression_method; /* 8 2 Compression method */
short int time; /* 10 2 File last modification time */
short int date; /* 12 2 File last modification date */
int crc; /* 14 4 CRC-32 */
int compressed_size; /* 18 4 Compressed size */
int uncompressed_size; /* 22 4 Uncompressed size */
short int name_length; /* 26 2 File name length (n) */
short int extra_field_length; /* 28 2 Extra field length (m) */
char *name; /* 30 n File name */
char *extra_field; /*30+n m Extra field */
} ZIP_local_file_header;
The size returned by sizeof(ZIP_local_file_header) is 40, but if the sum of each field is calculated with sizeof operator the total size is 38.
If we have the next struct:
typedef struct {
short int x;
int y;
} FOO;
sizeof(FOO) returns 8 because the memory is allocated with 4 bytes every time. So, to allocate x are reserved 4 bytes (but the real size is 2 bytes). If we need another short int it will fill the resting 2 bytes of the previous allocation. But as we have an int it will be allocated plus 4 bytes and the empty 2 bytes are wasted.
To read data from file, we can use the function fread:
ZIP_local_file_header p;
fread(&p,sizeof(ZIP_local_file_header),1,file);
But as there're empty bytes in the middle, it isn't read correctly.
What can I do to sequentially and efficiently store data with ZIP_local_file_header wasting no bytes?
A: C structs are just about grouping related pieces of data together, they do not specify a particular layout in memory. (Just as the width of an int isn't defined either.) Little-endian/Big-endian is also not defined, and depends on the processor.
Different compilers, the same compiler on different architectures or operating systems, etc., will all layout structs differently.
As the file format you want to read is defined in terms of which bytes go where, a struct, although it looks very convenient and tempting, isn't the right solution. You need to treat the file as a char[] and pull out the bytes you need and shift them in order to make numbers composed of multiple bytes, etc.
A: The solution is compiler-specific, but for instance in GCC, you can force it to pack the structure more tightly by appending __attribute__((packed)) to the definition. See http://gcc.gnu.org/onlinedocs/gcc-3.2.3/gcc/Type-Attributes.html.
A: It's been a while since I worked with zip-compressed files, but I do remember the practice of adding my own padding to hit the 4-byte alignment rules of PowerPC arch.
At best you simply need to define each element of your struct to the size of the piece of data you want to read in. Don't just use 'int' as that may be platform/compiler defined to various sizes.
Do something like this in a header:
typedef unsigned long unsigned32;
typedef unsigned short unsigned16;
typedef unsigned char unsigned8;
typedef unsigned char byte;
Then instead of just int use an unsigned32 where you have a known 4-byte vaule. And unsigned16 for any known 2-byte values.
This will help you see where you can add padding bytes to hit 4-byte alignment, or where you can group 2, 2-byte elements to make up a 4-byte alignment.
Ideally you can use a minimum of padding bytes (which can be used to add additional data later as your expand the program) or none at all if you can align everything to 4-byte boundaries with variable-length data at the end.
A: In order to meet the alignment requirements of the underlying platform, structs may have "padding" bytes between members so that each member starts at a properly aligned address.
There are several ways around this: one is to read each element of the header separately using the appropriately-sized member:
fread(&p.signature, sizeof p.signature, 1, file);
fread(&p.version, sizeof p.version, 1, file);
...
Another is to use bit fields in your struct definition; these are not subject to padding restrictions. The downside is that bit fields must be unsigned int or int or, as of C99, _Bool; you may have to cast the raw data to the target type to interpret it correctly:
typedef struct {
unsigned int signature : 32;
unsigned int version : 16;
unsigned int bit_flag; : 16;
unsigned int compression_method : 16;
unsigned int time : 16;
unsigned int date : 16;
unsigned int crc : 32;
unsigned int compressed_size : 32;
unsigned int uncompressed_size : 32;
unsigned int name_length : 16;
unsigned int extra_field_length : 16;
} ZIP_local_file_header;
You may also have to do some byte-swapping in each member if the file was written in big-endian but your system is little-endian.
Note that name and extra field aren't part of the struct definition; when you read from the file, you're not going to be reading pointer values for the name and extra field, you're going to be reading the actual contents of the name and extra field. Since you don't know the sizes of those fields until you read the rest of the header, you should defer reading them until after you've read the structure above. Something like
ZIP_local_file_header p;
char *name = NULL;
char *extra = NULL;
...
fread(&p, sizeof p, 1, file);
if (name = malloc(p.name_length + 1))
{
fread(name, p.name_length, 1, file);
name[p.name_length] = 0;
}
if (extra = malloc(p.extra_field_length + 1))
{
fread(extra, p.extra_field_length, 1, file);
extra[p.extra_field_length] = 0;
}
A: Also, the name and extra_field will not contain any meaningful data, most likely. At least not between runs of the program, since these are pointers.
| |
doc_23534912
|
Possible Duplicate:
How can I sort an NSArray containing NSDictionaries?
I have an array of dictionaries.. This is what my dictionary looks like
MOD = 0;
MAU= 30;
MODN = "SOME WORD";
MODID = 518;
I have tried sorting the array of dictionaries like this
sortedArray = [[ICArray valueForKey:@"MODN"] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
However this only gives me an array of the values in MODN in alphabetical order... where in actual fact I am hoping to get the each dictionary sorted into an array.
Any help would be greatly appreciated..
A: You can use a custom block based comparator to look at the values in each of the dictionaries, and sort however you want. Something like below should work for you
NSArray *unsortedArray = @[@{@"MOD" : @(0), @"MAU" : @(30), @"MODN" : @"SOME WORD", @"MODID" : @(518)},
@{@"MOD" : @(0), @"MAU" : @(30), @"MODN" : @"ANOTHER WORD", @"MODID" : @(518)},
@{@"MOD" : @(0), @"MAU" : @(30), @"MODN" : @"THIRD WORD", @"MODID" : @(518)}];
NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(id obj1, id obj2) {
return [[obj1 valueForKey:@"MODN"] localizedCaseInsensitiveCompare:[obj2 valueForKey:@"MODN"]];
}];
| |
doc_23534913
|
I'm afraid the problem lies in the if(!(this instanceof Buffer)){} code, that is evaluating to false, since the code doesn't actually inherit from the prototype, so I need a way to fool the instanceof operator to make it work.
I'm using the ES5 Class module https://npmjs.org/package/es5class
var Class = require('es5class');
var MyBuffer = Class.define('MyBuffer').implement(Buffer, true);
// MyBuffer.prototype.write exists
// (new MyBuffer(4)).length is undefined
// (new MyBuffer(4)).parent is undefined, etc
But EventEmitter works as usual
var Class = require('es5class');
var MyEventEmitter = Class.define('MyEventEmitter').implement(require('events').EventEmitter, true);
// MyEventEmitter.prototype.emit exists
// (new MyEventEmitter())._events is an object as expected
I'm trying to change the ES5 class module to make it work, trying to overwrite the constructor before calling f.apply(), but to no avail.
// $apply is an array of mixin'd classes, for example, Buffer or EventEmitter
self.$apply.forEach(function (f){
var oldctor = instance.constructor; // current instance constructor
Object.defineProperty(instance, 'constructor', {
value : f, // trying to change it
writable : true,
configurable: true,
enumerable : false
});
console.log(instance instanceof f); // false, this needs to evaluate to true just before the f.apply, how to? instance.prototype cannot "redefine" prototype
f.apply(instance, arguments); // works the same as EventEmitter.apply(this, arguments);
Object.defineProperty(instance, 'constructor', {
value : oldctor, // try to restore it
writable : true,
configurable: true,
enumerable : false
});
});
Managed to fix it with a rather ugly hack, that Bergi pointed out in https://github.com/pocesar/ES5-Class/blob/master/index.js#L24
superApply = function(instance, object, args){
if (object.$apply.length) {
object.$apply.forEach(function (f){
// dirty little hack to make classes like Buffer think the prototype is instanceof itself
spo(instance, f.prototype);
f.apply(instance, args);
});
}
},
| |
doc_23534914
|
These numbers look oddly high to me, and I have few hypothesis, but I don't have any tool to investigate: is there a way to browse the history of the issued calls/commands to Cloud Firestore? It would be nice to have the auth.uid of the call issuer and some other details (time, location, etc.).
Notice: I know I could implement something like that myself, using a Firebase Function, but I'd rather rely on provider-side infos and at this moment such overhead would be killing my efforts for days.
A: Firebase employee here
There is no way to get a report of the queries that were made to Firestore. You'll have to find a way to log those on your own.
| |
doc_23534915
|
1.
select
extract(year from (sysdate - to_date('2002-12-25')) year to month) Y
from dual;
2.
with age(d) as
(
select (sysdate - to_date('2002-12-25')) from dual
)
select
extract(year from (age.d) year to month) Y
from age;
error:
ORA-30083: syntax error was found in interval value expression
30083. 00000 - "syntax error was found in interval value expression"
*Cause: A syntax error was found during parsing an interval value
A: In second query there is NUMBER value sysdate - to_date('2002-12-25'). You cannot EXTRACT year from number.
In first query you convert number back to one of date interval datatype.
-- datatype: internal NUMBER of a DATE subtraction
SELECT dump(sysdate - to_date('2002-12-25', 'YYYY-MM-DD'))
FROM dual;
-- datatype: INTERVAL YEAR TO MONTH
SELECT dump((sysdate - to_date('2002-12-25', 'YYYY-MM-DD')) year to month)
FROM dual;
-- datatype: NUMBER
SELECT dump(extract(year from (sysdate - to_date('2002-12-25', 'YYYY-MM-DD')) year to month))
FROM dual;
DUMP returns a VARCHAR2 value containing the data type code, length in
bytes, and internal representation of expr.
A: Your question could be simplified a bit to, why does this work:
select (sysdate - date '2002-12-25') year to month from dual;
(SYSDA
------
+14-03
but plugging the same number produced by sysdate - date '2002-12-25' into the same call does not, with or without parentheses in various combinations:
select (5217.4197) year to month from dual;
ORA-30083: syntax error was found in interval value expression
The problem is that the two numbers are actually different internally. As @hinoff suggested, you can use the dump() function to examine them:
select dump(sysdate - date '2002-12-25')
from dual;
DUMP(SYSDATE-DATE'2002-12-25')
-----------------------------------
Typ=14 Len=8: 97,20,0,0,195,143,0,0
select dump(5217.4197) from dual;
DUMP(5217.4197)
----------------------------
Typ=2 Len=5: 194,53,18,42,98
Type 2 is documented as number. and is further explain in MoS document ID 1031902.6.
You would get the same error if you explicitly converted the calculation to a type-2 number:
select (cast(sysdate - date '2002-12-25' as number)) year to month from dual;
ORA-30083: syntax error was found in interval value expression
Type 14 seems to be an undocumented internal representation, and Oracle is able - internally - to convert that to and from an interval in a way it can't with a normal type-2 number.
You can convert a number to an interval with numtodsinterval(5217.4197, 'DAY'), but because the day-to-second and year-to-month intervals aren't compatible you can't extract the number of years from that (which makes some sense, as the number of days in a year varies).
You'd see similar issues if you tried to avoid it with timestamp instead of dates:
select (systimestamp - timestamp '2002-12-25 00:00:00') year to month from dual;
(SYSTI
------
+14-03
select dump(systimestamp - timestamp '2002-12-25 00:00:00') from dual;
DUMP(SYSTIMESTAMP-TIMESTAMP'2002-12-2500:00:00')
------------------------------------------------------------------------
Typ=190 Len=24: 97,20,0,0,9,0,0,0,38,0,0,0,44,0,0,0,24,177,20,9,10,0,0,0
which also isn't one of the documented interval types, but can be internally converted to either year-to-month or day-to-second. Trying to use it in your CTE also fails; using extract(year from age.d) gets "ORA-30076: invalid extract field for extract source" because it's seen as a DS interval at this point, and extract(year from (age.d) year to month) is back to ORA-30083.
You might be better off switching from intervals to other units, such as months:
with age(m) as
(
select months_between(sysdate, date '2002-12-25') from dual
)
select
trunc(age.m / 12) Y
from age;
Y
----------
14
If you want the number of months as well you could use trunc(remainder(age.m, 12)).
Or if you really want an interval, convert it in the CTE:
with age(ym) as
(
select numtoyminterval(
months_between(sysdate, date '2002-12-25'), 'MONTH') from dual
)
select
extract(year from age.ym) Y
from age;
or closer to your original:
with age(ym) as
(
select (sysdate - date '2002-12-25') year to month from dual
)
select
extract(year from age.ym) Y
from age;
Interestingly, the documentation suggests this isn't really allowed - "The six combinations that yield interval values are valid in an interval expression", and date-date isn't one of those six. That might suggest type 14 is closer to an interval than a number type.
| |
doc_23534916
|
*
*There is an expiration setting in SDWebImage codes, should I set the expiration time to a large value to store the cache permanently?
*Since I wanted the pictures to be cached permanently, should I stored them into a dedicated folder or the default directory is sufficient? My app needs those picture to be persistent when the app is closed and re-open as well as when the phone is restarted.
*If I wanted to cache the picture permanently, is there anything else I need to watch out other than setting the expiration to a large value?
Thanks.
A: Unfortunately SDWebImage Does not provide such a capability
so to make use of the advanced caching capabilities provided by SDWebImage i wrote a wrapper around it
basically this class manages a fallback permanent cache so if the requested image not found in the SDWeb image cache "disk and memory" it will look for it in the permanent cache
and if it was found the permanent cache it will be copied to the SDwebImage cache to make use of its memory cashing in later requests
using this approach i managed to keep setting images to table cells as smooth as usual with SDWebImage
you can also trigger clearImageCache to errase the permanent cache whenever you need
.h file
@interface CacheManager : NSObject
+ (CacheManager*)sharedManager;
// Images
- (BOOL) diskImageExistsForURL:(NSURL*) url;
- (void) downloadImage:(NSURL*) url completed:(void(^)(UIImage*))onComplete;
- (void) setImage:(NSURL*)url toImageView:(UIImageView*)iv completed:(void(^)(UIImage*))onComplete;
- (void) clearImageCache;
@end
.m file
#import "CacheManager.h"
#import <SDWebImage/UIImageView+WebCache.h>
#define CACH_IMAGES_FOLDER @"ImagesData"
@implementation CacheManager
static CacheManager *sharedManager = nil;
#pragma mark -
#pragma mark Singilton Init Methods
// init shared Cache singleton.
+ (CacheManager*)sharedManager{
@synchronized(self){
if ( !sharedManager ){
sharedManager = [[CacheManager alloc] init];
}
}
return sharedManager;
}
// Dealloc shared API singleton.
+ (id)alloc{
@synchronized( self ){
NSAssert(sharedManager == nil, @"Attempted to allocate a second instance of a singleton.");
return [super alloc];
}
return nil;
}
// Init the manager
- (id)init{
if ( self = [super init] ){}
return self;
}
/**
@returns YES if image found in the permanent cache or the cache managed by SDWebImage lib
*/
- (BOOL) diskImageExistsForURL:(NSURL*) url{
// look for image in the SDWebImage cache
SDWebImageManager *manager = [SDWebImageManager sharedManager];
if([manager diskImageExistsForURL:url])
return YES;
// look for image in the permanent cache
NSString *stringPath = url.path;
NSFileManager *fileManager = [NSFileManager defaultManager];
return [fileManager fileExistsAtPath:stringPath];
}
/**
get the image with specified remote url asynchronosly
first looks for the image in SDWeb cache to make use of the disk and memory cache provided by SDWebImage
if not found, looks for it in the permanent cache we are managing, finally if not found in either places
it will download it using SDWebImage and cache it.
*/
- (void) downloadImage:(NSURL*) url completed:(void(^)(UIImage*))onComplete{
NSString *localPath = [[self getLocalUrlForImageUrl:url] path];
NSFileManager *fileManager = [NSFileManager defaultManager];
// -1 look for image in SDWeb cache
SDWebImageManager *manager = [SDWebImageManager sharedManager];
if([manager diskImageExistsForURL:url]){
[manager downloadImageWithURL:url options:SDWebImageRetryFailed
progress:^(NSInteger receivedSize, NSInteger expectedSize) {}
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
onComplete(image);
// save the image to the perminant cache for later
// if not saved before
if(image){
if ([fileManager fileExistsAtPath:localPath]){
NSURL* localeUrl = [self getLocalUrlForImageUrl:url];
[self saveImage:image toCacheWithLocalPath:localeUrl];
}
}
}];
return;
}
// -2 look for the image in the permanent cache
if ([fileManager fileExistsAtPath:localPath]){
UIImage *img = [self getImageFromCache:url];
onComplete(img);
// save image back to the SDWeb image cache to make use of the memory cache
// provided by SDWebImage in later requests
[manager saveImageToCache:img forURL:url];
return;
}
// -3 download the image using SDWebImage lib
[manager downloadImageWithURL:url options:SDWebImageRetryFailed
progress:^(NSInteger receivedSize, NSInteger expectedSize) {}
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
onComplete(image);
// save the image to the permanent cache for later
if(image){
NSURL* localeUrl = [self getLocalUrlForImageUrl:url];
[self saveImage:image toCacheWithLocalPath:localeUrl];
}
}];
}
- (void) setImage:(NSURL*)url toImageView:(UIImageView*)iv completed:(void(^)(UIImage*))onComplete{
[self downloadImage:url completed:^(UIImage * downloadedImage) {
iv.image = downloadedImage;
onComplete(downloadedImage);
}];
}
/**
@param:imgUrl : local url of image to read
*/
- (UIImage*) getImageFromCache:(NSURL*)imgUrl{
return [UIImage imageWithData: [NSData dataWithContentsOfURL:imgUrl]];
}
/**
writes the suplied image to the local path provided
*/
-(void) saveImage:(UIImage*)img toCacheWithLocalPath:(NSURL*)localPath{
NSData * binaryImageData = UIImagePNGRepresentation(img);
[binaryImageData writeToFile:[localPath path] atomically:YES];
}
// Generate local image URL baesd on the name of the remote image
// this assumes the remote images already has unique names
- (NSURL*)getLocalUrlForImageUrl:(NSURL*)imgUrl{
// Saving an offline copy of the data.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDirectory = [paths objectAtIndex:0];
NSString *folderPath = [cachesDirectory stringByAppendingPathComponent:CACH_IMAGES_FOLDER];
BOOL isDir;
// create folder not exist
if (![fileManager fileExistsAtPath:folderPath isDirectory:&isDir]){
NSError *dirWriteError = nil;
if (![fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:&dirWriteError]){
NSLog(@"Error: failed to create folder!");
}
}
NSString *imgName = [[[imgUrl path] lastPathComponent] stringByDeletingPathExtension];
NSURL *cachesDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
NSString *pathString = [NSString stringWithFormat:@"%@/%@", CACH_IMAGES_FOLDER, imgName];
return [cachesDirectoryURL URLByAppendingPathComponent:pathString];
}
/**
removes the folder contating the cahced images,
the folder will be reacreated whenever a new image is being saved to the permanent cache
*/
-(void)clearImageCache{
// set the directory path
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDirectory = [paths objectAtIndex:0];
NSString *folderPath = [cachesDirectory stringByAppendingPathComponent:CACH_IMAGES_FOLDER];
BOOL isDir;
NSError *dirError = nil;
// folder exist
if ([fileManager fileExistsAtPath:folderPath isDirectory:&isDir]){
if (![fileManager removeItemAtPath:folderPath error:&dirError])
NSLog(@"Failed to remove folder");
}
}
@end
| |
doc_23534917
|
Tap (mousedown) on the stage to create and add a child at that location.
*EDIT: I'm also trying to solve for multitouch, so multiple balls can be created at the same time.
As you hold down you can drag (pressmove) that child around and it grows (using regX/regY/scaleX/scaleY) until you release (pressup), at which point it falls (using a tick cycle).
I have everything sort of working, but I've hit a snag wherein I can't add a child and have it immediately register mousedown without releasing and pressing again.
Is there a way to manually trigger mousedown after adding, or some other workaround that makes more sense? dispatchEvent doesn't seem to be working.
Here's my stage event listener and touch bits:
stage.enableMouseOver(10);
createjs.Touch.enable(stage, false, false);
stage.preventSelection = false;
stage.addEventListener("stagemousedown", spawnsnowball);
And here are my functions. The spawnsnowball one includes displayObject event listeners verging on desperate, but the only way I've been able to get the pressmove and pressup working is to click on the same snowball again. releasesnowball right now just releases all instances of them (using a 'stagemouseup' listener), but if I can get it triggering off of pressup then I'll rewrite it to target just the event target.
function spawnsnowball(evt){
var ball = new createjs.Bitmap(loader.getResult("snowball"));
ball.crossOrigin="Anonymous";
ball.name="ball";
ball.scaleX = 0.5;
ball.scaleY = ball.scaleX;
ball.regX = ball.image.width/2;
ball.regY = ball.image.height/2;
ball.x = evt.stageX;
ball.y = evt.stageY;
ball.type = balltype;
ball.holding = 1;
ball.velX = 0;
ball.velY = 0;
ball.addEventListener("pressup",releasesnowball);
ball.addEventListener("pressmove",dragsnowball);
ball.onPress = function(mouseEvent) {};
stage.addChild(ball);
ball.dispatchEvent("mousedown");
ball.dispatchEvent("pressdown");
}
function dragsnowball(evt){
evt.target.x = evt.stageX;
evt.target.y = evt.stageY;
}
function releasesnowball(evt){
for(var i=0;i<stage.getNumChildren();i++){
var shape = stage.getChildAt(i);
if(shape.type == balltype){
if(shape.holding){
shape.holding = 0;
var dX = shape.x - shape.oldX;
var dY = shape.y - shape.oldY;
if(Math.abs(dY)>8)
dY = 8*dY/Math.abs(dY);
if(Math.abs(dX)>3)
dX = 3*dX/Math.abs(dX);
}
}
}
}
A: The pressmove event is special because it basically stores off the target of the last mousedown event, and then remembers it for pressmove and pressup events.
This means you can't really fake the event by forcing mouse events. Dispatching a mouse event from the target will not do the trick.
Instead, consider just handling the initial drag manually. You already know what you want to be the target of the pressmove, so you can listen for the stagemousemove event, and handle it yourself:
// Listen to the stagemousemove and manually call the event.
var initialDrag = stage.on("stagemousemove", function(event) {
event.target = ball; // Re-target the event so your other method works fine.
dragsnowball(event);
});
// When done, remove the move listener.
// The off() method supports a "once" parameter so you don't have to unsubscribe that listener.
stage.on("stagemouseup", function(event) {
stage.off("stagemousemove", initialDrag);
}, null, true); // Fires one time
Here is a quick sample using your code as the base: http://jsfiddle.net/3qhmur82/
I also added some comments in the demo which might be useful.
Hope that helps!
| |
doc_23534918
|
Why cannot I create a new project?
greetings and thx in advance
A: Plugin is not same as the SDK. Plugin just makes it easy to work with GWT projects.
The actual GWT compiler and libraries are present in the SDK which needs to be downloaded separately.
Once you download and extract the SDK, You have to configure its location in Eclipse's Preferences. Go to Window > Preferences > Google > Web Toolkit and add the SDK there.
A: I had the same problem.
If you do not want to use GWT just uncheck the "Use Google Web Toolkit" checkbox on that same dialog. You do not need this turned on in order to create a New Web Application Project.
I personally think it was confusing that the checkbox for GWT is turned on by default, even if you don't have one installed.
The SDK that you installed with your eclipse plugin should be sufficient.
| |
doc_23534919
|
const {
config
} = require("dotenv");
const Discord = require('discord.js');
const client = new Discord.Client();
// Variables
const ownerID = '426345341072179223';
const PREFIX = '.';
// Message to ping the bot
client.on('message', message => {
let args =
message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'ping':
message.reply('you have successfuly pinged me');
break;
}
})
client.once("ready", () => {
//When bot is ready
client.user.setActivity(`SpongeBoZZ ACAB on
YouTube`, {
type: 'LISTENING'
}); //It will set status
: )
});
// Server Stats Setup
const serverStats = {
guildID: '669622560098353152',
totalUsersID: '694688882977144854',
memberCountID: '694689022588616814',
botCountID: '694689099725930597'
};
client.on('ready', () => console.log('Bot is now
Connected '));
client.on('guildMemberAdd', member => {
if (member.guild.id !== serverStats.guildID)
return;
` client.channels.cache.get(serverStats.totalUsersID).setName(`
Total Users: $ {
member.guild.memberCount
}
`);
client.channels.cache.get(serverStats.memberCountID).setName(`
Member Count: $ {
member.guild.members.cache.filter(m => !m.user.bot).size
}
`);
client.channels.cache.get(serverStats.botCountID).setName(`
Bot Count: $ {
member.guild.members.cache.filter(m => m.user.bot).size
}
`);
});
client.on('guildMemberRemove', member =>
{
if (member.guild.id !== serverStats.guildID) return;
client.channels.cache.get(serverStats.totalUsersID).setName(`
Total Users: $ {
member.guild.memberCount
}
`);
client.channels.cache.get(serverStats.memberCountID).setName(`
Member Count: $ {
member.guild.members.cache.filter(m => !m.user.bot).size
}
`);
client.channels.cache.get(serverStats.botCountID).setName(`
Bot Count: $ {
member.guild.members.cache.filter(m => m.user.bot).size
}
`);
});
// Login to Discord
client.login(process.env.token);
A: For "Total Users", you're using .memberCount which is direct from the Discord API. For "Member Count" and "Bot Count", you're pulling the numbers directly from cache. Here, it isn't guaranteed that every member/user will be cached, which will affect the accuracy of your counts.
A: to count the member of user present on all discord server your bot is, you can do something like:
let membersCount = 0;
client.users.cache.map(users => users.id ? membersCount += 1 : false).pop()
console.log(membersCount);
Then you get the amount of users you bot can see!
to get the nb of members on a single guild you have yo change the client user by the guild collection.
client.on("message", (message) => {
let membersCount = 0;
message.guild.members.cache.map(users => users.id ? membersCount += 1 : false).pop()
console.log(membersCount);
});
| |
doc_23534920
|
Here is my code snippet:
ProgressDialog progDialog = new ProgressDialog(ProgressBarExample.this);
progDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progDialog.setMax(200);
progDialog.setMessage("Dollars in checking account:");
progDialog.setButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
progDialog.show();
here is a screenshot:
Thanks,
Ram.
A: progDialog.setProgressNumberFormat(null);
progDialog.setProgressPercentFormat(null);
A: extra info:
// wrong way
progDialog.setProgressNumberFormat(null); // NullPointerException !!!
progDialog.show();
// right way
progDialog.show();
progDialog.setProgressNumberFormat(null);
A: Create this class for Android < API Level 11 and use it instead the default ProgressDialog. It uses reflection to set the visbility to GONE:
public class CustomProgressDialog extends ProgressDialog {
public CustomProgressDialog(Context context) {
super(context);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
Method method = TextView.class.getMethod("setVisibility",
Integer.TYPE);
Field[] fields = this.getClass().getSuperclass()
.getDeclaredFields();
for (Field field : fields) {
if (field.getName().equalsIgnoreCase("mProgressNumber")) {
field.setAccessible(true);
TextView textView = (TextView) field.get(this);
method.invoke(textView, View.GONE);
}
if (field.getName().equalsIgnoreCase("mProgressPercent")) {
field.setAccessible(true);
TextView textView = (TextView) field.get(this);
method.invoke(textView, View.GONE);
}
}
} catch (Exception e) {
Log.e(TAG,
"Failed to invoke the progressDialog method 'setVisibility' and set 'mProgressNumber' to GONE.",
e);
}
}
}
| |
doc_23534921
|
When a user submits content via a php form what exactly happens?
I'm trying to understand how exactly submission data from a form gets saved so that its their for others to see. Take reddit (or even this site) for example, users fill out a form hit submit and their post is there for everyone to see forever. Does this happen no matter what? or is there more code that needs to be added. If it does happen automatically, is the data lost if the server goes offline? how is that data deleted? etc etc
Thanks for the help in advance
EDIT: I guess a better question is how exactly does POST work.
A: This is a POST example. Please try to find a tutorial to learn PHP.
<form method="POST">
<input type="text" name="yourName">
<input type="submit" value="Submit your name">
</form>
<?php
// This is a PHP comment
// We check if the POST is made
if(isset($_POST['yourName'])){
// We store the POST-variable in a usual variable
$variableWithName = $_POST['yourName'];
// Print out the name
echo "Your name is ".$variableWithName;
}
| |
doc_23534922
|
I have created dynamic data-ids carriers_{{name}}_name
in my jsp as below:
<div class="gs grid-7of8 pointer cell"><p data-id="carriers_{{name}}_name">{{name}}</p></div>
now if i want to do the DOM manipulation in my JS by searching through this data-id. How can i do it? how can i get this dynamic value {{name}} in my JS?
A: $(document).ready(functoin(){
var $text="#"+$('.cell').find('p').attr('id');
alert($($text)).html();
})
for more then one paragraphs you can use each() statement
$(document).ready(functoin(){
$('.cell').each('p'){
var $text="#"+$(this).attr('id');
alert($($text)).html();
});
});
A: I think you should just get the dynamic value in your javascript by fetching the json.
| |
doc_23534923
|
implementation 'com.google.android.material:material:1.1.0'
And use the following code
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
FloatingActionButton fab = findViewById(R.id.fab);
fab.hide() // This is the method to hide the button as the Documentation But This does not hide the button
fab.setVisibility(View.GONE) // Neither this work,
}
Is there any other specific method to hide it?
| |
doc_23534924
|
df
date overall eastern
1 1997-12-15 17.548 18.751
2 1998-01-15 16.189 17.155
3 1998-02-15 15.667 16.504
4 1998-03-15 15.509 16.208
5 1998-04-15 16.709 17.702
6 1998-05-15 18.822 19.660
7 1998-06-15 22.722 23.512
8 1998-07-15 25.372 25.912
9 1998-08-15 26.597 27.226
10 1998-09-15 25.256 26.151
11 1998-10-15 22.857 24.440
12 1998-11-15 20.242 21.867
13 1998-12-15 17.179 18.797
14 1999-01-15 16.003 17.206
15 1999-02-15 15.140 16.345
16 1999-03-15 15.522 16.689
17 1999-04-15 16.537 17.521
18 1999-05-15 19.658 20.740
19 1999-06-15 23.245 24.161
20 1999-07-15 25.313 26.053
21 1999-08-15 26.753 27.112
22 1999-09-15 26.040 26.597
23 1999-10-15 23.843 24.940
24 1999-11-15 20.940 22.375
25 1999-12-15 17.842 19.439
A: We convert the 'date' to Date class (with lubridate::ymd or as.Date from base R), extract the year as grouping variable and summarise across the columns to get the mean value
library(dplyr)
library(lubridate)
df1 %>%
group_by(year = year(ymd(date))) %>%
summarise(across(overall:eastern, mean, na.rm = TRUE))
-output
# A tibble: 3 × 3
year overall eastern
<dbl> <dbl> <dbl>
1 1997 17.5 18.8
2 1998 20.3 21.3
3 1999 20.6 21.6
If we also want by seasons, create a key value dataset with month and seasons values, join and do a group by mean
keydat <- tibble(seasons = rep(c("Winter", "Spring", "Summer", "Fall"),
each = 3), month = c("Dec", month.abb[-length(month.abb)]))
df1 %>%
mutate(date = as.Date(date), month = format(date, '%b'),
year = format(date, '%Y')) %>%
left_join(keydat) %>%
group_by(year, seasons) %>%
summarise(across(c(overall, eastern), mean, na.rm = TRUE),
.groups = 'drop')
-output
# A tibble: 9 × 4
year seasons overall eastern
<chr> <chr> <dbl> <dbl>
1 1997 Winter 17.5 18.8
2 1998 Fall 22.8 24.2
3 1998 Spring 17.0 17.9
4 1998 Summer 24.9 25.6
5 1998 Winter 16.3 17.5
6 1999 Fall 23.6 24.6
7 1999 Spring 17.2 18.3
8 1999 Summer 25.1 25.8
9 1999 Winter 16.3 17.7
Or in base R
aggregate(.~ year, transform(df1, year = format(as.Date(date),
'%Y'))[-1], FUN = mean)
year overall eastern
1 1997 17.54800 18.75100
2 1998 20.26008 21.26117
3 1999 20.56967 21.59817
data
df1 <- structure(list(date = c("1997-12-15", "1998-01-15", "1998-02-15",
"1998-03-15", "1998-04-15", "1998-05-15", "1998-06-15", "1998-07-15",
"1998-08-15", "1998-09-15", "1998-10-15", "1998-11-15", "1998-12-15",
"1999-01-15", "1999-02-15", "1999-03-15", "1999-04-15", "1999-05-15",
"1999-06-15", "1999-07-15", "1999-08-15", "1999-09-15", "1999-10-15",
"1999-11-15", "1999-12-15"), overall = c(17.548, 16.189, 15.667,
15.509, 16.709, 18.822, 22.722, 25.372, 26.597, 25.256, 22.857,
20.242, 17.179, 16.003, 15.14, 15.522, 16.537, 19.658, 23.245,
25.313, 26.753, 26.04, 23.843, 20.94, 17.842), eastern = c(18.751,
17.155, 16.504, 16.208, 17.702, 19.66, 23.512, 25.912, 27.226,
26.151, 24.44, 21.867, 18.797, 17.206, 16.345, 16.689, 17.521,
20.74, 24.161, 26.053, 27.112, 26.597, 24.94, 22.375, 19.439)),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24",
"25"))
| |
doc_23534925
| ||
doc_23534926
|
After the above-mentioned process, I made a few transactions for testing purposes. But they haven't got synced. What I realized is that it is not get synced after linking the account. Also, I am not receiving any event through the webhook.
I have written this on StackOverflow after getting fed up with the Yodlee support team as they were not able to give correct information to sort out my issue.
Also, I would like to know whether I can use Yodlee Dummy Account to test this kind of scenario.
A: If account is 2fa enabled I don't think there will be a scheduled sync to get new transactions. You need to check other API's to get updates.
| |
doc_23534927
|
=IF(OR(AND(C4>0,TODAY()-F4>250),AND(C4=0,TODAY()-D4>60)),"Sell Now", "Check back in 30")
At TODAY()-F4>250 I get a Value error if there is no data in Cell F4. I have tried variants of modifying with ISNUMBER or ISBLANK but it throws off my Logical condition and gives me false negatives when it should return TRUE.
Can I modify it somehow where if a blank exists, to proceed to the second condition in the OR argument at AND(C4=0,TODAY()-D4>60)) ? Thank you
I'm really just trying to say if this condition is true or this condition is true - sell now, otherwise check back. If I have a blank on that first argument it throws it off.
A: Use IFERROR:
If you still want the C4>0 check to happen:
=IF(OR(AND(C4>0,IFERROR(TODAY()-F4>250,TRUE)),AND(C4=0,TODAY()-D4>60)),"Sell Now", "Check back in 30")
If you want to skip the C4>0 check as well:
=IF(OR(IFERROR(AND(C4>0,TODAY()-F4>250),FALSE),AND(C4=0,TODAY()-D4>60)),"Sell Now", "Check back in 30")
It's not exactly apparent whether you want the second argument of IFERROR to be TRUE or FALSE; adjust according to whether you want the first condition to pass or not.
| |
doc_23534928
|
How can I align labels vertically, input and submit without using col-md?
<form class="form-inline" action="action1.php" method="POST">
<div class="form-group">
<label for="input1">Email test</label>
<input type="text" class="form-control" id="input1" placeholder="Email" name="email">
</div>
<button type="submit" class="btn btn-default">Submit 1</button>
</form>
<form class="form-inline" action="action2.php" method="POST">
<div class="form-group">
<label for="input2">Email</label>
<input type="text" class="form-control" id="input2" placeholder="Email" name="email">
</div>
<button type="submit" class="btn btn-default">Submit 2</button>
</form>
...
...
See:
https://jsfiddle.net/Lwss0606/
A: As per the UI image you have posted. Use col-md-x class to provide grid structure to your forms elements. For example
<form class="form-inline" action="action1.php" method="POST">
<div class="form-group">
<label for="input1" class="col-md-3">Email test</label>
<input type="text" class="form-control col-md-6" id="input1" placeholder="Email" name="email">
<button type="submit" class="btn btn-default col-md-3">Submit 1</button>
</div>
</form>
DEMO
A: you can try this style
.form-inline input{
width: 60%;
float: left;
margin-right: 5px;
}
.form-inline label {
float: left;
padding-right: 10px;
display: flex;
align-items: center;
height: 34px;
}
| |
doc_23534929
|
However, my project has an added difficulty, I have to use rules that include markers and variables.
A variable represents any letter in the alphabet and a marker is simply a character that is used as a reference to move the variables around (It doesn't have a real value).
This example duplicates every character in a string:
Alphabet: {a,b,c}
Markers: {M}
Variables: {x}
Rule 1: Mx -> xxM
Rule 2: xM -> x
Rule 3: x -> Mx
input: abc
abc //We apply rule 3
Mabc //We apply rule 1
aaMbc //We apply rule 1
aabbMc //We apply rule 1
aabbccM //We apply rule 2
aabbcc
This is my recursive function that implements a markov algorithm that only works with string inputs for example: Rule 1: "apple" -> "orange", Input: "apple".
public static String markov(String input, LinkedList<Rule> rules) {
for (Rule rule : rules) {
if (!input.equals(input.replace(rule.getFrom(), rule.getTo()))) { //If the rule matches a substring
if (rule.isTerminating()) { //If the rule is terminating
input = input.replaceFirst(Pattern.quote(rule.getFrom()), rule.getTo());
System.out.println(input); //Replace the first instance
return input; //return and end the cycle
} else {
input = input.replaceFirst(Pattern.quote(rule.getFrom()), rule.getTo());
System.out.println(input);
return markov(input, rules); //Start looking again for matching rules
}
}
}
return input;
}
I can't figure out how to implement variables and markers into this logic so perhaps someone can educate me on the best way to implement this logic? any advice is welcome.
If the question doesn't comply with SO guidelines please let me know why in the comments so I don't repeat the mistake.
Thank You!
GitHub
A: I think the easiest way to do this is using Java regular expressions. Once you get your head around those, then the following rules should work for your example:
Rule 1: "M([a-c])" -> "$1$1M"
Rule 2: "([a-c])M" -> "$1" (terminating)
Rule 3: "([a-c])" -> "M$1"
Note that you need a couple of tweaks to your current method to make this work...
replace takes a literal string as it's first parameter whereas replaceFirst uses a regex, so:
replace: if (!input.equals(input.replace(rule.getFrom(), rule.getTo()))) {
with: if (!input.equals(input.replaceFirst(rule.getFrom(), rule.getTo()))) {
You are quoting the rule.getFrom() string, which will not work with regular expressions, so:
replace: input = input.replaceFirst(Pattern.quote(rule.getFrom()), rule.getTo());
with: input = input.replaceFirst(rule.getFrom(), rule.getTo());
At that point, you have a bit of duplication in the code calling replaceFirst twice, so you could stick that in a temp variable the first time and reuse it:
String next = input.replace(rule.getFrom(), rule.getTo());
if (!input.equals(next)) {
...
input = next;
...
}
As you are currently quoting the entire rule.getFrom() string I'm guessing you have had problems with regular expression special characters in this before. If so, you'll need to address them individually when creating the rules. I really don't want to get into regular expressions here as it is a huge area and is completely separate to the Markov algorithm, so if you are having problems with these then please do some research online (e.g. Regular Expressions and Capturing Groups), or ask a separate question here focusing on the regular expression specific problem.
Note that you can still combine these with the normal rules so (changing the marker character from M to # to allow M to be used in the alphabet), these rules:
"A" -> "apple"
"B" -> "bag"
"S" -> "shop"
"T" -> "the"
"the shop" -> "my brother"
"#([a-zA-Z .])" -> "$1$1#"
"([a-zA-Z .])#" -> "$1" (terminating)
"([a-zA-Z .])" -> "#$1"
Would convert:
from: I bought a B of As from T S.
to: II bboouugghhtt aa bbaagg ooff aapppplleess ffrroomm mmyy bbrrootthheerr..
Hope this helps.
| |
doc_23534930
|
However, my code for the scrolling to the bottom is not working at all.
To demonstrate this, I created this fiddle:
https://jsfiddle.net/jcp1sw23/
And this is my jquery code:
$(document).on("click",".sendPm",function() {
var txt = $('#message2').val();
var htm = '<li id="'+ txt +'" class="self"><div class="msg"><p>'+ txt +'</p><time>7:45</time></div></li>';
$(".endDivChat").before(htm);
var $t = $('#messages');
$t.animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
});
If you type a few messages until the messages elemet is full, you should see the scrollbar appears. But it doesn't animate or scroll to the bottom.
Specifically, this is my code for the scrolling to the bottom:
var $t = $('#messages');
$t.animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
Could someone please advice on this issue?
Thanks in davance.
A: $("html, body").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
you were selecting the messages at the front, you want the html body since that is what is scrolling:)
here is it working: https://jsfiddle.net/jcp1sw23/31/
A: Because your scrolling element is not the #messages element but the body: so try this:
$(document).on("click", ".sendPm", function() {
var txt = $('#message2').val();
var htm = '<li id="' + txt + '" class="self"><div class="msg"><p>' + txt + '</p><time>7:45</time></div></li>';
$(".endDivChat").before(htm);
$("html, body").animate({
scrollTop: 2000
}, 600);
});
A: Here you are applying scroll on messages ul element. While after watching your demo it was clear that your scroll is at body level and hence the scrolling code should be:
var $t = $('html');
$t.animate({"scrollTop": $('body')[0].scrollHeight}, "slow");
Here your body has scrollHeight which needs to be set on parent container of fixed height i.e. html element.
Here is js fiddle link which is working after adding above code:
https://jsfiddle.net/jcp1sw23/27/
A: You have to use
$("html, body").animate({ scrollTop: 1000 }, 1000);
to scroll the scrollbar to the bottom whenever user sends the message
$(document).on("click",".sendPm",function() {
var txt = $('#message2').val();
var htm = '<li id="'+ txt +'" class="self"><div class="msg"><p>'+ txt +'</p><time>7:45</time></div></li>';
$(".endDivChat").before(htm);
$("html, body").animate({ scrollTop: 1000 }, "slow");
});
@import url(https://fonts.googleapis.com/css?family=Lato:100,300,400,700);
@import url(https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css);
html, body {
background: #e5e5e5;
font-family: 'Lato', sans-serif;
/*margin: 0px auto;*/
}
::selection{
background: rgba(82,179,217,0.3);
color: inherit;
}
a{
color: rgba(82,179,217,0.9);
}
/* M E N U */
.menu {
position: absolute;
top: 0px;
left: 0px;
right: 0px;
width: 100%;
height: 50px;
background: rgba(82,179,217,0.9);
z-index: 100;
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
.back {
position: absolute;
width: 90px;
height: 50px;
top: 0px;
left: 0px;
color: #fff;
line-height: 50px;
font-size: 30px;
padding-left: 10px;
cursor: pointer;
}
.back img {
position: absolute;
top: 5px;
left: 30px;
width: 40px;
height: 40px;
background-color: rgba(255,255,255,0.98);
border-radius: 100%;
-webkit-border-radius: 100%;
-moz-border-radius: 100%;
-ms-border-radius: 100%;
margin-left: 15px;
}
.back:active {
background: rgba(255,255,255,0.2);
}
.name{
position: absolute;
top: 3px;
left: 110px;
font-family: 'Lato';
font-size: 25px;
font-weight: 300;
color: rgba(255,255,255,0.98);
cursor: default;
}
.last{
position: absolute;
top: 30px;
left: 115px;
font-family: 'Lato';
font-size: 11px;
font-weight: 400;
color: rgba(255,255,255,0.6);
cursor: default;
}
/* M E S S A G E S */
.chat {
list-style: none;
background: none;
margin: 0;
padding: 0 0 50px 0;
margin-top: 60px;
margin-bottom: 10px;
}
.chat li {
padding: 0.5rem;
overflow: hidden;
display: flex;
}
.chat .avatar {
width: 40px;
height: 40px;
position: relative;
display: block;
z-index: 2;
border-radius: 100%;
-webkit-border-radius: 100%;
-moz-border-radius: 100%;
-ms-border-radius: 100%;
background-color: rgba(255,255,255,0.9);
}
.chat .avatar img {
width: 40px;
height: 40px;
border-radius: 100%;
-webkit-border-radius: 100%;
-moz-border-radius: 100%;
-ms-border-radius: 100%;
background-color: rgba(255,255,255,0.9);
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
.chat .day {
position: relative;
display: block;
text-align: center;
color: #c0c0c0;
height: 20px;
text-shadow: 7px 0px 0px #e5e5e5, 6px 0px 0px #e5e5e5, 5px 0px 0px #e5e5e5, 4px 0px 0px #e5e5e5, 3px 0px 0px #e5e5e5, 2px 0px 0px #e5e5e5, 1px 0px 0px #e5e5e5, 1px 0px 0px #e5e5e5, 0px 0px 0px #e5e5e5, -1px 0px 0px #e5e5e5, -2px 0px 0px #e5e5e5, -3px 0px 0px #e5e5e5, -4px 0px 0px #e5e5e5, -5px 0px 0px #e5e5e5, -6px 0px 0px #e5e5e5, -7px 0px 0px #e5e5e5;
box-shadow: inset 20px 0px 0px #e5e5e5, inset -20px 0px 0px #e5e5e5, inset 0px -2px 0px #d7d7d7;
line-height: 38px;
margin-top: 5px;
margin-bottom: 20px;
cursor: default;
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
.other .msg {
order: 1;
border-top-left-radius: 0px;
box-shadow: -1px 2px 0px #D4D4D4;
}
.other:before {
content: "";
position: relative;
top: 0px;
right: 0px;
left: 40px;
width: 0px;
height: 0px;
border: 5px solid #fff;
border-left-color: transparent;
border-bottom-color: transparent;
}
.self{
justify-content: flex-end;
align-items: flex-end;
}
.self li{
background: #e1ffc7;
}
.self .msg {
order: 1;
border-bottom-right-radius: 0px;
box-shadow: 1px 2px 0px #D4D4D4;
}
.self .avatar {
order: 2;
}
.self .avatar:after {
content: "";
position: relative;
display: inline-block;
bottom: 19px;
right: 0px;
width: 0px;
height: 0px;
border: 5px solid #fff;
border-right-color: transparent;
border-top-color: transparent;
box-shadow: 0px 2px 0px #D4D4D4;
}
.msg {
background: white;
min-width: 50px;
padding: 10px;
border-radius: 2px;
box-shadow: 0px 2px 0px rgba(0, 0, 0, 0.07);
}
.msg p {
font-size: 0.8rem;
margin: 0 0 0.2rem 0;
color: #777;
}
.msg img {
position: relative;
display: block;
width: 450px;
border-radius: 5px;
box-shadow: 0px 0px 3px #eee;
transition: all .4s cubic-bezier(0.565, -0.260, 0.255, 1.410);
cursor: default;
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
.self .msg{
background: #e1ffc7 !important;
}
@media screen and (max-width: 800px) {
.msg img {
width: 300px;
}
}
@media screen and (max-width: 550px) {
.msg img {
width: 200px;
}
}
.msg time {
font-size: 0.7rem;
color: #ccc;
margin-top: 3px;
float: right;
cursor: default;
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
.msg time:before{
content:"\f017";
color: #ddd;
font-family: FontAwesome;
display: inline-block;
margin-right: 4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
<div class="back"> <img src="https://media.gettyimages.com/photos/close-up-portrait-of-teenage-girl-picture-id518339053" draggable="false"/></div>
<div class="name">test user</div>
<div class="last status">Offline</div>
</div>
<ul class="chat" id="messages">
<div class="endDivChat"></div>
<!--<li class="other">
<div class="avatar"><img src="https://i.imgur.com/DY6gND0.png" draggable="false"/></div>
<div class="msg">
<p>Hola!</p>
<p>Te vienes a cenar al centro? <emoji class="pizza"/></p>
<time>20:17</time>
</div>
</li>
<li class="self">
<div class="avatar"><img src="https://i.imgur.com/HYcn9xO.png" draggable="false"/></div>
<div class="msg">
<p>Puff...</p>
<p>Aún estoy haciendo el contexto de Góngora... <emoji class="books"/></p>
<p>Mejor otro día</p>
<time>20:18</time>
</div>
</li>-->
</ul>
<div style="width:100%; height:44px; position:fixed; bottom:0; left:0;z-index:10;background:#fff;">
<input style="padding-left:15px;border:none;height:44px;width:80%;display:inline-block;float:left; -webkit-box-sizing: border-box; -moz-box-sizing: border-box;box-sizing: border-box;" id="message2" type="text" placeholder="Type here!"/>
<button style="color:rgba(82,179,217,0.9);font-size:24px;text-align:center;line-height:44px;width:20%;display:inline-block;float:left; -webkit-box-sizing: border-box; -moz-box-sizing: border-box;box-sizing: border-box;" class="sendPm" >
<div class="circle" style="">
<i class="zmdi zmdi-mail-send"></i> Send
</div>
</button>
</div>
| |
doc_23534931
|
fileLake = open("lakes.txt", "r") # has two columns
listLake = []
for lay in fileLake:
line = lay.strip().split(",")
nameLake = line[0]
waterQuality = line[1]
listLake = nameLake, waterQuality
print(listLake)
filePortage = open("portages.txt", "r") # has three columns
for ages in filePortage:
inLand = ages.strip().split(",")
lake1 = inLand[0]
lake2 = inLand[1]
distance = inLand[2]
data = lake1, lake2, distance
result = data, listLake
print(result)
the output should be something like this
manomin, winnanage, 0.6, upper, good
but for some reason i keep getting the last input of the lakes combining with each line of the portage file like this
(('Manomin', ' Winnange', ' 0.6'), ('Caddy', ' average'))
(('Winnange', ' Upper Stewart', ' 0.8'), ('Caddy', ' average'))
(('Lower Stewart', ' Upper Stewart', ' 0.1'), ('Caddy', ' average'))
(('Lower Stewart', ' Geejay', ' 0.4'), ('Caddy', ' average'))
(('Manomin', ' Geejay', ' 0.75'), ('Caddy', ' average'))
(('Crabclaw', ' Winnange', ' 1.25'), ('Caddy', ' average'))
(('Crabclaw', ' Eagle', ' 0.35'), ('Caddy', ' average'))
(('Falcon', ' West Hawk', ' 1.7'), ('Caddy', ' average'))
(('West Hawk', ' Caddy', ' 2.4'), ('Caddy', ' average'))
can someone explain, what i am doing wrong here
thank you
A: ASSUMING the two files have the same number of lines, this will do it:
fileLake = open("lakes.txt", "r") # has two columns
filePortage = open("portages.txt", "r") # has three columns
for line1,line2 in zip(fileLake.readlines(), filePortage.readlines()):
lake = line1.strip().split(",")
port = line2.strip().split(",")
print( ",".join(lake + port) )
A: There are multiple ways of fixing the issue.
The thing that you are doing wrong is : first iterating over the filesLake and in line 7 the last element of the list(of file elements) is being assigned to listLake, so in 2nd last line listLake will have only one element and that is getting added for every element of other file(because we are in loop of second file)
FIX :
In line 7 : replace listLake = nameLake, waterQuality
with listLake.append(tuple(nameLake, waterQuality))
do the same in second loop, for data list -> append tuple of data
and then concat both the lists in second last line(keep it outside the 2nd loop)
result = data + listLake
Not performing any other checks.
| |
doc_23534932
|
Can you please help me to upload multiple pdf files and upload in sql?
Thank you.
<div>
<label style="font-size: 14px;">
<span style='color:navy;font-weight:bold'>Attachment Instructions :</span>
</label>
<ul>
<li>
Allowed only files with extension (jpg, png, gif)
</li>
<li>
Maximum number of allowed files 10 with 300 KB for each
</li>
<li>
you can select files from different folders
</li>
</ul>
<!--To give the control a modern look, I have applied a stylesheet in the parent span.-->
<span class="btn btn-success fileinput-button">
<span>Select Attachment</span>
<input type="file" name="files[]" id="files" multiple accept="image/jpeg, image/png, image/gif,"><br />
</span>
<output id="Filelist"></output>
</div>
document.addEventListener("DOMContentLoaded", init, false);
//To save an array of attachments
var AttachmentArray = [];
//counter for attachment array
var arrCounter = 0;
//to make sure the error message for number of files will be shown only one time.
var filesCounterAlertStatus = false;
//un ordered list to keep attachments thumbnails
var ul = document.createElement("ul");
ul.className = "thumb-Images";
ul.id = "imgList";
function init() {
//add javascript handlers for the file upload event
document
.querySelector("#files")
.addEventListener("change", handleFileSelect, false);
}
//the handler for file upload event
function handleFileSelect(e) {
//to make sure the user select file/files
if (!e.target.files) return;
//To obtaine a File reference
var files = e.target.files;
// Loop through the FileList and then to render image files as thumbnails.
for (var i = 0, f; (f = files[i]); i++) {
//instantiate a FileReader object to read its contents into memory
var fileReader = new FileReader();
// Closure to capture the file information and apply validation.
fileReader.onload = (function(readerEvt) {
return function(e) {
//Apply the validation rules for attachments upload
ApplyFileValidationRules(readerEvt);
//Render attachments thumbnails.
RenderThumbnail(e, readerEvt);
//Fill the array of attachment
FillAttachmentArray(e, readerEvt);
};
})(f);
// Read in the image file as a data URL.
// readAsDataURL: The result property will contain the file/blob's data encoded as a data URL.
// More info about Data URI scheme https://en.wikipedia.org/wiki/Data_URI_scheme
fileReader.readAsDataURL(f);
}
document
.getElementById("files")
.addEventListener("change", handleFileSelect, false);
}
//To remove attachment once user click on x button
jQuery(function($) {
$("div").on("click", ".img-wrap .close", function() {
var id = $(this)
.closest(".img-wrap")
.find("img")
.data("id");
//to remove the deleted item from array
var elementPos = AttachmentArray.map(function(x) {
return x.FileName;
}).indexOf(id);
if (elementPos !== -1) {
AttachmentArray.splice(elementPos, 1);
}
//to remove image tag
$(this)
.parent()
.find("img")
.not()
.remove();
//to remove div tag that contain the image
$(this)
.parent()
.find("div")
.not()
.remove();
//to remove div tag that contain caption name
$(this)
.parent()
.parent()
.find("div")
.not()
.remove();
//to remove li tag
var lis = document.querySelectorAll("#imgList li");
for (var i = 0; (li = lis[i]); i++) {
if (li.innerHTML == "") {
li.parentNode.removeChild(li);
}
}
});
});
//Apply the validation rules for attachments upload
function ApplyFileValidationRules(readerEvt) {
//To check file type according to upload conditions
if (CheckFileType(readerEvt.type) == false) {
alert(
"The file (" +
readerEvt.name +
") does not match the upload conditions, You can only upload jpg/png/gif files"
);
e.preventDefault();
return;
}
//To check file Size according to upload conditions
if (CheckFileSize(readerEvt.size) == false) {
alert(
"The file (" +
readerEvt.name +
") does not match the upload conditions, The maximum file size for uploads should not exceed 300 KB"
);
e.preventDefault();
return;
}
//To check files count according to upload conditions
if (CheckFilesCount(AttachmentArray) == false) {
if (!filesCounterAlertStatus) {
filesCounterAlertStatus = true;
alert(
"You have added more than 10 files. According to upload conditions you can upload 10 files maximum"
);
}
e.preventDefault();
return;
}
}
//To check file type according to upload conditions
function CheckFileType(fileType) {
if (fileType == "image/jpeg") {
return true;
} else if (fileType == "image/png") {
return true;
} else if (fileType == "image/gif") {
return true;
} else {
return false;
}
return true;
}
//To check file Size according to upload conditions
function CheckFileSize(fileSize) {
if (fileSize < 300000) {
return true;
} else {
return false;
}
return true;
}
//To check files count according to upload conditions
function CheckFilesCount(AttachmentArray) {
//Since AttachmentArray.length return the next available index in the array,
//I have used the loop to get the real length
var len = 0;
for (var i = 0; i < AttachmentArray.length; i++) {
if (AttachmentArray[i] !== undefined) {
len++;
}
}
//To check the length does not exceed 10 files maximum
if (len > 9) {
return false;
} else {
return true;
}
}
//Render attachments thumbnails.
function RenderThumbnail(e, readerEvt) {
var li = document.createElement("li");
ul.appendChild(li);
li.innerHTML = [
'<div class="img-wrap"> <span class="close">×</span>' +
'<img class="thumb" src="',
e.target.result,
'" title="',
escape(readerEvt.name),
'" data-id="',
readerEvt.name,
'"/>' + "</div>"
].join("");
var div = document.createElement("div");
div.className = "FileNameCaptionStyle";
li.appendChild(div);
div.innerHTML = [readerEvt.name].join("");
document.getElementById("Filelist").insertBefore(ul, null);
}
//Fill the array of attachment
function FillAttachmentArray(e, readerEvt) {
AttachmentArray[arrCounter] = {
AttachmentType: 1,
ObjectType: 1,
FileName: readerEvt.name,
FileDescription: "Attachment",
NoteText: "",
MimeType: readerEvt.type,
Content: e.target.result.split("base64,")[1],
FileSizeInBytes: readerEvt.size
};
arrCounter = arrCounter + 1;
}
| |
doc_23534933
|
<ul>
<li>List Item 01</li>
<li>List Item 02</li>
<li>List Item 03</li>
<li>List Item 04</li>
<li>List Item 05</li>
<li>List Item 06</li>
<li>List Item 07</li>
<li>List Item 08</li>
</ul>
With this list, I want to Keep a fixed width space in between item 04 and 05. And first four items should be align to right of that space and last four to align to left as below image I attached.
I tried it something like this:
ul {
list-style: none;
padding: 0;
margin: 0;
display: flex;
}
ul li:nth-child(4) {
margin-right: 10em;
}
It seems ok for me, but one thing is when the list have 4 or 6 items then it should group 2 or 3.
Can anybody tell what would be the solution for this. Its good if I have CSS only solution.
Thank you.
A: Its interesting!
Need find the middle one to do something without use js.
So i use odd and even to split in half, then use pseudo-element to become the middle one.
see below.
* {
margin: 0;
padding: 0;
list-style: none;
}
ul {
list-style: none;
padding: 0;
margin: 0;
display: flex;
justify-content: center;
width: 60%;
margin: auto;
}
li{
width: 10em;
border: 1px solid #000;
}
ul li:nth-child(odd) {
order: 0;
}
ul li:nth-child(even) {
order: 2;
}
ul::after {
content: '';
display: block;
width: 10rem;
order: 1;
}
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
<li>item5</li>
<li>item6</li>
<li>item7</li>
<li>item8</li>
</ul>
=============================================================
JS
let num = document.getElementsByTagName('li');
let half = num.length / 2;
let li = document.createElement('li');
num[half].parentNode.insertBefore(li, num[half])
* {
margin: 0;
padding: 0;
list-style: none;
}
ul {
list-style: none;
padding: 0;
margin: 0;
display: flex;
justify-content: center;
width: 60%;
margin: auto;
}
li{
width: 10em;
border: 1px solid #000;
}
li:empty{
border: none;
}
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
<li>item5</li>
<li>item6</li>
<li>item7</li>
<li>item8</li>
</ul>
================================================
JQ
var li = $('ul li');
$($('<li>')).insertBefore(li[li.length / 2])
* {
margin: 0;
padding: 0;
list-style: none;
}
ul {
list-style: none;
padding: 0;
margin: 0;
display: flex;
justify-content: center;
width: 60%;
margin: auto;
}
li {
width: 10em;
border: 1px solid #000;
}
li:empty {
border: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
<li>item5</li>
<li>item6</li>
<li>item7</li>
<li>item8</li>
</ul>
| |
doc_23534934
|
Here is an example about my problem:
public class ListFragment extends Fragment {
private MyAdapter adapter;
private List<String> data = new ArrayList<>();
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
for (int i = 1; i < 30; i++) {
data.add("POS: " + i);
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_list, container, false);
adapter = new MyAdapter();
((RecyclerView) root.findViewById(R.id.bone_list)).setAdapter(adapter);
return root;
}
@Override
public void onResume() {
super.onResume();
data.add("POS: " + (data.size() + 1));
// Working
//adapter.setData(data);
// Not working
Observable.just(data)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<String>>() {
@Override
public void accept(List<String> strings) throws Exception {
adapter.setData(strings);
}
});
}
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> values = new ArrayList<>();
public void setData(List<String> items) {
values = items;
notifyDataSetChanged();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_content, parent, false));
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.content.setText(values.get(position));
holder.root.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().beginTransaction()
.replace(R.id.container, Fragment.instantiate(getContext(), DetialFragment.class.getName()))
.addToBackStack(null)
.commit();
}
});
}
@Override
public int getItemCount() {
return values.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
final View root;
final TextView content;
ViewHolder(View view) {
super(view);
root = view;
content = (TextView) view.findViewById(R.id.content);
}
}
}
}
Working (simple set data):
Not working (rx):
Thanks,
Robert
A: I may be late but got the same problem.
RecyclerView automatically (as any view with ID) saves state, but you should provide a data before the first layout pass.
So synchronous adapter.setData(data) works, but asynchronous Rx operations don't.
You can cache data and set it synchronously or directly save and set position in your accept function.
| |
doc_23534935
|
I know I could potentially just run bower link to symlink a local copy of the cloned repo elsewhere - or even cd into the package dir and clone the repo inside this but I thought maybe it was possible via config?
| |
doc_23534936
|
I do a simple test in my controller.
In my controller, i placed this code:
`include(app_path().'/Classes/PHPExcel.php');`
`include(app_path().'/Classes/PHPExcel/Writer/Excel2007.php');`
Then I instantiate the object PHPExcel :
`$workbook = new PHPExcel;`
I activate the sheet on which I work (the default form), with method ->getActiveSheet().
`$sheet = $workbook->getActiveSheet();`
I filled my first cell with the method ->setCellValue().
`$sheet->setCellValue('A1','MaitrePylos');`
Finally to create the file, I need to instantiate an object writer, specific to the type of picture I want to generate.
`$writer = new PHPExcel_Writer_Excel2007($workbook);`
I give a name to my file, and save :
`$records = 'storage/app/sampleData/fichier.xlsx';`
`$writer->save($records);`
Result: I have a generated error
Class 'App\Http\Controllers\PHPExcel_Writer_Excel2007' not found
Who can help me to better organize my code and fix my error problem?
A: Just use the Laravel Excel Package, behind the scenes it uses the PHPExcel class.
https://github.com/Maatwebsite/Laravel-Excel
| |
doc_23534937
|
When I communicate with one of them, everything is fine.
When I communicate with two, a few minutes into the convo, my message (short or long, text or sticker or picture) gets stuck sending for a number of minutes. I am not able to receive in that channel either. After a number of minutes, the send is completed and the channel works again.
At the same moment, even while I am "stuck" in the three-person channel, I can change over to a channel shared with only one of them and messages go back and forth just fine. But in those one-on-one conversations, I see spinning circles which seem to happen when the iphone person I am communicating with one-on-one is also communicating on the three-person channel with the other iphone person.
We have deleted the conversation and recreated it. The problem persists.
Messages does this on my phone. Sometimes I have the Messages for Web chromium-browser extension open on my desktop at the same time, and sometimes not.
Any ideas what I might do?
| |
doc_23534938
|
Question
I want to disable a single option with JS. I tried using the following code:
var input = $('input[value="' + selectedPriLang + "Sec" + '"]');
input.prop('disabled', false);
input.parent('li').addClass('disabled');
It kind of works, but the problem is I can still enable the option using the Select all button.
Also, not sure if relevant, I execute the code in a onChange from a different multiselect.
<select id="sel_secLang" multiple="multiple">
<option value="nlSec" disabled="disabled">Dutch</option>
<option value="enSec">English</option>
<option value="deSec">German</option>
<option value="FrSec">French</option>
</select>
Hope this explanation is clear enough, first question ;D.
Answer
Although Joe's answer worked I tried it out myself, For disabling:
var input = $('input[value="' + selectedPriLang + "Sec" + '"]');
input.prop('disabled', true);
var input2 = input.parent('label').parent('a').parent('li');
input4.removeClass('active');
input4.addClass('disabled');
For enabling:
var input = $('input[value="' + selectedPriLang + "Sec" + '"]');
input.prop('disabled', false);
var input2 = input.parent('label').parent('a').parent('li');
input2.removeClass('disabled');
Just the value of the input
selectedPriLang = $('#sel_priLang option:selected').val();
A: Just a quick note to clarify: disabling the corresponding checkbox and adding the .disabled class to the appropriate li is not sufficient. You also have to disable the underlying option. Example (can also be found in the documentation):
<script type="text/javascript">
$(document).ready(function() {
$('#example-disable-javascript').multiselect({
includeSelectAllOption: true
});
$('#example-disable-javascript-disable').on('click', function() {
var input = $('#example-disable-javascript-container input[value="3"]');
var option = $('#example-disable-javascript-container option[value="3"]');
input.prop('disabled', true);
option.prop('disabled', true);
input.parent('label').parent('a').parent('li').addClass('disabled');
});
$('#example-disable-javascript-check').on('click', function() {
var options = '';
$('#example-disable-javascript option:selected').each(function() {
options += $(this).val() + ', ';
});
alert(options.substr(0, options.length - 2));
});
});
</script>
<div class="btn-group" id="example-disable-javascript-container">
<select id="example-disable-javascript" multiple="multiple">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
<option value="6">Option 6</option>
</select>
<button id="example-disable-javascript-disable" class="btn btn-primary">Disable an option!</button>
<button id="example-disable-javascript-check" class="btn btn-primary">Check</button>
</div>
A: You'll have to process the disabled events in an on-change handler on you're own and de-select them when the select-all is picked. Generally the process could look like:
*
*Capture on selection event for select all
*Iterate on elements
*Remove the checked attribute for the disabled elements
Something along the lines of capturing on change, find disabled, and unchecking them:
$('#sel_secLang').multiselect({
onChange: function(option, checked, select) {
$('input[type=checkbox]:disabled').each(checkbox, function(){
checkbox.attr('checked', false);
});
}
});
| |
doc_23534939
|
Here, this code http://jsfiddle .net/dk5sy93d/
A: I'm new to Jquery (since yesterday). I have to make a simple slider in an upcoming web development competition. This is just something I wrote because everything I seem to come across has a large library attached to it.
//Manual Slider Control Jquery
$("#slider-next").click(function(){
if($(".slider-a").is(":visible")){
$(".slider-a").hide(3000);
}else{
$(".slider-b").hide(3000);
}
});
$("#slider-prev").click(function(){
if(($(".slider-a").not(":visible")) && ($(".slider-b").is(":visible"))){
$(".slider-a").show(3000);
}else if(($(".slider-a").not(":visible")) && ($(".slider-b").not(":visible"))){
$(".slider-b").show(3000);
}
});
/* Slider CSS */
#slider-container{
margin:auto;
text-align:center;
}
#slider-content{
margin:auto;
height:300px;
width:400px;
overflow:hidden;
border:2px solid #000;
background-color:grey;
}
#slider-controls{
margin:auto;
text-align:center;
width:400px;
}
#slider-controls button{
background-color:#000;
padding:0 15px;
font-size:1em;
border-radius: 0 0 15px 15px;
color:white;
}
#slider-prev{
float:left;
}
#slider-next{
float:right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="slider-container">
<div id="slider-content">
<img class="slider-img slider-a" src="http://www.light2015.org/.imaging/stk/pop/zoom/dam/CosmicLight/A-Universe-of-Images/Vela_Supernova_Remnant/jcr:content/Vela_Supernova_Remnant.2014-07-17-20-32-16.png" width="400px" height="300px" />
<img class="slider-img slider-b" src="http://www.sciuridae.co.uk/photography/images/blown_out_skies/two_images.jpg" width="400px" height="300px" />
<img class="slider-img clider-c" src="http://www1.hw.ac.uk/estate/images/landscape-images/cycleways-and-footpaths-big.JPG" width="400px" height="300px" />
</div>
<div id="slider-controls">
<button id="slider-prev">Previous</button>
<button id="slider-next">Next</button>
</div>
</div>
Please comment on this answer if you feel it can be simplified further and offer the same (if not improved) functionality.
A: Here is the JS for your HTML.
http://jsbin.com/nalewayume/1/edit?js,console,output
function nextSlide() {
if(currentSlide < allSlides) {
$slide.eq(currentSlide).fadeOut(200);
$slide.eq(currentSlide + 1).fadeIn(200);
currentSlide+=1;
}
}
| |
doc_23534940
|
The regression is a basic one, with just one predictor variable and one dependent. How do I handle the fact that i need to pass an aggregated value to the lm() function, even though i need to send the entire column?
With a column called 'Predictor', and another called 'Dependent', I essentially need to do this in Tableau:
fit <- lm(df$Dependent ~ df$Predictor)
return fit
Tableau does not let me do this unless I pass to it
SUM[Dependent] and SUM[Predictor]
But instead of aggregating it, i need it to work on the entire column
Thanks
A: Add a dimension to any shelf, say the detail shelf, that partitions the data at the level you wish. If you want each individual row to be included in the model, use a dimension that has a unique value for each row, say some sort of row id.
BTW, you know you can perform regression models directly within Tableau, right? You don't need to call out to R just to fit a linear model.
| |
doc_23534941
|
So I've got this piece of code here
mov DWORD PTR [ebp-4],0X0
cmp DWORD PTR [ebp-4],0X9
.
.
.
lea eax,[ebp-4]
inc DWORD PTR [eax]
...
and I am not sure why exactly do I have to use the "lea" and "eax" here. If I understand it correctly, [ebp-4] points to int(4 bytes) with the value of 0. Could I increment it directly without using "eax" reigster ?
Also, obviously I can directly compare the value in [ebp-4] with value "9" so why couldn't I increment it in the same fashion ?
Thanks for every hint.
A: Simple:
lea eax,[ebp-4] ; eax = ebp-4
inc DWORD PTR [eax] ;decrease dword at location ebp-4 by one.
If you had written:
inc DWORD PTR [ebp-4]
It would have done the exact same thing.
There is no need to use EAX here, you can use complex addressing anywhere you can address memory at no cost (other than perhaps instruction length).
Perhaps the code is reusing eax a lot further down, or perhaps you're looking at unoptimized code.
| |
doc_23534942
|
for example: if user entered input:
I like the red color
blue is also nice
and green is lovely
but I don't like orange
output:
but I don't like orange
and green is lovely
blue is also nice
I like the red color
Thanks in advance!
#include<iostream>
#include<string>
using namespace std;
const int SIZE= 500;
int main()
{
const int SIZE = 500;
char mystring[SIZE];
int i;
for(i=0; i<SIZE; i++)
{
cout<<"Enter a string: ";
cin.getline(mystring, SIZE);
} while (mystring != 0);
char * reverse= new char[strlen(mystring) + 1];
char *p1 = mystring+ strlen(mystring);
char *p2 = reverse;
while(p1 != mystring)
{
p1--;
*p2= *p1;
p2++;
}
*p2 = '\0';
cout << reverse<<endl;
system("PAUSE");
return 0;
}
A: A considerable way you're intended to approach this is the following algorithm:
*
*Load the file into a buffer, terminating it with a null char.
*Position a pointer p to the location of the last buffer slot.
*While p is not pointing to the start of the buffer do the following:
*
*If the character is a newline ('\n') then
*
*Send the string past the newline (p+1) to stdout.
*Overwrite the newline pointed to by p with a null char.
*Decrement p back one char position.
*After the above loop is finished there is one line remaining: the first one. send it to stdout and you're done.
Or so I am led to believe. Important things to consider are the following:
*
*Does the algorithm work with an empty file?
*Does the algorithm work with a file containing ONLY newlines?
*Does the algorithm work with a multi-line file WITH NO trailing newline?
*Does the algorithm work with a single line file WITH NO trailing newline?
*Does the algorithm work with a multi-line file WITH trailing newline?
*Does the algorithm work with a single line file WITH trailing newline?
That being said, here is a potential candidate:
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
// assume the file to reverse-print is the first
// command-line parameter. if we don't have one
// we need to leave now.
if (argc < 2)
return EXIT_FAILURE;
// will hold our file data
std::vector<char> data;
// open file, turning off white-space skipping
ifstream inf(argv[1]);
inf.seekg(0, inf.end);
size_t len = inf.tellg();
inf.seekg(0, inf.beg);
// resize buffer to hold (len+1) chars
data.resize(len+1);
inf.read(&data[0], len);
data[len] = 0; // terminator
// walk the buffer backwards. at each newline, send
// everything *past* it to stdout, then overwrite the
// newline char with a nullchar (0), and continue on.
char *start = &data[0];
char *p = start + (data.size()-1);
for (;p != start; --p)
{
if (*p == '\n')
{
if (*(p+1))
cout << (p+1) << endl;
*p = 0;
}
}
// last line (the first line)
cout << p << endl;
return EXIT_SUCCESS;
}
Input
I like the red color
blue is also nice
and green is lovely
but I don't like orange
Output
but I don't like orange
and green is lovely
blue is also nice
I like the red color
A Considerably Simpler Approach
There are much simpler ways to do this, and I'll explain each step in comment along the way. Chance are you can't use something like this, but it is important you understand what is available to you when you can:
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
// assume the file to reverse-print is the first
// command-line parameter. if we don't have one
// we need to leave now.
if (argc < 2)
return EXIT_FAILURE;
// collection that will hold our lines of text
vector<string> lines;
// read lines one at a time until none are returned
// pushing each line in to our vector.
ifstream inf(argv[1]);
string line;
while (getline(inf, line))
lines.push_back(line);
inf.close();
// a LOT happens in the next single line of code, and
// I will try to describe each step along the way.
//
// we use std::copy() to copy all "items" from
// a beginning and ending iterator pair. the
// target of the copy is another iterator.
//
// our target iterator for our formatted ouput
// is a special iterator class designed to
// perform an output-stream insertion operation
// (thats the << operator) to the stream it is
// constructed with (in our case cout) using each
// item we give it from our copy-iteration. to use
// this class the "copied" item must support the
// traditional insertion operator <<, which of
// course, std::string does. after each item is
// written, the provided suffix (in our case \n)
// is written as well. without this all the lines
// would be ganged together.
//
// lastly, to glue this together (and the whole
// reason we're here), we use a pair of special
// iterators designed to work just like the regular
// begin() and end() iterators you're familiar with,
// when traversing forward in a sequence, but these
// ones, rbegin() and rend(), move from the last
// item in the sequence to the first item, which is
// *exactly* what we need.
copy(lines.rbegin(), lines.rend(),
ostream_iterator<string>(cout, "\n"));
// and thats it.
return EXIT_SUCCESS;
}
Input
I like the red color
blue is also nice
and green is lovely
but I don't like orange
Output
but I don't like orange
and green is lovely
blue is also nice
I like the red color
UPDATE: Incorporating User Input
An example of incorporating user input for the second version would be:
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
// collection that will hold our lines of text
vector<string> lines;
do
{ // prompt the user
cout << "Sentance (<enter> to exit): ";
string line;
if (!getline(cin, line) || line.empty())
break;
lines.push_back(line);
} while (true);
// send back to output using reverse iterators
// to switch line order.
copy(lines.rbegin(), lines.rend(),
ostream_iterator<string>(cout, "\n"));
return EXIT_SUCCESS;
}
A: Maybe something like:
#include <string>
#include <iostream>
#include <vector>
using namespace std;
// include headers and avoid having to use std:: all the time
int main(){
vector<string> data;
string line;
do{
std::getline(std::cin, line);
data.push_back( line );
}while( cin );//read lines and store to a vector
for (int i=data.size()-1;i>=0;--i)// traverse the vector in a reversed order (maybe size_t for i would be better)
cout<<data[i]<<endl;
}
Looks like it's some homework and probably you are restricted to use some features.
If you insist, we can write a homework-safe version:
// this is just intended to illustrate how RIDICULOUS it is not to use STL features.
#include <cstring>
#include <cstdio>
#include <cstdlib>
int main(){
#define MAXLEN (10000)
char* buffer = (char*)malloc(MAXLEN);//allocate space from heap
char* buffer_ptr = buffer + 1;
*buffer = '\0';//string terminator
while( fgets(buffer_ptr,buffer+MAXLEN-buffer_ptr , stdin ) ){
buffer_ptr += strlen(buffer_ptr);
++buffer_ptr;// reserve the '\0'
}
buffer_ptr -= 2;
while(buffer_ptr >= buffer){
if (!*buffer_ptr)// find end of string
fputs(buffer_ptr+1,stdout);
--buffer_ptr;// traverse backward
}
free(buffer);//free space
}
which avoids C++ extension whenever possible. (In a possibly ridiculous way)
A: #include<iostream>
using namespace std;
int main(){
char str[100][100];
for(int i =0; i < 10 ; i++) {
cin.getline(str[i],100);
}
for(int i = 9 ; i >=0 ; i--) {
cout<<str[i]<<endl;
}
}
A: This is how to do it pretty.
template<class It>
struct range_t {
It b; It e;
It begin() const { return b; }
It end() const { return e; }
};
template<class It>
range_t<It> range(It s, It f) {
return {s,f};
}
range( start, finish ) is a helper that lets you create a range that can be for(:) iterated over.
template<class C>
auto backwards(C&& c) {
using std::rbegin; using std::rend;
return range( rbegin(c), rend(c) );
}
backwards(container) returns a range that iterates over the container backwards.
Once we have written the above library code, all the heavy lifting is done. The remaining code reads almost as pretty as python:
int main() {
std::cout << "Enter some text (blank line to finish):\n";
std::string line;
std::vector<std::string> lines;
while (std::getline(std::cin, line))
lines.push_back(line);
for (auto&& line:backwards(lines))
std::cout << line << "\n";
}
We get lines, buffer them, then print them backwards.
Live example.
The goal here is to make the main program logic as clear as possible. The backwards and range boilerplate just serves that need.
| |
doc_23534943
|
Here is the HTML tag.
<ul id="filter" class="group">
<li>
<a class="art-direction" href="#" title="View all items filed under Art Direction">
<span class="term-name">Art Direction</span>
<!-- START .term-count -->
<span class="term-count">4<span class="triangle-down"></span></span>
<!-- END .term-count -->
</a>
</li>
<li>
<a class="brand-strategy" href="#" title="View all items filed under Brand Strategy">
<span class="term-name">Brand Strategy</span>
<!-- START .term-count -->
<span class="term-count">2<span class="triangle-down"></span></span>
<!-- END .term-count -->
</a>
</li>
<li>
<a class="communication-2" href="#" title="View all items filed under Communication">
<span class="term-name">Communication</span>
<!-- START .term-count -->
<span class="term-count">5<span class="triangle-down"></span></span>
<!-- END .term-count -->
</a>
</li>
<li>
<a class="design-collaboration" href="#" title="View all items filed under Design Collaboration">
<span class="term-name">Design Collaboration</span>
<!-- START .term-count -->
<span class="term-count">2<span class="triangle-down"></span></span>
<!-- END .term-count -->
</a>
</li>
</ul>
And this is the JS code I made, it doesn't work. It is supposed to put a random background color to the span when I am hovering it.
$( '#filter a' ).hover( function() {
//Store available css classes
var classes = new Array("green", "purple", "teal", "violet", "pink");
//Give a random class index
var randomIndex = Math.floor(Math.random()*classes.length);
$(this).find( '.term-name' ).stop().animate({ backgroundColor: 'classes[randomNumber]',}, 500, 'easeInOutExpo');
}, function() {
//return to original
$(this).find( '.term-name' ).stop().animate({ backgroundColor: 'white',}, 500, 'easeInOutExpo')";
});
It was inspired by the JS code (http://jsfiddle.net/GNgjZ/290/)
Btw, as you can observe the link is composed of 2 span (term-name & term-count)
<a><span class="term-name"></span><span class="term-count"></span></a>
The term-count has also animate working and it is working, here is the JS:
$( '.term-count' ).each( function() {
$(this).css( 'marginLeft', '-' + Math.round( ($(this).outerWidth() / 2) ) + 'px' );
});
$( '#filter a' ).hover( function() {
$(this).find( '.term-count' ).stop().animate({ marginBottom: '8px', opacity: 1 }, 500, 'easeInOutExpo');
}, function() {
$(this).find( '.term-count' ).stop().animate({ marginBottom: 0, opacity: 0 }, 500, 'easeInOutExpo');
});
Thanks, Hope my JS works now.
A: According to Jquery API, "All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color() plugin is used)". Apart from that your code has some other issues as well.
A: This FIDDLE will get you off to a good start. You had a number of things wrong with your code such as quotes around variables, extra semicolons and parentheses. I recommend watching you console when you load your page and test your javascript. It tells you a lot. Look closely at the fiddle and let me know if you have any questions. Hope this helps.
var classes = ["#1ace84", "#a262c0", "#4ac0aa", "#8c78ba", "#d529cd"];
$( '#filter a' ).hover( function(e) {
//Give a random class index
var randomIndex = Math.floor(Math.random()*classes.length);
$(e.currentTarget).find( '.term-name' ).css( "backgroundColor", classes[randomIndex]);
}, function(e) {
//return to original
$(e.currentTarget).find( '.term-name' ).css( "backgroundColor", 'white');
});
| |
doc_23534944
|
I'm not sure when it started because I was relying on the emulator, but I do know that it was working at some point
Here is my app.json
{
"name": "appname",
"displayName": "appname",
"expo": {
"name": "appname",
"version": "1.0.0",
"slug": "appslug",
"orientation": "portrait",
"privacy": "unlisted",
"sdkVersion": "32.0.0",
"description": "",
"platforms": [
"ios",
"android"
],
"icon": "./assets/images/icon.png",
"splash": {
"image": "./assets/images/splash.png",
"resizeMode": "contain",
"backgroundColor": "#ffffff"
},
"updates": {
"enabled": true,
"fallbackToCacheTimeout": 30000,
"checkAutomatically": "ON_LOAD"
},
"ios": {
"buildNumber": "1.0.0",
"icon": "./assets/images/icon.png",
"bundleIdentifier": "my.unique.id"
// "splash": {
// "backgroundColor": "#FFFFFF",
// "resizeMode": "cover",
// "image": "./assets/iphone/Default-667h@2x.png"
// }
},
"android": {
"versionCode": 1,
"icon": "./assets/images/icon.png",
"package": "my.unique.id",
"adaptiveIcon": {
"foregroundImage": "./assets/images/icon.png",
"backgroundColor": "#FFFFFF"
}
// "splash": {
// "backgroundColor": "#FFFFFF",
// "resizeMode": "cover",
// "mdpi": "./assets/android/res/drawable-mdpi/background.9.png", // natural sized image (baseline),
// "hdpi": "./assets/android/res/drawable-hdpi/background.9.png", // scale 1.5x
// "xhdpi": "./assets/android/res/drawable-xhdpi/background.9.png", // scale 2x
// "xxhdpi": "./assets/android/res/drawable-xxhdpi/background.9.png", // scale 3x
// "xxxhdpi": "./assets/android/res/drawable-xxxhdpi/background.9.png" // scale 4x
// }
},
"hooks": {
"postPublish": [
{
"file": "sentry-expo/upload-sourcemaps",
"config": {
"organization": "my.org",
"project": "proj",
"authToken": "************"
}
}
]
},
"primaryColor": "#fefefe"
}
}
And here is my App.js
import React from 'react';
import { Platform, StatusBar, StyleSheet, View } from 'react-native';
import { AppLoading, Asset, Font, Icon } from 'expo';
import AppNavigator from './navigation/AppNavigator';
import { Ionicons } from '@expo/vector-icons';
import Sentry from 'sentry-expo';
// Remove this once Sentry is correctly setup.
Sentry.enableInExpoDevelopment = true;
Sentry.config('https://sentry').install();
export default class App extends React.Component {
state = {
isLoadingComplete: false,
};
async componentDidMount() {
await Font.loadAsync({
'Roboto': require('native-base/Fonts/Roboto.ttf'),
'Roboto_medium': require('native-base/Fonts/Roboto_medium.ttf'),
...Ionicons.font,
});
}
render() {
if (!this.state.isLoadingComplete && !this.props.skipLoadingScreen) {
return (
<AppLoading
startAsync={this._loadResourcesAsync}
onError={this._handleLoadingError}
onFinish={this._handleFinishLoading}
/>
);
} else {
return (
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="default" />}
<AppNavigator />
</View>
);
}
}
_loadResourcesAsync = async () => {
return Promise.all([
Asset.loadAsync([
require('./assets/images/robot-dev.png'),
require('./assets/images/robot-prod.png'),
]),
Font.loadAsync({
// This is the font that we are using for our tab bar
...Icon.Ionicons.font,
// We include SpaceMono because we use it in HomeScreen.js. Feel free
// to remove this if you are not using it in your app
'space-mono': require('./assets/fonts/SpaceMono-Regular.ttf'),
}),
]);
};
_handleLoadingError = error => {
// In this case, you might want to report the error to your error
// reporting service, for example Sentry
console.warn(error);
};
_handleFinishLoading = () => {
this.setState({ isLoadingComplete: true });
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
});
/navigation/MainTabNavigator.js
import React from 'react';
import {Platform} from 'react-native';
import {createBottomTabNavigator, createStackNavigator} from 'react-navigation';
import TabBarIcon from '../components/TabBarIcon';
import HomeScreen from '../screens/HomeScreen';
import NotificationScreen from '../screens/NotificationScreen';
import SettingsScreen from '../screens/SettingsScreen';
import ProfileScreen from "../screens/ProfileScreen";
import DraftScreen from "../screens/DraftScreen";
import StatsScreen from "../screens/StatsScreen";
import Colors from "../constants/Colors";
import ViewStoryScreen from "../screens/ViewStoryScreen";
import LoginScreen from "../screens/LoginScreen";
import RegisterScreen from "../screens/RegisterScreen";
import MyStoriesScreen from "../screens/MyStories";
import EditStoryScreen from "../screens/EditStoryScreen";
import AddStoryScreen from "../screens/AddStoryScreen";
const headerStyle = {
/* The header config from HomeScreen is now here */
/*
For full list of options
https://reactnavigation.org/docs/en/stack-navigator.html#navigationoptions-for-screens-inside-of-the-navigator
*/
defaultNavigationOptions: {
headerStyle: {
backgroundColor: Colors.headerBackgroundColor,
},
headerTintColor: Colors.headerTintColor,
headerTitleStyle: {
fontWeight: 'bold',
},
headerBackTitleStyle: {color: Colors.headerTintColor},
headerBackStyle: {color: Colors.headerTintColor},
headerBackAllowFontScaling: true,
},
};
const HomeStack = createStackNavigator({
Home: HomeScreen,
ViewStoryScreen: ViewStoryScreen,
EditStory: EditStoryScreen,
AddStory: AddStoryScreen,
},
{
/* The header config from HomeScreen is now here */
defaultNavigationOptions: headerStyle.defaultNavigationOptions
}
);
HomeStack.navigationOptions = {
tabBarLabel: 'Home',
tabBarIcon: ({focused}) => (
<TabBarIcon
focused={focused}
name={
Platform.OS === 'ios'
? `ios-home`
: 'md-home'
}
/>
),
};
const NotificationStack = createStackNavigator({
Links: NotificationScreen,
ViewStoryScreen: ViewStoryScreen,
},
{
/* The header config from HomeScreen is now here */
defaultNavigationOptions: headerStyle.defaultNavigationOptions
});
NotificationStack.navigationOptions = {
tabBarLabel: 'Notifications',
tabBarIcon: ({focused}) => (
<TabBarIcon
focused={focused}
name={Platform.OS === 'ios' ? 'ios-notifications' : 'md-notifications'}
/>
),
};
const SettingsStack = createStackNavigator({
Settings: SettingsScreen,
Profile: ProfileScreen,
Drafts: DraftScreen,
Stats: StatsScreen,
Login: LoginScreen,
Register: RegisterScreen,
MyStories: MyStoriesScreen,
ViewStoryScreen: ViewStoryScreen,
EditStory: EditStoryScreen,
AddStory: AddStoryScreen,
},
{
/* The header config from HomeScreen is now here */
defaultNavigationOptions: headerStyle.defaultNavigationOptions
}
);
SettingsStack.navigationOptions = {
tabBarLabel: 'Settings',
tabBarIcon: ({focused}) => (
<TabBarIcon
focused={focused}
name={Platform.OS === 'ios' ? 'ios-options' : 'md-options'}
/>
),
};
export default createBottomTabNavigator({
HomeStack,
NotificationStack,
SettingsStack,
});
Solution
As @Masuk Helal Anik mentioned this is a bug
Here is what worked for me, but had to sacrifice header back title.
In every screen add this
static navigationOptions = ({navigation}) => {
return {
headerLeft: (
<Ionicons
name={Platform.OS === "ios" ? "ios-arrow-back" : "md-arrow-back"}
size={Platform.OS === "ios" ? 35 : 24}
color={Colors.headerTintColor}
style={
Platform.OS === "ios"
? { marginBottom: -4, width: 25, marginLeft: 9 }
: { marginBottom: -4, width: 25, marginLeft: 20 }
}
onPress={() => {
navigation.goBack();
}}
/>
),
title: 'Screen Title'
}
};
A: It seems to me like a bug. As a solution in this issue is stated
if you use expo you should include the assets from react-navigation in
your assetBundlePatterns so the images are bundled with your app when
you build a standalone app. the easiest way to do this is to just
bundle all assets that your app uses:
https://github.com/expo/new-project-template/blob/6d4c5636de573852dfd2f7715cfa152fd9c84f89/app.json#L20-L22.
to fix it in development mode within expo, you can cache the assets
locally as per this guide. we do this in the navigationplayground
example app, so you can copy that code from here.
There is some workaround also. Try out them to find which one working for you!
| |
doc_23534945
|
I was able to make it work, but I suspect not in the best way. I'm wondering if it could be done more "Flask"-ily.
What I do now, for example if I was updating all rows in table cars to have tires = 4:
*
*A custom action in the CarView class collects the ids of the rows to be modified, a callback url from request.referrer, and the tablename cars, and returns render_template(mass_update_info.html) with these as parameters.
*mass_update_info.html is an HTML form where the user specifies 1) the field they would like to change and 2) the value to change it to. On submit, the form makes a POST to a a certain view (do_mass_update) with this data (everything else is passed as hidden fields in this form).
*do_mass_update uses the data sent to it to construct a SQL query string -- in its entirety, "UPDATE {} SET {}='{}' WHERE id IN ({})".format(table, column, value, ids) -- which is run via db.engine.execute().
*The user is redirected to the callback url.
It bothers me that I don't seem to be using any of SQLAlchemy, but (from a newbie's perspective) it all seems to be based on the model objects e.g. User.query(...), while I only have access to the model/table name as a string. Can I get some kind of identifier from the model, pass that through, and do a lookup to retrieve the on the other side?
| |
doc_23534946
|
.fifty {
@include span-columns(3);
@include nth-omega(2n);
}
However as soon as I ad a 1px border to the button the effective width is 100%+4px and thus it breaks the layout.
I'm using the Compass Vertical Rhythm plugin for all my button padding values so would like not to mess that up.
A: This is related to "How to include padding in column width with Susy", but your second option is a bit different. This problem isn't specific to Susy - it's true of any fluid layout - But Compass and Susy can help you with the first solution:
*
*Use box-sizing: border-box; - this is now supported by all the major browsers, and Compass has a handy box-sizing() mixin to take care of prefixes for you. If you use it everywhere (like I do), it can change the size of a Susy container, but Susy comes with the handy mixin to fix all that for you. Simply add this at the root, before you set your containers - it will set the box model, and let Susy know to adjust for it:
@include border-box-sizing;
Or just use the Compass box-sizing(border-box) mixin where you want it (on these buttons).
*Since borders don't take % values, there is simply no good way to add borders to fluid elements (using the default content-box model). If you can't use the border-box model, the only other option is to add an internal element in the markup, use the outer for sizing, and the inner for borders and styles.
*There is a third option - using calc() - but it's harder to do, and has even less browser support...
Option #1 is the best by far - as long as you can leave IE7 out of the fun.
| |
doc_23534947
|
When I tried graphs , it shows only one at a time. Whether telerik supports more than one chart in the same page ?
My Index Page
<link href="@Url.Content("~/Content/kendo.dataviz.min.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/examples-offline.min.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
<script src="@Url.Content("~/Scripts/kendo.dataviz.min.js")"></script>
<script src="@Url.Content("~/Scripts/kendo.aspnetmvc.min.js")"></script>
<script src="@Url.Content("~/Scripts/console.min.js")"></script>
<script src="@Url.Content("~/Scripts/prettify.min.js")"></script>
<div style="width: 30%; height: 10%">
@Html.Partial("_PieSeries")
</div>
Hi
<br />
<div style="width: 30%; height: 10%">
@Html.Partial("_BarSeries")
</div>
_PieSeries
<div >
@(Html.Kendo().Chart()
.Name("chart")
.Title("Weekly Enagagement Allocation Status ")
.Legend(legend => legend
.Position(ChartLegendPosition.Bottom)
)
.Series(series =>
{
series.Pie(new dynamic[] {
new { category = "Mumbai_IND_DC_A112", value = 12 },
new { category = "Bejing_CHI_DC_A223", value = 68 },
new { category = "Redmount_US_DC_B221", value = 49 },
new { category = "Sydney_AUS_DC_B1989", value = 37 },
new { category = "DC_US_B1341", value = 17 },
new { category = "KPMG_US_DC_B1099", value = 57 },
new { category = "KPMG_CHI_DC_U9489", value = 67 },
new { category = "DI_US_DC_A1369", value = 87 },
new { category = "MIC_UK_DC_B1709", value = 27 },
new { category = "KPMG_UK_DC_B6990", value = 37 }
});
})
.Tooltip(tooltip => tooltip
.Visible(true)
.Format("{0}%")
)
)
</div>
_BarSeries
<div >
@(Html.Kendo().Chart()
.Name("chart")
.Title("Internet Users")
.Legend(legend => legend
.Position(ChartLegendPosition.Bottom)
)
.Series(series => {
series.Column(new double[] { 15.7, 16.7, 20, 23.5, 26.6 }).Name("World");
series.Column(new double[] { 67.96, 68.93, 75, 74, 78 }).Name("United States");
})
.CategoryAxis(axis => axis
.Categories("2005", "2006", "2007", "2008", "2009")
)
.ValueAxis(axis => axis
.Numeric().Labels(labels => labels.Format("{0}%"))
)
.Tooltip(tooltip => tooltip
.Visible(true)
.Format("{0}%")
)
)
</div>
A: I think all you need to do is to change the Name property of one of your charts. Each chart needs to have a unique Name.
@(Html.Kendo().Chart()
.Name("chart1")
.Title("Weekly Enagagement Allocation Status ")
@(Html.Kendo().Chart()
.Name("chart2")
.Title("Internet Users")
If both charts have the same Name, only one chart will display.
| |
doc_23534948
|
I have so far wrote this query:
SELECT
to_char(favi.date::date, 'mm-dd-yyyy') AS "Date",
(SELECT COUNT(dv.severity) WHERE dv.severity='Critical') AS "Critical Vulns",
(SELECT COUNT(dv.severity) WHERE dv.severity='Severe') AS "Severe Vulns",
(SELECT COUNT(dv.severity) WHERE dv.severity='Moderate') AS "Moderate Vulns",
COUNT(favi.asset_id) AS "Asset Count"
FROM fact_asset_vulnerability_instance favi
JOIN dim_vulnerability dv ON dv.vulnerability_id=favi.vulnerability_id
GROUP BY to_char(favi.date::date, 'mm-dd-yyyy'), dv.severity
ORDER BY to_char(favi.date::date, 'mm-dd-yyyy')
My results though are:
How exactly do I combine the rows on the date? The results split the date into three rows each one displaying the actual count for whatever severity it is. I just want one row per date that shows each of the severity values on one line.
I've played around with UNION, DISTINCT, FULL JOIN, etc but this is slightly past my knowledge of how to get the desired results.
A: The below code is what ended up working.
SELECT
to_char(favi.date::date, 'mm-dd-yyyy') AS "Date",
SUM(CASE WHEN dv.severity = 'Critical' THEN 1 END) AS "Critical Vulns",
SUM(CASE WHEN dv.severity = 'Severe' THEN 1 END) AS "Severe Vulns",
SUM(CASE WHEN dv.severity = 'Moderate' THEN 1 END) AS "Moderate Vulns",
COUNT(favi.asset_id) AS "Asset Count"
FROM fact_asset_vulnerability_instance favi
JOIN dim_vulnerability dv ON dv.vulnerability_id=favi.vulnerability_id
GROUP BY to_char(favi.date::date, 'mm-dd-yyyy')
ORDER BY to_char(favi.date::date, 'mm-dd-yyyy')
so by doing the SUM function as @SOS mentioned I was able to drop the GROUP BY on dv.severity
| |
doc_23534949
|
Oct 09, 2013 4:26:46 PM org.apache.catalina.loader.WebappClassLoader findResourceInternal
INFO: Illegal access: this web application instance has been stopped already.
Could not load oracle/sql/converter_xcharset/CharacterConverter002e.glb. The
eventual following stack trace is caused by an error thrown for debugging purposes
as well as to attempt to terminate the thread which caused the illegal access, and
has no functional impact.
I am using ojdbc6 and see that there isn't anything like "CharacterConverter002e.glb" in the library. What is causing my application to look for this? Am I using the wrong ojdbc? It doesn't appear to keep anything from working but it's bothersome.
| |
doc_23534950
|
List<ServiceLineTypeResource> serviceLineList = serviceLineRepository.findAll();
Print Output:
[Backup, COI, Network, Oracle, SQL_Activities, Storage, Unix/Linux, Virtualization, Windows, #N/A]
...that I want to split into three separate lists of each 3 items each, excluding the final item:
List<ServiceLineTypeResource> serviceLineListRow1 = serviceLineList.subList(0, min(serviceLineList.size(), 3));
List<ServiceLineTypeResource> serviceLineListRow2 = serviceLineList.subList(4, min(serviceLineList.size(), 7));
List<ServiceLineTypeResource> serviceLineListRow3 = serviceLineList.subList(8, min(serviceLineList.size(), 11));
I'm adding each to a HashMap along with another unrelated list:
HashMap<String, String> rowHashMap1 = new HashMap<>();
List<String> styleList = new ArrayList<>();
styleList.add("tile-pink");
styleList.add("tile-sqr tile-cyan");
styleList.add("tile-sqr tile-purple");
for (int i = 0; i < serviceLineListRow1.size(); i++) {
rowHashMap1.put(serviceLineListRow1.get(i).getName(), styleList.get(i));
System.out.println("Row 1: " + serviceLineListRow1.get(i).getName());
}
Output:
Row 1: Backup
Row 1: COI
Row 1: Network
Row 2: SQL_Activities
Row 2: Storage
Row 2: Unix/Linux
Row 3: Windows
Row 3: #N/A
For some reason it's always skipping the 8th item in the list, Virtualization and gives the last one, # instead. I want each of my "row" lists to contain three items, and I don't want the # to appear in any of them. What's going on here?
A: https://docs.oracle.com/javase/8/docs/api/java/util/List.html#subList-int-int-
Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
So if you want the first 9 items you need to do:
List<ServiceLineTypeResource> serviceLineListRow1 = serviceLineList.subList(0, min(serviceLineList.size(), 3));
List<ServiceLineTypeResource> serviceLineListRow2 = serviceLineList.subList(3, min(serviceLineList.size(), 6));
List<ServiceLineTypeResource> serviceLineListRow3 = serviceLineList.subList(6, min(serviceLineList.size(), 9));
| |
doc_23534951
|
I am asking because this is the first time I want to use svelte, and I have an entire app of my company written in JavaScript OOP and I want to rewrite it entirely to svelte.
And I wonder if I can copy and paste the old class code and use the bind and other cool stuff from svelte to make it more interesting, and faster and reactive
<script>
let myReactiveVar = "hello";
class myClass {
constructor(variable) {
this.variable = variable;
}
myMethod() {
// some code
}
get getterVar {
// return something
}
}
// here the let variable should always change and passed to the class
// the class is used only for business logic (oop)
let myCreatedClass = new myClass(myReactiveVar)
</script>
// the change happen with input bind.
<input bind:value={myReactiveVar}/>
<p>{myCreatedClass.getterVar}</p>
or should I rewrite the logic with functional programming?
A: This will not work unless you re-create the class every time you change the variable:
$: myCreatedClass = new myClass(myReactiveVar)
(Which might not be a good idea depending on how expensive it is to create the class and whether you have to retain internal state.)
Other than that you can bind to class variables but internal dependencies will not be tracked, i.e. the property you set has to be the same that you get, e.g.
<script>
class MyClass {
constructor(variable) {
this._variable = variable;
}
set variable(value) { this._variable = value; }
get variable() { return this._variable }
}
const myCreatedClass = new MyClass("hello")
</script>
<input bind:value={myCreatedClass.variable} />
<p>{myCreatedClass.variable}</p>
REPL
For everything else there is the option to use stores, which have their own change notifications and thus can be passed around and be handled in external code, but working with them is a bit more complicated than a plain variable.
| |
doc_23534952
|
This class is used to check for subclassing, and is defined in Predef:
sealed abstract class <:<[-From, +To] extends (From => To) with Serializable
private[this] final val singleton_<:< = new <:<[Any,Any] { def apply(x: Any): Any = x }
However when I write A <:< B I am not sure if I am using an instance of <:<[A,A] or<:<[B,B], because following the static overloading rule neither is more specific then the other.
We first try this just to be sure it really works, replacing <:< with my mycic:
class superC
class subC extends superC
abstract class mycic[-From,+To] extends ((From) => To) with Serializable
object Main extends App {
implicit def FandT[A]: mycic[A,A] = new (mycic[A,A]) { def apply(x: A) ={x}}
val e = implicitly[subC mycic superC]
val a = new subC
e.apply(a)
}
This runs nicely. But when we try to define which one it is using:
class superC
class subC extends superC
abstract class mycic[-From,+To] extends ((From) => To) with Serializable
object Main extends App {
implicit val FF : mycic[subC,subC] = new(mycic[subC,subC]){def apply(x:subC) ={println("FF");x}}
implicit val TT : mycic[superC,superC] = new(mycic[superC,superC]){def apply(x:superC) ={println("TT");x}}
val e = implicitly[subC mycic superC]
val a = new subC
e.apply(a)
}
we get the following compilation error:
Main.scala:10: error: ambiguous implicit values:
both value TT in object Main of type => mycic[superC,superC]
and value FF in object Main of type => mycic[subC,subC]
match expected type mycic[subC,superC]
val e = implicitly[subC mycic superC]
^
Which implicit instance of mycic is it using in the code that runs? Why does it behave differently in the second example?
A: You can use print-tab completion to see types:
scala> def f[A,B](a: A, b: B)(implicit ev: A <:< B) = ev
f: [A, B](a: A, b: B)(implicit ev: <:<[A,B])<:<[A,B]
scala> trait X ; trait Y extends X
defined trait X
defined trait Y
scala> f(null.asInstanceOf[Y], null.asInstanceOf[X]) //print
$line3.$read.$iw.$iw.f[Y, X](null.asInstanceOf[$line4.$read.$iw.$iw.Y], null.asInstanceOf[$line4.$read.$iw.$iw.X])(scala.Predef.$conforms[Y]) // : <:<[Y,X]
(Scroll right to witness scala.Predef.$conforms[Y] as the implicit call.)
The conforms method is just an identity function. Because of variance of function:
scala> implicitly[(Y => Y) <:< (Y => X)]
res0: <:<[Y => Y,Y => X] = <function1>
scala> f(null.asInstanceOf[Y], null.asInstanceOf[X])
res1: <:<[Y,X] = <function1>
scala> .apply(null.asInstanceOf[Y])
res2: X = null
So if Y conforms to X, I can use Y => Y where you asked for Y => X. Similarly for <:<.
The ambiguous example is because neither of the two implicit vals conforms to the other (because of the contra- and co-variance of the type params). Otherwise, one val would have been picked as more specific.
Edit: You can use -Ytyper-debug to observe type inference, which is how it picks a type arg that is not specified. Here, it infers $conforms[Y] because the expected type is <:<[Y,X]:
| | | | solving for (A: ?A, B: ?B)
| | | | [search #1] start `[A, B](a: A, b: B)(implicit ev: <:<[A,B])<:<[A,B]`, searching for adaptation to pt=<:<[Y,X] (silent: value res0 in $iw) implicits disabled
| | | | [search #1] considering $conforms
| | | | solving for (A: ?A)
| | | | [adapt] $conforms adapted to [A]=> <:<[A,A] based on pt <:<[Y,X]
| | | | [search #1] success inferred value of type <:<[Y,X] is SearchResult(scala.Predef.$conforms[Y], )
| | | | |-- [A, B](a: A, b: B)(implicit ev: <:<[A,B])<:<[A,B] EXPRmode (site: value res0 in $iw)
| | | | | \-> <:<[Y,X]
If you specify f[X,X], it will similarly use $conforms[X].
| |
doc_23534953
|
country:
*
*id
*name
region:
*
*id
*name
*fk_country
dept:
*
*id
*name
*fk_region
user:
*
*id
*fk_country
*fk_region
*fk_dept
The user table has only one foreign key set (the others should be null).
We do not have to set the foreign key fk_pays because we can touch the country table via fk_dept.fk_region.fk_country (when fk_dept is set)
OR
via fk_region.fk_country (when fk_region is set)
This behavior was made to avoid redundancy.
My question is :
How to fetch all country informations with an added column that contains the number of users (COUNT) in that country ?
I know how to do using a different request for each pays (using COALESCE) but i wish to do that in a single.
A: Try this one:
SELECT count(user.id), country.name, region.name, dept.name FROM user
JOIN country ON user.fk_country = country.id
JOIN region ON region.fk_country = country.id
JOIN dept ON dept.fk_region = region.id
GROUP BY country.id
A: Just use OR in join
SELECT c.id, c.name, count(DISTINCT u.id)
FROM country AS c
JOIN region AS r ON c.id=r.fk_country
JOIN dept AS d ON r.id=d.fk_region
JOIN users AS u ON u.fk_country=c.id OR u.fk_region=r.id OR u.fk_dept=d.id
GROUP BY c.id,c.name;
http://sqlfiddle.com/#!1/3026f/1
| |
doc_23534954
|
DataTextField="name" DataValueField="name" MaxLength="0"
style="display: inline;"
AutoCompleteMode="SuggestAppend">
</asp:ComboBox>
this is the asp code for my combobox...i am populating my combobox from database.I have all the city names in my combobox.Now i have enabled suggest append as you can see..but its not searching the elemnts anywhere from the names..mean when i type "SBC" code it searches for bangalore city..but i need that when i type "bang" in this also it should show me bangalore city..the same functionality as we have in makemytrip site..how can i do that..??..plzz help..
A: You are asking for autocomplete feature.
See this link.
You can do it using the jQuery.ajax functions. This Article explains how you can do it.
| |
doc_23534955
|
void delete (int s[] , int &top , int v)
{
int ts[size] ;
int ttop=-1;
while(top!=-1)
{
if(s[top]!=v)
push(ts,ttop,s[top]);
pop(top);
}
while(ttop!=-1)
{
push(s,top,ts[ttop]);
pop(ttop);
}
}
A: You need to define a flag which will be set after the first find.
void delete (int s[] , int &top , int v)
{
bool found = false;
int ts[size] ;
int ttop=-1;
while(top!=-1)
{
if (s[top]!=v)
{
push(ts,ttop,s[top]);
}
else
{
if (found == false)
{
found = true;
push(ts,ttop,s[top]);
}
}
pop(top);
}
while(ttop!=-1)
{
push(s,top,ts[ttop]);
pop(ttop);
}
}
As long as found is false, it will also check to see if the element matches. Once found is true, it will always include the item, even if it matches.
Note that this is not the most effective way to do this, merely a means of modifying your code so that it does the trick.
| |
doc_23534956
|
A: You can get the prefix by using the function getTableName() like below :
Always use getTableName with raw queries to fetch the table along with the prefix dynamically
protected $_resource;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\App\ResourceConnection $resource
) {
$this->_resource = $resource;
parent::__construct($context);
}
public function execute()
{
$connection = $this->_resource->getConnection();
$tableName = $connection->getTableName('customer_entity'); // It will return "yourtableprefix_customer_entity"
$mapsDeleteQuery = "your raw SQL Query";
$connection->query($mapsDeleteQuery);
}
A: It seems that there have been some code changes in Magento. So now referring to @Manashvi Birla answer, you need to replace :
$connection->getTableName('customer_entity');
by :
$this->_resource->getTableName('customer_entity');
to be able to get the table prefix.
A: Just open env.php. You can find env.php file under base_dir/app/etc/env.php
Here you can search keyword table_prefix.
I hope it helps you.
| |
doc_23534957
|
*
*A UIImageView whose image has a portion of it cut away to reveal what is below it.
*A UIButton below the UIImageView that is revealed through the cut away portion of the UIImageView.
Since the UIImageView overlaps the UIButton spatially it is preventing touches from reaching the UIButton even though the UIButon is fully visible due to the alpha matte cutout in the UIImageView. How do I allow the UIImageView to pass touches to it's sibling UIButton?
Thanks,
Doug
A: UIImageView usually won't block touches, UIViews do.
You can set the userInteractionEnabled property on the overlapping views to NO, then touches should go through them.
An other approach would be writing a custom hitTest that redirects the thouches to the button.
A: In addition to Bastian's answer it was also necessary for me to uncheck the Opaque drawing attribute in interface builder for my UIImageView
A: Even with user interaction enabled, which is the default value when placing a UIImageView in Interface Builder, the touches should pass through to your button underneath, even if your image view has a solid background. Something else must be going on like a UIView sitting on top of the button.
If you are trying to do something more complex to get touches to pass through to underlying views or a separate view controller whose view is underneath, I created this simple open source library:
https://github.com/natrosoft/NATouchThroughView
The REAMDE and demo show how to use it.
| |
doc_23534958
|
I've tried py2exe and cx_Freeze, both giving me a dist or build directory with an .exe and several other files (dependencies). This does work, since I'm able to zip up the whole folder and distribute via .zip, but it's not ideal. I want to be able to wrap it all up in one file.
So I started googling 'how to compile python into a single exe'. However, unlike many of the programming problems I have tried googling before, I just can't get a straight, reliable answer. So far the most recent reliable answer I've tried gives me this setup.py script:
from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')
setup(
options = {'py2exe': {'bundle_files': 1, 'compressed': True}},
windows = ['snek.py'],
zipfile = None
)
# Python 3.4.4, py2exe 0.9.2.2; modules used: pygame, random
Still, it gives me a whole folder instead of a single .exe, which the program cannot run without.
So, I come to you, the all-knowing, the great, stackoverflow, with two questions.
Just in case I missed anything: how do you suggest I achieve my single .exe dream?
And: why the hell is this so difficult?
A: This question is already answered here:
py2exe - generate single executable file
PyInstaller will create a single .exe file with no dependencies; use the --onefileoption. It does this by packing all the needed shared libs into the executable, and unpacking them before it runs, just as you describe (EDIT: py2exe also has this feature, see minty's answer)
| |
doc_23534959
|
$('#nextMonth, #prevMonth').click(function() {
// execute code
});
but trying to make it look something more like this, but not sure how to write it in a way that works
$('#nextMonth, #prevMonth').click || $('.yearSelect).change(function() {
// execute code
});
so basically, if #nextMonth / #prevMonth is clicked, run the function, or if $('.yearSelect') is changed (a dropdown menu), then execute the code in the function. What would be the correct way to write this?
A: To execute common code from different event handlers, you can move the common code in javascript / jquery function and call it from event handlers
$('#nextMonth, #prevMonth').click(function() {
commonExecution();
});
$('.yearSelect').change(function() {
commonExecution();
});
function commonExecution() {
// execute code
}
| |
doc_23534960
|
Also, to understand the question, consider the use of Row.CREATE_NULL_AS_BLANK missing policy we use in row.getCell() method. When does excel sheet have null value for a cell where we can use this missing policy?
A: In a Excel file in storage for a sheet only rows and cells are stored if they have values or settings. Other rows and cells are not stored. Otherwise each sheet always would must have all possible rows and cells stored even when those rows and cells are not used. That would be a waste of file memory.
Rows have values if they contain cells having values or settings. Rows have settings if they have a row style or a special row height different from default.
Cells have values if they have cell value set. Cells have settings if they have cell styles.
It might also be that cells are stored even if they are totally blank and don't have style. That depends on the spreadsheet software used. Mainly this happens when cells were present and then deleted or when cells were copy/pasted.
The Sheet.getRow and Row.getCell methods of apache poi get not stored rows or cells as null. In other words, only stored rows and cells are got as not null. So you always need check null after Sheet.getRow and Row.getCell:
...
Row row = sheet.getRow(3); if (row == null) row = sheet.createRow(3);
Cell cell = row.getCell(3); if (cell == null) cell = row.createCell(3);
...
After that you can be sure having Row row and Cell cell not null.
For Cell you also can use Row.getCell(int cellnum, Row.MissingCellPolicy policy). See (Row.MissingCellPolicy).
There also is CellUtil which provides methods CellUtil.getRow(int rowIndex, Sheet sheet) and CellUtil.getCell(Row row, int columnIndex). Both are creating the row or cell if they cannot be got.
If you only need traversing filled rows and cells, then you can use the iterators as described in Iterate over rows and cells. The iterators never have null rows or cells. But then you possibly miss totally blank rows or skip blank cells in rows. To avoid that read "Iterate over cells, with control of missing / blank cells" right below.
| |
doc_23534961
|
You will notice that every other document that gets added to the items field is automatically highlighted light blue. I was wondering if it was possible to change that color, and furthermore if it was possible to set it so only the top item (or a single items) gets highlighted in that list of documents?
I thought this would be as simple as finding and changing a CSS file somewhere, but despite changing a number of different CSS files within Alfresco, I have had little luck changing that color. Just wondering if anyone had any experience with this and would be willing to help me out?
A: EDITED:
The class you're looking for is:
tr.yui-dt-highlighted
The problem here is that these classes are generated automatically by JavaScript injected in the page. So, I've searched and found this little info:
path share/res/js/yui-common.js you should use a tool like JavaScript Formatting to understand some code in there. There is a CLASS_HIGHLIGHTED that starts a function, and you should try to override this:
highlightRow: function (k) {
var i = this.getTrEl(k);
if (i) {
var j = this.getRecord(i);
c.addClass(i, d.CLASS_HIGHLIGHTED);
this.fireEvent("rowHighlightEvent", {
record: j,
el: i
});
return;
}
},
unhighlightRow: function (k) {
var i = this.getTrEl(k);
if (i) {
var j = this.getRecord(i);
c.removeClass(i, d.CLASS_HIGHLIGHTED);
this.fireEvent("rowUnhighlightEvent", {
record: j,
el: i
});
return;
}
},
There are highlightRow and highlightColumn to look into. It's always very difficult to override YAHOO yui functions..
| |
doc_23534962
|
However, there is a lot of ambiguity and some of the answers provided ... including duplicating JAR references in the jars/executor/driver configuration or options.
The ambiguous and/or omitted details
The following ambiguity, unclear, and/or omitted details should be clarified for each option:
*
*How ClassPath is affected
*
*Driver
*Executor (for tasks running)
*Both
*not at all
*Separation character: comma, colon, semicolon
*If provided files are automatically distributed
*
*for the tasks (to each executor)
*for the remote Driver (if ran in cluster mode)
*type of URI accepted: local file, HDFS, HTTP, etc.
*If copied into a common location, where that location is (HDFS, local?)
The options which it affects:
*
*--jars
*SparkContext.addJar(...) method
*SparkContext.addFile(...) method
*--conf spark.driver.extraClassPath=... or --driver-class-path ...
*--conf spark.driver.extraLibraryPath=..., or --driver-library-path ...
*--conf spark.executor.extraClassPath=...
*--conf spark.executor.extraLibraryPath=...
*not to forget, the last parameter of the spark-submit is also a .jar file.
I am aware where I can find the main Apache Spark documentation, and specifically about how to submit, the options available, and also the JavaDoc. However, that left for me still quite some holes, although it was answered partially too.
I hope that it is not all that complex, and that someone can give me a clear and concise answer.
If I were to guess from documentation, it seems that --jars, and the SparkContext addJar and addFile methods are the ones that will automatically distribute files, while the other options merely modify the ClassPath.
Would it be safe to assume that for simplicity, I can add additional application JAR files using the three main options at the same time?
spark-submit --jar additional1.jar,additional2.jar \
--driver-library-path additional1.jar:additional2.jar \
--conf spark.executor.extraLibraryPath=additional1.jar:additional2.jar \
--class MyClass main-application.jar
I found a nice article on an answer to another posting. However, nothing new was learned. The poster does make a good remark on the difference between a local driver (yarn-client) and remote driver (yarn-cluster). It is definitely important to keep in mind.
A: Another approach in Apache Spark 2.1.0 is to use --conf spark.driver.userClassPathFirst=true during spark-submit which changes the priority of the dependency load, and thus the behavior of the spark-job, by giving priority to the JAR files the user is adding to the class-path with the --jars option.
A: There is a restriction on using --jars: if you want to specify a directory for the location of jar/xml files, it doesn't allow directory expansions. This means if you need to specify an absolute path for each JAR file.
If you specify --driver-class-path and you are executing in yarn cluster mode, then the driver class doesn't get updated. We can verify if the class path is updated or not under the Spark UI or Spark history server under the tab environment.
The option which worked for me to pass JAR files which contains directory expansions and which worked in yarn cluster mode was the --conf option. It's better to pass the driver and executor class paths as --conf, which adds them to the Spark session object itself and those paths are reflected in the Spark configuration. But please make sure to put JAR files on the same path across the cluster.
spark-submit \
--master yarn \
--queue spark_queue \
--deploy-mode cluster \
--num-executors 12 \
--executor-memory 4g \
--driver-memory 8g \
--executor-cores 4 \
--conf spark.ui.enabled=False \
--conf spark.driver.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
--conf spark.hadoop.mapred.output.dir=/tmp \
--conf spark.executor.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
--conf spark.hadoop.mapreduce.output.fileoutputformat.outputdir=/tmp
A: Other configurable Spark option relating to JAR files and classpath, in case of yarn as deploy mode are as follows.
From the Spark documentation,
spark.yarn.jars
List of libraries containing Spark code to distribute to YARN containers.
By default, Spark on YARN will use Spark jars installed locally, but the Spark jars can also be
in a world-readable location on HDFS. This allows YARN to cache it on nodes so that it doesn't
need to be distributed each time an application runs. To point to jars on HDFS, for example,
set this configuration to hdfs:///some/path. Globs are allowed.
spark.yarn.archive
An archive containing needed Spark jars for distribution to the YARN cache. If set, this
configuration replaces spark.yarn.jars and the archive is used in all the
application's containers. The archive should contain jar files in its root directory.
Like with the previous option, the archive can also be hosted on HDFS to speed up file
distribution.
Users can configure this parameter to specify their JAR files, which in turn gets included in Spark driver's classpath.
A: ClassPath:
ClassPath is affected depending on what you provide. There are a couple of ways to set something on the classpath:
*
*spark.driver.extraClassPath or it's alias --driver-class-path to set extra classpaths on the node running the driver.
*spark.executor.extraClassPath to set extra class path on the Worker nodes.
If you want a certain JAR to be effected on both the Master and the Worker, you have to specify these separately in BOTH flags.
Separation character:
Following the same rules as the JVM:
*
*Linux: A colon, :
*
*e.g: --conf "spark.driver.extraClassPath=/opt/prog/hadoop-aws-2.7.1.jar:/opt/prog/aws-java-sdk-1.10.50.jar"
*Windows: A semicolon, ;
*
*e.g: --conf "spark.driver.extraClassPath=/opt/prog/hadoop-aws-2.7.1.jar;/opt/prog/aws-java-sdk-1.10.50.jar"
File distribution:
This depends on the mode which you're running your job under:
*
*Client mode - Spark fires up a Netty HTTP server which distributes the files on start up for each of the worker nodes. You can see that when you start your Spark job:
16/05/08 17:29:12 INFO HttpFileServer: HTTP File server directory is /tmp/spark-48911afa-db63-4ffc-a298-015e8b96bc55/httpd-84ae312b-5863-4f4c-a1ea-537bfca2bc2b
16/05/08 17:29:12 INFO HttpServer: Starting HTTP Server
16/05/08 17:29:12 INFO Utils: Successfully started service 'HTTP file server' on port 58922.
16/05/08 17:29:12 INFO SparkContext: Added JAR /opt/foo.jar at http://***:58922/jars/com.mycode.jar with timestamp 1462728552732
16/05/08 17:29:12 INFO SparkContext: Added JAR /opt/aws-java-sdk-1.10.50.jar at http://***:58922/jars/aws-java-sdk-1.10.50.jar with timestamp 1462728552767
*Cluster mode - In cluster mode Spark selected a leader Worker node to execute the Driver process on. This means the job isn't running directly from the Master node. Here, Spark will not set an HTTP server. You have to manually make your JAR files available to all the worker nodes via HDFS, S3, or Other sources which are available to all nodes.
Accepted URI's for files
In "Submitting Applications", the Spark documentation does a good job of explaining the accepted prefixes for files:
When using spark-submit, the application jar along with any jars
included with the --jars option will be automatically transferred to
the cluster. Spark uses the following URL scheme to allow different
strategies for disseminating jars:
*
*file: - Absolute paths and file:/ URIs are served by the driver’s HTTP
file server, and every executor pulls the file from the driver HTTP
server.
*hdfs:, http:, https:, ftp: - these pull down files and JARs
from the URI as expected
*local: - a URI starting with local:/ is
expected to exist as a local file on each worker node. This means that
no network IO will be incurred, and works well for large files/JARs
that are pushed to each worker, or shared via NFS, GlusterFS, etc.
Note that JARs and files are copied to the working directory for each
SparkContext on the executor nodes.
As noted, JAR files are copied to the working directory for each Worker node. Where exactly is that? It is usually under /var/run/spark/work, you'll see them like this:
drwxr-xr-x 3 spark spark 4096 May 15 06:16 app-20160515061614-0027
drwxr-xr-x 3 spark spark 4096 May 15 07:04 app-20160515070442-0028
drwxr-xr-x 3 spark spark 4096 May 15 07:18 app-20160515071819-0029
drwxr-xr-x 3 spark spark 4096 May 15 07:38 app-20160515073852-0030
drwxr-xr-x 3 spark spark 4096 May 15 08:13 app-20160515081350-0031
drwxr-xr-x 3 spark spark 4096 May 18 17:20 app-20160518172020-0032
drwxr-xr-x 3 spark spark 4096 May 18 17:20 app-20160518172045-0033
And when you look inside, you'll see all the JAR files you deployed along:
[*@*]$ cd /var/run/spark/work/app-20160508173423-0014/1/
[*@*]$ ll
total 89988
-rwxr-xr-x 1 spark spark 801117 May 8 17:34 awscala_2.10-0.5.5.jar
-rwxr-xr-x 1 spark spark 29558264 May 8 17:34 aws-java-sdk-1.10.50.jar
-rwxr-xr-x 1 spark spark 59466931 May 8 17:34 com.mycode.code.jar
-rwxr-xr-x 1 spark spark 2308517 May 8 17:34 guava-19.0.jar
-rw-r--r-- 1 spark spark 457 May 8 17:34 stderr
-rw-r--r-- 1 spark spark 0 May 8 17:34 stdout
Affected options:
The most important thing to understand is priority. If you pass any property via code, it will take precedence over any option you specify via spark-submit. This is mentioned in the Spark documentation:
Any values specified as flags or in the properties file will be passed
on to the application and merged with those specified through
SparkConf. Properties set directly on the SparkConf take highest
precedence, then flags passed to spark-submit or spark-shell, then
options in the spark-defaults.conf file
So make sure you set those values in the proper places, so you won't be surprised when one takes priority over the other.
Let’s analyze each option in the question:
*
*--jars vs SparkContext.addJar: These are identical. Only one is set through Spark submit and one via code. Choose the one which suits you better. One important thing to note is that using either of these options does not add the JAR file to your driver/executor classpath. You'll need to explicitly add them using the extraClassPath configuration on both.
*SparkContext.addJar vs SparkContext.addFile: Use the former when you have a dependency that needs to be used with your code. Use the latter when you simply want to pass an arbitrary file around to your worker nodes, which isn't a run-time dependency in your code.
*--conf spark.driver.extraClassPath=... or --driver-class-path: These are aliases, and it doesn't matter which one you choose
*--conf spark.driver.extraLibraryPath=..., or --driver-library-path ... Same as above, aliases.
*--conf spark.executor.extraClassPath=...: Use this when you have a dependency which can't be included in an über JAR (for example, because there are compile time conflicts between library versions) and which you need to load at runtime.
*--conf spark.executor.extraLibraryPath=... This is passed as the java.library.path option for the JVM. Use this when you need a library path visible to the JVM.
Would it be safe to assume that for simplicity, I can add additional
application jar files using the 3 main options at the same time:
You can safely assume this only for Client mode, not Cluster mode. As I've previously said. Also, the example you gave has some redundant arguments. For example, passing JAR files to --driver-library-path is useless. You need to pass them to extraClassPath if you want them to be on your classpath. Ultimately, when you deploy external JAR files on both the driver and the worker is, you want:
spark-submit --jars additional1.jar,additional2.jar \
--driver-class-path additional1.jar:additional2.jar \
--conf spark.executor.extraClassPath=additional1.jar:additional2.jar \
--class MyClass main-application.jar
A: When using spark-submit with --master yarn-cluster, the application JAR file along with any JAR file included with the --jars option will be automatically transferred to the cluster. URLs supplied after --jars must be separated by commas. That list is included in the driver and executor classpaths
Example:
spark-submit --master yarn-cluster --jars ../lib/misc.jar, ../lib/test.jar --class MainClass MainApp.jar
Reference
Submitting Applications
A: I know that adding jar with --jars option automatically adds it to classpath as well.
https://spark.apache.org/docs/3.2.1/submitting-applications.html
That list is included in the driver and executor classpaths.
A: While we submit Apache Spark jobs using the spark-submit utility, there is an option, --jars . Using this option, we can pass the JAR file to Spark applications.
| |
doc_23534963
|
format error: file is too short at /usr/share/perl5/Archive/Zip/Archive.pm line 667.
Archive::Zip::Archive::_findEndOfCentralDirectory('Archive::Zip::Archive=HASH(0x8acf47c)', 'IO::File=GLOB(0x8ac9d70)') called at /usr/share/perl5/Archive/Zip/Archive.pm line 581
Archive::Zip::Archive::readFromFileHandle('Archive::Zip::Archive=HASH(0x8acf47c)', 'IO::File=GLOB(0x8ac9d70)', 'some zip file') called at /usr/share/perl5/Archive/Zip/Archive.pm line 548
I want to skip some corrupted archives.
A: It is very untidy to mess with the SIGWARN handler or redirect the STDERR output to the null device.
Archive::Zip has a function to set the error handler Archive::Zip::setErrorHandler. The default is to use Carp::carp, which produces the output you're seeing.
You can write your own replacement, for instance to save the error messages in an array for later examination, like this
my @errors;
Archive::Zip::setErrorHandler(sub { push @errors, $_[0] });
Also don't forget to check the return codes from the functions as there will otherwise be no way to know that there has been a problem.
A: Depending on where you are calling the function that emits this error, you can override the warning handler locally to ignore the warnings.
sub f {
...
local $SIG{__WARN__} = sub { # do nothing };
}
Now all warnings emitted in function f get routed to your local warn handler, which does nothing.
You should note that Archive::Zip has an error flag AZ_OK that is returned from most operations. For instance:
# Read a Zip file
my $somezip = Archive::Zip->new();
if ( $somezip->read( 'someZip.zip' ) != AZ_OK ) {
die 'read error';
}
A: `command-to-extract-file 2>/dev/null`
Pipes stderr to /dev/null
This works for linux. Not sure about windows??
| |
doc_23534964
|
SyntaxError: syntax error
[Break On This Error]
<!DOCTYPE html>
It references Line 31 which is this line of code:
var formResponse = eval(msg);
Here is the full AJAX Code:
function jqsub() {
var $f = $('#email-form');
var $m = $('#success-message');
$.ajax({
type: 'POST',
url: $f.attr('action') + '&JSON=1',
data: $f.serialize(),
success: function(msg) {
var formResponse = eval(msg);
if (formResponse.FormProcessV2Response.success) {
$f.fadeOut();
$m.fadeIn().html('<p>Thank you for joining our mailing list.</p>');
}
},
error: function(msg) {
alert('error'+msg);
return false;
}
});
}
What does this syntax error mean and how to I fix this?
Note: I am using a CMS called Business Catalyst and FormProcessV2Response is a part of their system.
A: url: $f.attr('action') + '&JSON=1'
should be
url: $f.attr('action') + '&JSON=1'
This will make it actually return JSON. You only use & in HTML — you may have copied this from a link attribute or something.
Also, since you’re using jQuery, instead of using eval, you can use $.parseJSON. Or better, set dataType: 'json' in the $.ajax options and just use msg as-is! (And even if you weren’t, JSON.parse would still be preferable.)
A: Your server's response contains HTML, not JSON. You eval JSON because JSON is a subset of JavaScript. You can't eval HTML, it's not valid JavaScript.
| |
doc_23534965
|
Actually in a page I have list of items is being there using pagination it is being accessed, but everytime when I click on the next button it relaods the page, Since in the same page I have other features like ADS, TAGS so it takes more time each time loading.
So I need to list out the only the content.
So do help me in this Issue.
A: You really should upgrade to D6 if AT ALL possible. You're like 5 years behind the times and in Drupal years, that's a loooong time.
A: You could perhaps try and use a search engine.
The first result is from Drupal's documentation itself.
So now that you've mentioned what's wrong (i.e. pagination), the possibility of getting help increases.
So you're saying your pagination links reload the whole page. What is the href attribute set to?
A: If you upgrade to Drupal 5, you could use http://drupal.org/project/ajax_views . At any rate, I'd recommend taking a look at the code in that module and see what you can use/what ideas you can get.
A: It sounds like you have a JavaScript fatal error on your page, which will disable all JavaScript. There should be an return false attached to the click handler for the pagination, but if that fails, the graceful degradetion would be to execute the link, which will simply reload the page.
So I would suggest you get something like Firebug for Firefox or any other JavaScript development tool, and first check if you get fatal errors.
| |
doc_23534966
|
I am now trying to start blinking LEDs. In order to do this I need to configure GPIO1. In trying to configure this port I have found that TI's C runtime immediately goes to user mode (4 instructions from startup). When I try reading or writing the control memory locations I get an error that we believe is caused by not being in supervisor mode.
In order to get in to supervisor mode I am attempting to write a software interrupt handler and then do the necessary configuration from there. I can write the handler, and I can get main() to call a software interrupt, but I am struggling trying to get my interrupt handler to actually work.
#pragma SWI_ALIAS(7);
int function(int i);
#pragma INTERRUPT(SWI);
int function(int i)
{
return i + 1;
}
int main(void) {
int i = function(5);
while(1);
}
Calls to function produce SWI 7 in the disassembly, as I would expect, but function is never called. I have written a intvecs.asm file, but that didn't help.
.global _c_int00
.global _Z8functioni
.retain ".intvecs"
.sect ".intvecs"
B _c_int00 ; reset interrupt
.word 0 ; undefined instruction interrupt
B _Z8functioni ; software interrupt
.word 0 ; abort (prefetch) interrupt
.word 0 ; abort (data) interrupt
.word 0 ; reserved
.word 0 ; IRQ interrupt
.word 0 ; FIQ interrupt
I would appreciate any suggestions on how to get this working.
It appears that the .gel file that comes with CCS 5.5 doesn't actually permit writing to 0x00000000, which, to my understanding, is the location of the interrupt vectors. So the JTAG adapter isn't updating the interrupt vector.
A: If you are doing bare-bone programming, then you can rewrite the asm startup code to NOT enter user mode and remain in SVC mode.
A: I finally found in the Technical Reference Manual, in section 26.1.3.2 Public RAM Memory Map, the following paragraph:
The RAM exception vectors enable a simple means for redirecting
exceptions to custom handlers. Table 26-3 shows content of the RAM
space reserved for RAM vectors. The first seven addresses are ARM
instructions which load the value located in the subsequent seven
addresses into the PC register. Theses instructions are executed when
an exception occurs since they are called from the ROM exception
vectors. Undefined, SWI, Unused and FIQ exceptions are redirected to a
hardcoded dead loop. Pre-fetch abort, data abort, and IRQ exception
are redirected to pre-defined ROM handlers. User code can redirect any
exception to a custom handler either by writing its address to the
appropriate location from 4030CE24h to 4030CE3Ch or by overriding the
branch (load into PC) instruction between addresses from 4030CE04h to
4030CE1Ch.
The base for the table of exception handlers on this micro is 0x4030CE24, not 0x00000000 or 0xffff0000 as indicated by the ARM manual.
| |
doc_23534967
|
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:ts="http://www.test.com/testModel.owl#">
<ts:Entity rdf:ID="1234_test">
<ts:Resource>
<ts:testProp rdf:datatype="http://www.w3.org/2001/XMLSchema#string">test_ID_test</ts:testProp>
</ts>
</ts>
</rdf:RDF>
How i can extract the value test_ID_test??? And if i want use SPARQL how can i do with jena???
A: For running a SPARQL query using Jena, see the ARQ documentation or the Jena SPARQL tutorial.
As for your query, it depends how you want to identify the resource. If you know a priori the URI of the resource, it's straightforward:
prefix ts: <http://www.test.com/testModel.owl#>
select ?tp_value where {
ts:1234_test ts:testProp ?tp_value
}
If you happen to know only that it's a resource of type Entity, the query is only slightly more involved:
prefix ts: <http://www.test.com/testModel.owl#>
select ?tp_value where {
?entity a ts:Entity ;
ts:testProp ?tp_value
}
| |
doc_23534968
|
I have about 500k Id's and 25 columns (as of now).
I'd like to make the query dynamic so that any added columns will not require a code change.
For each ID, I want to find column names of the top 3 values.
The results should be:
[Id]
[Rank1]
[Rank2]
[Rank3]
27807745
Value3
Value2
Value8
96448378
Value6
Value5
Value1
etc
My first attempt was to create a joined table of Id's and column names:
[Id]
[Value1]
[Value]
27807745
Value1
NULL
27807745
Value2
NULL
27807745
Value3
NULL
27807745
Value4
NULL
27807745
Value5
NULL
Then run a looped update, then sequence by Id, Value DESC.
This gets me there but is taking over 2 hours to complete.
I looked at PIVOT and UNPIVOT but both want to return the values, not the column names.
Is there any other way to do this?
A: Here is an option that will dynamically unpivot your data WITHOUT using Dynamic SQL
Example or dbFiddle
Select A.ID
,B.*
From YourTable A
Cross Apply (
Select Rank1 = max(case when Rnk=1 then [Key] end)
,Rank2 = max(case when Rnk=2 then [Key] end)
,Rank3 = max(case when Rnk=3 then [Key] end)
From (
Select [Key]
,Value
,Rnk = row_number() over (order by convert(int,value) desc)
From OpenJson((Select A.* For JSON Path,Without_Array_Wrapper ))
Where [Key] Not IN( 'ID','Other','Columns','ToExclude')
) B1
) B
| |
doc_23534969
|
Normal template specialization is not possible because the std::unique pointer can be instantiated with any type.
Queue code is like this:
bool TQueue<T>::Push(const T& item)
{
m_Mem[currTail] = item;
}
bool TQueue<T>::Pop( T& item )
{
item = m_Mem[currHead];
}
How to make this work for std::unique_ptr types as well, when I need to do m_Mem[curtail] = std::move(item)
A: You're approaching the problem from a slightly wrong angle. The move() cannot be inside the Push(), that's too late. It must be outside - you cannot really steal the resources of an arbitrary argument, you must ask the user to actively move the non-copyable resource there. So simply provide an extra overload:
bool TQueue<T>::Push(const T& item)
{
m_Mem[currTail] = item;
}
bool TQueue<T>::Push(T&& item)
{
m_Mem[currTail] = std::move(item);
}
That way, your users can actively move their objects into the container when they want (by doing queue.Push(std::move(my_object));.
For Pop(), the situation is even simpler: Pop() removes an element from the queue, so you should always move() it out - you're not retaining any copies:
bool TQueue<T>::Pop( T& item )
{
item = std::move(m_Mem[currHead]);
}
| |
doc_23534970
|
There is JS snippet below. My point - to define REQUEST_POST_BODY and RECEIVE_POST_BODY cases in posts reducer.
Main difficult - to find and update right object in store.
I try to use code from example:
return Object.assign({}, state, {
[action.subreddit]: posts(state[action.subreddit], action)
})
But it used simple array of posts. It's not needed to find right post by id.
Here my code:
const initialState = {
items: [{id:3, title: '1984', isFetching:false}, {id:6, title: 'Mouse', isFetching:false}]
}
// Reducer for posts store
export default function posts(state = initialState, action) {
switch (action.type) {
case REQUEST_POST_BODY:
// here I need to set post.isFetching => true
case RECEIVE_POST_BODY:
// here I need to set post.isFetching => false and post.body => action.body
default:
return state;
}
}
function requestPostBody(id) {
return {
type: REQUEST_POST_BODY,
id
};
}
function receivePostBody(id, body_from_server) {
return {
type: RECEIVE_POST_BODY,
id,
body: body_from_server
};
}
dispatch(requestPostBody(3));
dispatch(receivePostBody(3, {id:3, body: 'blablabla'}));
A: With Arrays
If you'd prefer to stick with arrays, then you can write a reducer that just tackles single post objects.
export default function reducePost(post, action) {
if(post.id !== action.id) return post;
switch(action.type) {
case REQUEST_POST_BODY:
return Object.assign({}, post, { isFetching: true });
case RECEIVE_POST_BODY:
return Object.assign({}, post, { isFetching: false, body: action.body });
default:
return post;
}
Your root reducer would become:
export default function posts(state = initialState, action) {
return state.map(post => reducePost(post, action);
}
We're just running our new reducer over each post in the list, to return an updated array of posts. In this case, the unique id will ensure that only one item will be changed.
With Objects
If each item has a unique string/number id, then you can flip your array around and use an object instead.
const initialState = {
items: {
3: {id:3, title: '1984', isFetching:false},
6: {id:6, title: 'Mouse', isFetching:false}
};
}
Then you can simplify your reducer.
switch (action.type) {
case REQUEST_POST_BODY:
let id = action.id;
return Object.assign({}, state, {
[id]: Object.assign({}, state[id], { isFetching: true })
});
case RECEIVE_POST_BODY:
let id = action.id;
return Object.assign({}, state, {
[id]: Object.assign({}, state[id], {
isFetching: false,
body: action.body
})
});
default:
return state;
}
If you're happy to experiment with some ES7 syntax too, you can enable the Object spread operator with Babel and rewrite the calls to Object.assign.
switch (action.type) {
case REQUEST_POST_BODY:
let id = action.id;
return {
...state,
[id]: {...state[id], isFetching: true }
};
case RECEIVE_POST_BODY:
let id = action.id;
return {
...state,
[id]: {
...state[id],
isFetching: false,
body: action.body
}
};
default:
return state;
}
If you're not so keen on using the spread syntax, then it's still possible to make Object.assign a bit more palatable.
function $set(...objects) {
return Object.assign({}, ...objects);
}
case RECEIVE_POST_BODY:
let id = action.id;
return $set(state, {
[id]: $set(state[id], {
isFetching: false,
body: action.body
})
});
A: If I understand correctly, you are having trouble getting the specific post you want.
First of all, Having your reducer also update the array and the object in it, makes it hard to read and maintain. I suggest you watch this short video explaining about reducer composition with arrays.
You can simplify your code by using the technique described there.
In your case, you would a posts reducer and a post reducer, while posts reducer calls the post reducer.
As for finding the right object to work on, Dan Prince's suggestion makes it easier.
Having an object map instead of an array would make it easier for you. Relevant code snippet from Dan's answer:
const initialState = {
items: {
3: {id:3, title: '1984', isFetching:false},
6: {id:6, title: 'Mouse', isFetching:false}
];
}
A: I pretty much implemented Object reducers by using Object.assign, which works, but as our project has grown and we have added a bunch of dependent components it has become very inefficient and renders are very slow.
If I'd know about immer I would have used that from the start.
Essentially you use immer as follows, where the example has a layers object that looks like this:
const initialState = {
layers: {
'layer1': { selected: false },
'layer2': { selected: true }
}
}
Reducers.js (extract)
import produce from 'immer'
import has from 'lodash/has'
export const layers = (state = null, action) => {
switch (action.type) {
case ADD_LAYER:
// Using `immer.produce` only for consistency
// clearly the whole object changes in this case.
return produce(state, layers => {
// Take a copy of the prebuilt layer
var layer = Object.assign({}, action.layer)
// Add some defaults
if (!has(layer, 'selected')) {
layer.selected = false
}
layers[action.id] = layer
})
case SELECT_LAYER:
return produce(state, layers => {
layers[action.id].selected = true
})
case UNSELECT_LAYER:
return produce(state, layers => {
layers[action.id].selected = false
})
default:
return state
}
}
Actions.js (extract)
export const addLayer = id => ({
type: ADD_LAYER,
id
})
export const selectLayer = id => ({
type: SELECT_LAYER,
id
})
export const unSelectLayer = id => ({
type: UNSELECT_LAYER,
id
})
References:
https://github.com/immerjs/immer
https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns
| |
doc_23534971
|
module A(a,b,c);
input a,b;
output c;
assign c=a&b;
initial
$display("%b",c);
endmodule
module testbench11;
reg a,b;
wire c;
A a1(a,b,c);
initial
$monitor(,$time,"a=%b,b=%b,c=%b",a,b,c);
initial
begin
#0 a=1'b0;b=1'b0;
#3 a=1'b0;b=1'b0;
#3 a=1'b0;b=1'b0;
end
endmodule
So I want to display the result of c after every time instance so as to check whether I am getting desired output. It may seem to display results at the end in this case, but in some complex problems I wanted to use display for debugging purposes just as I use printf in C. Is there some way to do that in verilog?
A:
Because display should always be inside initial block and so there is no way I can use display for debugging purposes.
I am not sure where you got this from, it is the same as nearly everything but assign in that it must be used inside a block, intial or always.
To use it to debug inside the module:
module A(a,b,c);
input a,b;
output c;
assign c = a&b;
always @*
$display("%b",c);
endmodule
It is best to display and check from the top level keeping the module code clean. to use display in the testench you can do:
The same format as inside the module:
always @* begin
$display("%b",c);
end
Or to know you are displaying after each stimulus step:
initial begin
#0 a=1'b0;b=1'b0;
#1 $display("%b",c);
#3 a=1'b0;b=1'b0;
#1 $display("%b",c);
#3 a=1'b0;b=1'b0;
#1 $display("%b",c);
end
A: Verilog/SystemVerilog contains a well organized event queue. All the statements in each and every time stamp executes according to this queue. Following are some of the different display system tasks.
*
*$display executes in ACTIVE region, so if there is any non-blocking assignment(which executes in INACTIVE region), it won't be shown by $display. This displays a single output line.
*$write also executes in ACTIVE region, but an explicit call to newline character(\n) is required to insert another line. This system task is generally used when you want to display Multidimensional array using for loop. This is similar to display except (\n) character.
*$strobe executes in MONITOR/POSTPONED region, that is, at the end of time stamp. Hence the updated value is shown by $strobe.
*$monitor displays every time one of its display parameters changes. Only one $monitor per Simulation is to be used. Monitor, as the name suggests, monitors the signals continuously and executes if any signal value changes.
For your code, to display at various points, following change of code can be done.
initial
#5 $display("%b",c); // display after some arbitrary time.
initial
begin
repeat(5)
begin
wait(c);
$display("%b",c); // display after change in c 5 times.
end
end
initial
begin
forever
begin
#1;
$display("%b",c); // display c at every timestamp
end
end
always @(c)
$display("%b",c); // display after any change in c
always @(a,b,c)
$display("%b",c); // display after any change in a or b or c
For displaying at every change, $monitor is useful. $display can be used as above but this will make your code messy. Just remember that there must be only one $monitor in your code. There is no such limit in $display.
These are just some of the methods, many other are available. Further information can be found out at this
and this links.
| |
doc_23534972
|
DF_Transactions
H1
H_date
A
2-Jan-20
A
2-Jan-20
C
3-Jan-20
A
2-Jan-20
A
2-Jan-20
DF_Events
H1
H_date
H_class
A
2-Jan-20
class_1
A
2-Jan-20
class_2
Using pd.merge(DF_transactions, DF_Events, on=['H1'], how='left') I have obtained too many duplicates
DF_Wrong_Results
H1
H_date
H_class
A
2-Jan-20
class_1
A
2-Jan-20
class_1
C
3-Jan-20
A
2-Jan-20
class_2
A
2-Jan-20
class_2
A
2-Jan-20
class_1
A
2-Jan-20
class_1
A
2-Jan-20
class_2
A
2-Jan-20
class_2
I cannot use drop_duplicates on the dataframe as it would remove the last 2 entries in the left dataframe. What is the simplest way to get the correct dataframe below?
DF_Correct_Results
H1
H_date
H_class
A
2-Jan-20
class_1
A
2-Jan-20
class_2
C
3-Jan-20
A
2-Jan-20
class_1
A
2-Jan-20
class_2
Please see the sample code below:
# import pandas as pd
import pandas as pd
# list of strings
lst1 = ['A','A','C','A','A']
lst2 = ['2-Jan-20','2-Jan-20', '3-Jan-20','2-Jan-20','2-Jan-20']
lst3 = ['A', 'A']
lst4 = ['2-Jan-20', '2-Jan-20']
lst5 = ['Class_1','Class_2']
# Calling DataFrame constructor on list
# with indices and columns specified
df = pd.DataFrame(list(zip(lst1, lst2)), columns=['H1', 'H_date'])
df1 = pd.DataFrame(list(zip(lst3, lst4, lst5)), columns=['H1', 'H_date', 'Class'])
df2 = pd.merge(df, df1, on=['H1', 'H_date'], how='left')
print(df2)
A: according to pandas documentation https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html
your code should be as such
DF_transactions.merge(DF_Events, on=['H1'], how='left')
It should be (left dataframe).merge((right dataframe),) syntax.
Try again and see if it works.
A: Have a look at merge_asof:
pd.merge_asof(df1.sort_values(['H1', 'H_date']),
df2,
on='H_date',
by='H1')
H1 H_date H_class
0 A 2020-01-02 class_1
1 A 2020-01-02 class_1
2 B 2020-01-02 class_2
3 B 2020-01-02 class_2
4 C 2020-01-03 NaN
| |
doc_23534973
|
public virtual ActionResult List(int assessmentId, int? chapterId, bool? isMenuClick)
{
Mapper.CreateMap<Element, AssessmentQuestionViewModel>().
ForMember(dest => dest.AssessmentId, opt => opt.MapFrom(e => assessmentId));
...
}
It doesn't matter if I use UseValue, ResolveUsing or MapFrom in the above opt => lambda. The behavior is the same, that is, it reuses the value from previous calls.
AssessmentId property does not exist in the source type ( Element ). This way I try to assign AssessmentId a value that "may" change dynamically during subsequent calls to the method where I have this code. assessmentId is a parameter in my ASP.NET MVC action method as shown above in the method signature.
Then I call this code in the List action method:
var questions =
Mapper.Map<IEnumerable<Element>, IEnumerable<AssessmentQuestionViewModel>>
(Database.Elements.Where(e => !elementIds.Contains(e.ElementId) &&
e.Standard.ChapterId == chapterId));
The first time, questions is OK, that is, all AssessmentQuestionViewModel objects have the AssessmentId property set correctly as per the CreateMap defined.
Starting from the 2nd call, it reuses the assessmentId from the 1st call and it messes up with my business logic because I expect it to map AssessmentId to the updated assessmentId that's being passed as a parameter to the List method.
Just to be sure: I've set a breakpoint in the code and I can see that the value of the assessmentId parameter is correct. It's just the returned mapped objects questions that have the wrong value in the AssessmentId property - a value that differs from the current assessmentId value. The values should be equal as I understand it since I'm asking AutoMapper to do the mapping using that current value.
I have AutoMapper 2.2.1-ci9000 (Prerelease), but I tested this with the previous version and I saw this same behavior. I updated to the Prerelease thinking that this "misbehavior" would go away.
I think this is a bug. Please correct me if I'm wrong or if I'm trying to use it in a way not supported. :)
A: I think the problem here your trying to create multiple mappings of the same type - which AutoMapper doesn't support. Everytime your List action is called, you create a new mapping (which has a different ForMember(...) clause). AutoMapper won't throw an exception it just ignores the duplicate mapping so what you are seeing here isn't a bug, it's expected behaviour.
ForMember is infact called on every map, however, you have a scoping issue here as your variable is hard-coded into the expression. As a work-around you could do something like:
public class MyController
{
public MyController()
{
// define mapping once, but make assessment expression dynamic
Mapper.CreateMap<Element, AssessmentQuestionViewModel>().
ForMember(dest => dest.AssessmentId, opt => opt.MapFrom(e => GetCurrentAssessmentId()));
}
private int GetCurrentAssessmentId()
{
return (int)TempData["AssessmentId"];
}
public ActionResult List(int assessmentId, ...)
{
// store current assessment temporarily
TempData.Add("AssessmentId", assessmentId);
// execute mapping
var questions = Mapper.Map<IEnumerable<Element>, IEnumerable<AssessmentQuestionViewModel>>
(Database.Elements.Where(e => !elementIds.Contains(e.ElementId) &&
e.Standard.ChapterId == chapterId));
}
}
I will say though, your jumping through a lot of hoops for this to work, it would be much simpler to manually set the property without the help of AutoMapper e.g.
var questions = Mapper.Map<IEnumerable<Element>, IEnumerable<AssessmentQuestionViewModel>>(...);
foreach (var q in questions)
{
q.AssessmentId = assessmentId;
}
| |
doc_23534974
|
My AJAX code sends limit and start values to fetch.php and fetch data in the division
A 2nd ajax code sends cat_id to load-prod.php to filter data on button click
index.php
<div class="row">
<div class="col-md-12 p-3 text-center">
<span>Categories  </span>
<div class="btn-group" role="group" aria-label="Basic outlined example">
<button type="button" class="btn btn-outline-dark active showct" value="">All</button>
<?php echo show_cat(); ?>
</div>
</div>
<div class="col-md-12">
<div class="row row-cols-1 row-cols-md-3 g-4" id="showpr">
</div>
</div>
<div class="col-md-12 text-center p-3" id="datamsg"></div>
</div>
//lazy load
<script>
var limit = 9; //The number of records to display per request
var start = 0; //The starting pointer of the data
var action = 'inactive'; //Check if current action is going on or not. If not then inactive otherwise active
function lazyload(limit, start)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{limit:limit, start:start},
cache:false,
success:function(data)
{
$('#showpr').append(data);
if(data == '')
{
$('#datamsg').html("<button type='button' class='btn btn-dark' disabled>No more data</button>");
action = 'active';
}
else
{
$('#datamsg').html("<button type='button' class='btn btn-outline-dark' disabled>Loading More...</button>");
action = 'inactive';
} }});}
if(action == 'inactive')
{
action = 'active';
lazyload(limit, start);
}
$(window).scroll(function(){
if($(window).scrollTop() + $(window).height() > $(document).height() - 100 && action== "inactive")
{
action = 'active';
start = start + limit;
setTimeout(function(){
lazyload(limit, start);
}, 1000);}});
</script>
//show according to category
<script>
$(document).ready(function(){
$('.showct').click(function(){
var cat_id = $(this).val();
$.ajax({
url:"load-prod.php",
method:"POST",
data:{cat_id:cat_id},
success:function(data){
$("#showpr").html(data);
}});
});});
</script>
load-prod.php
<?php
include ('connect.php');
global $con;
if(isset($_POST["cat_id"]))
{
if($_POST["cat_id"]!='')
{
$cf = "select * from products where c_id = '".$_POST['cat_id']."'";
}
else{
$cf = "select * from products";
}
$filter = mysqli_query($con,$cf);
while ($ctf=mysqli_fetch_array($filter)) {
echo "<div class='col-12'><h5 class='card-title'>".$ctf['name']."</h5>";
}
}
?>
fetch.php
<?php
include ('connect.php');
global $con;
if(isset($_POST["limit"], $_POST["start"]))
{
$query = "SELECT * FROM album ORDER BY id ASC LIMIT ".$_POST["start"].", ".$_POST["limit"]."";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
echo "<div class='col-12'><h5 class='card-title'>".$row['name']."</h5>" ;
}
}?>
| |
doc_23534975
|
I would expect to be able to use initWithFrame, and take the bounds from the passed-in NSRect, but if I examine the data in the debugger, I just get an NSRect instance with (x=0, y=0), (width=0, height=0). Presumably it's not initialised yet?
More puzzling is that if I log the frame width to the console, I get the value twice:
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
CGFloat width = frame.size.width;
NSLog(@"width: %f", width);
}
}
This code logs:
21/10/2011 09:40:55.733 Test App: width: 480.000000
21/10/2011 09:40:55.818 Test App: width: 0.000000
It's as if initWithFrame is running in two separate threads and we have some kind of race condition. What's the correct way to get the frame width when the view is initialised?
UPDATE [SOLVED]: This issue has now been resolved. It turns out that I had two instances of my NSView subclass in Interface Builder. One was drawn as a Custom View and the other was an Object in the side panel. I hadn't realised that adding an object to the side panel caused it to be instantiated at runtime. Removed the object and my code now works.
A: The frame passed in initWithFrame is the frame used by the view, are you sure you are not creating two views, or calling this twice?
| |
doc_23534976
|
I know how the compiler generates the virtual address table (v-table). So to make things simple for me to explain, lets take this simple example,
class Entity {
public:
Entity() {}
virtual void Initialize() {}
};
class Player : public Entity {
public:
Player() {}
virtual void Initialize() override final { ... }
};
So now we make an instance of Player and assign its address in the Entity class pointer,
Player player = {};
Enity* pEntity = &player;
Now I'm going to call the Initialize method, one using the player variable and the other in pEntity variable.
player.Initialize(); // Call 1.
pEntity->Initialize(); // Call 2.
So my question is,
When will the v-table of the class Player get accessed? Is it in Call 1 or is it in Call 2 or is it in both the cases?
Thanks in advance!
A: Compilers are free to do whatever they want. They can implement everything without vtables, so take all the below with a grain of salt.
Player player = {};
player.Initialize();
When you define an object with class type, the compiler knows that the static type is equal to the dynamic type. So it is likely to call the required method directly. It can even inline and optimize-out the call. But this behavior is not required - the compiler may decide to play it dumb, and use vtable to call the method.
Enity* pEntity = &player;
pEntity->Initialize();
When you define an object with a pointer (or reference) type, the compiler may assume it's a pointer (or reference) to a base class, and access its vtable during the call. However, many compilers do devirtualization in cases where they can determine the runtime type with certainty. It's easy to determine the runtime type here because there is no code between the creation of the object and the virtual call.
The final specifier can help the compiler devirtualize calls. In the simplest case, it's not even necessary; it would help in the following code:
Player* pPlayer = VeryComplexPlayerFactory();
pPlayer->Initialize();
Here, it's easy to see that pPlayer will point to a type derived from Player, so there is only one implementation option for the Initialize method.
Devirtualization is an optimization; some compilers let you disable it (-fno-devirtualize). You should disable it if you want to explore generated machine code for vtables.
| |
doc_23534977
|
can you tell me if there's a way on objective-c do that?
A: Sounds like a job for Uniform Type Identifiers. The UTI mechanism provides the ability to identify different types of data based on different criteria.
| |
doc_23534978
|
/*
Write a program that reads numbers from the keyboard into an array of type int[].
You may assume that there will be 50 or fewer entries in the array. Your program
allows any number of numbers to be entered, up to 50. The output is to be a
two-column list. The first column is a list of the distinct array elements;
the second is the count of the number of occurrences of each element.
The list should be sorted on entries in the first column, largest to smallest.
For the array:
-12, 3, -12, 4, 1, 1, -12, 1, -1, 1, 2, 3, 4, 2, 3, -12
the output should be:
N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
*/
import java.util.Scanner;
public class Project2C {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[][] twoColumn = new int[2][50];
int[] inputValues = new int[50];
int temp = 0;
int valueFrequency = 0;
int lastUsedSpace = 0;
//gather user input to fill an array (up to 50 values);
System.out.println("Input up to 50 values.");
for (int i = 0; i < 50; i++) {
System.out.println("value #" + (i + 1) + ":");
inputValues[i] = keyboard.nextInt();
/*System.out.println("Press 0 to stop, or 1 to continue.");
if (keyboard.nextInt() == 0) {
break;
}
else if (keyboard.nextInt() == 1){
continue;
}
else if (keyboard.nextInt() != 0 && keyboard.nextInt() != 1) {
System.out.println("You must enter 0 or 1. Now you must re-enter the value.");
i--;
}*/
}
// checking if each value occurs more than once, and assigning it a place
// in the two column array if it is unique.
for (int i = 0; i < inputValues.length; i++) {
for (int j = 0; j < inputValues.length; j++) {
if (i == 0 && inputValues[i] != inputValues[j]) {
twoColumn[0][lastUsedSpace] = inputValues[i];
} else if (i > 0 && inputValues[i] != inputValues[j]) {
twoColumn[0][lastUsedSpace + 1] = inputValues[i];
}
}
}
lastUsedSpace = -1;
//Sorting the first column of the two column array
for (int i = 0; i < twoColumn.length; i++) {
for (int j = 0; j < twoColumn.length; j++) {
if (twoColumn[0][i] < twoColumn[0][j + 1]) {
temp = twoColumn[0][j + 1];
twoColumn[0][j + 1] = twoColumn[0][i];
twoColumn[0][i] = temp;
}
}
}
// filling in the frequency column of the array
for (int i = 0; i < inputValues.length; i++) {
for (int j = 0; j < inputValues.length; j++) {
if (inputValues[i] == inputValues[j]) {
valueFrequency = valueFrequency + 1;
}
if (j <= inputValues.length - 1 && lastUsedSpace == -1) {
lastUsedSpace = 0;
twoColumn[1][0] = valueFrequency;
valueFrequency = 0;
} else if (j <= inputValues.length - 1 && lastUsedSpace > -1) {
twoColumn[1][lastUsedSpace + 1] = valueFrequency;
valueFrequency = 0;
}
}
}
//printing output
for (int i = 0; i < twoColumn.length; i++) {
System.out.println("Input Frequency");
System.out.println(twoColumn[0][i]+" "+twoColumn[1][i]);
}
}
}
}
A: there I tested and fixed it you should take out the -999 jazz if you want the user to have to go through the whole 50
import java.util.Arrays;
import java.util.Scanner;
public class swinging {
static Scanner keyboard = new Scanner(System.in);
static int[] inputValues = new int[50];
int temp = 0;
int valueFrequency = 0;
int lastUsedSpace = 0;
public static void main(String[] args){
int j = 0;
for (; j < 50; j++) {
System.out.println("value #" + (j + 1) + ":");
inputValues[j] = keyboard.nextInt();
if(inputValues[j]==-999)break;
}
theValues= bubbleSort(Arrays.copyOf(inputValues, j));
for (int i = 0; i < theValues.length; i++) {
System.out.println("Input Frequency");
System.out.println(theValues[i]+" "+howMany[i]);
}
}
static int[] theValues;
static int[] howMany;
public static int[] bubbleSort(int[] Is ){
boolean switchedOne=true;
int temp;
howMany=new int[Is.length];
Arrays.fill(howMany,1);
int length=Is.length-1;
while(switchedOne){switchedOne=false;
for(int i=0;i<length;i++){
if(Is[i]>Is[i+1]){temp=Is[i];Is[i]=Is[i+1];Is[i+1]=temp;switchedOne=true;
temp=howMany[i];howMany[i]=howMany[i+1];howMany[i+1]=temp;}
if(Is[i]==Is[i+1]){Is=removeElement(Is,i+1);howMany=removeElement(howMany,i+1);howMany[i]++;length--;}
}
}
return Is;
}
public static int[] removeElement(int[] Is,int index){
for(int i=index;i<Is.length-1;i++){Is[i]=Is[i+1];}
return Arrays.copyOf(Is,Is.length-1);
}}
A: In case you are not playing with loops and wish to solve the problem on a higher-level, you could use a TreeMap and NavigableMap. See example below.
// ArrayGroupByCount.java
package com.geoloo.array;
import java.util.HashMap;
import java.util.NavigableMap;
import java.util.Scanner;
import java.util.TreeMap;
/*
* Description: Display occurence of entered numbers in descending order
* Sample input/output:
Input up to 50 values. 0 to exit
value #1:-12
value #2:3
value #3:-12
value #4:4
value #5:1
value #6:1
value #7:-12
value #8:1
value #9:-1
value #10:1
value #11:2
value #12:3
value #13:4
value #14:2
value #15:3
value #16:-12
value #17:0
map: {1=4, 2=2, 3=3, 4=2, -12=4, -1=1}
nmap: {4=2, 3=3, 2=2, 1=4, -1=1, -12=4}
*/
public class ArrayGroupByCount {
public static void main(String[] args) {
Integer input = 0;
Scanner keyboard = new Scanner(System.in);
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
TreeMap<Integer, Integer> treemap = new TreeMap<Integer, Integer>();
System.out.println("Input up to 50 values. 0 to exit");
for (int i = 0; i < 50; i++) {
System.out.print("value #" + (i + 1) + ":");
input = (int)keyboard.nextInt();
if(input==0){
break;
}
int content = 0;
if(map.containsKey(input))
content = map.get(input);
map.put(input, content+1);
}
keyboard.close();
treemap.putAll(map);
NavigableMap<Integer, Integer> nmap=treemap.descendingMap();
System.out.println("map: "+map);
System.out.println("nmap: "+nmap);
}
}
A: package project2c;
import java.util.Scanner;
public class Project2C {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int valueAmount = 0;
int temp = 0;
int valueFrequency = 1;
//gather user input to fill an array (up to 50 values);
System.out.println("how many values would you like to process?");
valueAmount = keyboard.nextInt();
int[] inputValues = new int[valueAmount];
for (int i = 0; i < valueAmount; i++) {
System.out.println("value #" + (i + 1) + ":");
inputValues[i] = keyboard.nextInt();
}
//sort values in descending order
for (int i = 0; i < inputValues.length - 1; i++) {
for (int j = 0; j < inputValues.length - 1; j++) {
if (inputValues[j + 1] > inputValues[j]) {
temp = inputValues[j + 1];
inputValues[j + 1] = inputValues[j];
inputValues[j] = temp;
}
}
}
//print out put
System.out.println();
System.out.println("Value Frequency");
for (int i = 0; i < inputValues.length - 1; i++) {
if (inputValues[i] == inputValues[i + 1]) {
valueFrequency = valueFrequency + 1;
} else if (inputValues[i] > inputValues[i + 1]) {
System.out.println(inputValues[i] + " " + valueFrequency);
valueFrequency = 1;
}
}
}
}
| |
doc_23534979
|
If I run GOPATH="$(pwd)/vendor:$(pwd)" GOBIN="$(pwd)/bin" go clean I get the following error:
can't load package: package github.com/marvincaspar/go-example: unknown import path "github.com/marvincaspar/go-example": cannot find module providing package github.com/marvincaspar/go-example
This is only for go clean, go run or go build works fine.
Here is the folder structure of main code:
.
├── Makefile
├── cmd
│ └── server
│ └── main.go
├── go.mod
├── go.sum
└── pkg
└── storage
└── mysql
└── storage.go
Here is how the go.mod file looks like:
module github.com/marvincaspar/go-example
go 1.12
require (
github.com/go-sql-driver/mysql v1.4.1
)
And finally the main.go file:
package main
import (
"fmt"
"os"
"github.com/marvincaspar/go-example/pkg/storage/mysql"
)
func main() {
if err := run(); err != nil {
fmt.Fprintf(os.Stderr, "%v", err)
os.Exit(1)
}
}
func run() error {
// init storage
s := mysql.NewStorage()
// do some other stuff...
}
Any ideas what I am doing wrong?
A: I generally use go get and go mod tidy for same. It works all the time.
go mod tidy
A: Normally this new project approach works for me:
go mod init <project_name>
go test
I have found that developing projects outside of GOROOT and GOPATH are much easier
A: Go build/install is trying to find main package in your root directory, it is not checking sub-directories (cmd/server) in your case. Hence you are getting package not found error.
To properly build your code, you can run:
go build github.com/marvincaspar/go-example/cmd/server
Similarly, to run your project, you will have to provide module-name/main-package-path:
go run github.com/marvincaspar/go-example/cmd/server
Go clean can be executed in same way, by providing module-name/path-with-main-package
go clean github.com/marvincaspar/go-example/cmd/server
or
GOPATH="$(pwd)/vendor:$(pwd)" GOBIN="$(pwd)/bin" go clean github.com/marvincaspar/go-example/cmd/server
However, as per https://blog.learngoprogramming.com/code-organization-tips-with-packages-d30de0d11f46, just put your source files into your project’s root. It’s better that way.
A: This can also happen if you are using workspaces. It seems like you can't use one package without workspaces if you are using others with workspaces.
So try going into your top level workspace and do
go work use ./problemPackage.
At least this worked for me.
A: To solve this problem you have to do few things, First, go to the project directory via the Terminal then run the following command ( If you are using git clone then go to the clone directory folder via Terminal and run the following command):
Step 1: sudo go mod init your-program.go
Step 2: sudo go mod tidy
Step 3: sudo go build your-program.go
| |
doc_23534980
|
After the identification I need to authenticate that user with Azure AD, without entering/passing the password. (Fingerprint only authentication).
Is this possible?
A: No. Azure AD will require the password regardless.
In the future we might have a passwordless authentication capability there, but that would be up to the user to enable.
| |
doc_23534981
|
How would I make up a rule in my parser that will match the string above?
Seems rather impossible for me, since you cant define an unlimited amount of properties in the rule? Could someone please clarify, how you would do such a thing with FsLex and FsYacc?
A: If you're using FsLex and FsYacc then you can parse the properties inside { ... } as a list of properties. Assuming you have a lexer that properly recognizes all the special characters and you have a rule that parses individual property, you can write something like:
declaration:
| navigators LCURLY propertyList RCURLY { Declaration($1, $3) }
| navigators LCURLY RCURLY { Declaration($1, []) }
propertyList:
| property SEMICOLON propertyList { $1::$2 }
| property { [$1] }
property:
| IDENTIFIER COLON values { Property($1, $3) }
The declaration rule parses the entire declaration (you'll need to write parser for various navigators that can be used in CSS such as div.foo #id etc.) The propertyList rule parses one property and then calls itself recursively to parse multiple properties.
The values constructed on the right-hand-side are going to be a list of values representing individual property. The property rule parses individual property assignment e.g. width:100% (but you'll need to finish parsing of values, because that can be a list or a more compelx expression).
| |
doc_23534982
|
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
jQuery = window.jQuery.noConflict(true);
main();
}
/******** Main function ********/
function main() {
jQuery(document).ready(function ($) {
var domain = 'http://qo.microssoftware.com';
/******* Load SimpleModal *******/
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
domain + "/js/simplemodal.js");
script_tag.onload = modalLoadHandler;
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
});
}
function modalLoadHandler() {
/******* Open Modal *******/
$.modal("<div><h1>SimpleModal</h1></div>", {});
}
A: Try:
<script type="text/javascript" src="http://qo.microssoftware.com/js/simplemodal.js"></script>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$.modal("<div><h1>SimpleModal</h1></div>");
});
</script>
OR, if you want to call the modal using your main() function:
<script type="text/javascript" src="http://qo.microssoftware.com/js/simplemodal.js"></script>
<script type="text/javascript">
jQuery(document).ready(function ($) {
function main() {
$.modal("<div><h1>SimpleModal</h1></div>");
}
});
</script>
You don't need to put the js in the header... Actually some programmers always put all their JS just before the ending BODY-tag.
A: I would suggest that this is unnecessary, to begin with. The simplemodal script is very compact. Give more consideration to how to optimize script loading in general (gzip, or if you must go ajax, AMD dependency loading with RequireJS or the like) without the unnecessary complication of this kind of ajax method.
The script loaders that use this type of method (like the Facebook SDK or Google Maps) will search the window (global) element for a callback to call once the script is initialized. Basically, you would have to modify the simplemodal code and then wrap your dependent code in a callback. I hardly see how that could be necessary in this case.
A: This is where you would want to create an async-closure based around the onload event of the script.
If you must support ancient IE, you can also hook into the onreadystatechange event, the same way you would do it in AJAX requests (in pure JS).
The more-modern browsers won't fire this event.
So turn the onload into a callback, which fires known methods from the file.
You can get around errors by also attaching to the onerror of the script's loading.
| |
doc_23534983
|
How to make this using php?
| |
doc_23534984
|
I've taken all constrains into consideration, but it seems like all the facts are being deleted for some reason...
This my code so far:
;;MAIN Module
(deftemplate state
(slot farmer-position)
(slot fox-position)
(slot goat-position)
(slot cabbage-position)
(slot id)
(slot prev-state (default nil))
(multislot move (default nil)))
(deftemplate finished
(slot value))
(deffacts initial-facts
(state (farmer-position s1)
(fox-position s1)
(goat-position s1)
(cabbage-position s1)
(id 0))
(opp s1 s2)
(opp s2 s1))
;;CONSTARIN Modle
(defmodule CONSTRAIN)
(defrule CONSTRAIN::fox-goat
(declare (auto-focus true))
?p<-(MAIN::state (fox-position ?f) (goat-position ?f) (farmer-position
~?f))
=>
(retract ?p))
(defrule CONSTRAIN::goat-cabbge
(declare (auto-focus true))
?p<-(MAIN::state (goat-position ?f) (cabbage-position ?f) (farmer-
position ~?f))
=>
(retract ?p))
(defrule CONSTRAIN::no-doubles
(declare (auto-focus true))
?p1<-(MAIN::state (farmer-position ?s1) (fox-position ?s2) (goat-
position ?s3) (cabbage-position ?s4) (id ?id1))
?p2<-(MAIN::state (farmer-position ?s1) (fox-position ?s2) (goat-
position ?s3) (cabbage-position ?s4) (id ?id2&:(> ?id2 ?id1)))
=>
(retract ?p2))
(defrule CONSTRAIN::stop-exc
(declare (auto-focus true))
?p1<-(MAIN::state (farmer-position s2) (fox-position s2) (goat-position
s2) (cabbage-position s2))
=>
(assert (MAIN::finished (value yes))))
;;MOVE Module
(defmodule MOVE)
(defrule MOVE::move-fox
?p<-(MAIN::state (farmer-position ?old) (fox-position ?old) (id ?id))
(not (MAIN::finished (value yes)))
(opp ?old ?new)
=>
(duplicate ?p (farmer-position ?new)
(fox-position ?new)
(prev-state ?p)
(id (+ ?id 1))
(move fox ?new)))
(defrule MOVE::move-goat
?p<-(MAIN::state (farmer-position ?old) (goat-position ?old) (id ?id))
(not (MAIN::finished (value yes)))
(opp ?old ?new)
=>
(duplicate ?p (farmer-position ?new)
(goat-position ?new)
(prev-state ?p)
(id (+ ?id 1))
(move goat ?new)))
(defrule MOVE::move-cabbage
?p<-(MAIN::state (farmer-position ?old) (cabbage-position ?old) (id ?
id))
(not (MAIN::finished (value yes)))
(opp ?old ?new)
=>
(duplicate ?p (farmer-position ?new)
(cabbage-position ?new)
(prev-state ?p)
(id (+ ?id 1))
(move cabbage ?new)))
;;RUN
(reset)
(watch all)
(focus MOVE)
(run)
(facts)
And here is my output:
<== Focus MAIN
==> Focus MOVE
FIRE 1 MOVE::move-fox f-1,, f-2
==> f-4 (MAIN::state (farmer-position s2) (fox-position s2) (goat-position
s1) (cabbage-position s1) (id 1) (prev-state <Fact-1>) (move fox s2))
==> Activation: CONSTRAIN::goat-cabbge : f-4
==> Activation: MOVE::move-fox : f-4,, f-3
<== Focus MOVE
==> Focus CONSTRAIN
FIRE 2 CONSTRAIN::goat-cabbge f-4
<== f-4 (MAIN::state (farmer-position s2) (fox-position s2) (goat-position
s1) (cabbage-position s1) (id 1) (prev-state <Fact-1>) (move fox s2))
<== Activation: MOVE::move-fox : f-4,, f-3
<== Focus CONSTRAIN
==> Focus MOVE
FIRE 3 MOVE::move-cabbage f-1,, f-2
==> f-5 (MAIN::state (farmer-position s2) (fox-position s1) (goat-position
s1) (cabbage-position s2) (id 1) (prev-state <Fact-1>) (move cabbage s2))
==> Activation: CONSTRAIN::fox-goat : f-5
==> Activation: MOVE::move-cabbage : f-5,, f-3
<== Focus MOVE
==> Focus CONSTRAIN
FIRE 4 CONSTRAIN::fox-goat f-5
<== f-5 (MAIN::state (farmer-position s2) (fox-position s1) (goat-position
s1) (cabbage-position s2) (id 1) (prev-state <Fact-1>) (move cabbage s2))
<== Activation: MOVE::move-cabbage : f-5,, f-3
<== Focus CONSTRAIN
==> Focus MOVE
FIRE 5 MOVE::move-goat f-1,, f-2
==> f-6 (MAIN::state (farmer-position s2) (fox-position s1) (goat-position
s2) (cabbage-position s1) (id 1) (prev-state <Fact-1>) (move goat s2))
==> Activation: MOVE::move-goat : f-6,, f-3
FIRE 6 MOVE::move-goat f-6,, f-3
==> f-7 (MAIN::state (farmer-position s1) (fox-position s1) (goat-position
s1) (cabbage-position s1) (id 2) (prev-state <Fact-6>) (move goat s1))
==> Activation: CONSTRAIN::no-doubles : f-1, f-7
==> Activation: MOVE::move-fox : f-7,, f-2
==> Activation: MOVE::move-goat : f-7,, f-2
==> Activation: MOVE::move-cabbage : f-7,, f-2
<== Focus MOVE
==> Focus CONSTRAIN
FIRE 7 CONSTRAIN::no-doubles f-1, f-7
<== f-7 (MAIN::state (farmer-position s1) (fox-position s1) (goat-position
s1) (cabbage-position s1) (id 2) (prev-state <Fact-6>) (move goat s1))
<== Activation: MOVE::move-fox : f-7,, f-2
<== Activation: MOVE::move-goat : f-7,, f-2
<== Activation: MOVE::move-cabbage : f-7,, f-2
<== Focus CONSTRAIN
==> Focus MOVE
<== Focus MOVE
==> Focus MAIN
<== Focus MAIN
For a total of 0 facts in module MOVE.
A: Fact f-6 was not retracted. The only valid first move is for the farmer to cross the river with the goat and that's the move represented by f-6. You don't have a rule for moving the farmer across the river alone, so the only valid move for the farmer from f-6 is to move back across the river with the goat which takes you back to the initial position. Since the initial position represented by f-1 is the same as f-7, the rule no-doubles retracts f-7 and there are no remaining valid moves.
If you download Jess from http://www.jessrules.com/jess/download.shtml, code for the river crossing example is available in the examples directory in the file dilemma.clp.
| |
doc_23534985
|
I have Glass Development Kit Preview from Android API 19 installed. My build.gradle(Module: app) is updated to reflect that:
compileSdkVersion 'Google Inc.:Glass Development Kit Preview:19'
buildToolsVersion '25.0.0'
I've looked at similar problems and I seem to have my build.gradle set up properly. How can I get the Gradle Sync to recognize my GDK?
A: You can try using the base build Tools for GDK:
android {
compileSdkVersion "Google Inc.:Glass Development Kit Preview:19"
buildToolsVersion "19.1.0"
}
Download Android 4.4.2 or API 19.
Or try using this link . It creates a new project of GDK, and you can check how gradle looks afterwards.
| |
doc_23534986
|
One possible solution to this would be to generate GUIDs as ClientID. This way the ClientID will at most be 32 characters long.
Has anyone ever tried something like this before?
I am on .NET 4.0
A: You can use ClientIDMode enumeration and specify static. But then you will have to manage the uniqueness of each control's ClientID.
Using GUID won't be such a good idea because it would be difficult to access them in client side code. You will be required to maintain a mapping between GUID and which control it corresponds to.
But you should really think whether having a lengthy client ID is really that bad for your page performance. Instead of worrying about the client ids you should find a way to limit number of controls/data to be displayed on the page, implement something like paging.
A: If you have too many controls on your page, it might be time to rethink your architecture rather than getting a miniscule bit of better performance from shorter ID's.
Page your data (load it via AJAX). You can also load entire sections of your page via Ajax and build up a dynamic web page.
A: That is generally a bad idea.
But if you are interested, you can set ClientIDMode property to Static, which will not change the id.
The id will remain the same.
| |
doc_23534987
|
Could not establish trust relationship
System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)...
For the an ASP.NET web App:
Example1 es = new Example1();
try
{
int result = es.checkUserExists("bob");
TextBox1.Text = result.ToString();
}
catch (Exception ex) {
TextBox1.Text = ex.ToString();
}
My Proxy is the following:
<proxy xmlns="http://ws.apache.org/ns/synapse" name="Example1" transports="https,http" statistics="disable" trace="disable" startOnLoad="true">
<target>
<inSequence>
<property name="STATUS" value="asking_id" scope="default" type="STRING"/>
<log level="full">
<property name="insequence****" value="This is the in sequence"/>
<property xmlns:ns2="http://chi/" name="property_arg0" expression="//ns2:checkUserExists/arg0"/>
</log>
<send>
<endpoint>
<address uri="http://192.168.10.176:8080/Example1/UserExist/"/>
</endpoint>
</send>
</inSequence>
<outSequence>
<switch source="get-property('STATUS')">
<case regex="asking_id">
<log level="full">
<property name="sequence*******" value="outSequence - STATE 01 - asking for balance"/>
<property xmlns:ns2="http://chi/" name="property_result******" expression="//ns2:checkUserExistsResponse/return"/>
<property name="status********" expression="get-property('STATUS')"/>
</log>
<property xmlns:ns2="http://chi/" name="id_result" expression="//ns2:checkUserExistsResponse/return" scope="default" type="STRING"/>
<enrich>
<source type="inline" clone="true">
<ns2:getBalancebyID xmlns:ns2="http://chi/">
<arg0 xmlns="">?</arg0>
</ns2:getBalancebyID>
</source>
<target type="body"/>
</enrich>
<enrich>
<source type="property" clone="true" property="id_result"/>
<target xmlns:ns2="http://chi/" xpath="//ns2:getBalancebyID/arg0"/>
</enrich>
<property name="STATUS" value="response" scope="default" type="STRING"/>
<send>
<endpoint>
<address uri="http://192.168.10.176:8080/Example1/UserBalance"/>
</endpoint>
</send>
</case>
<case regex="response">
<log level="full">
<property name="sequence*******" value="outSequence - STATE 02 - returning balance"/>
</log>
<send/>
</case>
</switch>
</outSequence>
</target>
<publishWSDL key="conf:/UserExist.xml"/>
<description></description>
</proxy>
Any suggestion why I cannot consume the Proxy?
Thank you for your help
A: This is related to .Net App..There are number of sources available regarding this issue
eg:
http://support.microsoft.com/kb/823177
| |
doc_23534988
|
The code is as follows:
package test;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
public class Demo {
private final JFrame frame;
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
private JPanel videoPane;
private JPanel buttonPane;
private Button exitButton;
private ActionListener a;
private static String vlc_location = "C:\\Program Files\\VideoLAN\\VLC";
public static void main(String[] args) {
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), vlc_location);
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Demo().run();
}
});
}
public Demo() {
mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
a = new MyActionListener();
exitButton = new Button("Exit");
exitButton.setActionCommand("Exit app");
exitButton.addActionListener(a);
buttonPane = new JPanel();
buttonPane.setLayout(new BorderLayout());
buttonPane.setBackground(Color.black);
buttonPane.add(exitButton, BorderLayout.CENTER);
videoPane = new JPanel();
videoPane.setLayout(new BorderLayout());
videoPane.setBackground(Color.black);
videoPane.add(mediaPlayerComponent, BorderLayout.CENTER);
videoPane.add(buttonPane, BorderLayout.PAGE_END);
frame = new JFrame("vlcj demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100, 100);
frame.setSize(1200, 800);
frame.setContentPane(videoPane);
frame.setVisible(true);
}
public void run() {
mediaPlayerComponent.getMediaPlayer().playMedia(video_file);
}
class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
String s = arg0.getActionCommand();
if (s.equals("Exit")) {
System.exit(0);
}
}
}
}
The problem is that the button does show up but it cannot be clicked. When i removed the videoPane, it was back to clickable! Any ideas if I'm missing something?
I am using the version 2.1.0 for vlcj.
Thanks!
A: Thanks MadProgrammer for your advise. I went on to think about it and tried commenting away the line of code in run(). The JButton came back!
However, when i un-commented the code in run(), the JButton disappeared. I was thinking maybe the Swing runnable was causing issue with the creation of the JButton.
Hence, what i did was to comment away the whole Swing runnable and just use:
final Demo demo = new Demo();
demo.run();
The demo can now play video and display the Exit button, thanks!
| |
doc_23534989
|
After researching in JWT workflow, what I understood is:
1) JWT token should have the least expiry date (TTL: 30 minutes).
2) JWT refresh token expiry date should not be greater than 1 week.
The flow from what I understood is:
1) The user logs in and receives a JWT token.
2) For every request, it should provide the JWT token to the system.
3) If JWT token is expired, the system checks the JWT token and provides it with the refresh token
What I did not understand is:
1) What to do if the refresh token is expired? Do the user again sign in?
2) Should the mobile replace the expired token to refresh token and provide the currently saved refresh token every time it requests to the system?
3) If the unauthorized person has the expired token, he/she can still access the person's information since the system always provides it with refresh token and the loop continues.
4) Do I have to store the refresh token in Laravel app?
I extracted the JWT token check inside VerifyJWTToken.php middleware
class VerifyJWTToken extends BaseMiddleware
{
public function handle($request, Closure $next)
{
try {
if (!$user = JWTAuth::parseToken()->authenticate()) {
return response()->json([
'status' => 'false',
'data' => null,
'message' => 'User not found'
]);
}
} catch (TokenExpiredException $e) {
try {
$refreshed = JWTAuth::refresh(JWTAuth::getToken());
$user = JWTAuth::setToken($refreshed)->toUser();
$request->merge(['refreshed_token'=> $refreshed])
} catch (JWTException $e) {
return response()->json([
'status' => 'false',
'data' => null,
'message' => 'Token Invalid'
]);
}
} catch (JWTException $e) {
return response()->json([
'status' => 'false',
'data' => null,
'message' => 'Token Not Provided'
]);
}
auth()->login($user);
return $next($request);
}
}
A: 1) What to do if the refresh token is expired? Do the user again sign in?
=> Yes if this token is expired you should redirect to login page.
4) Do I have to store the refresh token in Laravel app?
=> No need, but you need save this token on client app ( Localstogare, Cookie, etc... )
| |
doc_23534990
|
I am using win7, wamp64 with cakephp3. In the php.ini file the extension existsextension=php_intl.dll exists so what is the problem? I can run phpinfo
Fatal error: You must enable the intl extension to use CakePHP.
A: You have to check
*
*Open /wamp64/bin/php/php.ini
*Change ;extension=php_intl.dll to extension=php_intl.dll (remove the semicolon)
*Copy all the /wamp64/bin/php/ic*.dll files to /wamp64/bin/apache/bin then click Restart All Services in the Wamp try icon from your task bar.
N.B: Also you have to check php_intl.dll exist in /wamp64/bin/php/ext/
Update:
try to reinstall the Apache trayicon>>Apache>>Service Administration>>Install Service then click Restart All Services in the Wamp tray
| |
doc_23534991
|
Total companies processed so far:0 Traceback (most recent call last):
File "process1.py", line 261, in
print "Company Name: "+hit.text File "C:\Python27\lib\encodings\cp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\xfd' in
position 3 3: character maps to
my code is here :
if companyAlreadyKnown == 0:
for hit in soup2.findAll("h1"):
print "Company Name: "+hit.text
pCompanyName = hit.text
flog.write("\nCompany Name: "+str(pCompanyName))
companyObj.setCompanyName(pCompanyName)
I don't know why it is happened.Any suggestion in this problem?
A: Czech language contains a lot of non ASCII characters. u'\xfd' is a unicode representation of ý. You need to decode UTF-8. An even better solution is to detect what encoding the website you are scraping uses and decode to that one.
if companyAlreadyKnown == 0:
for hit in soup2.findAll("h1"):
company_name = hit.text.decode('utf-8')
print "Company Name: " + company_name
flog.write("\nCompany Name: " + pCompanyName)
companyObj.setCompanyName(company_name)
| |
doc_23534992
|
Sample Input:
Also known as temple of the city,
xxx as Pune Banglore as kolkata Delhi India,
as Mumbai India or as Bombay India,
Calcutta,India is now know as Kolkata,India,
From the above I want to convert as xxx xxxx xx, to as xxx_xxxx_xx, and it should be effective after the last as.
Sample output for above:
Also known as temple_of_the_city,
xxx as Pune Banglore as kolkata_Delhi_India,
as Mumbai India or as Bombay_India,
Calcutta,India is now know as Kolkata,India,
There should be no space separated string after the last as in a line.
Please let me know if it is not clear.
Thanks
A: Paul is right that it's not really a simple task. This is a sed solution that I put together:
sed 's/\(.*as \)/\1\n/;h;y/ /_/;G;s/.*\n\(.*\)\n\(.*\)\n.*/\2\1/' file.txt
Demonstration on your data:
$ echo 'Also known as temple of the city,
> xxx as Pune Banglore as kolkata Delhi India,
> as Mumbai India or as Bombay India,
> Calcutta,India is now know as Kolkata,India,' | \
> sed 's/\(.*as \)/\1\n/;h;y/ /_/;G;s/.*\n\(.*\)\n\(.*\)\n.*/\2\1/'
Also known as temple_of_the_city,
xxx as Pune Banglore as kolkata_Delhi_India,
as Mumbai India or as Bombay_India,
Calcutta,India is now know as Kolkata,India,
A: I'd be inclined to use Perl, the swiss army chainsaw, but sed is also an option. In either case you're looking at a substantial learning curve.
The replacement you've described is probably complex enough that you'd be better off writing a script rather than trying to do it as a one liner.
If you're going to write a script and don't already know Perl there's no reason why you shouldn't pick your scripting language of choice (python, ruby, etc) as long as it has some sort of text pattern matching syntax.
I don't know of a simple, shallow learning curve method of doing a complex pattern match and replacement of this sort. Is this a one time thing where you need to do this replacement only? Or are you going to be doing similar sorts of complicated pattern replacements in the future. If you're going to be doing this frequently you really should invest the time in learning some scripting language but I won't impose my Perl bias on you. Just pick any language that seems accessible.
| |
doc_23534993
|
For example:
Dim clone_object As Variant
Set clone_object = some_object
some_object.Left = 0
clone_object.Left = 666
'I want it to show 0 instead of 666
Debug.print some_object.Left
A: You need to create methods like this in your class module (here it is Config) or do the same in the regular module if it is not a custom object :
Friend Sub SetConfig(SrcConfig As Config)
Set Cfg = SrcConfig
End Sub
Public Function Copy() As Config
Dim Result As Config
Set Result = New Config
Call Result.SetConfig(Cfg)
Set Copy = Result
End Function
| |
doc_23534994
|
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Login::$membership_model
Filename: controllers/login.php
Line Number: 12
Backtrace:
File: C:\xampp\htdocs\Project5_1\CodeIgniter\application\controllers\login.php
Line: 12
Function: _error_handler
File: C:\xampp\htdocs\Project5_1\CodeIgniter\index.php
Line: 315
Function: require_once
Fatal error: Call to a member function getSearchBook() on null in C:\xampp\htdocs\Project5_1\CodeIgniter\application\controllers\login.php on line 12
A PHP Error was encountered
Severity: Error
Message: Call to a member function getSearchBook() on null
Filename: controllers/login.php
Line Number: 12
Backtrace:
My Controller Page is:
<?php
class Login extends CI_Controller{
function search(){
$searchBook = $this->input->post('searchBook');
$data = $this->membership_model->getSearchBook($seachBook);
$this->load->view('main_content',$data);
}
?>
My Model page is:
class Membership_model extends CI_Model{
function getSearchBook($searchBook) {
$this->db->select('*');
$this->db->from('book');
$this->db->like('author',$searchBook);
return $query->result();
}
}
My main_content.php is:
<?php
echo form_open('login/search');
echo form_input('searchBook','Search Book', 'id="searchBook"');
echo form_submit('submit', 'Search');
echo form_close();
?>
<table><th>Title</th></table>
<div>
<?php
// List up all results.
foreach ($results as $val)
{
echo $val['title'];
}
?>
</div>
</body>
A: It's been a long time since I used CodeIgniter, but from what I remember, you're not loading the model in your Login class constructor. That's why you're getting these two parts of the error:
Message: Undefined property: Login::$membership_model
Message: Call to a member function getSearchBook() on null
Neither the property or the function exist in the Login class if you haven't loaded the membership_model model.
Off the top of my head, I think it needs to be something like this in your Login controller:
<?php
class Login extends CI_Controller{
function __construct()
{
parent::__construct();
$this->load->model('membership_model');
}
function search(){
$searchBook = $this->input->post('searchBook');
$data = $this->membership_model->getSearchBook($seachBook);
$this->load->view('main_content',$data);
}
?>
| |
doc_23534995
|
If I do the following:
df.rolling(window = 30).mean().shift(1)
my df results in a window with lots of NaNs, which is probably caused by NaNs in the original dataframe here and there (1 NaN within the 30 data points results the MA to be NaN).
Is there a method that ignores NaN (avoiding apply-method, I run it on large data so performance is key)? I do not want to replace the value with 0 because that could skew the results.
the same applies than to moving standard deviation.
A: For example you can adding min_periods, and NaN is gone
df=pd.DataFrame({'A':[1,2,3,np.nan,2,3,4,np.nan]})
df.A.rolling(window=2,min_periods=1).mean()
Out[7]:
0 1.0
1 1.5
2 2.5
3 3.0
4 2.0
5 2.5
6 3.5
7 4.0
Name: A, dtype: float64
A: Option 1
df.dropna().rolling('30D').mean()
Option 2
df.interpolate('index').rolling('30D').mean()
Option 2.5
df.interpolate('index').rolling(30).mean()
Option 3
s.rolling('30D').apply(np.nanmean)
Option 3.5
df.rolling(30).apply(np.nanmean)
A: You can try dropna() to remove the nan values or fillna() to replace the nan with specific value.
Or you can filter out all nan value by notnull() or isnull() within your operation.
df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', 'h'],columns=['one', 'two', 'three'])
df2 = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
print df2
one two three
a 0.434024 -0.749472 -1.393307
b NaN NaN NaN
c 0.897861 0.032307 -0.602912
d NaN NaN NaN
e -1.056938 -0.129128 1.328862
f -0.581842 -0.682375 -0.409072
g NaN NaN NaN
h -1.772906 -1.342019 -0.948151
df3 = df2[df2['one'].notnull()]
# use ~isnull() would return the same result
# df3 = df2[~df2['one'].isnull()]
print df3
one two three
a 0.434024 -0.749472 -1.393307
c 0.897861 0.032307 -0.602912
e -1.056938 -0.129128 1.328862
f -0.581842 -0.682375 -0.409072
h -1.772906 -1.342019 -0.948151
For further reference, Pandas has a clean documentary about handling missing data(read this).
| |
doc_23534996
|
My question is: How long should I keep a Entity Manager open?
Swing Application:
- One open Entity Manager as long as the application is running
- Each single action a new Entity Manager
Web Application:
- One Entity Manager per (distinct) action
- One per request
- One per session
- One per application(-scope), asuming the application is thread safe
Best Regards
A: For the Swing application, I will opt for the one EntityManager per action since it's quite cheap to create one and you might not want to keep so many entites managed by EntityManager when you're not using it (this is One EntityManager per application).
For the Web application, typical pattern used is "OpenSessionInView" pattern (Session applied to Hibernate but it can be applied to EntityManager as well since both are logically providing the same role/functionality).
More info here:
https://community.jboss.org/wiki/OpenSessionInView
Hope this helps.
A: One entity manager per request should be normal. But they should work through some connection pool.
| |
doc_23534997
|
public class Company {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public List<People> Peoples { get; set; }
[StringLength(100)]
[Required]
public string Bname { get; set; }
}
and
public class People {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string FName { get; set; }
[StringLength(50)]
public string LName { get; set; }
[StringLength(50)]
}
i prefer not to use data annotation, so i can keep my maps seperated and in on place.
My simplified mapping is:
class CompanyMap : EntityTypeConfiguration<Company> {
public CompanyMap() {
HasMany(p => p.Peoples)
.WithRequired();
}}
It's seems to work well, people got a fk to company in db, and EF can insert and pull back data, and i can query it if i do it with lambda:
var tmp = db.Companies.Include("Peoples")
but if i try to query it with linq, and join them up:
var tmp2 = from c in db.Companies
join p in db.Person
on c.Id equals p.
and right there is my problem, People object did not expose it's foreign key from db, so i can't join them up like this.
So my question is, can i expose the fluent api created fk to my object modell, so i can linq it?
Alternatively should i use the lambda one, and map it to my viewmodel somehow, so it wont produce unneeded columns for this view?
A: First, add the FK property (CompanyId) and the navigation property (Company) to your People entity:
public class People {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
//...
public int CompanyId {get;set}
public virtual Company Company{get;set;}
}
Then, move the Fluent Api relationship configuration to the PeopleMap class and modify that configuration this way (also map the FK property with the same name that have that FK column in the People table):
public class PeopleMap : EntityTypeConfiguration<People> {
public CompanyMap() {
Property(p => p.CompanyId)
.HasColumnName("CompanyId");//remember change the name for the real FK column
HasRequired(p=>p.Company)
.WithMany(c=>c.Peoples)
.HasForeignKey(p=>p.CompanyId);
}
}
After that, you should be able of use CompanyId FK property in your query:
var tmp2 = from c in db.Companies
join p in db.Person on c.Id equals p.CompanyId
//...
| |
doc_23534998
|
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Cookies extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
Cookie coki[]=request.getCookies();
Cookie tokenCookie=null;
if(coki!=null)
{
for(int i=0;i<coki.length;i++)
{
if(coki[i].getName().equals("token"))
{
tokenCookie=coki[i];
break;
}
}
}
String resetParam=request.getParameter("resetParam");
if(tokenCookie==null || (resetParam!=null && resetParam.equals("yes")))
{
Random rnd=new Random();
long cookieid=rnd.nextLong();
out.println("Welcome. A new token "+cookieid+" is now established");
tokenCookie =new Cookie("token",Long.toString(cookieid));
tokenCookie.setComment("Cookie named token to identity user");
tokenCookie.setMaxAge(-1);
tokenCookie.setPath("/ServletPractice/Cookies");
response.addCookie(tokenCookie);
}
else
{
out.println("Welcome back. Your token id is "+tokenCookie.getValue()+"");
}
String requestURLSame=request.getRequestURL().toString();
String requestURLNew=request.getRequestURL()+"?requestParam=yes";
out.println("Click <a href="+requestURLSame+">here</a> to browse with same identity");
out.println("Click <a href="+requestURLNew+">here</a> to browse with new identity");
out.close();
}
}
When I run the above servlet in my chrome browser it displays,
If I click the link for "new identity" the the id displayed is not changed but the string changes from to that of "welcome" to "welcome back".
Kindly guide me through.
Thanks in advance.
| |
doc_23534999
|
A: Use the string.split() method to split the string on the " " character and then return the nth-1 element of the array (this example doesn't include any bounds checking so be careful):
var getNthWord = function(string, n){
var words = string.split(" ");
return words[n-1];
}
A: I think you can split your string based on space, get the array and then look for value from the index n-1.
var myStr = "Pumpkin pie and ice cream";
var strArr = myStr.split(String.fromCharCode(32)) //ascii code for space is 32.
var requiredWord = strArr[n-1];
var firstWord = strArr[0];
var lastWord = strArr[ strArr.length - 1 ];
Ofcourse error handling is left to you.
A: Use the split function to get the individual words into a list, then just grab the word that's in index n - 1.
var sentence = "Pumpkin pie and ice cream";
var words[] = sentence.split(" ");
print words[2]; // if you want word 3, since indexes go from 0 to n-1, rather than 1 to n.
A: A very simple solution would be:
var str = "Pumpkin pie and ice cream"; //your string
var word = 3; //word number
var word = str.split(" ")[word - 1];
However, this does not take consideration of other whitespace(tabs, newlines...) or periods and commas.
A: Or use the non-word based split: "test,test2 test3".split(/\W/) would yield: [test,test2,test3].
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.