text:
Q: Socket destroyed or timeout while reading data I am writing an socket client at the moment.
Writing on the socket works perfectly.
But when i try to read the data with BufferedReader it hangs.
Sometimes it works but the mostly the socket is destroyed by the (device?).
(I only see this at the Server Side: +WIND:62:Socket Client Gone:172.20.237.2, which means Client is gone/closed socket)
I tried:
- first i used readNewLine, it worked but slowly so i tought this was
blocking.
- then i tried Char by Char but this is also blocking at: br.read i think.
- i tried to set Socket Timeot to 100000 e.g.
- i changed port (80,3067, now 6660)

i dont know why its so slow its only connection from Wifi-Module (with Socketlistener) to Android-phone.
At this example i use char "!" to let my client know when string is at the end.
Maybe its another problem...
I hope somebody can help me.
Here is my Write/Read code:
 @Override
     protected String doInBackground(String... params) //was strings
     {
         ip = params[0];
        message = params[1];
        port = params[2];

        try
        {
            s = new Socket(ip,Integer.parseInt(port));
            s.setSoTimeout(100000);

            if (s.isConnected())
            {
                dos = new DataOutputStream(s.getOutputStream());
                dos.writeBytes(message);
                dos.flush();

                is = s.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                //StringBuffer buffer = new StringBuffer();

                // or of course StringBuffer if you need to be treadsafe
                StringBuilder messageBuffer = new StringBuilder();

                // reads to the end of the stream or till end of message
                while((value = br.read()) != -1) {
                    char c = (char)value;
                    // end?  jump out
                    if (c == endMarker) {
                        break;
                    }
                    // else, add to buffer
                    messageBuffer.append(c);
                }
                // message is complete!
                response = messageBuffer.toString();

                /*
                BufferedReader br = new BufferedReader(new
InputStreamReader(s.getInputStream()));
                response = br.readLine();
                */
            }
            //dos.writeUTF(message);

            //br.close();
            dos.close();
            s.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        return response;
    }

And the LogCat after i saw the Client was gone:
I dont know if this caused the problem or happend after it:
java.lang.NumberFormatException: s == null
2018-11-20 15:34:44.921 3787-3920/? D/SemContextService:
Service.updateContext() : service = Step Level Monitor
2018-11-20 15:34:44.924 22956-23045/? I/Sensor[0x06]: [0x01] 33
2018-11-20 15:34:44.925 22956-23045/? I/Sensor[0x04]: [0x01]
1542724446610[0x02] 0[0x03] 2[0x04] 10012
2018-11-20 15:34:45.686 27406-27406/? D/gpsd: CALL_SENTRY(main()):
GlEngine::OnResourceRelease took 251 ms (from 143759612 to 143759863)
(logOverhead=0,0,0,0,0,0,0), start: 15:34:45.435
2018-11-20 15:34:45.937 27406-27406/? D/gpsd: CALL_SENTRY(main()):
GlEngine::OnResourceRequest took 251 ms (from 143759863 to 143760114)
(logOverhead=0,0,0,0,0,0,0), start: 15:34:45.686
2018-11-20 15:34:45.940 27406-27406/? D/gpsd: CALL_SENTRY(main()):
GlEngine::ChipData took 506 ms (from 143759611 to 143760117)
(logOverhead=0,0,0,0,0,0,0), start: 15:34:45.434
2018-11-20 15:34:45.941 27406-27406/? D/gpsd: CALL_SENTRY(main()):
ProcessEvent took 507 ms (from 143759611 to 143760118)
(logOverhead=0,0,0,0,0,0,0), start: 15:34:45.434
2018-11-20 15:34:46.161 3787-8916/? D/ConnectivityService:
filterNetworkStateForUid() uid: 1000 networkInfo: [type: WIFI[] - WIFI,
state: CONNECTED/CONNECTED, reason: (unspecified), extra: "SocketAppTest",
failover: false, available: true, roaming: false, metered: false]
2018-11-20 15:34:46.192 3408-6813/? V/APM_AudioPolicyManager:
getAudioPolicyConfig: audioParam;activeStream
2018-11-20 15:34:46.193 3408-6813/? V/APM_AudioPolicyManager: ### active
stream : 0
2018-11-20 15:34:46.194 3787-8916/? D/AudioService: active stream is 0x0
2018-11-20 15:34:46.196 3408-6813/? V/APM_AudioPolicyManager:
getAudioPolicyConfig: audioParam;outDevice
2018-11-20 15:34:46.196 3408-6813/? V/APM_AudioPolicyManager:
getNewOutputDevice() selected device 0
2018-11-20 15:34:46.197 3408-6813/? V/APM_AudioPolicyManager: ### curdevice
: 2
2018-11-20 15:34:46.202 3787-8916/? W/System.err:
java.lang.NumberFormatException: s == null
2018-11-20 15:34:46.202 3787-8916/? W/System.err:     at
java.lang.Integer.parseInt(Integer.java:570)
2018-11-20 15:34:46.203 3787-8916/? W/System.err:     at b.b.aF(:79)
2018-11-20 15:34:46.203 3787-8916/? W/System.err:     at b.c.aN(:149)
2018-11-20 15:34:46.203 3787-8916/? W/System.err:     at b.n.run(:72)
2018-11-20 15:34:46.203 3787-8916/? W/System.err:     at
android.os.Handler.handleCallback(Handler.java:789)
2018-11-20 15:34:46.203 3787-8916/? W/System.err:     at
android.os.Handler.dispatchMessage(Handler.java:98)
2018-11-20 15:34:46.203 3787-8916/? W/System.err:     at
android.os.Looper.loop(Looper.java:164)
2018-11-20 15:34:46.203 3787-8916/? W/System.err:     at
android.os.HandlerThread.run(HandlerThread.java:65)
2018-11-20 15:34:46.678 12232-12699/? D/ClClient: Not sending keepalive.
Current connection state=STOPPED
2018-11-20 15:34:46.699 3418-3639/? D/DnsProxyListener: DNSDBG::dns addrinfo
af 2
2018-11-20 15:34:47.611 3787-8916/? D/SSRM:w: SIOP:: AP = 340, PST = 340
(W:15), BAT = 313, USB = 318, CHG = 346, CP = 333
2018-11-20 15:34:48.087 4959-4959/? D/io_stats: !@   8,0 r 5038254 276077112
w 1290028 18962328 d 122047 41066928 f 289127 307003 iot 2157260 1768288 th
307200 0 0 pt 0 inp 0 0 63174.392
2018-11-20 15:34:49.339 3787-3909/? D/SamsungAlarmManager: Expired : 4
2018-11-20 15:34:49.340 3787-3909/? I/SamsungAlarmManager: setLocked to
kernel - T:2 / 20181120T153509, SetElapsed=143783728, nowELAPSED=143763517
2018-11-20 15:34:49.341 3787-3909/? I/SamsungAlarmManager: setLocked to
kernel - T:3 / 20181120T153500, SetElapsed=143774177, nowELAPSED=143763518
2018-11-20 15:34:49.342 3787-3909/? V/SamsungAlarmManager: Sending to uid :
1000 listener=android.app.AlarmManager$ListenerWrapper@fa0b687
alarm=Alarm{5a2ea2f type 2 when 143763516 android}
2018-11-20 15:34:49.356 3787-4006/? D/SamsungAlarmManager: setExact Listener
(T:2/F:9/AC:false) 20181120T153525 - CU:1000/CP:3787
2018-11-20 15:34:49.501 13308-13308/? E/hw-IPCThreadState: binder thread
pool (1 threads) starved for 155 ms
2018-11-20 15:34:49.632 13308-13308/? E/hw-IPCThreadState: binder thread
pool (1 threads) starved for 129 ms
2018-11-20 15:34:49.649 3787-4015/? D/WifiP2pService: InactiveState143375
2018-11-20 15:34:49.650 3787-4015/? D/WifiP2pService: P2pEnabledState143375
2018-11-20 15:34:49.701 3787-6300/? D/SamsungAlarmManager: setExact Listener
(T:2/F:9/AC:false) 20181120T153450 - CU:1000/CP:3787
2018-11-20 15:34:49.702 3787-6300/? I/SamsungAlarmManager: setLocked to
kernel - T:2 / 20181120T153450, SetElapsed=143764875, nowELAPSED=143763879
2018-11-20 15:34:50.698 3787-3909/? D/SamsungAlarmManager: Expired : 4
2018-11-20 15:34:50.699 3787-3909/? I/SamsungAlarmManager: setLocked to
kernel - T:2 / 20181120T153509, SetElapsed=143783728, nowELAPSED=143764876
2018-11-20 15:34:50.700 3787-3909/? V/SamsungAlarmManager: Sending to uid :
1000 listener=android.app.AlarmManager$ListenerWrapper@44c69c5
alarm=Alarm{213f1a type 2 when 143764844 android}
2018-11-20 15:34:50.747 3787-6300/? D/SamsungAlarmManager: setExact Listener
(T:2/F:9/AC:false) 20181120T153452 - CU:1000/CP:3787
2018-11-20 15:34:50.747 3787-6300/? I/SamsungAlarmManager: setLocked to
kernel - T:2 / 20181120T153452, SetElapsed=143767063, nowELAPSED=143764924
2018-11-20 15:34:50.753 3787-6300/? D/DhcpClient: Renewed lease: IP address
172.20.237.2/24 Gateway 172.20.237.1  DNS servers: [ 172.20.237.1 ] Domains
DHCP server /172.20.237.1 Vendor info null lease 240 seconds
2018-11-20 15:34:50.754 3787-6300/? D/SamsungAlarmManager: Cancel Alarm
calling from uid:1000 pid :3787 /
listener:android.app.AlarmManager$ListenerWrapper@77dfa4b
2018-11-20 15:34:50.754 3787-4006/? D/SamsungAlarmManager: Cancel Alarm
calling from uid:1000 pid :3787 /
listener:android.app.AlarmManager$ListenerWrapper@912383c
2018-11-20 15:34:50.758 3787-6300/? I/SamsungAlarmManager: setLocked to
kernel - T:2 / 20181120T153500, SetElapsed=143774177, nowELAPSED=143764935
2018-11-20 15:34:50.769 3787-4015/? D/WifiP2pService: InactiveState143375
2018-11-20 15:34:50.769 3787-6300/? D/SamsungAlarmManager: setExact Listener
(T:2/F:9/AC:false) 20181120T153645 - CU:1000/CP:3787
2018-11-20 15:34:50.770 3787-4015/? D/WifiP2pService: P2pEnabledState143375

Also i just found this in LogCat:(Maybe the problem?)
2018-11-20 16:01:01.546 3384-3384/? E/audit: type=1400
audit(1542726061.545:3227): avc:  denied  { read } for  pid=16998
comm="Analytics-Norma" name="boot_id" dev="proc" ino=3571102
scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:object_r:proc:s0
tclass=file permissive=0 SEPF_SM-G955F_8.0.0_0017 audit_filtered
2018-11-20 16:01:01.549 16998-17153/? E/msgr.BootIdReader: Error reading
boot_id from procfs
java.io.FileNotFoundException: /proc/sys/kernel/random/boot_id (Permission
denied)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:200)
    at java.io.FileInputStream.<init>(FileInputStream.java:150)
    at java.io.FileInputStream.<init>(FileInputStream.java:103)
    at java.io.FileReader.<init>(FileReader.java:58)
    at X.2MN.a(:372675)
    at X.46q.a(:579709)
    at X.0Hi.A(Unknown Source:26)
    at X.0IH.a(:60614)
    at X.0IH.b(:60638)
    at X.41k.a(:569612)
    at X.1y8.a(:339223)
    at X.1rz.a(:330137)
    at X.0dC.a(:118033)
    at X.0d9.a(:117958)
    at X.0fP.d(:123017)
    at X.0fP.c(:122985)
    at X.0fP.handleMessage(:123035)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.os.HandlerThread.run(HandlerThread.java:65)
2018-11-20 16:01:02.739 16656-16708/? E/Fabric: Settings request failed.
+...
2018-11-20 16:04:25.446 16779-16855/? E/BtGatt.GattService: [GSIM LOG]:
gsimLogHandler, msg: MESSAGE_SCAN_STOP, appName: com.enbw.ev, scannerId: 7,
reportDelayMillis=0
2018-11-20 16:04:25.472 4777-5949/? E/ExecutionCriteria: Package unavailable
for task: com.tumblr/com.firebase.jobdispatcher.GooglePlayReceiver{u=0
tag="retryServiceTag"
trigger=window{start=3429s,end=3610s,earliest=-3609249s,latest=-3609069s}
requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=-3612679s
last_run=N/A jid=N/A status=PENDING retries=0
client_lib=FIREBASE_JOB_DISPATCHER-1}
2018-11-20 16:04:36.402 3787-4392/? E/Watchdog: !@Sync 2164 [2018-11-20
16:04:36.402]
2018-11-20 16:04:39.119 5626-5793/? E/ContactsProvider_EventLog: Flush
buffer to file cnt : 1 size : 1Kb duration : 2ms lastUpdatedAfter : 60132 ms
mFlush_time_threasold : 2000 mCurrentSize : 800
2018-11-20 16:04:55.481 4777-5949/? E/ExecutionCriteria: Package unavailable
for task: com.tumblr/com.firebase.jobdispatcher.GooglePlayReceiver{u=0
tag="retryServiceTag"
trigger=window{start=3429s,end=3610s,earliest=-3609279s,latest=-3609099s}
requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=-3612709s
last_run=N/A jid=N/A status=PENDING retries=0
client_lib=FIREBASE_JOB_DISPATCHER-1}
2018-11-20 16:04:55.551 16779-16855/? E/BtGatt.GattService: [GSIM LOG]:
gsimLogHandler, msg: MESSAGE_SCAN_START, appName: com.enbw.ev, scannerId: 7,
reportDelayMillis=0
2018-11-20 16:05:00.596 16779-16855/? E/BtGatt.GattService: [GSIM LOG]:
gsimLogHandler, msg: MESSAGE_SCAN_STOP, appName: com.enbw.ev, scannerId: 7,
reportDelayMillis=0


text:
Q: Akka dispatchers waiting for ever Recently, I've been developing different examples using Akka; for instance a playtool P2P model. For the evaluation, benchmarking, and understanding better, I tried to run the example using different types of dispatchers that Akka introduces.
The issue that I've been facing is that specifically using BalancingDispatcher with a thread-pool-executor (which by default should be for this type of dispatcher), the application tends to enter a total waiting state; is this a deadlock?! When I use jstack to get the dump for the threads in the application, the prominent observation is that all dispatcher threads are in TIMED_WAITING or WAITING state.
I am interested to know if this is a deadlock due to application design? And, more importantly, how can I get to debug or delve into dealing with such as issue?
The most helpful code snippets in this application can be:
The search method in each Node to ask peers for a search query and return results
  def search(query: String): Collection[String] = {
    var result: List[String] = List[String]()
    this.list().toList.foreach { q =>
        if (q.contains(query)) {
            result = query :: result
        }
    }
    implicit val timeout = Timeout(1 hour)
    // println("[" + this + "]'s peers: " + peers)
    for (p <- peers) {
      // println("asking [" + p + "] for [" + query + "]")
      val tmp: Future[Collection[String]] = ask(p.asInstanceOf[ActorRef], _search(query)).mapTo[Collection[String]]
      msgs.incrementAndGet()
      val l = Await.result(tmp, timeout.duration).asInstanceOf[Collection[String]]
      l.toList.foreach { q =>
        if (q.contains(query)) {
            result = q :: result
        }
      }
    }
    result.toList
  }

The snippet in the main section to evaluate a network of nodes:
import context.dispatcher
var start = System.currentTimeMillis
val futures = List.fill(querySize)(ask(root, _search("_" + r.nextInt(100))).mapTo[Collection[String]])
val results = Future.sequence(futures)
Await.ready(results, Timeout(1000 hour).duration)
var end = System.currentTimeMillis

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need to understand how events work with delegates in C# I cannot understand how delegates work with events in C#.
The form of the syntax is:
public event someNameDelegate someName;
control.someName += new control.someNameDelegate(methodName);
So how does it know what event (like mouse click etc) fires the method.
I'm totally missing how this works.
I understand that the delegate will call methodName but I don't understand for what event.
[Addittional Info]
In the 2 lines above if someName is ContentModified then the code compiles
In the 2 lines above if someName is Banana then the code does not compile.
However ContentModified is nowhere else in the code apart from the 2 line above:
So How does the compiler tell the difference?

A: For example, suppose you create a userControl and your control has a button, and when the button text changes, you define an event for it. That is, you see where the button text changes and there you define an event for it.
 public event TextChangedEventHandler ItemTextChanged;
 public delegate void TextChangedEventHandler(object Sender);

 private void btnContent_Click(object sender, RoutedEventArgs e)
 {
      if (ItemTextChanged != null)
      {
           ItemTextChanged(txtbChildBtn);
      }
 }

Same example with another name
public event ValueChangedEventHandler ItemValueChanged;
public delegate void ValueChangedEventHandler(object Sender);

private void btnContent_Click(object sender, RoutedEventArgs e)
{
   if (ItemValueChanged != null)
   {
       ItemValueChanged(sender);
   }
}

or FucosChanged button
 public event FucosEventHandler FucosChanged;
 public delegate void FucosEventHandler(object Sender, DependencyPropertyChangedEventArgs e);

 private void btnContent_FocusableChanged(object sender, , DependencyPropertyChangedEventArgs e)
 {
      if (FucosChanged != null)
      {
           FucosChanged(sender, e);
      }
 }


text:
Q: Loop through 2 arrays simultaneously in AppleScript Say I have:
set U = { "a", "b", "c" }
set V = { 1, 2, 3 }

How can I get "a1", "b2" and "c3"? (V is numbers not strings)

A: Does that the trick? :
set U to {"a", "b", "c"}
set V to {1, 2, 3}
set X to {}
repeat with i from 1 to number of items in U
    set end of X to ((item i of U) & (item i of V)) as text
end repeat

A: Almost the same code as Zero but it checks for the length of list U and V if one would be shorter than the other. The second difference is getting rid of the parentheses. When you join data in AppleScript and the first item of the join is a string then all the other values are automatically coerced into string objects.
set U to {"a", "b", "c"}
set V to {1, 2, 3}
set i to 1
set R to {}
repeat until i > (count of U) or i > (count of V)
    set end of R to item i of U & item i of V
    set i to i + 1
end repeat
return R

A: This scripts starts from your example, loops through the first array and adds the items of the second array using a counter. It then converts the new string to a list.
-- your example
set u to {"a", "b", "c"}
set v to {1, 2, 3}
-- prepare variables
set x to "" as text
set counter to 0
-- loop through the two arrays
repeat with c in u as text
    set counter to counter + 1
    set x to x & (c & item counter of v) & ","
end repeat
-- remove last comma
set len to the length of x
set x to characters 1 thru (len - 1) of x as text
-- convert string x to list x
set AppleScript's text item delimiters to ","
set x to every text item of x
-- display result
return x

This script produces {"a1","b2","c3"}

A: Here is another approach...
set U to {"a", "b", "c"}
set V to {1, 2, 3}
set text item delimiters to ","
set {U, V} to {U as text, V as text}
set text item delimiters to {return & space, return}
set X to text items 1 thru -2 of (do shell script "echo {" & U & "}{" & V & "}'\\n'")
set text item delimiters to ""


text:
Q: WebDAV: Mini-Redirector client - got own (read-only?) cookie-storage? Imagine this szenario: Web-Server and WebDAV-Server using same cookie-domain.
WebServer sets some authentication cookie.
When starting an WebDAV-Session via special-link on the Web-Server,
WIN7 Microsoft Mini-redirector can read the cookie
set by Web-Server fine and starts an WebDAV-Session
on WebDAV-server using this cookie.
But after the first DAV-call, the cookie seems to be read-only
to both DAV-Server and mini-redirector.

*

*DAV-Server cannot update this cookie

*DAV-Server cannot delete (expiry in the past) the cookie

*Mini-redirector keeps sending the old values
(even, if Web-Server has updated its values in between)

Anybody got informations

*

*where mini-redirector stores its cookies

*how to avoid this behaviour?

Thanks, Karl

A: I had the similar problem. On the client you should know when the server is updating the cookie. When you know server may reset the cookie, call wnetcancelconnection2 and clear of the the existing webdav connection and call wnetaddconnection2 to create the connection again. But give some time between these two calls atleast a minute, i guess it takes a while to clean up the existing cache.
In my application when i knew the server is going down or my application exiting or going to ask for new session, i call the wnetcancelconnection2 and wnetaddconnection2. It worked for me. Hope this helps.


text:
Q: UITableView accessoryView position was strange The UITableView accessaoryView of my app work fine on below iOS 9.0, It's like this
The same project run on iOS 9.0, It's like this
There have a offset, the detail code about accessoryView like this:
    CGRect abc = CGRectMake(0, 0, cell.frame.size.width/2,    supportMininumHeight);
    UIView *customView = [self addControlFromArrayToAccessory :controlContent:indexPath:abc];
    cell.accessoryView =  customView;
    cell.accessoryView.backgroundColor = [UIColor redColor];

Please give some advice, Thx.

A: The easy way to do this is make your custom cell in Interface builder with Auto layout, and load that cell in your tableView. I don't think custom accessory view is the right choose to do in your case.


text:
Q: scraping websites and Retrieving data or downloade existing website files I want to scrape specific websites.For example in that website(https://www.accessdata.fda.gov/scripts/cder/cliil/index.cfm) in index page when you select a data field(you can choose country) and in Country keyword you can choose USA it navigate search page( https://www.accessdata.fda.gov/scripts/cder/cliil/dsp_Search.cfm ) I want to download search page.I want to scrape it.But there is no query string.How can I do this?
Are there any solution that I can post form in index with parameters?
Edited:
I use webrequest but it does not show page with data.Are my parameters is false?
here is my code
   System.Net.WebRequest request1 = System.Net.WebRequest.Create("https://www.accessdata.fda.gov/scripts/cder/cliil/dsp_Search.cfm");
            var Deger1 = "{'DataField':'COUNTRY','COUNTRY':'USA','Keywords':'','Submit':'Submit'}";
            request1.Method = "POST";

              byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(Deger1);
            request1.ContentType = "text/xml";
            request1.ContentLength = byteArray.Length;
            Stream dataStream = request1.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            System.Net.WebResponse response = request1.GetResponse();
            Console.WriteLine(((System.Net.HttpWebResponse)response).StatusDescription);
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream, System.Text.Encoding.UTF8, true);
            string responseFromServer = reader.ReadToEnd();

            reader.Close();
            dataStream.Close();
            response.Close();

A: I don't know how to make http requests with #c but to get your requirement fulfilled I think the below information is enough.
1. FormData={
    'DataField':'COUNTRY','COUNTRY':'USA','Keywords':'','Submit':'Submit'
}
2. You should make a post request with the below url along with the above form data.

"https://www.accessdata.fda.gov/scripts/cder/cliil/dsp_Search.cfm"

I've tested it in other language and found it working.
Btw, I've got above information by satisfying the below parameter in the search field using the following url:
url = "https://www.accessdata.fda.gov/scripts/cder/cliil/index.cfm"

Search Fields:

1. Country
2. USA


text:
Q: TextEdit keeps changing file extensions when I save Is there a way to prevent TextEdit from changing the file extension on a file that I open it with, or at least prompt me?
Example:

*

*Open somefilename.yyy

*Save becomes somefilename.rtf

I have looked through TextEdit preferences without finding a setting.

A: Try with making the file to an Plain text file. It's under the Format tab (not in preferences).
Have you taken a look at this?
Apple support page


text:
Q: TypeORM with default null value for a timestamp type column generates infinite migrations I have the following column definition in an entity, within a NestJs project using TypeORM:
@CreateDateColumn({
    nullable: true,
    type: 'timestamp',
    default: () => 'NULL',
    })
public succeededAt?: Date;

This generates a migration that looks correct:
export class migration123 implements MigrationInterface {
   name = 'migration123';

   public async up(queryRunner: QueryRunner): Promise\<void\> {
      await queryRunner.query(
         `CREATE TABLE [...], "succeededAt" TIMESTAMP DEFAULT NULL, [...]`
   );
   \[...\]
}

But after running the migration, if I try to generate a new migration with TypeORM CLI, it still detects some differences:
[...]
public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`ALTER TABLE "mercadopago_payment_request" ALTER COLUMN "succeededAt" SET DEFAULT null`);
[...]

I'm guessing that Postgres detects the default value as the global default anyways (every column has null as default if not stated otherwise) and doesn't add any special rule for it. Then TypeORM doesn't see the rule and tries to add it... again.
Any ideas on how to prevent this?

I tried removing the default value:
@CreateDateColumn({
    nullable: true,
    type: 'timestamp',
    })
public succeededAt?: Date;

But that generates a migration with a default value as now():
export class migration123 implements MigrationInterface {
   name = 'migration123';

   public async up(queryRunner: QueryRunner): Promise\<void\> {
      await queryRunner.query(
         `CREATE TABLE [...], "succeededAt" TIMESTAMP DEFAULT now(), [...]`
   );
   \[...\]
}

The reason why I'm trying to state specifically null as the default value.

A: My problem was due to the @CreateDateColumn decorator.
I was able to achieve the correct behavior with a regular date column:
  @Column({ nullable: true, type: 'timestamp' })
  @IsDate()
  public succeededAt: Date | null;


text:
Q: xml parsing using 2 tables I written a function to save the data in xml file to database.I am using two models ,see the below.
models.py
class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)
    email = models.EmailField()
    age = models.IntegerField()

class Book(models.Model):
    book_id=models.AutoField(primary_key=True,unique=True)
    book_name=models.CharField(max_length=30)
    publisher_name=models.CharField(max_length=40)
    author=models.ForeignKey(Author)

my .xml file is
 <book>
    <book_id>101</book_id>
    <book_name>Python</book_name>
    <publisher_name>Maxwell</publisher_name>
    <author_id>1002</author_id>
    <first_name>John</first_name>
    <last_name>Dezosa</last_name>
    <email>john@gmail.com</email>
    <age>34</age>
  </book>
  <book>
    <book_id>102</book_id>
    <book_name>Django</book_name>
    <publisher_name>Technical</publisher_name>
    <author_id>1003</author_id>
    <first_name>Josep</first_name>
    <last_name>Raj</last_name>
    <email>joseph@gmail.com</email>
    <age>29</age>
  </book>

What i required is to save the xml data into appropriate fields.From google i learned about paring using single table,here i don't know how to create the object for the "author" table.
I tried with the below code
for books in xmlDocTree.iter('book'):
            book_id = books[0].text
            book_name = books[1].text
            publisher_name = books[2].text
            author_id = books[3].text
            books.first_name = books[0].text
            books.last_name = books[1].text
            books.email = books[2].text
            books.age = books[3].text

getting the following traceback
AttributeError at /addxml/
first_name
Request Method: POST
Request URL:    http://localhost:8000/addxml/
Django Version: 1.3.7
Exception Type: AttributeError
Exception Value:
first_name
Exception Location: /root/Samples/DemoApp/DemoApp/views.py in addxml, line 106

Thanks

A: Your books model does not have a first_name
You need to create an author object, and then save the author as a foreign key to the book model.
for books in xmlDocTree.iter('book'):
    book_id = books[0].text
    book_name = books[1].text
    publisher_name = books[2].text

    author_id = books[3].text
    first_name = books[4].text
    last_name = books[5].text
    email = books[6].text
    age = books[7].text

    author, _ = Author.objects.get_or_create(id=author_id, defaults={'first_name': first_name, 'last_name': last_name, 'email': email, 'age': age})
    author.save()

    book, - =  Book.objects.get_or_create(book_id=book_id, defaults={'book_name': book_name, 'published_name': publisher_name, 'author': author)})
    book.save()

You might need another column in your Author model called author_id


text:
Q: DotNetNuke modal popup dialog boxes get wrong styling I have an old DNN site that has been upgraded several times, from 5.6.2, through 6.2.5, 6.2.8, 7.0.5 and now is on 7.0.6. Most everything works well, but the popup modal dialog boxes (e.g. the Settings dialog box) look strange. specifically, the size is very narrow for my browser window. If I just click on the resize control on the lower right, it pops up to a normal size. Also, the close and maximize controls on the upper right are cropped, i.e. overflow is set to hidden. I can see from the Chrome Developer Tools that at least the 'overflow' css style is being set to hidden in the element.style style rule. I am not sure where this is coming from. I suspect that somehow this is due to the skin being an old, non-responsive skin, which I don't know much about. Can someone point me in the right direction as to how to get these looking right? It's kind of annoying when I am working on the site.
Thanks.
EDIT: Added the screen shot. I have circled the cropped controls in the upper right, and you can see that the dialog box is only about 1/3 the width it should be. Thanks for your time in helping me on this issue.


text:
Q: estimate missing edge weight (travel duration) in a complete graph I have a complete (fully connected) graph where each node is a geographic location. The edge weights describe the time it takes to walk from one location to the other (along some road network). Now I add a new node (location) into the graph. Because querying the walking duration from the new node to all the other nodes is expensive, I only want to query a subset.
How can I estimate the walking duration from the new node to the remaining locations?
Given that I have the walking duration between all existing nodes and between the new node and a subset of the existing nodes it should be possible to come up with a good estimation for the remaining connections.

A: Store all locations in a data structure that makes finding neighbors efficient
      ( quadtree https://en.wikipedia.org/wiki/Quadtree )

Find neighbors of new location.

Query walking distance from new location and neighbours

Loop over all other locations

   Find neighbour closest to other location

   Estimate distance from new location to other by sum of
          distance from new to neighbor and neighbou to other.

I have implemented a quadtree search for neighbours of a point and compared the performance with a simple search through a vector of points.   If there are less than 100 points to search, the performances are similar, at less than a microsecond for each search. For more than 100 points, the advantage of a quadtree becomes significant.

Here is the code.


text:
Q: A Scheme function to compose other functions I wish to create a function that can compose two functions into one. Given g and f, it should create a function h provides the output of f as input to g. Here was my result:
(define (compose g f)
    (lambda (.args)
        (g (apply f (if (atom? .args) (list .args) .args)))))

The following snippet works with compose.
(display ((compose add1 add1) 3))

However, I cannot figure out why the example below won't work. I provided the error message that I got below, and I am using Chez Scheme 9.5.2. The error here probably has to do with the variadic nature of compose, but that's just an idea. Does anyone know why my second test isn't working as expected?
(define (reduce f lst seed)
    (if (null? lst) seed
        (f (car lst) (reduce f (cdr lst) seed))))

(define product-of-incremented-list
    (compose
        (lambda (lst) (reduce * lst 1))
        (lambda (lst) (map add1 lst))))

(display (product-of-incremented-list '(3 4 5)))
; I was expecting 120, because (3 4 5) -> (4 5 6) and (4 5 6) -> 120
; I'm getting an error instead:
; Exception: incorrect number of arguments to #<procedure at compose.scm:285>

A: You are trying to use .args to mean "a list of arguments", perhaps by analogy with (lambda (x . more) ...), but this is not correct. .args is just a symbol like any other, so you have written a function that takes one argument named .args. Then when you discover your argument is a list, you (apply f '(3 4 5)). But the lambda you are using for f does not expect three arguments, it expects a single list argument. Thus the error.
Instead, the way to say "a list of arguments" is
(lambda args
  ...)

In general, what you write after the lambda is how to treat the input argument list. If you put a list like (x y) there, then the argument list is expected to be two components, x and y. For (x . more), the first element is named x, and then the rest of the list is named more. If you just want the list as-is, you simply give it a name: here, args.
Your second issue is this checking of whether the arguments are a list or an atom. This is silly: you can be certain it will always be a list, because you do not break down the input parameters. So,
(define (compose f g)
  (lambda args
    (f (apply g args))))


text:
Q: Shell Script for checking processes We have around 300 servers (AIX, HP-UX, Suse Linux, RHEL, Solaris) in the environment, which makes it very difficult to check whether a process called syslog is running in these servers or not, individually.
Hence, I am developing a shell script which should ssh in as root from my Linux open client Lenovo Thinkpad and execute the ps -ef command and return the ouput in a text file.
for i in `cat /tmp/serverlist |awk '{ print $1 }'`
do
    ssh -l root $i `bash -x ./sysloginfo.sh` >>syslogdata.txt
done

And the script file sysloginfo.sh contains the following:
for i in `ps -ef |grep -i syslog |grep -v pts |grep -v super |awk '{ print $9 }'`
do
    echo "`uname -n`" $i "\n"
done

Now when I execute the command, it says the following for all the servers one by one and returns back my $ prompt of my Linux Laptop Terminal.
   bash: xxxxxx.xxxx.com: command not found
   ++ ps -ef
   ++ grep -i syslog
   ++ grep -v pts
   ++ grep -v super
   ++ awk '{ print $9 }'
   + for i in '`ps -ef |grep -i syslog |grep -v pts |grep -v super |awk '\''{ print $9 }'\''`'
   ++ uname -n
   + echo oc7057073017.ibm.com -i '\n'
   + for i in '`ps -ef |grep -i syslog |grep -v pts |grep -v super |awk '\''{ print $9 }'\''`'
   ++ uname -n
   + echo xxxxxx.xxxx.com: --start '\n'

A: Why do all of that ?
If you have snmp installed - use SNMP to query all remote hosts without any SSH  I will try to help out and point you in the right direction:
snmpwalk -v2c -c public localhost 1.3.6.1.2|grep -i syslog
HOST-RESOURCES-MIB::hrSWRunName.1171 = STRING: "rsyslogd"
HOST-RESOURCES-MIB::hrSWRunPath.1171 = STRING: "/sbin/rsyslogd"
HOST-RESOURCES-MIB::hrSWRunParameters.1171 = STRING: "-i /var/run/syslogd.pid -c 5"
HOST-RESOURCES-MIB::hrSWRunParameters.15145 = STRING: "-i syslog"
HOST-RESOURCES-MIB::hrSWInstalledName.392 = STRING: "rsyslog-5.8.10-6.el6"

These are all the stuff related to snmp on this machine
Now running this specific set of snmpwalk commands I can pin point the pid on this local machine but changing localhost to a remote host so long as the password is public and snmp connections are allowed from my host then this should work
snmpwalk -v2c -c public -Oq localhost HOST-RESOURCES-MIB::hrSWRunName|grep syslog
HOST-RESOURCES-MIB::hrSWRunName.1171 "rsyslogd"

 snmpwalk -v2c -c public -Oq localhost HOST-RESOURCES-MIB::hrSWRunName|grep syslog|awk -F"hrSWRunName." '{print $2}'|awk -F" " '{print $1}'
1171

The pid is 1171
ps auwx|grep 1171
root      1171  0.0  0.0 249276  1820 ?        Sl   Nov20   0:03 /sbin/rsyslogd -i /var/run/syslogd.pid -c 5

A: Finally, found out a way to pull out the process in a text file. Please refer to the code below.
    for i in `cat /tmp/serverlist`
    do
    echo $i:`ssh -l root $i "uname -n;ps -eo comm | grep -i syslog"` >> sysloginfo.txt
    done

And that gives an output as,
    xx.xx.xx.xx: xxxxxxx101 syslogd
    xx.xx.xx.xx: xxxxxxx102 syslog-ng
    xx.xx.xx.xx: xxxxxxx103
    xx.xx.xx.xx: xxxxxxx104 syslog-ng syslog-ng


text:
Q: Winforms DataGridViewColumn with Image and Text I am asking this question here as I could not find any conclusive results thru Google.  HOw would it be possible to include an image and text in the same column in a Winforms datagridview?
I have the following code handling the CellPainting event, but it does not work too well if the user adjusts the height of the row.
private void dgvTasks_CellPainting( object sender, DataGridViewCellPaintingEventArgs e ) {
    if (e.RowIndex >= 0 && e.ColumnIndex == 7) {
        e.Graphics.DrawImage( Properties.Resources.task, e.CellBounds.X, e.CellBounds.Y, 16, 16 );
    }
    e.Handled = true;
}

Column 7 is currently databound to a string type.  As mentioned, the problem with the above code, is that when the user resizes the row height, the text automatically vertically aligns to the center, but the image stays put in the top-left.
I started creating my own DataGridViewImageTextColumn (and Cell) class that inherits from DataGridViewColumn/Cell, but dont know how to take this idea further.  Is it any way possible for someone to help me out on this one by giving me a nudge in the right direction?
Forever grateful!
Cheers!

A: nevermind...its too much of a bother.  I just disabled row-resizing


text:
Q: Flutter get all map entries where map value matches condition I am trying to find all elements in a Map where a condition is met.
My widget receives final Map<String, Item> itemMap; from a Parent Widget
I have a function that gets called when a Dropdown element is selected
  handleTypeSelect(String? selectedType) {
    var newList = widget.itemMap.entries
        .where((element) => element.value.type == selectedType)
        .toList();

    var foo = Map<String, Item>.fromIterable(newList);
    var bar = Map<String, Item>.fromEntries(newList);
    print('newlist ${bar}');

  }

All I need is to create a new Map with the same structure Map<String, Item> that only contains the map entries where Item.type matched the type selected from the dropdown. I tried several things but always ended up with different errors like: Expected a value of type 'String', but got one of type 'MapEntry<String, Item>' or some Map of entries that I am unable to access.
Item Model is probably not relevant but just in case it helps.
  final String name;
  final String id;
  final String type;
  final int circulation;
  final String description;
  final String imageLink;
  final int marketValue;

A: Try the following:
Map<int, bool> example = {1: true, 2: false};
var trueEntries = example.entries.where((MapEntry e) => e.value);
print(Map.fromEntries(trueEntries));

Which yields {1: true}.
In your code it would probably be something like this:
  handleTypeSelect(String? selectedType) {
    var filteredEntries = widget.itemMap.entries
        .where((MapEntry e) => e.value.type == selectedType);
    var bar = Map.fromEntries(newList);
  }


text:
Q: Shape of passed values is (12, 1), indices imply (1, 12) I tried to create a table.
p_data = ["20", "30", "40", "50", "60", "70", "80", "90",
          "100", "110", "120", "130"];
p_columns = ["2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017",
             "2018", "2019", "2020", "2021"]

data_frame = pd.DataFrame(columns=p_columns , index=["house"], data=p_data )

I got an error:
Shape of passed values is (12, 1), indices imply (1, 12)
I want my table looks like this:
image of what i want
Someone can help me please?

A: You need to use [data] as the input must be 2D if you specify the index/columns:
data_frame = pd.DataFrame(columns=p_data, index="house", data=[p_data])

output:
       20  30  40  50  60  70  80  90  100  110  120  130
house  20  30  40  50  60  70  80  90  100  110  120  130

Also I imagine you rather want p_columns as columns:
data_frame = pd.DataFrame(columns=p_columns, index="house", data=[p_data])

output:
      2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
house   20   30   40   50   60   70   80   90  100  110  120  130


text:
Q: Meshgraph of functions - Matlab Could someone please help me with this task; I was asked this question:

And I tried to solve it this way:
    syms x y

    [x,y]=meshgrid(0:0.-1:1);

    a=1-(exp(-x/sqrt(2))/2+exp(-x/sqrt(2)));

    b=exp(-x/sqrt(2))/((2+exp(-x/sqrt(2)))^2);

    c=((exp(-x/sqrt(2))*(exp(-x/sqrt(2))-2)))./4*((2+exp(-x/sqrt(2)))^3);

    d=(exp(-x/sqrt(2))*(((exp(-x/sqrt(2)))^2)-8*(exp(-x/sqrt(2)))+4))./24*((2+exp(-x/sqrt(2)))^4);

    z=a+(y*b)+(c*y^2)+(d*y^3);

    mesh(x,y,z);

but for some reason the graph won't plot, what seems to be the issue here?


text:
Q: How to order by count or some conditions from other table I've a project that create a q&a website.
I want to show questions by these conditions.
 1. Show by the latest question, yeah i know just order by created desc.
 2. Show and sort questions by most answers.
 3. Show and sort questions by most voted. (like most answers) example.
 4. Show questions where unanswered. example
And here is my tables structure in database.
TABLE question
COLUMNS
q_id (primary key)
userid
title
content
created

TABLE answer
COLUMNS
a_id (primary key)
userid
q_id
content
created

TABLE vote
COLUMNS
userid
q_id
created

And each tables it can have a million of rows.
For my 4 questions above I'm trying these SQL(s).
1 Show by the latest question. (solved)
select * from question order by created desc

2 Show and sort by most answers. (seems to slow)
SELECT q.*, COUNT(a.id) as answerCount
FROM question q
LEFT JOIN answer a
        ON (q.q_id = a.q_id)
ORDER BY answerCount DESC

3 Show and sort by most voted. (seems to slow).
SELECT q.*, COUNT(v.id) as voteCount
FROM question q
LEFT JOIN vote v
        ON (q.q_id = v.q_id)
ORDER BY voteCount DESC

4 Show questions where unanswered. (seems to slow)
SELECT q.*
    FROM question q
    LEFT JOIN answer a
        ON p.q_id = a.q_id
    WHERE a.q_id IS NULL ORDER BY q.created DESC

Note: If i use INNER JOIN the rows where count = 0 will not be selected.
As I think, The other websites are commonly have field to count answers and votes already? To make it fast and should i change to this or they have some algorithm which no need to count answer and vote in question table?
TABLE question
COLUMNS
q_id (primary key)
userid
title
content
created
answer_count
votes_count

Help or advice will be truly appreciated.

A: You can try re-writing your queries, but as MySQL is known for preferring joins over more straight-forward ways, they are not likely to be faster. Here are some queries you can try:
Show and sort by most answers. Use GROUP BY and COUNT(*) to make it plain what you do.
SELECT q.*, COUNT(*) as answerCount
FROM question q
LEFT JOIN answer a ON a.q_id = q.q_id
GROUP BY q.q_id
ORDER BY answerCount DESC;

Show and sort by most answers. Count in a sub-query.
SELECT q.*, (select count(*) from answers a where a.q_id = q.q_id) as answerCount
FROM question q
ORDER BY answerCount DESC;

Show and sort by most answers. Count in a derived table query.
SELECT q.*, a.answerCount
FROM question q
LEFT JOIN (select q_id, count(*) as answerCount from answers group by q_id) a
  ON a.q_id = q.q_id
ORDER BY a.answerCount DESC;

Show questions where unanswered. I.e. where no answer EXISTS:
SELECT q.*
FROM question q
WHERE NOT EXISTS (select * from answer a where a.q_id = q.q_id)
ORDER BY q.created DESC;

However, as mentioned, these more straight-forward queries are not necessarily faster. Well, you can give them a try anyhow.
So if re-writing the queries doesn't speed things up, then, yes you can add an answer and a vote count to your question table. This is certainly redundant, but if requirements make such a step necessary, then take it.


text:
Q: Buying an IP address from Morocco and assigning it to an AWS server? Due to some restrictions of a service, I can only login from a Morrocan IP address.
Is it possible to get a Morrocan IP address and assign it to a VPN proxy that I created on AWS using an elastic IP adresss?

A: You can create an EC2 VPN router and connect to this. (Using, for example OpenVPN). You will need to configure it for NAT, forwarding and advertise/configure the route, but this is all quite doable. You might also need to do MTU clamping.
Unfortunately, I dont believe AWS currently have a DC in Morocco, so you may need to navigate that.  An alternative might be to use another company that provides VPS/Virtual machines in Morocco.


text:
Q: Equality involving combinatorics Does anyone know of any relationship involving sums and factorials that can help me prove this identity?
I want to prove that for $j, k \in \mathbb{N}$
$$\sum_{i=1}^{2j+1}\frac{(-1)^{i+1}}{(-i+2j+1)!(i+2k)!}= \frac{1}{(2k)!(2j)!(2k+2j+1)}.$$
My attempt was to separate the positive and negative terms and try to write as binomials, as follows
\begin{equation}
\begin{split}
\sum_{i=2}^{2j+1}\frac{(-1)^{i+1}}{(-i+2j+1)!(i+2k)!}&= \sum_{i=1}^{j}\frac{1}{(2k+2i+1)!(2j-2i)! }- \sum_{i=1}^{j}\frac{1}{(2k+2i)!(2j+1-2i)! }\\
&= \frac{1}{(2k+2j+1)!}\left[ \sum_{i=1}^{j}\binom{2k+2j+1}{2k+2i+1} - \binom{2k+2j+1}{2k+2i} \right].
\end{split}
\end{equation}
The first term I left to be added at the end. This way, the amount of positive and negative factors is the same and i can join in the same sum. From here I have no idea how to continue.

A: Let the quantity you want to evaluate be $X$. Multiplying, we have
$$(2k+2j+1)!X=\sum_{i=1}^{2j+1}\frac{(-1)^{i+1}(2k+2j+1)!}{(-i+2j+1)!(i+2k)!}=\sum_{i=1}^{2j+1}(-1)^{i+1}\binom{2k+2j+1}{2j+1-i}.$$
We want to show that this is $\binom{2k+2j}{2j}$.
Let
$$S_{n,m}=\sum_{i=0}^m(-1)^\ell\binom{n}{\ell},$$
so that
$$(2k+2j+1)!X=\sum_{i=0}^{2j}(-1)^\ell\binom{2k+2j+1}{\ell}=S_{2k+2j+1,2j};$$
we will show that
$$S_{n,m}=(-1)^m\binom{n-1}m.$$
We can show this by induction on $m$. For $m=0$, the sum consists only of the summand $1$, so it's true there. Now, assume it's true for $m$; then
$$S_{n,m+1}=S_{n,m}+(-1)^{m+1}\binom n{m+1}=(-1)^{m+1}\left(\binom n{m+1}-\binom{n-1}m\right)=(-1)^{m+1}\binom{n-1}{m+1},$$
as desired.

A: We seek to verify that
$$\sum_{p=1}^{2j+1} (-1)^{p+1} {2j+2k+1\choose 2j+1-p}
= {2j+2k\choose 2j}.$$
As there are no odd multiples of $j$ and $k$ we may alternatively prove
the more general
$$\sum_{p=1}^{j+1} (-1)^{p+1} {j+k+1\choose j+1-p}
= {j+k\choose j}.$$
which includes OP's question as a special case with $j$ and $k$ being
even. The LHS is
$$[z^{j+1}] (1+z)^{j+k+1} \sum_{p=1}^{j+1} (-1)^{p+1} z^p.$$
Now here the coefficient etractor enforces the upper range of the sum
and we may write
$$[z^{j+1}] (1+z)^{j+k+1} \sum_{p\ge 1} (-1)^{p+1} z^p
= [z^{j+1}] (1+z)^{j+k+1} z \sum_{p\ge 0} (-1)^p z^p
\\ = [z^j] (1+z)^{j+k+1} \frac{1}{1+z}
= [z^j] (1+z)^{j+k} = {j+k\choose j}$$
as claimed.


text:
Q: Apple Mac IPhoto clear trash I've read some stuff on here about emptying the trash can in iPhoto but it keeps locking up .. 35 thousand images in trash but will not go .. any help appreciated.
With a standard windows pc I can run winderstat and go in the back end if stuck.
Is there a way on a Mac ?


text:
Q: How can I manage to not lose the value of my variable in a function? I've been trying to return a certain list of variables, 'params' in my code. If it matches certain criteria the params become something about color and name of a person etc.
However, whenever it matches the first ones ( the third IF statement where the color gets red) I tell it to return the list, but it doesn't do that. It instead executes the last few lines of the the code and the params variable seems undefined by then
When I console.log the params its empty at the bottom of the block, but right after i assigt them it doesn't
log outcome:
params Object {
  "backgroundColor": "red",
  "occupant": "Mauro",
  "prep": "OCCUPIED",
  "timeFree": "until 15:0",
}
laatste Object {}

. So that is my first issue. Am I getting it wrong about the return statement? shouldn't that end the method and return the list? And if I'm wrong, how do I get the desired outcome? ( when matching first three criteria, return the list only )
timeCalc(){
  var params = {}
  var curTime = new Date();
  this.state.events.find( event => {
    var temp = new Date(event.start)
    var end = new Date(event.end)

    if(temp.getFullYear() === curTime.getFullYear() &&
    temp.getMonth() === curTime.getMonth() &&
    temp.getDay() === curTime.getDay() &&
    temp.getHours() >= curTime.getHours()

    ){
      if( temp.getHours() == curTime.getHours()){
        if( temp.getMinutes() == curTime.getMinutes()){
          params = {
            prep: 'OCCUPIED',
            backgroundColor: 'red',
            occupant: event.title,
            timeFree: "until "+end.getUTCHours()+":"+end.getMinutes()
          }
          console.log('params',params)

          return params;
        }}
         else{
            var params = {
              prep: 'FREE',
              timeFree: "until "+temp.getUTCHours()+":"+temp.getMinutes(),
              backgroundColor: '#009DDC',
              occupant: null

            }
            return params;
          }
        }
    }
    else{
      var params = {
        prep: 'TEST',
        timeFree: "nooit",
        backgroundColor: "yellow",
        occupant: "Niemand"
      }
      return params;
    }
    }
  )
  console.log("laatste",params)
  return params;

}

And secondly:
The params somehow make it to this part of my code, where all of the logs tell me the variables are undefined, yet the setstate below that  takes the backgroundColor variable, while the other 3 don't seem to. Why is only the background color being set and not the other 3?
  var params = this.timeCalc();
  console.log(params.prep);
  console.log(params.timeFree);
  console.log(params.backgroundColor);
  console.log(params.occupant);

undefined
undefined
undefined
undefined

  this.setState({

    prep: params.prep,
    timeFree: params.timeFree,
    backgroundColor: params.backgroundColor,
    occupant: params.occupant

  })

I understand this is chaotic, I tried my best in putting this up as clearly as I can and I hope you understand and might be able to help me out. Please ask me anything or give advice on how to better voice this. Thanks in advance

A: From MDN:

The find() method returns the value of the first element in the provided array that satisfies the provided testing function.

The way you're using .find() is inefficient and is causing issues. Instead of doing all of the logic in the find callback, use it to fetch the correct event and then transform it into params:
timeCalc() {
  let params = {};
  let curTime = new Date(), start, end;

  let event = this.state.events.find(e => {
    start = new Date(e.start);
    end = new Date(e.end);

    return start.getFullYear() === curTime.getFullYear() &&
    start.getMonth() === curTime.getMonth() &&
    start.getDay() === curTime.getDay() &&
    start.getHours() >= curTime.getHours();
  });

  if(start.getHours() != curTime.getHours()) {
    return {
      prep: 'FREE',
      timeFree: "until "+start.getUTCHours()+":"+start.getMinutes(),
      backgroundColor: '#009DDC',
      occupant: null
    };
  } else if(start.getHours() == curTime.getHours() && start.getMinutes() == curTime.getMinutes()) {
    return {
      prep: 'OCCUPIED',
      backgroundColor: 'red',
      occupant: event.title,
      timeFree: "until "+end.getUTCHours()+":"+end.getMinutes()
    };
  }
}


text:
Q: Angular json to interface I have created model(by interface) for my json response:
export interface Test {
    id: number;
    name: string;
}

and I have variable for data:
  public test: Test;

But when I get json response with more parameters like last_name which is not in interface I still can use it in code. How can I cast this json response to match only my model?
I tried  assertion but It's not working, I still have access to all other properties.

A: Interfaces are known only at compile time. You can use classes instead and by declaring properties in constructor they will be known at runtime:
class Test {
  constructor(
    public id: number,
    public name: string
  ){}
}

Then you can create function that will return an instance of a given class and fill it with data:
function cast<T>(data: any, model: new (...args: any[]) => T ): T {
  const classInstance = new model();
  const classProps = Object.getOwnPropertyNames(classInstance);

  classProps.forEach(prop => classInstance[prop] = data[prop]);
  return classInstance;
}

You can use this function to map received data to given model:
this.http.get<Test>('someUrl').map(res => cast(res, Test))

A:
I couldn't do it for an Interface, but using a class to achieve what you want to do, is possible.

Angular [Typescript]
class Award {
  name = "";
  category = "";
}

this.httpClient.get<Awards>("./assets/configs/award.json").subscribe(($:Award) => {
  // Pass an instance of the Class, you wish to receive your response as
  console.log(this.takeWhatIsNecessary(new Award(), $));
});

// Breadth First Search
// This function will go through keys, in any depth, and copy
// property values from corresponding keys from Response
// Into the target value
// And returns the target
takeWhatIsNecessary(target, response) {
const stack = [];

if (!response || !target) {
  return response;
}

stack.push({
  r: response,
  t: target
});

while (stack.length > 0) {
   const obj = stack.shift();

   for (const key in obj.t) {
     if (obj.t.hasOwnProperty(key) && obj.r.hasOwnProperty(key)) {
       if (typeof obj.t[key] === "object") {
         stack.push({
           t: obj.t[key],
           r: obj.r[key]
         });
       }
       obj.t[key] = obj.r[key];
     }
   }
 }
 return target;
}

Javascript Sample

var uglyJSON = '{"name":"Test Name","category":"Test Category","author":"Do Not","appendix":"Read This","important":{"take_this":"Awesome","not_this":"Wow"}}';

var uglyResponse = JSON.parse(uglyJSON);

var myCustomClassObj = {
  name: "",
  category: "",
  important: {
    take_this: ""
  }
};

console.log(takeWhatIsNecessary(myCustomClassObj, uglyResponse));

// Breadth First Search
function takeWhatIsNecessary(target, response) {
  var stack = [];

  if (!response || !target) {
    return response;
  }

  stack.push({
    r: response,
    t: target
  });

  while (stack.length > 0) {
    var obj = stack.shift();

    for (var key in obj.t) {
      if (obj.t.hasOwnProperty(key) && obj.r.hasOwnProperty(key)) {
        if (typeof obj.t[key] === "object") {
          stack.push({
            t: obj.t[key],
            r: obj.r[key]
          });
          continue;
        }
        obj.t[key] = obj.r[key];
      }
    }
  }

  return target;
}


text:
Q: How to select children using the children() function? I can't understand how to use children() function in jQuery, I have this code:
jQuery('#nav li.over a.level-top').css({'padding-bottom': '26px'});

I want to replace #nav li.over with var navLiOver = jQuery('#nav li.over');
This doesn't work:
navLiOver.children('a.level-top').css({'padding-bottom': '26px'});

Can anybody explain to me how the children() function works?
HTML code:

        Link1

1

2

3

A: The equivalent of $('#nav li.over a.level-top') is navLiOver.find('a.level-top')
For your padding-bottom code to have any effect, though, you need to make sure that the anchor has a display mode that allows padding, such as block or inline-block. This is true regardless of how you find the element.
Demo

A: you can use find()
navLiOver.find('a.level-top');

The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

whereas find()

Gets all  the descendants of each element in the current set of matched elements

A: The difference between
jQuery('#nav li.over a.level-top')

and
jQuery('#nav li.over').children('a.level-top')

is that the latter only selects the immediate children. For the behaviour you are expecting, use find() instead.

A: Your code work's just fine
navLiOver.children('a.level-top')

The thing that doesn't work is .css({'padding-bottom': '26px'});
Fiddle
the a tag is inline by default. You cannot apply top/bottom padding to an inline element
If you want some padding around your  you can do this
a { color: #fff; display: inline-block; text-decoration: none; padding: 0px 0px 26px 0px;}

Fiddle


text:
Q: -Bash command not found appearing every time I start terminal every time I start my terminal, it always says "-bash:  .: command not found" twice.  Does anyone know how I can get rid of that?

A: It sounds like you have an errant command in a file like .bashrc or .profile. Try opening those files and looking for a command that doesn't belong. If something look suspect you might want to copy and paste it into Terminal to see if it runs correctly.
You might also check your prompt if you've customized it to see if you introduced an error there.

A: I would suggest you look into your ~/.bashrc or ~/.bash_profile files with a text editor. You probably mistipped something you have a . or some other character that is being executed at startup.

A: Yes, review the .profile ( /Users/yourusername/.profile ), it sure has something like that .:
Just remove it from there and it will stop showing up.


text:
Q: Obtener datos de diferentes tipos de un archivo csv y pasarlos a un typedef struct c++ Estoy empezando en C++.
Estoy intentando hacer un programa (con funciones propias de C++ y no de C) dónde tengo un typedef struct Persona con datos de diferentes tipos, creo un array de 5 personas de tipo Persona, y luego intento rellenar los datos de esas personas con los datos que hay en un archivo csv.
El csv contiene lineas de datos así:

1001  pepito  PRJ 23550

Dónde: int id, string nombre, char [] iniciales, int puntos.
No sé cómo hacerlo, mi intento es creando un ostringstream al que le doy una secuencia de entrada de datos que coincide con como le va a entrar una linea de datos con getline.
No sé como substraer cada uno de los datos recogidos para asignarlos a persona[i].id_persona etc.
Esto es lo que tengo:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

#include <string>
using std::string;

#include <fstream>
using std::ifstream;
using std::ios;

#include <sstream>
using std::ostringstream;

typedef struct{

    int id_persona;
    string nombre;
    char iniciales[3];
    int puntos;

}Persona;

Persona personas[5];

int main(){

    int id_persona_aux;
    string nombre_aux;
    char iniciales_aux[3];
    int puntos_aux;

    string linea;

    ostringstream registro;

    registro << id_persona_aux << nombre_aux << iniciales_aux << puntos_aux;

    ifstream datos("csvprueba.csv", ios::in);

    while(getline(datos, linea)){

        registro << linea;

    }

    return 0;

}

Muchas gracias, estoy empezando, puede que codee o diga tonterías, pero espero que sirva para aportar a la comunidad.

A: Se me ocurre que todas estas variables que terminan en _aux podrían ser std::string, y hacer algo como esto:
while (getline(datos, id_persona_aux, ' '))
{
    getline(datos, nombre_aux, ' ');
    getline(datos, iniciales_aux, ' ');
    getline(datos, puntos_aux);
}

El tercer argumento para getline es el separador. Yo puse un espacio pero puede ser lo que sea.
Así cuando hayas leído las cuatro partes de cada registro, ya las puedes convertir tú al tipo correcto para meterlas al struct.
Y por cierto, si quieres definir Persona como C++ más moderno, podrías hacer esto:
using Persona = struct {
   int id_persona;
   string nombre;
   char iniciales[3];
   int puntos;
};

Ahora así se hacen los typedefs.


text:
Q: Analyzing grades across classes whose distributions differ Let's say I have grade data for 5 classes of students. I also know some information about each student in each of those classes from a survey (gender, age, grade level, etc.). I want to know if a given characteristic (e.g., gender) is correlated with the grade the student gets, on average. So far so good--this suggests a regression of some kind.
However, the classes are not all equally easy/hard, so the means/medians of the grade distributions in each class are different. A score of 82 might be above average in one class and well below average in another. This indicates that these data cannot all be treated as the same across courses in their raw forms.
I see multiple ways of approaching this question from here.

*

*Standardize all the values within classes, either by subtracting the
mean score and dividing by the standard deviation or by subtracting
the median and dividing by the interquartile range. Then, do the
regression on these standardized values, with the regression telling
me how much a factor influences grade score relative to the average/median
grade in a course.

*Make the regression a mixed model and add class in as a grouping/random variable that adjusts the intercept, essentially letting every class "start" in a different place but otherwise assume the relationships between each factor and grade occur the same way irrespective of that starting point.

*Do a quantile regression of some kind? I think here a standardization within class would still be necessary...

Which of these approaches would be the most straight-forward and defensible? What factors beyond those I have already laid out should I be considering?
I should mention my motivation for asking this question: Our proposed approach to analyzing these data was to turn the outcome into a binary variable for every student--Grade above the median course grade vs. grade below the median course grade. Then, we would analyze the data using a logistic regression. However, this feels like a wasteful approach to me and it seems like one or more of the above directions might be superior.


text:
Q: I can't redirect /domain.com/.html to index.php Search Console Error is showing me this URL:
/domain.com/.html as an error.
If I put that url in my browser I get:
Forbidden
You don't have permission to access /.html on this server.
this situation is because Apache is searching a file named .html how can I add a rule for htaccess file to fix this situation? if the URL is /.html redirect to index /

A: Good Morning,
why exactly do you want /.html to be a valid call? Shouldn't it be /specificName.html like /stack.html?
Anyway, try something like this:
RewriteRule /(specificName)\.html$ / [R=permanent,L]

If you really meant /.html just leave the bracket out.
Hope it helps :)


text:
Q: Swift: Creating the segue between two controllers does not accept my second view controller I am trying to segue between two uiviewcontrollers but Swift will not compile my code. Here is my code:
prepareForSegue(segue: UIStoryboardSegue(identifier: "containerSegue", source: self, destination: EventColumnViewController.self), sender: nil)

Where EventColumnViewController is my custom ViewController class, and here is the error I get:
Cannot find an initializer for type 'UIStoryboardSegue' that accepts an argument list of type '(identifier: String, source: ViewController, destination: EventColumnViewController.Type)'

Why is this happening? How can I fix this?
Here is my class declaration: class EventColumnViewController: UIViewController, UIViewControllerTransitioningDelegate

A: You don't want to specify a specific segue in the function signature for prepareForSegue.  Instead the function receives whichever segue is triggered and you can perform specific code for a certain segue using if blocks.
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "containerSegue") {
        // perform specific code here.
    }
}

If you actually want to perform the specific segue named "containerSegue" programatically, you would want to use a different function:
performSegueWithIdentifier("containerSegue", sender: self)

Notice the difference:

*

*prepareForSegue is used to do setup (such as passing data to the next controller) after a segue has been triggered

*performSegueWithIdentifier actually triggers the segue


text:
Q: Python: for key in gasCount: NameError: name 'gasCount' is not defined import string

def getFile():
    filename = input('Filename: ') #the file name should be .csv
    file = open(filename, 'r')
    firstline = True

    Line = file.readline()
    if Line == None or Line == '':
        return None

    if firstline: # I do not want to read the field names
        Line = file.readline() # there is more to read
        firstline = False # so I skip them. the code assuems

    return file

#Count the number of (T's) in the field [correct]
def calcT(correct):
    global tCount
    found = False
    for ch in correct:#look at each character in turn
        if ch in 'tT':
            found = True

    if found:
        tCount +=1

#How many times does the least common string appear in the field [gas]

def gas_Count(gas):
    global gasCount
    if gas in gasCount:
        gasCount[gas] += 1
    else:
        gasCount[gas] = 1

smallest = 100000
for key in gasCount:
    if gasCount[key] < smallest:
        smallest = gasCount[key]

answers = []
for key in gasCount:
    if gasCount[key] == smallest:
        answers.append(key)

#Find the sum of the values in the field [quant] less than (408)
def sum_quant(quant):
    global qsum
    if quant < 408:
        qsum += quant
code="0"
#How many values in the 'code' field do not match the format 9999(x9+)9?
def checkString(astring):
    if len(code)  != 10:
        return False
    if not astring[0] in string.digits:
        return False
    if not astring[1] in string.digits:
        return False
    if not astring[2] in string.digits:
        return False
    if not astring[3] in string.digits:
        return False
    if not astring[4]=='(':
        return False
    if not astring[5] in string.ascii_lowercase:
        return False
    if not astring[6] in string.digits:
        return False
    if not astring[7]=='+':
        return False
    if not astring[8]==')':
        return False
    if not astring[9] in string.digits:
        return False
    return True

if checkString(code):
    global cCount
    cCount += 1

#What is the average value of the numbers in the field [age] in the range (30) and (107) inclusive
def average_age(age):
    global tAge
    global ageCount
    if age >= 30 and age <=107:
        tAge += age
    ageCount += 1

#Find the sum of the numbers in field [length] between (2.482) and (6.428) inclusive
def sum_Length(leng):
    global lensum
    if leng >= 2.482 and leng <= 6.428:
        lensum += leng

#count the lines where gas's have the value (Nitrogen) *or* quant is less than 318
def calcGas(gas, quant):
    global clines
    if gas == 'Nitrogen' or quant < 318:
        clines += 1

def processLine(Line):
    Line = Line.strip()
    fields = Line.split(',')

    correct = fields[0]
    gas = fields[1]
    quant = int(fields[2])
    code = fields[3]
    age = int(fields[4])
    leng = float(fields[5])
    calcT(correct)
    sum_Length(leng)
    calcGas(gas, quant)
    average_age(age)
    sum_quant(quant)
    gas_Count(gas)
    checkString(astring)

def processFile(data):

    for line in data:
        processLine(line)

    data.close()

def displayResults():
    #Count the number of (T's) in the field [correct]
    print('The number of (T) in the field [correct]: %d'%(tCount))
    print('-' *10)
    print(gasCount)
    print('-' *10)
    print(cCount)
    #Find the sum of the values in the field [quant] less than (408)
    print('The sum of the values in the field [quant] less than (408): %d'%(qsum))
    print('-' *10)
    #How many values in the 'code' field do not match the format 9999(x9+)9?
    #print('The values in the code field do not match the format 9999(x9+)9: %d'%()
    print('-' *10)
    #What is the average value of the numbers in the field [age] in the range (30) and (107) inclusive
    print((tAge/ageCount))
    print('-' *10)
    #Find the sum of the numbers in field [length] between (2.482) and (6.428) inclusive
    print('The sum of the numbers in field [length] between (2.482) and (6.428): %6.3f'%(lensum))
    print('-' *10)
    #count the lines where gas's have the value (Nitrogen) *or* quant is less than 318
    print('The lines where gas have the value (Nitrogen) *or* quant is less than 318: %d' %(clines))

tCount = 0
gasCount = {}
qsum = 0
cCount = 0
ageCount = 0
tAge = 0
lensum = 0
clines = 0
myfile = getFile()
processFile(myfile)
displayResults()

getting error:
Traceback (most recent call last):
  File "C:\Users\Ultra\Downloads\3215402\3215402\3215402 Stage 1 Function.py", line 63, in <module>

editing to this for tobias_k:
def gas_Count(gas):
    global gasCount
    if gas in gasCount:
        gasCount[gas] += 1
    else:
        gasCount[gas] = 1
    smallest = 100000
for key in gasCount:
    if gasCount[key] < smallest:
         smallest = gasCount[key]
answers = []
for key in gasCount:
    if gasCount[key] == smallest:
            answers.append(key)

gives this error
Traceback (most recent call last):
  File "C:\Users\Ultra\Downloads\3215402\3215402\3215402 Stage 1 Function.py", line 57, in <module>
    for key in gasCount:
NameError: name 'gasCount' is not defined


text:
Q: JS create new element then edit the html in that new element I am basically trying to go through an array of arrays and create a new div element for each array item on the array and then add some code to the new div element created. I get Cannot set properties of null (setting 'innerHTML') error message which I understand to mean the JS does not recognise the div element when it is run but surely if I just created it in the line before it should exist by the time that line is executed. Sample code below:

for (var elem in ArrayOfArray){
            document.createElement('div').setAttribute('id', elem[1]);
            document.getElementById(elem[1]).innerHTML = "hello (or some other code)";
        }

Does anyone know why this doesn't work? TIA

A: document.getElementById searches the document for an element with a given ID.
You've created an element, set an attribute on it, and then discarded it. You haven't kept any references to it and you haven't added it to the document.
It isn't in the document for getElementById to find.

const element = document.createElement('div');
element.setAttribute('id', elem[1]);
document.body.appendChild(element);
document.getElementById(elem[1]).innerHTML = "hello (or some other code)";

But since you need to keep a reference to the element in order to do that, you can skip dealing with IDs entirely.
const element = document.createElement('div');
document.body.appendChild(element);
element.innerHTML = "hello (or some other code)";


text:
Q: How to generate and plot all spanning trees? I have a toy graph g, then I have found the number of spanning trees by cofactor of the Laplacian. The number is 11.
library(igraph)
set.seed(2)
n <- 5   #  n=5
m <- 6   #  m=6
g <- erdos.renyi.game(n, p.or.m=m, type="gnm" , directed=FALSE, loops=FALSE)

lap_mat <- laplacian_matrix(g)
print(paste("number of spanning trees by cofactor = ", det(lap_mat[-1,-1])))
# 11

I have n=5 verteces, and I plot the original graph:
par(mfrow=c(2, 3))
layout <- layout.fruchterman.reingold(g)
plot(g, main="Original graph", vertex.size = 40, layout = layout)

then 5 spanning trees were created with the graph.bfs() function:
for (i in 1:n) {
  r <- graph.bfs(g, root=i, order=TRUE, father=TRUE)
  h <- graph(rbind(r$order, r$father[r$order, na_ok = TRUE])[, -1], directed=FALSE)
  plot(h, main=paste("Spanning tree for root=", i), vertex.size = 40, layout = layout)
}

I need to plot all spanning trees. For example, the next tree with root = 5 is not created:

Question. What is a possible way to generate all trees for small random graph?

A: First of all, I would say, my solution below is a brute-force method, thus only working well for graphs of small size, i.e., not many vertices or arcs.
If you have large networks, you should refer to some more advanced algorithms, e.g., https://link.springer.com/article/10.1007/s40747-018-0079-7

Since you have 6 arcs and 5 vertices, you only need to remove 2 arcs out of 6 to find the spanning tree. There would be combn(6,2) options, and you can delete those edge combinations one by one to check if a spanning tree remains
Filter(
  function(x) length(decompose(x)) == 1,
  combn(
    ecount(g),
    ecount(g) - vcount(g) + 1,
    FUN = function(x) delete.edges(g, E(g)[x]),
    simplify = FALSE
  )
)

which gives all 11 spanning trees
[[1]]
IGRAPH 9692f3d U--- 5 4 -- Erdos renyi (gnm) graph
+ attr: name (g/c), type (g/c), loops (g/l), m (g/n)
+ edges from 9692f3d:
[1] 2--4 3--4 1--5 2--5

[[2]]
IGRAPH 969368e U--- 5 4 -- Erdos renyi (gnm) graph
+ attr: name (g/c), type (g/c), loops (g/l), m (g/n)
+ edges from 969368e:
[1] 1--3 3--4 1--5 2--5

[[3]]
IGRAPH 969368e U--- 5 4 -- Erdos renyi (gnm) graph
+ attr: name (g/c), type (g/c), loops (g/l), m (g/n)
+ edges from 969368e:
[1] 1--3 2--4 1--5 2--5

[[4]]
IGRAPH 96938fa U--- 5 4 -- Erdos renyi (gnm) graph
+ attr: name (g/c), type (g/c), loops (g/l), m (g/n)
+ edges from 96938fa:
[1] 1--3 2--4 3--4 2--5

[[5]]
IGRAPH 96938fa U--- 5 4 -- Erdos renyi (gnm) graph
+ attr: name (g/c), type (g/c), loops (g/l), m (g/n)
+ edges from 96938fa:
[1] 1--3 2--4 3--4 1--5

[[6]]
IGRAPH 9693ded U--- 5 4 -- Erdos renyi (gnm) graph
+ attr: name (g/c), type (g/c), loops (g/l), m (g/n)
+ edges from 9693ded:
[1] 1--2 2--4 3--4 2--5

[[7]]
IGRAPH 969404b U--- 5 4 -- Erdos renyi (gnm) graph
+ attr: name (g/c), type (g/c), loops (g/l), m (g/n)
+ edges from 969404b:
[1] 1--2 2--4 3--4 1--5

[[8]]
IGRAPH 96942b7 U--- 5 4 -- Erdos renyi (gnm) graph
+ attr: name (g/c), type (g/c), loops (g/l), m (g/n)
+ edges from 96942b7:
[1] 1--2 1--3 3--4 2--5

[[9]]
IGRAPH 9694527 U--- 5 4 -- Erdos renyi (gnm) graph
+ attr: name (g/c), type (g/c), loops (g/l), m (g/n)
+ edges from 9694527:
[1] 1--2 1--3 3--4 1--5

[[10]]
IGRAPH 9694527 U--- 5 4 -- Erdos renyi (gnm) graph
+ attr: name (g/c), type (g/c), loops (g/l), m (g/n)
+ edges from 9694527:
[1] 1--2 1--3 2--4 2--5

[[11]]
IGRAPH 9694797 U--- 5 4 -- Erdos renyi (gnm) graph
+ attr: name (g/c), type (g/c), loops (g/l), m (g/n)
+ edges from 9694797:
[1] 1--2 1--3 2--4 1--5

A: First let's notice the following:

*

*For the original graph G, we have |V(G)| = 5, |E(G)| = 6

*A spanning tree T of graph G will have exactly V(G)-1=4 vertices.

*But that does not mean that we can arbitrarily select and delete any 2 edges from G to obtain a spanning tree T. For example, if we choose to remove the edges (1,5) and (2,5), we shall obtain the following disconnected graph, which is not a tree:

*Let's find the cycles in the graph starting from vertex 1. Note that since there is an edge from vertex 1 to 2, finding all possible paths (of length >1) starting from 1 and ending on vertex 2. Now, if we extend each of the paths by adding the edge (2,1) in the end, we shall find all possible cycles in the simple graph G, starting/ending on vertex 1, as it's done in the next code block:
cycle_edges <- c()
C <- list() # all possible cycles staring / ending on vertex 1
for (path in all_simple_paths(g, 1, 2, mode="out")) {
   pn <- length(path)
   if (pn > 2) { # not a single edge
      cycle <- c(as.vector(path), 1)
      name <- paste(cycle, collapse='')
      C[[name]] <- c()
      for (i in 1:pn) {
         C[[name]] <- c(C[[name]], paste(cycle[i], cycle[i+1], sep='|'))
      }
   }
}

Two of the cycles found in the graph are shown below:
C
# $`13421`
# [1] "1|3" "3|4" "4|2" "2|1"
# $`1521`
# [1] "1|5" "5|2" "2|1"

*Now select one edge from each cycle to delete and generate a unique spanning tree:
par(mfrow=c(4,3))
count <- 1
for (e1 in C[[1]]) {
   for (e2 in C[[2]]) {
      if (e1 != e2) { # make sure not to remove same edge twice
         g1 <- g %>% delete_edges(c(e1, e2))
         plot(g1, main=paste("spanning tree", count), layout = layout)
         count <- count + 1
       }
    }
 }


text:
Q: Django - Variable is not getting send with POST request Hey im using for my django project typescript to get a specific section from a text to my view but it somehow doesnt work and I dont really know why.
Here is my template in which I want the "currentgap" sent to my view after clicking on the submit button. The getSelectionText() method just sets the id 'gap' to a specific string:
<form action="editorgapcreate" id=create method="POST">

    This is a test section.

  {% csrf_token %}

  Your current selected gap:

  <input type="hidden" name="gap" id="currentgap">

  <button type="submit" name="create_gap">Create gap</button>

</form>

and here is my view in which I tried calling it:
def editorstart(request):
  if request.method == 'POST':
    gap = request.POST['gap']
    print(gap)
    return render(request, 'editor_start.html')
  else:
    return render(request, 'editor_start.html')

The first time using currentgap in my template it displays it correctly but trying to send it to my view with a POST request doesnt work and the print is empty and I dont really know why.
EDIT:
My textselector.js:
function getSelectionText() {
  var text = "";
  if (window.getSelection) {
      text = window.getSelection().toString();
  }
  else if (document.selection && document.selection.type != "Control") {
      text = document.selection.createRange().text;
  }
document.getElementById('currentgap').innerHTML = text;
return text;
}


text:
Q: MVC 4 ajax Json passing model .I am trying to post my view model through ajax as below:
var val = Json.Encode(Model);
var check = @Html.Raw(val);

$("#stats").click(function (e) {
    e.preventDefault();
    console.debug(JSON.stringify(check));
    $.ajax({
    url: '/ReportingWall/analyseStats/',
    type: 'POST',
    data: JSON.stringify(check),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (data) {
    alert("Sucess");
    }
});
});

My Controller Action is
public ContentResult AnalyseStats(ResponsiveReportViewModel model)
        {
            //JavaScriptSerializer js = new JavaScriptSerializer();

            //ResponsiveReportViewModel model = (ResponsiveReportViewModel)js.Deserialize(jsonPost, typeof(ResponsiveReportViewModel));

            if (model != null)
            {
                var sources = model.Sources.Where(x => x.Checked).Select(x => x.Id);
                var terms = model.Terms.Where(x => x.Checked).Select(x => x.Id.ToString());
                if (terms.Count() > 0)
                {
                    var graph = _reportingWallQueries.SetGraphData(terms, model.FromDate, model.ToDate);
                    if (graph != null)
                    {
                        string json;
                        var s = new JavaScriptSerializer();
                        var sw = new StringBuilder();
                        s.Serialize(graph, sw);
                        json = sw.ToString();
                        return new ContentResult { Content = json, ContentType = "application/json" };
                    }
                }
            }
            return null;
        }

Just to let you know its a complex model but ajax is passing model correctly, apart from date.
Date value DateTime.MinValue (which is incorrect). When I look at the date in client side it is there in Json Format.
I think some how it cannot able to Deserialize just date. All the other objects are fine.
Any help will be appreciated.
Edit
Object {Id: null, DetectedDevice: "", Search: null, RequestUrl: ""}
DataModel: Object
DateTimePeriodDescription: null
DetectedDevice: ""
FromDate: "/Date(1405707399000)/"
Id: null
PageSize: 49
ReportType: null
RequestUrl: ""
Search: null
Sources: Array[5]
Terms: Array[82]
ToDate: "/Date(1406312199000)/"
isResultsExits: true
__proto__: Object

A: @using (Ajax.BeginForm("", "", null, new AjaxOptions() { HttpMethod = "POST" }, new { id = "frm" }))
    {
        <div id="hiddenFields">
            <input type="hidden" name="PageIndex" id="PageIndex" value="1" />
        </div>

    }

    var dataPost = $("#frm").serialize();

    $.post("/controller/testmethod", dataPost, function (data) {

    }

    publick void (Mydata data){

    }

    public class Mydata {

    public PageIndex {get;set}

    }


text:
Q: PreparedStatements or callableStatements I tried to understand the difference between PreparedStatements & CallableStatements and I couldn't get it. so please can anyone convert following sql Query to CallableStatement. I know how to convert Statement into a PreparedStatement but having problems with CallableStatements.
as a java.sql.Statement
SELECT * FROM Customer WHERE customerId = 'C001'

as a java.sql.PreparedStatement
SELECT * FROM Customer WHERE customerId = ? //set customerId using preparedStatement.setString(1,"C001")

How to write this same query in CallableStatements
Thanks in advance!

A: As stated in the CallableStatement API:

The interface used to execute SQL stored procedures.

And as such, it can not be used to execute queries.

A: Callable Statements are used for accessing stored procedures.
You have to write stored procedure in database
for
SELECT * FROM Customer WHERE customerId = 'C001'

And
please look into the following links to have help on callable statements -
1 > http://www.mkyong.com/jdbc/jdbc-callablestatement-stored-procedure-out-parameter-example/
2> http://www.tutorialspoint.com/jdbc/callablestatement-object-example.htm
Thanks

A: check this
DIfference Between Stored Procedures and Prepared Statements..?
CallableStatement used for mainly StoredProcedure


text:
Q: How do I open a Windows Form returning only data from specific id I have a C# windows application which does the following:
1) the main form is called EmployeeForm.cs which holds 1 employee record from a sql database. I have used linq to sql to display the records.
2) There is a button on the EmployeeForm when clicked opens another form called Orders.cs which displays a datagrid of orders pertaining to the Employee ID. I am using linq to sql again to display this data.
3) I have got everything working except being able to filter the datagrid by the specific Employee ID. I assume I need some sort of where clause in the orders linq statement??
I know how to achieve this a few different ways for the web but cannot work this out for my windows app. I have included what I have so far:
public partial class EmployeeForm : Form
{
    private NorthWindDataContext db;
    public EmployeeForm()
    {
        InitializeComponent();
        db = new NorthWindDataContext();
        var employeeQuery = from employee in db.Employees
                            orderby employee.FirstName
                            select employee;
        employeeBindingSource.DataSource = employeeQuery;
    }

    private void Orders_Click(object sender, EventArgs e)
    {
        OpenOrdersForm();
    }

    private void OpenOrdersForm()
    {
        OrderForm orderFormInstance = new OrderForm();
        orderFormInstance.ShowDialog();
    }
}

and
 public partial class OrderForm : Form

 {private NorthWindDataContext db;

    public OrderForm()
    {
        InitializeComponent();
    }

    private void OrderForm_Load(object sender, EventArgs e)
    {
        db = new NorthWindDataContext();
        var ordersQuery = from orders in db.Orders
                          orderby orders.OrderID
                          select orders;
        orderBindingSource.DataSource = ordersQuery;
    }

}

A: What have you tried so far?
Is this what you are looking for?
from orders in db.Orders
  where orders.employeeID == 42 // supposing orders has an employeeID field
  orderby orders.OrderID
  select orders;

Have a look at this MSDN page, under "filtering": Basic LINQ Query Operations (C#)


text:
Q: Change Popup background Image with JS and PHP I have a JS Function:
function zoom(now) {
document.getElementById("popup").style.display = "block";
document.getElementById("photos").style.backgroundImage = "url('" +    now + "')";
}

And I have echoed  in php, which has onclick function
echo
"	";

So it says
Uncaught SyntaxError: Unexpected token ILLEGAL.

When I put just 1.jpg in php instead of imagelink it works. but not with $row['imagelink']. I absolutely need to change background image, so please if anyone can help or give me a different option in JS, PHP, HTML only. Thank you

A: You are missing quotes in the php, so it generates invalid HTML
echo '	';

A: I assume the $row['imagelink'] variable contains a filename string, eg 'file.jpeg'.
When echoed in PHP, the HTML onclick attribute would be

The quotes around file.jpeg are missing, so the PHP should be:
"	";


text:
Q: I want to make a program that recognize a button that is in the League of Legends client I want to make a program that recognize a button that is in the League of Legends client, and when the queue's button shows up the mouse instantly click on it.
Its a sort of a AutoAccept Client...
There is already a program that someone did, but it has so many unnecessary things and it does not work very well....
How do I do to recognize a element inside a program to make my mouse move there when it shows up?
I can try to code this in any language, just gimme a tip pls

A: You can create a program that takes a screenshot every 100ms, use a recognition algorithm of your choice and then (optionally) performs a mouse click. There are enough libraries that can screenshot for you, you should be able to recognise the button by colour and location and every language should have some method of controlling the mouse.

A: Sikulix (can be paired with python) is a perfect tool to use for this. It scans over your screen constantly, and if the image in question pops up (the accept button) you can click on it.
You will have to take a screenshot and likely store it as .png so the program knows what it is looking for.
Google Sikulix.


text:
Q: Can't Configure Sublime Text for Python 3 on Mac I wanted to configure sublime text for python 3 on my Mac but it did not work even after I followed every instructions on my tutorial.
I first found out the full path to my Python interpreter by enteringtype -a python3in the terminal, and the terminal returned this:
python3 is /usr/local/bin/python3

Then I created a new build system in Sublime Text and created a new build named "Python3.sublime-build ", the codes are as followed:
{
"cmd": ["/usr/local/bin/python3", "-u", "$file"],
}

It is the path that the terminal returned to me but when I tried to run a program, the console returned error to me:
/usr/local/opt/python3/bin/python3.5: can't find '__main__' module in ''
[Finished in 0.0s with exit code 1]
[cmd: ['/usr/local/bin/python3', '-u', '']]
[dir: /Applications/Sublime Text.app/Contents/MacOS]
[path: /usr/bin:/bin:/usr/sbin:/sbin]

I don't know if this is because I reinstalled python3 earlier on and did not delete all the previous symbolic files/frameworks. Any tips or suggestions would be appreciated!


text:
Q: Can't load third party library using Cocoa Pods I've loaded many pods without issue, but this one is causing an issue.
Here is my Podfile:

And the install appears to go well:

Yet I'm getting an error when I go to import in my View Controller:

A: As it turns out, the issue was I named my XCode Project the same name as the library I was trying to import.  This created confusion for the compiler.  You can see this in the third image I attached.


text:
Q: Duplicate original elements without deleting using Jquery drag and drop I have a widget in which I can drop items into a container. I want to be able to leave the original element outside of the droppable container, so that the user can drag and drop the same element into the container (so the container can have multiple of the same element). I am using the clone helper, but can't figure out how to not delete the original element. Any help is appreciated. Thanks! Below is my code:
$(function() {
var $gallery = $( "#gallery" ),
    $trash = $( "#trash" );

$( "li", $gallery ).draggable({
    cancel: "a.ui-icon",
    revert: "invalid",
    containment: $( "#demo-frame" ).length ? "#demo-frame" : "document", // stick to demo-frame if present
    helper: "clone",
    cursor: "move"
});

$trash.droppable({
    accept: "#gallery > li",
    activeClass: "ui-state-highlight",
    drop: function( event, ui ) {
        deleteImage( ui.draggable );
    }
});

$gallery.droppable({
    accept: "#trash li",
    activeClass: "custom-state-active",
    drop: function( event, ui ) {
        recycleImage( ui.draggable );
    }
});

HTML:

Red

Orange

        <h5 class="fpheader"Yellow

Green

Blue

Purple

White

A: The clone helper clones the element you're dragging for the purpose of display while dragging. Otherwise it does not clone the element on drop. What you need to do inside your drop handler is to clone the element yourself (you can use ui.draggable) and attach it to your droppable container.
Here's an example:
$trash.droppable({
    accept: "#gallery > li",
    activeClass: "ui-state-highlight",
    drop: function( event, ui ) {
        var element = ui.draggable.clone().appendTo($(this));
        element.draggable({
            cancel: "a.ui-icon",
            revert: "invalid",
            containment: $( "#demo-frame" ).length ? "#demo-frame" : "document", // stick to demo-frame if present
            helper: "clone",
            cursor: "move"
        });
    }
});


text:
Q: Genus of intersection of two surfaces in $\mathbb{P}^3$ Let $F_1$ and $F_2$ be two (smooth) surfaces in $\mathbb{P}^3$, of degrees $d_1$ and $d_2$ respectively. Let $C$ denote curve given as their intersection. How one can compute arithmetical genus of the curve $C$?
Perhaps I need to add some assumptions on $F$ and $G$ to exclude degenerate cases.

A: The cohomology of the intersection of two surfaces can also be computed by writing resolutions. First of all, we have the ideal sheaf sequence $$ 0 \to \mathcal I \to \mathcal O_\mathbb P \to \mathcal O_C \to 0.$$
We also have the exact sequence
$$
0 \to \mathcal O(-d-e) \to \mathcal O(-d) \oplus \mathcal O(-e) \to \mathcal O \to \mathcal I \to 0.
$$
Then you can use arguments with long exact sequences to compute the cohomology of $C$. First of all, the cohomology of the ideal sheaf is completely determined by the second exact sequence together with results on the cohomology of projective space. Then combine this with the first sequence to determine the  cohomology of $\mathcal O_C$.
(this is more bothersome than Asal Beag Dubh's method however...)

A: You can get the answer by using the adjunction formula.
First assume that $C$ is smooth. Then its normal bundle $N_C$ is the restriction of $\mathscr O (d_1) \oplus \mathscr O(d_2)$ to $C$. Then the adjunction formula (Hartshorne II.8.20) says that the canonical bundle of $C$ is
$$K_C = (K_{\mathbf P^3})_{|C} \otimes \bigwedge^2 N_C = (\mathscr O(-4) \otimes \mathscr O(d_1+d_2))_{|C}.$$
Since $C$ is a curve of degree $d_1d_2$, that means $K_C$ is a line bundle of degree $d_1d_2(d_1+d_2-4)$.
On the other hand, the genus of $C$ is related to this number by
$$2g-2= \operatorname{deg} K_C = d_1d_2(d_1+d_2-4)$$
so one gets $g= \frac12 (d_1d_2(d_1+d_2-4)+2)$.
As a sanity check, if say $d_1=1$, then $C$ is actually a plane curve of degree $d_2$, and the formula above gives its genus as $\frac12(d_2(d_2-3)+2)=\frac12(d_2-1)(d_2-2)$ as expected.
Now,  what if $C$ is not smooth? I claim it doesn't matter, as long as $C$ is viewed the scheme-theoretic intersection of the surfaces and we calculate arithmetic genus accordingly.  By deforming the coefficients of the defining equations of $F_1$ and $F_2$ we get a flat family of curves in $\mathbf P^3$ which has $C$ as one member and whose general member is a smooth intersection of surfaces of degrees $d_1$ and $d_2$. Hartshorn III.9.10 shows that arithmetic genus is constant in such a family.

Edit: The OP asked me to justify the claim that $N_C$ is $\mathscr O (d_1) \oplus \mathscr O(d_2)$ restricted to $C$, so let's do that.
Here $\mathscr O(d_1)_{|F_i}$ is the normal bundle to $F_i$ for each $i$.
(From now on, I won't write the restriction everywhere. It should be clear from context where the bundles in question live.)
Now $N_C = T_X/T_C$ and $N_{|F_i} = T_X/T_{F_i}$  so there is a canonical quotient map $$N_C \rightarrow N_{F_i}$$ for each $i$. This gives a map $$\varphi: N_C \rightarrow N_{F_1} \oplus N_{F_2}$$ which I claim is an isomorphism. To see this, observe that both bundles have the same rank at each point, so it is enough to prove it is injective. And now the key point is that since $C$ is smooth, the two surfaces intersect transversely at each point of $C$: that is
$$ T_{F_1} \cap T_{F_2} = T_C $$
at each point of $C$. Therefore the map $\varphi$ above has trivial kernel.


text:
Q: Why Cassndra is called unstructured database Why Cassandra is called unstructured even though table/column family  has to be defined with columns and their data type.
For the defined table with some fixed columns we can choose to fill some columns in one particular row and choose not to fill in other row. But same thing can be done in RDBMS where we can leave some columns in the insert statement and the columns left out should allow null?
As mongo store the data in json documents where we can store different (keys) data every time insert new document. we don't need to define anything . But for cassandra we need to reconfigure our table to accommodate new columns getting added.
Even though some articles are present but still its not clear to me. Can someone pin point the reason.

A: Basically is not about "how it works", is how the files are stored,  this is why cassandra have not structure for the files, you can have a same récords in diferents folders.


text:
Q: How do I preserve html as is when using Javascript's innerHTML everything is working fine, decodeURIComponent(xmlhttp.responseText) comes back as html from parsing script as checked with alert, no errors in the console, but replacing the html to the editor with
retHTML.innerHTML =decodeURIComponent(xmlhttp.responseText);

seems to have a "feature" of translating my html to encoded html(& to &) etc..
I'm not sure why a command that says it is the inner html would prevent you from actually using html? innerText simply amplifies this rather then returning the html free text as implied. How do I get the returned html back to the div as the html I am requesting?
function setHTML(retHTML)
{
retHTML.innerText =retHTML.innerHTML; }

function setTEXT(retHTML)
{
var tmpTXT =encodeURIComponent(retHTML.innerText);
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{ retHTML.innerHTML =decodeURIComponent(xmlhttp.responseText);  }
xmlhttp.open("POST","path.php",true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send('send=' + tmpTXT); }

test markup as follows
<object width="853" height="510">
<param name="movie" value="http://www.youtube.com/v/iaysTVcounI?version=3&hl=en_US&rel=0">
<param name="allowFullScreen" value="true">
<param name="allowscriptaccess" value="always">
<embed src="http://www.youtube.com/v/iaysTVcounI?version=3&hl=en_US&rel=0&autoplay=1" type="application/x-shockwave-flash" width="853" height="510" allowscriptaccess="always" allowfullscreen="true">
</object>

should be
<object width="853" height="510">
<param name="movie" value="http://www.youtube.com/v/iaysTVcounI?version=3&hl=en_US&rel=0">
<param name="allowFullScreen" value="true">
<param name="allowscriptaccess" value="always">
<embed src="http://www.youtube.com/v/iaysTVcounI?version=3&hl=en_US&rel=0&autoplay=1" type="application/x-shockwave-flash" width="853" height="510" allowscriptaccess="always" allowfullscreen="true">
</object>

A: innerHTML is a parser when you write to it and a serialiser when you read, not a simple property that stores text.
When you write to innerHTML, it converts the HTML source text into DOM objects like Element, Attr and TextNode. It is these DOM objects that reflect the real live state of the document in the browser window, and not anything that looks like HTML source.
On writing, any information that is not significant to the 'information set' stored in the DOM is lost. This includes things like case (whether your tag was <b> or <B>), order of attributes, whitespace inside tags, entity and character references (ie whether you said café, café or café—it's all the same to an HTML parser), and much more.
Reading back the innerHTML you just wrote will re-serialise the parsed DOM and give you something back that won't necessarily be the same string as what you put in. If you made mistakes in your original HTML, you'll also find that the output has been corrected to reflect what the HTML parser did to be able to read what you put in. So an invalid bare ampersand will necessarily turn into &.
(I'm not sure what kind of 'editor' you're referring to, but if it's a <textarea> then that will additionally fix up < to < in any HTML you write to it, because a textarea can't contain markup. It's also rather odd and unnecessary that you would be passing back URL-encoded data in a responseText; are you sure that's what's happening?)
ETA:

should be value="http://www.youtube.com/v/iaysTVcounI?version=3&hl=en_US&rel=0"

No it shouldn't. That's not valid HTML. Escaping the &s to & is absolutely the correct, required thing to do.

A: I feel this is kinda ghetto but ultimately the following will be my fix. I recomend this as an alternative to innerHTML for literal replacement of the string.
retHTML.innerHTML ='';
retHTML.execCommand('insertHTML',false,xmlhttp.responseText);


text:
Q: Excel sheet is not opening in ASP.NET application after deploying HI,
I have deployed an Asp.Net 2.0 application in IIS.In this, I have folder(uploads) which contains a temp file.In the page, i have once button(Display),when i click on the display button, the excel sheet should be opened.This is happening in local but not after deploying in IIS. It showing the error message like "Microsoft Office Excel cannot open or save any more documents because there is not enough available memory or disk space".
Please help me in resolving this issue.
Thanks
Rupa

A: for that try spread Sheet Gear third party component
http://www.spreadsheetgear.com/
Plus you can check this thread if this is help for you
ASP.NET manuplating Excel sheet